#!/usr/bin/env python3 """CLEVRER-style descriptive questions (v2). Replaces the descriptive pool in questions.py. Follows CLEVRER's descriptive conventions: * open-ended - never multiple choice, no `choices` field * single word - every answer is one token from a closed vocabulary * sub-typed - `count` / `exist` / `query_*`, like CLEVRER's count / exist / query_color / query_material / query_shape * family id - `question_family_index` + `question_family` per question * balanced - answers are sampled to be near-uniform, so no phrasing has a majority answer that can be guessed without watching Explanatory / predictive / counterfactual questions are NOT touched here; the regeneration script carries them over verbatim from the shipped files. Facts are read from the shipped frame-aligned CSVs (or re-simulated from index.csv, which is bit-identical), so no video is needed. """ from __future__ import annotations import math import numpy as np FPS = 12 FRAMES = 160 CUT_FRAME = 96 # intervention boundary, t = 8.0 s # --------------------------------------------------------------------------- # trajectory facts # --------------------------------------------------------------------------- def _peaks(theta, omega, hi, lo): """Turning-point times/amplitudes (rad) inside frames [lo, hi). The scan must stop at hi-1: comparing frames (hi-1, hi) would detect a turning point that falls *after* the last frame actually shown in the clip. """ times, amps = [], [] for i in range(lo, max(lo, hi - 1)): if omega[i] == 0.0 or omega[i] * omega[i + 1] < 0: frac = abs(omega[i]) / (abs(omega[i]) + abs(omega[i + 1]) + 1e-12) times.append((i + frac) / FPS) amps.append(max(abs(theta[i]), abs(theta[i + 1]))) return np.array(times), np.array(amps) def analyze(A, hi=FRAMES, lo=0): """Fact table over frames [lo, hi). `hi < FRAMES` = pre-intervention only.""" th = A["theta_rad"] om = A["omega_rad_s"] en = A["energy_j_per_kg"] lt = A["light_angle_deg"] f = {} f["window_frames"] = hi - lo f["theta0_deg"] = float(np.degrees(th[lo])) f["omega0"] = float(om[lo]) p_t, p_a = _peaks(th, om, hi, lo) f["n_peaks"] = len(p_a) f["peak_amps_deg"] = np.degrees(p_a) if len(p_a) else np.array([]) f["n_peaks_15"] = int((f["peak_amps_deg"] > 15.0).sum()) f["n_peaks_20"] = int((f["peak_amps_deg"] > 20.0).sum()) if len(p_a) >= 3: mid = len(p_a) // 2 f["mid_amp_deg"] = float(np.degrees(p_a[mid])) f["env_ratio"] = float(p_a[-1] / p_a[0]) last = hi - 1 win = om[max(lo, hi - 12):hi] omax = float(np.max(np.abs(win))) f["last_sec_omega_max"] = omax j = max(lo, hi - 12) + int(np.argmax(np.abs(win))) f["last_sec_sign"] = float(np.sign(om[j])) f["theta_end_deg"] = float(np.degrees(th[last])) e0, e1 = float(en[lo]), float(en[last]) f["energy_end_ratio"] = e1 / e0 if e0 > 1e-12 else 1.0 # light source f["light_amp_deg"] = float(np.max(lt[lo:hi]) - np.min(lt[lo:hi])) / 2.0 f["light_travel_deg"] = float(np.max(lt[lo:hi]) - np.min(lt[lo:hi])) f["light_dir0"] = float(np.sign(lt[lo + 1] - lt[lo])) return f # --------------------------------------------------------------------------- # single-word helpers # --------------------------------------------------------------------------- def _side(deg): return "left" if deg < 0 else "right" def _dir(sign): if sign > 0: return "right" if sign < 0: return "left" return "still" def _band3(value, t1, t2): return "small" if value < t1 else ("medium" if value < t2 else "large") def _band3_rev(value, t1, t2): """large when the value is small (e.g. energy still high).""" return "large" if value > t1 else ("medium" if value > t2 else "small") # --------------------------------------------------------------------------- # descriptive families # --------------------------------------------------------------------------- # Each entry: (family_index, family_name, subtype, question_text, answer_fn) # answer_fn(f) -> one-word str, or None to skip the question for that video. OMEGA_STILL = 0.196 # empirical median over train -> exactly 50/50 yes/no # Skip a question when the deciding value sits this close to a threshold. Without # it, a peak at 19.9999 deg flips the answer under a change of integration # resolution (observed: video_10595, count_swing_very_wide, 4 vs 5 at 96/192 Hz). MARGIN_DEG = 0.25 MARGIN_OMEGA = 0.01 def _near_edge(values, edges, margin): return any(abs(float(v) - e) < margin for v in values for e in edges) FAMILIES = [ (0, "count_swing_wide", "count", ["How many swings in this video are wider than 15 degrees?", "Count the swings that reach more than 15 degrees in this video.", "How many of the bob's swings in this video exceed 15 degrees?"], lambda f: None if _near_edge(f["peak_amps_deg"], [15.0], MARGIN_DEG) else str(f["n_peaks_15"])), (1, "count_swing_very_wide", "count", ["How many swings in this video are wider than 20 degrees?", "Count the swings that reach more than 20 degrees in this video.", "How many of the bob's swings in this video exceed 20 degrees?"], lambda f: None if _near_edge(f["peak_amps_deg"], [20.0], MARGIN_DEG) else str(f["n_peaks_20"])), (2, "count_turning_points", "count", ["How many times does the bob stop and turn around in this video?", "Count the moments when the bob reverses direction in this video.", "How many turning points does the bob reach in this video?"], lambda f: str(f["n_peaks"]) if f["n_peaks"] >= 1 else None), (3, "query_release_side", "query_side", ["Which side of the pivot was the bob released from at the start of the video?", "At the beginning of the video, is the bob on the left or the right?", "Which side of the pivot does the bob start on?"], lambda f: _side(f["theta0_deg"]) if abs(f["theta0_deg"]) >= 5.0 else None), (4, "query_initial_direction", "query_direction", ["Which way is the bob moving at the very start of the video?", "At the first frame, which direction is the bob travelling?", "Which way does the bob set off at the start of the video?"], lambda f: _dir(np.sign(f["omega0"])) if abs(f["omega0"]) >= 0.01 else "still"), (5, "query_release_amplitude", "query_amplitude", ["How wide is the bob's first swing?", "How large is the bob's initial swing?", "How wide is the swing the bob starts with?"], lambda f: None if abs(f["theta0_deg"]) < 5.0 or _near_edge([abs(f["theta0_deg"])], [23.0, 32.0], MARGIN_DEG) else _band3(abs(f["theta0_deg"]), 23.0, 32.0)), (6, "query_mid_amplitude", "query_amplitude", ["How wide is the bob's swing halfway through the video?", "Around the middle of the video, how wide is the swing?", "How wide is the swing at the midpoint of the video?"], lambda f: None if "mid_amp_deg" not in f or _near_edge([f["mid_amp_deg"]], [8.0, 18.0], MARGIN_DEG) else _band3(f["mid_amp_deg"], 8.0, 18.0)), (7, "query_end_direction", "query_direction", ["Which way is the bob moving during the final second of the video?", "In the last second, which direction is the bob travelling?", "Which way is the bob swinging as the video ends?"], lambda f: None if _near_edge([f["last_sec_omega_max"]], [OMEGA_STILL], MARGIN_OMEGA) else ("still" if f["last_sec_omega_max"] < OMEGA_STILL else _dir(f["last_sec_sign"]))), (8, "query_end_side", "query_position", ["Which side of the pivot is the bob on in the last frame of the video?", "At the end of the video, is the bob on the left or the right?", "Which side of the pivot does the bob finish on?"], lambda f: _side(f["theta_end_deg"]) if abs(f["theta_end_deg"]) >= 1.0 else None), (9, "query_light_travel", "query_light", ["How far does the orange light source travel during the video?", "How much does the orange light source move in this video?", "Over the video, how large is the light source's sweep?"], lambda f: None if _near_edge([f["light_travel_deg"]], [10.0, 20.0], MARGIN_DEG) else _band3(f["light_travel_deg"], 10.0, 20.0)), (10, "query_light_direction", "query_direction", ["Which way is the orange light source drifting at the start of the video?", "At the beginning, which direction is the light source moving?", "Which way does the light source set off at the start?"], lambda f: _dir(f["light_dir0"]) if f["light_travel_deg"] >= 4.0 else None), # NOTE: `query_energy_end` was dropped. Every train video loses 86-99.9% of # its energy (gamma in 0.15-0.50), so the answer is near-constant and the # question is guessable without watching. (12, "exist_still_swinging", "exist", ["Is the bob still visibly swinging at the end of the video?", "Is the bob still moving when the video ends?", "At the end of the video, is the bob still swinging?"], # gated to full-length clips: over the 8 s pre-intervention window the bob # is always still swinging, which would make this constant. lambda f: None if f["window_frames"] < FRAMES or _near_edge([f["last_sec_omega_max"]], [OMEGA_STILL], MARGIN_OMEGA) else ("yes" if f["last_sec_omega_max"] >= OMEGA_STILL else "no")), ] # Intervention families (intervened/ subset only). Emitted for every video; # balanced by construction because the subset is 120 light_shift / 120 torque_push. INTERVENTION_FAMILIES = [ (20, "query_intervention_target", "query_type", "Around the 8-second mark, which part of the scene is directly changed?", lambda kind: "light" if kind == "light_shift" else "bob"), (21, "query_intervention_invariant", "query_invariant", "Around the 8-second mark, which part of the scene stays the same?", lambda kind: "bob" if kind == "light_shift" else "light"), (22, "query_energy_at_cut", "query_energy", "At the 8-second mark, what happens to the bob's mechanical energy?", lambda kind: "smooth" if kind == "light_shift" else "jumps"), ] # --------------------------------------------------------------------------- # balanced selection # --------------------------------------------------------------------------- def build_descriptive(facts, rng, tally, n_desc=2, hi=FRAMES, lo=0, intervention_kind=None): """Pick `n_desc` descriptive questions, greedy-balancing the answer marginals. `tally` is a dict {(family_name, answer): count} shared across the whole split, so the marginal answer distribution stays near-uniform. """ out = [] if intervention_kind is not None: for fidx, name, sub, text, fn in INTERVENTION_FAMILIES: ans = fn(intervention_kind) out.append(_mk(fidx, name, sub, text, ans)) tally[(name, ans)] = tally.get((name, ans), 0) + 1 n_desc = max(0, n_desc - len(INTERVENTION_FAMILIES)) # candidates for this video cands = [] for fidx, name, sub, phrasings, fn in FAMILIES: try: ans = fn(facts) except Exception: ans = None if ans is None: continue text = phrasings[int(rng.integers(len(phrasings)))] cands.append((fidx, name, sub, text, ans)) order = rng.permutation(len(cands)) for i in order: if len(out) >= n_desc + (len(INTERVENTION_FAMILIES) if intervention_kind else 0): break fidx, name, sub, text, ans = cands[i] if any(o["question_family"] == name for o in out): continue out.append(_mk(fidx, name, sub, text, ans)) tally[(name, ans)] = tally.get((name, ans), 0) + 1 return out def _mk(fidx, name, sub, text, ans): return { "question_type": "descriptive", "question_subtype": sub, "question_family_index": fidx, "question_family": name, "question": text, "answer": str(ans), } ANSWER_VOCAB = sorted({ # count - closed numeric range. Observed maximum across all 3,000 videos # (including the OOD val regimes) is 22; 0..31 leaves headroom. *[str(i) for i in range(32)], # query_side / query_position / query_direction "left", "right", "still", # query_amplitude / query_light / query_energy "small", "medium", "large", # exist "yes", "no", # intervention "light", "bob", "smooth", "jumps", })