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 ADDED
@@ -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)
grintools/cli.py ADDED
@@ -0,0 +1,74 @@
1
+ """Command-line entry point: `grin-fit`. Installed via the console_scripts hook."""
2
+ import argparse
3
+ import os
4
+ import numpy as np
5
+
6
+ from . import io as gio
7
+ from .criterion import Criterion, Target
8
+ from . import default_model_path
9
+
10
+
11
+ def read_matrix(path):
12
+ with open(path) as f:
13
+ first = f.readline().strip()
14
+ def is_num(t):
15
+ try:
16
+ float(t); return True
17
+ except ValueError:
18
+ return False
19
+ if all(is_num(t) for t in first.split(",")):
20
+ return np.loadtxt(path, delimiter=",", dtype=int), None
21
+ import csv
22
+ with open(path) as f:
23
+ rows = list(csv.reader(f))
24
+ labels = [c.strip() for c in rows[0]]
25
+ return np.array([[int(float(x)) for x in r] for r in rows[1:]], dtype=int), labels
26
+
27
+
28
+ def main(argv=None):
29
+ ap = argparse.ArgumentParser(prog="grin-fit",
30
+ description="Run GRIN on a confusion matrix with a stopping decision.")
31
+ ap.add_argument("--csv", default=None, help="4x4 CSV; defaults to the bundled example")
32
+ ap.add_argument("--model", default=None, help="path to npe_model.onnx (bundled model if omitted)")
33
+ ap.add_argument("--sd", type=float, default=0.15, help="precision target: zx/zy SD threshold")
34
+ ap.add_argument("--construct", default="PS_A", help="PI/PS_A/PS_B or a *_violated variant")
35
+ ap.add_argument("--at-least", type=float, default=0.90, help="probability threshold")
36
+ ap.add_argument("--combine", default="any", choices=["all", "any"])
37
+ args = ap.parse_args(argv)
38
+
39
+ csv_path = args.csv or os.path.join(os.path.dirname(__file__), "data", "example_cm.csv")
40
+ mat, labels = read_matrix(csv_path)
41
+ if labels is None:
42
+ ci = gio.to_confusion(mat, order="canonical")
43
+ else:
44
+ ci = gio.to_confusion(mat, stim_labels=labels, resp_labels=labels,
45
+ factor_a=("Old", "Young"), factor_b=("Neg", "Pos"))
46
+
47
+ print("=" * 60)
48
+ gio.describe(ci.counts, order="canonical")
49
+ print("=" * 60)
50
+
51
+ from .onnx import GrinOnnx
52
+ result, constructs = GrinOnnx(args.model or default_model_path())(ci.counts, ci.trials)
53
+
54
+ print("posterior (mean +/- SD):")
55
+ for i, n in enumerate(result.names):
56
+ print(f" {n:7s} {result.params[i]:+.2f} +/- {result.std[i]:.2f}")
57
+ print("\nconstructs (probability the construct holds, and the call):")
58
+ for label, pkey, dkey in (("PI", "p_PI", "decision_PI"),
59
+ ("PS_A", "p_sep_A", "decision_sep_A"),
60
+ ("PS_B", "p_sep_B", "decision_sep_B")):
61
+ print(f" {label:5s} {constructs[pkey]:.2f} {constructs[dkey]}")
62
+
63
+ crit = Criterion([Target.precision(params=["zx", "zy"], sd_max=args.sd),
64
+ Target.probability(args.construct, at_least=args.at_least)],
65
+ combine=args.combine)
66
+ decision = crit.evaluate(result, constructs)
67
+ print("\nstopping decision\n" + "-" * 60)
68
+ print(decision.summary())
69
+ print("-" * 60)
70
+ print(f"\n>>> {'STOP collecting' if decision.stop else 'KEEP collecting'} <<<")
71
+
72
+
73
+ if __name__ == "__main__":
74
+ main()
grintools/criterion.py ADDED
@@ -0,0 +1,149 @@
1
+ """
2
+ criterion.py: stopping decisions for adaptive designs.
3
+
4
+ Split out of io.py so `grintools.criterion` can be imported (and reasoned about)
5
+ independently of the input-normalisation layer; `Target`/`Criterion` only need
6
+ PARAM_NAMES/PARAM_GROUPS from io.py, not any of its parsing machinery.
7
+ """
8
+ from __future__ import annotations
9
+ import numpy as np
10
+
11
+ from .io import PARAM_NAMES, PARAM_GROUPS
12
+
13
+ # =========================================================================== #
14
+ # Stopping decisions. The EXPERIMENTER declares a Criterion from Targets; GRIN
15
+ # evaluates it. Four ways to use it:
16
+ #
17
+ # 1. passthrough : build no Criterion; read result.* and constructs yourself.
18
+ # 2. precision : Target.precision(params=..., sd_max=... | ci_width_max=...)
19
+ # stop when the parameter posterior is tight enough. This is
20
+ # the "I want the space measured, verdict aside" target.
21
+ # 3. probability : Target.probability("PI"|"PS_A"|"PS_B"|"*_violated", at_least=0.9)
22
+ # stop when a construct probability (from model_posterior)
23
+ # crosses a threshold. This is the "I want the verdict" target.
24
+ # 4. combine : Criterion([...targets...], combine="all"|"any")
25
+ #
26
+ # The construct targets read model_posterior's per-matrix dict directly, including
27
+ # its evidence_* flags. When an evidence flag is False the target is reported as
28
+ # unreachable (Decision.blocked_by), which is how the PI identifiability limit
29
+ # surfaces: a threshold on a construct the data cannot decide will never be met,
30
+ # and we say so rather than letting the loop run forever.
31
+ # =========================================================================== #
32
+ _CONSTRUCT_MAP = {
33
+ "PI": ("p_PI", "evidence_PI", False),
34
+ "PS_A": ("p_sep_A", "evidence_sep_A", False),
35
+ "PS_B": ("p_sep_B", "evidence_sep_B", False),
36
+ "PI_violated": ("p_PI", "evidence_PI", True),
37
+ "PS_A_violated": ("p_sep_A", "evidence_sep_A", True),
38
+ "PS_B_violated": ("p_sep_B", "evidence_sep_B", True),
39
+ }
40
+
41
+
42
+ def _select_indices(params):
43
+ if params is None or params == "all":
44
+ return list(range(len(PARAM_NAMES)))
45
+ idx = []
46
+ for p in ([params] if isinstance(params, str) else list(params)):
47
+ if p in PARAM_GROUPS:
48
+ idx.extend(PARAM_GROUPS[p])
49
+ elif p in PARAM_NAMES:
50
+ idx.append(PARAM_NAMES.index(p))
51
+ else:
52
+ raise ValueError(f"unknown parameter selector {p!r}; use a name in "
53
+ f"{PARAM_NAMES} or a group in {list(PARAM_GROUPS)}")
54
+ return sorted(set(idx))
55
+
56
+
57
+ class Target:
58
+ def __init__(self, kind, cfg):
59
+ self.kind = kind
60
+ self.cfg = cfg
61
+
62
+ @classmethod
63
+ def precision(cls, *, params=None, sd_max=None, ci_width_max=None):
64
+ if (sd_max is None) == (ci_width_max is None):
65
+ raise ValueError("precision target needs exactly one of sd_max or ci_width_max")
66
+ return cls("precision", dict(params=params, sd_max=sd_max, ci_width_max=ci_width_max))
67
+
68
+ @classmethod
69
+ def probability(cls, construct, *, at_least):
70
+ if construct not in _CONSTRUCT_MAP:
71
+ raise ValueError(f"unknown construct {construct!r}; choose from {list(_CONSTRUCT_MAP)}")
72
+ return cls("probability", dict(construct=construct, at_least=float(at_least)))
73
+
74
+ def check(self, result, constructs):
75
+ if self.kind == "precision":
76
+ idx = _select_indices(self.cfg["params"])
77
+ names = getattr(result, "names", PARAM_NAMES)
78
+ if self.cfg["sd_max"] is not None:
79
+ vals = np.asarray(result.std, float)[idx]; thr = self.cfg["sd_max"]; q = "sd"
80
+ else:
81
+ vals = (np.asarray(result.ci_high, float) - np.asarray(result.ci_low, float))[idx]
82
+ thr = self.cfg["ci_width_max"]; q = "ci_width"
83
+ worst = int(np.argmax(vals))
84
+ return dict(met=bool(np.all(vals <= thr)), value=float(vals[worst]),
85
+ name=f"{q}:{names[idx[worst]]}", threshold=thr, reachable=True, note="")
86
+ # probability
87
+ c = self.cfg["construct"]; thr = self.cfg["at_least"]
88
+ if constructs is None:
89
+ return dict(met=False, value=float("nan"), name=c, threshold=thr,
90
+ reachable=None, note="no constructs supplied; cannot evaluate")
91
+ key, evkey, violated = _CONSTRUCT_MAP[c]
92
+ p = float(constructs[key])
93
+ if violated:
94
+ p = 1.0 - p
95
+ ev = bool(constructs.get(evkey, True))
96
+ note = "" if ev else ("evidence flag is False: the data may not be able to decide "
97
+ "this construct in the current regime (a property of the data, "
98
+ "not of GRIN)")
99
+ return dict(met=bool(p >= thr and ev), value=p, name=c, threshold=thr,
100
+ reachable=ev, note=note)
101
+
102
+
103
+ class Decision:
104
+ def __init__(self, stop, checks, combine, blocked):
105
+ self.stop = bool(stop)
106
+ self.checks = checks
107
+ self.combine = combine
108
+ self.blocked_by = blocked
109
+
110
+ def __bool__(self):
111
+ return self.stop
112
+
113
+ def summary(self):
114
+ lines = [f"stop = {self.stop} (combine='{self.combine}')"]
115
+ for c in self.checks:
116
+ mark = "met" if c["met"] else "not met"
117
+ val = "nan" if c["value"] != c["value"] else f"{c['value']:.3f}"
118
+ lines.append(f" {c['name']:16s} {val} vs {c['threshold']:.3f} [{mark}]")
119
+ if c["note"]:
120
+ lines.append(f" note: {c['note']}")
121
+ if self.blocked_by:
122
+ lines.append(f" unreachable target(s): {self.blocked_by} "
123
+ f"(threshold may never be met with current data)")
124
+ return "\n".join(lines)
125
+
126
+
127
+ class Criterion:
128
+ def __init__(self, targets, combine="all"):
129
+ self.targets = list(targets)
130
+ if combine not in ("all", "any"):
131
+ raise ValueError("combine must be 'all' or 'any'")
132
+ self.combine = combine
133
+
134
+ @property
135
+ def needs_constructs(self):
136
+ return any(t.kind == "probability" for t in self.targets)
137
+
138
+ def evaluate(self, result=None, constructs=None):
139
+ checks = [t.check(result, constructs) for t in self.targets]
140
+ mets = [c["met"] for c in checks]
141
+ stop = all(mets) if self.combine == "all" else any(mets)
142
+ blocked = [c["name"] for c in checks if c["reachable"] is False]
143
+ return Decision(stop, checks, self.combine, blocked)
144
+
145
+
146
+ def stop_on_precision(result, *, sd_max=None, ci_width_max=None, params=None):
147
+ """Convenience for the common single-target precision case."""
148
+ return Criterion([Target.precision(params=params, sd_max=sd_max,
149
+ ci_width_max=ci_width_max)]).evaluate(result)
@@ -0,0 +1,4 @@
1
+ 71,17,9,5
2
+ 20,67,5,9
3
+ 13,6,63,20
4
+ 5,10,15,71