"""second17.py - exact SECOND MOMENT of the half-word adjacent-pair-sum exceedance count X_h under route 17's common-phase law at x19 (job #4203, pursue route 17; step set by return #1852), with literal small-instance validation. Imports #639's firstmoment17.py UNCHANGED (sha256 checked) for the law, the BEST counts and the weight recurrence. Law (#459, as in #639): uniform over distinct arrangements of the half multiset whose mod-5 residue path from phase 4 stays in {1,2,4} and ends at 1. Equivalently: a uniform admissible residue word, then a uniform assignment of each class's values to that class's positions. A residue word = a uniform m0-subset of the n positions for the zeros (loops), interleaved with a nonzero word (an open Euler trail 4 -> 1 on the six edge types), mixed over flow types c with #467's weights W(c). Second moment. E[X^2] = E[X] + sum_{i != j} P(I_i I_j), with I_i = [g_i + g_{i+1} > t]. j = i +- 1 (overlap): triples (i, i+1, i+2), each counted twice. |i - j| >= 2 (disjoint): ordered pairs of disjoint adjacencies. A marked adjacency, or a marked triple, is collapsed into one SUPER LETTER. Its zeros are inert, since they leave the phase unchanged. Its nonzero letters must be consecutive in the nonzero trail, head to tail, so the super letter is: a loop (no nonzero letter); a distinguished single edge of type a (one nonzero letter; the graph is unchanged); a merged edge tail(a1) -> head(ak) (two or more nonzero letters). Counting (word, ordered marks) = counting super-words: super-words = [interleavings of loop items with nonzero items] x [nonzero item sequences]; interleavings = n''! / ((n''-l)! (m0-z)!), with n'' items, l = (m0-z) free zeros + loop super letters, and z the zeros consumed; nonzero item sequences at flow type c = trails_labeled(G'') / prod_k m''_k!, where G'' = G minus the used letters, plus one distinguishable edge per super letter with a nonzero letter. At x19 the ratio to W(c) is prod_k falling(m_k, u_k) * tau''/tau * prod_v 1/falling(out_v - 1, d_v) (v != 1) and 1/falling(out_1, d_1) at v = 1, where d_v is the out-degree lost at internal chain vertices (as #639's marked_ratio, extended to several merges). Small instances use the direct big-integer BEST count throughout. Value factor: the values at the marked positions are drawn without replacement inside each class. The exact joint probability that every marked adjacency exceeds t is summed over value tuples. Checks (all exact rationals): (A) literal end-to-end on value multisets from the pinned x19 values: E[X] and E[X^2] at EVERY threshold, from all admissible arrangements, against the pipeline (direct counts). (B) ratio form == direct BEST count at x19 flow types lo/mid/hi, for every chain combination used. (C) the pipeline's E[X] at x19 equals #639's E_cond (21.76682214945484096...) exactly. stdout is the artifact (deterministic JSON); timings go to stderr. Usage: python second17.py input1071.json > second17-out.json """ import hashlib, importlib.util, itertools, json, math, os, random, sys, time from collections import Counter from fractions import Fraction HERE = os.path.dirname(os.path.abspath(__file__)) FM_PATH = os.path.join(HERE, 's639', 'firstmoment17.py') FM_SHA = hashlib.sha256(open(FM_PATH, 'rb').read()).hexdigest() spec = importlib.util.spec_from_file_location('fm17', FM_PATH) FM = importlib.util.module_from_spec(spec); spec.loader.exec_module(FM) EDGES, NONZERO, END = FM.EDGES, FM.NONZERO, FM.END RES_TYPES = {r: [k for k in NONZERO if EDGES[k][2] == r] for r in range(1, 5)} def log(msg): sys.stderr.write(msg + '\n'); sys.stderr.flush() def falling(a, k): out = 1 for i in range(k): out *= a - i return out def chains_for(residues): """All type chains for the nonzero residues of a super letter (zeros dropped), head(a_i) == tail(a_{i+1}).""" nz = [r for r in residues if r] if not nz: return [()] out = [] for combo in itertools.product(*[RES_TYPES[r] for r in nz]): if all(EDGES[combo[i]][1] == EDGES[combo[i + 1]][0] for i in range(len(combo) - 1)): out.append(combo) return out def used_and_specials(chains): used = Counter(); specials = []; dec = Counter() for ch in chains: for k in ch: used[k] += 1 if ch: specials.append((EDGES[ch[0]][0], EDGES[ch[-1]][1], 1)) for k in ch[:-1]: dec[EDGES[k][1]] += 1 return used, specials, dec def count_direct(mult, chains): """Number of (nonzero word, marked super letters) at this flow type: direct big-integer BEST.""" used, specials, _ = used_and_specials(chains) if any(mult[k] < u for k, u in used.items()): return 0 m2 = {k: mult[k] - used[k] for k in NONZERO} den = 1 for k in NONZERO: den *= math.factorial(m2[k]) num = FM.trails_labeled(FM.graph_edges(m2) + specials) q, r = divmod(num, den) assert r == 0 return q def ratio_form(mult, chains, tau, outdeg): """count / W(c) by the contraction ratio (valid when no vertex vanishes; used at x19).""" used, specials, dec = used_and_specials(chains) num = 1 for k, u in used.items(): if mult[k] < u: return Fraction(0) num *= falling(mult[k], u) if not any(len(ch) >= 2 for ch in chains): return Fraction(num) # only loops and distinguished single edges: the graph is unchanged m2 = {k: mult[k] - used[k] for k in NONZERO} taup = FM.tau_of(FM.graph_edges(m2) + specials) # every super letter with a nonzero letter is one edge of G'' den = tau for v, d in dec.items(): den *= falling(outdeg[v], d) if v == END else falling(outdeg[v] - 1, d) assert den > 0 return Fraction(num * taup, den) def outdegrees(mult): o = Counter() for k in NONZERO: o[EDGES[k][0]] += mult[k] return o def class_values(hc): return {r: {v: k for v, k in hc.items() if v % 5 == r} for r in range(5)} def joint_prob(cls, m, residues, pairs, t): """P(every listed adjacency (p, q) of the marked positions has v_p + v_q > t), values drawn without replacement inside each class at the marked positions (residues[p] = class of position p).""" k = len(residues) need = Counter(residues) if any(need[r] > m[r] for r in need): return Fraction(0) den = 1 for r, c in need.items(): den *= falling(m[r], c) tot = 0 for vals in itertools.product(*[list(cls[r].items()) for r in residues]): if not all(vals[p][0] + vals[q][0] > t for p, q in pairs): continue ways = 1 per = Counter() for (v, cnt), r in zip(vals, residues): per[(r, v)] += 1 for (r, v), u in per.items(): ways *= falling(cls[r][v], u) tot += ways return Fraction(tot, den) def interleave(n, m0, L, z, loops_s, items_removed): """[n''!/((n''-l)!(m0-z)!)] / [n!/(m0! L!)] with n'' = n - items_removed, l = (m0 - z) + loops_s.""" n2 = n - items_removed l = (m0 - z) + loops_s L2 = n2 - l if m0 - z < 0 or L2 < 0 or l < 0: return Fraction(0) # n2!/n! * L!/L2! * m0!/(m0-z)! num = math.prod(range(L2 + 1, L + 1)) if L >= L2 else 1 den = math.prod(range(L + 1, L2 + 1)) if L2 > L else 1 num *= falling(m0, z) den *= falling(n, items_removed) return Fraction(num, den) def pipeline(hc, thresholds, weights=None, mode='direct', log_every=None): """Exact E[X] and E[X^2] (all thresholds) for value multiset hc. mode 'direct' (small) or 'ratio' (x19).""" m = FM.residue_counts(hc) if FM.balance(m): return None n = sum(m); m0 = m[0]; L = n - m0 if weights is None: weights = FM.weight_law(m) SW = sum(W for _, W in weights) # the super-letter patterns pairs = [(x, y) for x in range(5) for y in range(5)] triples = [(x, y, w) for x in range(5) for y in range(5) for w in range(5)] single_combos = {} # chain -> sum_c count need_single = set() for p in pairs: for ch in chains_for(p): need_single.add((ch,)) need_pair = set() for p1 in pairs: for p2 in pairs: for c1 in chains_for(p1): for c2 in chains_for(p2): need_pair.add((c1, c2)) need_trip = set() for tr in triples: for ch in chains_for(tr): need_trip.add((ch,)) combos = sorted(need_single | need_pair | need_trip) acc = {cb: 0 for cb in combos} t0 = time.perf_counter() if mode == 'ratio' and len(weights) > 1000: from concurrent.futures import ProcessPoolExecutor chunks = [weights[i::8] for i in range(8)] with ProcessPoolExecutor(8) as ex: for part in ex.map(_ratio_chunk, [(m, ch, combos) for ch in chunks]): for cb, v in part.items(): acc[cb] += v weights_iter = [] log(' ratio accumulation over %d flow types on 8 processes: %.0fs' % (len(weights), time.perf_counter() - t0)) else: weights_iter = weights for idx, (c, W) in enumerate(weights_iter): mult = FM.multiplicities(m, c) if mode == 'ratio': tau = FM.tau_of(FM.graph_edges(mult)); od = outdegrees(mult) for cb in combos: if mode == 'direct': acc[cb] += count_direct(mult, cb) else: r = ratio_form(mult, cb, tau, od) if r: q, rem = divmod(W * r.numerator, r.denominator) assert rem == 0, ('non-integral marked count', c, cb) acc[cb] += q if log_every and idx % log_every == 0: log(' flow type %d/%d %.0fs' % (idx, len(weights), time.perf_counter() - t0)) if mode == 'direct': for c, W in weights: assert W == FM.words_direct(FM.multiplicities(m, c)) cls = class_values(hc) E1 = {t: Fraction(0) for t in thresholds} Ed = {t: Fraction(0) for t in thresholds} Eo = {t: Fraction(0) for t in thresholds} # first moment: one super letter of 2 letters for p in pairs: z = p.count(0); ls = 1 if z == 2 else 0 f = interleave(n, m0, L, z, ls, 1) if not f: continue cnt = sum(acc[(ch,)] for ch in chains_for(p)) if not cnt: continue M = f * Fraction(cnt, SW) for t in thresholds: E1[t] += M * joint_prob(cls, m, list(p), [(0, 1)], t) # disjoint ordered pairs: two super letters of 2 letters each for p1 in pairs: for p2 in pairs: z = p1.count(0) + p2.count(0); ls = (p1.count(0) == 2) + (p2.count(0) == 2) f = interleave(n, m0, L, z, ls, 2) if not f: continue cnt = sum(acc[(c1, c2)] for c1 in chains_for(p1) for c2 in chains_for(p2)) if not cnt: continue M = f * Fraction(cnt, SW) for t in thresholds: Ed[t] += M * joint_prob(cls, m, list(p1) + list(p2), [(0, 1), (2, 3)], t) # overlapping: one super letter of 3 letters (counted twice in sum_{i != j}) for tr in triples: z = tr.count(0); ls = 1 if z == 3 else 0 f = interleave(n, m0, L, z, ls, 2) if not f: continue cnt = sum(acc[(ch,)] for ch in chains_for(tr)) if not cnt: continue M = f * Fraction(cnt, SW) for t in thresholds: Eo[t] += M * joint_prob(cls, m, list(tr), [(0, 1), (1, 2)], t) E2 = {t: E1[t] + Ed[t] + 2 * Eo[t] for t in thresholds} return {'m': m, 'E1': E1, 'E2': E2, 'Ed': Ed, 'Eo': Eo, 'combos': len(combos), 'acc': acc, 'SW': SW} def _ratio_chunk(args): m, chunk, combos = args acc = {cb: 0 for cb in combos} for c, W in chunk: mult = FM.multiplicities(m, c) tau = FM.tau_of(FM.graph_edges(mult)); od = outdegrees(mult) for cb in combos: r = ratio_form(mult, cb, tau, od) if r: q, rem = divmod(W * r.numerator, r.denominator) assert rem == 0, ('non-integral marked count', c, cb) acc[cb] += q return acc def literal(ms, thresholds): adm = [] for w in FM.distinct_arrangements(ms): res = [g % 5 for g in w] h = FM.walk_half(res) assert h == FM.walk_full(res) if h: adm.append(w) if not adm: return None E1, E2 = {}, {} for t in thresholds: xs = [sum(1 for u, v in zip(w, w[1:]) if u + v > t) for w in adm] E1[t] = Fraction(sum(xs), len(adm)); E2[t] = Fraction(sum(x * x for x in xs), len(adm)) return E1, E2, len(adm) def check_end_to_end(values, seed=4203): rng = random.Random(seed) cases = [] for k in (2, 3, 4): cases += [tuple(c) for c in itertools.combinations_with_replacement(values, k)] for k, howmany in ((5, 150), (6, 60), (7, 20), (8, 6)): for _ in range(howmany): cases.append(tuple(sorted(rng.choice(values) for _ in range(k)))) # targeted: balanced (admissible) multisets of length 7..9 with at least two residue-0 values, so the zero # overlay (ZZ, ZN, NZ, zeros inside disjoint and overlapping marks) is exercised at the second moment zeros = [v for v in values if v % 5 == 0]; tgt = [] while len(tgt) < 36: k = rng.choice((7, 8, 9)); nz = rng.choice((2, 3, 4)) ms = tuple(sorted([rng.choice(zeros) for _ in range(nz)] + [rng.choice(values) for _ in range(k - nz)])) if FM.balance(FM.residue_counts(Counter(ms))) == 0 and ms not in tgt: tgt.append(ms) cases += tgt stats = Counter() for ms in cases: hc = Counter(ms) sums = sorted({u + v for u, v in itertools.combinations_with_replacement(sorted(hc), 2)}) thresholds = [s - 1 for s in sums] + [sums[-1]] lit = literal(ms, thresholds) stats['multisets'] += 1 m = FM.residue_counts(hc) if lit is None: assert FM.balance(m) != 0 stats['no_admissible'] += 1 continue res = pipeline(hc, thresholds, mode='direct') for t in thresholds: assert res['E1'][t] == lit[0][t], ('E1', ms, t, res['E1'][t], lit[0][t]) assert res['E2'][t] == lit[1][t], ('E2', ms, t, res['E2'][t], lit[1][t]) stats['threshold_checks'] += 1 stats['admissible_arrangements'] += lit[2] stats['with_admissible'] += 1 if m[0] >= 2 and len(ms) >= 7: stats['with_2plus_zeros_len_ge7'] += 1 return dict(stats) def decimal(fr, digits=30): return FM.decimal(fr, digits) def main(): t0 = time.perf_counter() data = json.loads(open(sys.argv[1], encoding='utf-8').read()) level = [lv for lv in data['levels'] if lv['x'] == 19][0] hc = FM.half_multiset(level) m = FM.residue_counts(hc) n = sum(m) A2 = int(level['A2']) assert list(m) == [41614, 31438, 67975, 33906, 14404] and n == 189337 and A2 == 186 log('(A) literal end-to-end, E[X] and E[X^2] at every threshold') valA = check_end_to_end(sorted(hc)) log(' ok %s %.1fs' % (valA, time.perf_counter() - t0)) log('x19: weight law') weights = FM.weight_law(m) fr = FM.flow_range(m) assert len(weights) == 33907 log('(B) ratio vs direct BEST at lo/mid/hi for every chain combination') t1 = time.perf_counter() spot = [fr.start, (fr.start + fr.stop - 1) // 2, fr.stop - 1] pairs = [(x, y) for x in range(5) for y in range(5)] triples = [(x, y, w) for x in range(5) for y in range(5) for w in range(5)] combos = sorted({(c1, c2) for p1 in pairs for p2 in pairs for c1 in chains_for(p1) for c2 in chains_for(p2)} | {(ch,) for tr in triples for ch in chains_for(tr)}) bchecks = 0 for c in spot: mult = FM.multiplicities(m, c) W = FM.words_direct(mult) tau = FM.tau_of(FM.graph_edges(mult)); od = outdegrees(mult) for cb in combos: if cb[0] == () and (len(cb) == 1 or cb[1] == ()): continue # loops only: count == W trivially r = ratio_form(mult, cb, tau, od) assert W * r == count_direct(mult, cb), ('ratio vs direct', c, cb) bchecks += 1 log(' c=%d ok (%d combos) %.1fs' % (c, len(combos), time.perf_counter() - t1)) log('x19: accumulate marked counts over all flow types (ratio form)') res = pipeline(hc, [A2], weights=weights, mode='ratio', log_every=2000) E1, E2 = res['E1'][A2], res['E2'][A2] fm_out = json.load(open(os.path.join(HERE, 's639', 'firstmoment17-out.json'), encoding='utf-8')) e639 = fm_out['result_threshold_186']['E_cond_half_word']['decimal_30'] assert decimal(E1, 30) == e639, ('E[X] differs from #639', decimal(E1, 30), e639) V = E2 - E1 * E1 cant = V / (V + E1 * E1) cheb = V / (E1 * E1) thresh = E1 * E1 / 99 out = { 'scope': 'Exact second moment of the half-word adjacent-pair-sum exceedance count X_h (threshold 186) under the ' 'route 17 common-phase law at x19; full reflected word X = 2 X_h (#639/#1852), so P(X = 0) = P(X_h = 0) ' 'and the Cantelli ratio is the same. No draw, no A1, exponent or infinitude claim.', 'custody': {'input': 'input1071.json', 'sha256': hashlib.sha256(open(sys.argv[1], 'rb').read()).hexdigest(), 'firstmoment17_py_sha256': FM_SHA, 'residue_counts': list(m), 'n': n, 'A2': A2, 'flow_types': len(weights), 'chain_combinations': res['combos']}, 'validation': {'A_end_to_end_literal_E1_E2_every_threshold': valA, 'B_ratio_vs_direct_BEST_x19_checks': bchecks, 'B_spot_c': spot, 'C_E1_equals_639': True}, 'result_threshold_186': { 'E_h': decimal(E1, 30), 'E_h2': decimal(E2, 30), 'disjoint_pairs_term': decimal(res['Ed'][A2], 30), 'overlap_term_x2': decimal(2 * res['Eo'][A2], 30), 'V_h': decimal(V, 30), 'V_h_float': float(V), 'V_over_E': decimal(V / E1, 20), 'cantelli_V_over_V_plus_E2': decimal(cant, 20), 'cantelli_float': float(cant), 'chebyshev_V_over_E2': decimal(cheb, 20), 'prereg_threshold_E2_over_99': decimal(thresh, 20), 'prereg_bound_below_1e-2': V < thresh, 'unconditioned_E_for_reference': '5000696/189337', }, } json.dump(out, sys.stdout, indent=1, sort_keys=True) sys.stdout.write('\n') log('total %.1fs' % (time.perf_counter() - t0)) if __name__ == '__main__': try: sys.stdout.reconfigure(newline='\n') except AttributeError: pass main()