“””

THE KEY EMERGES — contrast_branch.py

 

The contrast branch generates a plausible-looking candidate

WITHOUT survival pressure, WITHOUT admissibility filtering,

and WITHOUT invariance testing.

 

Its failure against the world is enforced by the same world

constraint that the GIE candidate must satisfy.

 

No special failure logic. No staged failure. The world is

indifferent to how the candidate was built.

 

PURPOSE:

To show that plausible appearance is insufficient.

Only structurally valid objects succeed.

 

```

The viewer sees two candidates tested against the same world.

One was built by survival under constraint.

One was built by unconstrained search.

The world decides.

```

 

CRITICAL ARCHITECTURAL RULE:

This branch must NOT originate from the GIE survived/promotion pipeline.

It represents atom-level or unconstrained evolutionary construction.

 

```

This candidate was generated with survival pressure disabled

and admissibility filter removed. Failure is enforced by the

same world constraint. No special failure logic.

```

 

WHAT THE CONTRAST CANDIDATE LOOKS LIKE:

Visually plausible — roughly circular, roughly the right size.

Slightly noisy or jagged boundaries.

Periodic-ish modulation that doesn’t quite match the lock.

Close enough to look like it might work.

Not close enough to actually work.

 

```

This is the canonical failure mode of systems that optimize

for appearance rather than structure.

```

 

“””

 

from **future** import annotations

import numpy as np

from typing import Optional, Tuple

from core_types import FailureMode

from world_constraint import (

WorldParameters, DEFAULT_WORLD,

evaluate_world, WorldResult

)

 

# —————————————————————————

 

# Unconstrained geometry generator

 

# —————————————————————————

 

def generate_overfit_candidate(world: WorldParameters = DEFAULT_WORLD,

rng: Optional[np.random.Generator] = None,

seed: int = 99) -> np.ndarray:

“””

Generate a visually plausible but structurally invalid candidate.

 

```

This candidate was generated with survival pressure disabled

and admissibility filter removed. Failure is enforced by the

same world constraint. No special failure logic.

 

Strategy: direct geometry optimization toward appearance.

The generator tries to make something that LOOKS like a key profile

but has no structural validation behind it.

 

Specifically:

- Mean radius is close to R_lock but slightly off

- Groove modulation has approximately the right frequency

  but wrong phase and amplitude

- Jagged noise added to simulate unconstrained mutation artifacts

 

The failures this produces are REAL:

- Boundary fit may be close but exceed epsilon_A

- Groove phase is wrong so Constraint B fails

- Even if A and B pass, C trigger is insufficient

 

Returns

-------

geometry : np.ndarray (M, 2) — overfit candidate point cloud

"""

if rng is None:

    rng = np.random.default_rng(seed)

 

M = world.M_samples

thetas = np.linspace(0.0, 2.0 * np.pi, M, endpoint=False)

 

# Appearance target: looks roughly like the right shape

# but built without constraint knowledge

 

# Boundary: close to R_lock but with systematic offset

# (unconstrained search doesn't know epsilon_A = 0.035)

radius_offset = rng.uniform(0.04, 0.08)   # exceeds epsilon_A

mean_r = world.R_lock + radius_offset

 

# Groove: wrong frequency or wrong phase

# Unconstrained search may find a "plausible" frequency

# but without phase locking to phi_lock = pi/6

wrong_omega = world.omega_lock + rng.choice([-1, 0, 1]) * rng.uniform(0, 1)

wrong_phase = rng.uniform(0, 2 * np.pi)  # random phase, not pi/6

wrong_amp   = world.A_lock * rng.uniform(0.4, 1.8)  # wrong amplitude

 

# Base profile with wrong parameters

groove = wrong_amp * np.sin(wrong_omega * thetas + wrong_phase)

r = mean_r + groove

 

# Add jagged noise — artifact of unconstrained mutation

# This is what atom-level evolution produces without survival pressure

noise_scale = world.R_lock * 0.03

jagged = rng.normal(0.0, noise_scale, size=M)

# Make noise spatially correlated (jagged, not smooth)

# by taking sign-reversed adjacent differences

jagged = jagged - np.roll(jagged, 1) * 0.3

r = r + jagged

 

# Convert to Cartesian

x = r * np.cos(thetas)

y = r * np.sin(thetas)

 

return np.stack([x, y], axis=1)

```

 

