Lara Monteagudo Tubau commited on
Commit Β·
2a95ee9
1
Parent(s): d176097
Update Script with latest analysis flow
Browse filesFiles changed (10)
50 unmodified lines51525354555650 unmodified linesactivity phases begin and end."""import jsonfrom pathlib import Pathfrom typing import Optional50 unmodified lines515253545556575850 unmodified linesactivity phases begin and end."""from __future__ import annotationsimport jsonfrom pathlib import Pathfrom typing import Optional
48 unmodified lines49505152535448 unmodified linesAgent 1a NEVER assigns dimension codes."""import jsonfrom pathlib import Path48 unmodified lines495051525354555648 unmodified linesAgent 1a NEVER assigns dimension codes."""from __future__ import annotationsimport jsonfrom pathlib import Path
56 unmodified lines57585960616256 unmodified linesAgent 1b NEVER reads Tier 3 (candidate corrections β reserved for Agent 2)."""import jsonfrom pathlib import Pathfrom typing import Optional56 unmodified lines575859606162636456 unmodified linesAgent 1b NEVER reads Tier 3 (candidate corrections β reserved for Agent 2)."""from __future__ import annotationsimport jsonfrom pathlib import Pathfrom typing import Optional
34 unmodified lines353637383940148 unmodified lines1891901911921931941951961971985 unmodified lines204205206207208209210211212213214215216274 unmodified lines49149249349449549649749849950050150250350450550650750850951051151251351451551651751851934 unmodified lines- A rule without human approval before it goes live for Agent 1"""import jsonimport uuidfrom pathlib import Path148 unmodified lineslines.append(f"Candidate ID: {c.get('candidate_id', 'unknown')}")lines.append(f" Session: {c.get('session_id')}")lines.append(f" Segment: {c.get('segment_id')}")lines.append(f" Agent 1 assigned: {c.get('agent1_dimension')}")lines.append(f" R1 coded: {c.get('r1_dimension')} | Comment: {c.get('r1_comment', '')}")lines.append(f" R2 coded: {c.get('r2_dimension')} | Comment: {c.get('r2_comment', '')}")lines.append(f" Resolved to: {c.get('resolved_dimension', 'unresolved')}")lines.append(f" Resolution note: {c.get('resolution_note', '')}")lines.append(f" Agent 1 rationale: {c.get('agent1_rationale', '')}")lines.append("")5 unmodified linesreturn "No session reports available."lines = []for r in reports:lines.append(f"Session: {r['session_id']} | Kappa: {r['overall_kappa']} | "f"Segments: {r['n_segments_total']} | Disagreed: {r['n_segments_disagreed']}")dim_kappas = r.get("kappa_per_dimension", {})low_dims = [f"{d}={k:.2f}" for d, k in dim_kappas.items()if k is not None and k < 0.70]if low_dims:lines.append(f" Low-agreement dimensions: {', '.join(low_dims)}")return "\n".join(lines)274 unmodified linesr2_comment: str,resolved_dimension: str,resolution_note: str,) -> str:"""Add a resolved disagreement to Tier 3 for Agent 2 to review later.Returns the candidate_id of the new entry."""pending_path = TIER3_PATH / "pending_review.json"data = json.loads(pending_path.read_text(encoding="utf-8"))candidate_id = str(uuid.uuid4())[:8]entry = {"candidate_id": candidate_id,"session_id": session_id,"segment_id": segment_id,"added_at": datetime.now(timezone.utc).isoformat(),"agent1_dimension": agent1_dimension,"agent1_rationale": agent1_rationale,"r1_dimension": r1_dimension,"r1_comment": r1_comment,"r2_dimension": r2_dimension,"r2_comment": r2_comment,"resolved_dimension": resolved_dimension,"resolution_note": resolution_note,"consumed": False, # flipped to True after Agent 2 processes it}data["pending_review"].append(entry)34 unmodified lines3536373839404142148 unmodified lines1911921931941951961971981992002012022032042052062072082092102115 unmodified lines217218219220221222223224225226227228229230231232233274 unmodified lines50850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854934 unmodified lines- A rule without human approval before it goes live for Agent 1"""from __future__ import annotationsimport jsonimport uuidfrom pathlib import Path148 unmodified lineslines.append(f"Candidate ID: {c.get('candidate_id', 'unknown')}")lines.append(f" Session: {c.get('session_id')}")lines.append(f" Segment: {c.get('segment_id')}")# Primary dimensiona1_sec = c.get("agent1_secondary_dimension")lines.append(f" Agent 1 primary: {c.get('agent1_dimension')}"+ (f" | secondary: {a1_sec}" if a1_sec else ""))r1_sec = c.get("r1_secondary_dimension")lines.append(f" R1 primary: {c.get('r1_dimension')}"+ (f" | secondary: {r1_sec}" if r1_sec else "")+ f" | Comment: {c.get('r1_comment', '')}")r2_sec = c.get("r2_secondary_dimension")lines.append(f" R2 primary: {c.get('r2_dimension')}"+ (f" | secondary: {r2_sec}" if r2_sec else "")+ f" | Comment: {c.get('r2_comment', '')}")res_sec = c.get("resolved_secondary_dimension")lines.append(f" Resolved primary: {c.get('resolved_dimension', 'unresolved')}"+ (f" | secondary: {res_sec}" if res_sec else ""))lines.append(f" Resolution note: {c.get('resolution_note', '')}")lines.append(f" Agent 1 rationale: {c.get('agent1_rationale', '')}")lines.append("")5 unmodified linesreturn "No session reports available."lines = []for r in reports:# Use AC1 as primary reliability metric; fall back to kappa for legacy reportsac1 = r.get("overall_ac1", r.get("overall_kappa", "?"))kappa = r.get("overall_kappa", "?")lines.append(f"Session: {r['session_id']} | AC1: {ac1} | ΞΊ: {kappa} | "f"Segments: {r['n_segments_total']} | Disagreed: {r['n_segments_disagreed']}")# Per-dimension reliability: prefer AC1, fall back to kappadim_rel = r.get("ac1_per_dimension") or r.get("kappa_per_dimension", {})low_dims = [f"{d}={k:.2f}" for d, k in dim_rel.items()if k is not None and k < 0.70]if low_dims:lines.append(f" Low-reliability dimensions: {', '.join(low_dims)}")return "\n".join(lines)274 unmodified linesr2_comment: str,resolved_dimension: str,resolution_note: str,# Secondary dimension fields β optional, preserved for Agent 2 learningr1_secondary_dimension: Optional[str] = None,r2_secondary_dimension: Optional[str] = None,agent1_secondary_dimension: Optional[str] = None,resolved_secondary_dimension: Optional[str] = None,) -> str:"""Add a resolved disagreement to Tier 3 for Agent 2 to review later.Returns the candidate_id of the new entry.Secondary dimension fields are optional. When present they give Agent 2richer context: if researchers consistently mark D1 as secondary alongsideD3, Agent 2 can propose a disambiguation or co-occurrence rule."""pending_path = TIER3_PATH / "pending_review.json"data = json.loads(pending_path.read_text(encoding="utf-8"))candidate_id = str(uuid.uuid4())[:8]entry = {"candidate_id": candidate_id,"session_id": session_id,"segment_id": segment_id,"added_at": datetime.now(timezone.utc).isoformat(),"agent1_dimension": agent1_dimension,"agent1_secondary_dimension": agent1_secondary_dimension,"agent1_rationale": agent1_rationale,"r1_dimension": r1_dimension,"r1_secondary_dimension": r1_secondary_dimension,"r1_comment": r1_comment,"r2_dimension": r2_dimension,"r2_secondary_dimension": r2_secondary_dimension,"r2_comment": r2_comment,"resolved_dimension": resolved_dimension,"resolved_secondary_dimension": resolved_secondary_dimension,"resolution_note": resolution_note,"consumed": False,}data["pending_review"].append(entry)
39 unmodified lines40414243444546471 unmodified line4950515253545556575859606162636465666768697071721085 unmodified lines115811591160116111621163404 unmodified lines156815691570157115721573366 unmodified lines194019411942194319441945186 unmodified lines21322133213421352136213739 unmodified linesPipelineStats,)from llm_client import circuit_stateSESSIONS_ROOT = Path("sessions")_STYLES_DIR = Path(__file__).parent / "static" / "styles"MODEL_ID = "Qwen/Qwen2.5-72B-Instruct"1 unmodified line# ---------------------------------------------------------------------------# CSS loading (compile SCSS with libsass if available, else pre-compiled CSS)# ---------------------------------------------------------------------------def _load_css() -> str:scss_entry = _STYLES_DIR / "main.scss"if scss_entry.exists():try:import sass # type: ignorecss = sass.compile(filename=str(scss_entry), output_style="expanded",include_paths=[str(_STYLES_DIR)])(_STYLES_DIR / "main.css").write_text(css, encoding="utf-8")return cssexcept Exception as e:print(f"[CollabCode] SCSS compile error: {e}")compiled = _STYLES_DIR / "main.css"if compiled.exists():return compiled.read_text(encoding="utf-8")return ""# ---------------------------------------------------------------------------1085 unmodified linescollected_results: dict[str, dict] = {}pipeline_stats_html = ""try:for sr, pstats in run_boundaries_parallel(404 unmodified lines)def fn_resolve(seg_id: str, dim_choice: str, note: str, state: dict):if not seg_id.strip():raise gr.Error("Enter the segment ID.")366 unmodified linesdiscard_btn = gr.Button("Discard segment", variant="secondary")dis_status = gr.Markdown()with gr.Column(scale=1, min_width=200):with gr.Accordion("Research Basis", open=True):gr.HTML(RESEARCH_INFO["agreement"])186 unmodified linesoutputs=[state, dis_status],)# Rule review tabload_rules_btn.click(fn=fn_load_rules, outputs=[rules_html_comp, rule_selector])approve_rule_btn.click(39 unmodified lines404142434445464748495051525354551 unmodified line575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061085 unmodified lines119211931194119511961197119811991200120112021203404 unmodified lines1608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710366 unmodified lines207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112186 unmodified lines22992300230123022303230423052306230723082309231023112312231323142315231639 unmodified linesPipelineStats,)from llm_client import circuit_statefrom sequential_analysis import (load_and_analyse,render_transition_matrix_html,render_significant_transitions_html,to_csv as seq_to_csv,lag_to_csv,)SESSIONS_ROOT = Path("sessions")SESSIONS_ROOT.mkdir(parents=True, exist_ok=True) # Gap 3: ensure exists at startup_STYLES_DIR = Path(__file__).parent / "static" / "styles"MODEL_ID = "Qwen/Qwen2.5-72B-Instruct"1 unmodified line# ---------------------------------------------------------------------------# CSS loading## Priority order:# 1. Dart Sass CLI (`sass` command) β full @use/@forward support# 2. Pre-compiled static/styles/main.css (committed artifact)# 3. Inline fallback β covers the most critical Gradio overrides## The SCSS design system uses Dart Sass @use syntax (requires Dart Sass β₯ 1.23).# libsass does not support @use. Install Dart Sass:# npm install -g sass # Node.js# brew install sass/sass/sass # macOS# choco install sass # Windows# Then run: python static/build.py# ---------------------------------------------------------------------------def _load_css() -> str:# 1. Try Dart Sass CLIscss_entry = _STYLES_DIR / "main.scss"if scss_entry.exists():try:import subprocessresult = subprocess.run(["sass", str(scss_entry), "--style=expanded","--load-path", str(_STYLES_DIR), "--no-source-map"],capture_output=True, text=True, timeout=30,)if result.returncode == 0 and result.stdout:css = result.stdout(_STYLES_DIR / "main.css").write_text(css, encoding="utf-8")print("[CollabCode] SCSS compiled via Dart Sass CLI.")return cssexcept (FileNotFoundError, subprocess.TimeoutExpired):pass # sass CLI not available# 2. Pre-compiled CSScompiled = _STYLES_DIR / "main.css"if compiled.exists():print("[CollabCode] Using pre-compiled main.css.")return compiled.read_text(encoding="utf-8")# 3. Inline fallback β no external dependency requiredprint("[CollabCode] No compiled CSS found. Using inline fallback. ""Install Dart Sass and run `python static/build.py` for full styling.")return "" # EXTRA_CSS below covers essential Gradio overrides# ---------------------------------------------------------------------------1085 unmodified linescollected_results: dict[str, dict] = {}pipeline_stats_html = ""# Initialise pstats before the loop so references after the try block are# always safe even if run_boundaries_parallel raises before its first yield.pstats = PipelineStats(agent_name="Agent 1a β Boundary Detector",n_sections=len(sections),)try:for sr, pstats in run_boundaries_parallel(404 unmodified lines)def fn_run_sequence_analysis(rater_choice: str, state: dict):"""Run sequential analysis on one rater's coding file.Sequential analysis (Bakeman & Gottman 1986; Bakeman & Quera 2011)reveals temporal patterns invisible in frequency counts:which dimension transitions occur more or less often than chance?Args:rater_choice: "R1 (you)" or "R2 (co-researcher)" or "Both (merged)"state: app state (used to locate the session folder)"""if not state.get("session_id"):raise gr.Error("No session loaded β complete the Pipeline tab first.")d = _session_dir(state)try:if "R2" in rater_choice:path = d / "coding_R2.json"else:path = d / f"coding_{state['researcher_id']}.json"if not path.exists():raise gr.Error(f"Coding file not found: {path.name}. Download your coding first.")analysis = load_and_analyse(path, max_lag=3)except gr.Error:raiseexcept Exception as e:raise gr.Error(f"Sequence analysis failed: {e}") from eif "error" in analysis:raise gr.Error(analysis["error"])stat = analysis.get("statistics", {})n_ep = stat.get("n_episodes", 0)n_tr = stat.get("n_transitions", 0)cats = stat.get("categories_used", [])entropy = stat.get("transition_entropy", 0.0)ent_max = stat.get("entropy_max", 0.0)sig_pos = stat.get("significant_pos", [])sig_neg = stat.get("significant_neg", [])# Summary markdownent_note = (f"**{entropy:.3f}** bits / max {ent_max:.3f} β "+ ("high entropy: transitions are distributed; no strong sequential pattern"if ent_max > 0 and entropy / ent_max > 0.80else "moderate entropy: some transitions dominate"if ent_max > 0 and entropy / ent_max > 0.50else "low entropy: a few transitions strongly dominate the sequence"))warnings = analysis.get("sparse_warnings", [])warn_md = ""if warnings:warn_md = (f"\n\n*β {len(warnings)} sparse cell(s) β residuals unreliable: "f"{'; '.join(warnings[:3])}{'β¦' if len(warnings) > 3 else ''}*")summary_md = (f"**{n_ep}** episodes Β· **{n_tr}** transitions Β· "f"**{len(cats)}** dimensions used: `{'`, `'.join(cats)}` \n"f"Transition entropy: {ent_note} \n"f"**{len(sig_pos)}** significantly common Β· **{len(sig_neg)}** significantly rare"f"{warn_md} \n\n"f"*Adjusted residuals β Bakeman & Quera (2011). "f"|z| > 1.96 = p < .05 Β· |z| > 2.58 = p < .01*")matrix_html = render_transition_matrix_html(analysis)sig_html = render_significant_transitions_html(analysis)gr.Info(f"Sequence analysis complete: {n_ep} episodes, {len(sig_pos)} significant transitions.")return summary_md, matrix_html, sig_html, gr.update(visible=True)def fn_download_seq_csv(rater_choice: str, state: dict):"""Download transition matrix as CSV for R/Python/SPSS."""if not state.get("session_id"):raise gr.Error("No session loaded.")d = _session_dir(state)path = d / ("coding_R2.json" if "R2" in rater_choiceelse f"coding_{state['researcher_id']}.json")if not path.exists():raise gr.Error(f"Coding file not found: {path.name}")analysis = load_and_analyse(path)if "error" in analysis:raise gr.Error(analysis["error"])csv_str = seq_to_csv(analysis)tmp = Path(tempfile.mktemp(suffix=f"_transitions_{state['session_id']}.csv"))tmp.write_text(csv_str, encoding="utf-8")return str(tmp)def fn_resolve(seg_id: str, dim_choice: str, note: str, state: dict):if not seg_id.strip():raise gr.Error("Enter the segment ID.")366 unmodified linesdiscard_btn = gr.Button("Discard segment", variant="secondary")dis_status = gr.Markdown()# ββ Sequence Analysis ββββββββββββββββββββββββββββββwith gr.Accordion("Sequence Analysis", open=False) as accord_seq:gr.HTML('<div style="background:#f0fdf4;border:1px solid #86efac;''border-radius:8px;padding:10px 14px;margin-bottom:10px;''font-size:0.83em;color:#065f46">''<strong>Temporal structure of the coded sequence.</strong> ''Frequency counts tell you <em>how much</em> of each dimension; ''sequential analysis tells you <em>what follows what</em>. ''<em>Bakeman & Gottman (1986); Bakeman & Quera (2011)</em>''</div>')with gr.Row():seq_rater_choice = gr.Dropdown(label="Analyse coding from",choices=["R1 (you)", "R2 (co-researcher)"],value="R1 (you)", scale=2,)seq_run_btn = gr.Button("Run β", variant="primary", scale=1)seq_summary_md = gr.Markdown()seq_matrix_html = gr.HTML()seq_sig_html = gr.HTML()with gr.Column(visible=False) as col_seq_download:seq_dl_btn = gr.Button("Download transition matrix (CSV for R/Python/SPSS)",variant="secondary", size="sm",)seq_dl_file = gr.File(visible=False)with gr.Column(scale=1, min_width=200):with gr.Accordion("Research Basis", open=True):gr.HTML(RESEARCH_INFO["agreement"])186 unmodified linesoutputs=[state, dis_status],)# Sequence analysisseq_run_btn.click(fn=fn_run_sequence_analysis,inputs=[seq_rater_choice, state],outputs=[seq_summary_md, seq_matrix_html, seq_sig_html, col_seq_download],)seq_dl_btn.click(fn=fn_download_seq_csv,inputs=[seq_rater_choice, state],outputs=[seq_dl_file],).then(fn=lambda: gr.update(visible=True), outputs=[seq_dl_file])# Rule review tabload_rules_btn.click(fn=fn_load_rules, outputs=[rules_html_comp, rule_selector])approve_rule_btn.click(
6 unmodified lines78910111213146 unmodified lines"rules": [{"rule_id": "R01","label": "One dimension per segment","description": "Each segment must be assigned exactly one dimension code. If multiple dimensions are observable, assign the most dominant one and flag the segment as uncertain with a note on the competing dimension."},{"rule_id": "R02",6 unmodified lines78910111213146 unmodified lines"rules": [{"rule_id": "R01","label": "Primary dimension required; secondary optional","description": "Every segment requires exactly one PRIMARY dimension β the dominant behavioral pattern. An optional SECONDARY dimension may be added when a second dimension is clearly and substantially observable alongside the primary, not merely incidental. Use secondary sparingly: most segments are single-dimensional. IMPORTANT DISTINCTION: uncertain=true is for when you cannot determine which dimension is primary (competing interpretations). secondary_dimension_id is for when two dimensions genuinely co-occur and the primary is clear. Do not confuse the two. Reference: Strijbos et al. (2006) multi-functional discourse moves."},{"rule_id": "R02",
1234567891011121314151617181920212223242526272 unmodified lines30313233343536{"_meta": {"version": "1.0","locked": true,"description": "Anchor examples per dimension. These are research-team-authored examples that ground the LLM's interpretation. Agent 2 must never modify this file. New examples may only be added by the research team."},"examples": [{"dimension_id": "D1","type": "positive","label": "Successful comprehension check and paraphrase","source": "Study 1, translated","exchange": [{"speaker": "Psychology Student (P)", "text": "Did you understand what I just said?"},{"speaker": "Medical Student (M)", "text": "U-hum. That is, you mean, whether now there is a psychotic component in addition to the depression and the multiple sclerosis?"},{"speaker": "Psychology Student (P)", "text": "Exactly!"}],"annotation_note": "P elicits comprehension check. M paraphrases back accurately. P confirms. Classic D1 positive episode."},{"dimension_id": "D2","type": "negative","label": "Overlapping speech causing communication breakdown","source": "Study 1, translated","exchange": [{"speaker": "P", "text": "[It's certainly a depression]"},{"speaker": "M", "text": "[...has always been]"},2 unmodified lines{"speaker": "M", "text": "[But schizophrenia... schizophrenia] I can't read that."},{"speaker": "P", "text": "[It's certainly a depression... Sorry?]"}],"annotation_note": "Brackets indicate simultaneous speech. Repeated overlaps, confusion about the floor, neither partner can complete a thought. Classic D2 negative episode."}]}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869702 unmodified lines737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361{"_meta": {"version": "2.0","locked": true,"description": "Anchor examples per dimension grounding the LLM's interpretation. Research-team authored. Agent 2 must never modify this file. Format: 2-3 positive + 1-2 negative examples per dimension. Sources drawn from the CollabCode corpus and reconstructed from Meier, Spada & Rummel (2007). Literature: Brown et al. (2020) show that even 2-3 examples significantly improve LLM classification over definition-only prompts."},"examples": [{"dimension_id": "D1","type": "positive","label": "Successful comprehension check and paraphrase","source": "Study 1, translated (Meier et al. 2007)","exchange": [{"speaker": "Psychology Student (P)", "text": "Did you understand what I just said?"},{"speaker": "Medical Student (M)", "text": "U-hum. That is, you mean, whether now there is a psychotic component in addition to the depression and the multiple sclerosis?"},{"speaker": "Psychology Student (P)", "text": "Exactly!"}],"annotation_note": "P elicits comprehension check. M paraphrases back accurately. P confirms. Classic D1 positive episode β the behavioral marker is the explicit paraphrase demonstrating active comprehension."},{"dimension_id": "D1","type": "positive","label": "Repair sequence β catching ambiguity before it causes confusion","source": "CollabCode corpus, reconstructed","exchange": [{"speaker": "Lara", "text": "So in the third condition we applied the same procedure as before."},{"speaker": "Gayathri", "text": "Wait, which condition? I thought we only had two experimental conditions."},{"speaker": "Lara", "text": "Oh sorry, I meant the third transcript, not condition. We only have two conditions."},{"speaker": "Gayathri", "text": "OK, that makes sense now."}],"annotation_note": "Gayathri catches an ambiguous term and initiates repair. Lara corrects the misunderstanding. Gayathri confirms re-established understanding. Both partners actively work to maintain shared knowledge β the repair sequence is the behavioral marker, not just the content of what was corrected."},{"dimension_id": "D1","type": "negative","label": "Complex explanation delivered without any comprehension check","source": "CollabCode corpus, reconstructed","exchange": [{"speaker": "Lara", "text": "And then we run the sequential analysis, compute the transition matrix, get the adjusted residuals, check which ones exceed 1.96, and export it all for R."},{"speaker": "Gayathri", "text": "Mhm."},{"speaker": "Lara", "text": "Anyway, so that's what I did."}],"annotation_note": "Lara delivers a complex multi-step explanation without checking understanding. Gayathri's 'mhm' is a minimal backchannel, not a comprehension signal. Neither partner initiates a check, paraphrase, or repair. Code as D3 (information pooling, one-way sharing) rather than D1. D1 requires an observable behavioral act β elicitation, paraphrase, or repair β that is absent here."},{"dimension_id": "D2","type": "positive","label": "Smooth floor management with explicit yield and transfer","source": "CollabCode corpus, reconstructed","exchange": [{"speaker": "Rwitajit", "text": "So Lara was saying that the episode segmentation was good butβ"},{"speaker": "Lara", "text": "Actually, can I just finish that point?"},{"speaker": "Rwitajit", "text": "Yes, go ahead, sorry."},{"speaker": "Lara", "text": "The segmentation was good but the labeling was inconsistent. Now Gayathri, what do you think?"}],"annotation_note": "Lara explicitly reclaims the floor ('can I just finish'). Rwitajit explicitly yields ('go ahead, sorry'). Lara completes her thought, then explicitly transfers the floor to Gayathri. All three floor mechanisms β claim, yield, transfer β are visible. This is D2."},{"dimension_id": "D2","type": "negative","label": "Overlapping speech causing communication breakdown","source": "Study 1, translated (Meier et al. 2007)","exchange": [{"speaker": "P", "text": "[It's certainly a depression]"},{"speaker": "M", "text": "[...has always been]"},2 unmodified lines{"speaker": "M", "text": "[But schizophrenia... schizophrenia] I can't read that."},{"speaker": "P", "text": "[It's certainly a depression... Sorry?]"}],"annotation_note": "Brackets indicate simultaneous speech. Repeated overlaps, confusion about who has the floor, neither partner can complete a thought. Classic D2 negative β dialogue management breaks down visibly."},{"dimension_id": "D3","type": "positive","label": "Both partners share findings and build on each other's knowledge","source": "CollabCode corpus, reconstructed","exchange": [{"speaker": "Lara", "text": "I found that with DeepSeek, the episode segmentation was quite accurate β around 18 episodes, which is in the same ballpark as the 28 we coded manually."},{"speaker": "Gayathri", "text": "That's interesting. I also looked at the Wednesday transcript and the number of segments seemed stable too. But did you check if the dimension labels matched?"},{"speaker": "Lara", "text": "Not yet, that's the next step. The labeling is where I see inconsistency β task division gets confused with consensus."},{"speaker": "Gayathri", "text": "That matches what I was seeing. Maybe we need more examples in the prompt."}],"annotation_note": "Both partners share task-relevant findings, elaborate, and elicit more. Lara shares quantitative results; Gayathri adds her own observation and asks a follow-up; Lara elaborates; Gayathri corroborates and extends. Information flows bidirectionally with mutual elaboration β the defining behavioral marker of D3."},{"dimension_id": "D3","type": "positive","label": "Knowledge elicitation β drawing out a partner's domain expertise","source": "CollabCode corpus, reconstructed","exchange": [{"speaker": "Rwitajit", "text": "What do you know about few-shot learning for annotation tasks? You've done more with prompting than I have."},{"speaker": "Lara", "text": "So the idea is that instead of a long definition you give the model a couple of examples of what each category looks like in practice."},{"speaker": "Rwitajit", "text": "And does that work better than the definition-only approach?"},{"speaker": "Lara", "text": "Based on what I read, yes β Brown et al. 2020 showed that even a few examples significantly improve classification accuracy."},{"speaker": "Rwitajit", "text": "OK, so we should probably add example exchanges to the prompt."}],"annotation_note": "Rwitajit explicitly elicits Lara's expertise ('you've done more with prompting'). Lara elaborates with domain-specific information and a citation. Rwitajit requests further elaboration. Information is task-relevant and builds the group's knowledge β D3. Note: this differs from D4 (no decision is being evaluated) and D1 (no comprehension check)."},{"dimension_id": "D3","type": "negative","label": "Social chat β information exchange that is not task-relevant","source": "CollabCode corpus, reconstructed","exchange": [{"speaker": "Lara", "text": "I hope you had a nice weekend."},{"speaker": "Gayathri", "text": "Yes, it was good, we went to the market. You?"},{"speaker": "Lara", "text": "Oh nice. Mine was quiet, just caught up on reading."},{"speaker": "Gayathri", "text": "Good."}],"annotation_note": "Turns are social β weekend activities, personal life. Information is being exchanged but it is not domain-specific or task-relevant. D3 requires pooling of information relevant to the collaborative task (Meier et al. 2007). Code as NA (off-task, social). NOT D3 even though information flows β the dimension requires task-relevant content."},{"dimension_id": "D4","type": "positive","label": "Evaluating two options and reaching a joint decision with explicit rationale","source": "CollabCode corpus, reconstructed","exchange": [{"speaker": "Lara", "text": "So we could either add more examples to the prompt, or we could rewrite the definitions to be shorter and more operational."},{"speaker": "Gayathri", "text": "Adding examples is better I think. The definitions are from the paper so we shouldn't change them."},{"speaker": "Rwitajit", "text": "I agree with Gayathri. The definitions are validated β we should keep them and add examples on top."},{"speaker": "Lara", "text": "OK, so we go with adding examples. That's decided."}],"annotation_note": "Lara presents two options explicitly. Gayathri argues for one with a reason (definitions are validated). Rwitajit evaluates and agrees, adding a rationale. Lara closes with a joint decision. The key D4 markers are: explicit option evaluation, exchange of arguments, and a clearly identifiable collective decision outcome."},{"dimension_id": "D4","type": "positive","label": "Moving from mild disagreement to consensus through argument","source": "CollabCode corpus, reconstructed","exchange": [{"speaker": "Lara", "text": "I think we should use the whole transcript for the analysis, not just the first half."},{"speaker": "Gayathri", "text": "But the second half is mostly administrative turns. It'll dilute the reliability results."},{"speaker": "Lara", "text": "You're right, the second half does have a lot of off-task turns. OK, we use only the first 45 minutes."},{"speaker": "Gayathri", "text": "Yes, that makes more sense."}],"annotation_note": "Partners have an initial difference of view. Gayathri gives an evaluative argument (dilution concern). Lara re-evaluates, acknowledges the argument, and proposes a specific alternative. Both confirm. The decision is clearly identified (first 45 minutes). D4 β critical evaluation leading to consensus, not just agreement."},{"dimension_id": "D4","type": "negative","label": "Discussion of options that ends without a decision β stays as D3","source": "CollabCode corpus, reconstructed","exchange": [{"speaker": "Lara", "text": "Should we use kappa or AC1 for the reliability check?"},{"speaker": "Gayathri", "text": "Kappa is the standard in the literature."},{"speaker": "Lara", "text": "But AC1 handles imbalanced distributions better."},{"speaker": "Gayathri", "text": "That's a good point. I'm not sure what the field prefers."},{"speaker": "Lara", "text": "Me neither. We should look into it."}],"annotation_note": "The discussion explores two options and relevant arguments, but ends without a decision. 'We should look into it' explicitly defers the decision. Code as D3 (domain knowledge being pooled) rather than D4. D4 requires a clearly identifiable joint decision outcome β without one, even substantive discussion of options does not qualify."},{"dimension_id": "D5","type": "positive","label": "Explicit allocation of work items with clear individual ownership","source": "CollabCode corpus, reconstructed","exchange": [{"speaker": "Rwitajit", "text": "So what do we each need to do before next meeting?"},{"speaker": "Lara", "text": "I'll code the Wednesday transcript and run the sequential analysis."},{"speaker": "Gayathri", "text": "I can look at the literature on few-shot prompting and draft some examples."},{"speaker": "Rwitajit", "text": "I'll review Lara's output and write up the methods section."}],"annotation_note": "Rwitajit explicitly opens the task division phase with a question. Each partner claims a specific deliverable using first-person ownership ('I'll', 'I can'). There is no ambiguity about who does what. This is D5 β systematic decomposition of work into individually owned subtasks with clear scope."},{"dimension_id": "D5","type": "positive","label": "Dividing a complex analysis into sequential subtasks with a handoff point","source": "CollabCode corpus, reconstructed","exchange": [{"speaker": "Lara", "text": "OK so for the analysis: I'll do the quantitative part β kappa, sequence analysis β and then hand that over to Gayathri."},{"speaker": "Gayathri", "text": "And I'll do the qualitative interpretation and write the discussion section from that."},{"speaker": "Lara", "text": "Exactly. And we both check each other's section before the submission deadline."}],"annotation_note": "Lara proposes a sequential division with an explicit handoff point ('hand that over'). Gayathri accepts and specifies her scope. Both confirm a mutual review step. This is D5 β not only are tasks divided, but the workflow between the tasks is also articulated."},{"dimension_id": "D5","type": "negative","label": "Listing remaining tasks without assigning them β code as D3 or D4","source": "CollabCode corpus, reconstructed","exchange": [{"speaker": "Lara", "text": "So we still need to: code the new transcripts, improve the prompts, and write the results section."},{"speaker": "Gayathri", "text": "Yes, and we also need to do the inter-rater reliability check."},{"speaker": "Rwitajit", "text": "Right, and the literature review needs updating."},{"speaker": "Lara", "text": "OK, those are the main things we need to do."}],"annotation_note": "Partners identify remaining tasks but do not assign them to anyone. Nobody says who is doing what. The list builds shared awareness of project status but does not divide labor. This is D3 (pooling knowledge about project state). Code as D5 only when clear individual ownership is assigned β a task list without names is not D5."},{"dimension_id": "D6","type": "positive","label": "Checking elapsed time and actively adjusting the meeting agenda","source": "CollabCode corpus, reconstructed","exchange": [{"speaker": "Rwitajit", "text": "OK, we're already 40 minutes in and we haven't covered the reliability analysis yet."},{"speaker": "Lara", "text": "Should we skip the detailed demo and just go over the key numbers?"},{"speaker": "Gayathri", "text": "Yes, let's do that. We need to finish by 3:30."},{"speaker": "Rwitajit", "text": "Agreed. So let's just go through the key results quickly."}],"annotation_note": "Rwitajit checks elapsed time and identifies an agenda gap. Lara proposes a time-adjusted strategy. Gayathri anchors the hard constraint (3:30 deadline). Partners jointly reprioritize. D6 requires all three behaviors: explicit time check, identification of the constraint, and an adaptive strategy response."},{"dimension_id": "D6","type": "negative","label": "Mentioning the time without adjusting pace or agenda","source": "CollabCode corpus, reconstructed","exchange": [{"speaker": "Lara", "text": "It's almost 3 o'clock."},{"speaker": "Gayathri", "text": "Yeah."},{"speaker": "Lara", "text": "OK, so anyway, as I was saying about the analysis..."}],"annotation_note": "The time mention is incidental β Lara does not propose any change in pace, agenda adjustment, or strategy. Gayathri simply acknowledges. The conversation continues unchanged. This does NOT meet the D6 criterion of actively managing time. Code the surrounding content (D3, D4, etc.) rather than D6 when time is noted but not acted upon."},{"dimension_id": "D7","type": "positive","label": "Coordinating shared screen access and navigating a shared document together","source": "CollabCode corpus, reconstructed","exchange": [{"speaker": "Lara", "text": "I'm sharing my screen now. Can you see the Excel?"},{"speaker": "Gayathri", "text": "Yes, I can see it."},{"speaker": "Lara", "text": "OK, so if you go to tab 3 β actually, can you control the mouse?"},{"speaker": "Gayathri", "text": "I don't have control. Should I just tell you where to navigate?"},{"speaker": "Lara", "text": "Yes, do that. Where do you want me to go?"}],"annotation_note": "Both partners actively manage a shared technical environment. Lara coordinates screen sharing access; Gayathri verifies access; they negotiate tool control. This is D7 β explicit management of shared technical tools (screen sharing, shared document) to enable collaborative work. Visible behavioral markers: 'Can you see it?', access negotiation, joint navigation."},{"dimension_id": "D7","type": "positive","label": "Cooperative resolution of a technical disruption","source": "CollabCode corpus, reconstructed","exchange": [{"speaker": "Gayathri", "text": "I can't see your screen anymore, it went black."},{"speaker": "Lara", "text": "Let me stop sharing and restart. One second."},{"speaker": "Gayathri", "text": "OK."},{"speaker": "Lara", "text": "Can you see it now?"},{"speaker": "Gayathri", "text": "Yes, it's back. OK good."},{"speaker": "Lara", "text": "Great, so where were we?"}],"annotation_note": "Technical failure is resolved cooperatively. Lara takes initiative to fix the problem; Gayathri provides feedback on whether it worked. The session then continues. D7 β partners manage technical disruption to maintain the shared workspace. Both partners contribute to the resolution: one acts, one verifies."},{"dimension_id": "D7","type": "negative","label": "Technical issue acknowledged but not managed β does not qualify as D7","source": "CollabCode corpus, reconstructed","exchange": [{"speaker": "Rwitajit", "text": "Sorry, I joined late, I was having internet problems."},{"speaker": "Lara", "text": "OK, we already covered the first part."},{"speaker": "Rwitajit", "text": "I couldn't hear the beginning."},{"speaker": "Lara", "text": "OK, well, we're moving on now."}],"annotation_note": "A technical problem is acknowledged but not managed cooperatively. No one attempts to catch up Rwitajit, resolve the audio issue, or adapt. The issue is noted and then ignored. This is closer to D2 (poor dialogue management) than D7. D7 requires active, cooperative management of shared technical tools β passive acknowledgement does not qualify."},{"dimension_id": "D8","type": "positive","label": "Mutual appreciation with specific acknowledgement of each partner's contribution","source": "CollabCode corpus, reconstructed","exchange": [{"speaker": "Gayathri", "text": "I thought your approach of using the LLM to segment first before coding was actually quite elegant β it avoids the circular problem."},{"speaker": "Lara", "text": "Thanks. Though I think your suggestion about adding examples will make a real difference to the labeling."},{"speaker": "Gayathri", "text": "We can try it together. Both ideas combined will probably work better than either alone."}],"annotation_note": "Gayathri offers genuine appreciation with a specific reason ('avoids the circular problem'). Lara reciprocates with appreciation for Gayathri's contribution. Both acknowledge each other as equal contributors to a shared approach. D8 markers: mutual respect, specific (not generic) appreciation, equal status framing, collaborative stance ('together')."},{"dimension_id": "D8","type": "positive","label": "Constructive challenge accepted openly β respectful disagreement","source": "CollabCode corpus, reconstructed","exchange": [{"speaker": "Rwitajit", "text": "I'm not sure that approach is right. Dropping the second half of the transcript might introduce bias."},{"speaker": "Lara", "text": "That's a fair challenge. What would you suggest instead?"},{"speaker": "Rwitajit", "text": "We could flag those turns as off-task and exclude them selectively rather than cutting by time."},{"speaker": "Lara", "text": "That's actually more principled. Let's do that."}],"annotation_note": "Rwitajit challenges without dismissing ('I'm not sure'). Lara accepts the challenge as legitimate and invites an alternative. Rwitajit proposes; Lara evaluates openly and accepts. Constructive critique met with open engagement. D8 β mutual respect even through disagreement, equal standing, no defensiveness or dominance."},{"dimension_id": "D8","type": "negative","label": "Dominance pattern β one partner repeatedly talks over the other","source": "CollabCode corpus, reconstructed","exchange": [{"speaker": "Lara", "text": "So I think we shouldβ"},{"speaker": "Rwitajit", "text": "Yes but the important thing is that we need to run this on all transcripts first."},{"speaker": "Lara", "text": "Right, but I was going to sayβ"},{"speaker": "Rwitajit", "text": "And also we need to think about the submission deadline."},{"speaker": "Lara", "text": "Mm."}],"annotation_note": "Rwitajit repeatedly redirects before Lara can complete a thought. Lara's contributions are cut off twice. The interaction is asymmetric β one partner drives, the other cannot contribute. No mutual respect or equal footing. NOT D8. Code surrounding content based on what the dominant partner is doing (D5 if task-dividing, D4 if deciding, etc.)."},{"dimension_id": "D9","type": "positive","label": "Systematic individual account of independent work","source": "CollabCode corpus, reconstructed","exchange": [{"speaker": "Lara", "text": "So let me walk through what I did. First, I gave the LLM the definition from the paper. Then I asked it to segment the transcript into episodes of 1-5 minutes. Then I had it code each episode with one dimension. And finally I compared that to the human coding from our study."},{"speaker": "Gayathri", "text": "OK."},{"speaker": "Lara", "text": "The segmentation was good β 18 LLM episodes vs 28 human. The coding was inconsistent."}],"annotation_note": "Lara presents a structured, systematic account of her individual work. Gayathri's 'OK' is a backchannel that scaffolds without interrupting. Lara stays focused, on-task, and advances the group through her individual contribution. D9 β individual task engagement that benefits the group. The focus and organization of the individual contribution is the behavioral marker."},{"dimension_id": "D9","type": "positive","label": "Each partner contributes their distinct domain expertise to a shared problem","source": "CollabCode corpus, reconstructed","exchange": [{"speaker": "Lara", "text": "From the NLP side, few-shot prompting should improve consistency. Brown et al. 2020 showed even 2-3 examples significantly help classification."},{"speaker": "Gayathri", "text": "And from the CSCL side, examples need to represent the prototypical case β not the edge cases first."},{"speaker": "Rwitajit", "text": "From a methodology standpoint, we should validate the examples against the coding manual before putting them in the prompt."}],"annotation_note": "Each partner contributes focused, task-relevant knowledge from their specific area of expertise. No one is off-task or merely reacting socially. Contributions are complementary and advance the group's problem-solving. D9 β individual task orientation where each partner's active, engaged contribution drives the group forward."},{"dimension_id": "D9","type": "negative","label": "Off-task social tangent β partner disengages from the task","source": "CollabCode corpus, reconstructed","exchange": [{"speaker": "Gayathri", "text": "By the way, I saw that Yoshua Bengio gave a talk at NeurIPS last week."},{"speaker": "Lara", "text": "Oh really? I missed it."},{"speaker": "Gayathri", "text": "Yes, it was about AI safety. Very interesting apparently."},{"speaker": "Lara", "text": "I'll have to watch it. Anyway..."}],"annotation_note": "Exchange is off-task β a conference talk unrelated to the current work. Neither partner engages with the coding task. Code as NA (off-task, not applicable to any dimension). NOT D9 β D9 requires active engagement with the current task. A tangential topic, even one adjacent to the field, does not qualify as individual task orientation."}]}
298 unmodified lines299300301302303304305306307308309310311312313314298 unmodified lines# Collect and yield as results arriven_received = 0while n_received < len(sections):sr = result_q.get(timeout=_TIMEOUT_MAX_WAIT)stats.results.append(sr)n_received += 1if n_received == len(sections):# All done β compute final statsstats.parallel_wall_s = round(time.perf_counter() - t_wall_start, 1)stats.sequential_est_s = sum(r.wall_time_s for r in stats.results)yield sr, stats298 unmodified lines299300301302303304305306307308309310311312313314315316317318319320298 unmodified lines# Collect and yield as results arriven_received = 0while n_received < len(sections):try:sr = result_q.get(timeout=_TIMEOUT_MAX_WAIT)except queue.Empty:remaining = len(sections) - n_receivedraise RuntimeError(f"Timed out waiting for {remaining} section result(s) after "f"{_TIMEOUT_MAX_WAIT}s. The HF Inference API may be overloaded ""or unreachable. Check your HF_TOKEN and retry.")stats.results.append(sr)n_received += 1if n_received == len(sections):stats.parallel_wall_s = round(time.perf_counter() - t_wall_start, 1)stats.sequential_est_s = sum(r.wall_time_s for r in stats.results)yield sr, stats
123gradio>=6.0.0huggingface_hub>=1.8.0libsass>=0.23.012345678gradio>=6.0.0huggingface_hub>=1.8.0libsass>=0.23.0# Design system compilation (optional β UI works without it via inline styles):# Requires Dart Sass CLI, NOT libsass (libsass does not support @use).# Install: npm install -g sass OR brew install sass/sass/sass# Then run: python static/build.py
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655"""sequential_analysis.py----------------------Sequential analysis of dimension coding data.
Collaborative learning unfolds over time. A flat frequency distributionof dimension codes answers "how much?" but not "in what order?" β yettemporal structure is precisely what distinguishes learning sequences fromrandom collections of behavioral events.
This module computes: 1. Transition matrix β observed frequencies D_i β D_j 2. Transition probabilities β row-conditional P(D_j | D_i) 3. Adjusted residuals (z-scores) β which transitions exceed chance? 4. Lag-sequential analysis β P(D_j | D_i at lag k), k = 1β¦max_lag 5. Sequence statistics β entropy, most common transitions 6. CSV export β tidy format for R / Python / SPSS
Theory and primary references------------------------------Lag-sequential analysis (Sackett 1979; Bakeman & Gottman 1986): Sackett, G. P. (1979). The lag sequential analysis of contingency and cyclicity in behavioral interaction research. In J. D. Osofsky (Ed.), Handbook of infant development. Wiley. β Original framework: conditional probabilities at increasing lags reveal whether a "criterion" behavior predicts what comes next.
Bakeman, R., & Gottman, J. M. (1986). Observing interaction: An introduction to sequential analysis. Cambridge University Press. β Canonical text; defines transition matrices, lag analysis, and the adjusted-residual significance test.
Adjusted residuals (Bakeman & Quera 2011): Bakeman, R., & Quera, V. (2011). Sequential analysis and observational methods for the behavioral sciences. Cambridge University Press, p.96. β Formula: z = (O - E) / sqrt(E Γ (1 β p_i) Γ (1 β p_j)) β |z| > 1.96 β p < .05 (significant) β |z| > 2.58 β p < .01 (highly significant)
Temporal entropy (Shannon 1948): Shannon, C. E. (1948). A mathematical theory of communication. Bell System Technical Journal, 27, 379β423. β H = βΞ£ p_i log2(p_i) measured in bits. β High entropy β many transitions are equally probable (unpredictable). β Low entropy β a few transitions dominate (stereotyped sequence). Applied to collaborative coding: Poquet & Lim (2021). Temporal analytics: Time and sequence in learning (ch. 3). Springer.
Applied CSCL references: JΓ€rvelΓ€ et al. (2016). Temporal and sequential tracing of students' regulated learning during distance learning. Metacognition and Learning. β Demonstrates lag-sequential analysis on CSCL coded data.
Molenaar, P. C. M. (2004). A manifesto on psychology as idiographic science. Measurement, 2(4), 201β218. β Argues for within-person temporal analysis; applies to dyadic data.
Significance note-----------------Adjusted residuals are asymptotically standard normal under the null ofno sequential dependency. They are approximate for sparse cells; usecaution when expected frequency < 5 (flag raised automatically)."""
from __future__ import annotations
import csvimport ioimport jsonimport mathimport refrom pathlib import Pathfrom typing import Optional
DIMENSIONS = ["D1", "D2", "D3", "D4", "D5", "D6", "D7", "D8", "D9", "NS", "NA"]
# Significance thresholds for adjusted residuals (two-tailed z)Z_05 = 1.96 # p < .05Z_01 = 2.58 # p < .01
# Minimum expected frequency below which residuals are flagged as unreliableMIN_EXPECTED = 5
# ---------------------------------------------------------------------------# Sequence construction# ---------------------------------------------------------------------------
def _segment_sort_key(segment_id: str) -> tuple: """ Integer-aware sort key for segment IDs.
Lexicographic sort breaks for non-zero-padded IDs: "s1_ep1" < "s10_ep1" < "s2_ep1" (wrong temporal order)
Splitting on digit runs and casting to int gives correct ordering: ("s", 1, "_ep", 1) < ("s", 2, "_ep", 1) < ("s", 10, "_ep", 1) """ parts = re.split(r"(\d+)", segment_id) return tuple(int(p) if p.isdigit() else p for p in parts)
def build_sequence(codings: list[dict]) -> list[str]: """ Sort coding records into temporal order and return the dimension sequence.
Uses integer-aware sort so non-zero-padded IDs (s1, s2 β¦ s10) are correctly ordered rather than lexicographically misplaced. Segments with missing or empty dimension_id are silently excluded. """ sorted_c = sorted(codings, key=lambda c: _segment_sort_key(c.get("segment_id", ""))) return [c["dimension_id"] for c in sorted_c if c.get("dimension_id")]
# ---------------------------------------------------------------------------# Transition matrix# ---------------------------------------------------------------------------
def compute_transition_matrix( sequence: list[str], categories: list[str],) -> dict[str, dict[str, int]]: """ Count all consecutive pairs D_i β D_j in the sequence.
Only categories in `categories` are tracked; others are ignored. Self-transitions (D_i β D_i) are preserved β they indicate the same dimension dominating adjacent episodes, which is substantively meaningful.
Returns: Nested dict: matrix[from_dim][to_dim] = count """ cat_set = set(categories) matrix = {a: {b: 0 for b in categories} for a in categories}
for i in range(len(sequence) - 1): a, b = sequence[i], sequence[i + 1] if a in cat_set and b in cat_set: matrix[a][b] += 1
return matrix
def compute_transition_probabilities( matrix: dict[str, dict[str, int]], categories: list[str],) -> dict[str, dict[str, float]]: """ Row-normalise the transition matrix to give conditional probabilities. P(D_j | D_i) = count(D_i β D_j) / count(D_i β *)
Rows with zero total (dimension never appears as 'from') return uniform 0.0 for all targets rather than NaN. """ probs: dict[str, dict[str, float]] = {} for a in categories: row_total = sum(matrix.get(a, {}).values()) if row_total == 0: probs[a] = {b: 0.0 for b in categories} else: probs[a] = { b: round(matrix[a][b] / row_total, 4) for b in categories } return probs
# ---------------------------------------------------------------------------# Adjusted residuals (Bakeman & Quera 2011)# ---------------------------------------------------------------------------
def compute_adjusted_residuals( matrix: dict[str, dict[str, int]], categories: list[str],) -> tuple[dict[str, dict[str, float]], list[str]]: """ Compute adjusted residuals for each cell of the transition matrix.
Formula (Bakeman & Quera 2011, p.96): E_ij = N Γ p_i Γ p_j z_ij = (O_ij β E_ij) / sqrt(E_ij Γ (1 β p_i) Γ (1 β p_j))
where: N = total number of transitions p_i = row_total_i / N (marginal probability of state i as 'from') p_j = col_total_j / N (marginal probability of state j as 'to')
Returns: (residuals_dict, warnings_list) residuals_dict: residuals[from][to] = z-score (or 0.0 if undefined) warnings_list : messages for cells where E_ij < MIN_EXPECTED """ N = sum(sum(row.values()) for row in matrix.values()) if N == 0: empty = {a: {b: 0.0 for b in categories} for a in categories} return empty, []
row_totals = {a: sum(matrix.get(a, {}).values()) for a in categories} col_totals = { b: sum(matrix.get(a, {}).get(b, 0) for a in categories) for b in categories }
residuals: dict[str, dict[str, float]] = {} warnings: list[str] = []
for a in categories: residuals[a] = {} p_i = row_totals[a] / N for b in categories: p_j = col_totals[b] / N O = matrix.get(a, {}).get(b, 0) E = N * p_i * p_j
if E < MIN_EXPECTED and (O > 0 or row_totals[a] > 0): warnings.append( f"{a}β{b}: E={E:.1f} < {MIN_EXPECTED}; " f"residual unreliable (sparse cell)" )
denom = E * (1 - p_i) * (1 - p_j) if denom <= 0 or E == 0: residuals[a][b] = 0.0 else: residuals[a][b] = round((O - E) / math.sqrt(denom), 3)
return residuals, warnings
# ---------------------------------------------------------------------------# Lag-sequential analysis (Sackett 1979; Bakeman & Gottman 1986)# ---------------------------------------------------------------------------
def compute_lag_analysis( sequence: list[str], criteria: list[str], max_lag: int = 3,) -> dict[str, dict[str, dict[int, float]]]: """ Compute lag-conditional probabilities for a set of criterion dimensions.
For criterion C and target T at lag k: P(T | C, lag k) = count(C at t, T at t+k) / count(C at t)
This answers: "after seeing dimension C, how likely is dimension T to appear k episodes later?"
Args: sequence : ordered list of dimension codes (temporal order) criteria : dimensions to use as "given" (criterion) max_lag : maximum lag to compute (default 3)
Returns: {criterion: {target: {lag: probability, ...}, ...}, ...}
Literature: Bakeman & Gottman (1986) recommend computing lag analysis for all dimensions that appear frequently enough (n β₯ 10) to give stable probability estimates. """ n = len(sequence) results: dict[str, dict[str, dict[int, float]]] = {}
for criterion in criteria: n_crit = sequence.count(criterion) if n_crit == 0: continue
targets = sorted(set(sequence)) results[criterion] = {t: {} for t in targets}
for lag in range(1, max_lag + 1): # Count how often each target appears at lag k after criterion target_counts: dict[str, int] = {t: 0 for t in targets} valid_origins = 0
for i, code in enumerate(sequence): if code == criterion and i + lag < n: target_counts[sequence[i + lag]] += 1 valid_origins += 1
for t in targets: p = round(target_counts[t] / valid_origins, 4) if valid_origins > 0 else 0.0 results[criterion][t][lag] = p
return results
# ---------------------------------------------------------------------------# Sequence statistics# ---------------------------------------------------------------------------
def compute_sequence_statistics( sequence: list[str], matrix: dict[str, dict[str, int]], residuals: dict[str, dict[str, float]], categories: list[str],) -> dict: """ Summary statistics for the coded sequence.
Returns: n_episodes : total episode count n_transitions : n_episodes β 1 categories_used : dimensions that appear at least once frequency : raw count per dimension proportion : proportion per dimension transition_entropy : Shannon entropy of the transition distribution most_common : top-5 (from, to) transitions by count significant_pos : transitions with z > 1.96 (more common than chance) significant_neg : transitions with z < β1.96 (less common than chance) """ n = len(sequence) N_trans = max(n - 1, 0)
freq = {d: sequence.count(d) for d in categories if sequence.count(d) > 0} prop = {d: round(freq[d] / n, 4) for d in freq} if n > 0 else {} cats_used = sorted(freq.keys(), key=lambda d: -freq[d])
# Shannon entropy of the row-conditional transition distribution # H = βΞ£ p_ij log2(p_ij) averaged over all from-states entropy_sum = 0.0 entropy_n = 0 for a in categories: row_total = sum(matrix.get(a, {}).values()) if row_total == 0: continue h = 0.0 for b in categories: p = matrix.get(a, {}).get(b, 0) / row_total if p > 0: h -= p * math.log2(p) entropy_sum += h entropy_n += 1 transition_entropy = round(entropy_sum / entropy_n, 4) if entropy_n > 0 else 0.0
# Most common transitions (by count) all_pairs = [ (a, b, matrix.get(a, {}).get(b, 0)) for a in categories for b in categories if matrix.get(a, {}).get(b, 0) > 0 ] all_pairs.sort(key=lambda x: -x[2]) most_common = [ {"from": a, "to": b, "count": cnt} for a, b, cnt in all_pairs[:8] ]
# Significant transitions sig_pos = [] sig_neg = [] for a in categories: for b in categories: z = residuals.get(a, {}).get(b, 0.0) cnt = matrix.get(a, {}).get(b, 0) entry = {"from": a, "to": b, "count": cnt, "z": z} if z >= Z_05: sig_pos.append(entry) elif z <= -Z_05: sig_neg.append(entry)
sig_pos.sort(key=lambda x: -x["z"]) sig_neg.sort(key=lambda x: x["z"])
return { "n_episodes": n, "n_transitions": N_trans, "categories_used": cats_used, "frequency": freq, "proportion": prop, "transition_entropy": transition_entropy, "entropy_max": round(math.log2(len(cats_used)), 4) if len(cats_used) > 1 else 0.0, "most_common": most_common, "significant_pos": sig_pos, "significant_neg": sig_neg, }
# ---------------------------------------------------------------------------# Main entry point# ---------------------------------------------------------------------------
def run_sequential_analysis( codings: list[dict], max_lag: int = 3, min_freq_for_lag: int = 3,) -> dict: """ Full sequential analysis on a list of coding dicts.
Args: codings : list of coding dicts from a coding_RX.json file max_lag : maximum lag for lag analysis (default 3) min_freq_for_lag : minimum times a dimension must appear to be used as a criterion in lag analysis (default 3)
Returns a dict with all computed structures, ready for display or export. """ sequence = build_sequence(codings) if len(sequence) < 2: return {"error": "Fewer than 2 coded segments β cannot compute transitions."}
cats_used = sorted({d for d in sequence if d in DIMENSIONS})
matrix = compute_transition_matrix(sequence, cats_used) probs = compute_transition_probabilities(matrix, cats_used) residuals, sparse_warnings = compute_adjusted_residuals(matrix, cats_used) stats = compute_sequence_statistics(sequence, matrix, residuals, cats_used)
# Lag analysis only for frequent-enough criteria lag_criteria = [d for d in cats_used if sequence.count(d) >= min_freq_for_lag] lag_analysis = compute_lag_analysis(sequence, lag_criteria, max_lag)
return { "sequence": sequence, "categories_used": cats_used, "transition_matrix": matrix, "transition_probs": probs, "adjusted_residuals": residuals, "sparse_warnings": sparse_warnings, "lag_analysis": lag_analysis, "statistics": stats, }
# ---------------------------------------------------------------------------# Export# ---------------------------------------------------------------------------
def to_csv(analysis: dict) -> str: """ Export the transition matrix to a tidy CSV compatible with R, Python, SPSS.
Columns: from, to, count, probability, adjusted_residual, sig_05, sig_01 (boolean significance flags)
R usage: df <- read.csv("transitions.csv") library(tidyverse) df %>% filter(sig_05) %>% arrange(desc(adjusted_residual))
Python (pandas): df = pd.read_csv("transitions.csv") df[df.sig_05].sort_values("adjusted_residual", ascending=False) """ cats = analysis.get("categories_used", []) mat = analysis.get("transition_matrix", {}) probs = analysis.get("transition_probs", {}) res = analysis.get("adjusted_residuals", {})
buf = io.StringIO() w = csv.writer(buf) w.writerow(["from", "to", "count", "probability", "adjusted_residual", "sig_05", "sig_01"]) for a in cats: for b in cats: cnt = mat.get(a, {}).get(b, 0) prob = probs.get(a, {}).get(b, 0.0) z = res.get(a, {}).get(b, 0.0) w.writerow([a, b, cnt, f"{prob:.4f}", f"{z:.4f}", str(abs(z) >= Z_05), str(abs(z) >= Z_01)]) return buf.getvalue()
def lag_to_csv(analysis: dict) -> str: """ Export lag-sequential probabilities to CSV.
Columns: criterion, target, lag, probability """ lag_data = analysis.get("lag_analysis", {}) buf = io.StringIO() w = csv.writer(buf) w.writerow(["criterion", "target", "lag", "probability"]) for criterion, targets in sorted(lag_data.items()): for target, lags in sorted(targets.items()): for lag, prob in sorted(lags.items()): w.writerow([criterion, target, lag, f"{prob:.4f}"]) return buf.getvalue()
# ---------------------------------------------------------------------------# HTML rendering helpers (used by app.py)# ---------------------------------------------------------------------------
def render_transition_matrix_html(analysis: dict) -> str: """ Render the transition matrix as a color-coded HTML table.
Color coding (Bakeman & Quera 2011 adjusted residuals): Dark green : z > 2.58 (p < .01, significantly common) Light green : z > 1.96 (p < .05, significantly common) Dark red : z < β2.58 (p < .01, significantly rare) Light red : z < β1.96 (p < .05, significantly rare) Light gray : |z| β€ 1.96 (not significant) """ cats = analysis.get("categories_used", []) mat = analysis.get("transition_matrix", {}) prob = analysis.get("transition_probs", {}) res = analysis.get("adjusted_residuals", {}) stat = analysis.get("statistics", {})
if not cats: return "<p><em>No sequence data available.</em></p>"
n_eps = stat.get("n_episodes", 0) n_trans = stat.get("n_transitions", 0) entropy = stat.get("transition_entropy", 0.0) ent_max = stat.get("entropy_max", 0.0) ent_pct = round(entropy / ent_max * 100, 0) if ent_max > 0 else 0
# Summary bar summary = ( f'<div style="display:flex;gap:16px;flex-wrap:wrap;margin-bottom:12px;' f'font-size:0.82em;color:#64748b">' f'<span>{n_eps} episodes Β· {n_trans} transitions</span>' f'<span>Entropy: <strong style="color:#4338ca">{entropy:.3f}</strong> ' f'bits / max {ent_max:.3f} ({ent_pct:.0f}% of max)</span>' f'</div>' )
# Legend legend = ( '<div style="display:flex;gap:8px;flex-wrap:wrap;margin-bottom:8px;font-size:0.75em">' '<span style="background:#d1fae5;padding:2px 6px;border-radius:3px">z>2.58 p<.01 β</span>' '<span style="background:#ecfdf5;padding:2px 6px;border-radius:3px">z>1.96 p<.05 β</span>' '<span style="background:#f8fafc;padding:2px 6px;border-radius:3px">n.s.</span>' '<span style="background:#fee2e2;padding:2px 6px;border-radius:3px">z<β1.96 p<.05 β</span>' '<span style="background:#fca5a5;padding:2px 6px;border-radius:3px">z<β2.58 p<.01 β</span>' '<div style="color:#94a3b8;margin-left:4px">Each cell: count / P(to|from) / z</div>' '</div>' )
# Header row th_style = ( "padding:5px 8px;background:#f1f5f9;font-weight:700;font-size:0.78em;" "text-align:center;border:1px solid #e2e8f0;color:#475569" ) header_cells = "".join(f'<th style="{th_style}">{c}</th>' for c in cats) header = ( f'<tr>' f'<th style="{th_style};text-align:left">From \\ To</th>' f'{header_cells}' f'</tr>' )
# Data rows rows = "" for a in cats: freq = stat.get("frequency", {}).get(a, 0) row_th = ( f'<th style="{th_style};text-align:left;white-space:nowrap">' f'{a} <span style="color:#94a3b8;font-weight:400">({freq})</span></th>' ) cells = "" for b in cats: cnt = mat.get(a, {}).get(b, 0) p = prob.get(a, {}).get(b, 0.0) z = res.get(a, {}).get(b, 0.0)
# Cell background by z-score if z >= Z_01: bg, col = "#d1fae5", "#065f46" elif z >= Z_05: bg, col = "#ecfdf5", "#059669" elif z <= -Z_01: bg, col = "#fee2e2", "#991b1b" elif z <= -Z_05: bg, col = "#fef2f2", "#dc2626" else: bg, col = "#f8fafc", "#94a3b8"
# Diagonal (self-transition) slightly different styling diag_style = "border-left:2px solid #e2e8f0;" if a == b else ""
cells += ( f'<td style="padding:5px 7px;background:{bg};color:{col};' f'text-align:center;border:1px solid #e2e8f0;{diag_style}' f'font-size:0.78em;min-width:52px">' f'<div style="font-weight:700">{cnt}</div>' f'<div style="opacity:0.85">{p:.2f}</div>' f'<div style="font-size:0.85em">z={z:.1f}</div>' f'</td>' )
rows += f'<tr>{row_th}{cells}</tr>'
table = ( f'<div style="overflow-x:auto">' f'<table style="border-collapse:collapse;font-size:0.8em">' f'{header}{rows}</table></div>' )
return summary + legend + table
def render_significant_transitions_html(analysis: dict) -> str: """Render the significant-transitions summary in plain text.""" stat = analysis.get("statistics", {}) sig_pos = stat.get("significant_pos", []) sig_neg = stat.get("significant_neg", [])
if not sig_pos and not sig_neg: return ( '<div style="color:#94a3b8;font-size:0.85em;font-style:italic">' 'No significant transitions detected (all |z| β€ 1.96). ' 'This may reflect a short sequence or uniform transitions.</div>' )
def _row(entry: dict, direction: str, col: str) -> str: return ( f'<div style="display:flex;gap:12px;align-items:baseline;' f'padding:4px 0;border-bottom:1px solid #f1f5f9">' f'<span style="font-weight:700;color:{col}">' f'{entry["from"]} β {entry["to"]}</span>' f'<span style="color:#64748b;font-size:0.85em">' f'count={entry["count"]} z={entry["z"]:.2f} {direction}</span>' f'</div>' )
html = "" if sig_pos: html += ( '<div style="font-size:0.75em;font-weight:700;text-transform:uppercase;' 'letter-spacing:0.07em;color:#059669;margin-bottom:4px">' f'Significantly common ({len(sig_pos)})</div>' ) html += "".join(_row(e, "β more than chance", "#065f46") for e in sig_pos)
if sig_neg: html += ( '<div style="font-size:0.75em;font-weight:700;text-transform:uppercase;' 'letter-spacing:0.07em;color:#dc2626;margin:10px 0 4px">' f'Significantly rare ({len(sig_neg)})</div>' ) html += "".join(_row(e, "β less than chance", "#991b1b") for e in sig_neg)
return html
# ---------------------------------------------------------------------------# Load from file# ---------------------------------------------------------------------------
def load_and_analyse(coding_path: Path, max_lag: int = 3) -> dict: """ Load a coding_RX.json file and run the full sequential analysis. Convenience wrapper for use in app.py callbacks. """ data = json.loads(coding_path.read_text(encoding="utf-8")) codings = data.get("codings", []) if not codings: return {"error": "No codings found in file."} return run_sequential_analysis(codings, max_lag=max_lag)agent0_sectioner.py+2
agent1a_boundary.py+2
agent1b_coder.py+2
agent2_learner.py+51-21
app.py+188-9
library/tier1_core/coding_rules.json+2-2
library/tier1_core/examples.json+331-6
pipeline.py+11-5
requirements.txt+5
sequential_analysis.pyAdded+655