jimchen2-pendulum-shift / scripts /regenerate_descriptive.py
jimchen2's picture
Upload folder using huggingface_hub (part 2)
2a7bf26 verified
Raw History Blame Contribute Delete
8 kB
#!/usr/bin/env python3
"""Regenerate the descriptive questions in CLEVRER style.
python3 regenerate_descriptive.py
Reads : index.csv, intervened/index_intervention.csv,
questions/questions_{train,val}.json,
intervened/questions/questions_train.json,
itv_ts/*.csv (shipped intervened labels)
Writes : out/questions/questions_train.json
out/questions/questions_val.json
out/questions/taxonomy.json
out/questions/answer_vocab.json
out/intervened/questions/questions_train.json
out/intervened/questions/taxonomy.json
out/balance_report.json
Explanatory / predictive / counterfactual questions are copied verbatim, so the
question count per video and every question_id are preserved exactly.
"""
from __future__ import annotations
import collections
import csv
import json
import sys
from pathlib import Path
import numpy as np
sys.path.insert(0, "scripts")
import pendulum_gen as G
import questions_v2 as Q
HERE = Path(__file__).parent
OUT = HERE / "out"
SEED = 20261014
ITV_SEED = 20261118
def cfg_from_row(r):
c = G.Configuration(name=r["name"])
for k in ("theta0_deg", "omega0_rad_s", "damping_s_inv", "light_mean_deg",
"light_amplitude_deg", "light_frequency_hz", "light_phase_rad",
"gravity_m_s2", "length_m", "quad_drag_beta", "drive_amp_rad_s2",
"drive_freq_hz", "drive_phase_rad"):
setattr(c, k, float(r[k]))
c.damping_model = r["damping_model"]
return c
def sim_array(cfg):
rows = G.simulate(cfg, frames=G.EXT_FRAMES, substeps=G.SUBSTEPS)
cols = collections.defaultdict(list)
for row in rows:
for k, v in row.items():
cols[k].append(v)
return {k: np.asarray(v, dtype=float) for k, v in cols.items()}
def csv_array(path):
rows = list(csv.DictReader(open(path)))
return {k: np.asarray([float(r[k]) for r in rows], dtype=float)
for k in rows[0] if k not in ("frame",)}
def rewrite(entry, new_desc, q_rng):
"""Swap descriptive questions in place, keeping ids and order."""
out, i = [], 0
for q in entry["questions"]:
if q["question_type"] != "descriptive":
out.append(q)
continue
if i >= len(new_desc):
continue
nq = dict(new_desc[i])
nq["question_id"] = q["question_id"]
out.append(nq)
i += 1
entry["questions"] = out
return entry
def process(src, dst, arrays, tally, seed, n_desc, intervention=None):
data = json.load(open(src))
for k, entry in enumerate(data["scene_annotation"]):
vid = entry["video_id"]
q_rng = np.random.default_rng(np.random.SeedSequence([seed, k, 777]))
hi, lo = (Q.CUT_FRAME, 0) if intervention else (Q.FRAMES, 0)
facts = Q.analyze(arrays[vid], hi=hi, lo=lo)
kind = intervention[vid] if intervention else None
new = Q.build_descriptive(facts, q_rng, tally, n_desc=n_desc,
hi=hi, lo=lo, intervention_kind=kind)
rewrite(entry, new, q_rng)
info = data["info"]
info["descriptive_style"] = (
"CLEVRER-style v2: open-ended, single-word answers from a closed "
"vocabulary, sub-typed count/exist/query_*, family-indexed, "
"answer-balanced")
info["answer_convention"] = (
"descriptive: single-word open-ended string from answer_vocab.json; "
"explanatory/predictive/counterfactual: index into 'choices'")
data["answer_vocab"] = Q.ANSWER_VOCAB
OUT.joinpath(dst).parent.mkdir(parents=True, exist_ok=True)
json.dump(data, open(OUT / dst, "w"), indent=1)
return data
def taxonomy(data, extra=()):
fams = collections.OrderedDict()
for v in data["scene_annotation"]:
for q in v["questions"]:
if q["question_type"] != "descriptive":
continue
e = fams.setdefault(q["question_family"], {
"question_family_index": q["question_family_index"],
"question_subtype": q["question_subtype"],
"question_family": q["question_family"],
"question_templates": [],
"answers": [],
})
if q["question"] not in e["question_templates"]:
e["question_templates"].append(q["question"])
if q["answer"] not in e["answers"]:
e["answers"].append(q["answer"])
for e in fams.values():
e["answers"] = sorted(e["answers"], key=lambda a: (not a.isdigit(), a))
for e in extra:
fams[e["question_family"]] = e
return {
"descriptive_style": "CLEVRER-style: open-ended, single-word, "
"family-indexed, sub-typed, answer-balanced",
"descriptive_families": list(fams.values()),
"other_question_types": ["explanatory", "predictive", "counterfactual"],
"answer_convention": "descriptive: single-word string from "
"answer_vocab.json; others: index into 'choices'",
"answer_vocab": Q.ANSWER_VOCAB,
}
def report(data, tag, out):
byfam = collections.defaultdict(list)
phrasings = collections.defaultdict(set)
for v in data["scene_annotation"]:
for q in v["questions"]:
if q["question_type"] != "descriptive":
continue
byfam[q["question_family"]].append(q["answer"])
phrasings[q["question_family"]].add(q["question"])
tot = maj = 0
for fam, ans in sorted(byfam.items(), key=lambda kv: -len(kv[1])):
c = collections.Counter(ans)
tot += len(ans)
maj += c.most_common(1)[0][1]
out.append({"tag": tag, "family": fam, "n": len(ans),
"distinct_answers": len(c),
"majority": round(c.most_common(1)[0][1] / len(ans), 4),
"phrasings": len(phrasings[fam]),
"distribution": dict(c.most_common())})
print(f" {tag:22s} n={tot:6d} no-video baseline={maj/tot:6.1%} "
f"families={len(byfam)} phrasings={sum(len(s) for s in phrasings.values())}")
return tot, maj
def main():
OUT.mkdir(exist_ok=True)
idx = list(csv.DictReader(open("index.csv")))
print("re-simulating 3000 parental trajectories from index.csv ...")
arrays = {r["video_id"]: sim_array(cfg_from_row(r)) for r in idx}
print("loading 240 shipped intervened trajectories ...")
itv_idx = list(csv.DictReader(open("intervened/index_intervention.csv")))
itv_arrays = {r["video_id"]: csv_array(f"itv_ts/{r['video_id']}.csv")
for r in itv_idx}
itv_kind = {r["video_id"]: r["intervention_type"] for r in itv_idx}
out_rows, gt, gm = [], 0, 0
print("\nregenerating descriptive questions:")
tally = {}
d = process("questions/questions_train.json", "questions/questions_train.json",
arrays, tally, SEED, 2)
a, b = report(d, "root/train", out_rows); gt += a; gm += b
d = process("questions/questions_val.json", "questions/questions_val.json",
arrays, tally, SEED, 2)
a, b = report(d, "root/val", out_rows); gt += a; gm += b
json.dump(taxonomy(d), open(OUT / "questions/taxonomy.json", "w"), indent=1)
json.dump({"answer_vocab": Q.ANSWER_VOCAB},
open(OUT / "questions/answer_vocab.json", "w"), indent=1)
tally = {}
d = process("intervened/questions/questions_train.json",
"intervened/questions/questions_train.json",
itv_arrays, tally, ITV_SEED, 5, intervention=itv_kind)
a, b = report(d, "intervened/train", out_rows); gt += a; gm += b
json.dump(taxonomy(d),
open(OUT / "intervened/questions/taxonomy.json", "w"), indent=1)
print(f"\n {'TOTAL descriptive':22s} n={gt:6d} no-video baseline={gm/gt:6.1%}")
json.dump(out_rows, open(OUT / "balance_report.json", "w"), indent=1)
if __name__ == "__main__":
main()