Spaces:
Running
Running
Download docs/methods/make_methods.py from princessamygdala/HarvestForTwo: direct link, hf CLI and curl.
- Browser
- Download file 23.9 kB
-
https://huggingface.co/spaces/princessamygdala/HarvestForTwo/resolve/main/docs/methods/make_methods.py
- Command line
-
hf download hf://spaces/princessamygdala/HarvestForTwo/docs/methods/make_methods.py
-
curl -L -o make_methods.py https://huggingface.co/spaces/princessamygdala/HarvestForTwo/resolve/main/docs/methods/make_methods.py
23.9 kB
| """Generate the method and design-decisions document. | |
| Kept as a generator, with the figures beside it, so the document can be | |
| rebuilt from the repository. The .docx itself is gitignored: it is output, | |
| and HuggingFace rejects binary documents in the deployed Space. | |
| python docs/methods/make_methods.py | |
| """ | |
| import json | |
| import os | |
| from docx import Document | |
| from docx.enum.text import WD_ALIGN_PARAGRAPH | |
| from docx.shared import Inches, Pt, RGBColor | |
| HERE = os.path.dirname(os.path.abspath(__file__)) | |
| REPO = os.path.dirname(os.path.dirname(HERE)) | |
| BLACK = RGBColor(0, 0, 0) | |
| GREY = RGBColor(0x55, 0x55, 0x55) | |
| doc = Document() | |
| for name in ("Normal", "List Bullet", "List Bullet 2"): | |
| try: | |
| st = doc.styles[name] | |
| except KeyError: | |
| continue | |
| st.font.name, st.font.size, st.font.color.rgb = "Arial", Pt(11), BLACK | |
| for s in doc.sections: | |
| s.top_margin = s.bottom_margin = Inches(0.9) | |
| s.left_margin = s.right_margin = Inches(0.9) | |
| def _run(p, text, *, bold=False, italic=False, size=11, color=BLACK, mono=False): | |
| r = p.add_run(text) | |
| r.font.name = "Consolas" if mono else "Arial" | |
| r.font.size, r.font.bold, r.font.italic = Pt(size), bold, italic | |
| r.font.color.rgb = color | |
| return r | |
| def title(text): | |
| p = doc.add_paragraph(); p.space_after = Pt(4) | |
| _run(p, text, bold=True, size=15) | |
| def subtitle(text): | |
| p = doc.add_paragraph(); p.space_after = Pt(12) | |
| _run(p, text, size=10, color=GREY) | |
| def h(text): | |
| p = doc.add_paragraph(); p.space_before, p.space_after = Pt(13), Pt(4) | |
| _run(p, text, bold=True, size=12) | |
| def h2(text): | |
| p = doc.add_paragraph(); p.space_before, p.space_after = Pt(9), Pt(3) | |
| _run(p, text, bold=True, italic=True) | |
| def bullet(parts, level=0): | |
| """parts: a string, or a list of (text, style) where style is '', 'b', 'i', 'm'.""" | |
| p = doc.add_paragraph(style="List Bullet" if level == 0 else "List Bullet 2") | |
| p.space_after = Pt(2) | |
| for text, style in ([(parts, "")] if isinstance(parts, str) else parts): | |
| _run(p, text, bold="b" in style, italic="i" in style, mono="m" in style) | |
| def eq(text): | |
| """A display formula, monospaced and indented.""" | |
| p = doc.add_paragraph(); p.space_before, p.space_after = Pt(4), Pt(4) | |
| p.paragraph_format.left_indent = Inches(0.35) | |
| _run(p, text, mono=True, size=10.5) | |
| def note(text): | |
| p = doc.add_paragraph(); p.space_after = Pt(6) | |
| _run(p, text, size=9.5, color=GREY, italic=True) | |
| def figure(path, caption, width=6.2): | |
| doc.add_picture(path, width=Inches(width)) | |
| doc.paragraphs[-1].alignment = WD_ALIGN_PARAGRAPH.CENTER | |
| p = doc.add_paragraph(); p.space_after = Pt(8) | |
| p.alignment = WD_ALIGN_PARAGRAPH.CENTER | |
| _run(p, caption, size=9, color=GREY, italic=True) | |
| def table(headers, rows, widths=None): | |
| t = doc.add_table(rows=1, cols=len(headers)) | |
| t.style = "Table Grid" | |
| for i, cell in enumerate(t.rows[0].cells): | |
| cell.text = "" | |
| _run(cell.paragraphs[0], headers[i], bold=True, size=10) | |
| for row in rows: | |
| cells = t.add_row().cells | |
| for i, val in enumerate(row): | |
| cells[i].text = "" | |
| mono = isinstance(val, str) and val.startswith("`") | |
| _run(cells[i].paragraphs[0], val.strip("`"), size=10, mono=mono) | |
| doc.add_paragraph().space_after = Pt(6) | |
| return t | |
| # ============================================================ title | |
| title("Prosocial Effort Task (Harvest for Two)") | |
| subtitle("Method, design decisions, and the calculations behind them. " | |
| "Version of 23 September 2026. Values are those currently implemented.") | |
| # ============================================================ model overview | |
| h("1. Model and parameters at a glance") | |
| bullet("Every block is a binary choice fitted with the same softmax. Subjective " | |
| "value drives the probability of choosing an option, and beta sets how " | |
| "sharply.") | |
| eq("P(option) = sigma( beta * (V_option - V_alternative) )") | |
| bullet([("Effort ", ""), ("E", "bi"), | |
| (" is always the required work as a fraction of that participant's own " | |
| "calibrated reference, so it runs 0.35 to 0.80 and means the same thing " | |
| "for a fast and a slow participant. Rewards are in credits.", "")]) | |
| h2("The three models") | |
| eq("day task V_work = R - k_agent * E^2 V_rest = 2") | |
| eq("Night 1 V_raid = g - h*l - k * E^2 V_sleep = 2") | |
| eq("Night 2 V_self - V_partner = a - w*b + dk * E^2") | |
| table( | |
| ["parameter", "block", "meaning", "rises when"], | |
| [["`k_self`", "day", "how steeply effort devalues a reward for oneself", | |
| "the participant rests more on SELF trials"], | |
| ["`k_other`", "day", "the same when the partner is paid", | |
| "the participant rests more on OTHER trials"], | |
| ["`gap`", "day", "k_other minus k_self, obtained by subtraction, not fitted", | |
| "effort is spent less readily for the partner"], | |
| ["`h`", "Night 1", "harm aversion: how far a credit taken off the partner " | |
| "cancels one gained", "the participant avoids costly raids"], | |
| ["`w`", "Night 2", "social weight: what a credit in the partner's pocket is " | |
| "worth relative to one in their own", "the participant leaves more behind"], | |
| ["`dk`", "Night 2", "k_other minus k_self, fitted directly here", | |
| "effort feels costlier when it benefits the partner"], | |
| ["`beta`", "all", "choice consistency", "choices track value more closely"]]) | |
| note("Night 2 gives identical effort to both options, so the two effort terms " | |
| "cancel and only their difference survives. It can never estimate k_self " | |
| "and k_other separately.") | |
| bullet([("Model comparison crosses one against two ", ""), ("k", "bi"), | |
| (", one against two ", ""), ("beta", "bi"), | |
| (", and a parabolic against a linear exponent, giving eight models for " | |
| "the day task. The single-", ""), ("k", "bi"), | |
| (" models are the null: if one of them wins, the design did not detect " | |
| "prosocial discounting at all.", "")]) | |
| bullet("Fitting is hierarchical expectation maximization, via pyEM (Rhoads). " | |
| "The model follows Lockwood et al. (2017, 2021) and the implementation in " | |
| "Cutler's mod_ms_all.m.") | |
| # ============================================================ structure | |
| h("2. Trial structure") | |
| table(["block", "trials", "composition"], | |
| [["day task", "48", "2 beneficiaries x 4 effort x 3 reward = 24 conditions, each twice, " | |
| "split across two blocks with a break"], | |
| ["Night 1", "24", "4 effort x 6 gain-loss pairs"], | |
| ["Night 2", "24", "4 effort x 6 reward pairs"]]) | |
| bullet("Beneficiary is interleaved within blocks rather than blocked, following " | |
| "the original Qualtrics implementation.") | |
| bullet("The two night blocks are optional and activated by a link parameter. " | |
| "Without it the task runs as the two standard blocks only.") | |
| # ============================================================ effort levels | |
| h("3. Effort levels: why 35/50/65/80 and not 50/65/80/95") | |
| bullet([("The levels are a fraction of the participant's calibrated reference. " | |
| "Rounding 95% of that reference returns the reference itself for any " | |
| "value at or below 10, because ", ""), | |
| ("round(m * 0.95) = m", "m"), | |
| (" whenever ", ""), ("m <= 10", "m"), (".", "")]) | |
| bullet("The hardest level therefore asked for the participant's best recorded " | |
| "count in all eight pilot sessions examined, not 95% of it.") | |
| figure(os.path.join(HERE, "fig_levels.png"), | |
| "Left: the old levels. The hardest level (purple) sits on the reference " | |
| "line up to a reference of 10, so it asks for 100% rather than 95%. " | |
| "Right: the current levels, clear of the reference at every value.") | |
| table(["reference", "old levels", "hardest = reference?", "new levels", "distinct"], | |
| [["4", "`2, 3, 3, 4`", "yes", "`1, 1, 2, 3`", "3 of 4"], | |
| ["6", "`3, 4, 5, 6`", "yes", "`2, 3, 4, 5`", "4 of 4"], | |
| ["8", "`4, 5, 6, 8`", "yes", "`3, 4, 5, 6`", "4 of 4"], | |
| ["10", "`5, 6, 8, 10`", "yes", "`4, 5, 6, 8`", "4 of 4"], | |
| ["12", "`6, 8, 10, 11`", "no", "`4, 6, 8, 10`", "4 of 4"]]) | |
| bullet("Levels are now forced strictly below the reference and forced distinct " | |
| "wherever the arithmetic allows.") | |
| bullet([("Observed success at the hardest level was ", ""), ("42.6%", "b"), | |
| (", against approximately 96% in comparable published tasks (EEfRT; " | |
| "Klein-Flugge et al., 2015, who treat that rate as evidence that their " | |
| "calibration was adequate).", "")]) | |
| bullet([("Because the harvest is all or nothing, failure risk removed part of " | |
| "the expected reward and the model absorbed it into ", ""), ("k", "bi"), | |
| (". The value equation assumes the reward is certain once the option is " | |
| "chosen, so some of ", ""), ("k", "bi"), | |
| (" was probability discounting rather than effort aversion.", "")]) | |
| bullet([("Predicted success after the revision is ", ""), ("87%", "b"), | |
| (" at the hardest level and ", ""), ("95%", "b"), | |
| (" across all four. The ratio of hardest to easiest work widens from " | |
| "2.0 to 2.5.", "")]) | |
| bullet("Four distinct levels require a reference of 5 or more. The floor is 4, " | |
| "where two levels coincide and the design drops to three. This affected " | |
| "one pilot participant and remains open.") | |
| # ============================================================ mean vs max | |
| h("4. Calibration: why the mean of two attempts and not the better one") | |
| bullet("Participants complete two timed warm-up attempts. The reference is their " | |
| "mean, not their maximum.") | |
| bullet("A harvest rate varies by roughly 18% from attempt to attempt. The better " | |
| "of two draws from that distribution is the upper end of the variation, " | |
| "which is a personal record rather than a reproducible capability.") | |
| figure(os.path.join(HERE, "fig_meanmax.png"), | |
| "Simulated: true capability 10 stalks, 18% between-attempt variation, " | |
| "120,000 participants. Taking the better attempt is biased upward by 10% " | |
| "and is also the noisier of the two estimators.") | |
| table(["estimator", "mean estimate", "bias", "sd"], | |
| [["better of the two", "11.02", "+1.02 (+10%)", "1.49"], | |
| ["mean of the two", "10.00", "0.00", "1.27"]]) | |
| bullet("The two errors compound. Setting the hardest level at 95% of an estimate " | |
| "that is already 10% too high asks for 105% of true capability, which is " | |
| "unachievable by construction.") | |
| eq("0.95 * 11.02 = 10.47 = 105% of true capability (old)\n" | |
| "0.80 * 10.00 = 8.00 = 80% of true capability (current)") | |
| bullet("Grip-force tasks can take a maximum because maximum voluntary contraction " | |
| "is reproducible. A peak rate in a timed task is not.") | |
| note("The recorded field keeps the name max_boxes for continuity with earlier " | |
| "data but holds a mean. It must not be compared with a maximum voluntary " | |
| "contraction value from the grip-force literature.") | |
| # ============================================================ yoking | |
| h("5. Yoking, and why Night 1 crosses gain against loss") | |
| bullet([("Night 1 pays the participant ", ""), ("g", "bi"), | |
| (" for a raid and costs the sleeping partner ", ""), ("l", "bi"), | |
| (". The fit has to separate three regressors.", "")]) | |
| eq("V_raid = g - h*l - k*E^2 regressors: g, -l, -E^2") | |
| h2("What yoking would mean") | |
| bullet([("Yoking means tying the partner's loss to the participant's gain, so " | |
| "that taking 6 credits always costs the partner 6. Then ", ""), | |
| ("l = g", "m"), (" and the value equation collapses:", "")]) | |
| eq("V_raid = g - h*g - k*E^2 = g*(1 - h) - k*E^2") | |
| bullet([("The two columns become the same column. Only the product ", ""), | |
| ("(1 - h)", "m"), | |
| (" is identifiable, never ", ""), ("h", "bi"), | |
| (" on its own, so harm aversion cannot be told apart from simply valuing " | |
| "credits less. No sample size fixes this: it is a property of the design " | |
| "matrix, not of the data.", "")]) | |
| figure(os.path.join(HERE, "fig_yoking.png"), | |
| "The shipped design crosses gain against loss in a 3 by 2 factorial, " | |
| "correlation 0.00, and the design matrix has full rank. Yoked, the points " | |
| "fall on a diagonal, the matrix loses a rank and its condition number " | |
| "rises by fourteen orders of magnitude.") | |
| table(["design", "corr(gain, loss)", "rank", "condition number", "h identifiable"], | |
| [["crossed, as shipped", "0.00", "3 of 3", "41.8", "yes"], | |
| ["yoked", "-1.00", "2 of 3", "5.9 x 10^15", "no"]]) | |
| bullet("The same reasoning explains Night 2. Its two options require identical " | |
| "effort, which is deliberate, and the consequence is that the two effort " | |
| "terms cancel and only their difference is estimable.") | |
| eq("V_self - V_partner = a - w*b - (k_self - k_other)*E^2\n" | |
| " = a - w*b + dk*E^2 , dk = k_other - k_self") | |
| bullet("As shipped, Night 2's reward pairs sum to 12 on every trial, so the two " | |
| "amounts correlate -1. Simulation shows decoupling them does not improve " | |
| "recovery of the social weight (0.78 against 0.79), so the coupling is " | |
| "retained, but it is a choice rather than an oversight.") | |
| # ============================================================ rewards, timing | |
| h("6. Rewards, rest, and timing") | |
| table(["option", "credits", "value"], | |
| [["rest", "2", "$0.08"], ["work, low", "3", "$0.12"], | |
| ["work, mid", "6", "$0.24"], ["work, high", "10", "$0.40"]]) | |
| bullet([("One credit is ", ""), ("$0.04", "b"), | |
| (" (points divided by 25), capped at $6.00 per recipient. Full effort " | |
| "reaches the cap at 150 of a possible 152 credits, so the advertised " | |
| "maximum is attainable. The previous divisor placed the maximum " | |
| "attainable bonus at $0.14.", "")]) | |
| bullet("Rest moved from 1 credit to 2. The smallest trade-off is unchanged at one " | |
| "credit either way, while the 6- and 10-credit offers come off the " | |
| "ceiling, where choice probability had been 0.92 and 1.00.") | |
| bullet("The decision phase is untimed. In pilot data 18% of decisions took longer " | |
| "than the 4 second window used in the Qualtrics version, and a deadline " | |
| "would have discarded them.") | |
| bullet("The work window is 10 seconds, unchanged. Resting also lasts 10 seconds, " | |
| "so the two options differ in effort and never in time.") | |
| bullet("Presses of the same key closer than 50 ms apart are rejected. One pilot " | |
| "session logged 3008 key events in a single trial at a median gap of 0 ms " | |
| "and reached 100% success by flooding, which turns a trial from a measure " | |
| "of willingness to work into a measure of input rate. A human's fastest " | |
| "deliberate repeat is around 90 ms. Rejected presses are counted and " | |
| "exported rather than silently dropped.") | |
| # ============================================================ randomization | |
| h("7. Randomization and reproducibility") | |
| bullet("Everything below is a deterministic function of the participant " | |
| "identifier. A reload, a refresh, a browser crash or a server restart " | |
| "returns the same session. Nothing is drawn from a shared pool, so two " | |
| "participants arriving at once cannot collide, and anyone who withdraws " | |
| "consumes nothing.") | |
| eq("seed = crc32(\"pe|\" + participant_id) e.g. 0001 -> 1338488714") | |
| bullet([("This replaced Python's ", ""), ("hash()", "m"), | |
| (", which is salted per process. The same identifier produced a " | |
| "different trial order on every server restart, and a restart during " | |
| "a session reshuffled the remaining blocks. The regression test spawns " | |
| "fresh interpreters, because nothing running inside one process can " | |
| "detect it.", "")]) | |
| h2("What is randomized, and from what") | |
| table(["what", "varies by", "source"], | |
| [["arm: which night blocks, and their order", "participant", | |
| "pre-registered allocation table"], | |
| ["trial order within each block", "participant", "seed"], | |
| ["which side shows the work option", "trial", "seed"], | |
| ["positions of the stalks", "trial", "seed"], | |
| ["items in the rest scene", "presentation position", "seed"], | |
| ["the partner's displayed identifier", "participant", "seed"], | |
| ["group: control or CU", "recruited, not randomized", "first digit of the id"]]) | |
| bullet("The allocation table covers 250 participants, 125 per group, with the " | |
| "arms balanced inside each group so the night manipulation stays " | |
| "orthogonal to the clinical comparison. It is generated and inspected " | |
| "before collection rather than sampled per arrival: a seed gives random " | |
| "assignment, a table gives balanced assignment.") | |
| bullet("Participants who bring their own identifier, as on a recruitment " | |
| "platform, are not in that table. Their arm is derived from a hash of " | |
| "the identifier instead, so it is still stable across restarts, but " | |
| "balance is approximate rather than exact.") | |
| bullet("Order of the two night blocks is counterbalanced. Presenting one first " | |
| "for everyone would confound any difference between them with fatigue " | |
| "and practice. Both orderings are built and the unused one skipped, " | |
| "because the stage list is fixed before any participant arrives.") | |
| bullet("Which side shows the work option is randomized per trial and the " | |
| "instructions say so. Pilot data gives a choice rate of 0.67 with the " | |
| "work option on the left against 0.57 on the right, which is not " | |
| "significant across nine sessions but is the size of bias that fixing " | |
| "the side would write into the main outcome. Randomizing turns a side " | |
| "preference into noise.") | |
| bullet("Rest-scene items are assigned by presentation position rather than by " | |
| "trial condition. Presentation order is already randomized against " | |
| "condition, so which items appear is decorrelated from beneficiary, " | |
| "effort and reward by construction. The model assumes the value of " | |
| "resting is constant; this makes any wobble noise rather than bias, and " | |
| "the items are recorded so the assumption can be checked.") | |
| bullet("Every randomized quantity is written to the trial record: the seed, " | |
| "the arm, the night order, and per trial the presentation position, the " | |
| "side shown and the rest items. A session can be reconstructed from the " | |
| "exported file without re-running the task.") | |
| h("8. Parameter and model recovery") | |
| bullet("Recovery was assessed on simulated data, where the generating values are " | |
| "known, so the results describe the design rather than any participant.") | |
| bullet("Discount rates were drawn from 6 to 18, from the indifference points " | |
| "implied by the published design. Inverse temperature was drawn from 0.7 " | |
| "to 2.2, matched to the choice determinism in Cutler's simulation code on " | |
| "the product of temperature and value difference, since the two value " | |
| "scales differ.") | |
| th = json.load(open(os.path.join(REPO, "analysis/trials_needed.json"))) | |
| SHIP = {"day task (SELF/OTHER)": 48, "night 1 (raid)": 24, "night 2 (whose pocket)": 24} | |
| rows = [] | |
| for label, per_n in th["results"].items(): | |
| ship = SHIP[label] | |
| for param in per_n[str(ship)]: | |
| t = th["threshold"].get(f"{label}::{param}") | |
| rows.append([label.split(" (")[0], f"`{param}`", | |
| f"{per_n[str(ship)][param]:+.2f}", | |
| (str(t) if t else "not by 150"), | |
| "yes" if (t and t <= ship) else "no"]) | |
| table(["block", "parameter", "r at shipped trials", "trials for r >= 0.7", | |
| "clears as shipped"], rows) | |
| bullet("The quantities the task exists to measure clear the threshold at the " | |
| "trial counts already in use: both discount rates, harm aversion in " | |
| "Night 1, and the social weight in Night 2.") | |
| bullet([("The self/other difference does not. It recovers at +0.60 over 48 " | |
| "trials and needs roughly 96. The two rates correlate at about 0.92 " | |
| "across participants, so their difference carries less " | |
| "between-participant variance than either component while the two " | |
| "measurement errors combine. Classical test theory gives the " | |
| "reliability of a difference score as", "")]) | |
| eq("rho_D = (s1^2*r11 + s2^2*r22 - 2*s1*s2*r12) / (s1^2 + s2^2 - 2*s1*s2*r12)") | |
| bullet("At r12 = 0.92 and component reliabilities of 0.90, that expression is " | |
| "approximately zero. At r12 = 0.50 it is 0.80. The cost is the " | |
| "correlation between the components, not the design.") | |
| bullet("Published analyses of this paradigm never use a per-participant " | |
| "difference score. Lockwood et al. compare the two estimated rates with a " | |
| "paired nonparametric test and model trial-level choices with a " | |
| "mixed-effects model carrying effort and reward as separate predictors, " | |
| "reading the self versus other contrast from the interaction with " | |
| "beneficiary. Neither requires a reliable difference per person.") | |
| bullet("Model recovery over 48 trials identifies the generating model in 6 of 8 " | |
| "cases. Both failures concern the number of inverse temperature " | |
| "parameters; the number of discount rates is never misidentified.") | |
| bullet("As a check on the procedure, the same harness reproduces the recovery " | |
| "values reported by Lockwood et al. (2021) for their 150 trial schedule " | |
| "(0.93, 0.93 and 0.77 for self k, other k and beta; this harness gives " | |
| "0.92, 0.94 and 0.86).") | |
| note("Full output: analysis/recovery.ipynb for parameter and model recovery in " | |
| "all three blocks, and analysis/trials_needed.ipynb for recovery against " | |
| "trial count from 24 to 150.") | |
| # ============================================================ open | |
| h("9. Decisions still open") | |
| bullet("Whether the identifier used to grant course credit may be stored " | |
| "alongside responses, given the wording of the consent form.") | |
| bullet("The mechanism for paying the performance bonus, since the recruitment " | |
| "system grants course credit and does not disburse money.") | |
| bullet("The credit to currency rate, which differs between the task, the consent " | |
| "form and a separate implementation.") | |
| bullet("Whether to raise the calibration floor from 4 to 5, so that four " | |
| "distinct effort levels are always available.") | |
| bullet("The warm-up and the main task do not demand comparable work per unit " | |
| "harvested, and this is not yet addressed. The warm-up places 28 stalks " | |
| "on the grid; a main-task trial places between 3 and 10. Walking " | |
| "greedily to the nearest, that is about 1.8 steps per stalk in the " | |
| "warm-up against 4.1 to 6.4 in the task, so the same count costs " | |
| "roughly twice the presses. An effort level set at 80 percent of the " | |
| "warm-up count therefore demands closer to 160 percent of the warm-up " | |
| "effort, which is a better explanation of the observed success rates " | |
| "than the levels being too high. It also compresses the manipulation, " | |
| "since the multiplier is larger at low counts than at high ones. Until " | |
| "it is resolved, E is a fraction of a count collected under different " | |
| "conditions rather than a fraction of capability.") | |
| bullet("Walking distance varies within an effort level because stalk positions " | |
| "are random within the seeded layout. Movement is about 68% of key " | |
| "presses, so this is a real effort dimension. It is recorded but not " | |
| "controlled.") | |
| out = os.path.join(REPO, "ProsocialEffortTask_Method_and_Decisions.docx") | |
| doc.save(out) | |
| print("wrote", out) | |