""" sequential_analysis.py ---------------------- Sequential analysis of dimension coding data. Collaborative learning unfolds over time. A flat frequency distribution of dimension codes answers "how much?" but not "in what order?" — yet temporal structure is precisely what distinguishes learning sequences from random 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 of no sequential dependency. They are approximate for sparse cells; use caution when expected frequency < 5 (flag raised automatically). """ from __future__ import annotations import csv import io import json import math import re from pathlib import Path from 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 < .05 Z_01 = 2.58 # p < .01 # Minimum expected frequency below which residuals are flagged as unreliable MIN_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 "
No sequence data available.
" 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'