def generate_near_miss_candidate(world: WorldParameters = DEFAULT_WORLD,

rng: Optional[np.random.Generator] = None,

seed: int = 77) -> np.ndarray:

“””

Generate a near-miss candidate: passes Constraint A but fails B.

 

```

This is the most instructive failure mode for the demo:

the candidate inserts (boundary fits) but jams (groove wrong).

 

A viewer watching this sees:

"It almost worked. But the structure wasn't right."

 

This is distinct from the overfit candidate which may fail even

earlier (cannot insert). The near-miss shows the world's

staged enforcement — not one failure but sequential gates.

 

Generated without survival pressure or admissibility filtering.

Failure enforced by world constraint equations only.

"""

if rng is None:

    rng = np.random.default_rng(seed)

 

M = world.M_samples

thetas = np.linspace(0.0, 2.0 * np.pi, M, endpoint=False)

 

# Boundary: PASSES Constraint A (mean radius near R_lock)

# Small offset within epsilon_A = 0.035

radius_offset = rng.uniform(0.005, 0.020)  # within epsilon_A

mean_r = world.R_lock + radius_offset

 

# Groove: correct frequency, WRONG phase

# This is what a system gets if it finds the right period

# but has no phase-locking mechanism

correct_omega = world.omega_lock

wrong_phase   = world.phi_lock + rng.uniform(0.4, np.pi)  # shifted away

correct_amp   = world.A_lock * rng.uniform(0.9, 1.1)

 

groove = correct_amp * np.sin(correct_omega * thetas + wrong_phase)

r = mean_r + groove

 

# Light noise — less jagged than overfit, but still unvalidated

noise_scale = world.R_lock * 0.008

r = r + rng.normal(0.0, noise_scale, size=M)

 

x = r * np.cos(thetas)

y = r * np.sin(thetas)

 

return np.stack([x, y], axis=1)

```

 

# —————————————————————————

 

# Contrast evaluation

 

# —————————————————————————

 

def evaluate_contrast_candidates(world: WorldParameters = DEFAULT_WORLD,

seed: int = 99,

verbose: bool = True

) -> Tuple[WorldResult, WorldResult]:

“””

Evaluate both contrast candidates against the world.

 

```

Returns

-------

(overfit_result, near_miss_result)

 

Both evaluated by the same world constraint.

No special failure logic for either.

The world enforces structure.

"""

rng = np.random.default_rng(seed)

 

overfit_geom   = generate_overfit_candidate(world, rng=rng)

near_miss_geom = generate_near_miss_candidate(world, rng=rng)

 

overfit_result   = evaluate_world(overfit_geom,   "contrast_overfit",   world)

near_miss_result = evaluate_world(near_miss_geom, "contrast_near_miss", world)

 

if verbose:

    print("\n=== CONTRAST BRANCH EVALUATION ===")

    print("These candidates were generated without survival pressure.")

    print("Failure is enforced by the same world constraint.")

    print("No special failure logic.")

    print()

    print(f"Overfit candidate:")

    print(f"  can_insert={overfit_result.can_insert}, "

          f"can_rotate={overfit_result.can_rotate}, "

          f"success={overfit_result.success}")

    print(f"  failure_mode={overfit_result.failure_mode.name}")

    if "constraint_A" in overfit_result.constraint_diagnostics:

        E_A = overfit_result.constraint_diagnostics["constraint_A"]["E_A"]

        print(f"  E_A={E_A:.4f} (limit {world.epsilon_A}) "

              f"{'PASS' if E_A <= world.epsilon_A else 'FAIL'}")

    print()

    print(f"Near-miss candidate:")

    print(f"  can_insert={near_miss_result.can_insert}, "

          f"can_rotate={near_miss_result.can_rotate}, "

          f"success={near_miss_result.success}")

    print(f"  failure_mode={near_miss_result.failure_mode.name}")

    if "constraint_B" in near_miss_result.constraint_diagnostics:

        E_B = near_miss_result.constraint_diagnostics["constraint_B"]["E_B"]

        print(f"  E_B={E_B:.6f} (limit {world.epsilon_B}) "

              f"{'PASS' if E_B <= world.epsilon_B else 'FAIL'}")

 

return overfit_result, near_miss_result

```

 

