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
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
"""Stage-3 hold-out skip pattern generator for the HareSkip experiment.

Offline reproduction of the skip patterns the HareSkip extension would emit at
inference time, using the measured ERSDE-Beta trajectory (t_now per step) from
analysis-phase1-02/outputs/tables/master_long.csv.

Two independent implementations are run and compared:
  1) SELF  -- a from-scratch re-implementation of the extension logic in this
              file (_self_generate), written from reading the source.
  2) EXT   -- the actual extension modules imported read-only from
              forge-neo-Anima-HareSkip (hareskip.skip_pattern).
If they disagree on any candidate, the script aborts. Nothing is written
outside this scratchpad directory; the extension repo and experiment data are
opened read-only.

Usage:  python simulate_patterns.py
"""

import csv
import hashlib
import math
import os
import random
import sys

# --- paths (read-only inputs) ----------------------------------------------

EXT_ROOT = r"S:\30_OriginalApps\16_HareSkip\forge-neo-Anima-HareSkip"
EXP_ROOT = r"S:\30_OriginalApps\16_HareSkip\experiment-HareSkip"
MASTER_LONG = os.path.join(
    EXP_ROOT, "analysis-phase1-02", "outputs", "tables", "master_long.csv"
)
STAGE2_PATTERNS = os.path.join(
    EXP_ROOT, "patterns", "stage2-interaction-patterns.txt"
)
STAGE1_PATTERNS = os.path.join(
    EXP_ROOT, "patterns", "layer1-single-skip-sweep-30steps.txt"
)
OUT_DIR = os.path.dirname(os.path.abspath(__file__))

NUM_STEPS = 30
IMAGE_SEEDS = [3000995193, 2455776111, 2767019676]
SKIP_WINDOW = (0.05, 0.95)          # extension default
ZONE_BOUNDARIES = (-4.0, 0.0)       # extension default
ZONE_MAX_STREAK = {"danger": 1, "middle": 2, "safe": 3}
MODEL = "sigmoid_band_v0.1"

# --- extension import (read-only) ------------------------------------------

sys.path.insert(0, EXT_ROOT)
from hareskip import skip_pattern as ext_sp            # noqa: E402
from hareskip import probability_models as ext_pm      # noqa: E402


# --- SELF re-implementation -------------------------------------------------


def _sigmoid(x):
    if x >= 0.0:
        return 1.0 / (1.0 + math.exp(-x))
    e = math.exp(x)
    return e / (1.0 + e)


def _clamp(x, lo, hi):
    return max(lo, min(hi, x))


def self_params(a):
    a = _clamp(a, 0.0, 1.0)
    return {
        "p_cap": 0.40 + 0.40 * a,
        "z_enter": -1.8 - 5.0 * (a ** 1.35),
        "tau_enter": 0.55 + 0.35 * a,
        "z_exit": 4.2 + 1.0 * a,
        "tau_exit": 0.45,
    }


def self_p(z, prm):
    p = (
        prm["p_cap"]
        * _sigmoid((z - prm["z_enter"]) / prm["tau_enter"])
        * _sigmoid((prm["z_exit"] - z) / prm["tau_exit"])
    )
    return _clamp(p, 0.0, 1.0)


def self_z(t_now, eps=1e-6):
    t = max(eps, min(1.0 - eps, t_now))
    return 2.0 * math.log((1.0 - t) / t)


def self_zone(z, boundaries=ZONE_BOUNDARIES):
    low, high = boundaries
    if z < low:
        return "danger"
    if z < high:
        return "middle"
    return "safe"


def self_skip_seed(image_seed, offset):
    digest = hashlib.sha256(
        "{}|hareskip|{}".format(int(image_seed), int(offset)).encode("utf-8")
    ).hexdigest()
    return int(digest, 16) % (2 ** 63)


