grintools 0.1.1__py3-none-any.whl
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/__init__.py +58 -0
- grintools/cli.py +74 -0
- grintools/criterion.py +149 -0
- grintools/data/example_cm.csv +4 -0
- grintools/io.py +428 -0
- grintools/models/model_provenance.json +10 -0
- grintools/models/npe_model.onnx +0 -0
- grintools/models/recalibration.json +103 -0
- grintools/onnx.py +186 -0
- grintools/plot.py +690 -0
- grintools/py.typed +0 -0
- grintools-0.1.1.dist-info/METADATA +284 -0
- grintools-0.1.1.dist-info/RECORD +17 -0
- grintools-0.1.1.dist-info/WHEEL +5 -0
- grintools-0.1.1.dist-info/entry_points.txt +2 -0
- grintools-0.1.1.dist-info/licenses/LICENSE +21 -0
- grintools-0.1.1.dist-info/top_level.txt +1 -0
grintools/io.py
ADDED
|
@@ -0,0 +1,428 @@
|
|
|
1
|
+
"""
|
|
2
|
+
grin_io.py: the input contract and stopping decisions for GRIN.
|
|
3
|
+
|
|
4
|
+
This is the thin layer between an experiment and the trained network. It does
|
|
5
|
+
three jobs and nothing else:
|
|
6
|
+
|
|
7
|
+
NORMALISE whatever the experiment has (labelled 4x4, bare 4x4, long trial
|
|
8
|
+
log, aggregated long) -> the canonical-order 4x4 count matrix plus
|
|
9
|
+
per-stimulus trial totals that api.infer expects.
|
|
10
|
+
DESCRIBE echo back exactly what was parsed, WITHOUT running the network, so
|
|
11
|
+
an experimenter can confirm their wiring before trusting a result.
|
|
12
|
+
DECIDE turn a posterior (and, optionally, the construct probabilities from
|
|
13
|
+
model_posterior) into a stop / keep-collecting decision, using a
|
|
14
|
+
criterion the EXPERIMENTER declares. GRIN does not choose the rule.
|
|
15
|
+
|
|
16
|
+
Principle: liberal about shape, strict about meaning. Any container/layout is
|
|
17
|
+
coerced, but two things are never guessed because guessing returns a confident
|
|
18
|
+
wrong answer: (1) stimulus/response ORDER for a bare unlabelled matrix, and (2)
|
|
19
|
+
counts vs proportions (the network reads trial totals as a second input, so
|
|
20
|
+
proportions silently wreck the posterior's width). Both are refused unless the
|
|
21
|
+
caller resolves them explicitly.
|
|
22
|
+
|
|
23
|
+
Canonical layout (from grt_model.py): rows = stimuli, cols = responses, both in
|
|
24
|
+
order A1B1, A1B2, A2B1, A2B2 (dimension A = x, B = y, B fastest). Canonical index
|
|
25
|
+
of a cell = 2*a_level + b_level.
|
|
26
|
+
|
|
27
|
+
Australian English. numpy required; pandas optional (duck-typed).
|
|
28
|
+
"""
|
|
29
|
+
|
|
30
|
+
from __future__ import annotations
|
|
31
|
+
import numpy as np
|
|
32
|
+
|
|
33
|
+
# --------------------------------------------------------------------------- #
|
|
34
|
+
# Canonical layout (mirror grt_model.py; fall back so this runs standalone).
|
|
35
|
+
# --------------------------------------------------------------------------- #
|
|
36
|
+
try:
|
|
37
|
+
from grt_model import STIMULUS_ORDER as CANON_STIM, RESPONSE_ORDER as CANON_RESP
|
|
38
|
+
from grt_model import PARAM_NAMES
|
|
39
|
+
except Exception:
|
|
40
|
+
CANON_STIM = ["A1B1", "A1B2", "A2B1", "A2B2"]
|
|
41
|
+
CANON_RESP = ["a1b1", "a1b2", "a2b1", "a2b2"]
|
|
42
|
+
PARAM_NAMES = ([f"zx_{i}" for i in range(4)]
|
|
43
|
+
+ [f"zy_{i}" for i in range(4)]
|
|
44
|
+
+ [f"rho_{i}" for i in range(4)])
|
|
45
|
+
|
|
46
|
+
PARAM_GROUPS = {"zx": list(range(0, 4)), "zy": list(range(4, 8)), "rho": list(range(8, 12))}
|
|
47
|
+
|
|
48
|
+
_SPARSE_TRIALS = 20
|
|
49
|
+
_PROP_TOL = 1e-6
|
|
50
|
+
_INT_TOL = 1e-8
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
# =========================================================================== #
|
|
54
|
+
# Containers
|
|
55
|
+
# =========================================================================== #
|
|
56
|
+
class ConfusionInput:
|
|
57
|
+
"""A normalised, network-ready input plus a record of how it was parsed."""
|
|
58
|
+
def __init__(self, counts, trials, placement, warnings, asserted_order):
|
|
59
|
+
self.counts = counts # (4,4) int, canonical order
|
|
60
|
+
self.trials = trials # (4,) int, per-stimulus totals
|
|
61
|
+
self.placement = placement # canonical cell -> source label
|
|
62
|
+
self.warnings = warnings # list[str]
|
|
63
|
+
self.asserted_order = asserted_order # did the caller assert canonical order?
|
|
64
|
+
|
|
65
|
+
@property
|
|
66
|
+
def ready(self):
|
|
67
|
+
return self.counts is not None
|
|
68
|
+
|
|
69
|
+
def __repr__(self):
|
|
70
|
+
return (f"ConfusionInput(trials={list(map(int, self.trials))}, "
|
|
71
|
+
f"warnings={len(self.warnings)})")
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
# =========================================================================== #
|
|
75
|
+
# Label resolution (strict): map 4 labels onto canonical order, or fail loudly.
|
|
76
|
+
# =========================================================================== #
|
|
77
|
+
def _canonical_index(a_level, b_level):
|
|
78
|
+
return 2 * int(a_level) + int(b_level)
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def _parse_cell_label(label, factor_a, factor_b, sep):
|
|
82
|
+
if isinstance(label, (tuple, list)):
|
|
83
|
+
if len(label) != 2:
|
|
84
|
+
raise ValueError(f"label {label!r} is not a 2-tuple (a_name, b_name)")
|
|
85
|
+
a_name, b_name = label
|
|
86
|
+
else:
|
|
87
|
+
parts = str(label).split(sep)
|
|
88
|
+
if len(parts) != 2:
|
|
89
|
+
raise ValueError(
|
|
90
|
+
f"cannot split label {label!r} on sep {sep!r} into two factor "
|
|
91
|
+
f"levels; pass a (a_name, b_name) tuple or use a matching sep")
|
|
92
|
+
a_name, b_name = parts[0].strip(), parts[1].strip()
|
|
93
|
+
if a_name not in factor_a:
|
|
94
|
+
raise ValueError(f"'{a_name}' from {label!r} is not a level of factor_a={factor_a}")
|
|
95
|
+
if b_name not in factor_b:
|
|
96
|
+
raise ValueError(f"'{b_name}' from {label!r} is not a level of factor_b={factor_b}")
|
|
97
|
+
return factor_a.index(a_name), factor_b.index(b_name)
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def _permutation_to_canonical(labels, factor_a, factor_b, sep):
|
|
101
|
+
"""Return (perm, placement) so axis[perm[c]] is canonical cell c. Raises unless
|
|
102
|
+
the 4 labels form a complete 2x2 factorial."""
|
|
103
|
+
canon_tokens = [t.lower() for t in CANON_STIM]
|
|
104
|
+
low = [str(x).lower() for x in labels]
|
|
105
|
+
if low == canon_tokens or low == [t.lower() for t in CANON_RESP]:
|
|
106
|
+
return list(range(4)), {CANON_STIM[i]: labels[i] for i in range(4)}
|
|
107
|
+
if factor_a is None or factor_b is None:
|
|
108
|
+
raise ValueError(
|
|
109
|
+
"labels are not canonical A1B1.. tokens, so I need factor_a=(A1,A2) and "
|
|
110
|
+
"factor_b=(B1,B2) to place them. Refusing to assume an order.")
|
|
111
|
+
factor_a, factor_b = tuple(factor_a), tuple(factor_b)
|
|
112
|
+
source_of_canon, seen = {}, set()
|
|
113
|
+
for pos, lab in enumerate(labels):
|
|
114
|
+
a, b = _parse_cell_label(lab, factor_a, factor_b, sep)
|
|
115
|
+
c = _canonical_index(a, b)
|
|
116
|
+
if c in seen:
|
|
117
|
+
raise ValueError(f"label {lab!r} duplicates canonical cell {CANON_STIM[c]}; "
|
|
118
|
+
f"the 4 labels must be a complete 2x2 factorial")
|
|
119
|
+
seen.add(c); source_of_canon[c] = pos
|
|
120
|
+
missing = [CANON_STIM[c] for c in range(4) if c not in seen]
|
|
121
|
+
if missing:
|
|
122
|
+
raise ValueError(f"labels do not cover the full factorial; missing: {missing}")
|
|
123
|
+
perm = [source_of_canon[c] for c in range(4)]
|
|
124
|
+
placement = {CANON_STIM[c]: labels[source_of_canon[c]] for c in range(4)}
|
|
125
|
+
return perm, placement
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
# =========================================================================== #
|
|
129
|
+
# Normaliser
|
|
130
|
+
# =========================================================================== #
|
|
131
|
+
def _is_dataframe(x):
|
|
132
|
+
return hasattr(x, "columns") and hasattr(x, "itertuples") and hasattr(x, "index")
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def _counts_guard(counts, trials, warnings):
|
|
136
|
+
counts = np.asarray(counts, dtype=float)
|
|
137
|
+
row_sums = counts.sum(axis=1)
|
|
138
|
+
looks_like_props = np.allclose(row_sums, 1.0, atol=1e-3) and np.all(counts <= 1.0 + _PROP_TOL)
|
|
139
|
+
non_integer = np.any(np.abs(counts - np.round(counts)) > _INT_TOL)
|
|
140
|
+
if looks_like_props or non_integer:
|
|
141
|
+
if trials is None:
|
|
142
|
+
raise ValueError(
|
|
143
|
+
"input looks like PROPORTIONS, not counts (rows sum to ~1 or contain "
|
|
144
|
+
"non-integers). The network reads per-stimulus trial totals as a "
|
|
145
|
+
"separate input, so proportions would silently wreck the posterior "
|
|
146
|
+
"uncertainty. Pass counts, or pass trials=[...] to rescale.")
|
|
147
|
+
trials = np.asarray(trials, dtype=float).reshape(4)
|
|
148
|
+
counts = np.round(counts * trials[:, None])
|
|
149
|
+
warnings.append("input treated as proportions and rescaled to counts using the "
|
|
150
|
+
"supplied trials; verify this is what you intended")
|
|
151
|
+
return np.round(counts).astype(int)
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def _row_warnings(counts, trials, warnings):
|
|
155
|
+
for i, n in enumerate(trials):
|
|
156
|
+
if n < _SPARSE_TRIALS:
|
|
157
|
+
warnings.append(f"stimulus {CANON_STIM[i]} has only {int(n)} trials "
|
|
158
|
+
f"(< {_SPARSE_TRIALS}); posterior will be wide here")
|
|
159
|
+
if np.any(counts == 0):
|
|
160
|
+
z = [(CANON_STIM[i], CANON_RESP[j]) for i in range(4) for j in range(4)
|
|
161
|
+
if counts[i, j] == 0]
|
|
162
|
+
warnings.append(f"{len(z)} empty cell(s) {z}; fine for GRIN, but this is the "
|
|
163
|
+
f"cell-separation regime where MLE baselines diverge")
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def _from_long(data, factor_a, factor_b, sep, warnings):
|
|
167
|
+
stim, resp, cnt = [], [], []
|
|
168
|
+
if _is_dataframe(data):
|
|
169
|
+
cols = [str(c).lower() for c in data.columns]
|
|
170
|
+
def col(name): return data.columns[cols.index(name)]
|
|
171
|
+
if "stimulus" not in cols or "response" not in cols:
|
|
172
|
+
raise ValueError("long DataFrame needs 'stimulus' and 'response' columns "
|
|
173
|
+
"(a 'count' column is optional)")
|
|
174
|
+
has_count = "count" in cols
|
|
175
|
+
for row in data.itertuples(index=False):
|
|
176
|
+
d = row._asdict()
|
|
177
|
+
stim.append(d[col("stimulus")]); resp.append(d[col("response")])
|
|
178
|
+
cnt.append(d[col("count")] if has_count else 1)
|
|
179
|
+
else:
|
|
180
|
+
for row in data:
|
|
181
|
+
row = tuple(row)
|
|
182
|
+
if len(row) == 2:
|
|
183
|
+
stim.append(row[0]); resp.append(row[1]); cnt.append(1)
|
|
184
|
+
elif len(row) == 3:
|
|
185
|
+
stim.append(row[0]); resp.append(row[1]); cnt.append(row[2])
|
|
186
|
+
else:
|
|
187
|
+
raise ValueError(f"long row {row!r} must be (stimulus, response) or "
|
|
188
|
+
f"(stimulus, response, count)")
|
|
189
|
+
stim_labels = list(dict.fromkeys(stim))
|
|
190
|
+
resp_labels = list(dict.fromkeys(resp))
|
|
191
|
+
if len(stim_labels) != 4 or len(resp_labels) != 4:
|
|
192
|
+
raise ValueError(f"expected 4 distinct stimuli and 4 responses; got "
|
|
193
|
+
f"{len(stim_labels)} stimuli, {len(resp_labels)} responses")
|
|
194
|
+
s_perm, s_place = _permutation_to_canonical(stim_labels, factor_a, factor_b, sep)
|
|
195
|
+
r_perm, _ = _permutation_to_canonical(resp_labels, factor_a, factor_b, sep)
|
|
196
|
+
s_to_c = {stim_labels[s_perm[c]]: c for c in range(4)}
|
|
197
|
+
r_to_c = {resp_labels[r_perm[c]]: c for c in range(4)}
|
|
198
|
+
counts = np.zeros((4, 4), dtype=float)
|
|
199
|
+
for s, r, c in zip(stim, resp, cnt):
|
|
200
|
+
counts[s_to_c[s], r_to_c[r]] += c
|
|
201
|
+
return counts, s_place
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
def to_confusion(data, *, stim_labels=None, resp_labels=None, factor_a=None,
|
|
205
|
+
factor_b=None, order=None, trials=None, sep="/", long=False):
|
|
206
|
+
"""Normalise any supported input into a canonical-order ConfusionInput.
|
|
207
|
+
Raises ValueError on any ambiguity of meaning."""
|
|
208
|
+
warnings = []
|
|
209
|
+
factor_a = tuple(factor_a) if factor_a is not None else None
|
|
210
|
+
factor_b = tuple(factor_b) if factor_b is not None else None
|
|
211
|
+
|
|
212
|
+
is_long = long or (_is_dataframe(data)
|
|
213
|
+
and "stimulus" in [str(c).lower() for c in data.columns])
|
|
214
|
+
if is_long:
|
|
215
|
+
counts, placement = _from_long(data, factor_a, factor_b, sep, warnings)
|
|
216
|
+
asserted = False
|
|
217
|
+
else:
|
|
218
|
+
if _is_dataframe(data):
|
|
219
|
+
if resp_labels is None:
|
|
220
|
+
resp_labels = list(data.columns)
|
|
221
|
+
idx = list(data.index)
|
|
222
|
+
if stim_labels is None and not all(isinstance(i, (int, np.integer)) for i in idx):
|
|
223
|
+
stim_labels = idx
|
|
224
|
+
mat = np.asarray(data.values, dtype=float)
|
|
225
|
+
else:
|
|
226
|
+
mat = np.asarray(data, dtype=float)
|
|
227
|
+
if mat.shape != (4, 4):
|
|
228
|
+
mat = mat.reshape(4, 4)
|
|
229
|
+
|
|
230
|
+
if order == "canonical":
|
|
231
|
+
counts = mat
|
|
232
|
+
placement = {c: c for c in CANON_STIM}
|
|
233
|
+
asserted = True
|
|
234
|
+
elif stim_labels is not None or resp_labels is not None:
|
|
235
|
+
if resp_labels is not None and stim_labels is None:
|
|
236
|
+
stim_labels = list(resp_labels)
|
|
237
|
+
warnings.append("rows were unlabelled; assumed to follow the same "
|
|
238
|
+
"category order as the column labels")
|
|
239
|
+
if stim_labels is None or resp_labels is None:
|
|
240
|
+
raise ValueError("need both stim_labels and resp_labels (or "
|
|
241
|
+
"order='canonical') to place a 4x4 matrix")
|
|
242
|
+
r_perm, placement = _permutation_to_canonical(stim_labels, factor_a, factor_b, sep)
|
|
243
|
+
c_perm, _ = _permutation_to_canonical(resp_labels, factor_a, factor_b, sep)
|
|
244
|
+
counts = mat[np.ix_(r_perm, c_perm)]
|
|
245
|
+
asserted = False
|
|
246
|
+
else:
|
|
247
|
+
raise ValueError(
|
|
248
|
+
"a bare 4x4 with no labels and no order assertion is refused: I will "
|
|
249
|
+
"not guess the stimulus/response order and hand back a confident wrong "
|
|
250
|
+
"posterior. Either pass order='canonical' to assert your matrix is "
|
|
251
|
+
"already A1B1,A1B2,A2B1,A2B2, or pass stim_labels/resp_labels with "
|
|
252
|
+
"factor_a and factor_b.")
|
|
253
|
+
|
|
254
|
+
counts = _counts_guard(counts, trials, warnings)
|
|
255
|
+
resolved_trials = (np.asarray(trials, dtype=float).round().astype(int).reshape(4)
|
|
256
|
+
if trials is not None else counts.sum(axis=1))
|
|
257
|
+
if trials is not None and not np.array_equal(resolved_trials, counts.sum(axis=1)):
|
|
258
|
+
warnings.append("supplied trials disagree with row sums of the counts; using "
|
|
259
|
+
"the supplied trials")
|
|
260
|
+
_row_warnings(counts, resolved_trials, warnings)
|
|
261
|
+
return ConfusionInput(counts, resolved_trials, placement, warnings, asserted)
|
|
262
|
+
|
|
263
|
+
|
|
264
|
+
# =========================================================================== #
|
|
265
|
+
# Describe: setup guide / dev mode / exception surface in one. Never raises.
|
|
266
|
+
# =========================================================================== #
|
|
267
|
+
def describe(data, *, printout=True, **kwargs):
|
|
268
|
+
report = {"ready": False, "errors": [], "warnings": [], "counts": None,
|
|
269
|
+
"trials": None, "placement": None, "asserted_order": None}
|
|
270
|
+
try:
|
|
271
|
+
ci = to_confusion(data, **kwargs)
|
|
272
|
+
report.update(ready=True, counts=ci.counts, trials=ci.trials,
|
|
273
|
+
placement=ci.placement, warnings=ci.warnings,
|
|
274
|
+
asserted_order=ci.asserted_order)
|
|
275
|
+
except Exception as e:
|
|
276
|
+
report["errors"].append(f"{type(e).__name__}: {e}")
|
|
277
|
+
if printout:
|
|
278
|
+
lines = ["GRIN input check", "-" * 52]
|
|
279
|
+
if report["ready"]:
|
|
280
|
+
lines.append("parsed OK, ready for inference"
|
|
281
|
+
+ (" (order asserted by caller)" if report["asserted_order"]
|
|
282
|
+
else " (order resolved from labels)"))
|
|
283
|
+
lines.append("canonical placement (canonical cell <- your label):")
|
|
284
|
+
for c in CANON_STIM:
|
|
285
|
+
lines.append(f" {c} <- {report['placement'][c]!r}")
|
|
286
|
+
lines.append(f"trials per stimulus: {list(map(int, report['trials']))}")
|
|
287
|
+
lines.append("counts (canonical order):")
|
|
288
|
+
for i, rowc in enumerate(report["counts"]):
|
|
289
|
+
lines.append(f" {CANON_STIM[i]:5s} | " + " ".join(f"{v:4d}" for v in rowc))
|
|
290
|
+
else:
|
|
291
|
+
lines.append("NOT ready, could not parse:")
|
|
292
|
+
for w in report["warnings"]:
|
|
293
|
+
lines.append(f" warning: {w}")
|
|
294
|
+
for e in report["errors"]:
|
|
295
|
+
lines.append(f" ERROR: {e}")
|
|
296
|
+
print("\n".join(lines))
|
|
297
|
+
return report
|
|
298
|
+
|
|
299
|
+
|
|
300
|
+
# =========================================================================== #
|
|
301
|
+
# Response bias: two different things people mean by the term, kept
|
|
302
|
+
# deliberately distinct rather than collapsed into one function.
|
|
303
|
+
#
|
|
304
|
+
# empirical_bias() is a description of the DATA: how often a level-2 response
|
|
305
|
+
# was given, relative to chance, straight from the raw counts. It needs no
|
|
306
|
+
# model fit and works even on a matrix GRIN can't otherwise fit.
|
|
307
|
+
#
|
|
308
|
+
# response_bias() is the SDT-native quantity: GRT is a multidimensional
|
|
309
|
+
# extension of signal detection theory, and its decision bound is fixed at 0
|
|
310
|
+
# by convention (see the ordering contract, above) -- an unbiased observer's
|
|
311
|
+
# two levels on a dimension are mirror images about that bound, so their four
|
|
312
|
+
# identified z-scores average to exactly zero. A nonzero average is a shifted
|
|
313
|
+
# decision criterion in the classical SDT sense, read directly off parameters
|
|
314
|
+
# infer() already estimated, no extra computation beyond an average.
|
|
315
|
+
# Confirmed numerically before shipping: a deliberately asymmetric z-score
|
|
316
|
+
# input and its raw-data response rate move together and agree in sign with
|
|
317
|
+
# empirical_bias() on the same case.
|
|
318
|
+
# =========================================================================== #
|
|
319
|
+
def empirical_bias(counts, trials=None):
|
|
320
|
+
"""Empirical response bias from a raw confusion matrix.
|
|
321
|
+
|
|
322
|
+
The signed tendency to report level 2 of a dimension more or less often
|
|
323
|
+
than level 1, averaged across the four stimuli: 0 is unbiased, positive
|
|
324
|
+
means the observer favours the "2" response on that dimension more than a
|
|
325
|
+
fair coin would, negative means they favour "1". A description of the
|
|
326
|
+
data, independent of any model fit -- it needs no trained network and
|
|
327
|
+
works even on a matrix GRIN can't otherwise fit. See response_bias() for
|
|
328
|
+
the model-based decision-criterion counterpart.
|
|
329
|
+
|
|
330
|
+
`counts`: a canonical-order 4x4 matrix, or a length-16 vector read
|
|
331
|
+
row-major. `trials`: optional per-stimulus trial totals; defaults to row
|
|
332
|
+
sums.
|
|
333
|
+
|
|
334
|
+
Returns a dict: `x_bias`, `y_bias` (each in [-0.5, 0.5]), and `p_resp2`,
|
|
335
|
+
a (4, 2) array giving P(respond level 2) on each dimension for each of
|
|
336
|
+
the four stimuli (so a systematic bias can be told apart from one driven
|
|
337
|
+
by a single stimulus).
|
|
338
|
+
"""
|
|
339
|
+
cm = np.asarray(counts, dtype=float).reshape(4, 4)
|
|
340
|
+
if trials is None:
|
|
341
|
+
trials = cm.sum(axis=1)
|
|
342
|
+
trials = np.asarray(trials, dtype=float).reshape(4)
|
|
343
|
+
props = cm / trials[:, None]
|
|
344
|
+
p_x2 = props[:, 2] + props[:, 3] # respond "A2" (canonical cols a2b1, a2b2)
|
|
345
|
+
p_y2 = props[:, 1] + props[:, 3] # respond "B2" (canonical cols a1b2, a2b2)
|
|
346
|
+
return {
|
|
347
|
+
"x_bias": float(p_x2.mean() - 0.5),
|
|
348
|
+
"y_bias": float(p_y2.mean() - 0.5),
|
|
349
|
+
"p_resp2": np.stack([p_x2, p_y2], axis=1),
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
|
|
353
|
+
def response_bias(result):
|
|
354
|
+
"""Parametric (decision-criterion) response bias from a fitted result.
|
|
355
|
+
|
|
356
|
+
The mean of a dimension's four identified z-scores: exactly zero when the
|
|
357
|
+
two levels are mirror images about the fixed decision bound (unbiased),
|
|
358
|
+
and equal to the criterion's effective offset from that symmetric point
|
|
359
|
+
otherwise -- the same sign convention as empirical_bias() (positive
|
|
360
|
+
favours level 2), but read directly off `result.params` rather than raw
|
|
361
|
+
response counts. Unlike empirical_bias(), this needs an infer() fit, and
|
|
362
|
+
carries the fit's own uncertainty forward.
|
|
363
|
+
|
|
364
|
+
`result`: an OnnxResult (e.g. the first element of infer(M)'s return, or
|
|
365
|
+
any object duck-typing `.names`/`.params`/`.std`).
|
|
366
|
+
|
|
367
|
+
Returns a dict: `x_bias`, `y_bias`, and `x_bias_se`/`y_bias_se`. The SEs
|
|
368
|
+
are a marginal-independence approximation from `result.std` (the
|
|
369
|
+
posterior's full covariance across parameters isn't exposed by infer(),
|
|
370
|
+
only per-parameter marginal SDs, so this likely under- or overstates the
|
|
371
|
+
true joint uncertainty somewhat; treat as approximate, not exact).
|
|
372
|
+
"""
|
|
373
|
+
p = dict(zip(result.names, result.params))
|
|
374
|
+
s = dict(zip(result.names, result.std))
|
|
375
|
+
x_nm = [f"zx_{i}" for i in range(4)]
|
|
376
|
+
y_nm = [f"zy_{i}" for i in range(4)]
|
|
377
|
+
x_vals = np.array([p[n] for n in x_nm]); y_vals = np.array([p[n] for n in y_nm])
|
|
378
|
+
x_sds = np.array([s[n] for n in x_nm]); y_sds = np.array([s[n] for n in y_nm])
|
|
379
|
+
return {
|
|
380
|
+
"x_bias": float(x_vals.mean()), "y_bias": float(y_vals.mean()),
|
|
381
|
+
"x_bias_se": float(np.sqrt(np.sum(x_sds ** 2)) / 4),
|
|
382
|
+
"y_bias_se": float(np.sqrt(np.sum(y_sds ** 2)) / 4),
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
|
|
386
|
+
# =========================================================================== #
|
|
387
|
+
# Convenience: normalise -> infer (-> constructs -> decide) in one call. Network
|
|
388
|
+
# imports are lazy so this module and its I/O are usable without torch present.
|
|
389
|
+
# =========================================================================== #
|
|
390
|
+
def _import_infer():
|
|
391
|
+
try:
|
|
392
|
+
from api import infer, load_model
|
|
393
|
+
except Exception:
|
|
394
|
+
from .api import infer, load_model
|
|
395
|
+
return infer, load_model
|
|
396
|
+
|
|
397
|
+
|
|
398
|
+
def _import_model_posterior():
|
|
399
|
+
try:
|
|
400
|
+
from model_posterior import model_posterior
|
|
401
|
+
except Exception:
|
|
402
|
+
from .model_posterior import model_posterior
|
|
403
|
+
return model_posterior
|
|
404
|
+
|
|
405
|
+
|
|
406
|
+
def fit(data, *, stim_labels=None, resp_labels=None, factor_a=None, factor_b=None,
|
|
407
|
+
order=None, trials=None, sep="/", long=False, criterion=None,
|
|
408
|
+
constructs=False, model=None, n_samples=1000):
|
|
409
|
+
"""Normalise `data`, run GRIN, optionally compute construct probabilities and a
|
|
410
|
+
stopping decision. Returns the InferenceResult with `.input_` attached, plus
|
|
411
|
+
`.constructs` and `.decision` when requested."""
|
|
412
|
+
ci = to_confusion(data, stim_labels=stim_labels, resp_labels=resp_labels,
|
|
413
|
+
factor_a=factor_a, factor_b=factor_b, order=order,
|
|
414
|
+
trials=trials, sep=sep, long=long)
|
|
415
|
+
infer, load_model = _import_infer()
|
|
416
|
+
want_constructs = constructs or (criterion is not None and criterion.needs_constructs)
|
|
417
|
+
if model is None and want_constructs:
|
|
418
|
+
model = load_model() # load once, share with model_posterior
|
|
419
|
+
result = infer(ci.counts, trials=ci.trials, model=model, n_samples=n_samples)
|
|
420
|
+
result.input_ = ci
|
|
421
|
+
if want_constructs:
|
|
422
|
+
model_posterior = _import_model_posterior()
|
|
423
|
+
result.constructs = model_posterior(
|
|
424
|
+
model, ci.counts.reshape(1, 16).astype(float),
|
|
425
|
+
ci.trials.reshape(1, 4).astype(float), n_samples=n_samples)[0]
|
|
426
|
+
if criterion is not None:
|
|
427
|
+
result.decision = criterion.evaluate(result, getattr(result, "constructs", None))
|
|
428
|
+
return result
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
{
|
|
2
|
+
"model_file": "npe_model.onnx",
|
|
3
|
+
"sha256": "d9ce8f1f5632b8aef5b47c5f37b01f75002384eb7389815280c2d2aa731da4b2",
|
|
4
|
+
"version": "1.0.0",
|
|
5
|
+
"source_commit": "7c466d174262c4fce52dc22c6484a0c952d7e635",
|
|
6
|
+
"exported_utc": "2026-09-29T14:06:20Z",
|
|
7
|
+
"exported_by": "scripts/export_onnx.py --install (release bytes, 2026-08-25)",
|
|
8
|
+
"checkpoint_file": "results/models/npe_model.pt",
|
|
9
|
+
"checkpoint_sha256": "0f9deae1c5623b2403dc30241b09108368422ef1b3f444e92626eababc1f8fc0"
|
|
10
|
+
}
|
|
Binary file
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
{
|
|
2
|
+
"meta": {
|
|
3
|
+
"model": "/home/msb/projects/grin/results/models/npe_model.pt",
|
|
4
|
+
"n_fit": 18000,
|
|
5
|
+
"n_val": 18000,
|
|
6
|
+
"seed_fit": 1234,
|
|
7
|
+
"seed_val": 5678,
|
|
8
|
+
"levels": [
|
|
9
|
+
0.5,
|
|
10
|
+
0.7,
|
|
11
|
+
0.8,
|
|
12
|
+
0.9,
|
|
13
|
+
0.95
|
|
14
|
+
],
|
|
15
|
+
"method": "per-family scale on the posterior SD, s = SD(standardised residual)"
|
|
16
|
+
},
|
|
17
|
+
"global_scale": {
|
|
18
|
+
"z": 0.8752770871818708,
|
|
19
|
+
"rho": 1.0822007570298786
|
|
20
|
+
},
|
|
21
|
+
"by_trials": {
|
|
22
|
+
"z": {
|
|
23
|
+
"0-20": 0.9586682933660284,
|
|
24
|
+
"20-50": 0.9246520290211189,
|
|
25
|
+
"50-200": 0.8260123901116132,
|
|
26
|
+
"200-10000": 0.7048340682344255
|
|
27
|
+
},
|
|
28
|
+
"rho": {
|
|
29
|
+
"0-20": 1.1282987916836469,
|
|
30
|
+
"20-50": 1.101807906153062,
|
|
31
|
+
"50-200": 1.056938271768986,
|
|
32
|
+
"200-10000": 1.0049146759996477
|
|
33
|
+
}
|
|
34
|
+
},
|
|
35
|
+
"validation": {
|
|
36
|
+
"0.5": {
|
|
37
|
+
"z": {
|
|
38
|
+
"raw": 0.5509097222222222,
|
|
39
|
+
"global_scaled": 0.4906041666666667,
|
|
40
|
+
"by_trials_scaled": 0.48439583333333336
|
|
41
|
+
},
|
|
42
|
+
"rho": {
|
|
43
|
+
"raw": 0.4093125,
|
|
44
|
+
"global_scaled": 0.4424166666666667,
|
|
45
|
+
"by_trials_scaled": 0.4411875
|
|
46
|
+
}
|
|
47
|
+
},
|
|
48
|
+
"0.7": {
|
|
49
|
+
"z": {
|
|
50
|
+
"raw": 0.7620555555555556,
|
|
51
|
+
"global_scaled": 0.6952361111111112,
|
|
52
|
+
"by_trials_scaled": 0.6930555555555555
|
|
53
|
+
},
|
|
54
|
+
"rho": {
|
|
55
|
+
"raw": 0.6140625,
|
|
56
|
+
"global_scaled": 0.657375,
|
|
57
|
+
"by_trials_scaled": 0.6579166666666667
|
|
58
|
+
}
|
|
59
|
+
},
|
|
60
|
+
"0.8": {
|
|
61
|
+
"z": {
|
|
62
|
+
"raw": 0.8649722222222223,
|
|
63
|
+
"global_scaled": 0.8009791666666667,
|
|
64
|
+
"by_trials_scaled": 0.8030208333333333
|
|
65
|
+
},
|
|
66
|
+
"rho": {
|
|
67
|
+
"raw": 0.7364583333333333,
|
|
68
|
+
"global_scaled": 0.7814166666666666,
|
|
69
|
+
"by_trials_scaled": 0.78375
|
|
70
|
+
}
|
|
71
|
+
},
|
|
72
|
+
"0.9": {
|
|
73
|
+
"z": {
|
|
74
|
+
"raw": 0.9469861111111111,
|
|
75
|
+
"global_scaled": 0.9101041666666667,
|
|
76
|
+
"by_trials_scaled": 0.9110555555555555
|
|
77
|
+
},
|
|
78
|
+
"rho": {
|
|
79
|
+
"raw": 0.8740416666666667,
|
|
80
|
+
"global_scaled": 0.913375,
|
|
81
|
+
"by_trials_scaled": 0.9176666666666666
|
|
82
|
+
}
|
|
83
|
+
},
|
|
84
|
+
"0.95": {
|
|
85
|
+
"z": {
|
|
86
|
+
"raw": 0.9761111111111112,
|
|
87
|
+
"global_scaled": 0.9556666666666667,
|
|
88
|
+
"by_trials_scaled": 0.9553125
|
|
89
|
+
},
|
|
90
|
+
"rho": {
|
|
91
|
+
"raw": 0.95125,
|
|
92
|
+
"global_scaled": 0.9718541666666667,
|
|
93
|
+
"by_trials_scaled": 0.9709583333333334
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
},
|
|
97
|
+
"mean_abs_coverage_error": {
|
|
98
|
+
"raw": 0.05184097222222225,
|
|
99
|
+
"global_scaled": 0.018493055555555554,
|
|
100
|
+
"by_trials_scaled": 0.01977083333333332
|
|
101
|
+
},
|
|
102
|
+
"recommended": "global"
|
|
103
|
+
}
|