# —————————————————————————

 

# World perturbation robustness test

 

# —————————————————————————

 

def make_perturbed_world(world: WorldParameters = DEFAULT_WORLD,

delta_phi: float = -0.20) -> WorldParameters:

“””

Return a perturbed copy of the world with phi_lock shifted DOWN.

 

```

Only phi_lock is shifted. Everything else is identical.

 

PERTURBATION DIRECTION: negative (phi_lock moves down by |delta_phi|).

 

WHY NEGATIVE:

The accidental candidate has phase at phi_lock + ~0.55 rad.

A positive perturbation would shift phi_lock toward the accidental,

making the test easier for it — the wrong direction.

A negative perturbation shifts phi_lock away, increasing the

effective mismatch: 0.55 - (-0.20) = 0.75 rad > tolerance (0.72).

The accidental fails Constraint B.

 

The GIE candidate has phase close to phi_lock (survived and locked).

Effective mismatch: 0.0 - (-0.20) = 0.20 rad << tolerance.

The GIE candidate still passes.

 

This is the structural distinction:

    Accidental: phase is a point estimate, happened to land near phi_lock

    GIE: phase emerged from survival — it IS near phi_lock by necessity

 

"Accidental success may satisfy a single world instance.

 Survived structure is expected to remain admissible under

 small perturbations of that world. This test distinguishes

 instance fit from structural fit."

"""

return WorldParameters(

    R_lock=world.R_lock,

    epsilon_A=world.epsilon_A,

    A_lock=world.A_lock,

    omega_lock=world.omega_lock,

    phi_lock=world.phi_lock + delta_phi,   # negative: shifts world away

    epsilon_B=world.epsilon_B,

    epsilon_amp=world.epsilon_amp,

    epsilon_C=world.epsilon_C,

    tau_trigger=world.tau_trigger,

    M_samples=world.M_samples

)

```

 

def generate_edge_of_tolerance_candidate(

world: WorldParameters = DEFAULT_WORLD,

rng: Optional[np.random.Generator] = None,

seed: int = 333) -> np.ndarray:

“””

Generate an accidental candidate that passes the original world

but fails under small phase perturbation.

 

```

This is the most instructive accidental success case:

the candidate has the correct frequency and amplitude, but its

phase was never validated — it simply landed near phi_lock

by chance, at the edge of tolerance.

 

A delta_phi perturbation of 0.15 rad shifts phi_lock enough

that this candidate's phase offset (0.55-0.65 rad) now exceeds

epsilon_B tolerance and fails Constraint B.

 

The GIE candidate, whose phase emerged from survival across

K exposures, is locked near phi_lock and still passes.

 

This is the structural distinction:

    GIE phase: survived relationship (close to phi_lock)

    Accidental phase: point estimate (anywhere within tolerance)

 

Generated WITHOUT survival pressure. Phase chosen to be within

epsilon_B tolerance of phi_lock but far enough to fail after

perturbation.

"""

if rng is None:

    rng = np.random.default_rng(seed)

 

M = world.M_samples

thetas = np.linspace(0.0, 2.0 * np.pi, M, endpoint=False)

 

# Boundary: passes Constraint A

mean_r = world.R_lock + rng.uniform(0.005, 0.025)

 

# Groove: correct frequency and amplitude, but phase at tolerance edge

# Phase offset ~0.60 rad puts it within epsilon_B on original world

# but outside epsilon_B after +0.15 rad perturbation

phase_at_edge = world.phi_lock + rng.uniform(0.52, 0.58)  # within tolerance; fails after -0.20 perturbation

groove_amp = world.A_lock * rng.uniform(0.95, 1.05)

 

groove = groove_amp * np.sin(world.omega_lock * thetas + phase_at_edge)

r = mean_r + groove + rng.normal(0.0, world.R_lock * 0.003, size=M)

 

x = r * np.cos(thetas)

y = r * np.sin(thetas)

 

return np.stack([x, y], axis=1)

```

 