def self_apply_streak(skip, z_by_step, p_by_step, boundaries=ZONE_BOUNDARIES):
    while True:
        n = len(skip)
        i = 0
        violated = None
        while i < n:
            if not skip[i]:
                i += 1
                continue
            j = i
            while j < n and skip[j]:
                j += 1
            allowed = min(
                ZONE_MAX_STREAK[self_zone(z_by_step[k], boundaries)]
                for k in range(i, j)
            )
            if (j - i) > allowed:
                violated = (i, j)
                break
            i = j
        if violated is None:
            return
        start, end = violated
        best = None
        for k in range(start, end):
            key = (p_by_step[k], z_by_step[k], k)
            if best is None or key < best[0]:
                best = (key, k)
        skip[best[1]] = False


def self_generate(t_now_by_step, a, skip_seed,
                  skip_window=SKIP_WINDOW, boundaries=ZONE_BOUNDARIES):
    """Independent reproduction of hareskip.generate_skip_pattern (no target)."""
    n = len(t_now_by_step)
    prm = self_params(a)
    rng = random.Random(skip_seed)
    ws, we = skip_window
    z_by_step, p_by_step, skip = [], [], []
    for idx, t_now in enumerate(t_now_by_step):
        progress = 0.0 if n <= 1 else idx / float(n - 1)
        eligible = ws <= progress <= we
        z = self_z(t_now)
        p = self_p(z, prm) if eligible else 0.0
        z_by_step.append(z)
        p_by_step.append(p)
        # NOTE: the RNG is consumed ONLY for eligible steps -- matches
        # _draw_pattern in skip_pattern.py, where rng.random() sits inside the
        # `if eligible` conditional expression and is short-circuited otherwise.
        skip.append((rng.random() < p) if eligible else False)
    self_apply_streak(skip, z_by_step, p_by_step, boundaries)
    return skip, z_by_step, p_by_step, prm


# --- trajectory (measured ERSDE-Beta t_now) ---------------------------------


def load_trajectory():
    """Return (t_now_by_step[30], z_by_step[30], audit) from master_long.csv.

    master_long uses mapA: skip_step k <-> traj_step k-1, columns `z`/`tnow`.
    skip_step 2..30 are present; step 1 (idx 0) has no measured t_now and is
    extrapolated (log-linear in z) -- it is outside the skip window and
    residual-less at inference, so it can never be skipped either way.
    """
    by_step = {}
    with open(MASTER_LONG, newline="", encoding="utf-8") as fh:
        for r in csv.DictReader(fh):
            if r["sampler"] != "ERSDE-Beta":
                continue
            k = int(float(r["skip_step"]))
            rec = (float(r["tnow"]), float(r["z"]), float(r["traj_step"]))
            by_step.setdefault(k, set()).add(rec)

    audit = {}
    conflicts = {k: v for k, v in by_step.items() if len(v) != 1}
    audit["steps_present"] = sorted(by_step)
    audit["conflicts"] = conflicts
    assert not conflicts, "z/tnow differ across ERSDE-Beta conditions: %r" % conflicts
    assert audit["steps_present"] == list(range(2, 31))

    t_now = [None] * NUM_STEPS
    z_meas = [None] * NUM_STEPS
    for k, v in by_step.items():
        tn, z, _ts = next(iter(v))
        # cross-check that the recorded z is exactly the extension's proxy
        assert abs(ext_sp.logsnr_proxy_from_t_now(tn) - z) < 1e-9, k
        assert abs(self_z(tn) - z) < 1e-9, k
        t_now[k - 1] = tn
        z_meas[k - 1] = z
    # extrapolate step 1 in z (linear backwards from steps 2 and 3)
    z1 = z_meas[1] - (z_meas[2] - z_meas[1])
    t_now[0] = 1.0 / (1.0 + math.exp(z1 / 2.0))
    z_meas[0] = self_z(t_now[0])
    audit["z1_extrapolated"] = z_meas[0]
    return t_now, z_meas, audit


# --- known patterns to exclude ----------------------------------------------


def load_known():
    known = set()
    with open(STAGE2_PATTERNS, encoding="utf-8") as fh:
        for line in fh:
            line = line.strip()
            if line:
                known.add(frozenset(int(x) for x in line.split(",")))
    with open(STAGE1_PATTERNS, encoding="utf-8") as fh:
        for line in fh:
            line = line.strip()
            if line:
                known.add(frozenset(int(x) for x in line.split(",")))
    return known


