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/plot.py ADDED
@@ -0,0 +1,690 @@
1
+ """
2
+ plot.py: reporting and visualisation for GRIN results, at both the individual
3
+ and group level. Mirrors grin (the R package)'s plotting suite function-for-
4
+ function -- a figure made with grintools.plot and one made with grin should
5
+ read as the same family.
6
+
7
+ Kept out of grintools/__init__.py deliberately: the core package is
8
+ numpy + onnxruntime only (torch-free, dependency-light by design), and this
9
+ module needs matplotlib + pandas + scipy. Install with the [plot] extra:
10
+
11
+ pip install grintools[plot]
12
+ import grintools as gt
13
+ import grintools.plot as gtplot
14
+
15
+ result, constructs = gt.infer(M)
16
+ gtplot.plot_space(result)
17
+
18
+ Default style is black-on-white -- publication-safe, greyscale-safe, no
19
+ colour-vision assumptions. A small set of named colour palettes is opt-in:
20
+ pass `palette="name"` to any plot function (see `palette_names()`), or your
21
+ own list of hex colours, or set `grintools.plot.DEFAULT_PALETTE = "name"`
22
+ once to change the default everywhere. Either way, a single
23
+ stimulus/participant space never gets a four-way colour split -- with
24
+ everything else fixed, four colours for four points is decoration, not
25
+ information; stimuli are told apart by a text label instead.
26
+
27
+ `tidy()` is the shared foundation: it turns one or many (result, constructs)
28
+ pairs -- e.g. from `[gt.infer(m) for m in matrices]` -- into a pandas
29
+ DataFrame, which every group-level plot builds on.
30
+
31
+ Every function returns a plain matplotlib Axes (or Figure, for the
32
+ multi-panel ones). If a parameter below doesn't cover what you need, that is
33
+ deliberate rather than an oversight: the returned object is an ordinary
34
+ matplotlib object and takes ordinary matplotlib calls
35
+ (`ax = gtplot.plot_space(result); ax.set_title("...")`), which covers far
36
+ more than this package could ever anticipate as an argument. See the
37
+ package README's "Editing a figure further" section for worked examples.
38
+ """
39
+ import numpy as np
40
+
41
+ try:
42
+ import matplotlib.pyplot as plt
43
+ import pandas as pd
44
+ except ImportError as e: # pragma: no cover
45
+ raise ImportError(
46
+ "grintools.plot needs matplotlib and pandas. Install with: "
47
+ "pip install grintools[plot]") from e
48
+
49
+ INK, MUTE, PAPER = "#2B2B2E", "#9AA0A6", "#FFFFFF"
50
+ STIM = ["A1B1", "A1B2", "A2B1", "A2B2"]
51
+
52
+ # --------------------------------------------------------------------------- #
53
+ # Named colour palettes. "mono" (INK only) is the default and needs no entry
54
+ # here. "contrast" is the colour-vision-deficiency-safe categorical palette of
55
+ # Okabe & Ito (2008). Hex values match grin (the R package)'s palettes exactly,
56
+ # so a figure made with either package is visually the same family.
57
+ # --------------------------------------------------------------------------- #
58
+ PALETTES = {
59
+ "contrast": ["#0072B2", "#E69F00", "#009E73", "#D55E00", "#CC79A7", "#56B4E9"],
60
+ "dusk": ["#0B3954", "#12678A", "#1C9FC9", "#6FD6E8"],
61
+ "ember": ["#4A0E0E", "#9E2B25", "#D9622B", "#F2A65A"],
62
+ }
63
+
64
+ #: Default for every plot function's `palette` argument. Set
65
+ #: `grintools.plot.DEFAULT_PALETTE = "name"` once instead of passing
66
+ #: `palette="name"` to every call; an explicit `palette=` argument always wins.
67
+ DEFAULT_PALETTE = "mono"
68
+
69
+
70
+ def palette_names():
71
+ """List the built-in palette names: "mono" (default) plus PALETTES's keys."""
72
+ return ["mono"] + list(PALETTES)
73
+
74
+
75
+ def _resolve_palette(palette):
76
+ """`palette`: None (defer to DEFAULT_PALETTE), a built-in name, a single hex
77
+ string, or a list of hex colours supplied directly by the caller."""
78
+ if palette is None:
79
+ palette = DEFAULT_PALETTE
80
+ if isinstance(palette, (list, tuple)):
81
+ return list(palette)
82
+ if isinstance(palette, str) and palette.startswith("#"):
83
+ return [palette]
84
+ if palette == "mono":
85
+ return [INK]
86
+ if palette in PALETTES:
87
+ return PALETTES[palette]
88
+ raise ValueError(f"unknown palette {palette!r}; use one of {palette_names()}, "
89
+ "or pass your own list of hex colours")
90
+
91
+
92
+ def _group_colors(n, palette):
93
+ """n category colours: the resolved palette, repeated/cycled to length n --
94
+ so a mono plot never carries a legend distinguishing "black" from "black"."""
95
+ cols = _resolve_palette(palette)
96
+ if len(cols) == 1:
97
+ return cols * n
98
+ if n <= len(cols):
99
+ return cols[:n]
100
+ reps = -(-n // len(cols))
101
+ return (cols * reps)[:n]
102
+
103
+
104
+ def _style(ax, base_size=12):
105
+ """Clean axes: left+bottom spines only, no gridlines, ink-coloured ticks,
106
+ font sizes scaled off `base_size` (title/labels/ticks)."""
107
+ ax.spines["top"].set_visible(False)
108
+ ax.spines["right"].set_visible(False)
109
+ ax.spines["left"].set_color(INK)
110
+ ax.spines["bottom"].set_color(INK)
111
+ ax.tick_params(colors=INK, labelsize=base_size - 1)
112
+ ax.xaxis.label.set_color(INK); ax.xaxis.label.set_fontsize(base_size)
113
+ ax.yaxis.label.set_color(INK); ax.yaxis.label.set_fontsize(base_size)
114
+ ax.title.set_color(INK); ax.title.set_fontsize(base_size + 2); ax.title.set_fontweight("bold")
115
+ ax.set_facecolor(PAPER)
116
+ return ax
117
+
118
+
119
+ # --------------------------------------------------------------------------- #
120
+ # Forward model: identified GRT parameters -> predicted response probabilities.
121
+ # Used only for reporting/diagnostics (plot_diagnostics()'s predicted-vs-
122
+ # observed panel) -- inference itself never runs this, the trained network
123
+ # does. Identical to the Sheppard r-integration used to build the training
124
+ # data (see the "Software description" section of the manuscript and
125
+ # src/grt_model.py in the main GRIN repo), so a diagnostic plot's "predicted"
126
+ # values are computed the same way the network was taught to invert.
127
+ # --------------------------------------------------------------------------- #
128
+ _GL_NODES, _GL_WEIGHTS = np.polynomial.legendre.leggauss(48)
129
+
130
+
131
+ def _norm_cdf(x):
132
+ from scipy.stats import norm
133
+ return norm.cdf(x)
134
+
135
+
136
+ def _bvn_cdf(h, k, rho):
137
+ """Bivariate normal CDF Phi2(h, k; rho), standard normal margins."""
138
+ h = np.asarray(h, dtype=float); k = np.asarray(k, dtype=float); rho = np.asarray(rho, dtype=float)
139
+ base = _norm_cdf(h) * _norm_cdf(k)
140
+ t = rho[..., None] * (_GL_NODES + 1.0) / 2.0
141
+ jac = rho[..., None] / 2.0
142
+ hh = h[..., None]; kk = k[..., None]
143
+ omt2 = 1.0 - t * t
144
+ dens = np.exp(-(hh * hh - 2.0 * t * hh * kk + kk * kk) / (2.0 * omt2)) / (2.0 * np.pi * np.sqrt(omt2))
145
+ return base + np.sum(_GL_WEIGHTS * dens * jac, axis=-1)
146
+
147
+
148
+ def _forward_probabilities(zx, zy, rho):
149
+ """Per-stimulus (zx, zy, rho) -> 4x4 predicted response probabilities
150
+ (rows = stimuli, cols = responses, canonical order)."""
151
+ zx = np.asarray(zx, dtype=float); zy = np.asarray(zy, dtype=float); rho = np.asarray(rho, dtype=float)
152
+ p_x1 = _norm_cdf(-zx); p_y1 = _norm_cdf(-zy)
153
+ p11 = _bvn_cdf(-zx, -zy, rho)
154
+ p12 = p_x1 - p11; p21 = p_y1 - p11; p22 = 1.0 - p_x1 - p_y1 + p11
155
+ return np.clip(np.stack([p11, p12, p21, p22], axis=-1), 0.0, 1.0)
156
+
157
+
158
+ # --------------------------------------------------------------------------- #
159
+ # Tidy layer
160
+ # --------------------------------------------------------------------------- #
161
+ def tidy(results, ids=None):
162
+ """Turn one or many (result, constructs) pairs into a tidy DataFrame.
163
+
164
+ `results`: a single (result, constructs) tuple, or a list of them (e.g.
165
+ `[gt.infer(m) for m in matrices]`).
166
+ `ids`: optional participant IDs, same length as results; defaults to
167
+ p1, p2, ...
168
+
169
+ Returns a pandas DataFrame, one row per participant: id, model_class, the
170
+ 12 parameter estimates and their SDs, p_PI/p_sep_A/p_sep_B, the
171
+ evidence_* flags, and x_bias/y_bias (the decision-criterion bias of
172
+ response_bias()).
173
+ """
174
+ from .io import response_bias as _response_bias
175
+ if isinstance(results, tuple) and len(results) == 2 and hasattr(results[0], "names"):
176
+ results = [results]
177
+ if ids is None:
178
+ ids = [f"p{i + 1}" for i in range(len(results))]
179
+ if len(ids) != len(results):
180
+ raise ValueError(f"len(ids)={len(ids)} != len(results)={len(results)}")
181
+
182
+ rows = []
183
+ for pid, (result, constructs) in zip(ids, results):
184
+ row = {"id": pid, "model_class": result.model_class}
185
+ for name, est, sd in zip(result.names, result.params, result.std):
186
+ row[name] = float(est)
187
+ row[f"{name}_sd"] = float(sd)
188
+ row["p_PI"] = constructs["p_PI"]
189
+ row["p_sep_A"] = constructs["p_sep_A"]
190
+ row["p_sep_B"] = constructs["p_sep_B"]
191
+ row["evidence_PI"] = constructs["evidence_PI"]
192
+ row["evidence_sep_A"] = constructs["evidence_sep_A"]
193
+ row["evidence_sep_B"] = constructs["evidence_sep_B"]
194
+ bias = _response_bias(result)
195
+ row["x_bias"] = bias["x_bias"]
196
+ row["y_bias"] = bias["y_bias"]
197
+ rows.append(row)
198
+ return pd.DataFrame(rows)
199
+
200
+
201
+ def _long_params(df):
202
+ """Wide tidy DataFrame -> long (id, group, param, estimate, sd), one row
203
+ per participant x parameter."""
204
+ groups = {"zx": [f"zx_{i}" for i in range(4)], "zy": [f"zy_{i}" for i in range(4)],
205
+ "rho": [f"rho_{i}" for i in range(4)]}
206
+ out = []
207
+ for grp, names in groups.items():
208
+ for nm in names:
209
+ out.append(pd.DataFrame({
210
+ "id": df["id"], "group": grp, "param": nm,
211
+ "estimate": df[nm], "sd": df[f"{nm}_sd"],
212
+ }))
213
+ return pd.concat(out, ignore_index=True)
214
+
215
+
216
+ def _ellipse_xy(zx, zy, rho, k, n=100):
217
+ theta = np.linspace(0, 2 * np.pi, n)
218
+ L = np.array([[1, 0], [rho, np.sqrt(max(1 - rho**2, 0))]])
219
+ circle = np.stack([np.cos(theta), np.sin(theta)])
220
+ xy = (L @ circle) * k
221
+ return zx + xy[0], zy + xy[1]
222
+
223
+
224
+ def _ci_k(ci):
225
+ from scipy.stats import norm
226
+ return norm.ppf(0.5 + ci / 2)
227
+
228
+
229
+ def _marginal_strip(means, rng, orientation, col, base_size, ax=None):
230
+ """A small axes with one Normal(mean, 1) density curve per stimulus, over
231
+ `rng`. `orientation="y"` flips it for use as a right-side vertical strip."""
232
+ ax = ax or plt.subplots(figsize=(2, 5) if orientation == "y" else (5, 2))[1]
233
+ xs = np.linspace(rng[0], rng[1], 200)
234
+ for m in means:
235
+ d = np.exp(-0.5 * (xs - m) ** 2) / np.sqrt(2 * np.pi)
236
+ if orientation == "y":
237
+ ax.plot(d, xs, color=col)
238
+ ax.set_ylim(rng)
239
+ else:
240
+ ax.plot(xs, d, color=col)
241
+ ax.set_xlim(rng)
242
+ ax.set_xticks([]); ax.set_yticks([])
243
+ for spine in ax.spines.values():
244
+ spine.set_visible(False)
245
+ ax.set_facecolor(PAPER)
246
+ return ax
247
+
248
+
249
+ # --------------------------------------------------------------------------- #
250
+ # Individual-level plots
251
+ # --------------------------------------------------------------------------- #
252
+ def plot_space(result, ci=0.90, palette=None, title=None, xlabel="dimension A (zx)",
253
+ ylabel="dimension B (zy)", stim_labels=STIM, show_labels=True,
254
+ show_uncertainty=True, show_marginals=False, base_size=12, ax=None):
255
+ """One participant's perceptual space: 4 stimulus means with correlation
256
+ ellipses, decision bounds at 0 (GRIN's identified coordinates). Stimuli
257
+ are told apart by a text label at each point by default, not by colour --
258
+ with one participant on the plot, four colours for four points is
259
+ decoration, not information, and the quadrant is already fixed by the
260
+ sign convention.
261
+
262
+ The ellipse and the (optional) error bars show two different kinds of
263
+ uncertainty and the plot never conflates them: the ellipse is the
264
+ predicted spread of a single trial's perceptual sample around the mean
265
+ (fixed at unit variance by the model, shaped by rho); the error bars, if
266
+ shown, are the *posterior* uncertainty about where that mean itself is,
267
+ given the data (`result.std`).
268
+
269
+ `show_marginals=True` adds per-dimension marginal density strips (one
270
+ curve per stimulus) above and to the right of the main panel, and returns
271
+ a Figure instead of an Axes; incompatible with passing your own `ax`. See
272
+ also `plot_diagnostics()`, which pairs marginals with a
273
+ predicted-vs-observed reconstruction panel for a fuller view (not a
274
+ goodness-of-fit test of GRT itself -- see that function's docstring).
275
+ """
276
+ if len(stim_labels) != 4:
277
+ raise ValueError("stim_labels must have exactly 4 entries")
278
+ if show_marginals and ax is not None:
279
+ raise ValueError("show_marginals=True builds its own multi-panel figure; "
280
+ "pass ax=None (the default)")
281
+ k = _ci_k(ci)
282
+ col = _group_colors(1, palette)[0]
283
+ p = dict(zip(result.names, result.params))
284
+ s = dict(zip(result.names, result.std))
285
+
286
+ main_ax = ax or plt.subplots(figsize=(6, 6), constrained_layout=(not show_marginals))[1]
287
+ main_ax.axvline(0, ls="--", color=MUTE, lw=1)
288
+ main_ax.axhline(0, ls="--", color=MUTE, lw=1)
289
+ zxs, zys = [], []
290
+ for i, stim in enumerate(stim_labels):
291
+ zx, zy, rho = p[f"zx_{i}"], p[f"zy_{i}"], p[f"rho_{i}"]
292
+ zxs.append(zx); zys.append(zy)
293
+ if show_uncertainty:
294
+ sx, sy = s[f"zx_{i}"], s[f"zy_{i}"]
295
+ main_ax.plot([zx - k * sx, zx + k * sx], [zy, zy], color=col, lw=1.2, zorder=2)
296
+ main_ax.plot([zx, zx], [zy - k * sy, zy + k * sy], color=col, lw=1.2, zorder=2)
297
+ ex, ey = _ellipse_xy(zx, zy, rho, k)
298
+ main_ax.plot(ex, ey, color=col)
299
+ main_ax.scatter([zx], [zy], color=col, s=50, zorder=3)
300
+ if show_labels:
301
+ main_ax.annotate(stim, (zx, zy), color=col, fontsize=base_size - 3, ha="center",
302
+ va="bottom", xytext=(0, 8), textcoords="offset points")
303
+ if xlabel is not None:
304
+ main_ax.set_xlabel(xlabel)
305
+ if ylabel is not None:
306
+ main_ax.set_ylabel(ylabel)
307
+ unc_note = " and error bars" if show_uncertainty else ""
308
+ default_title = f"Perceptual space ({result.model_class})"
309
+ if not show_marginals:
310
+ subtitle = f"{ci:.0%} ellipses{unc_note}; dashed lines are the decision bounds"
311
+ full_title = (default_title if title is None else title) + f"\n{subtitle}"
312
+ # a single Text object (title \n subtitle), not a separate floating
313
+ # annotation, and the DEFAULT loc (not loc="left"): ax.set_title(...)
314
+ # on the returned Axes -- also default loc -- then cleanly replaces
315
+ # the whole thing, rather than adding a second title next to an
316
+ # orphaned one at a different loc.
317
+ main_ax.set_title(full_title, fontsize=base_size + 1)
318
+ main_ax.set_aspect("equal")
319
+ _style(main_ax, base_size)
320
+
321
+ if not show_marginals:
322
+ return main_ax
323
+
324
+ ex_all = np.concatenate([_ellipse_xy(zxs[i], zys[i], p[f"rho_{i}"], k)[0] for i in range(4)])
325
+ ey_all = np.concatenate([_ellipse_xy(zxs[i], zys[i], p[f"rho_{i}"], k)[1] for i in range(4)])
326
+ x_rng = (ex_all.min(), ex_all.max()); y_rng = (ey_all.min(), ey_all.max())
327
+ main_ax.set_xlim(x_rng); main_ax.set_ylim(y_rng)
328
+
329
+ fig = main_ax.figure
330
+ fig.set_size_inches(7.5, 7.5)
331
+ gs = fig.add_gridspec(2, 2, width_ratios=(4, 1), height_ratios=(1, 4),
332
+ left=0.1, right=0.95, bottom=0.08, top=0.9, wspace=0.05, hspace=0.05)
333
+ main_ax.set_position(gs[1, 0].get_position(fig))
334
+ main_ax.set_subplotspec(gs[1, 0])
335
+ top_ax = fig.add_subplot(gs[0, 0], sharex=main_ax)
336
+ right_ax = fig.add_subplot(gs[1, 1], sharey=main_ax)
337
+ _marginal_strip(zxs, x_rng, "x", col, base_size, ax=top_ax)
338
+ _marginal_strip(zys, y_rng, "y", col, base_size, ax=right_ax)
339
+ fig.suptitle(title if title else f"Perceptual space ({result.model_class})", fontsize=base_size + 2)
340
+ return fig
341
+
342
+
343
+ def plot_params(result, palette=None, title=None, param_labels=None, base_size=12, ax=None):
344
+ """One participant's 12 parameter estimates with 90% CIs (dot-and-whisker).
345
+ Position already separates the zx/zy/rho groups, so colour is optional.
346
+ `param_labels`: relabel the y-axis (defaults to result.names)."""
347
+ labels = list(param_labels) if param_labels is not None else list(result.names)
348
+ if len(labels) != len(result.names):
349
+ raise ValueError("param_labels must be the same length as result.names (12)")
350
+ ax = ax or plt.subplots(figsize=(6, 5))[1]
351
+ groups = ["zx"] * 4 + ["zy"] * 4 + ["rho"] * 4
352
+ cols = dict(zip(["zx", "zy", "rho"], _group_colors(3, palette)))
353
+ y = np.arange(len(labels))[::-1]
354
+ ax.axvline(0, ls="--", color=MUTE, lw=1)
355
+ for yi, est, lo, hi, grp in zip(y, result.params, result.ci_low, result.ci_high, groups):
356
+ ax.plot([lo, hi], [yi, yi], color=cols[grp], lw=1.5)
357
+ ax.scatter([est], [yi], color=cols[grp], s=40, zorder=3)
358
+ ax.set_yticks(y); ax.set_yticklabels(labels)
359
+ ax.set_xlabel("estimate (90% CI)")
360
+ ax.set_title("Parameter estimates" if title is None else title)
361
+ return _style(ax, base_size)
362
+
363
+
364
+ def plot_constructs(result, constructs, palette=None, title=None, base_size=12, ax=None):
365
+ """One participant's construct probabilities: correlation structure
366
+ (P(PI)/P(RHO1)/P(free)) and separability (P(sep A)/P(sep B)). Bars for a
367
+ construct the data can't decide (evidence_* is False) are flagged, not
368
+ silently plotted as if informative."""
369
+ ax = ax or plt.subplots(figsize=(6, 4))[1]
370
+ names = ["PI", "RHO1", "free", "sep A", "sep B"]
371
+ probs = list(constructs["p_corr"]) + [constructs["p_sep_A"], constructs["p_sep_B"]]
372
+ evidence = [constructs["evidence_PI"]] * 3 + [constructs["evidence_sep_A"], constructs["evidence_sep_B"]]
373
+ panel_colors = _group_colors(2, palette)
374
+ colors = [panel_colors[0]] * 3 + [panel_colors[1]] * 2
375
+ alphas = [1.0 if e else 0.35 for e in evidence]
376
+ bars = ax.bar(names, probs, color=colors)
377
+ for one_bar, a, ev in zip(bars, alphas, evidence):
378
+ one_bar.set_alpha(a)
379
+ if not ev:
380
+ ax.text(one_bar.get_x() + one_bar.get_width() / 2, one_bar.get_height() + 0.02,
381
+ "insufficient\nevidence", ha="center", va="bottom", fontsize=base_size - 4, color=MUTE)
382
+ ax.set_ylim(0, 1.15)
383
+ ax.set_ylabel("P(construct)")
384
+ ax.set_title(f"Construct probabilities ({result.model_class})" if title is None else title)
385
+ return _style(ax, base_size)
386
+
387
+
388
+ def plot_bias(result, ci=0.90, palette=None, title=None, dim_labels=("A", "B"),
389
+ base_size=12, ax=None):
390
+ """Decision-criterion response bias for one participant, with error bars
391
+ carrying its (approximate) uncertainty forward. See
392
+ grintools.response_bias(). For the model-free alternative, see
393
+ plot_empirical_bias()."""
394
+ from .io import response_bias
395
+ if len(dim_labels) != 2:
396
+ raise ValueError("dim_labels must have exactly 2 entries")
397
+ b = response_bias(result)
398
+ k = _ci_k(ci)
399
+ col = _group_colors(1, palette)[0]
400
+ ax = ax or plt.subplots(figsize=(4, 5))[1]
401
+ ax.axhline(0, ls="--", color=MUTE, lw=1)
402
+ ax.bar(dim_labels, [b["x_bias"], b["y_bias"]], color=col, width=0.5)
403
+ ax.errorbar(dim_labels, [b["x_bias"], b["y_bias"]],
404
+ yerr=[k * b["x_bias_se"], k * b["y_bias_se"]],
405
+ fmt="none", ecolor=INK, capsize=4)
406
+ ax.set_ylabel("decision-criterion bias (mean z-score)")
407
+ subtitle = (f"{ci:.0%} CI; 0 = unbiased; positive favours level 2, "
408
+ "negative favours level 1")
409
+ ax.set_title((("Response bias" if title is None else title)) + f"\n{subtitle}",
410
+ fontsize=base_size + 1)
411
+ return _style(ax, base_size)
412
+
413
+
414
+ def plot_empirical_bias(counts, trials=None, palette=None, title=None, dim_labels=("A", "B"),
415
+ base_size=12, ax=None):
416
+ """Empirical response bias for one participant: how far each dimension's
417
+ "respond level 2" rate sits from the unbiased 0.5, averaged across the
418
+ four stimuli. Works directly from a confusion matrix -- no gt.infer()
419
+ call needed. See grintools.empirical_bias(). For the model-based
420
+ decision-criterion alternative, see plot_bias()."""
421
+ from .io import empirical_bias
422
+ if len(dim_labels) != 2:
423
+ raise ValueError("dim_labels must have exactly 2 entries")
424
+ b = empirical_bias(counts, trials)
425
+ col = _group_colors(1, palette)[0]
426
+ ax = ax or plt.subplots(figsize=(4, 5))[1]
427
+ ax.axhline(0, ls="--", color=MUTE, lw=1)
428
+ ax.bar(dim_labels, [b["x_bias"], b["y_bias"]], color=col, width=0.5)
429
+ ax.set_ylim(-0.5, 0.5)
430
+ ax.set_ylabel("response bias (P(respond level 2) - 0.5)")
431
+ subtitle = "0 = unbiased; positive favours level 2, negative favours level 1"
432
+ ax.set_title((("Empirical response bias" if title is None else title)) + f"\n{subtitle}",
433
+ fontsize=base_size + 1)
434
+ return _style(ax, base_size)
435
+
436
+
437
+ def plot_diagnostics(result, counts, trials=None, show_predicted_observed=True,
438
+ show_marginals=True, palette=None, title=None, base_size=12):
439
+ """Predicted-vs-observed reconstruction and marginal-distribution
440
+ diagnostics for one participant. Needs the ORIGINAL confusion matrix as
441
+ well as the fitted result, because it compares what was observed against
442
+ what the fitted parameters predict -- gt.infer()'s return value alone
443
+ doesn't carry the input matrix back out.
444
+
445
+ Deliberately not a "goodness-of-fit" test: the identified 12-parameter
446
+ model is saturated (see the accompanying paper's Introduction and
447
+ identifiability-frontier study), so a single confusion matrix's response
448
+ proportions cannot, in principle, be used to test whether the underlying
449
+ GRT assumptions hold -- essentially any proportion table has SOME fitting
450
+ parameter vector. What this view shows is whether GRIN's OWN fitted
451
+ parameters reconstruct the matrix, informative in one direction only: a
452
+ poor reconstruction is a real signal (network approximation error, or a
453
+ matrix outside the trained envelope) worth a second look, but a good
454
+ reconstruction does not itself validate the GRT assumptions, because the
455
+ saturated model was essentially guaranteed to reconstruct it regardless.
456
+
457
+ `show_predicted_observed`: the forward model's predicted response
458
+ probability for each of the 16 stimulus/response cells, plotted against
459
+ the cell's observed proportion. Points near the diagonal indicate a good
460
+ reconstruction; systematic departure for one stimulus (told apart by
461
+ marker shape, not colour) says where the fit is struggling and is worth a
462
+ second look.
463
+
464
+ `show_marginals`: the predicted Normal(mean, 1) density on each dimension
465
+ for each of the four stimuli -- the same marginals plot_space()'s
466
+ `show_marginals=True` draws alongside the space plot itself, here paired
467
+ with the reconstruction check instead.
468
+
469
+ Returns a single Axes if only one panel is requested, otherwise a Figure.
470
+ """
471
+ if not show_predicted_observed and not show_marginals:
472
+ raise ValueError("nothing to plot: set show_predicted_observed and/or show_marginals=True")
473
+ cm = np.asarray(counts, dtype=float).reshape(4, 4)
474
+ if trials is None:
475
+ trials = cm.sum(axis=1)
476
+ trials = np.asarray(trials, dtype=float).reshape(4)
477
+ observed = cm / trials[:, None]
478
+
479
+ p = dict(zip(result.names, result.params))
480
+ zx = np.array([p[f"zx_{i}"] for i in range(4)])
481
+ zy = np.array([p[f"zy_{i}"] for i in range(4)])
482
+ rho = np.array([p[f"rho_{i}"] for i in range(4)])
483
+ col = _group_colors(1, palette)[0]
484
+
485
+ n_panels = int(show_predicted_observed) + int(show_marginals) * 2
486
+ fig, axes = plt.subplots(1, n_panels, figsize=(4.5 * n_panels, 4.5))
487
+ axes = np.atleast_1d(axes)
488
+ idx = 0
489
+
490
+ if show_predicted_observed:
491
+ predicted = _forward_probabilities(zx, zy, rho)
492
+ ax = axes[idx]; idx += 1
493
+ markers = ["o", "^", "s", "D"]
494
+ ax.plot([0, 1], [0, 1], ls="--", color=MUTE, lw=1)
495
+ for i, stim in enumerate(STIM):
496
+ ax.scatter(observed[i], predicted[i], color=col, marker=markers[i], s=45, label=stim)
497
+ ax.set_xlim(0, 1); ax.set_ylim(0, 1); ax.set_aspect("equal")
498
+ ax.set_xlabel("observed proportion"); ax.set_ylabel("predicted probability")
499
+ ax.set_title("Predicted vs. observed")
500
+ ax.legend(title="stimulus", fontsize=base_size - 4, title_fontsize=base_size - 3)
501
+ _style(ax, base_size)
502
+
503
+ if show_marginals:
504
+ x_rng = (zx.min() - 3, zx.max() + 3); y_rng = (zy.min() - 3, zy.max() + 3)
505
+ _marginal_strip(zx, x_rng, "x", col, base_size, ax=axes[idx])
506
+ axes[idx].set_title("dimension A marginals"); axes[idx].set_xlabel("zx")
507
+ _style(axes[idx], base_size); idx += 1
508
+ _marginal_strip(zy, y_rng, "x", col, base_size, ax=axes[idx])
509
+ axes[idx].set_title("dimension B marginals"); axes[idx].set_xlabel("zy")
510
+ _style(axes[idx], base_size)
511
+
512
+ fig.tight_layout()
513
+ if title:
514
+ fig.suptitle(title, fontsize=base_size + 2)
515
+ fig.subplots_adjust(top=0.85)
516
+ return axes[0] if n_panels == 1 else fig
517
+
518
+
519
+ # --------------------------------------------------------------------------- #
520
+ # Group-level plots
521
+ # --------------------------------------------------------------------------- #
522
+ def plot_space_group(results, ids=None, facet=True, ci=0.90, palette=None, title=None,
523
+ base_size=12, ncols=4):
524
+ """Many participants' perceptual spaces: one small-multiple panel each
525
+ (facet=True), or an overlay of all stimulus means + a single
526
+ across-participant mean ellipse per stimulus (facet=False).
527
+
528
+ facet=False is an EXPLORATORY INSPECTION VIEW ONLY, not a reporting
529
+ figure: GRT's perceptual space is defined per observer, and there is no
530
+ sense in which a "grand mean" ellipse over several independently-fitted
531
+ spaces is itself a fitted GRT model, or a quantity with the
532
+ calibrated-uncertainty guarantees gt.infer() gives an individual
533
+ estimate. Use it to eyeball whether a sample looks roughly homogeneous
534
+ before deciding how to report it properly (per participant, or via
535
+ plot_params_group() / plot_model_classes()) -- not as the figure itself.
536
+ A warning is printed each time this mode is used, as a standing reminder
537
+ rather than a one-off you might miss.
538
+ """
539
+ df = tidy(results, ids)
540
+ k = _ci_k(ci)
541
+ col = _group_colors(1, palette)[0]
542
+ n = len(df)
543
+
544
+ if facet:
545
+ ncols_ = min(ncols, n)
546
+ nrows = int(np.ceil(n / ncols_))
547
+ fig, axes = plt.subplots(nrows, ncols_, figsize=(3.2 * ncols_, 3.2 * nrows), squeeze=False)
548
+ for i, (_, row) in enumerate(df.iterrows()):
549
+ ax = axes[i // ncols_][i % ncols_]
550
+ ax.axvline(0, ls="--", color=MUTE, lw=0.8)
551
+ ax.axhline(0, ls="--", color=MUTE, lw=0.8)
552
+ for si, stim in enumerate(STIM):
553
+ zx, zy, rho = row[f"zx_{si}"], row[f"zy_{si}"], row[f"rho_{si}"]
554
+ ex, ey = _ellipse_xy(zx, zy, rho, k, n=60)
555
+ ax.plot(ex, ey, color=col, lw=1)
556
+ ax.scatter([zx], [zy], color=col, s=20, zorder=3)
557
+ ax.annotate(stim, (zx, zy), color=col, fontsize=6, ha="center", va="bottom",
558
+ xytext=(0, 4), textcoords="offset points")
559
+ ax.set_title(row["id"], fontsize=10)
560
+ ax.set_aspect("equal")
561
+ _style(ax, base_size)
562
+ for j in range(n, nrows * ncols_):
563
+ axes[j // ncols_][j % ncols_].axis("off")
564
+ fig.suptitle("Perceptual spaces by participant" if title is None else title)
565
+ fig.tight_layout()
566
+ return fig
567
+
568
+ import warnings
569
+ warnings.warn(
570
+ "plot_space_group(facet=False): exploratory inspection view only -- the "
571
+ "overlaid mean ellipse is not a fitted GRT model or a reporting figure. "
572
+ "See the plot_space_group() docstring.", stacklevel=2)
573
+ ax = plt.subplots(figsize=(6, 6), constrained_layout=True)[1]
574
+ ax.axvline(0, ls="--", color=MUTE, lw=1)
575
+ ax.axhline(0, ls="--", color=MUTE, lw=1)
576
+ for si, stim in enumerate(STIM):
577
+ zxs, zys, rhos = df[f"zx_{si}"], df[f"zy_{si}"], df[f"rho_{si}"]
578
+ ax.scatter(zxs, zys, color=col, s=20, alpha=0.3)
579
+ mx, my, mrho = zxs.mean(), zys.mean(), rhos.mean()
580
+ ex, ey = _ellipse_xy(mx, my, mrho, k)
581
+ ax.plot(ex, ey, color=col, lw=2)
582
+ ax.scatter([mx], [my], color=col, s=80, marker="D", zorder=3)
583
+ ax.annotate(stim, (mx, my), color=col, fontsize=9, ha="center", va="bottom",
584
+ xytext=(0, 10), textcoords="offset points")
585
+ ax.set_xlabel("zx"); ax.set_ylabel("zy")
586
+ default_title = "Perceptual space, group overlay (exploratory only)"
587
+ subtitle = (f"faint points = individuals; diamonds + {ci:.0%} ellipse = "
588
+ "across-participant mean -- inspection view, not a fitted model")
589
+ ax.set_title((default_title if title is None else title) + f"\n{subtitle}",
590
+ fontsize=base_size + 1)
591
+ ax.set_aspect("equal")
592
+ return _style(ax, base_size)
593
+
594
+
595
+ def plot_params_group(results, ids=None, palette=None, title=None, base_size=12):
596
+ """Boxplot of each parameter's estimate across many participants,
597
+ faceted by group (zx/zy/rho)."""
598
+ df = tidy(results, ids)
599
+ long = _long_params(df)
600
+ fig, axes = plt.subplots(1, 3, figsize=(12, 4.5))
601
+ cols = dict(zip(["zx", "zy", "rho"], _group_colors(3, palette)))
602
+ for ax, grp in zip(axes, ["zx", "zy", "rho"]):
603
+ sub = long[long["group"] == grp]
604
+ names = [f"{grp}_{i}" for i in range(4)]
605
+ data = [sub.loc[sub["param"] == nm, "estimate"].values for nm in names]
606
+ bp = ax.boxplot(data, tick_labels=names, patch_artist=True)
607
+ for box in bp["boxes"]:
608
+ box.set_facecolor(cols[grp]); box.set_alpha(0.6)
609
+ ax.axhline(0, ls="--", color=MUTE, lw=1)
610
+ ax.set_title(grp)
611
+ _style(ax, base_size)
612
+ fig.suptitle(f"Parameter distributions across participants (n={len(df)})" if title is None else title)
613
+ fig.tight_layout()
614
+ return fig
615
+
616
+
617
+ def plot_model_classes(results, ids=None, palette=None, title=None, base_size=12, ax=None):
618
+ """Bar chart of componentwise modal structures across many participants."""
619
+ df = tidy(results, ids)
620
+ counts = df["model_class"].value_counts()
621
+ col = _group_colors(1, palette)[0]
622
+ ax = ax or plt.subplots(figsize=(7, 4.5))[1]
623
+ ax.bar(counts.index, counts.values, color=col)
624
+ for i, v in enumerate(counts.values):
625
+ ax.text(i, v + 0.02 * max(counts.values), str(v), ha="center", color=INK)
626
+ ax.set_ylabel("participants")
627
+ ax.set_title(f"Componentwise modal structure (n={len(df)})" if title is None else title)
628
+ plt.setp(ax.get_xticklabels(), rotation=30, ha="right")
629
+ return _style(ax, base_size)
630
+
631
+
632
+ def plot_precision_group(results, ids=None, palette=None, title=None, base_size=12, ax=None):
633
+ """Boxplot of posterior SD across many participants, by parameter group."""
634
+ df = tidy(results, ids)
635
+ long = _long_params(df)
636
+ ax = ax or plt.subplots(figsize=(6, 4.5))[1]
637
+ groups = ["zx", "zy", "rho"]
638
+ cols = dict(zip(groups, _group_colors(3, palette)))
639
+ data = [long.loc[long["group"] == g, "sd"].values for g in groups]
640
+ bp = ax.boxplot(data, tick_labels=groups, patch_artist=True)
641
+ for box, g in zip(bp["boxes"], groups):
642
+ box.set_facecolor(cols[g])
643
+ box.set_alpha(0.6)
644
+ ax.set_ylabel("posterior SD")
645
+ ax.set_title(f"Precision across participants (n={len(df)})" if title is None else title)
646
+ return _style(ax, base_size)
647
+
648
+
649
+ def plot_bias_group(results, ids=None, palette=None, title=None, base_size=12, ax=None):
650
+ """Group-level companion to plot_bias(): one boxplot per dimension of
651
+ response_bias(), computed per participant from their fitted result. For
652
+ the model-free alternative, see plot_empirical_bias_group()."""
653
+ df = tidy(results, ids)
654
+ col = _group_colors(1, palette)[0]
655
+ ax = ax or plt.subplots(figsize=(4, 5))[1]
656
+ ax.axhline(0, ls="--", color=MUTE, lw=1)
657
+ data = [df["x_bias"].to_numpy(), df["y_bias"].to_numpy()]
658
+ bp = ax.boxplot(data, tick_labels=["A", "B"], patch_artist=True, widths=0.5)
659
+ for box in bp["boxes"]:
660
+ box.set_facecolor(col); box.set_alpha(0.5)
661
+ ax.set_ylabel("decision-criterion bias (mean z-score)")
662
+ ax.set_title(f"Response bias across participants (n={len(df)})"
663
+ if title is None else title)
664
+ return _style(ax, base_size)
665
+
666
+
667
+ def plot_empirical_bias_group(counts_list, trials_list=None, palette=None, title=None,
668
+ base_size=12, ax=None):
669
+ """Group-level companion to plot_empirical_bias(): one boxplot per
670
+ dimension of empirical_bias() computed on each participant's own
671
+ confusion matrix. Works directly from confusion matrices -- no
672
+ gt.infer() call needed."""
673
+ from .io import empirical_bias
674
+ if trials_list is None:
675
+ trials_list = [None] * len(counts_list)
676
+ if len(trials_list) != len(counts_list):
677
+ raise ValueError("trials_list must be the same length as counts_list")
678
+ b = [empirical_bias(c, t) for c, t in zip(counts_list, trials_list)]
679
+ col = _group_colors(1, palette)[0]
680
+ ax = ax or plt.subplots(figsize=(4, 5))[1]
681
+ ax.axhline(0, ls="--", color=MUTE, lw=1)
682
+ data = [[bi["x_bias"] for bi in b], [bi["y_bias"] for bi in b]]
683
+ bp = ax.boxplot(data, tick_labels=["A", "B"], patch_artist=True, widths=0.5)
684
+ for box in bp["boxes"]:
685
+ box.set_facecolor(col); box.set_alpha(0.5)
686
+ ax.set_ylim(-0.5, 0.5)
687
+ ax.set_ylabel("response bias (P(respond level 2) - 0.5)")
688
+ ax.set_title(f"Empirical response bias across participants (n={len(counts_list)})"
689
+ if title is None else title)
690
+ return _style(ax, base_size)