File size: 33,327 Bytes
af4f316
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Validate and summarize the paired Ablation4 test predictions."""

from __future__ import annotations

import argparse
import csv
import hashlib
import json
import math
import sys
from collections import Counter
from datetime import datetime, timezone
from pathlib import Path

import numpy as np


EXPERIMENT = Path(__file__).resolve().parent.parent
FROZEN = Path(__file__).resolve().parent / "frozen_scoring"   # scoring code of the evaluation release
sys.path.insert(0, str(FROZEN / "evaluation"))
from score_predictions import key, units_for
from scoring_metrics import metrics, metrics_from_counts, parse_jsonish

CONDITIONS = ("original", "early", "late")
DOMAINS = ("essays", "news", "reports", "abstracts")
METHODS = {
    "desklib": "document", "radar": "document", "fast-detectgpt": "document",
    "gpt54-sent-conf-none": "sentence",
}
METHOD_DIRECTORIES = {method: method for method in METHODS}
METHOD_DIRECTORIES["gpt54-sent-conf-none"] = "gpt54"
COMPRESSION = {"original": 4, "early": 2, "late": 6}
METRICS = ("accuracy", "f1_ai", "macro_f1", "fnr")
BOOTSTRAPS = 2000
SEED = 42
EXPECTED_DOMAIN_ROWS = {"essays": 265, "news": 243, "reports": 225, "abstracts": 297}
EXPECTED_SOURCE_COUNTS = {"essays": 30, "news": 27, "reports": 25, "abstracts": 33}


def sha256(path):
    digest = hashlib.sha256()
    with Path(path).open("rb") as stream:
        for block in iter(lambda: stream.read(1024 * 1024), b""):
            digest.update(block)
    return digest.hexdigest()


def json_write(path, value):
    path.write_text(json.dumps(value, indent=2, ensure_ascii=False, allow_nan=False) + "\n", encoding="utf-8")


def csv_write(path, rows):
    if not rows:
        raise ValueError(f"No rows for {path}")
    fields = list(dict.fromkeys(name for row in rows for name in row))
    with path.open("w", encoding="utf-8", newline="") as stream:
        writer = csv.DictWriter(stream, fieldnames=fields)
        writer.writeheader()
        writer.writerows(rows)


def prediction_path(method, condition, domain):
    cell = EXPERIMENT / METHOD_DIRECTORIES[method] / "full" / condition / domain
    if METHODS[method] == "document":
        cell /= "test"
    return cell / "predictions.jsonl"


def read_predictions(path):
    result = {}
    if not path.exists():
        return result
    with path.open(encoding="utf-8") as stream:
        for line_number, line in enumerate(stream, 1):
            if not line.strip():
                continue
            try:
                row = json.loads(line)
            except json.JSONDecodeError as error:
                raise ValueError(f"{path}:{line_number}: invalid JSON") from error
            row_key = key(row)
            if row_key in result:
                raise ValueError(f"{path}: duplicate prediction {row_key}")
            result[row_key] = row
    return result


def row_digest(row):
    return hashlib.sha256(json.dumps(row, sort_keys=True, ensure_ascii=False,
                                    separators=(",", ":")).encode()).hexdigest()


def check_input(row):
    if row["split"] != "test":
        raise ValueError("Only the supplied test split belongs to this analysis")
    sentences = parse_jsonish(row["sentences"])
    sentence_truth = parse_jsonish(row["sent_labels"])
    tokens = parse_jsonish(row["tokens"])
    word_truth = parse_jsonish(row["tok_labels"])
    if not sentences or any(not isinstance(s, str) or not s.strip() for s in sentences):
        raise ValueError("Invalid supplied sentence sequence")
    if len(sentences) != len(sentence_truth) or len(tokens) != len(word_truth):
        raise ValueError("Canonical text/GT unit counts differ")
    if any(type(t) is not int or t not in (0, 1) for t in sentence_truth + word_truth):
        raise ValueError("Canonical truth must contain integer binary labels")
    if tokens != row["text_clean"].split():
        raise ValueError("Canonical tokens differ from actual whitespace words")
    if " ".join(" ".join(sentences).split()) != " ".join(row["text_clean"].split()):
        raise ValueError("Canonical sentences do not cover the body in order")
    if int(float(row["num_sentences"])) != len(sentences):
        raise ValueError("Canonical sentence count differs from supplied sequence")
    for name, actual in (("AI_sent_ratio", sum(sentence_truth) / len(sentence_truth)),
                         ("AI_token_ratio", sum(word_truth) / len(word_truth))):
        if not math.isclose(float(row[name]), actual, abs_tol=1e-12, rel_tol=0):
            raise ValueError(f"Canonical {name} differs from actual truth")
    return sentences, sentence_truth, tokens, word_truth


def canonical_inputs():
    canonical, identity, coverage = {}, [], []
    for condition in CONDITIONS:
        for domain in DOMAINS:
            path = EXPERIMENT / "paired" / condition / (domain + ".csv")
            with path.open(encoding="utf-8", newline="") as stream:
                rows = list(csv.DictReader(stream))
            by_key = {}
            for row in rows:
                row_key = key(row)
                if row_key in by_key:
                    raise ValueError(f"Duplicate canonical key {condition}/{domain}/{row_key}")
                sentences, sentence_truth, tokens, word_truth = check_input(row)
                by_key[row_key] = row
                coverage.append({
                    "condition": condition, "domain": domain, "essay_id": row_key[0],
                    "version": row_key[1], "split": "test", "operation": row["operation"],
                    "compression_version": f"v{COMPRESSION[condition]}",
                    "scheduled_sentence_coverage": float(row["C_sent_target"]),
                    "n_sentences": len(sentences), "n_ai_sentences": sum(sentence_truth),
                    "sentence_ai_coverage": sum(sentence_truth) / len(sentence_truth),
                    "n_words": len(tokens), "n_ai_words": sum(word_truth),
                    "word_ai_coverage": sum(word_truth) / len(word_truth),
                    "n_characters": len(row["text_clean"]),
                })
            if len(rows) != EXPECTED_DOMAIN_ROWS[domain]:
                raise ValueError(f"Unexpected canonical count {condition}/{domain}: {len(rows)}")
            expected_versions = {f"v{i}": EXPECTED_SOURCE_COUNTS[domain] - int(domain == "essays" and i >= 4)
                                 for i in range(9)}
            if dict(Counter(r["version"] for r in rows)) != expected_versions:
                raise ValueError(f"Unexpected version counts {condition}/{domain}")
            canonical[condition, domain] = by_key
            identity.append({"kind": "canonical", "path": str(path), "sha256": sha256(path), "records": len(rows)})
    for domain in DOMAINS:
        reference = canonical["original", domain]
        for condition in CONDITIONS[1:]:
            if canonical[condition, domain].keys() != reference.keys():
                raise ValueError("Three-condition matched key sets differ")
            for row_key, row in reference.items():
                if row_key[1] == "v0" and row["text_clean"] != canonical[condition, domain][row_key]["text_clean"]:
                    raise ValueError("Matched v0 bodies differ across conditions")
    return canonical, identity, coverage


def validated_predictions(canonical):
    records, missing, identities = {}, [], []
    sys.path.insert(0, str(FROZEN))
    from evaluate.aes.sentence_level_v0v8 import SENTENCE_CONF_PROMPT
    for method, level in METHODS.items():
        for condition in CONDITIONS:
            for domain in DOMAINS:
                path = prediction_path(method, condition, domain)
                predictions = read_predictions(path)
                truth = canonical[condition, domain]
                extras = predictions.keys() - truth.keys()
                if extras:
                    raise ValueError(f"Unknown prediction keys {path}: {sorted(extras)}")
                absent = truth.keys() - predictions.keys()
                if absent:
                    missing.append({"method": method, "condition": condition, "domain": domain,
                                    "path": str(path), "expected": len(truth), "found": len(predictions),
                                    "missing_count": len(absent)})
                if path.exists():
                    identities.append({"kind": "predictions", "method": method, "condition": condition,
                                       "domain": domain, "path": str(path), "sha256": sha256(path),
                                       "records": len(predictions)})
                for row_key, prediction in predictions.items():
                    row = truth[row_key]
                    if any(prediction.get(name) != value for name, value in row.items()):
                        raise ValueError(f"Saved input fields differ: {path}: {row_key}")
                    if level == "document":
                        if prediction.get("detection_detector") != method:
                            raise ValueError("Native document method identity differs")
                    else:
                        gpt = prediction["gpt"]
                        if prediction.get("input_row_sha256") != row_digest(row):
                            raise ValueError("GPT input row identity differs")
                        if gpt.get("variant") != method or gpt.get("model") != "gpt-5.4" or gpt.get("reasoning_effort") != "none":
                            raise ValueError("GPT model/settings differ from the selected method")
                        sentences = parse_jsonish(row["sentences"])
                        prompt = SENTENCE_CONF_PROMPT.format(
                            numbered_sentences="\n".join(f"[{i + 1}] {s}" for i, s in enumerate(sentences)),
                            num_sentences=len(sentences))
                        if gpt.get("prompt") != prompt:
                            raise ValueError("GPT prompt differs from the frozen sentence template")
                    y_true, y_pred, y_score = units_for(prediction, row, level, method)
                    if level == "document" and (len(y_true) != 1 or not 0 <= y_score[0] <= 1):
                        raise ValueError("Invalid native document probability/unit count")
                    if level == "document" and y_pred[0] != int(y_score[0] >= 0.5):
                        raise ValueError("Native document binary label differs from its configured threshold")
                    tp = sum(t == 1 and p == 1 for t, p in zip(y_true, y_pred))
                    tn = sum(t == 0 and p == 0 for t, p in zip(y_true, y_pred))
                    fp = sum(t == 0 and p == 1 for t, p in zip(y_true, y_pred))
                    fn = sum(t == 1 and p == 0 for t, p in zip(y_true, y_pred))
                    records[method, condition, domain, *row_key] = {
                        "truth": y_true, "pred": y_pred, "scores": y_score,
                        "counts": np.array([tp, tn, fp, fn], dtype=np.int64),
                    }
    return records, missing, identities


def items_for(records, method, condition, scope, version, cohort=None):
    domains = DOMAINS if scope == "pooled" else (scope,)
    selected = {}
    for (m, c, domain, essay_id, v), value in records.items():
        source = domain, essay_id
        if (m, c, v) == (method, condition, version) and domain in domains and (cohort is None or source in cohort):
            selected[source] = value
    return selected


def combined_metrics(items):
    truths, predictions, scores = [], [], []
    for value in items.values():
        truths.extend(value["truth"])
        predictions.extend(value["pred"])
        scores.extend(value["scores"])
    native = metrics(truths, predictions, scores)
    count_metrics = metrics_from_counts(*(sum((value["counts"] for value in items.values()), np.zeros(4, dtype=np.int64)).tolist()))
    for name in METRICS:
        if native[name] != count_metrics[name]:
            raise ValueError(f"Confusion aggregation differs from frozen metric: {name}")
    return native


def summaries(records):
    rows = []
    for method, level in METHODS.items():
        for condition in CONDITIONS:
            for scope in (*DOMAINS, "pooled"):
                for i in range(9):
                    version = f"v{i}"
                    items = items_for(records, method, condition, scope, version)
                    raw = combined_metrics(items)
                    rows.append({"method": method, "level": level, "domain": scope,
                                 "condition": condition, "version": version, "split": "test",
                                 "compression_version": f"v{COMPRESSION[condition]}",
                                 "n_records": len(items), **raw})
    return rows


def vector_metrics(counts):
    values = np.asarray(counts, dtype=float)
    tp, tn, fp, fn = [values[..., i] for i in range(4)]
    n, pos = tp + tn + fp + fn, tp + fn
    ai_denom, human_denom = 2 * tp + fp + fn, 2 * tn + fp + fn
    f_ai = np.divide(2 * tp, ai_denom, out=np.zeros_like(tp), where=ai_denom != 0)
    f_human = np.divide(2 * tn, human_denom, out=np.zeros_like(tn), where=human_denom != 0)
    return {
        "accuracy": np.divide(tp + tn, n, out=np.full_like(tp, np.nan), where=n != 0),
        "f1_ai": f_ai, "macro_f1": (f_ai + f_human) / 2,
        "fnr": np.divide(fn, pos, out=np.full_like(fn, np.nan), where=pos != 0),
    }


class SourceBootstrap:
    def __init__(self):
        self.cache = {}

    def weights(self, cohort):
        ordered = tuple(sorted(cohort))
        if ordered not in self.cache:
            rng = np.random.default_rng(SEED)
            result = np.zeros((BOOTSTRAPS, len(ordered)), dtype=np.int16)
            for domain in DOMAINS:
                indices = np.array([i for i, source in enumerate(ordered) if source[0] == domain])
                if indices.size:
                    draws = rng.integers(0, len(indices), size=(BOOTSTRAPS, len(indices)))
                    for replicate, drawn in enumerate(draws):
                        result[replicate, indices] = np.bincount(drawn, minlength=len(indices))
            self.cache[ordered] = result
        return ordered, self.cache[ordered]


def weighted_auroc(scores, truths, sources, ordered, weights):
    source_index = {source: i for i, source in enumerate(ordered)}
    sorted_units = sorted(zip(scores, truths, sources), key=lambda value: value[0])
    negative_before = np.zeros(BOOTSTRAPS, dtype=float)
    numerator = np.zeros(BOOTSTRAPS, dtype=float)
    positive_total = np.zeros(BOOTSTRAPS, dtype=float)
    index = 0
    while index < len(sorted_units):
        stop = index + 1
        while stop < len(sorted_units) and sorted_units[stop][0] == sorted_units[index][0]:
            stop += 1
        positive = np.zeros(BOOTSTRAPS, dtype=float)
        negative = np.zeros(BOOTSTRAPS, dtype=float)
        for _, truth, source in sorted_units[index:stop]:
            if truth:
                positive += weights[:, source_index[source]]
            else:
                negative += weights[:, source_index[source]]
        numerator += positive * (negative_before + 0.5 * negative)
        negative_before += negative
        positive_total += positive
        index = stop
    denominator = positive_total * negative_before
    return np.divide(numerator, denominator, out=np.full(BOOTSTRAPS, np.nan), where=denominator != 0)


def doc_auc_inputs(records, method, condition, scope, version, cohort=None):
    baseline = items_for(records, method, condition, scope, "v0", cohort)
    target = items_for(records, method, condition, scope, version, cohort)
    matched = baseline.keys() & target.keys()
    scores, truth, sources = [], [], []
    for source in sorted(matched):
        for item in (baseline[source], target[source]):
            scores.extend(item["scores"])
            truth.extend(item["truth"])
            sources.append(source)
    return scores, truth, sources, matched


def interval(values):
    valid = np.asarray(values)[np.isfinite(values)]
    if not len(valid):
        return None, None, 0
    lo, hi = np.percentile(valid, [2.5, 97.5])
    return float(lo), float(hi), int(len(valid))


def matched_auc_rows(records, bootstrap):
    from scoring_metrics import auroc_score
    rows = []
    for method, level in METHODS.items():
        if level != "document":
            continue
        for condition in CONDITIONS:
            for scope in (*DOMAINS, "pooled"):
                for i in range(1, 9):
                    version = f"v{i}"
                    scores, truth, sources, cohort = doc_auc_inputs(records, method, condition, scope, version)
                    ordered, weights = bootstrap.weights(cohort)
                    raw = auroc_score(truth, scores)
                    native_weighted = weighted_auroc(scores, truth, sources, ordered, np.ones((BOOTSTRAPS, len(ordered)), dtype=np.int16))[0]
                    if not math.isclose(raw, float(native_weighted), abs_tol=1e-12):
                        raise ValueError("Weighted matched AUROC differs from the native rank calculation")
                    lo, hi, valid = interval(weighted_auroc(scores, truth, sources, ordered, weights))
                    rows.append({"method": method, "level": "document", "domain": scope,
                                 "condition": condition, "baseline": "v0", "version": version,
                                 "n_source_pairs": len(cohort), "n_units": len(truth),
                                 "n_pos_ai": sum(truth), "n_neg_human": len(truth) - sum(truth),
                                 "auroc": raw, "ci95_lower": lo, "ci95_upper": hi,
                                 "valid_bootstraps": valid})
    return rows


def paired_differences(records, bootstrap):
    from scoring_metrics import auroc_score
    rows = []
    for method, level in METHODS.items():
        for scope in (*DOMAINS, "pooled"):
            for i in range(9):
                version = f"v{i}"
                original = items_for(records, method, "original", scope, version)
                for condition in CONDITIONS[1:]:
                    comparison = items_for(records, method, condition, scope, version)
                    cohort = original.keys() & comparison.keys()
                    ordered, weights = bootstrap.weights(cohort)
                    counts_a = np.stack([original[source]["counts"] for source in ordered])
                    counts_b = np.stack([comparison[source]["counts"] for source in ordered])
                    raw_a, raw_b = vector_metrics(counts_a.sum(axis=0)), vector_metrics(counts_b.sum(axis=0))
                    boot_a, boot_b = vector_metrics(weights @ counts_a), vector_metrics(weights @ counts_b)
                    for metric in METRICS:
                        defined = not (metric in ("f1_ai", "fnr") and np.sum(counts_a[:, [0, 3]]) == 0)
                        lo, hi, valid = interval(boot_b[metric] - boot_a[metric]) if defined else (None, None, 0)
                        rows.append({"method": method, "level": level, "domain": scope,
                                     "condition": condition, "reference_condition": "original",
                                     "version": version, "metric": metric, "n_source_pairs": len(cohort),
                                     "n_units_reference": int(counts_a.sum()), "n_units_comparison": int(counts_b.sum()),
                                     "reference": float(raw_a[metric]) if defined else None,
                                     "comparison": float(raw_b[metric]) if defined else None,
                                     "difference": float(raw_b[metric] - raw_a[metric]) if defined else None,
                                     "ci95_lower": lo, "ci95_upper": hi, "valid_bootstraps": valid})
                    if level == "document" and i:
                        s_a, t_a, k_a, cohort_a = doc_auc_inputs(records, method, "original", scope, version, cohort)
                        s_b, t_b, k_b, cohort_b = doc_auc_inputs(records, method, condition, scope, version, cohort)
                        if cohort_a != cohort or cohort_b != cohort:
                            raise ValueError("Matched AUROC baseline does not cover the comparison cohort")
                        value_a, value_b = auroc_score(t_a, s_a), auroc_score(t_b, s_b)
                        boot_auc_a = weighted_auroc(s_a, t_a, k_a, ordered, weights)
                        boot_auc_b = weighted_auroc(s_b, t_b, k_b, ordered, weights)
                        lo, hi, valid = interval(boot_auc_b - boot_auc_a)
                        rows.append({"method": method, "level": level, "domain": scope,
                                     "condition": condition, "reference_condition": "original",
                                     "baseline": "v0", "version": version, "metric": "v0_vs_vi_auroc",
                                     "n_source_pairs": len(cohort), "n_units_reference": len(t_a),
                                     "n_units_comparison": len(t_b), "reference": value_a, "comparison": value_b,
                                     "difference": value_b - value_a, "ci95_lower": lo, "ci95_upper": hi,
                                     "valid_bootstraps": valid})
    return rows


def coverage_summary(coverage):
    rows = []
    for condition in CONDITIONS:
        for scope in (*DOMAINS, "pooled"):
            for i in range(9):
                version = f"v{i}"
                cells = [r for r in coverage if r["condition"] == condition and r["version"] == version
                         and (scope == "pooled" or r["domain"] == scope)]
                summary = {"condition": condition, "domain": scope, "version": version,
                           "compression_version": f"v{COMPRESSION[condition]}", "n_records": len(cells),
                           "sentence_ai_coverage_micro": sum(r["n_ai_sentences"] for r in cells) / sum(r["n_sentences"] for r in cells),
                           "word_ai_coverage_micro": sum(r["n_ai_words"] for r in cells) / sum(r["n_words"] for r in cells)}
                for field in ("sentence_ai_coverage", "word_ai_coverage", "n_sentences", "n_words", "n_characters"):
                    values = np.array([r[field] for r in cells], dtype=float)
                    for name, value in (("mean", values.mean()), ("median", np.median(values)),
                                        ("q25", np.percentile(values, 25)), ("q75", np.percentile(values, 75)),
                                        ("min", values.min()), ("max", values.max())):
                        summary[field + "_" + name] = float(value)
                rows.append(summary)
    return rows


def present_metric(row, metric):
    if metric == "f1_ai" and row["n_pos_ai"] == 0:
        return None
    return row[metric]


def plots(rows, output):
    import matplotlib
    matplotlib.use("Agg")
    import matplotlib.pyplot as plt
    destination = output / "figures"
    destination.mkdir(exist_ok=True)
    colors = {"original": "#1f77b4", "early": "#d95f02", "late": "#228833"}
    for method in METHODS:
        for scope in (*DOMAINS, "pooled"):
            fig, axes = plt.subplots(2, 2, figsize=(10, 7), sharex=True, sharey=True)
            for axis, metric in zip(axes.flat, METRICS):
                for condition in CONDITIONS:
                    cells = sorted((r for r in rows if r["method"] == method and r["domain"] == scope and r["condition"] == condition),
                                   key=lambda r: int(r["version"][1:]))
                    values = [present_metric(r, metric) for r in cells]
                    values = [float("nan") if value is None else value for value in values]
                    axis.plot(range(9), values, marker="o", markersize=3, color=colors[condition],
                              label=f"{condition} (compression v{COMPRESSION[condition]})")
                    position = COMPRESSION[condition]
                    axis.scatter([position], [values[position]], marker="D", s=45, color=colors[condition], zorder=4)
                    axis.axvline(position, color=colors[condition], linestyle=":", alpha=0.22, linewidth=1)
                axis.set_title({"accuracy": "Accuracy", "f1_ai": "F1-AI", "macro_f1": "Macro-F1", "fnr": "FNR"}[metric])
                axis.set_xticks(range(9), [f"v{i}" for i in range(9)])
                axis.set_ylim(-0.03, 1.03)
                axis.grid(alpha=0.15)
            for axis in axes[-1]:
                axis.set_xlabel("Revision version")
            handles, labels = axes[0, 0].get_legend_handles_labels()
            fig.legend(handles, labels, loc="lower center", ncol=3, fontsize=8)
            fig.suptitle(f"{method} | {scope} | supplied test split")
            fig.tight_layout(rect=(0, 0.05, 1, 0.94))
            stem = destination / f"{method}_{scope}"
            fig.savefig(stem.with_suffix(".png"), dpi=180)
            fig.savefig(stem.with_suffix(".pdf"))
            plt.close(fig)


def markdown_results(rows, auc_rows):
    lines = ["# Compression-position ablation", "", "Results on the supplied test split. Scores are percentages; document AUROC uses matched v0-versus-vi records.", ""]
    for method, level in METHODS.items():
        lines.extend([f"## {method} ({level})", "", "| Condition | Version | Documents | Units | Accuracy | F1-AI | Macro-F1 | FNR | Matched document AUROC |",
                      "|---|---|---:|---:|---:|---:|---:|---:|---:|"])
        for condition in CONDITIONS:
            for row in rows:
                if (row["method"], row["domain"], row["condition"]) != (method, "pooled", condition):
                    continue
                values = [present_metric(row, name) for name in METRICS]
                auroc = next((r["auroc"] for r in auc_rows if (r["method"], r["domain"], r["condition"], r["version"])
                              == (method, "pooled", condition, row["version"])), None)
                formatted = ["N/A" if value is None else f"{100 * value:.2f}" for value in (*values, auroc)]
                lines.append(f"| {condition} | {row['version']} | {row['n_records']} | {row['n_units']} | " + " | ".join(formatted) + " |")
        lines.append("")
    return "\n".join(lines) + "\n"


def readme():
    return """# Ablation4 compression-position results