# --- helpers ----------------------------------------------------------------


def hamming(a, b):
    """Hamming distance between two skip sets over the 30-step vector."""
    return len(set(a) ^ set(b))


def max_streak(skip):
    best = cur = 0
    for s in skip:
        cur = cur + 1 if s else 0
        best = max(best, cur)
    return best


def zone_breakdown(steps, z_by_step):
    out = {"danger": 0, "middle": 0, "safe": 0}
    for s in steps:
        out[self_zone(z_by_step[s - 1])] += 1
    return out


def make_candidate(t_now, z_by_step, a, image_seed, offset, checks):
    """Generate one candidate with SELF and cross-check against EXT."""
    seed = self_skip_seed(image_seed, offset)
    assert seed == ext_sp.derive_skip_seed(image_seed, offset)

    s_skip, s_z, s_p, s_prm = self_generate(t_now, a, seed)
    e_pat = ext_sp.generate_skip_pattern(
        t_now, aggressiveness=a, skip_seed=seed,
        probability_model=MODEL,
        skip_window=SKIP_WINDOW, zone_boundaries=ZONE_BOUNDARIES,
    )
    # --- cross-implementation verification -------------------------------
    assert s_prm == e_pat.params, (s_prm, e_pat.params)
    assert all(abs(x - y) < 1e-12 for x, y in zip(s_z, e_pat.z_by_step))
    assert all(abs(x - y) < 1e-12 for x, y in zip(s_p, e_pat.p_by_step))
    assert s_skip == e_pat.skip, (a, image_seed, offset)
    checks["compared"] += 1

    steps = [i + 1 for i, s in enumerate(s_skip) if s]
    assert steps == e_pat.skipped_steps
    return {
        "a": a,
        "image_seed": image_seed,
        "offset": offset,
        "skip_seed": seed,
        "steps": steps,
        "count": len(steps),
        "zones": zone_breakdown(steps, s_z),
        "max_streak": max_streak(s_skip),
        "expected": e_pat.expected_skips_before_streak,
        "manual_added": [],
    }


def select_for_level(a, t_now, z_by_step, known, chosen_so_far, checks,
                     n_want=3, max_offset=400):
    """Pick n_want candidates at aggressiveness a satisfying the constraints."""
    picked = []
    for offset in range(0, max_offset):
        for image_seed in IMAGE_SEEDS:
            cand = make_candidate(t_now, z_by_step, a, image_seed, offset, checks)
            steps = cand["steps"]
            if len(steps) < 2:
                continue
            key = frozenset(steps)
            if key in known:
                continue
            if any(key == frozenset(p["steps"]) for p in picked + chosen_so_far):
                continue
            if any(hamming(steps, p["steps"]) < 3
                   for p in picked + chosen_so_far):
                continue
            picked.append(cand)
            if len(picked) == n_want:
                return picked
    raise RuntimeError("could not find %d candidates at a=%s" % (n_want, a))


# --- main -------------------------------------------------------------------