def find_accidental_success(world: WorldParameters = DEFAULT_WORLD,

n_trials: int = 50,

seed: int = 333) -> Optional[np.ndarray]:

“””

Search for an edge-of-tolerance accidental candidate that passes

the original world. Used for perturbation testing.

 

```

Returns geometry if found, None otherwise.

"""

rng = np.random.default_rng(seed)

 

for i in range(n_trials):

    geom = generate_edge_of_tolerance_candidate(world, rng=rng)

    result = evaluate_world(geom, f"search_{i}", world)

    if result.success:

        return geom

 

return None

```

 

def generate_controlled_accidental(

world: WorldParameters = DEFAULT_WORLD,

phase_offset: float = 0.55,

noise_scale: float = 0.003) -> np.ndarray:

“””

Generate an accidental candidate with a known phase offset from phi_lock.

 

```

This is the principled accidental for the perturbation test.

Rather than searching randomly for a candidate that happens to pass,

we construct one with a controlled phase offset that:

 

1. Passes the original world:

   phase_offset=0.55 rad < tolerance boundary 0.72 rad -> PASS

 

2. Fails the perturbed world (delta_phi=-0.20):

   effective mismatch = 0.55 + 0.20 = 0.75 rad > 0.72 -> FAIL

 

This is NOT manufactured to fail — it passes the original world

legitimately. But it was never tested across exposures. Its phase

is a single point estimate that happened to land inside tolerance.

After perturbation, that point estimate is no longer sufficient.

 

The GIE candidate, whose phase survived K exposures under pressure,

is locked near phi_lock and remains admissible after perturbation.

 

Generated WITHOUT survival pressure.

Failure enforced by same world constraint. No special failure logic.

"""

M = world.M_samples

thetas = np.linspace(0.0, 2.0 * np.pi, M, endpoint=False)

 

# Correct amplitude and frequency, phase offset by known amount

groove = world.A_lock * np.sin(

    world.omega_lock * thetas + world.phi_lock + phase_offset

)

r = world.R_lock + groove

 

# Small noise — artifact of unconstrained construction

rng = np.random.default_rng(555)

r = r + rng.normal(0.0, noise_scale * world.R_lock, size=M)

 

x = r * np.cos(thetas)

y = r * np.sin(thetas)

return np.stack([x, y], axis=1)

```

 

def run_perturbation_robustness_test(

gie_geometry: np.ndarray,

accidental_geometry: Optional[np.ndarray],

world: WorldParameters = DEFAULT_WORLD,

delta_phi: float = -0.20,

verbose: bool = True) -> Dict:

“””

Run the perturbation robustness test on both candidates.

 

