unitsign.py

Checks: COORDINATES: Size under indices criterion.

Cited on: COORDINATES.

To run it: save unitsign.py; standard library only.

"""unitsign.py -- which reads of a unit's channels fix its sign?

QUESTION. M squarefree, x in U(M) read as its least residue, its sign
[2x >= M]. Read the channels of a divisor P > 1 of M (an index at a
channel is a bijection of the residue there, so reading indices is
reading residues on U(M)). For which (M, P, r), r a unit mod P, do all
units x = r mod P carry one sign? A first count put such classes at
Z/2, Z/6 and Z/30 only among the rungs, none from Z/210 to Z/30030 at
one channel.

BY HAND (before any engine code).
  (a) THE FIBRE. N = M/P, coprime to P. The class's elements are
  x = r + P t, t in [0, N), and x is a unit iff gcd(r + P t, N) = 1 iff
  t - a is coprime to N, a = -r P^(-1) mod N: the class's units are a
  translate of the integers coprime to N. Its sign is 1 iff
  t >= N/2 - r/P; as 0 < r/P < 1 the split T = ceil(N/2 - r/P) leaves
  each side a run of at least floor(N/2) consecutive t. So the class
  holds both signs when j(N) <= floor(N/2), j(N) Jacobsthal's: the
  least J with every J consecutive integers holding one coprime to N.
  (b) LEGENDRE. L consecutive integers hold sum over d | N of mu(d)
  (L/d + theta_d) coprime to N, |theta_d| < 1, so more than
  L phi(N)/N - 2^w, w = omega(N): j(N) <= floor(N/2) once
  floor(N/2) phi(N)/N >= 2^w, which holds when
  F(N)(1 - 1/N) >= 2, F(N) = prod over q | N of (q - 1)/2. A prime
  q >= 11 gives F >= 5/2 and 1 - 1/N >= 10/11, so F(1 - 1/N) > 2;
  else the primes lie in {2, 3, 5, 7}, factors 1/2, 1, 2,
  3, and the bound fails only at N in {1, 2, 3, 5, 6, 10, 14, 15, 30,
  42}. By hand, the gaps between integers coprime to N: j(5) = 2,
  j(10) = 4, j(14) = 4, j(15) = 3, j(30) = 6, j(42) = 6, each at most
  floor(N/2); and j(1) = 1, j(2) = 2, j(3) = 2, j(6) = 4, each above.
  So every class holds both signs unless N is 1, 2, 3 or 6.
  (c) THE FOUR. N = 1, 2: each class is one unit, its sign fixed.
  N = 3: the units are {0, 1, 2} less a; T = 1 iff 2r >= P, where the
  class is {1, 2}, sign 1, iff a = 0 iff 3 | r; T = 2 iff 2r < P, the
  class {0, 1}, sign 0, iff a = 2 iff r = P mod 3. N = 6: T = 3, the
  units {a - 1, a + 1} mod 6, inside {0, 1, 2} iff a = 1 iff
  r = -P mod 6 (sign 0), inside {3, 4, 5} iff a = 4 iff r = 2P mod 6
  (sign 1). The CRITERION: the class r mod P has one sign iff N <= 2,
  or N = 3 and (2r >= P and 3 | r, or 2r < P and r = P mod 3), or
  N = 6 and r = -P or 2P mod 6.
  (d) THE RUNGS, one channel p of M = p_k#: N = M/p is 1, 2, 3 or 6
  only at (k, p) = (1, 2), (2, 3), (2, 2), (3, 5). At (2, 2), P = 2,
  r = 1: 2r >= P and 3 does not divide 1, and 2r < P fails: both
  signs (1 and 5). So the classes of one sign: k = 1 (r = 1), k = 2,
  p = 3 (r = 1, 2), k = 3, p = 5 (r = 1 by -5 = 1 mod 6, sign 0; r = 4
  by 10 = 4 mod 6, sign 1), and none from Z/210 on, every k.

  (e) THE FUNCTION (ADDED after the run, by hand; no change to the
  kill). The sign is a function of the channels of P on U(M) iff
  N <= 2, that is iff they determine the unit, a unit's residue at 2
  being 1. At N = 6, P is prime to 6 and P >= 5, so r = 3 is a unit
  mod P, and 3 is neither -P nor 2P mod 6 (those are 1 or 5, and
  even): both signs. At N = 3: if P = 2 mod 3, r = 1 fails both
  clauses; if P = 1 mod 3 and P odd, then P >= 7 and r = 2 has 2r < P
  and 2 not P mod 3; if P = 1 mod 3 and P even, P >= 10 and r = 3 does
  the same.

FAMILY. Every squarefree M <= 2310 (the rung p_5# included), every
divisor P > 1 of M, every unit r mod P: the criterion against the
class's units enumerated. The rungs k = 1 .. 7 (to 510510) at one
channel. The ten N of (b) by brute force.

CONTROLS (read before any verdict).
  HAND: Z/6's channel 3 fixes both classes ({1} sign 0, {5} sign 1);
  Z/30's channel 5 fixes 1 ({1, 11}, sign 0) and 4 ({19, 29}, sign 1),
  not 2 ({7, 17}) or 3 ({13, 23}); Z/30's P = 10 fixes 9 ({19, 29}).
  PLANT: the criterion with N = 6's sign-1 class at r = -2P mod 6
  must mismatch the enumeration somewhere in the family.
  JACOBSTHAL: the brute j at the ten N of (b) equals the hand values.

KILL (frozen; what the script PRINTS): "CRITERION: X mismatches over
Y classes (squarefree M <= 2310, every P > 1)" and "RUNGS: one sign
at (k, p, r) = [...]". It fires iff X > 0 or the rung list differs
from [(1, 2, 1), (2, 3, 1), (2, 3, 2), (3, 5, 1), (3, 5, 4)].

PREDICTIONS. X = 0 (strongly: (a) to (c) are a proof); the rung list
as (d) (strongly); the controls pass.

FINDINGS. The kill misses; every prediction held.
  "CRITERION: 0 mismatches over 1620223 classes (squarefree M <= 2310,
  every P > 1)"; "one-sign classes by N = M/P: {1: 1140579, 2: 229070,
  3: 35008, 6: 6898}", every N of (c) populated; "RUNGS: one sign
  at (k, p, r) = [(1, 2, 1), (2, 3, 1), (2, 3, 2), (3, 5, 1), (3, 5,
  4)]" to k = 7. The PLANT reads "6898 mismatches, first (30, 5, 2,
  [0, 1], 1)": the plant moves N = 6's sign-1 classes.
  "(M, P) where 'every class one sign' differs from M/P <= 2: 0", (e).
  The criterion is (a) to (c)'s proof at every squarefree M; the family
  only reads it. 8/8 checks, 1.8 s; 10.9 MB peak.

RUN: python unitsign.py.
"""
import os
import sys
import time
from math import gcd