def main():
    t_now, z_meas, audit = load_trajectory()
    known = load_known()

    checks = {"compared": 0}
    chosen = []
    for a in (0.3, 0.6, 0.9):
        picked = select_for_level(a, t_now, z_meas, known, chosen, checks)
        chosen.extend(picked)

    # --- extreme stress pattern: a=0.9 realisation + manual early steps ----
    base = chosen[-1]  # last a=0.9 pattern
    stress_steps = sorted(set(base["steps"]) | {3, 5})
    stress = dict(base)
    stress["steps"] = stress_steps
    stress["count"] = len(stress_steps)
    stress["zones"] = zone_breakdown(stress_steps, z_meas)
    sv = [False] * NUM_STEPS
    for s in stress_steps:
        sv[s - 1] = True
    stress["max_streak"] = max_streak(sv)
    stress["manual_added"] = [3, 5]
    stress["label"] = "stress"
    chosen.append(stress)

    # --- final validation --------------------------------------------------
    problems = []
    if len(chosen) != 10:
        problems.append("expected 10 patterns, got %d" % len(chosen))
    seen = set()
    for i, p in enumerate(chosen):
        st = p["steps"]
        if st != sorted(st):
            problems.append("pattern %d not sorted" % i)
        if not all(2 <= s <= 30 for s in st):
            problems.append("pattern %d out of range 2..30: %r" % (i, st))
        if 1 in st:
            problems.append("pattern %d contains step 1" % i)
        k = tuple(st)
        if k in seen:
            problems.append("duplicate pattern %d" % i)
        seen.add(k)
        if frozenset(st) in known:
            problems.append("pattern %d collides with stage1/2" % i)
    # pairwise hamming among the 9 simulated (stress excluded by construction)
    for i in range(9):
        for j in range(i + 1, 9):
            d = hamming(chosen[i]["steps"], chosen[j]["steps"])
            if d < 3:
                problems.append("hamming(%d,%d)=%d < 3" % (i, j, d))

    # --- write outputs -----------------------------------------------------
    txt = os.path.join(OUT_DIR, "stage3-holdout-patterns.txt")
    with open(txt, "w", encoding="utf-8", newline="\n") as fh:
        for p in chosen:
            fh.write(", ".join(str(s) for s in p["steps"]) + "\n")

    write_report(chosen, audit, checks, problems, z_meas, known)

    print("cross-implementation comparisons: %d (all identical)" % checks["compared"])
    print("validation problems:", problems or "none")
    for i, p in enumerate(chosen, 1):
        print("%2d  a=%.1f seed=%d off=%d  n=%2d  %s%s" % (
            i, p["a"], p["image_seed"], p["offset"], p["count"],
            p["steps"], "  (+manual 3,5)" if p["manual_added"] else ""))


