Spaces:
Sleeping

File size: 24,443 Bytes
2a95ee9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
"""
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 "<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&lt;.01 ↑</span>'
        '<span style="background:#ecfdf5;padding:2px 6px;border-radius:3px">z>1.96 p&lt;.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&lt;βˆ’1.96 p&lt;.05 ↓</span>'
        '<span style="background:#fca5a5;padding:2px 6px;border-radius:3px">z&lt;βˆ’2.58 p&lt;.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)