grintools 0.1.1__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.
- grintools-0.1.1/LICENSE +21 -0
- grintools-0.1.1/MANIFEST.in +5 -0
- grintools-0.1.1/PKG-INFO +284 -0
- grintools-0.1.1/README.md +248 -0
- grintools-0.1.1/grintools/__init__.py +58 -0
- grintools-0.1.1/grintools/cli.py +74 -0
- grintools-0.1.1/grintools/criterion.py +149 -0
- grintools-0.1.1/grintools/data/example_cm.csv +4 -0
- grintools-0.1.1/grintools/io.py +428 -0
- grintools-0.1.1/grintools/models/model_provenance.json +10 -0
- grintools-0.1.1/grintools/models/npe_model.onnx +0 -0
- grintools-0.1.1/grintools/models/recalibration.json +103 -0
- grintools-0.1.1/grintools/onnx.py +186 -0
- grintools-0.1.1/grintools/plot.py +690 -0
- grintools-0.1.1/grintools/py.typed +0 -0
- grintools-0.1.1/grintools.egg-info/PKG-INFO +284 -0
- grintools-0.1.1/grintools.egg-info/SOURCES.txt +23 -0
- grintools-0.1.1/grintools.egg-info/dependency_links.txt +1 -0
- grintools-0.1.1/grintools.egg-info/entry_points.txt +2 -0
- grintools-0.1.1/grintools.egg-info/requires.txt +10 -0
- grintools-0.1.1/grintools.egg-info/top_level.txt +1 -0
- grintools-0.1.1/pyproject.toml +59 -0
- grintools-0.1.1/setup.cfg +4 -0
- grintools-0.1.1/tests/test_packaged.py +91 -0
- grintools-0.1.1/tests/test_plot.py +257 -0
grintools-0.1.1/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Murray S. Bennett
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
grintools-0.1.1/PKG-INFO
ADDED
|
@@ -0,0 +1,284 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: grintools
|
|
3
|
+
Version: 0.1.1
|
|
4
|
+
Summary: Amortised, uncertainty-calibrated inference for General Recognition Theory (GRT) from a 2x2 identification confusion matrix -- milliseconds instead of maximum-likelihood fitting, via a neural network trained once on simulated data and shipped as an ONNX graph.
|
|
5
|
+
Author: Peter D. Kvam, Joseph W. Houpt
|
|
6
|
+
Author-email: "Murray S. Bennett" <murray.bennett92@gmail.com>
|
|
7
|
+
License-Expression: MIT
|
|
8
|
+
Project-URL: Homepage, https://grin.murraysbennett.com
|
|
9
|
+
Project-URL: Source, https://github.com/MurraySBennett/grin
|
|
10
|
+
Project-URL: Documentation, https://github.com/MurraySBennett/grin/tree/main/packages/grintools#readme
|
|
11
|
+
Project-URL: Changelog, https://github.com/MurraySBennett/grin/blob/main/packages/grintools/CHANGELOG.md
|
|
12
|
+
Project-URL: Issues, https://github.com/MurraySBennett/grin/issues
|
|
13
|
+
Keywords: general recognition theory,GRT,simulation-based inference,amortised inference,psychophysics,perceptual independence
|
|
14
|
+
Classifier: Development Status :: 4 - Beta
|
|
15
|
+
Classifier: Intended Audience :: Science/Research
|
|
16
|
+
Classifier: Programming Language :: Python :: 3
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
21
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
22
|
+
Classifier: Operating System :: OS Independent
|
|
23
|
+
Classifier: Topic :: Scientific/Engineering
|
|
24
|
+
Requires-Python: >=3.9
|
|
25
|
+
Description-Content-Type: text/markdown
|
|
26
|
+
License-File: LICENSE
|
|
27
|
+
Requires-Dist: numpy>=1.22
|
|
28
|
+
Requires-Dist: onnxruntime>=1.17
|
|
29
|
+
Provides-Extra: train
|
|
30
|
+
Requires-Dist: torch>=2.1; extra == "train"
|
|
31
|
+
Provides-Extra: plot
|
|
32
|
+
Requires-Dist: matplotlib>=3.5; extra == "plot"
|
|
33
|
+
Requires-Dist: pandas>=1.4; extra == "plot"
|
|
34
|
+
Requires-Dist: scipy>=1.8; extra == "plot"
|
|
35
|
+
Dynamic: license-file
|
|
36
|
+
|
|
37
|
+
# grintools
|
|
38
|
+
|
|
39
|
+
Amortised Bayesian inference for General Recognition Theory (GRT) from 2x2
|
|
40
|
+
identification confusion matrices. Feed a confusion matrix, get a calibrated
|
|
41
|
+
approximate posterior over the 12 GRT parameters plus construct probabilities
|
|
42
|
+
(perceptual independence, separability), and an optional stopping decision for
|
|
43
|
+
adaptive designs. "Calibrated" means checked against simulated ground truth
|
|
44
|
+
over the trained model's prior envelope (trial counts, parameter ranges) --
|
|
45
|
+
see the validation studies in the accompanying paper for what that covers and
|
|
46
|
+
does not.
|
|
47
|
+
|
|
48
|
+
Run time is torch-free: the trained network ships as an ONNX graph and runs under
|
|
49
|
+
`onnxruntime`. Retraining the pipeline re-exports the `.onnx`; this package is
|
|
50
|
+
otherwise unchanged.
|
|
51
|
+
|
|
52
|
+
## Install
|
|
53
|
+
|
|
54
|
+
```
|
|
55
|
+
pip install grintools
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
Needs Python 3.9 or newer. Dependencies are numpy and onnxruntime only — there is
|
|
59
|
+
no PyTorch dependency at run time, so the install is small and fast. Extras:
|
|
60
|
+
`pip install grintools[plot]` adds matplotlib/pandas/scipy for the reporting
|
|
61
|
+
figures, and `pip install grintools[train]` adds torch, needed only to re-export
|
|
62
|
+
the ONNX graph, never to use it.
|
|
63
|
+
|
|
64
|
+
To install the unreleased development version instead:
|
|
65
|
+
|
|
66
|
+
```
|
|
67
|
+
pip install "grintools @ git+https://github.com/MurraySBennett/grin.git#subdirectory=packages/grintools"
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
Check it worked:
|
|
71
|
+
|
|
72
|
+
```
|
|
73
|
+
python -c "import grintools as gt; print(gt.infer([[83,112,47,11],[38,154,28,33],[15,27,117,94],[6,36,75,136]])[1]['p_PI'])"
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
That prints `0.000710745...`, the probability of perceptual independence for the
|
|
77
|
+
worked example in the paper. A number means you are done.
|
|
78
|
+
|
|
79
|
+
## Use
|
|
80
|
+
|
|
81
|
+
```python
|
|
82
|
+
import grintools as gt
|
|
83
|
+
|
|
84
|
+
M = [[71, 17, 9, 5],
|
|
85
|
+
[20, 67, 5, 9],
|
|
86
|
+
[13, 6, 63, 20],
|
|
87
|
+
[5, 10, 15, 71]] # rows = stimuli, cols = responses
|
|
88
|
+
|
|
89
|
+
result, constructs = gt.infer(M) # trials default to row sums
|
|
90
|
+
print(result.summary())
|
|
91
|
+
print(constructs["p_PI"], constructs["p_sep_A"], constructs["p_sep_B"])
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
Or from the shell:
|
|
95
|
+
|
|
96
|
+
```
|
|
97
|
+
grin-fit --csv mydata.csv --construct PS_A --at-least 0.9 --sd 0.15 --combine any
|
|
98
|
+
```
|
|
99
|
+
|
|
100
|
+
## The ordering contract
|
|
101
|
+
|
|
102
|
+
`gt.infer()` needs to know which row/column of your matrix is which
|
|
103
|
+
stimulus/response. **Canonical order** means: number the four stimuli 1-4 by
|
|
104
|
+
crossing dimension A's two levels with dimension B's two levels, A changing
|
|
105
|
+
slower than B:
|
|
106
|
+
|
|
107
|
+
| position | A level | B level | canonical label |
|
|
108
|
+
|:--:|:--:|:--:|:--:|
|
|
109
|
+
| 1 | 1 | 1 | `A1B1` |
|
|
110
|
+
| 2 | 1 | 2 | `A1B2` |
|
|
111
|
+
| 3 | 2 | 1 | `A2B1` |
|
|
112
|
+
| 4 | 2 | 2 | `A2B2` |
|
|
113
|
+
|
|
114
|
+
Row *i* and column *i* of your matrix must be stimulus/response *i* in this
|
|
115
|
+
table. A bare matrix in unknown order is refused rather than guessed, because a
|
|
116
|
+
silent row/column swap returns a confident wrong posterior. Resolve it
|
|
117
|
+
explicitly:
|
|
118
|
+
|
|
119
|
+
```python
|
|
120
|
+
gt.to_confusion(M, order="canonical") # you assert it is already canonical
|
|
121
|
+
|
|
122
|
+
# or let it permute a different order for you -- e.g. dimension A = Age (Old/Young),
|
|
123
|
+
# dimension B = Emotion (Neg/Pos): position 1 = Old+Neg, ..., position 4 = Young+Pos
|
|
124
|
+
gt.to_confusion(M, stim_labels=["Old/Neg", "Old/Pos", "Young/Neg", "Young/Pos"],
|
|
125
|
+
resp_labels=["Old/Neg", "Old/Pos", "Young/Neg", "Young/Pos"],
|
|
126
|
+
factor_a=("Old", "Young"), factor_b=("Neg", "Pos"))
|
|
127
|
+
|
|
128
|
+
gt.describe(M, order="canonical") # print exactly what the model will see
|
|
129
|
+
```
|
|
130
|
+
|
|
131
|
+
Proportions (rows summing to 1) are refused unless you also pass `trials=[...]`,
|
|
132
|
+
because the model reads per-stimulus trial totals as a second input and proportions
|
|
133
|
+
would destroy the posterior's uncertainty.
|
|
134
|
+
|
|
135
|
+
`gt.to_confusion()` also accepts trial-level ("long format") data directly —
|
|
136
|
+
one row per trial with `stimulus`/`response` columns, no manual tallying — which
|
|
137
|
+
is the shape a PsychoPy or jsPsych/Pavlovia/Gorilla export already comes in:
|
|
138
|
+
|
|
139
|
+
```python
|
|
140
|
+
gt.to_confusion(trial_log, factor_a=("Old", "Young"), factor_b=("Neg", "Pos"), long=True)
|
|
141
|
+
```
|
|
142
|
+
|
|
143
|
+
See [`docs/data_collection.md`](https://github.com/MurraySBennett/grin/blob/main/docs/data_collection.md) for the full
|
|
144
|
+
walkthrough by platform (including running `grintools` live inside a PsychoPy
|
|
145
|
+
trial loop), and a note on where `grin` (R) fits in against this package for
|
|
146
|
+
post-hoc analysis.
|
|
147
|
+
|
|
148
|
+
## Scope: native 2×2 designs only
|
|
149
|
+
|
|
150
|
+
`grintools` is built for a design that actually crosses two binary
|
|
151
|
+
dimensions -- four stimuli, four responses. If your experiment has a third
|
|
152
|
+
dimension (a 2×2×2 or larger identification design) and you're tempted to
|
|
153
|
+
hand `grintools` a pairwise margin -- summing over the third dimension to get
|
|
154
|
+
a 2×2 table for each pair -- know that this is **not** equivalent to fitting
|
|
155
|
+
the full higher-dimensional GRT model. Marginalising over a dimension the
|
|
156
|
+
observer was actually attending to folds a mixture into what `grintools`
|
|
157
|
+
will read as a single bivariate-normal representation, and the
|
|
158
|
+
perceptual-independence and separability conclusions it reports are about
|
|
159
|
+
that pairwise projection, not about the design as a whole. Treat a pairwise
|
|
160
|
+
margin as a descriptive summary if you use one at all, not as a native
|
|
161
|
+
`grintools` analysis of a 2×2×2 experiment.
|
|
162
|
+
|
|
163
|
+
## Response bias
|
|
164
|
+
|
|
165
|
+
Separate from separability/independence, and GRT (as a multidimensional
|
|
166
|
+
extension of signal detection theory) gives two ways to ask about it.
|
|
167
|
+
`gt.empirical_bias()` reads the raw tendency to favour one response over
|
|
168
|
+
another straight off the matrix, no model fit required:
|
|
169
|
+
|
|
170
|
+
```python
|
|
171
|
+
gt.empirical_bias(M) # {'x_bias': ..., 'y_bias': ...} in [-0.5, 0.5]; 0 = unbiased
|
|
172
|
+
```
|
|
173
|
+
|
|
174
|
+
`gt.response_bias()` is the SDT-native version: the decision bound sits at 0
|
|
175
|
+
by convention, so an unbiased observer's two levels on a dimension are
|
|
176
|
+
mirror images about it and their identified z-scores average to zero -- a
|
|
177
|
+
nonzero average is a shifted decision criterion, read directly off a fit you
|
|
178
|
+
already have, uncertainty included:
|
|
179
|
+
|
|
180
|
+
```python
|
|
181
|
+
result, constructs = gt.infer(M)
|
|
182
|
+
gt.response_bias(result) # {'x_bias', 'y_bias', 'x_bias_se', 'y_bias_se'}
|
|
183
|
+
```
|
|
184
|
+
|
|
185
|
+
## Stopping rules for adaptive designs
|
|
186
|
+
|
|
187
|
+
The rule is the experimenter's, declared as a `Criterion` of `Target`s:
|
|
188
|
+
|
|
189
|
+
```python
|
|
190
|
+
crit = gt.Criterion([
|
|
191
|
+
gt.Target.precision(params=["zx", "zy"], sd_max=0.10), # want the space measured
|
|
192
|
+
gt.Target.probability("PS_A", at_least=0.90), # want the verdict
|
|
193
|
+
], combine="any")
|
|
194
|
+
decision = crit.evaluate(result, constructs)
|
|
195
|
+
if decision.stop:
|
|
196
|
+
...
|
|
197
|
+
```
|
|
198
|
+
|
|
199
|
+
`Target.precision` stops when the parameter posterior is tight enough;
|
|
200
|
+
`Target.probability` stops when a construct probability (`PI`, `PS_A`, `PS_B`, or a
|
|
201
|
+
`_violated` complement) crosses a threshold; `combine` is `"all"` or `"any"`.
|
|
202
|
+
|
|
203
|
+
Perceptual-independence questions are information-limited from a single confusion
|
|
204
|
+
matrix. Construct targets carry the model's evidence flags, so a threshold on a
|
|
205
|
+
construct the data cannot decide is reported in `decision.blocked_by` and does not
|
|
206
|
+
stop the loop. The limit is in the data, not the tool.
|
|
207
|
+
|
|
208
|
+
## Plotting and reporting
|
|
209
|
+
|
|
210
|
+
See [`docs/quickstart.md`](https://github.com/MurraySBennett/grin/blob/main/packages/grintools/docs/quickstart.md) for a full walkthrough (one
|
|
211
|
+
participant through a small sample) with rendered figures. Summary of the
|
|
212
|
+
API: needs the `[plot]` extra (`pip install grintools[plot]`, adds
|
|
213
|
+
matplotlib/pandas/scipy -- the core package stays torch-free and
|
|
214
|
+
dependency-light without it):
|
|
215
|
+
|
|
216
|
+
```python
|
|
217
|
+
import grintools.plot as gtplot
|
|
218
|
+
|
|
219
|
+
gtplot.plot_space(result) # perceptual space: means, correlation ellipses, error bars
|
|
220
|
+
gtplot.plot_params(result) # all 12 estimates, dot-and-whisker with 90% CIs
|
|
221
|
+
gtplot.plot_constructs(result, constructs) # P(PI)/P(RHO1)/P(free), P(separable A/B)
|
|
222
|
+
gtplot.plot_bias(result) # decision-criterion response bias per dimension
|
|
223
|
+
gtplot.plot_diagnostics(result, M) # predicted-vs-observed + marginal distributions
|
|
224
|
+
```
|
|
225
|
+
|
|
226
|
+
`plot_space()` also takes `title`, `xlabel`/`ylabel`, `stim_labels`,
|
|
227
|
+
`show_labels`, `show_uncertainty`, `show_marginals`, and `base_size`; see its
|
|
228
|
+
docstring for the full set. `plot_diagnostics()` needs the original matrix
|
|
229
|
+
alongside the fitted result, since `gt.infer()`'s return value doesn't carry
|
|
230
|
+
the input back out. `gtplot.plot_empirical_bias()` is the matrix-only,
|
|
231
|
+
no-fit-required counterpart to `plot_bias()` (see "Response bias" above).
|
|
232
|
+
|
|
233
|
+
Group level (many participants — collect `gt.infer()` results into a list;
|
|
234
|
+
`gtplot.tidy()` is the shared foundation if you want the raw DataFrame instead
|
|
235
|
+
of a plot):
|
|
236
|
+
|
|
237
|
+
```python
|
|
238
|
+
sample = [gt.infer(M1), gt.infer(M2), gt.infer(M3)]
|
|
239
|
+
|
|
240
|
+
gtplot.tidy(sample) # one row per participant: estimates, SDs, constructs
|
|
241
|
+
gtplot.plot_space_group(sample) # one panel per participant -- the individual-level analysis GRT licenses
|
|
242
|
+
gtplot.plot_params_group(sample) # per-parameter distribution across the sample
|
|
243
|
+
gtplot.plot_model_classes(sample) # componentwise modal structures across participants
|
|
244
|
+
gtplot.plot_precision_group(sample) # posterior SD distribution -- data quality across the sample
|
|
245
|
+
gtplot.plot_bias_group(sample) # response bias distribution across the sample
|
|
246
|
+
```
|
|
247
|
+
|
|
248
|
+
`gtplot.plot_space_group(sample, facet=False)` overlays all participants with
|
|
249
|
+
a single across-participant mean ellipse instead of one panel each.
|
|
250
|
+
**This is an exploratory inspection view only, not a reporting figure**: GRT's
|
|
251
|
+
perceptual space is defined per observer, and a "grand mean" ellipse over
|
|
252
|
+
several independently-fitted spaces is not itself a fitted GRT model. Use it
|
|
253
|
+
to eyeball whether a sample looks homogeneous, not to report it; a warning is
|
|
254
|
+
raised every time this mode runs.
|
|
255
|
+
|
|
256
|
+
Same visual identity as `grin` (the R package) -- a figure made with either
|
|
257
|
+
package reads as the same family. Bars/labels for a construct the data can't
|
|
258
|
+
decide (`evidence_* == False`) are visually flagged rather than plotted as if
|
|
259
|
+
informative, same principle as the stopping-rule API's `blocked_by`.
|
|
260
|
+
|
|
261
|
+
**Style**: black-on-white by default (publication- and greyscale-safe). Pass
|
|
262
|
+
`palette="<name>"` to any plot function for one of a few built-in colour sets
|
|
263
|
+
(`gtplot.palette_names()` lists them, including `"contrast"`, the
|
|
264
|
+
colour-vision-deficiency-safe categorical palette of Okabe & Ito, 2008), your
|
|
265
|
+
own list of hex colours, or set `gtplot.DEFAULT_PALETTE = "<name>"` once for
|
|
266
|
+
the session. Either way, `plot_space()` never splits one participant's four
|
|
267
|
+
stimuli into separate colours -- stimuli are told apart by a label instead.
|
|
268
|
+
|
|
269
|
+
**Editing a figure further**: every plot function returns a plain matplotlib
|
|
270
|
+
`Axes` (or `Figure`, for the multi-panel ones), so ordinary matplotlib calls
|
|
271
|
+
apply directly rather than needing a package argument for every possible
|
|
272
|
+
customisation:
|
|
273
|
+
|
|
274
|
+
```python
|
|
275
|
+
ax = gtplot.plot_space(result)
|
|
276
|
+
ax.set_title("Participant 7, session 2") # replaces the whole default title, subtitle included
|
|
277
|
+
ax.annotate("post-training session", (0, 2.3), ha="center", color="grey")
|
|
278
|
+
```
|
|
279
|
+
|
|
280
|
+
## Model provenance
|
|
281
|
+
|
|
282
|
+
Each release bundles one specific trained `.onnx`. The package version pins the
|
|
283
|
+
model, so `grintools==X.Y.Z` corresponds to a fixed set of weights with known
|
|
284
|
+
recovery and calibration behaviour (see the project's validation suite).
|
|
@@ -0,0 +1,248 @@
|
|
|
1
|
+
# grintools
|
|
2
|
+
|
|
3
|
+
Amortised Bayesian inference for General Recognition Theory (GRT) from 2x2
|
|
4
|
+
identification confusion matrices. Feed a confusion matrix, get a calibrated
|
|
5
|
+
approximate posterior over the 12 GRT parameters plus construct probabilities
|
|
6
|
+
(perceptual independence, separability), and an optional stopping decision for
|
|
7
|
+
adaptive designs. "Calibrated" means checked against simulated ground truth
|
|
8
|
+
over the trained model's prior envelope (trial counts, parameter ranges) --
|
|
9
|
+
see the validation studies in the accompanying paper for what that covers and
|
|
10
|
+
does not.
|
|
11
|
+
|
|
12
|
+
Run time is torch-free: the trained network ships as an ONNX graph and runs under
|
|
13
|
+
`onnxruntime`. Retraining the pipeline re-exports the `.onnx`; this package is
|
|
14
|
+
otherwise unchanged.
|
|
15
|
+
|
|
16
|
+
## Install
|
|
17
|
+
|
|
18
|
+
```
|
|
19
|
+
pip install grintools
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
Needs Python 3.9 or newer. Dependencies are numpy and onnxruntime only — there is
|
|
23
|
+
no PyTorch dependency at run time, so the install is small and fast. Extras:
|
|
24
|
+
`pip install grintools[plot]` adds matplotlib/pandas/scipy for the reporting
|
|
25
|
+
figures, and `pip install grintools[train]` adds torch, needed only to re-export
|
|
26
|
+
the ONNX graph, never to use it.
|
|
27
|
+
|
|
28
|
+
To install the unreleased development version instead:
|
|
29
|
+
|
|
30
|
+
```
|
|
31
|
+
pip install "grintools @ git+https://github.com/MurraySBennett/grin.git#subdirectory=packages/grintools"
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
Check it worked:
|
|
35
|
+
|
|
36
|
+
```
|
|
37
|
+
python -c "import grintools as gt; print(gt.infer([[83,112,47,11],[38,154,28,33],[15,27,117,94],[6,36,75,136]])[1]['p_PI'])"
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
That prints `0.000710745...`, the probability of perceptual independence for the
|
|
41
|
+
worked example in the paper. A number means you are done.
|
|
42
|
+
|
|
43
|
+
## Use
|
|
44
|
+
|
|
45
|
+
```python
|
|
46
|
+
import grintools as gt
|
|
47
|
+
|
|
48
|
+
M = [[71, 17, 9, 5],
|
|
49
|
+
[20, 67, 5, 9],
|
|
50
|
+
[13, 6, 63, 20],
|
|
51
|
+
[5, 10, 15, 71]] # rows = stimuli, cols = responses
|
|
52
|
+
|
|
53
|
+
result, constructs = gt.infer(M) # trials default to row sums
|
|
54
|
+
print(result.summary())
|
|
55
|
+
print(constructs["p_PI"], constructs["p_sep_A"], constructs["p_sep_B"])
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
Or from the shell:
|
|
59
|
+
|
|
60
|
+
```
|
|
61
|
+
grin-fit --csv mydata.csv --construct PS_A --at-least 0.9 --sd 0.15 --combine any
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
## The ordering contract
|
|
65
|
+
|
|
66
|
+
`gt.infer()` needs to know which row/column of your matrix is which
|
|
67
|
+
stimulus/response. **Canonical order** means: number the four stimuli 1-4 by
|
|
68
|
+
crossing dimension A's two levels with dimension B's two levels, A changing
|
|
69
|
+
slower than B:
|
|
70
|
+
|
|
71
|
+
| position | A level | B level | canonical label |
|
|
72
|
+
|:--:|:--:|:--:|:--:|
|
|
73
|
+
| 1 | 1 | 1 | `A1B1` |
|
|
74
|
+
| 2 | 1 | 2 | `A1B2` |
|
|
75
|
+
| 3 | 2 | 1 | `A2B1` |
|
|
76
|
+
| 4 | 2 | 2 | `A2B2` |
|
|
77
|
+
|
|
78
|
+
Row *i* and column *i* of your matrix must be stimulus/response *i* in this
|
|
79
|
+
table. A bare matrix in unknown order is refused rather than guessed, because a
|
|
80
|
+
silent row/column swap returns a confident wrong posterior. Resolve it
|
|
81
|
+
explicitly:
|
|
82
|
+
|
|
83
|
+
```python
|
|
84
|
+
gt.to_confusion(M, order="canonical") # you assert it is already canonical
|
|
85
|
+
|
|
86
|
+
# or let it permute a different order for you -- e.g. dimension A = Age (Old/Young),
|
|
87
|
+
# dimension B = Emotion (Neg/Pos): position 1 = Old+Neg, ..., position 4 = Young+Pos
|
|
88
|
+
gt.to_confusion(M, stim_labels=["Old/Neg", "Old/Pos", "Young/Neg", "Young/Pos"],
|
|
89
|
+
resp_labels=["Old/Neg", "Old/Pos", "Young/Neg", "Young/Pos"],
|
|
90
|
+
factor_a=("Old", "Young"), factor_b=("Neg", "Pos"))
|
|
91
|
+
|
|
92
|
+
gt.describe(M, order="canonical") # print exactly what the model will see
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
Proportions (rows summing to 1) are refused unless you also pass `trials=[...]`,
|
|
96
|
+
because the model reads per-stimulus trial totals as a second input and proportions
|
|
97
|
+
would destroy the posterior's uncertainty.
|
|
98
|
+
|
|
99
|
+
`gt.to_confusion()` also accepts trial-level ("long format") data directly —
|
|
100
|
+
one row per trial with `stimulus`/`response` columns, no manual tallying — which
|
|
101
|
+
is the shape a PsychoPy or jsPsych/Pavlovia/Gorilla export already comes in:
|
|
102
|
+
|
|
103
|
+
```python
|
|
104
|
+
gt.to_confusion(trial_log, factor_a=("Old", "Young"), factor_b=("Neg", "Pos"), long=True)
|
|
105
|
+
```
|
|
106
|
+
|
|
107
|
+
See [`docs/data_collection.md`](https://github.com/MurraySBennett/grin/blob/main/docs/data_collection.md) for the full
|
|
108
|
+
walkthrough by platform (including running `grintools` live inside a PsychoPy
|
|
109
|
+
trial loop), and a note on where `grin` (R) fits in against this package for
|
|
110
|
+
post-hoc analysis.
|
|
111
|
+
|
|
112
|
+
## Scope: native 2×2 designs only
|
|
113
|
+
|
|
114
|
+
`grintools` is built for a design that actually crosses two binary
|
|
115
|
+
dimensions -- four stimuli, four responses. If your experiment has a third
|
|
116
|
+
dimension (a 2×2×2 or larger identification design) and you're tempted to
|
|
117
|
+
hand `grintools` a pairwise margin -- summing over the third dimension to get
|
|
118
|
+
a 2×2 table for each pair -- know that this is **not** equivalent to fitting
|
|
119
|
+
the full higher-dimensional GRT model. Marginalising over a dimension the
|
|
120
|
+
observer was actually attending to folds a mixture into what `grintools`
|
|
121
|
+
will read as a single bivariate-normal representation, and the
|
|
122
|
+
perceptual-independence and separability conclusions it reports are about
|
|
123
|
+
that pairwise projection, not about the design as a whole. Treat a pairwise
|
|
124
|
+
margin as a descriptive summary if you use one at all, not as a native
|
|
125
|
+
`grintools` analysis of a 2×2×2 experiment.
|
|
126
|
+
|
|
127
|
+
## Response bias
|
|
128
|
+
|
|
129
|
+
Separate from separability/independence, and GRT (as a multidimensional
|
|
130
|
+
extension of signal detection theory) gives two ways to ask about it.
|
|
131
|
+
`gt.empirical_bias()` reads the raw tendency to favour one response over
|
|
132
|
+
another straight off the matrix, no model fit required:
|
|
133
|
+
|
|
134
|
+
```python
|
|
135
|
+
gt.empirical_bias(M) # {'x_bias': ..., 'y_bias': ...} in [-0.5, 0.5]; 0 = unbiased
|
|
136
|
+
```
|
|
137
|
+
|
|
138
|
+
`gt.response_bias()` is the SDT-native version: the decision bound sits at 0
|
|
139
|
+
by convention, so an unbiased observer's two levels on a dimension are
|
|
140
|
+
mirror images about it and their identified z-scores average to zero -- a
|
|
141
|
+
nonzero average is a shifted decision criterion, read directly off a fit you
|
|
142
|
+
already have, uncertainty included:
|
|
143
|
+
|
|
144
|
+
```python
|
|
145
|
+
result, constructs = gt.infer(M)
|
|
146
|
+
gt.response_bias(result) # {'x_bias', 'y_bias', 'x_bias_se', 'y_bias_se'}
|
|
147
|
+
```
|
|
148
|
+
|
|
149
|
+
## Stopping rules for adaptive designs
|
|
150
|
+
|
|
151
|
+
The rule is the experimenter's, declared as a `Criterion` of `Target`s:
|
|
152
|
+
|
|
153
|
+
```python
|
|
154
|
+
crit = gt.Criterion([
|
|
155
|
+
gt.Target.precision(params=["zx", "zy"], sd_max=0.10), # want the space measured
|
|
156
|
+
gt.Target.probability("PS_A", at_least=0.90), # want the verdict
|
|
157
|
+
], combine="any")
|
|
158
|
+
decision = crit.evaluate(result, constructs)
|
|
159
|
+
if decision.stop:
|
|
160
|
+
...
|
|
161
|
+
```
|
|
162
|
+
|
|
163
|
+
`Target.precision` stops when the parameter posterior is tight enough;
|
|
164
|
+
`Target.probability` stops when a construct probability (`PI`, `PS_A`, `PS_B`, or a
|
|
165
|
+
`_violated` complement) crosses a threshold; `combine` is `"all"` or `"any"`.
|
|
166
|
+
|
|
167
|
+
Perceptual-independence questions are information-limited from a single confusion
|
|
168
|
+
matrix. Construct targets carry the model's evidence flags, so a threshold on a
|
|
169
|
+
construct the data cannot decide is reported in `decision.blocked_by` and does not
|
|
170
|
+
stop the loop. The limit is in the data, not the tool.
|
|
171
|
+
|
|
172
|
+
## Plotting and reporting
|
|
173
|
+
|
|
174
|
+
See [`docs/quickstart.md`](https://github.com/MurraySBennett/grin/blob/main/packages/grintools/docs/quickstart.md) for a full walkthrough (one
|
|
175
|
+
participant through a small sample) with rendered figures. Summary of the
|
|
176
|
+
API: needs the `[plot]` extra (`pip install grintools[plot]`, adds
|
|
177
|
+
matplotlib/pandas/scipy -- the core package stays torch-free and
|
|
178
|
+
dependency-light without it):
|
|
179
|
+
|
|
180
|
+
```python
|
|
181
|
+
import grintools.plot as gtplot
|
|
182
|
+
|
|
183
|
+
gtplot.plot_space(result) # perceptual space: means, correlation ellipses, error bars
|
|
184
|
+
gtplot.plot_params(result) # all 12 estimates, dot-and-whisker with 90% CIs
|
|
185
|
+
gtplot.plot_constructs(result, constructs) # P(PI)/P(RHO1)/P(free), P(separable A/B)
|
|
186
|
+
gtplot.plot_bias(result) # decision-criterion response bias per dimension
|
|
187
|
+
gtplot.plot_diagnostics(result, M) # predicted-vs-observed + marginal distributions
|
|
188
|
+
```
|
|
189
|
+
|
|
190
|
+
`plot_space()` also takes `title`, `xlabel`/`ylabel`, `stim_labels`,
|
|
191
|
+
`show_labels`, `show_uncertainty`, `show_marginals`, and `base_size`; see its
|
|
192
|
+
docstring for the full set. `plot_diagnostics()` needs the original matrix
|
|
193
|
+
alongside the fitted result, since `gt.infer()`'s return value doesn't carry
|
|
194
|
+
the input back out. `gtplot.plot_empirical_bias()` is the matrix-only,
|
|
195
|
+
no-fit-required counterpart to `plot_bias()` (see "Response bias" above).
|
|
196
|
+
|
|
197
|
+
Group level (many participants — collect `gt.infer()` results into a list;
|
|
198
|
+
`gtplot.tidy()` is the shared foundation if you want the raw DataFrame instead
|
|
199
|
+
of a plot):
|
|
200
|
+
|
|
201
|
+
```python
|
|
202
|
+
sample = [gt.infer(M1), gt.infer(M2), gt.infer(M3)]
|
|
203
|
+
|
|
204
|
+
gtplot.tidy(sample) # one row per participant: estimates, SDs, constructs
|
|
205
|
+
gtplot.plot_space_group(sample) # one panel per participant -- the individual-level analysis GRT licenses
|
|
206
|
+
gtplot.plot_params_group(sample) # per-parameter distribution across the sample
|
|
207
|
+
gtplot.plot_model_classes(sample) # componentwise modal structures across participants
|
|
208
|
+
gtplot.plot_precision_group(sample) # posterior SD distribution -- data quality across the sample
|
|
209
|
+
gtplot.plot_bias_group(sample) # response bias distribution across the sample
|
|
210
|
+
```
|
|
211
|
+
|
|
212
|
+
`gtplot.plot_space_group(sample, facet=False)` overlays all participants with
|
|
213
|
+
a single across-participant mean ellipse instead of one panel each.
|
|
214
|
+
**This is an exploratory inspection view only, not a reporting figure**: GRT's
|
|
215
|
+
perceptual space is defined per observer, and a "grand mean" ellipse over
|
|
216
|
+
several independently-fitted spaces is not itself a fitted GRT model. Use it
|
|
217
|
+
to eyeball whether a sample looks homogeneous, not to report it; a warning is
|
|
218
|
+
raised every time this mode runs.
|
|
219
|
+
|
|
220
|
+
Same visual identity as `grin` (the R package) -- a figure made with either
|
|
221
|
+
package reads as the same family. Bars/labels for a construct the data can't
|
|
222
|
+
decide (`evidence_* == False`) are visually flagged rather than plotted as if
|
|
223
|
+
informative, same principle as the stopping-rule API's `blocked_by`.
|
|
224
|
+
|
|
225
|
+
**Style**: black-on-white by default (publication- and greyscale-safe). Pass
|
|
226
|
+
`palette="<name>"` to any plot function for one of a few built-in colour sets
|
|
227
|
+
(`gtplot.palette_names()` lists them, including `"contrast"`, the
|
|
228
|
+
colour-vision-deficiency-safe categorical palette of Okabe & Ito, 2008), your
|
|
229
|
+
own list of hex colours, or set `gtplot.DEFAULT_PALETTE = "<name>"` once for
|
|
230
|
+
the session. Either way, `plot_space()` never splits one participant's four
|
|
231
|
+
stimuli into separate colours -- stimuli are told apart by a label instead.
|
|
232
|
+
|
|
233
|
+
**Editing a figure further**: every plot function returns a plain matplotlib
|
|
234
|
+
`Axes` (or `Figure`, for the multi-panel ones), so ordinary matplotlib calls
|
|
235
|
+
apply directly rather than needing a package argument for every possible
|
|
236
|
+
customisation:
|
|
237
|
+
|
|
238
|
+
```python
|
|
239
|
+
ax = gtplot.plot_space(result)
|
|
240
|
+
ax.set_title("Participant 7, session 2") # replaces the whole default title, subtitle included
|
|
241
|
+
ax.annotate("post-training session", (0, 2.3), ha="center", color="grey")
|
|
242
|
+
```
|
|
243
|
+
|
|
244
|
+
## Model provenance
|
|
245
|
+
|
|
246
|
+
Each release bundles one specific trained `.onnx`. The package version pins the
|
|
247
|
+
model, so `grintools==X.Y.Z` corresponds to a fixed set of weights with known
|
|
248
|
+
recovery and calibration behaviour (see the project's validation suite).
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
"""
|
|
2
|
+
grintools: amortised Bayesian inference for General Recognition Theory (GRT).
|
|
3
|
+
|
|
4
|
+
Feed a 2x2 identification confusion matrix, get a calibrated posterior over the 12
|
|
5
|
+
GRT parameters plus construct probabilities (perceptual independence, separability),
|
|
6
|
+
and an optional stopping decision for adaptive designs. Torch-free at run time: the
|
|
7
|
+
trained network ships as an ONNX graph and runs under onnxruntime.
|
|
8
|
+
|
|
9
|
+
import grintools as gt
|
|
10
|
+
result, constructs = gt.infer([[71,17,9,5],[20,67,5,9],[13,6,63,20],[5,10,15,71]])
|
|
11
|
+
print(result.summary())
|
|
12
|
+
|
|
13
|
+
The confusion matrix must be in canonical order (rows and columns A1B1, A1B2, A2B1,
|
|
14
|
+
A2B2). If yours is not, normalise it first with gt.to_confusion(...) using labels and
|
|
15
|
+
factor levels, or assert gt.to_confusion(M, order="canonical").
|
|
16
|
+
"""
|
|
17
|
+
from importlib import resources
|
|
18
|
+
|
|
19
|
+
from .io import (to_confusion, describe, empirical_bias, response_bias,
|
|
20
|
+
ConfusionInput, PARAM_NAMES, PARAM_GROUPS)
|
|
21
|
+
from .criterion import Criterion, Target, Decision, stop_on_precision
|
|
22
|
+
from .onnx import GrinOnnx, OnnxResult
|
|
23
|
+
|
|
24
|
+
__version__ = "0.1.1"
|
|
25
|
+
|
|
26
|
+
__all__ = ["infer", "to_confusion", "describe", "empirical_bias", "response_bias",
|
|
27
|
+
"ConfusionInput", "Criterion", "Target", "Decision", "stop_on_precision",
|
|
28
|
+
"GrinOnnx", "OnnxResult", "default_model_path", "PARAM_NAMES",
|
|
29
|
+
"PARAM_GROUPS", "__version__"]
|
|
30
|
+
|
|
31
|
+
_SESSION_CACHE = {}
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def default_model_path():
|
|
35
|
+
"""Filesystem path to the ONNX model bundled with this release."""
|
|
36
|
+
return str(resources.files("grintools").joinpath("models", "npe_model.onnx"))
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def infer(counts, trials=None, model_path=None, calibrated=False, evidence_tol=0.5):
|
|
40
|
+
"""Run GRIN on a canonical-order 4x4 (or length-16) count matrix.
|
|
41
|
+
|
|
42
|
+
Returns (OnnxResult, constructs). `trials` defaults to row sums. Pass model_path
|
|
43
|
+
to use a specific .onnx; otherwise the bundled model is used and cached.
|
|
44
|
+
|
|
45
|
+
calibrated: False (default) returns the network's own posterior, which is what
|
|
46
|
+
every result in the GRIN paper is based on. True additionally rescales the
|
|
47
|
+
interval widths by per-family factors fitted on held-out simulations, correcting
|
|
48
|
+
a known asymmetry -- the sensitivity intervals run wider than nominal and the
|
|
49
|
+
correlation intervals narrower. Point estimates are unchanged either way. The
|
|
50
|
+
correction is estimated under the training prior and may not transfer to observers
|
|
51
|
+
far outside it, which is why it is opt-in. ``evidence_tol`` controls the width of
|
|
52
|
+
the undecided band used by the direction-explicit ``decision_*`` outputs.
|
|
53
|
+
"""
|
|
54
|
+
path = model_path or default_model_path()
|
|
55
|
+
grin = _SESSION_CACHE.get(path)
|
|
56
|
+
if grin is None:
|
|
57
|
+
grin = _SESSION_CACHE[path] = GrinOnnx(path)
|
|
58
|
+
return grin(counts, trials, evidence_tol=evidence_tol, calibrated=calibrated)
|