451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531 | def group_effect_table(
fit: Any,
groups: Sequence[str] | str | None = None,
probs: Sequence[float] = (0.025, 0.975),
) -> pd.DataFrame:
p = _probs(probs, three=False)
components = _posterior_components(fit)
spec = getattr(fit, "specification", None)
prepared = getattr(spec, "prepared", None)
data = getattr(prepared, "data", None)
contract = getattr(spec, "contract", None)
if data is None or contract is None:
raise GP3BayesError("The fit must retain prepared data and its model contract.")
available_groups: dict[str, tuple[str, str]] = {}
participant = contract.mappings.get("participant")
item = contract.mappings.get("item")
if isinstance(participant, str) and participant in data:
available_groups["participant"] = (participant, "participant")
if isinstance(item, str) and item in data:
available_groups["item"] = (item, "item")
requested = (
list(available_groups)
if groups is None
else ([groups] if isinstance(groups, str) else list(groups))
)
missing = [g for g in requested if g not in available_groups]
if missing:
raise GP3BayesError("Unknown grouping factors: " + ", ".join(missing))
rows: list[dict[str, Any]] = []
for group_name in requested:
column, stem = available_groups[group_name]
levels = pd.unique(data[column].dropna()).tolist()
sd_name = f"sd_{stem}"
z_name = f"{stem}_z"
if sd_name in components and z_name in components:
sd = np.asarray(components[sd_name], float)
z = np.asarray(components[z_name], float)
# z may have been flattened into component names by _posterior_components.
for idx, level in enumerate(levels):
component = f"{z_name}[{idx + 1}]"
if component in components:
draws = sd * np.asarray(components[component], float)
elif z.ndim >= 3 and idx < z.shape[2]:
draws = sd * z[:, :, idx]
else:
continue
flat = draws.reshape(-1)
q = np.quantile(flat, p, method="linear")
rows.append(
{
"group": group_name,
"level": str(level),
"coefficient": "Intercept",
"estimate": float(np.mean(flat)),
"se": float(np.std(flat, ddof=1)),
"lower": float(q[0]),
"upper": float(q[1]),
}
)
else:
# Canonical flattened r_* components from other backends.
prefix = f"r_{stem}["
for name, arr in components.items():
if not name.startswith(prefix):
continue
flat = np.asarray(arr, float).reshape(-1)
q = np.quantile(flat, p, method="linear")
rows.append(
{
"group": group_name,
"level": name[len(prefix) :].split(",", 1)[0].rstrip("]"),
"coefficient": "Intercept",
"estimate": float(flat.mean()),
"se": float(flat.std(ddof=1)),
"lower": float(q[0]),
"upper": float(q[1]),
}
)
if not rows:
raise GP3BayesError("No group-level effects could be extracted.")
return pd.DataFrame(rows)
|