The experiment compares compression at v4 (`original`), v2 (`early`), and v6 (`late`) on the supplied test split. It uses 115 source documents: 30 essays, 27 news articles, 25 reports, and 33 abstracts. The three conditions share 1,030 retained document/version records each. At v0–v3 there are 115 documents per condition; at v4–v8 there are 114. Rows are matched by domain, source ID, and version.

## Methods

GPT-5.4 returns sentence labels and probabilities using the frozen sentence prompt, reasoning effort `none`, and a 2,048-token output limit. Binary labels are used directly. Desklib, RADAR, and Fast-DetectGPT use their frozen model implementations and native document labels, scores, and truncation settings. Exact model and checkpoint settings are recorded in `../model_settings.json`. 

## Outputs

- `metrics.csv` and `metrics.json`: native confusion counts and metrics for each method, condition, version, and domain, plus pooled results. Sentence metrics pool actual sentence units. Pooled metrics are calculated from combined units, rather than averaging domain F1 scores.
- `document_matched_auroc.csv`: matched same-source v0-versus-vi document AUROC and source-bootstrap intervals. Each comparison includes the same source IDs at both versions.
- `paired_differences.csv`: early/late minus original differences and 95% percentile intervals. The 2,000 bootstrap replicates use seed 42, resample source documents together across conditions, and retain all units of a sampled source. Pooled resampling preserves each domain's source count. Comparisons use the intersection of available source IDs, including the v0 baseline for AUROC.
- `coverage_per_record.csv` and `coverage_summary.csv`: actual AI sentence/word coverage and body length statistics. Words follow the supplied whitespace-token sequence; character counts use Python Unicode character positions. `essay_length` is not used as edited-document length.
- `figures/`: version curves in PNG and PDF; diamonds mark each condition's compression step.
- `RESULTS.md`: pooled results formatted as percentages.