os.environ.setdefault("OPENBLAS_NUM_THREADS", "1")
CHECKS = []
TOP = 2310
RUNG_K = 7


def check(name, ok, detail=""):
    CHECKS.append(bool(ok))
    tail = f"  ({detail})" if detail else ""
    print(f"  {'PASS' if ok else 'FAIL'}  {name}{tail}", flush=True)


def primes_upto(n):
    sieve = bytearray([1]) * (n + 1)
    sieve[0:2] = bytes(2)
    for i in range(2, int(n ** 0.5) + 1):
        if sieve[i]:
            sieve[i * i::i] = bytearray(len(sieve[i * i::i]))
    return [i for i in range(n + 1) if sieve[i]]


def factor_sqfree(m, primes):
    """The prime list of m if m is squarefree, else None."""
    out = []
    for q in primes:
        if q * q > m:
            break
        if m % q == 0:
            m //= q
            if m % q == 0:
                return None
            out.append(q)
    if m > 1:
        out.append(m)
    return out


def classes(M, P):
    """{r: set of signs} over the units of U(M), r = x mod P."""
    out = {}
    for x in range(M):
        if gcd(x, M) == 1:
            out.setdefault(x % P, set()).add(int(2 * x >= M))
    return out


def criterion(M, P, r, plant=False):
    """(c): the sign the class r mod P is fixed at, or None."""
    N = M // P
    if N <= 2:
        return "fixed"
    if N == 3:
        if 2 * r >= P and r % 3 == 0:
            return 1
        if 2 * r < P and (r - P) % 3 == 0:
            return 0
        return None
    if N == 6:
        if (r + P) % 6 == 0:
            return 0
        if (r - (-2 * P if plant else 2 * P)) % 6 == 0:
            return 1
        return None
    return None


