Add divdata build scripts (build_divdata.py, build_trajectories.py); document consolidated dataset; replace absolute paths with $RUNS_DIR / OASIS_ROOT / SEED_DB env vars
327edac verified Download data/build_divdata.py from anonymousfileupload/divsim-code: direct link, hf CLI and curl.
- Browser
- Download file 10.4 kB
-
https://huggingface.co/datasets/anonymousfileupload/divsim-code/resolve/main/data/build_divdata.py
- Command line
-
hf download hf://datasets/anonymousfileupload/divsim-code/data/build_divdata.py
-
curl -L -o build_divdata.py https://huggingface.co/datasets/anonymousfileupload/divsim-code/resolve/main/data/build_divdata.py
10.4 kB
| """Consolidate every OASIS run into one Parquet dataset indexed by run_id and step. | |
| Each simulation currently lives as <run>.db + <run>.metadata.json + <run>_chats.jsonl. | |
| Step is NOT stored in the database; it lives only in the chat sidecar, one row per agent | |
| activation. Validated on every run: the agent's k-th status='ok' activation corresponds to | |
| its k-th action in `trace` ordered by time, so step is recovered EXACTLY (not inferred). | |
| Runs where that alignment fails are still emitted, with step = NULL and a flag, rather than | |
| silently guessed. | |
| Impressions are normalised. In the raw databases each `trace.refresh` event embeds the full | |
| text of all 20 slate posts, which is ~48% of every file (17.9 MB of a 37.6 MB run). Here an | |
| impression is just (run_id, step, viewer_agent_id, post_id); post text is stored once in | |
| `posts`. That is a ~150x reduction on the largest table. | |
| Tables written (one Parquet file each): | |
| runs run_id, experiment_type, model_default, n_agents, n_initial, steps, join_step, | |
| created_at, source_path, step_alignment_ok, step_coverage | |
| agents run_id, agent_id, user_id, model, persona, join_step | |
| posts run_id, post_id, agent_id, model, step, created_at, content | |
| comments run_id, comment_id, post_id, agent_id, model, step, created_at, content, | |
| is_cross_model | |
| impressions run_id, step, viewer_agent_id, post_id, slot (0-based position in the 20-slot slate) | |
| actions run_id, agent_id, step, action, created_at | |
| """ | |
| import sqlite3, glob, os, re, json, argparse, collections | |
| import pandas as pd | |
| ROOT = os.environ.get("OASIS_ROOT", ".") # directory holding runs/ (and attractor_rl/eval_runs*/) | |
| def agent_models(meta_path): | |
| try: | |
| j = json.load(open(meta_path)) | |
| except Exception: | |
| return None, {} | |
| am = j.get("agent_model_map") or {} | |
| out = {} | |
| for k, v in am.items(): | |
| try: k = int(k) | |
| except Exception: pass | |
| if isinstance(v, dict): | |
| out[k] = (v.get("model", "").split("/")[-1], v.get("join_step")) | |
| else: | |
| out[k] = (str(v).split("/")[-1], None) | |
| return j, out | |
| def steps_for(db, u2a): | |
| """Two per-agent step sequences from the chat sidecar, in file order: | |
| ok -- steps of status='ok' activations (incl. step 0). The k-th one is the | |
| agent's k-th ACTION (post or comment) in time order. | |
| ref -- steps of every activation with step > 0, any status. The k-th one is the | |
| agent's k-th `refresh` row in trace: exhausted activations still refresh, | |
| and the step-0 intro post is written without a refresh. | |
| Returns (ok, ref) or None if there is no sidecar.""" | |
| ch = db.replace(".db", "_chats.jsonl") | |
| if not os.path.exists(ch): | |
| return None | |
| ok = collections.defaultdict(list); ref = collections.defaultdict(list) | |
| try: | |
| for line in open(ch): | |
| try: d = json.loads(line) | |
| except Exception: continue | |
| ag = d.get("agent_id"); st = d.get("step") | |
| if d.get("status") == "ok": | |
| ok[ag].append(st) | |
| try: | |
| if int(st) > 0: ref[ag].append(st) | |
| except Exception: | |
| pass | |
| except Exception: | |
| return None | |
| return ok, ref | |
| def main(): | |
| ap = argparse.ArgumentParser() | |
| ap.add_argument("--out", default="divdata") | |
| ap.add_argument("--limit", type=int, default=0) | |
| a = ap.parse_args() | |
| os.makedirs(a.out, exist_ok=True) | |
| dbs = sorted(glob.glob(os.path.join(ROOT, "runs/**/*.db"), recursive=True)) + \ | |
| sorted(glob.glob(os.path.join(ROOT, "attractor_rl/eval_runs*/**/*.db"), recursive=True)) | |
| if a.limit: dbs = dbs[:a.limit] | |
| R, A, P, C, I, X = [], [], [], [], [], [] | |
| aligned = misaligned = skipped = 0 | |
| for idx, db in enumerate(dbs): | |
| if os.path.exists(db.replace(".db", "_checkpoint.json")): skipped += 1; continue | |
| meta_p = db.replace(".db", ".metadata.json") | |
| if not os.path.exists(meta_p): skipped += 1; continue | |
| meta, am = agent_models(meta_p) | |
| if not am: skipped += 1; continue | |
| run_id = os.path.relpath(db, ROOT)[:-3].replace("/", "__") | |
| try: | |
| c = sqlite3.connect(db) | |
| users = list(c.execute("SELECT user_id, agent_id, user_name FROM user")) | |
| u2a = {u: ag for u, ag, _ in users} | |
| a2u = {ag: u for u, ag, _ in users} | |
| persona = {ag: nm for _, ag, nm in users} | |
| _sq = steps_for(db, u2a) | |
| seq, rseq = (_sq if _sq else (None, None)) | |
| trace = list(c.execute( | |
| "SELECT user_id, action, created_at FROM trace " | |
| "WHERE action IN ('create_post','create_comment') ORDER BY created_at, rowid")) | |
| per_agent_actions = collections.defaultdict(list) | |
| for uid, act, ts in trace: | |
| ag = u2a.get(uid) | |
| if ag is not None: per_agent_actions[ag].append((act, ts)) | |
| # PER-AGENT alignment. An agent's k-th successful activation is its k-th | |
| # action in time order, so when the two counts agree the step is EXACT. A | |
| # single stray action (seen in ~half the older sweeps: one agent off by one, | |
| # e.g. 380 activations vs 379 actions) must not discard the other 19 agents, | |
| # so alignment is decided per agent and unalignable agents get step = NULL. | |
| step_of = {} | |
| n_ok = n_tot = 0 | |
| for ag, acts in per_agent_actions.items(): | |
| s_ag = (seq or {}).get(ag, []) | |
| n_tot += len(acts) | |
| if len(s_ag) == len(acts): | |
| n_ok += len(acts) | |
| for i, _ in enumerate(acts): | |
| step_of[(ag, i)] = s_ag[i] | |
| ok = n_tot > 0 and n_ok == n_tot | |
| aligned += ok; misaligned += (not ok) | |
| cover = (n_ok / n_tot) if n_tot else 0.0 | |
| for ag, (model, js) in am.items(): | |
| A.append(dict(run_id=run_id, agent_id=ag, user_id=a2u.get(ag), | |
| model=model, persona=persona.get(ag), join_step=js)) | |
| # Posts and comments are merged into ONE time-ordered stream per agent before | |
| # indexing. (An earlier version indexed all posts, then all comments, which | |
| # mis-assigned step for every agent that had both -- see BUILD_LOG.) | |
| events = [("post", pid, None, uid, ts, content) for pid, uid, ts, content in c.execute( | |
| "SELECT post_id, user_id, created_at, content FROM post")] + \ | |
| [("comment", cid, pid, uid, ts, content) for cid, pid, uid, ts, content in c.execute( | |
| "SELECT comment_id, post_id, user_id, created_at, content FROM comment")] | |
| events.sort(key=lambda e: (e[4], e[1])) | |
| seen = collections.Counter() | |
| owner, ownmodel = {}, {} | |
| for kind, _id, pid, uid, ts, content in events: | |
| ag = u2a.get(uid); m = am.get(ag, ("", None))[0] if ag is not None else None | |
| st = step_of.get((ag, seen[ag])) | |
| seen[ag] += 1 | |
| if kind == "post": | |
| owner[_id] = ag; ownmodel[_id] = m | |
| P.append(dict(run_id=run_id, post_id=_id, agent_id=ag, model=m, | |
| step=st, created_at=ts, content=content)) | |
| else: | |
| om = ownmodel.get(pid) | |
| C.append(dict(run_id=run_id, comment_id=_id, post_id=pid, agent_id=ag, model=m, | |
| step=st, created_at=ts, content=content, | |
| is_cross_model=(bool(om and m and om != m) if om and m else None))) | |
| # impressions: normalised out of trace.refresh | |
| ref = list(c.execute("SELECT user_id, created_at, info FROM trace WHERE action='refresh' ORDER BY created_at, rowid")) | |
| nref = collections.Counter(u2a.get(uid) for uid, _, _ in ref) | |
| rseen = collections.Counter() | |
| for uid, ts, info in ref: | |
| ag = u2a.get(uid) | |
| try: d = json.loads(info) | |
| except Exception: continue | |
| st = None | |
| r_ag = (rseq or {}).get(ag, []) | |
| k = rseen[ag] | |
| if len(r_ag) == nref[ag] and k < len(r_ag): st = r_ag[k] | |
| rseen[ag] += 1 | |
| for slot, p in enumerate(d.get("posts", []) or []): | |
| pid = p.get("post_id") | |
| if pid is not None: | |
| I.append(dict(run_id=run_id, step=st, viewer_agent_id=ag, post_id=pid, slot=slot)) | |
| aseen = collections.Counter() | |
| for uid, act, ts in trace: | |
| ag = u2a.get(uid) | |
| X.append(dict(run_id=run_id, agent_id=ag, step=step_of.get((ag, aseen[ag])), action=act, created_at=ts)) | |
| aseen[ag] += 1 | |
| c.close() | |
| R.append(dict(run_id=run_id, | |
| experiment_type=(meta or {}).get("experiment_type"), | |
| model_default=(meta or {}).get("model_default"), | |
| n_agents=(meta or {}).get("n_agents"), | |
| n_initial=(meta or {}).get("n_initial"), | |
| steps=(meta or {}).get("steps"), | |
| join_step=(meta or {}).get("join_step"), | |
| created_at=(meta or {}).get("created_at"), | |
| source_path=os.path.relpath(db, ROOT), | |
| step_alignment_ok=bool(ok), | |
| step_coverage=round(cover, 4))) | |
| except Exception: | |
| skipped += 1 | |
| continue | |
| if (idx + 1) % 100 == 0: | |
| print(f" ...{idx+1}/{len(dbs)} runs={len(R)} posts={len(P)} comments={len(C)} impressions={len(I)}", flush=True) | |
| print(f"\n runs kept={len(R)} skipped={skipped} step-aligned={aligned} misaligned={misaligned}") | |
| for name, rows in (("runs", R), ("agents", A), ("posts", P), ("comments", C), | |
| ("impressions", I), ("actions", X)): | |
| df = pd.DataFrame(rows) | |
| p = os.path.join(a.out, f"{name}.parquet") | |
| df.to_parquet(p, index=False, compression="zstd") | |
| print(f" {name:12s} {len(df):9d} rows {os.path.getsize(p)/1e6:8.1f} MB") | |
| if __name__ == "__main__": | |
| main() | |