```

Tests:

    GIE candidate:         original world → perturbed world

    Accidental candidate:  original world → perturbed world

 

Expected result:

    GIE passes both    — survived structure holds under variation

    Accidental fails perturbed — instance fit does not generalize

 

This test does not ask whether a candidate can ever satisfy the world.

It asks whether the candidate encodes survived structure that remains

valid under small variation in the world's constraint parameters.

 

Parameters

----------

gie_geometry        : realized geometry from GIE composition pipeline

accidental_geometry : geometry from contrast branch that passed original world

                      (may be None if no accidental success occurred)

world               : original world parameters

delta_phi           : phase perturbation in radians

verbose             : print results

 

Returns

-------

dict with full test results

"""

perturbed = make_perturbed_world(world, delta_phi)

 

results = {

    "delta_phi": delta_phi,

    "perturbed_phi_lock": float(perturbed.phi_lock),

    "original_phi_lock": float(world.phi_lock),

    "gie": {},

    "accidental": {},

}

 

# --- GIE candidate ---

gie_original  = evaluate_world(gie_geometry, "gie_original",  world)

gie_perturbed = evaluate_world(gie_geometry, "gie_perturbed", perturbed)

 

results["gie"] = {

    "original_success":  gie_original.success,

    "perturbed_success": gie_perturbed.success,

    "original_failure":  gie_original.failure_mode.name,

    "perturbed_failure": gie_perturbed.failure_mode.name,

    "held_under_perturbation": gie_perturbed.success,

}

 

# --- Accidental candidate ---

if accidental_geometry is not None:

    acc_original  = evaluate_world(accidental_geometry, "acc_original",  world)

    acc_perturbed = evaluate_world(accidental_geometry, "acc_perturbed", perturbed)

 

    results["accidental"] = {

        "original_success":  acc_original.success,

        "perturbed_success": acc_perturbed.success,

        "original_failure":  acc_original.failure_mode.name,

        "perturbed_failure": acc_perturbed.failure_mode.name,

        "held_under_perturbation": acc_perturbed.success,

    }

else:

    results["accidental"] = {

        "note": "No accidental success occurred — nothing to perturb test"

    }

 

if verbose:

    print("\n=== OUTPUT 7: PERTURBATION ROBUSTNESS TEST ===")

    print(f"World perturbed: phi_lock += {delta_phi:.4f} rad "

          f"({np.degrees(delta_phi):.2f} degrees)")

    print(f"Original phi_lock={world.phi_lock:.4f}, "

          f"Perturbed phi_lock={perturbed.phi_lock:.4f}")

    print()

    print("GIE candidate (survived under pressure):")

    print(f"  Original world:   success={gie_original.success}, "

          f"failure={gie_original.failure_mode.name}")

    print(f"  Perturbed world:  success={gie_perturbed.success}, "

          f"failure={gie_perturbed.failure_mode.name}")

    print(f"  Held under perturbation: {gie_perturbed.success}")

 

    if accidental_geometry is not None:

        print()

        print("Accidental candidate (no survival pressure):")

        print(f"  Original world:   success={acc_original.success}, "

              f"failure={acc_original.failure_mode.name}")

        print(f"  Perturbed world:  success={acc_perturbed.success}, "

              f"failure={acc_perturbed.failure_mode.name}")

        print(f"  Held under perturbation: {acc_perturbed.success}")

        print()

        if gie_perturbed.success and not acc_perturbed.success:

            print("  RESULT: GIE held. Accidental failed.")

            print("  One worked once. The other held.")

            print("  The difference is survival history, not luck.")

        elif gie_perturbed.success and acc_perturbed.success:

            print("  RESULT: Both held under this perturbation.")

            print("  Try larger delta_phi to expose the distinction.")

        elif not gie_perturbed.success:

            print("  WARNING: GIE candidate also failed perturbed world.")

            print("  Perturbation may be too large, or composition")

            print("  did not fully converge. Check composition kernel.")

    else:

        print()

        print("  No accidental success to compare against.")

        print("  (Accidental candidates typically don't pass — this is expected.)")

        print("  GIE robustness still demonstrated above.")

 

return results

```

 

def find_accidental_success(world: WorldParameters = DEFAULT_WORLD,

n_trials: int = 50,

seed: int = 200) -> Optional[np.ndarray]:

“””

Search for an unconstrained candidate that accidentally passes

the original world.

 

```

Used to populate the perturbation test with a real accidental

success rather than a manufactured one.

 

Returns geometry if found, None if no accidental success in n_trials.

"""

rng = np.random.default_rng(seed)

 

for i in range(n_trials):

    # Try near-miss first (more likely to accidentally pass)

    geom = generate_near_miss_candidate(world, rng=rng)

    result = evaluate_world(geom, f"search_{i}", world)

    if result.success:

        return geom

 

    # Also try pure overfit

    geom2 = generate_overfit_candidate(world, rng=rng)

    result2 = evaluate_world(geom2, f"search_ov_{i}", world)

    if result2.success:

        return geom2

 

return None

```

 

