ayar 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
ayar-0.1.0/.gitignore ADDED
@@ -0,0 +1,6 @@
1
+ __pycache__/
2
+ *.egg-info/
3
+ dist/
4
+ build/
5
+ .pytest_cache/
6
+ *.npz
ayar-0.1.0/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
ayar-0.1.0/PKG-INFO ADDED
@@ -0,0 +1,214 @@
1
+ Metadata-Version: 2.5
2
+ Name: ayar
3
+ Version: 0.1.0
4
+ Summary: Assay your spike-sorted finding before you publish: detect sorting artifacts and test whether your result survives them.
5
+ Author-email: Aslan Satary Dizaji <aslansatary@gmail.com>
6
+ License-Expression: Apache-2.0
7
+ License-File: LICENSE
8
+ Keywords: electrophysiology,kilosort,neuropixels,neuroscience,quality control,reproducibility,spike sorting,spikeinterface
9
+ Classifier: Development Status :: 3 - Alpha
10
+ Classifier: Intended Audience :: Science/Research
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Programming Language :: Python :: 3.10
13
+ Classifier: Programming Language :: Python :: 3.11
14
+ Classifier: Programming Language :: Python :: 3.12
15
+ Classifier: Programming Language :: Python :: 3.13
16
+ Classifier: Topic :: Scientific/Engineering :: Bio-Informatics
17
+ Classifier: Topic :: Scientific/Engineering :: Medical Science Apps.
18
+ Requires-Python: >=3.10
19
+ Requires-Dist: numpy>=1.23
20
+ Requires-Dist: scipy>=1.9
21
+ Provides-Extra: dev
22
+ Requires-Dist: pytest>=7; extra == 'dev'
23
+ Description-Content-Type: text/markdown
24
+
25
+ # ayar
26
+
27
+ **Assay your spike-sorted finding before you publish.**
28
+
29
+ *Ayar* (Persian عیار, Turkish *ayar*, Azerbaijani *əyar*) is the fineness of gold: how much of
30
+ it is the real thing. `ayar` asks the same question of a result built on sorted spikes:
31
+ how much of it is neuroscience, and how much is the spike sorter?
32
+
33
+ Tools such as SpikeInterface quality metrics, Bombcell and UnitRefine judge **units**.
34
+ `ayar` judges the **finding**. It reads the output of any sorter (Kilosort, MountainSort,
35
+ SpyKING CIRCUS, ... via Phy folders or a plain `.npz` bundle), flags sorting artifacts
36
+ that can manufacture or hide an effect, then re-computes *your* analysis without the
37
+ flagged units and tells you whether your numbers survive.
38
+
39
+ `ayar` does not sort spikes and does not prove a finding is right. It tests whether
40
+ specific, known artifacts can explain it.
41
+
42
+ ```
43
+ pip install ayar
44
+ ```
45
+
46
+ Python 3.10+, depends only on numpy and scipy, runs on a CPU.
47
+
48
+ ## Thirty seconds
49
+
50
+ ```bash
51
+ ayar synth demo.npz # a session with planted artifacts
52
+ ayar scan demo.npz --finding ayar.examples:condition_contrast
53
+ ```
54
+
55
+ ```
56
+ ERROR DRIFT_CONFOUND unit 16: rate follows detection loss (r=0.94; up to 50% of spikes
57
+ below threshold in the worst window)
58
+ ERROR DUPLICATE_UNIT 95% of unit 41's spikes have a unit 17 spike within ±0.25 ms (229x
59
+ chance): likely one neuron counted twice
60
+ ERROR OVERLAP_HOLE units 42 and 43 fire within ±0.5 ms 13% as often as expected from
61
+ the 2-10 ms flanks (37 vs 295, p=1.6e-80)
62
+ ...
63
+ finding audit: ayar.examples:condition_contrast
64
+ number remove units flagged by n baseline after change random-drop q95 verdict
65
+ frac_units_suppressed DRIFT_CONFOUND 3 0.06 0 100% 6% SENSITIVE
66
+ mean_contrast_hz DUPLICATE_UNIT 2 2.277 2.05 10% 8% ROBUST
67
+ ...
68
+ frac_units_suppressed: SENSITIVE - depends on the flagged units beyond what random removals explain
69
+ ```
70
+
71
+ In this synthetic block-design session, every "suppressed" unit was a drifting unit losing
72
+ spikes below threshold: there was no suppression at all.
73
+
74
+ On your own data:
75
+
76
+ ```bash
77
+ ayar scan path/to/kilosort_output/ --finding my_analysis.py:main --events events.npz
78
+ ```
79
+
80
+ `ayar scan` exits with status 1 when it finds an error-level artifact or a finding that is
81
+ SENSITIVE or FLIPPED, so it can gate a pipeline or CI job (`--fail-on warning|never`).
82
+
83
+ ## Your finding is a function
84
+
85
+ A finding is any function of a bundle that returns a number or a dict of numbers: the
86
+ numbers you would put in a paper.
87
+
88
+ ```python
89
+ import ayar
90
+
91
+ def main(bundle):
92
+ trains = bundle.trains() # {unit_id: spike times in s}
93
+ ev = bundle.events # ev.times, ev.labels
94
+ ...
95
+ return {"decoding_accuracy": acc, "frac_tuned": frac}
96
+
97
+ report = ayar.scan(ayar.load("kilosort_output/"), finding=main)
98
+ print(report)
99
+ report.finding_verdicts # {'decoding_accuracy': 'robust', 'frac_tuned': 'sensitive'}
100
+ report.to_json()
101
+ ```
102
+
103
+ For each detector that raised flags, `ayar` removes the implicated units (the duplicate
104
+ copy, one unit of each hole pair, the drifting unit), recomputes the finding, and compares
105
+ the change with **random-drop controls**: the same number of *unflagged* units removed at
106
+ random, 20 times. A change counts against the artifact only if it is bigger than what
107
+ dropping arbitrary units does.
108
+
109
+ | verdict | meaning |
110
+ |---|---|
111
+ | `robust` | changes by less than 10 % |
112
+ | `nonspecific` | changes, but no more than random removals (95th percentile) |
113
+ | `shifted` | moves beyond random removals, by 10-25 % |
114
+ | `sensitive` | moves beyond random removals, by 25 % or more |
115
+ | `flipped` | changes sign, which random removals almost never do |
116
+ | `failed` | your function raised an error on the reduced bundle |
117
+
118
+ `ayar.examples` has two finding templates: `condition_contrast` (two-condition rate effect)
119
+ and `zero_lag_synchrony` (synchrony between neighbouring units).
120
+
121
+ ## Detectors
122
+
123
+ | code | needs | what it catches | why it matters |
124
+ |---|---|---|---|
125
+ | `DUPLICATE_UNIT` | spike times | two units sharing most spikes within ±0.25 ms, far above chance | one neuron counted twice: inflated N, double weight in averages and decoders, fake zero-lag correlation |
126
+ | `OVERLAP_HOLE` | spike times (depths restrict to neighbours) | a gap near zero lag in a nearby pair's cross-correlogram, tested against the 2-10 ms flanks (Poisson, Bonferroni) | the sorter dropped overlapping spikes, or one neuron was split in two: synchrony is underestimated |
127
+ | `DRIFT_CONFOUND` | amplitudes or depths | firing rate that tracks spike amplitude, depth, or estimated detection loss (amplitude-cutoff per window) over the session | apparent rate changes are spikes lost below threshold; raised to **error** when conditions are ordered in time, because the loss then looks like a condition effect |
128
+
129
+ Each flag carries a code, a severity, the units, the evidence, why it matters and a fix.
130
+ Every threshold is named and can be overridden (`--set dup_window_ms=0.4`, or
131
+ `ayar.DEFAULTS.override(...)`). When a check cannot run, or runs on only some units,
132
+ `ayar` says so under *not checked* instead of guessing.
133
+
134
+ ## Evidence tiers
135
+
136
+ * **Tier 0: spike times.** Duplicate and overlap detectors run (all pairs, capped at 20,000
137
+ pairs).
138
+ * **Tier 1: plus amplitudes and/or depths.** Pair tests are restricted to neighbouring units
139
+ (100 µm), and the drift detector runs.
140
+ * **Tier 2: plus the raw recording** (hybrid ground truth, re-sorting). Planned.
141
+
142
+ ## Input: the bundle
143
+
144
+ ```python
145
+ b = ayar.from_phy("kilosort4_output/") # spike_times/clusters/amplitudes/positions, labels
146
+ b = ayar.from_arrays(times_s, clusters, amplitudes=amps, spike_depths=depths,
147
+ events=ayar.Events(trial_times, trial_labels))
148
+ b.save("session.npz") # plain npz, readable with numpy alone
149
+ ```
150
+
151
+ `from_phy` keeps units labelled `good` or `mua` (curated labels win over Kilosort's), reads
152
+ depths from `spike_positions.npy` (Kilosort 4) or `cluster_info.tsv` (Phy), and takes the
153
+ sample rate from `params.py`.
154
+
155
+ ## Self-validation
156
+
157
+ `ayar validate` plants artifacts in synthetic sessions, together with **controls** that
158
+ must not be flagged: pairs driven by genuine common input (a real cross-correlogram peak)
159
+ and units whose true rate ramps over the session at constant amplitude. Then it scores
160
+ every detector.
161
+
162
+ ```
163
+ ayar validate --sessions 20 --seed 100
164
+
165
+ detector planted found false ctrl alarms sensitivity precision
166
+ DUPLICATE_UNIT 40 40 0 0 1.00 1.00
167
+ OVERLAP_HOLE 40 40 0 0 1.00 1.00
168
+ DRIFT_CONFOUND 60 55 1 0 0.92 0.98
169
+
170
+ finding audit: in 19 session(s) drift manufactured 'suppressed' units; ayar called that
171
+ number SENSITIVE or FLIPPED in 19
172
+ ```
173
+
174
+ These numbers are measured on ayar's own synthetic data, whose artifacts are cleaner than
175
+ real ones. They show that the detectors do what they claim, not how often they fire on real
176
+ recordings.
177
+
178
+ ## Limitations (v0.1)
179
+
180
+ * Research prototype. Thresholds are calibrated on synthetic sessions, not yet on public
181
+ datasets with ground truth.
182
+ * Drift is detected per unit from rate-amplitude-depth co-variation. Units with few spikes
183
+ (fewer than ~600) get only the weaker amplitude/depth trend test and are reported as
184
+ partly checked.
185
+ * The finding audit removes units; it does not yet repair them (merge duplicates, restrict
186
+ drifting units to their stable epoch).
187
+ * `OVERLAP_HOLE` cannot yet tell missed overlaps from a split unit; both are reported.
188
+ * The audit calls your function about 20 times per detector. Use `--set audit_controls=0`
189
+ to skip controls when the function is slow.
190
+
191
+ ## Roadmap
192
+
193
+ * **v0.2**: SpikeInterface `SortingAnalyzer` and NWB adapters; `SPLIT_UNIT` and
194
+ `CONTAMINATION_TUNING` detectors; curation-threshold multiverse.
195
+ * **v0.3**: multiverse across sorters (Kilosort 4, MountainSort 5, SpyKING CIRCUS 2) with
196
+ unit matching; single-file HTML report; provenance through
197
+ [daftar](https://pypi.org/project/daftar/).
198
+ * **v0.4**: validation on public recordings (IBL, Allen, DANDI).
199
+
200
+ ## Family
201
+
202
+ `ayar` sits with [daftar](https://pypi.org/project/daftar/) (provenance),
203
+ [raftaar](https://pypi.org/project/raftaar/), [tarjuman](https://pypi.org/project/tarjuman/)
204
+ (NeuroML to Jaxley), [miras](https://pypi.org/project/miras/) (study-design
205
+ identifiability), [baghban](https://pypi.org/project/baghban/) (Bonsai workflow checks) and
206
+ [ayna](https://pypi.org/project/ayna/) (are your inferred dynamics real?).
207
+
208
+ ## Author
209
+
210
+ Aslan Satary Dizaji
211
+
212
+ ## License
213
+
214
+ Apache 2.0
ayar-0.1.0/README.md ADDED
@@ -0,0 +1,190 @@
1
+ # ayar
2
+
3
+ **Assay your spike-sorted finding before you publish.**
4
+
5
+ *Ayar* (Persian عیار, Turkish *ayar*, Azerbaijani *əyar*) is the fineness of gold: how much of
6
+ it is the real thing. `ayar` asks the same question of a result built on sorted spikes:
7
+ how much of it is neuroscience, and how much is the spike sorter?
8
+
9
+ Tools such as SpikeInterface quality metrics, Bombcell and UnitRefine judge **units**.
10
+ `ayar` judges the **finding**. It reads the output of any sorter (Kilosort, MountainSort,
11
+ SpyKING CIRCUS, ... via Phy folders or a plain `.npz` bundle), flags sorting artifacts
12
+ that can manufacture or hide an effect, then re-computes *your* analysis without the
13
+ flagged units and tells you whether your numbers survive.
14
+
15
+ `ayar` does not sort spikes and does not prove a finding is right. It tests whether
16
+ specific, known artifacts can explain it.
17
+
18
+ ```
19
+ pip install ayar
20
+ ```
21
+
22
+ Python 3.10+, depends only on numpy and scipy, runs on a CPU.
23
+
24
+ ## Thirty seconds
25
+
26
+ ```bash
27
+ ayar synth demo.npz # a session with planted artifacts
28
+ ayar scan demo.npz --finding ayar.examples:condition_contrast
29
+ ```
30
+
31
+ ```
32
+ ERROR DRIFT_CONFOUND unit 16: rate follows detection loss (r=0.94; up to 50% of spikes
33
+ below threshold in the worst window)
34
+ ERROR DUPLICATE_UNIT 95% of unit 41's spikes have a unit 17 spike within ±0.25 ms (229x
35
+ chance): likely one neuron counted twice
36
+ ERROR OVERLAP_HOLE units 42 and 43 fire within ±0.5 ms 13% as often as expected from
37
+ the 2-10 ms flanks (37 vs 295, p=1.6e-80)
38
+ ...
39
+ finding audit: ayar.examples:condition_contrast
40
+ number remove units flagged by n baseline after change random-drop q95 verdict
41
+ frac_units_suppressed DRIFT_CONFOUND 3 0.06 0 100% 6% SENSITIVE
42
+ mean_contrast_hz DUPLICATE_UNIT 2 2.277 2.05 10% 8% ROBUST
43
+ ...
44
+ frac_units_suppressed: SENSITIVE - depends on the flagged units beyond what random removals explain
45
+ ```
46
+
47
+ In this synthetic block-design session, every "suppressed" unit was a drifting unit losing
48
+ spikes below threshold: there was no suppression at all.
49
+
50
+ On your own data:
51
+
52
+ ```bash
53
+ ayar scan path/to/kilosort_output/ --finding my_analysis.py:main --events events.npz
54
+ ```
55
+
56
+ `ayar scan` exits with status 1 when it finds an error-level artifact or a finding that is
57
+ SENSITIVE or FLIPPED, so it can gate a pipeline or CI job (`--fail-on warning|never`).
58
+
59
+ ## Your finding is a function
60
+
61
+ A finding is any function of a bundle that returns a number or a dict of numbers: the
62
+ numbers you would put in a paper.
63
+
64
+ ```python
65
+ import ayar
66
+
67
+ def main(bundle):
68
+ trains = bundle.trains() # {unit_id: spike times in s}
69
+ ev = bundle.events # ev.times, ev.labels
70
+ ...
71
+ return {"decoding_accuracy": acc, "frac_tuned": frac}
72
+
73
+ report = ayar.scan(ayar.load("kilosort_output/"), finding=main)
74
+ print(report)
75
+ report.finding_verdicts # {'decoding_accuracy': 'robust', 'frac_tuned': 'sensitive'}
76
+ report.to_json()
77
+ ```
78
+
79
+ For each detector that raised flags, `ayar` removes the implicated units (the duplicate
80
+ copy, one unit of each hole pair, the drifting unit), recomputes the finding, and compares
81
+ the change with **random-drop controls**: the same number of *unflagged* units removed at
82
+ random, 20 times. A change counts against the artifact only if it is bigger than what
83
+ dropping arbitrary units does.
84
+
85
+ | verdict | meaning |
86
+ |---|---|
87
+ | `robust` | changes by less than 10 % |
88
+ | `nonspecific` | changes, but no more than random removals (95th percentile) |
89
+ | `shifted` | moves beyond random removals, by 10-25 % |
90
+ | `sensitive` | moves beyond random removals, by 25 % or more |
91
+ | `flipped` | changes sign, which random removals almost never do |
92
+ | `failed` | your function raised an error on the reduced bundle |
93
+
94
+ `ayar.examples` has two finding templates: `condition_contrast` (two-condition rate effect)
95
+ and `zero_lag_synchrony` (synchrony between neighbouring units).
96
+
97
+ ## Detectors
98
+
99
+ | code | needs | what it catches | why it matters |
100
+ |---|---|---|---|
101
+ | `DUPLICATE_UNIT` | spike times | two units sharing most spikes within ±0.25 ms, far above chance | one neuron counted twice: inflated N, double weight in averages and decoders, fake zero-lag correlation |
102
+ | `OVERLAP_HOLE` | spike times (depths restrict to neighbours) | a gap near zero lag in a nearby pair's cross-correlogram, tested against the 2-10 ms flanks (Poisson, Bonferroni) | the sorter dropped overlapping spikes, or one neuron was split in two: synchrony is underestimated |
103
+ | `DRIFT_CONFOUND` | amplitudes or depths | firing rate that tracks spike amplitude, depth, or estimated detection loss (amplitude-cutoff per window) over the session | apparent rate changes are spikes lost below threshold; raised to **error** when conditions are ordered in time, because the loss then looks like a condition effect |
104
+
105
+ Each flag carries a code, a severity, the units, the evidence, why it matters and a fix.
106
+ Every threshold is named and can be overridden (`--set dup_window_ms=0.4`, or
107
+ `ayar.DEFAULTS.override(...)`). When a check cannot run, or runs on only some units,
108
+ `ayar` says so under *not checked* instead of guessing.
109
+
110
+ ## Evidence tiers
111
+
112
+ * **Tier 0: spike times.** Duplicate and overlap detectors run (all pairs, capped at 20,000
113
+ pairs).
114
+ * **Tier 1: plus amplitudes and/or depths.** Pair tests are restricted to neighbouring units
115
+ (100 µm), and the drift detector runs.
116
+ * **Tier 2: plus the raw recording** (hybrid ground truth, re-sorting). Planned.
117
+
118
+ ## Input: the bundle
119
+
120
+ ```python
121
+ b = ayar.from_phy("kilosort4_output/") # spike_times/clusters/amplitudes/positions, labels
122
+ b = ayar.from_arrays(times_s, clusters, amplitudes=amps, spike_depths=depths,
123
+ events=ayar.Events(trial_times, trial_labels))
124
+ b.save("session.npz") # plain npz, readable with numpy alone
125
+ ```
126
+
127
+ `from_phy` keeps units labelled `good` or `mua` (curated labels win over Kilosort's), reads
128
+ depths from `spike_positions.npy` (Kilosort 4) or `cluster_info.tsv` (Phy), and takes the
129
+ sample rate from `params.py`.
130
+
131
+ ## Self-validation
132
+
133
+ `ayar validate` plants artifacts in synthetic sessions, together with **controls** that
134
+ must not be flagged: pairs driven by genuine common input (a real cross-correlogram peak)
135
+ and units whose true rate ramps over the session at constant amplitude. Then it scores
136
+ every detector.
137
+
138
+ ```
139
+ ayar validate --sessions 20 --seed 100
140
+
141
+ detector planted found false ctrl alarms sensitivity precision
142
+ DUPLICATE_UNIT 40 40 0 0 1.00 1.00
143
+ OVERLAP_HOLE 40 40 0 0 1.00 1.00
144
+ DRIFT_CONFOUND 60 55 1 0 0.92 0.98
145
+
146
+ finding audit: in 19 session(s) drift manufactured 'suppressed' units; ayar called that
147
+ number SENSITIVE or FLIPPED in 19
148
+ ```
149
+
150
+ These numbers are measured on ayar's own synthetic data, whose artifacts are cleaner than
151
+ real ones. They show that the detectors do what they claim, not how often they fire on real
152
+ recordings.
153
+
154
+ ## Limitations (v0.1)
155
+
156
+ * Research prototype. Thresholds are calibrated on synthetic sessions, not yet on public
157
+ datasets with ground truth.
158
+ * Drift is detected per unit from rate-amplitude-depth co-variation. Units with few spikes
159
+ (fewer than ~600) get only the weaker amplitude/depth trend test and are reported as
160
+ partly checked.
161
+ * The finding audit removes units; it does not yet repair them (merge duplicates, restrict
162
+ drifting units to their stable epoch).
163
+ * `OVERLAP_HOLE` cannot yet tell missed overlaps from a split unit; both are reported.
164
+ * The audit calls your function about 20 times per detector. Use `--set audit_controls=0`
165
+ to skip controls when the function is slow.
166
+
167
+ ## Roadmap
168
+
169
+ * **v0.2**: SpikeInterface `SortingAnalyzer` and NWB adapters; `SPLIT_UNIT` and
170
+ `CONTAMINATION_TUNING` detectors; curation-threshold multiverse.
171
+ * **v0.3**: multiverse across sorters (Kilosort 4, MountainSort 5, SpyKING CIRCUS 2) with
172
+ unit matching; single-file HTML report; provenance through
173
+ [daftar](https://pypi.org/project/daftar/).
174
+ * **v0.4**: validation on public recordings (IBL, Allen, DANDI).
175
+
176
+ ## Family
177
+
178
+ `ayar` sits with [daftar](https://pypi.org/project/daftar/) (provenance),
179
+ [raftaar](https://pypi.org/project/raftaar/), [tarjuman](https://pypi.org/project/tarjuman/)
180
+ (NeuroML to Jaxley), [miras](https://pypi.org/project/miras/) (study-design
181
+ identifiability), [baghban](https://pypi.org/project/baghban/) (Bonsai workflow checks) and
182
+ [ayna](https://pypi.org/project/ayna/) (are your inferred dynamics real?).
183
+
184
+ ## Author
185
+
186
+ Aslan Satary Dizaji
187
+
188
+ ## License
189
+
190
+ Apache 2.0
@@ -0,0 +1,40 @@
1
+ [build-system]
2
+ requires = ["hatchling>=1.18"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "ayar"
7
+ version = "0.1.0"
8
+ description = "Assay your spike-sorted finding before you publish: detect sorting artifacts and test whether your result survives them."
9
+ readme = "README.md"
10
+ license = "Apache-2.0"
11
+ requires-python = ">=3.10"
12
+ authors = [{ name = "Aslan Satary Dizaji", email = "aslansatary@gmail.com" }]
13
+ keywords = [
14
+ "neuroscience", "electrophysiology", "spike sorting", "neuropixels",
15
+ "kilosort", "spikeinterface", "quality control", "reproducibility",
16
+ ]
17
+ classifiers = [
18
+ "Development Status :: 3 - Alpha",
19
+ "Intended Audience :: Science/Research",
20
+ "Programming Language :: Python :: 3",
21
+ "Programming Language :: Python :: 3.10",
22
+ "Programming Language :: Python :: 3.11",
23
+ "Programming Language :: Python :: 3.12",
24
+ "Programming Language :: Python :: 3.13",
25
+ "Topic :: Scientific/Engineering :: Bio-Informatics",
26
+ "Topic :: Scientific/Engineering :: Medical Science Apps.",
27
+ ]
28
+ dependencies = ["numpy>=1.23", "scipy>=1.9"]
29
+
30
+ [project.optional-dependencies]
31
+ dev = ["pytest>=7"]
32
+
33
+ [project.scripts]
34
+ ayar = "ayar.cli:main"
35
+
36
+ [tool.hatch.build.targets.wheel]
37
+ packages = ["src/ayar"]
38
+
39
+ [tool.pytest.ini_options]
40
+ testpaths = ["tests"]