The raw metric files preserve the frozen scorer's zero-support convention: F1-AI is 0 when there is no positive ground-truth support, and Macro-F1 remains the fixed two-class average. In the readable results and figures, F1-AI and FNR with no AI support are shown as N/A. One-class per-version AUROC is undefined; the document AUROC table instead compares matched v0 and vi records. Confidence-interval differences use the 0–1 scale.

## Run

From the `Code_submit_iclr/` repository root:

```bash
python -B ablation4_compression_position/analysis/export_results.py
```

Use `--check-only` to validate currently available records and report missing predictions without producing result tables. Exit code 2 indicates missing inputs, 1 indicates an invalid record or analysis error, and 0 indicates complete validation. The script makes no model or API calls.
"""


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--check-only", action="store_true")
    args = parser.parse_args()
    output = Path(__file__).resolve().parent
    canonical, input_identity, coverage = canonical_inputs()
    records, missing, prediction_identity = validated_predictions(canonical)
    status = {"checked_utc": datetime.now(timezone.utc).isoformat(), "status": "missing_inputs" if missing else "validated",
              "expected_records_per_method": 3090, "valid_records": dict(Counter(k[0] for k in records)), "missing": missing}
    json_write(output / "status.json", status)
    if missing or args.check_only:
        print(json.dumps(status))
        return 2 if missing else 0
    if any(sum(k[0] == method for k in records) != 3090 for method in METHODS):
        raise ValueError("Unexpected final prediction accounting")
    bootstrap = SourceBootstrap()
    rows = summaries(records)
    auc_rows = matched_auc_rows(records, bootstrap)
    differences = paired_differences(records, bootstrap)
    coverage_rows = coverage_summary(coverage)
    csv_write(output / "metrics.csv", rows)
    json_write(output / "metrics.json", rows)
    csv_write(output / "document_matched_auroc.csv", auc_rows)
    csv_write(output / "paired_differences.csv", differences)
    csv_write(output / "coverage_per_record.csv", coverage)
    csv_write(output / "coverage_summary.csv", coverage_rows)
    plots(rows, output)
    (output / "RESULTS.md").write_text(markdown_results(rows, auc_rows), encoding="utf-8")
    (output / "README.md").write_text(readme(), encoding="utf-8")
    source_paths = [Path(__file__), FROZEN / "evaluation/score_predictions.py", FROZEN / "evaluation/scoring_metrics.py"]
    configuration_paths = sorted({path for method in METHOD_DIRECTORIES.values()
                                  for path in (EXPERIMENT / method / "full").rglob("*.json")
                                  if path.name in {"run_config.json", "model_metadata.json", "prediction_manifest.json", "scoring_manifest.json", "execution.json"}})
    manifest = {"created_utc": datetime.now(timezone.utc).isoformat(), "split": "test",
                "source_documents": EXPECTED_SOURCE_COUNTS, "condition_records": 1030,
                "conditions": CONDITIONS, "compression_versions": COMPRESSION,
                "methods": METHODS, "bootstrap_replicates": BOOTSTRAPS, "bootstrap_seed": SEED,
                "bootstrap_unit": "source_document", "pooled_bootstrap": "fixed_domain_source_counts",
                "paired_difference": "condition_minus_original", "metric_scale": "0_to_1",
                "input_and_prediction_files": input_identity + prediction_identity,
                "source_files": [{"path": str(path), "sha256": sha256(path)} for path in source_paths],
                "run_configuration_files": [{"path": str(path), "sha256": sha256(path)} for path in configuration_paths],
                "artifacts": [{"path": str(path.relative_to(output)), "sha256": sha256(path)}
                              for path in sorted(output.rglob("*")) if path.is_file() and path.name not in {"manifest.json", "status.json"}],
                "count_protocol": "Three matched conditions; 115 records at v0-v3 and 114 at v4-v8; raw unit pooling; same-source intersections for v0-vi comparisons."}
    json_write(output / "manifest.json", manifest)
    status.update(status="complete", metric_rows=len(rows), matched_auroc_rows=len(auc_rows),
                  paired_difference_rows=len(differences), coverage_rows=len(coverage))
    json_write(output / "status.json", status)
    print(json.dumps(status))
    return 0


if __name__ == "__main__":
    try:
        raise SystemExit(main())
    except Exception as error:
        print(json.dumps({"status": "invalid", "error": str(error), "error_type": type(error).__name__}), file=sys.stderr)
        raise