def write_report(chosen, audit, checks, problems, z_meas, known):
    lines = []
    A = lines.append
    A("# Stage-3 hold-out skip patterns -- generation report")
    A("")
    A("Generated by `simulate_patterns.py` (this directory). Inputs are read-only:")
    A("")
    A("- Extension logic: `%s\\hareskip\\{skip_pattern,probability_models}.py`" % EXT_ROOT)
    A("- Trajectory: `%s`" % MASTER_LONG)
    A("- Exclusion sets: `%s`, `%s`" % (STAGE2_PATTERNS, STAGE1_PATTERNS))
    A("")
    A("## Configuration")
    A("")
    A("| item | value |")
    A("|---|---|")
    A("| num_steps | %d |" % NUM_STEPS)
    A("| probability model | `%s` |" % MODEL)
    A("| skip_window | %s (extension default) |" % (SKIP_WINDOW,))
    A("| zone_boundaries | %s (extension default) |" % (ZONE_BOUNDARIES,))
    A("| zone max streak | danger 1 / middle 2 / safe 3 |")
    A("| skip_seed | `sha256(f\"{image_seed}|hareskip|{offset}\")` mod 2**63 |")
    A("| image seeds | %s |" % ", ".join(str(s) for s in IMAGE_SEEDS))
    A("")
    A("## Verification")
    A("")
    A("Two independent implementations were compared on **every candidate drawn**")
    A("(not just the 9 selected ones):")
    A("")
    A("1. `self_generate` in this script -- written from scratch by reading the")
    A("   extension source (probability formula, window eligibility, z proxy,")
    A("   zone/streak trimming with the `(p, z, index)` argmin flip rule, and the")
    A("   RNG consumption order: `rng.random()` is drawn **only for eligible")
    A("   steps**, because in `_draw_pattern` the call sits inside the")
    A("   `if eligible` conditional expression).")
    A("2. `hareskip.skip_pattern.generate_skip_pattern` imported directly from the")
    A("   extension repo (`sys.path.insert`, read-only; nothing installed or")
    A("   modified).")
    A("")
    A("Compared per candidate: `params`, `z_by_step`, `p_by_step`, the boolean")
    A("`skip` vector and `skipped_steps`. Any mismatch aborts the script.")
    A("")
    A("- Candidates cross-checked: **%d** -- all identical." % checks["compared"])
    A("- `derive_skip_seed` also cross-checked per candidate (SHA-256, not `hash()`).")
    A("- The extension's own suite `tests/test_skip_pattern.py` was run against the")
    A("  same modules: **42 passed** (including the pinned literal")
    A("  `derive_skip_seed(12345, 0) == 3695650839502921262`).")
    A("")
    A("Validation of the final 10 patterns: **%s**" % (
        "; ".join(problems) if problems else "no problems (all steps in 2..30, "
        "no step 1, no duplicates, no collision with stage-1/2, pairwise "
        "Hamming >= 3 among the 9 simulated)"))
    A("")
    A("## z(step) correspondence")
    A("")
    A("`master_long.csv` columns `z` / `tnow` follow **mapA**")
    A("(`traj_step = skip_step - 1`), the default in analysis-phase1-02/REPORT.md.")
    A("For the ERSDE-Beta sampler all **15 conditions carry identical `z`/`tnow`**")
    A("for every `skip_step` 2..30 (verified: zero conflicting values).")
    A("Each recorded `z` reproduces `logsnr_proxy_from_t_now(tnow)` to < 1e-9, so")
    A("the measured `tnow` column is fed straight into the extension as")
    A("`t_now_by_step`.")
    A("")
    A("Step 1 has no measured trajectory row (skip_step starts at 2); its z is")
    A("extrapolated linearly backwards to z = %.4f. It is irrelevant to the" % audit["z1_extrapolated"])
    A("result: idx 0 has progress 0.0 < 0.05 so it is outside the skip window,")
    A("and at inference the first call has no residual, so it is never skipped.")
    A("")
    A("| step | t_now | z | zone |")
    A("|---:|---:|---:|---|")
    for i in range(NUM_STEPS):
        z = z_meas[i]
        A("| %d%s | %.9f | %.5f | %s |" % (
            i + 1, " (extrap.)" if i == 0 else "",
            1.0 / (1.0 + math.exp(z / 2.0)), z, self_zone(z)))
    A("")
    A("## Patterns")
    A("")
    A("| # | a | image_seed | offset | skip_seed | n | skipped steps | danger | middle | safe | max streak | E[skips] |")
    A("|---:|---:|---:|---:|---|---:|---|---:|---:|---:|---:|---:|")
    for i, p in enumerate(chosen, 1):
        note = " **(+manual 3, 5)**" if p["manual_added"] else ""
        A("| %d | %.1f | %d | %d | %d | %d | %s%s | %d | %d | %d | %d | %.2f |" % (
            i, p["a"], p["image_seed"], p["offset"], p["skip_seed"], p["count"],
            ", ".join(str(s) for s in p["steps"]), note,
            p["zones"]["danger"], p["zones"]["middle"], p["zones"]["safe"],
            p["max_streak"], p["expected"]))
    A("")
    A("Rows 1-3: a=0.3. Rows 4-6: a=0.6. Rows 7-9: a=0.9. Row 10: extreme-stress.")
    A("")
    A("### Row 10 (extreme stress)")
    A("")
    st = chosen[-1]
    A("Row 10 is **not** a plain simulator output. It takes the realised a=0.9")
    A("pattern of row 9 (image_seed %d, offset %d) and **manually adds steps 3")
    A("and 5**. Those two steps sit in the danger band (z = %.2f and %.2f, both" % (
        z_meas[2], z_meas[4]))
    A("z < -4), which the probability model almost never selects and where the")
    A("danger-zone streak cap is 1 -- so this row is a deliberate out-of-sample")
    A("probe of the prediction formula's limit, not a reachable extension output.")
    A("Its max streak (%d) may therefore exceed what the extension would emit." % st["max_streak"])
    A("")
    A("## Output grammar")
    A("")
    A("`stage3-holdout-patterns.txt` -- 10 lines, one pattern per line,")
    A("comma-separated 1-based step numbers in ascending order; same grammar as")
    A("`stage2-interaction-patterns.txt` and the stage-1 sweep file.")
    A("")
    with open(os.path.join(OUT_DIR, "generation_report.md"), "w",
              encoding="utf-8", newline="\n") as fh:
        fh.write("\n".join(lines))


if __name__ == "__main__":
    main()