Download make_bear_sheet.py from princessamygdala/TreasureHuntForTwo: direct link, hf CLI and curl.
- Browser
- Download file 16 kB
-
https://huggingface.co/spaces/princessamygdala/TreasureHuntForTwo/resolve/main/make_bear_sheet.py
- Command line
-
hf download hf://spaces/princessamygdala/TreasureHuntForTwo/make_bear_sheet.py
-
curl -L -o make_bear_sheet.py https://huggingface.co/spaces/princessamygdala/TreasureHuntForTwo/resolve/main/make_bear_sheet.py
16 kB
| """Write the BEAR link workbook: every pool entry, premade, one row each. | |
| 206 rows, one per entry in randos.pool(): 103 children and their 103 parents, which is | |
| every dyad the parent gap allows. Each row carries its finished link, so recruitment copies | |
| a link instead of building one. | |
| WHY 103 DYADS. The pool is sized to them exactly. Children take ids 1..C and parents take | |
| 1+PARENT_GAP..C+PARENT_GAP, so the two blocks collide as soon as C passes PARENT_GAP: 103 | |
| dyads is the ceiling whatever the pool holds, and POOL_SIZE is 2 * PARENT_GAP, which is | |
| that ceiling written down. There are no spare entries, by design; a larger pool would only | |
| hold ids no dyad can reach. Running more than 103 dyads means raising PARENT_GAP, and the | |
| new value has to stay coprime to 12, 24 and 5 or a parent stops moving off their child on | |
| one of the three rotations. | |
| THE SHEET IS LINKAGE DATA once the bearid column is filled, so it belongs in the study's | |
| admin folder in Box, never in this repository, which is served publicly as a Space. --out | |
| refuses to write anywhere inside the repo. | |
| uv run python make_bear_sheet.py --out "<admin folder>/BEAR_hunt_links.xlsx" | |
| """ | |
| import argparse | |
| import pathlib | |
| import sys | |
| import bear_links | |
| import randos | |
| REPO = pathlib.Path(__file__).resolve().parent | |
| DEFAULT_BASE = "https://princessamygdala-treasurehuntfortwo.hf.space" | |
| #: `session` through `partner_id` are not filled in by hand: update_bear_sheet.py reads | |
| #: them off the summary row of each played session and writes them back, so the sheet | |
| #: says who has finished and what they are owed without anyone retyping a figure. | |
| HEAD = ["dyad", "pid", "who", "rando", "bearid", "link", "sent_on", "done_on", | |
| "session", "trials", "bonus_self", "bonus_stranger", "partner_id", "notes"] | |
| #: The sibling tab. A family with two children in the study is the one case the sheet's | |
| #: one-row-per-dyad shape does not read off directly, and getting it wrong either gives two | |
| #: siblings the same task or asks a parent to play twice. | |
| SIBLINGS = [ | |
| ("A parent with two children in the study", ""), | |
| ("", ""), | |
| ("The rule", "Every CHILD takes the child row of the next free dyad and carries their " | |
| "OWN bearid. The PARENT plays once, on the parent row of their first " | |
| "child's dyad, and that row carries both children's pids and both their " | |
| "bearids. The second dyad's parent row is not used."), | |
| ("", ""), | |
| ("Why", "pid is shared inside a dyad and rando is not. Two siblings therefore need two " | |
| "dyad rows, or they get two identical tasks. Their parent needs one rando, " | |
| "because they sit down once."), | |
| ("", ""), | |
| ("One id per child", "BEAR issues a bearid per child, so a family with two children " | |
| "has two of them and nothing in the bearid column says they are " | |
| "related. The parent's row is what says it: its pid and bearid " | |
| "cells name both children, joined with a semicolon, and that is " | |
| "how the family is put back together."), | |
| ("", ""), | |
| ("Worked example", "Two children, bearid 10001 and 10002, one parent."), | |
| ("", ""), | |
| ] | |
| #: The example table on that tab: (dyad, pid, who, rando, bearid, what to do, notes). | |
| SIBLING_EXAMPLE = [ | |
| ("dyad", "pid", "who", "rando", "bearid", "do", "notes"), | |
| (7, "2007", "c", 7, "10001", "send this link", "older child"), | |
| (7, "2007;2008", "p", 110, "10001;10002", "send this link", | |
| "parent of both; plays once, here. Session runs under pid 2007."), | |
| (8, "2008", "c", 8, "10002", "send this link", "younger child"), | |
| (8, "2008", "p", 111, "10002", "DO NOT SEND", | |
| "not used; this family's parent plays under dyad 7"), | |
| ] | |
| SIBLINGS_AFTER = [ | |
| ("", ""), | |
| ("What you get", "Three sessions. bear/2007/ holds the older child and the parent, " | |
| "told apart by the role column. bear/2008/ holds the younger child " | |
| "alone. The parent's session carries both bearids, so it joins to " | |
| "either child."), | |
| ("", ""), | |
| ("Three children", "Same rule. Three child rows, each with its own bearid, the parent " | |
| "on the first dyad's parent row carrying all three pids and all " | |
| "three bearids, the other two parent rows unused."), | |
| ("", ""), | |
| ("Two parents", "Not this case. Two children with a parent each is two ordinary " | |
| "dyads, nothing special to do."), | |
| ("", ""), | |
| ("The cost", "One pool entry per extra sibling, taken out of the 103. Note it, so the " | |
| "running total of dyads still available is honest."), | |
| ("", ""), | |
| ("Never", ""), | |
| ("", "Never put two children on one pid to keep them together. They would get the " | |
| "identical task, and their data would land in one folder."), | |
| ("", "Never send a parent two links. Two sessions from one person is two sets of " | |
| "learning data from someone who has already played."), | |
| ("", "Never move a rando onto a different row to use up the spare parent entry. The " | |
| "sheet is the record of what was sent; edit it and it stops being one."), | |
| ("", "Never give one bearid to two children. It is their own record id, and two " | |
| "children carrying one means one of them is mislabeled."), | |
| ("", ""), | |
| ("Filling it in", "Use enroll_bear.py --sibling, which writes all of this and rebuilds " | |
| "both links. Doing it by hand drops the bearid out of the URL, and " | |
| "the URL is the only thing that carries it into the data."), | |
| ] | |
| README = [ | |
| ("What this is", ""), | |
| ("", "Every entry in the randomization pool, one row each, with its link already " | |
| "built. Fill in bearid when a family is enrolled; leave the rest alone."), | |
| ("", ""), | |
| ("The three ids", ""), | |
| ("pid", "The session label and its data folder. A child and their parent share one, " | |
| "the way BEAR's own records do. It does not touch the randomization."), | |
| ("rando", "The pool entry. The whole design follows from this number and nothing " | |
| "else, which is what lets a dyad share a pid and still get two designs."), | |
| ("bearid", "BEAR's own record id, one per CHILD. Never parsed, never reaches the " | |
| "design. Two siblings have two different ones, so this column does not " | |
| "group a family; the parent's row does, by naming both children's pids " | |
| "and bearids."), | |
| ("", ""), | |
| ("Siblings", ""), | |
| ("", "A parent with two children in the study has its own tab. Read it before you " | |
| "send anything to that family."), | |
| ("", ""), | |
| ("Running out", ""), | |
| ("", "There are no spare entries. The pool is sized to exactly the 103 dyads the " | |
| "design allows, because a larger one would only hold ids no dyad can reach. If " | |
| "the study needs a 104th dyad, that is a code change (randos.PARENT_GAP), not a " | |
| "row you can add here. Ask before improvising one."), | |
| ("", ""), | |
| ("Never", ""), | |
| ("", "Never give one rando to two people: they get the identical task."), | |
| ("", "Never give one pid to two children: their data lands in one folder."), | |
| ("", "Never edit a link by hand, and never re-run make_bear_sheet.py over a sheet in " | |
| "use: it rebuilds every row blank and throws away every bearid, note and date. " | |
| "Use enroll_bear.py, which edits in place."), | |
| ] | |
| def rows(base): | |
| """(dyad rows, spare entries). Every dyad the parent gap allows.""" | |
| # Parents start at 1 + PARENT_GAP, so the two blocks touch when a child's id reaches | |
| # that. The largest block with no overlap is exactly PARENT_GAP. | |
| n = randos.PARENT_GAP | |
| kids, parents = randos.allocate(n, n) | |
| used, out = set(kids) | set(parents), [] | |
| for i, (ck, pk) in enumerate(zip(kids, parents), start=1): | |
| pid = bear_links.pid_for(i) | |
| out.append(dict(dyad=i, pid=pid, who="c", rando=ck, bearid="", | |
| link=bear_links.link_for(base, pid, "c", ck))) | |
| out.append(dict(dyad=i, pid=pid, who="p", rando=pk, bearid="", | |
| link=bear_links.link_for(base, pid, "p", pk))) | |
| return out, [r for r in randos.pool() if r not in used] | |
| def _check_out(path): | |
| p = pathlib.Path(path).expanduser().resolve() | |
| if REPO in p.parents or p.parent == REPO: | |
| sys.exit(f"refusing to write {p}\n" | |
| f"It maps BEAR subjects to task pids, and this repository is public.\n" | |
| f"Write it to the study's admin folder instead.") | |
| return p | |
| def write(path, base=DEFAULT_BASE): | |
| from openpyxl import Workbook | |
| from openpyxl.styles import Alignment, Font, PatternFill | |
| from openpyxl.utils import get_column_letter | |
| data, spare = rows(base) | |
| wb = Workbook() | |
| ws = wb.active | |
| ws.title = "links" | |
| ws.append(HEAD) | |
| child = PatternFill("solid", fgColor="EAF3FF") | |
| parent = PatternFill("solid", fgColor="FFF4E5") | |
| for r in data: | |
| ws.append([r["dyad"], r["pid"], r["who"], r["rando"], r["bearid"], r["link"], | |
| "", "", ""]) | |
| for c in ws[ws.max_row]: | |
| c.fill = child if r["who"] == "c" else parent | |
| for c in ws[1]: | |
| c.font = Font(bold=True) | |
| ws.freeze_panes = "A2" | |
| ws.auto_filter.ref = f"A1:{get_column_letter(len(HEAD))}{ws.max_row}" | |
| for col, w in zip("ABCDEFGHIJKLMN", | |
| (6, 8, 5, 7, 14, 92, 11, 11, 18, 7, 11, 15, 10, 30)): | |
| ws.column_dimensions[col].width = w | |
| for row in ws.iter_rows(min_row=2, min_col=6, max_col=6): | |
| row[0].alignment = Alignment(shrink_to_fit=False) | |
| sp = wb.create_sheet("spare") | |
| sp.append(["rando", "note"]) | |
| for r in spare: | |
| sp.append([r, "unused; takes a child row and its parent row together"]) | |
| if not spare: | |
| sp.append(["", f"None. The pool is {randos.POOL_SIZE} ids, which is exactly the " | |
| f"{randos.PARENT_GAP} dyads the design allows. A 104th dyad is a " | |
| f"code change, not a row."]) | |
| sp["A1"].font = sp["B1"].font = Font(bold=True) | |
| sp.column_dimensions["A"].width = 8 | |
| sp.column_dimensions["B"].width = 86 | |
| bal = wb.create_sheet("balance") | |
| for line in randos.report(len(data) // 2, len(data) // 2).splitlines(): | |
| bal.append([line]) | |
| bal.append([]) | |
| bal.append([f"pool size {randos.POOL_SIZE}, parent gap {randos.PARENT_GAP}"]) | |
| bal.append([f"base URL {base}"]) | |
| bal.column_dimensions["A"].width = 86 | |
| sb = wb.create_sheet("siblings") | |
| for a, b in SIBLINGS: | |
| sb.append([a, b]) | |
| head = sb.max_row + 1 | |
| for row in SIBLING_EXAMPLE: | |
| sb.append(list(row)) | |
| for row in SIBLINGS_AFTER: | |
| sb.append(list(row)) | |
| for row in sb.iter_rows(min_row=1, max_row=head - 1, max_col=2): | |
| if row[0].value and not row[1].value: | |
| row[0].font = Font(bold=True, size=13) | |
| elif row[0].value: | |
| row[0].font = Font(bold=True) | |
| row[1].alignment = Alignment(wrap_text=True, vertical="top") | |
| for c in sb[head]: | |
| c.font = Font(bold=True) | |
| c.fill = PatternFill("solid", fgColor="E8E8E8") | |
| for i, row in enumerate(sb.iter_rows(min_row=head + 1, | |
| max_row=head + len(SIBLING_EXAMPLE) - 1)): | |
| send = str(row[5].value or "").startswith("send") | |
| for c in row: | |
| c.fill = PatternFill("solid", fgColor="EAF3FF" if send else "FFE5E5") | |
| for row in sb.iter_rows(min_row=head + len(SIBLING_EXAMPLE), max_col=2): | |
| if row[0].value and not row[1].value: | |
| row[0].font = Font(bold=True, size=13) | |
| elif row[0].value: | |
| row[0].font = Font(bold=True) | |
| row[1].alignment = Alignment(wrap_text=True, vertical="top") | |
| for col, w in zip("ABCDEFG", (18, 96, 6, 7, 11, 16, 52)): | |
| sb.column_dimensions[col].width = w | |
| rd = wb.create_sheet("readme") | |
| for a, b in README: | |
| rd.append([a, b]) | |
| for row in rd.iter_rows(): | |
| if row[0].value and not row[1].value: | |
| row[0].font = Font(bold=True) | |
| row[1].alignment = Alignment(wrap_text=True, vertical="top") | |
| rd.column_dimensions["A"].width = 14 | |
| rd.column_dimensions["B"].width = 96 | |
| wb.save(path) | |
| return data, spare | |
| #: The tabs that are documentation rather than data. refresh_docs() rebuilds exactly | |
| #: these, which is how a correction reaches a sheet already in use: the links tab holds | |
| #: every bearid, note and date anyone has entered, and write() would rebuild it blank. | |
| DOC_TABS = ("spare", "balance", "siblings", "readme") | |
| def refresh_docs(path, base=DEFAULT_BASE): | |
| """Replace a sheet's documentation tabs with freshly generated ones. | |
| write() writes the whole workbook, so correcting a word in the readme by re-running it | |
| would rebuild all 206 link rows blank and lose every enrolment. This generates a new | |
| sheet in a temporary file and copies only the tabs that carry no data across, cell by | |
| cell with their formatting, leaving `links` exactly as it was. | |
| """ | |
| import copy | |
| import tempfile | |
| from openpyxl import load_workbook | |
| path = pathlib.Path(path) | |
| live = load_workbook(path) | |
| if "links" not in live.sheetnames: | |
| sys.exit(f"{path} has no links tab; this is not a BEAR link sheet") | |
| with tempfile.TemporaryDirectory() as tmp: | |
| fresh_path = pathlib.Path(tmp) / "fresh.xlsx" | |
| write(fresh_path, base) | |
| fresh = load_workbook(fresh_path) | |
| for name in DOC_TABS: | |
| if name in live.sheetnames: | |
| del live[name] | |
| src = fresh[name] | |
| dst = live.create_sheet(name) | |
| for row in src.iter_rows(): | |
| for c in row: | |
| d = dst.cell(row=c.row, column=c.column, value=c.value) | |
| if c.has_style: | |
| d.font = copy.copy(c.font) | |
| d.fill = copy.copy(c.fill) | |
| d.alignment = copy.copy(c.alignment) | |
| for letter, dim in src.column_dimensions.items(): | |
| dst.column_dimensions[letter].width = dim.width | |
| live.save(path) | |
| return DOC_TABS | |
| def main(argv=None): | |
| ap = argparse.ArgumentParser(description=__doc__, | |
| formatter_class=argparse.RawDescriptionHelpFormatter) | |
| ap.add_argument("--out", required=True) | |
| ap.add_argument("--base", default=DEFAULT_BASE) | |
| ap.add_argument("--refresh-docs", action="store_true", | |
| help="rebuild only the spare, balance, siblings and readme tabs of an " | |
| "existing sheet. Use this to correct the documentation without " | |
| "touching the links tab, which holds every enrolment.") | |
| a = ap.parse_args(argv) | |
| if not a.base.startswith("https://"): | |
| sys.exit(f"--base must be an https:// URL, got {a.base!r}") | |
| out = _check_out(a.out) | |
| if a.refresh_docs: | |
| if not out.exists(): | |
| sys.exit(f"{out} does not exist; drop --refresh-docs to create it") | |
| stamp = __import__("datetime").datetime.now().strftime("%Y%m%d-%H%M%S") | |
| backup = out.with_name(f"{out.stem}.{stamp}.bak{out.suffix}") | |
| __import__("shutil").copy2(out, backup) | |
| tabs = refresh_docs(out, a.base) | |
| print(f"rebuilt {', '.join(tabs)} in {out}") | |
| print(f"backup {backup.name}; the links tab was not touched") | |
| return | |
| out.parent.mkdir(parents=True, exist_ok=True) | |
| data, spare = write(out, a.base) | |
| print(f"wrote {out}") | |
| print(f" {len(data)} links: {len(data) // 2} dyads, children and parents") | |
| print(f" {len(spare)} spare pool entries: {spare}") | |
| print(f" {len(data) + len(spare)} rows against a pool of {randos.POOL_SIZE}") | |
| print() | |
| print(randos.report(len(data) // 2, len(data) // 2)) | |
| if __name__ == "__main__": | |
| main() | |