Structural Cancellative (Kulovany) Method
#!/usr/bin/env python3
"""
SCM — Structural Cancellative (Kulovany) Method v0.7
==========================================
Author: Josef Kulovany + zchg.org
A true CLI tool. Feed any equation, any arguments.
The four passes reduce structure to 1=1 in O(1).
USAGE EXAMPLES:
scm # interactive REPL
scm --fixed # canonical fixed point
scm -x 0 -y 0 -p 1 -m -1 # explicit coordinates
scm --eq "y**2 - 2*p*x*y + p**2*(x**2-1) - m**2" # any equation
scm --eq "x**3 + y**3 - p**3" -x 1 -y 0 -p 1 # cubic
scm --identity # print T12 Kulovany Identity
scm --theorems # print T1-T12
scm --symp 8 -x 0 -y 1 # symplectic loop
scm --scan --eq "y**2 - 2*p*x*y + p**2*(x**2-1) - m**2" # scan for anchors
"""
import math, sys, argparse, ast, re
from itertools import product
PHI = (1 + math.sqrt(5)) / 2
# ── colour helpers ────────────────────────────────────────────────────────────
def green(s): return f"\033[92m{s}\033[0m"
def red(s): return f"\033[91m{s}\033[0m"
def cyan(s): return f"\033[96m{s}\033[0m"
def bold(s): return f"\033[1m{s}\033[0m"
def yellow(s): return f"\033[93m{s}\033[0m"
def dim(s): return f"\033[2m{s}\033[0m"
# ── equation evaluator ────────────────────────────────────────────────────────
SAFE_NAMES = {
'sin': math.sin, 'cos': math.cos, 'tan': math.tan,
'exp': math.exp, 'log': math.log, 'sqrt': math.sqrt,
'abs': abs, 'pi': math.pi, 'e': math.e, 'phi': PHI,
}
def eval_eq(expr: str, vals: dict) -> float:
"""
Safely evaluate an equation string with given variable bindings.
Returns nan on any math domain error (log of negative, sqrt of negative, etc.)
"""
ns = {**SAFE_NAMES, **vals}
try:
return float(eval(compile(expr, '<eq>', 'eval'), {"__builtins__": {}}, ns))
except ZeroDivisionError:
return float('nan')
except ValueError:
return float('nan')
except Exception as e:
raise ValueError(f"Cannot evaluate '{expr}' with {vals}: {e}")
def detect_vars(expr: str) -> list:
"""Extract variable names from an expression string."""
# find all identifiers that aren't known functions/constants
tokens = re.findall(r'\b([a-zA-Z_][a-zA-Z0-9_]*)\b', expr)
known = set(SAFE_NAMES.keys()) | {'and', 'or', 'not', 'in', 'is'}
return sorted(set(t for t in tokens if t not in known))
# ── SCM passes ───────────────────────────────────────────────────────────────
def pass0_find_hyperplane_zeros(eq, vals, search_range=(-10, 10), steps=2000):
"""
Pass 0: Genuine Hyperplane Zero Search
THIS is what it means for the algo to 'add its own zero':
not injecting 0 as a default value, but FINDING where the
equation actually equals zero on each Cartesian hyperplane.
For each spatial variable, sets all others to zero and sweeps
the free variable to find sign changes (roots by bisection).
Returns dict: var -> list of real roots found on that axis.
This is what makes the method universal:
- If roots exist on the hyperplane -> anchor is real
- If no roots exist on any hyperplane -> honest MISS
- The tool never manufactures an anchor via default injection
"""
skip = {'p', 'm'}
# sweep variables that actually appear in the equation
eq_vars = set(detect_vars(eq))
# always sweep spatial vars found in equation
# also sweep p and m if they appear AND no spatial vars exist
spatial = sorted(k for k in vals if k not in skip and k in eq_vars)
params = {k: vals[k] for k in ('p', 'm') if k in vals}
# if equation only involves p and/or m, sweep them too
param_only = not spatial and any(v in eq_vars for v in ('p','m'))
if param_only:
sweep_vars = sorted(k for k in ('p','m') if k in eq_vars and k in vals)
base_fixed = {k: vals[k] for k in vals if k not in sweep_vars}
else:
sweep_vars = spatial
base_fixed = params
lo, hi = search_range
step_size = (hi - lo) / steps
results = {}
for free_var in sweep_vars:
zeros_found = []
# zero all other sweep vars, fix params
base = {v: 0.0 for v in sweep_vars}
base.update(base_fixed)
prev_val, prev_t = None, None
t = lo
while t <= hi:
base[free_var] = t
f = eval_eq(eq, base)
if not math.isnan(f):
if prev_val is not None and prev_val * f < 0:
# sign change — bisect
a, b, fa = prev_t, t, prev_val
for _ in range(52):
mid = (a + b) / 2
base[free_var] = mid
fmid = eval_eq(eq, base)
if math.isnan(fmid):
break
if abs(fmid) < 1e-12:
break
if fa * fmid < 0:
b = mid
else:
a, fa = mid, fmid
final_f = eval_eq(eq, {**base, free_var: mid})
# only accept if genuinely near zero, not a pole crossing
if not math.isnan(final_f) and abs(final_f) < 1e-6:
zeros_found.append(round(mid, 10))
elif abs(f) < 1e-10:
zeros_found.append(round(t, 10))
prev_val, prev_t = f, t
else:
# domain error — reset sign tracking to avoid false crossings
prev_val, prev_t = None, None
t += step_size
results[free_var] = sorted(set(zeros_found))
return results
def pass1_field_isolation(vals, eq):
"""Isolate scalar field. Cost: zero FP ops — symbolic shift."""
result = eval_eq(eq, vals)
return result, abs(result) < 1e-10
def pass2_unitary_mapping(vals):
"""
Inject linear test line L = y - p*x*y + p*(x-1).
L/L = 1 always. Cost: one identity check.
For equations without x/y/p, falls back to a generic
unitary check using the first two spatial variables found.
"""
x = vals.get('x', None)
y = vals.get('y', None)
p = vals.get('p', 1.0)
if x is None or y is None:
# generalize: pick first two spatial vars alphabetically
skip = {'p', 'm'}
spatial_keys = sorted(k for k in vals if k not in skip)
if len(spatial_keys) >= 2:
x = vals[spatial_keys[0]]
y = vals[spatial_keys[1]]
elif len(spatial_keys) == 1:
x = vals[spatial_keys[0]]
y = 0.0
else:
return 1.0, True, "UNITARY CONFIRMED: L/L = 1 (no spatial vars, trivially)"
L = y - p*x*y + p*(x - 1)
if abs(L) < 1e-12:
return L, False, "DEGENERATE: L=0 (x=1 boundary excluded — T3)"
return L, True, "UNITARY CONFIRMED: L/L = 1"
def pass3_parameter_collapse(vals):
"""
Symbolic cancellation: (x-1)/p(x-1) -> p=1 [quadratic]
p = 1+1/p -> p=phi [cubic]
Cost: one symbolic cancellation.
When x is absent, uses first spatial variable found.
When p is absent, collapses to unity by default.
"""
skip = {'p', 'm'}
spatial_keys = sorted(k for k in vals if k not in skip)
x = vals.get('x', vals[spatial_keys[0]] if spatial_keys else 0.0)
p = vals.get('p', 1.0)
if abs(x - 1) < 1e-12:
return None, "EXCLUDED: x=1 silent boundary (T3)"
# cubic test
cubic_residual = p**2 - p - 1
if abs(cubic_residual) < 1e-10:
return PHI, f"PHI_ATTRACTOR: p=φ={PHI:.8f} (T11 cubic)"
return 1.0, "UNITY_ATTRACTOR: p=1 (T2 quadratic)"
def pass4_anchor_extraction(vals):
"""
Generalized anchor extraction for any number of variables.
The SCM spatial filter generalizes from xy=0 to:
product of all free spatial variables = 0
At least one variable must be zero for the structural
anchor to hold. This is the Cartesian hyperplane condition:
the solution lies on one of the coordinate hyperplanes.
Cost: one boolean check per variable — still O(n) in variable
count but O(1) in the equation's degree.
"""
# spatial vars: everything except p and m (parameters)
skip = {'p', 'm'}
spatial = {k: v for k, v in vals.items() if k not in skip}
if not spatial:
return False, "NO_SPATIAL_VARS", {}
zeros = {k for k, v in spatial.items() if abs(v) < 1e-12}
nonzeros = {k for k in spatial if k not in zeros}
product_val = 1.0
for v in spatial.values():
product_val *= v
anchor = len(zeros) > 0
if anchor:
if len(zeros) == len(spatial):
axis = "ORIGIN"
else:
axis = f"HYPERPLANE ({', '.join(sorted(zeros))}=0)"
return True, axis, product_val
return False, f"OFF_HYPERPLANE — no variable is zero {dict(spatial)}", product_val
def verify_halt(vals, eq):
"""
T6: -1=1 is HALT SIGNAL not ERROR.
The structural sign absorber carries the flip from Pass 3.
Generalized: operates on the actual equation passed in,
not the canonical Y²-2pxy+p²(x²-1)=m² hardcode.
Two conditions checked:
1. The equation evaluates to zero at the anchor point (field confirmed)
2. The structural sign absorption holds: f(vals) and -f(vals) are conjugate
via the linear projection, producing the -1=1 state
"""
f = eval_eq(eq, vals)
rhs = vals.get('m', -1) ** 2
# field satisfied at anchor
field_zero = abs(f) < 1e-8
# structural sign absorption: equation value == -rhs (the contradiction state)
# i.e. f = -1 and rhs = 1, so f = -rhs
contradiction = abs(f + rhs) < 1e-6 and abs(abs(f) - rhs) < 1e-6
# unitary structural check via projection line
x = vals.get('x', 0)
y = vals.get('y', 0)
p = vals.get('p', 1)
m_struct = y - p*x*y + p*(x - 1)
structural_ok = abs(m_struct**2 - rhs) < 1e-8
if field_zero:
return True, "HALT: equation zero at anchor — field confirmed (T6)"
if contradiction and structural_ok:
return True, "HALT: −1=1 contradiction balanced by structural sign absorption (T6,T7)"
if structural_ok:
return True, "HALT: structural match confirmed via projection line"
return False, f"MISS: f={f:.6g}, rhs={rhs:.6g}, m_struct={m_struct:.6g}"
# ── full pipeline ─────────────────────────────────────────────────────────────
def run_pipeline(vals: dict, eq: str, verbose=True) -> dict:
"""
Run the full SCM pipeline on any equation with any variable bindings.
Pass 0: Find genuine zeros on each Cartesian hyperplane (no injected defaults)
Pass 1: Field isolation
Pass 2: Unitary mapping
Pass 3: Parameter collapse
Pass 4: Anchor extraction — uses Pass 0 roots, not injected zeros
Halt: T6 contradiction signal
"""
# Pass 0 — genuine root search on hyperplanes
hp_zeros = pass0_find_hyperplane_zeros(eq, vals)
any_real_anchor = any(len(zs) > 0 for zs in hp_zeros.values())
# if Pass 0 found real roots, evaluate at the first one for subsequent passes
eval_vals = dict(vals)
anchor_point = {}
if any_real_anchor:
# pick first axis with a root, use that root as the anchor point
for var, roots in hp_zeros.items():
if roots:
skip = {'p', 'm'}
spatial = [k for k in vals if k not in skip]
# zero all spatial, set free var to its root
for sv in spatial:
eval_vals[sv] = 0.0
eval_vals[var] = roots[0]
anchor_point = {var: roots[0]}
break
f_val, field_ok = pass1_field_isolation(eval_vals, eq)
L, unitary_ok, msg2 = pass2_unitary_mapping(eval_vals)
p_col, attractor = pass3_parameter_collapse(eval_vals)
anchor_ok, axis, xy = pass4_anchor_extraction(eval_vals)
halt_ok, halt_msg = verify_halt(eval_vals, eq)
# genuine success: Pass 0 found and verified a real root on a hyperplane,
# AND Pass 4 confirms anchor (at least one var zero at eval point).
# Pass 3 exclusion (x=1 boundary) is advisory — Pass 0 independently
# verified the root exists, so it overrides the exclusion.
# Halt must also confirm.
genuine_anchor = any_real_anchor and anchor_ok
success = genuine_anchor and halt_ok
result = {
'input': vals,
'equation': eq,
'pass0': {
'hyperplane_roots': hp_zeros,
'any_real_anchor': any_real_anchor,
'anchor_point': anchor_point,
'cost': 'O(n_vars * sweep)'
},
'pass1': {'f_value': f_val, 'eq_satisfied': field_ok, 'cost': 'ZERO_FP'},
'pass2': {'L': L, 'unitary': unitary_ok, 'msg': msg2, 'cost': 'ONE_CHECK'},
'pass3': {'p_collapsed': p_col, 'attractor': attractor, 'cost': 'ONE_CANCEL'},
'pass4': {'anchor': anchor_ok, 'axis': axis, 'xy': xy, 'cost': 'ONE_BOOL'},
'halt': {'confirmed': halt_ok, 'msg': halt_msg},
'success': success,
'cost': 'O(n_vars) sweep + O(1) structural',
}
if verbose:
print_report(result)
return result
def print_report(r: dict):
ok = lambda b: green("✓") if b else red("✗")
sep = dim("─" * 62)
print()
print(bold(cyan("SCM v0.3 — PIPELINE REPORT")))
print(sep)
print(f" {bold('Equation:')} {r['equation']}")
print(f" {bold('Input: ')} {r['input']}")
print(sep)
p0 = r['pass0']
print(f" {cyan('Pass 0')} Hyperplane Search {ok(p0['any_real_anchor'])}")
for var, roots in p0['hyperplane_roots'].items():
if roots:
print(f" {var}-axis roots: {roots}")
else:
print(f" {dim(var+'-axis: no real roots')}")
if p0['anchor_point']:
print(f" {dim('evaluating at: '+str(p0['anchor_point']))}")
p1 = r['pass1']
print(f" {cyan('Pass 1')} Field Isolation {ok(p1['eq_satisfied'])} "
f"f={p1['f_value']:.6g} [{p1['cost']}]")
p2 = r['pass2']
print(f" {cyan('Pass 2')} Unitary Mapping {ok(p2['unitary'])} "
f"L={p2['L']:.6g} {dim(p2['msg'])}")
p3 = r['pass3']
print(f" {cyan('Pass 3')} Parameter Collapse {ok(p3['p_collapsed'] is not None)} "
f"p→{p3['p_collapsed']} {dim(p3['attractor'])}")
p4 = r['pass4']
prod = p4['xy']
prod_str = f"{prod:.6g}" if isinstance(prod, float) else str(prod)
print(f" {cyan('Pass 4')} Anchor Extraction {ok(p4['anchor'])} "
f"∏vars={prod_str} {p4['axis']}")
ht = r['halt']
print(f" {cyan('Halt ')} T6 Signal {ok(ht['confirmed'])} "
f"{dim(ht['msg'])}")
print(sep)
status = green("SUCCESS — ANCHOR CONFIRMED") if r['success'] else red("MISS — outside SCM domain")
print(f" {bold('Result:')} {status} {dim('['+r['cost']+']')}")
print()
# ── anchor scanner ────────────────────────────────────────────────────────────
def scan_anchors(eq: str, p=1, m=-1, rng=(-3,3)):
"""
Scan integer grid for xy=0 solutions of any equation.
Only looks on Cartesian axes — that's the whole point.
"""
print(bold(cyan(f"\nANCHOR SCAN — '{eq}'")))
print(dim(f" p={p}, m={m}, range={rng}, scanning axes only (xy=0 domain)"))
print()
hits = []
lo, hi = rng
# x-axis: y=0
for x in range(lo, hi+1):
vals = {'x': float(x), 'y': 0.0, 'p': float(p), 'm': float(m)}
try:
v = eval_eq(eq, vals)
if abs(v) < 1e-8:
hits.append((x, 0, v))
print(f" {green('HIT')} x={x:3d}, y=0 f={v:.2e}")
except:
pass
# y-axis: x=0
for y in range(lo, hi+1):
if y == 0: continue # already checked origin
vals = {'x': 0.0, 'y': float(y), 'p': float(p), 'm': float(m)}
try:
v = eval_eq(eq, vals)
if abs(v) < 1e-8:
hits.append((0, y, v))
print(f" {green('HIT')} x=0, y={y:3d} f={v:.2e}")
except:
pass
if not hits:
print(f" {red('No anchors found on axes in range')} {rng}")
print()
return hits
# ── symplectic loop ───────────────────────────────────────────────────────────
def symplectic_loop(x0, y0, steps):
"""T9: sign lives in operation order, not a stored value."""
x, y = float(x0), float(y0)
rows = [(0, x, y)]
for i in range(steps):
tmp = x
x = x + y
y = y - tmp
rows.append((i+1, x, y))
return rows
# ── text blocks ───────────────────────────────────────────────────────────────
THEOREMS = f"""
{bold(cyan('THEOREMS — Structural Cancellative Method v0.3'))}
{'='*62}
T1 Degree Invariance xy=0 anchor holds regardless of polynomial degree
T2 Parameter Unity Quadratic SCM always collapses p→1
T3 Sign Absorption −1 carries functional load of ±i via structural routing
T4 Unitary Metric Free L/L=1 costs zero compute
T5 Spatial Filter xy=0 replaces all curve scanning O(1)
T6 Contradiction as Halt −1=1 is ANCHOR CONFIRMED not ERROR
T7 Sign Carried Sign inversion absorbed in Pass 3, arrives pre-resolved
T8 Zero Complex Memory No separate real/imaginary registers needed
T9 Symplectic Loop Sign lives in operation order not a stored value
T10 Degree Collapse 4th-degree monomials solved by 1st-degree assertions
T11 Degree-Indexed FP Quadratic→p=1 Cubic→p=φ={PHI:.8f}
T12 Kulovany Identity sqrt(−1) is a structural role, not a number extension
Binary: all-1s Trinary: T Complex: i
The equation is the unified selector across all three
"""
IDENTITY = f"""
{bold(cyan('='*64))}
{bold(cyan(' KULOVANY IDENTITY (T12)'))}
{bold(cyan('='*64))}
The equation:
Y² − 2pxy + p²(x²−1) = m²
At fixed point x=0, y=0, p=1 requires:
m² = −1
This has been called impossible in the reals and patched
with the extension sqrt(−1) = i.
We show this is not a patch.
It is a structural necessity that every number system
satisfies natively, in its own terms:
{bold('COMPLEX')} m = ±i i² = −1 exactly
i is a 90° rotation operator, not a fake number
{bold('BINARY')} m² = 1 = −1 via two's complement: all-1s IS −1
−1 = 1 is literally true by representation
2(pxy) becomes a left shift — coefficient is positional
{bold('TRINARY')} m = T T² = 1, T is the native negative trit
{{T, 0, 1}} = the fixed point values = the trit alphabet
The equation selects its own number system as solution
2 is not native → decomposes to carry = structural squaring
{bold('UNIFIED TABLE')}
┌─────────┬──────────┬──────────────────────┬────────┬───────────────┐
│ System │ Unit │ −1 representation │ m │ 2(pxy) │
├─────────┼──────────┼──────────────────────┼────────┼───────────────┤
│ Binary │ 1 │ two's complement │ 1 ≡ −1 │ left shift │
│ Trinary │ {{T,0,1}} │ native trit T │ T │ carry/sqr │
│ Complex │ i │ i² = −1 │ ±i │ rotation │
└─────────┴──────────┴──────────────────────┴────────┴───────────────┘
{bold('CONCLUSION')}
sqrt(−1) does not require extension of the reals.
It requires recognition that every number system already
contains the structural role i fills — under its own native
representation.
"Imaginary" numbers are not imaginary.
They are the name we gave to a structural necessity
that was always present, in every system, waiting to be seen.
The equation Y² − 2pxy + p²(x²−1) = m² is the witness.
Each number system contains exactly one unit that squares
to −1 or its structural equivalent.
The equation finds it without being told which system it is in.
{bold(cyan('='*64))}
"""
# ── REPL ──────────────────────────────────────────────────────────────────────
DEFAULT_EQ = "y**2 - 2*p*x*y + p**2*(x**2-1) - m**2"
def repl():
print(bold(cyan("\nSCM v0.3 — Interactive REPL")))
print(dim("Type 'help' for commands, 'quit' to exit\n"))
eq = DEFAULT_EQ
vals = {'x': 0.0, 'y': 0.0, 'p': 1.0, 'm': -1.0}
HELP = f"""
{bold('Commands')}
set x 0 set a variable
eq <expr> set equation (use x,y,p,m or any vars)
run run SCM pipeline
scan scan axes for anchors
symp <n> symplectic loop n steps
vars show current variable state
identity print T12 Kulovany Identity
theorems print T1-T12
reset reset to fixed point defaults
quit / exit exit
"""
while True:
try:
line = input(cyan("scm> ")).strip()
except (EOFError, KeyboardInterrupt):
print()
break
if not line:
continue
parts = line.split()
cmd = parts[0].lower()
if cmd in ('quit','exit','q'):
break
elif cmd == 'help':
print(HELP)
elif cmd == 'identity':
print(IDENTITY)
elif cmd == 'theorems':
print(THEOREMS)
elif cmd == 'vars':
print(f" equation: {yellow(eq)}")
for k,v in sorted(vals.items()):
print(f" {k} = {v}")
elif cmd == 'reset':
eq = DEFAULT_EQ
vals = {'x':0.0,'y':0.0,'p':1.0,'m':-1.0}
print(green(" reset to fixed point defaults"))
elif cmd == 'eq' and len(parts) >= 2:
eq = ' '.join(parts[1:])
# auto-detect new vars and zero them
for v in detect_vars(eq):
if v not in vals:
vals[v] = 0.0
print(dim(f" new variable '{v}' initialized to 0"))
print(green(f" equation set: {eq}"))
elif cmd == 'set' and len(parts) == 3:
try:
vals[parts[1]] = float(parts[2])
print(green(f" {parts[1]} = {vals[parts[1]]}"))
except ValueError:
print(red(f" invalid value: {parts[2]}"))
elif cmd == 'run':
run_pipeline(vals, eq)
elif cmd == 'scan':
scan_anchors(eq, p=vals.get('p',1), m=vals.get('m',-1))
elif cmd == 'symp' and len(parts) == 2:
try:
n = int(parts[1])
rows = symplectic_loop(vals.get('x',0), vals.get('y',0), n)
print(bold(f"\n Symplectic loop from (x={vals.get('x',0)}, y={vals.get('y',0)})"))
print(dim(" step x y"))
for step, x, y in rows:
print(f" {step:4d} {x:12.6f} {y:12.6f}")
print()
except ValueError:
print(red(" usage: symp <n>"))
else:
print(red(f" unknown command: '{line}' (type 'help')"))
# ── main ──────────────────────────────────────────────────────────────────────
def main():
p = argparse.ArgumentParser(
prog='scm',
description=bold('SCM v0.3 — Structural Cancellative Method'),
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog=dim("""
positional style (new):
scm eq "phi-x"
scm eq "x**2+y**2-1" x=1 y=0
scm eq "phi-x" x=1.61803398875
scm scan
scm symp 20
scm vars
scm fixed
scm run
scm identity
scm theorems
flag style (also supported):
scm --fixed
scm -x 0 -y 0 -p 1 -m -1
scm --eq "y**2 - 2*p*x*y + p**2*(x**2-1) - m**2"
scm --scan
scm --symp 8 -x 0 -y 1
scm --identity
scm --theorems
scm --quiet
no args: interactive REPL
""")
)
p.add_argument('-x', type=float, default=None)
p.add_argument('-y', type=float, default=None)
p.add_argument('-p', type=float, default=None)
p.add_argument('-m', type=float, default=None)
p.add_argument('--eq', type=str, default=None,
help='equation string evaluating to 0 at solution')
p.add_argument('--fixed', action='store_true',
help='run canonical fixed point (x=0,y=0,p=1,m=-1)')
p.add_argument('--scan', action='store_true',
help='scan Cartesian axes for anchors')
p.add_argument('--symp', type=int, default=0,
help='run symplectic loop N steps')
p.add_argument('--identity', action='store_true')
p.add_argument('--theorems', action='store_true')
p.add_argument('--quiet', action='store_true',
help='machine-readable output')
# ------------------------------------------------------------
# Positional command compatibility
#
# Allows:
# scm eq "phi-x"
# scm eq "x**2+y**2-1" x=1 y=0
# scm scan
# scm symp 20
# scm vars
# scm fixed
# scm run
# scm identity
# scm theorems
#
# while keeping all existing argparse flag options.
# ------------------------------------------------------------
argv = sys.argv[1:]
if argv and not argv[0].startswith("-"):
cmd = argv[0].lower()
if cmd == "identity":
print(IDENTITY)
return
if cmd == "theorems":
print(THEOREMS)
return
if cmd == "vars":
print("Current defaults")
print()
print("x = 0")
print("y = 0")
print("p = 1")
print("m = -1")
print()
print("Equation:")
print(DEFAULT_EQ)
return
if cmd in ("fixed", "run"):
run_pipeline(
{"x": 0.0, "y": 0.0, "p": 1.0, "m": -1.0},
DEFAULT_EQ
)
return
if cmd == "scan":
scan_anchors(DEFAULT_EQ)
return
if cmd == "symp":
steps = 10
if len(argv) > 1:
try:
steps = int(argv[1])
except ValueError:
print(red(f" symp requires an integer, got: {argv[1]}"))
return
rows = symplectic_loop(0, 0, steps)
print()
print(bold(" step x y"))
for s, x, y in rows:
print(f" {s:4d} {x:12.6f} {y:12.6f}")
print()
return
if cmd == "eq":
if len(argv) < 2:
print("usage:")
print(' scm eq "expression" [var=value ...]')
print(' scm eq phi-x + y - z x=1 y=2 z=3')
return
# Collect equation tokens until we hit a k=v assignment,
# then collect assignments. This lets unquoted expressions work:
# scm eq phi-x + y - z x=1 y=2 z=3
eq_tokens = []
assign_tokens = []
for tok in argv[1:]:
# a token is an assignment if it matches word=number
if re.match(r'^[A-Za-z_]\w*=[\-\d\.]', tok):
assign_tokens.append(tok)
elif assign_tokens:
# once we've started assignments, remaining are also assignments
assign_tokens.append(tok)
else:
eq_tokens.append(tok)
eq = ' '.join(eq_tokens)
# start with standard defaults; any detected var gets 0
vals = {"x": 0.0, "y": 0.0, "p": 1.0, "m": -1.0}
# auto-init any vars found in equation
for v in detect_vars(eq):
vals.setdefault(v, 0.0)
# apply explicit assignments — these override everything
for token in assign_tokens:
if "=" not in token:
continue
k, v = token.split("=", 1)
try:
vals[k.strip()] = float(v.strip())
except ValueError:
print(red(f" bad value: {token}"))
return
run_pipeline(vals, eq)
return
# unrecognised positional — fall through to argparse for error message
pass
# fall back to argparse
args = p.parse_args()
if args.identity:
print(IDENTITY); return
if args.theorems:
print(THEOREMS); return
# no args at all → REPL
if len(sys.argv) == 1:
repl(); return
eq = args.eq or DEFAULT_EQ
vals = {
'x': args.x if args.x is not None else (0.0 if args.fixed else 0.0),
'y': args.y if args.y is not None else (0.0 if args.fixed else 0.0),
'p': args.p if args.p is not None else (1.0 if args.fixed else 1.0),
'm': args.m if args.m is not None else (-1.0),
}
# auto-detect extra vars in equation and warn
for v in detect_vars(eq):
if v not in vals:
vals[v] = 0.0
if not args.quiet:
print(dim(f" note: '{v}' not specified, defaulting to 0"))
if args.scan:
scan_anchors(eq, p=vals['p'], m=vals['m'])
return
if args.symp > 0:
rows = symplectic_loop(vals['x'], vals['y'], args.symp)
if args.quiet:
for step, x, y in rows:
print(f"{step},{x:.8f},{y:.8f}")
else:
print(bold(f"\n Symplectic loop x0={vals['x']}, y0={vals['y']}"))
print(dim(" step x y"))
for step, x, y in rows:
print(f" {step:4d} {x:12.6f} {y:12.6f}")
print()
return
result = run_pipeline(vals, eq, verbose=not args.quiet)
if args.quiet:
import json
out = {k: v for k, v in result.items() if k != 'equation'}
print(json.dumps(out, default=str))
if __name__ == '__main__':
main()
USAGE:
Since REPL accepts arbitrary equations through:
eq <expression>
where the expression should evaluate to 0 at a solution, you can exercise almost every part of the engine. Below is a large collection grouped by category.
Canonical SCM
eq y**2-2*p*x*y+p**2*(x**2-1)-m**2
run
set x 0
set y 0
set p 1
set m -1
run
Simple lines
eq x
eq y
eq x+y
eq x-y
eq 2*x-y
eq 3*x+5*y
eq x+phi*y
Quadratics
eq x**2+y**2-1
eq x**2-y
eq y**2-x
eq x**2+y**2-25
eq x*y-1
eq x*y
eq x**2-y**2
eq x**2+2*x*y+y**2
eq (x+y)**2-9
Cubics
eq x**3+y**3-1
eq x**3-y
eq y**3-x
eq x**3+y**3-27
eq x**3-3*x*y**2
eq y**3-3*x**2*y
Quartics
eq x**4+y**4-1
eq x**4-y
eq y**4-x
eq x**4+y**2-16
eq x**2*y**2-1
Higher degree
eq x**5+y**5-1
eq x**6+y**6-1
eq x**7+y**7-1
eq x**8+y**8-1
eq x**10+y**10-1
Factorizations
eq (x-1)*(y-1)
eq (x+1)*(y+1)
eq (x-1)*(x+1)
eq (x-y)*(x+y)
eq (x-2)*(y+3)
Golden ratio
eq p**2-p-1
eq x-p
eq y-p
eq x**2-p
eq y**2-p
eq x+p*y-1
Fixed point tests
eq x-(1+1/x)
eq y-(1+1/y)
eq p-(1+1/p)
eq x-(1+1/p)
Rational
eq x/(y+1)-2
eq y/(x+1)-3
eq (x+y)/(x-y)-1
eq 1/x+1/y-1
eq x/(1+x)-0.5
Exponentials
eq exp(x)-2
eq exp(y)-10
eq exp(x+y)-5
eq exp(x)-y
Logarithms
eq log(x)-1
eq log(y)-2
eq log(x+y)-3
eq log(x)-y
Trigonometry
eq sin(x)
eq cos(x)
eq tan(x)
eq sin(x)+cos(y)
eq sin(x)-y
eq cos(x)-x
eq sin(x)**2+cos(x)**2-1
Roots
eq sqrt(x)-2
eq sqrt(y)-3
eq sqrt(x+y)-5
eq sqrt(abs(x))-1
Mixed nonlinear
eq x*y+x+y
eq x*y-x-y
eq x**2+x*y+y**2
eq x**3+x*y+y
eq x**4+x**2*y+y**2
Hyperbolas
eq x*y-4
eq x*y+1
eq x*y-phi
eq x*y-p
Ellipses
eq x**2/9+y**2/4-1
eq x**2/16+y**2/25-1
Parabolas
eq y-x**2
eq x-y**2
eq y-2*x**2
Saddle surfaces
eq x**2-y**2-1
eq x*y-y
eq x*y-x
Absolute values
eq abs(x)-1
eq abs(y)-2
eq abs(x)+abs(y)-5
Constants
eq pi-x
eq e-y
eq phi-p
eq phi-x
Multi-parameter
eq a*x+b*y-c
set a 2
set b 3
set c 6
run
eq a*x**2+b*y**2-c
eq a*x*y+b*x+c
eq a*sin(x)+b*cos(y)-c
Prime-inspired
eq x**2-p
eq p**2-x
eq x**2-p**2
eq x**2-p*x+1
eq p**3-p-1
Recursive-looking
eq x-(1+1/(y+1))
eq y-(1+1/(x+1))
eq p-(1+1/(p+1))
eq x-(1+1/(1+1/x))
Stress tests
eq (((x+y)**2-1)**2)-m
eq ((x*y+p)**3)-(m**2)
eq (sin(x)+cos(y))**2-1
eq exp(sin(x))+log(y+2)-3
eq (sqrt(abs(x))+sqrt(abs(y)))**2-4
Commands beyond eq
You can also exercise the rest of the engine:
vars
scan
symp 10
identity
theorems
reset