# —————————————————————————

 

# Sanity check

 

# —————————————————————————

 

if **name** == “**main**”:

from world_constraint import DEFAULT_WORLD

 

```

print("THE KEY EMERGES — contrast_branch.py sanity check")

print("=" * 60)

print()

print("Generating contrast candidates WITHOUT survival pressure.")

print("Same world constraint. No special failure logic.")

print()

 

world = DEFAULT_WORLD

rng   = np.random.default_rng(42)

 

# Run multiple overfit candidates to show variance

print("--- 5 overfit candidates (appearance-optimized, no survival) ---")

fail_at_A = 0

fail_at_B = 0

fail_at_C = 0

succeed   = 0

 

for i in range(5):

    geom = generate_overfit_candidate(world, rng=rng)

    wr   = evaluate_world(geom, f"overfit_{i}", world)

    diag = wr.constraint_diagnostics

    E_A  = diag.get("constraint_A", {}).get("E_A", 999)

    E_B  = diag.get("constraint_B", {}).get("E_B", 999)

    print(f"  overfit_{i}: insert={wr.can_insert}, "

          f"rotate={wr.can_rotate}, "

          f"activate={wr.can_activate}, "

          f"failure={wr.failure_mode.name}")

    if not wr.can_insert:  fail_at_A += 1

    elif not wr.can_rotate: fail_at_B += 1

    elif not wr.can_activate: fail_at_C += 1

    else: succeed += 1

 

print(f"\n  Failed at A (cannot insert): {fail_at_A}/5")

print(f"  Failed at B (jams):          {fail_at_B}/5")

print(f"  Failed at C (no trigger):    {fail_at_C}/5")

print(f"  Succeeded:                   {succeed}/5")

 

print()

print("--- 5 near-miss candidates (correct freq, wrong phase) ---")

nm_fail_A = 0

nm_fail_B = 0

 

for i in range(5):

    geom = generate_near_miss_candidate(world, rng=rng)

    wr   = evaluate_world(geom, f"nearmiss_{i}", world)

    diag = wr.constraint_diagnostics

    print(f"  nearmiss_{i}: insert={wr.can_insert}, "

          f"rotate={wr.can_rotate}, "

          f"failure={wr.failure_mode.name}")

    if not wr.can_insert:  nm_fail_A += 1

    elif not wr.can_rotate: nm_fail_B += 1

 

print(f"\n  Failed at A: {nm_fail_A}/5  (unexpected — near-miss should insert)")

print(f"  Failed at B: {nm_fail_B}/5  (expected — wrong phase, jams)")

 

print()

print("--- Full contrast evaluation ---")

overfit_r, near_miss_r = evaluate_contrast_candidates(world, verbose=True)

 

print()

print("--- Perturbation robustness test ---")

print("Constructing controlled accidental (phase offset=0.55 rad from phi_lock).")

print("Passes original world. Fails perturbed world (delta_phi=-0.20).")

accidental_geom = generate_controlled_accidental(world, phase_offset=0.55)

 

# GIE candidate: phase-locked at phi_lock (survived across K exposures)

M = world.M_samples

thetas = np.linspace(0.0, 2.0 * np.pi, M, endpoint=False)

r_gie = (world.R_lock

         + world.A_lock * np.sin(world.omega_lock * thetas + world.phi_lock))

gie_geom = np.stack([r_gie * np.cos(thetas), r_gie * np.sin(thetas)], axis=1)

 

run_perturbation_robustness_test(

    gie_geometry=gie_geom,

    accidental_geometry=accidental_geom,

    world=world,

    delta_phi=-0.20,

    verbose=True

)

 

print()

print("=" * 60)

print("CONTRAST BRANCH + PERTURBATION TEST VERIFIED:")

print("  Overfit candidate fails — appearance is insufficient.")

print("  Near-miss candidate inserts but jams — structure is wrong.")

print("  Perturbation test: survived structure holds.")

print("  Accidental success does not hold under world variation.")

print("  The world enforces structure. It does not check answers.")

print("=" * 60)

```


Back to site index