HarvestForTwo / analysis /tests /test_loader.py
princessamygdala's picture
Claude Opus 5
Flag the staff sessions, and stop asserting a design that moved
700dc4c
Raw History Blame Contribute Delete
5.7 kB
"""Reading a session file.
The reference session is PILOT03, which is the awkward one: its Harvest2 block
record never wrote, so its second block exists only as per-trial safety-net
records. Counting block records alone truncates it from 48 trials to 24 and
loses a whole participant's second block without saying so.
"""
import pandas as pd
import pytest
from pe_analysis import loader
def test_pilot03_needs_the_safety_net_fallback(pilot03):
recs = loader.read_records(pilot03)
by, net = loader._stage_data(recs)
assert len((by.get("Harvest2") or {}).get("trials") or []) == 0
assert len(net["Harvest2"]) == 24
assert len(loader.trials_frame(pilot03)) == 48
def test_trials_frame_has_the_columns_the_model_needs(pilot03):
df = loader.trials_frame(pilot03)
for col in ["pid", "session", "block", "trial_index", "beneficiary",
"effort_frac", "reward", "rest_credit", "choice", "chose_work",
"missed", "max_boxes"]:
assert col in df.columns, col
assert set(df["beneficiary"]) == {"self", "other"}
assert df["chose_work"].isin([0.0, 1.0]).all()
def test_the_design_is_read_from_the_file_not_assumed(pilot03):
"""PILOT03 ran the pre-September design: rewards 2/6/10, effort 0.50-0.95,
rest credit 1. The current build ships 3/6/10, 0.35-0.80 and 2. Anything
that hardcodes one of those silently mislabels the other."""
s = loader.session_summary(pilot03)
assert s["rewards"] == [2, 6, 10]
assert s["effort_fracs"] == [0.5, 0.65, 0.8, 0.95]
assert s["rest_credits"] == [1]
def test_the_design_grid_is_complete(pilot03):
"""2 beneficiary x 4 effort x 3 reward = 24 cells, each run twice."""
df = loader.trials_frame(pilot03)
counts = df.groupby(["beneficiary", "effort_frac", "reward"]).size()
assert len(counts) == 24
assert (counts == 2).all()
def test_session_summary_flags_an_always_work_responder(pilot03):
s = loader.session_summary(pilot03)
assert s["n_trials"] == 48
assert s["n_missed"] == 0
assert s["work_rate"] == 1.0
assert s["always_one_option"] is True
assert s["pid"] == "PILOT03"
def test_a_missing_file_is_an_error_but_a_truncated_one_is_not(tmp_path):
"""A session cut off mid-write still has every complete record before the
cut, and those are the ones worth reading."""
good = tmp_path / "x.msgpack"
import msgpack
rec = msgpack.packb(dict(name="Harvest1", data=dict(trials=[])))
with open(good, "wb") as f:
f.write(len(rec).to_bytes(4, "big")); f.write(rec)
f.write((999).to_bytes(4, "big")); f.write(b"\x00\x01") # torn tail
assert len(loader.read_records(good)) == 1
with pytest.raises(OSError):
loader.read_records(tmp_path / "nope.msgpack")
def test_build_returns_one_row_per_trial_and_one_per_session(sessions):
trials, sess = loader.build(sessions[:3])
assert len(sess) == 3
assert len(trials) == sum(sess["n_trials"])
assert list(sess["session"]) == sorted(set(sess["session"]), key=list(sess["session"]).index)
# --- the night watch -------------------------------------------------------
# The block was added in October and nothing in the analysis layer knew about
# it: "NightWatch" is in neither BLOCK_NAMES nor NIGHT_NAMES, so a session
# that played 48 watch trials loaded 48 day trials and the rest went nowhere,
# silently, with every column of the block's own design along with them.
def test_the_night_watch_block_is_read(watch_session):
df = loader.trials_frame(watch_session)
watch = df[df["night_watch"].astype(bool)]
assert len(watch) == 48, "the whole block, not the practice nights"
assert set(watch["beneficiary"]) <= {"self", "other", "conflict"}
def test_a_watch_trial_is_not_a_day_trial(watch_session):
"""It carries night=None, so "not a night trial" would count it as one."""
df = loader.trials_frame(watch_session)
assert df["night"].isna().all(), "this session ran no raid blocks"
day = df[loader.day_mask(df)]
assert len(day) == 48
assert not day["night_watch"].astype(bool).any()
s = loader.session_summary(watch_session)
assert s["n_day_trials"] == 48
assert s["n_watch_trials"] == 48
assert s["n_trials"] == 96
def test_the_watch_design_columns_survive(watch_session):
"""Both options pay and what moves is the partner's loss, so a frame
without these columns cannot say what any choice was between."""
df = loader.trials_frame(watch_session)
watch = df[df["night_watch"].astype(bool)]
for col in ["work_credit", "rest_credit", "loss_sleep", "loss_work",
"saved", "info_condition", "endowment"]:
assert watch[col].notna().all(), col
gap = (watch["rest_credit"].astype(float) - watch["work_credit"].astype(float))
# Two properties, and no particular number. What identifies the
# self-weight is that the gap holds still within a session, and the gap
# has to stay under the smallest loss averted or that level is dominated
# and its cell goes quiet. Asserting the number instead failed on the
# first live watch session: the task raised the gap from 1 to 5 on
# 2026-10-21, because at 1 every participant worked every night, and this
# test went on asserting the design it was written against.
assert len(set(gap.unique())) == 1, \
"the self-weight is identified by holding this gap constant"
held = float(gap.iloc[0])
assert 0 < held < float(watch["loss_sleep"].astype(float).min()), \
f"gap {held} is not strictly under the smallest loss averted"
assert (watch["loss_sleep"].astype(float) > watch["loss_work"].astype(float)).all()