princessamygdala's picture
Claude Opus 5
Load the questionnaires, not just the trials
76c60a1
Raw History Blame Contribute Delete
16.2 kB
"""msgpack sessions -> tidy trial and session frames.
One row per trial, one row per session. Nothing here knows about a particular
generation of the design: rewards, effort fractions and the rest credit are all
read off each trial, because the task has already changed all three once and
the pilot files and the current build do not agree about any of them.
The unit of analysis is the SESSION, not the pid. Pilot links were handed out
as "pick one of these at random", so one pid can be several people; nothing in
this module deduplicates by pid.
"""
from __future__ import annotations
import json
import re
from pathlib import Path
import msgpack
import numpy as np
import pandas as pd
# Block records, oldest naming first. "Block1"/"Block2" was the name before
# 2026-08; the export read those long after the stages were renamed, which is
# how an entire main task went missing from every CSV for a while.
BLOCK_NAMES = ("Harvest1", "Harvest2", "Block1", "Block2")
NIGHT_NAMES = ("Night1", "Night2", "Night1b", "Night2b")
#: The blocks added after the night raids, each a block of its own rather than
#: a variant of one already here. NightWatch was being dropped on the floor:
#: it is not in BLOCK_NAMES or NIGHT_NAMES, so a session that ran 48 watch
#: trials loaded 48 day trials and nothing else, with no error anywhere.
WATCH_NAMES = ("NightWatch",)
EXTRA_DAY_NAMES = ("HarvestSpeed", "Uncertainty")
_NET_RE = re.compile(
r"^(Harvest\d|Block\d|Night\d b?|Night\db?|NightWatch|HarvestSpeed|Uncertainty)"
r"_trial(\d+)$")
_SESSION_RE = re.compile(r"(\d{4}-\d{2}-\d{2}_\d{2}h\d{2}\.\d{2})")
CHOICES_WORK = ("work", "work_self", "work_partner")
#: The stage list, in the order the app builds it. Used only to say how far
#: through a session got, the way Qualtrics' Progress column does. A test in
#: the web-app suite (test_stage_order.py) fails if build_experiment() and this
#: ever disagree -- the analysis env has no nicegui, so it cannot be imported.
#: Every stage build_experiment() produces, in order. test_stage_order.py
#: asserts the two match, because the progress column is derived from the
#: position of the last stage a session reached in this list: a stage missing
#: here silently moves every later one and reports partial sessions as further
#: along than they are.
STAGE_ORDER = [
"Fatigue_pre", "HowToPlay", "Calibration", "Practice",
"Comprehension", "Ready", "Harvest1", "Break", "Harvest2",
"Night1", "Night2", "Night2b", "Night1b", "HarvestSpeed", "Uncertainty",
"QuestionnaireTransition", "Fatigue_post", "NASA_TLX", "Effort_impact",
"PostTask_Motivation", "PostTask_Effort2", "PostTask_TaskRating",
"PostTask_Hypothetical", "PostTask_Strategy",
# The night harvest and the battery that asks about it. Both sit after
# the day task's questions, because each block is asked about once it has
# been played rather than both at the end.
"NightWatchPractice", "NightWatch", "NightQuestionnaireTransition",
"Fatigue_night", "Night_NASA_TLX", "Night_Effort_impact",
"Night_PostTask_Motivation", "Night_PostTask_Effort2",
"Night_PostTask_TaskRating", "Night_PostTask_Strategy",
# The questions about the PEOPLE, then the ones about the participant. One
# belief page covering every partner, including the other task's, because
# split across the two batteries it was asked twice and still missed a
# partner each time. After everything that asks about the tasks, because
# asking whether the other person was real tells the participant there is
# something to doubt.
"PostTask_Belief", "PostTask_Liking", "TriPM", "Demographics",
]
def read_records(path) -> list[dict]:
"""Every record in one session file, in order.
The format is a bare sequence of length-prefixed msgpack maps: 4-byte
big-endian length, then the map. A truncated tail is ignored rather than
raised on, because a session that was cut off mid-write still has every
complete record before the cut and those are worth reading.
"""
out = []
with open(path, "rb") as f:
while True:
head = f.read(4)
if len(head) < 4:
break
n = int.from_bytes(head, "big")
body = f.read(n)
if len(body) < n:
break
out.append(msgpack.unpackb(body, strict_map_key=False))
return out
def _stage_data(records: list[dict]) -> tuple[dict, dict]:
"""Split records into {stage_name: data} and {block_name: {idx: trial}}.
Last record wins per stage name, matching export_qualtrics._records_by_name:
a participant who goes Back and redoes a stage overwrites the earlier one.
The second return value is the per-trial safety net. It exists because a
block record is written once, at the end of the block, and PILOT03's second
block record never wrote at all -- its 24 trials survive only as
Harvest2_trial0..23. Counting block records alone silently truncates that
session to 24 trials.
"""
by: dict = {}
net: dict = {}
for r in records:
name = r.get("name")
if not name:
continue
data = r.get("data") or {}
m = _NET_RE.match(name)
if m:
net.setdefault(m.group(1), {})[int(m.group(2))] = data
else:
by[name] = data
return by, net
def _block_trials(by: dict, net: dict) -> list[dict]:
"""Every trial in the session, block record or safety net, whichever has
more for that block."""
out = []
for name in BLOCK_NAMES + NIGHT_NAMES + WATCH_NAMES + EXTRA_DAY_NAMES:
from_block = (by.get(name) or {}).get("trials") or []
from_net = net.get(name) or {}
if len(from_net) > len(from_block):
out += [from_net[k] for k in sorted(from_net)]
else:
out += list(from_block)
return out
def _session_id(path) -> str:
m = _SESSION_RE.search(Path(path).name)
return m.group(1) if m else Path(path).stem
def _pid(path) -> str:
return Path(path).parent.name
def trials_frame(path) -> pd.DataFrame:
"""One row per trial. An empty frame (with the columns) if there are none."""
recs = read_records(path)
by, net = _stage_data(recs)
trials = _block_trials(by, net)
calib = by.get("Calibration") or {}
max_boxes = calib.get("max_boxes")
rows = []
for t in trials:
choice = t.get("choice")
missed = choice not in CHOICES_WORK and choice != "rest"
# The night watch is a block of its own: both options pay, and what
# the choice moves is the partner's loss. Its trials carry night=None,
# so without this column every day/night split in the pipeline would
# count them as day trials and the day model would be fitted on 96
# trials, half of them with reward=0.
watch = bool(t.get("nightWatch"))
rows.append(dict(
pid=_pid(path),
session=_session_id(path),
block=t.get("block"),
night=t.get("night"),
night_watch=watch,
is_day=(t.get("night") is None and not watch),
trial_index=t.get("trialIndex"),
loop_index=t.get("loopIndex"),
condition=t.get("condition"),
beneficiary=t.get("beneficiary"),
effort_level=t.get("effortLevel"),
effort_frac=t.get("effortFrac"),
required=t.get("required"),
reward=t.get("reward"),
rest_credit=t.get("restCredit"),
partner_loss=t.get("partnerLoss"),
partner_reward=t.get("partnerReward"),
work_side=t.get("workSide"),
choice=choice,
chose_work=np.nan if missed else float(choice in CHOICES_WORK),
missed=missed,
outcome=t.get("outcome"),
success=t.get("success"),
harvested=t.get("harvested"),
credits=t.get("credits"),
decision_rt=t.get("decisionRT"),
n_key_presses=t.get("nKeyPresses"),
flood_rejects=t.get("floodRejects"),
n_pauses=t.get("nPauses"),
paused_ms=t.get("pausedMs"),
corn_need_total=t.get("cornNeedTotal"),
max_boxes=max_boxes,
# Night-watch design columns. Both options pay (work_credit against
# rest_credit, a constant 1-credit gap), and what varies is how
# much the partner loses, which is what separates the weight on
# one's own credits from the weight on their loss.
work_credit=t.get("workCredit"),
loss_sleep=t.get("lossSleep"),
loss_work=t.get("lossWork"),
saved=t.get("saved"),
info_condition=t.get("infoCondition"),
sleep_certain=t.get("sleepCertain"),
watch_certain=t.get("watchCertain"),
loss_sleep_drawn=t.get("lossSleepDrawn"),
loss_work_drawn=t.get("lossWorkDrawn"),
endowment=t.get("endowment"),
))
return pd.DataFrame(rows, columns=list(_EMPTY_COLS))
_EMPTY_COLS = (
"pid", "session", "block", "night", "night_watch", "is_day",
"trial_index", "loop_index", "condition",
"beneficiary", "effort_level", "effort_frac", "required", "reward",
"rest_credit", "partner_loss", "partner_reward", "work_side", "choice",
"chose_work", "missed", "outcome", "success", "harvested", "credits",
"decision_rt", "n_key_presses", "flood_rejects", "n_pauses", "paused_ms",
"corn_need_total", "max_boxes",
"work_credit", "loss_sleep", "loss_work", "saved", "info_condition",
"sleep_certain", "watch_certain", "loss_sleep_drawn", "loss_work_drawn",
"endowment",
)
def day_mask(trials: pd.DataFrame) -> pd.Series:
"""Which rows are day-task trials.
One definition, used by the summary and by the model layer. A night-watch
trial carries night=None, so "not a night trial" is not the same question
as "a day trial", and the difference is 48 trials with reward=0 landing in
the day fit. Frames assembled by hand (a test, a simulation) may not carry
`is_day`, so it is derived where it is absent.
"""
idx = trials.index
night = trials["night"] if "night" in trials.columns else pd.Series(np.nan, index=idx)
watch = (trials["night_watch"] if "night_watch" in trials.columns
else pd.Series(False, index=idx))
derived = night.isna() & ~watch.fillna(False).astype(bool)
if "is_day" in trials.columns:
col = trials["is_day"]
return col.where(col.notna(), derived).astype(bool)
return derived
def metadata(path) -> dict:
"""The session's user_storage, or {} when its final push never landed.
Everything that is a property of the SESSION rather than of a trial lives
here and nowhere else: which task ran first, whether this was a debug run,
the theme, the block order. It is written once, on the last push, so for
every session before 2026-10-17 it is simply absent -- that push was
refused and landed nothing. Returning {} rather than raising is what lets
the audit read those sessions at all.
"""
meta = Path(path).with_suffix(".json")
if not meta.exists():
return {}
try:
with open(meta, encoding="utf-8") as f:
return json.load(f).get("user_storage", {}) or {}
except (OSError, ValueError):
return {}
def session_summary(path) -> dict:
"""One row's worth of facts about a session, for the inclusion table."""
recs = read_records(path)
meta = metadata(path)
by, net = _stage_data(recs)
df = trials_frame(path)
calib = by.get("Calibration") or {}
qt = by.get("QuestionnaireTransition") or {}
# is_day, not night.isna(): a night-watch trial has night=None and would
# otherwise be counted, summarised and fitted as a day trial.
day = df[day_mask(df)] if len(df) else df
answered = day[~day["missed"]] if len(day) else day
if len(answered):
rate = answered["chose_work"].mean()
always = bool(rate in (0.0, 1.0))
else:
rate, always = np.nan, False
seen = [r.get("name") for r in recs if r.get("name") and not _NET_RE.match(r["name"])]
ordered = [n for n in STAGE_ORDER if n in set(seen)]
return dict(
pid=_pid(path),
session=_session_id(path),
path=str(path),
stages_seen=ordered,
last_stage=ordered[-1] if ordered else None,
# Qualtrics keeps partial responses and marks them; so do we. `finished`
# is the last stage of the run, `progress` how far through the stage
# list they got. Neither drops anyone.
finished=bool(seen and STAGE_ORDER[-1] in set(seen)),
progress=round(
(STAGE_ORDER.index(ordered[-1]) + 1) / len(STAGE_ORDER), 3) if ordered else 0.0,
n_trials=int(len(df)),
n_day_trials=int(len(day)),
n_night_trials=int(df["night"].notna().sum()) if len(df) else 0,
n_watch_trials=int(df["night_watch"].sum()) if len(df) else 0,
n_missed=int(df["missed"].sum()) if len(df) else 0,
work_rate=rate,
always_one_option=always,
max_boxes=calib.get("max_boxes"),
calib_counts=[int(r.get("harvested", 0)) for r in (calib.get("reps") or [])],
reached_end=bool(qt),
easiest_attempts=qt.get("easiest_attempts"),
easiest_success_rate=qt.get("easiest_success_rate"),
self_points=qt.get("self_points"),
partner_points=qt.get("partner_points"),
# The design generation this session was run under. Rewards, effort
# fractions and the rest credit have all changed once; sessions from
# either side of that are not poolable, and this is what says which.
rewards=sorted({int(r) for r in df["reward"].dropna()}) if len(df) else [],
effort_fracs=sorted({round(float(e), 2) for e in df["effort_frac"].dropna()}) if len(df) else [],
rest_credits=sorted({int(c) for c in df["rest_credit"].dropna()}) if len(df) else [],
# From the metadata, so blank for every session whose last push was
# refused. `task_first` is the only between-participant randomisation
# in the combined study -- there is no group, the trait measures are
# dimensional -- and it is a nuisance factor the models should be able
# to see. It cannot be recomputed from the stored pid: that is a
# one-way hash of the survey code, and the order is crc32 of the code
# itself.
study=meta.get("study"),
theme=meta.get("theme"),
task_first=meta.get("task_first"),
task_position=meta.get("task_position"),
task_order_source=meta.get("task_order_source"),
block_order=meta.get("block_order"),
dev_mode=bool(meta.get("dev_mode")),
has_metadata=bool(meta),
)
def build(paths) -> tuple[pd.DataFrame, pd.DataFrame]:
"""(trials, sessions) for a list of session files.
The sessions frame carries the questionnaires too, so the TriPM scores,
the belief and liking checks and the demographics arrive alongside the
behaviour rather than needing a second pass. See `measures`, including
why the belief columns are keyed by which game the partner belonged to
and not by the order the participant met them in.
"""
#: Imported here, not at module level: measures reads records through
#: this module, so a top-level import is circular.
from . import measures as _measures
frames, summaries = [], []
for p in paths:
frames.append(trials_frame(p))
summary = session_summary(p)
#: The behavioural summary wins any name it shares with a
#: questionnaire field, so adding a measure can never quietly
#: redefine a column the rest of the pipeline already reads.
for k, v in _measures.measures(p).items():
summary.setdefault(k, v)
summaries.append(summary)
trials = (pd.concat(frames, ignore_index=True) if frames
else pd.DataFrame(columns=list(_EMPTY_COLS)))
return trials, pd.DataFrame(summaries)