def jacobsthal(N):
    """The least J with every J consecutive integers holding one
    coprime to N (one period suffices)."""
    cop = [t for t in range(1, 2 * N + 2) if gcd(t, N) == 1]
    return max(b - a for a, b in zip(cop, cop[1:]))


def family(plant=False):
    primes = primes_upto(TOP)
    cells = mism = 0
    witness = None
    byN = {}
    func_bad = 0
    for M in range(2, TOP + 1):
        ps = factor_sqfree(M, primes)
        if ps is None:
            continue
        for mask in range(1, 1 << len(ps)):
            P = 1
            for i, q in enumerate(ps):
                if mask >> i & 1:
                    P *= q
            cl = classes(M, P)
            if all(len(v) == 1 for v in cl.values()) != (M // P <= 2):
                func_bad += 1
            for r, signs in cl.items():
                cells += 1
                c = criterion(M, P, r, plant)
                fixed = len(signs) == 1
                if fixed:
                    byN[M // P] = byN.get(M // P, 0) + 1
                ok = (c is None and not fixed) or (
                    fixed and (c == "fixed" or c == next(iter(signs))))
                if not ok:
                    mism += 1
                    witness = witness or (M, P, r, sorted(signs), c)
    return cells, mism, witness, byN, func_bad


def rungs():
    ps = primes_upto(20)
    out = []
    M = 1
    for k in range(1, RUNG_K + 1):
        M *= ps[k - 1]
        units = [x for x in range(M) if gcd(x, M) == 1]
        for p in ps[:k]:
            signs = {}
            for x in units:
                signs.setdefault(x % p, set()).add(int(2 * x >= M))
            out += [(k, p, r) for r, s in sorted(signs.items())
                    if len(s) == 1]
    return out


if __name__ == "__main__":
    t0 = time.time()
    print("CONTROLS")
    c6, c30, c30b = classes(6, 3), classes(30, 5), classes(30, 10)
    check("HAND: Z/6 channel 3 fixes {1} at 0 and {5} at 1",
          c6 == {1: {0}, 2: {1}})
    check("HAND: Z/30 channel 5 fixes 1 at 0 and 4 at 1, not 2 or 3",
          c30 == {1: {0}, 4: {1}, 2: {0, 1}, 3: {0, 1}})
    check("HAND: Z/30 at P = 10 fixes 9 at 1", c30b[9] == {1})
    hand = {1: 1, 2: 2, 3: 2, 5: 2, 6: 4, 10: 4, 14: 4, 15: 3, 30: 6,
            42: 6}
    js = {N: jacobsthal(N) for N in hand}
    check("JACOBSTHAL: brute j equals the hand values at the ten N",
          js == hand, str(js))
    _, pm, pw, _, _ = family(plant=True)
    check("PLANT: N = 6's sign-1 class at -2P mismatches somewhere",
          pm > 0, f"{pm} mismatches, first {pw}")
    if not all(CHECKS):
        print("CONTROL FAILED: nothing below is read.")
        sys.exit(1)
    cells, mism, w, byN, fb = family()
    print(f"  (M, P) where 'every class one sign' differs from M/P <= 2: {fb}")
    print(f"  one-sign classes by N = M/P: {dict(sorted(byN.items()))}")
    print(f"CRITERION: {mism} mismatches over {cells} classes "
          f"(squarefree M <= {TOP}, every P > 1)" + (f", first {w}" if w else ""))
    rl = rungs()
    print(f"RUNGS: one sign at (k, p, r) = {rl}")
    want = [(1, 2, 1), (2, 3, 1), (2, 3, 2), (3, 5, 1), (3, 5, 4)]
    fired = mism > 0 or rl != want
    print(f"KILL fires: {fired}")
    check("CRITERION: (c) agrees with the enumeration at every class",
          mism == 0)
    check("FUNCTION: every class one sign iff M/P <= 2", fb == 0)
    check(f"RUNGS: the one-sign classes to k = {RUNG_K} are (d)'s",
          rl == want)
    print(f"\n{sum(CHECKS)}/{len(CHECKS)} checks, {time.time() - t0:.1f} s")
    sys.exit(0 if all(CHECKS) else 1)