“””

THE KEY EMERGES — world_constraint.py

 

The world is a deterministic constraint system.

It does not recognize a stored answer.

It enforces structural admissibility through explicit equations.

 

A candidate object succeeds only if it satisfies all three constraints

in sequence. Failure at any stage produces a specific failure mode.

The world does not award partial credit.

 

WORLD INTERFACE:

evaluate_world(candidate) -> WorldResult

 

The candidate is represented as a polar profile r(theta) sampled

at M uniformly spaced angles over [0, 2*pi].

 

THREE CONSTRAINTS (sequential, all required for success):

 

```

Constraint A — Boundary / Admission

    The candidate outer boundary must fit a circular aperture.

    Hard veto: failure means cannot insert.

 

Constraint B — Groove Alignment

    The candidate must present a periodic groove structure

    matching the lock's internal pins in frequency, phase,

    and amplitude.

    Failure: inserts but jams or cannot rotate.

 

Constraint C — Activation after 90-degree rotation

    The candidate must sustain groove admissibility after

    quarter-turn rotation AND exceed a trigger integral threshold.

    Failure: rotates but does not unlock.

```

 

WORLD PARAMETERS (defined first — curves and transforms were

chosen AFTER these were fixed):

 

```

R_lock    = 1.0     global lock radius

epsilon_A = 0.035   admission tolerance (3.5% of R_lock)

A_lock    = 0.12    required groove amplitude

omega_lock = 3      required groove frequency (3 cycles per revolution)

phi_lock  = pi/6    required groove phase offset

epsilon_B = 0.004   groove residual tolerance

epsilon_amp = 0.03  amplitude tolerance

epsilon_C = 0.004   post-rotation groove residual tolerance

tau_trigger = 0.006 minimum trigger integral for activation

```

 

These equations define the world. C1 and C2 were chosen to make

the required invariants discoverable — not to pre-encode the solution.

“””

 

from **future** import annotations

import numpy as np

from dataclasses import dataclass, field

from typing import Dict, Any, Optional

from core_types import FailureMode, WorldResult

 

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

 

# World parameters — locked before curves were chosen

 

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

 

@dataclass(frozen=True)

class WorldParameters:

“””

All world constraint parameters in one place.

Frozen: the world does not change during a run.

 

```

These values were defined FIRST. Latent curves C1 and C2 were

chosen afterward to support recovery of the required invariants.

No domain-specific tuning for any particular candidate was done here.

"""

R_lock: float = 1.0

epsilon_A: float = 0.035

 

A_lock: float = 0.12

omega_lock: float = 3.0

phi_lock: float = np.pi / 6.0

epsilon_B: float = 0.004

epsilon_amp: float = 0.03

 

epsilon_C: float = 0.004

tau_trigger: float = 0.006

 

M_samples: int = 360        # angular samples for constraint evaluation

```

 

# Default world — used throughout unless explicitly overridden

 

DEFAULT_WORLD = WorldParameters()

 

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

 

# Polar profile representation

 

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

 

def candidate_to_polar(geometry: np.ndarray,

M: int = 360) -> np.ndarray:

“””

Convert a 2D point cloud (N, 2) representing a candidate profile

into a sampled polar profile r(theta) at M uniform angles.

 

```

Strategy: for each of M angles, find the nearest candidate point

and record its radius. This is a projection, not an interpolation —

consistent with the no-smoothing requirement.

 

Returns

-------

r : np.ndarray, shape (M,)

    Sampled radii at theta_i = 2*pi*i/M

thetas : np.ndarray, shape (M,)

    Corresponding angles

"""

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

 

# Convert candidate points to polar

x, y = geometry[:, 0], geometry[:, 1]

point_angles = np.arctan2(y, x) % (2.0 * np.pi)

point_radii = np.sqrt(x**2 + y**2)

 

# For each target angle, find nearest point angle

r = np.zeros(M)

for i, theta in enumerate(thetas):

    # Angular distance (wrapped)

    diffs = np.abs(point_angles - theta)

    diffs = np.minimum(diffs, 2.0 * np.pi - diffs)

    nearest_idx = np.argmin(diffs)

    r[i] = point_radii[nearest_idx]

 

return r, thetas

```

 

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

 

# Constraint A — Boundary / Admission

 

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

 

def evaluate_constraint_A(r: np.ndarray,

params: WorldParameters) -> Dict[str, Any]:

“””

Constraint A: global boundary / admission.

 

```

Constraint A asks: is the overall object centered at the correct radius?

Constraint B asks: does it have the right groove?

These are orthogonal checks. Do not mix them.

 

PATCHED from max instantaneous deviation to mean radius deviation.

Rationale: instantaneous groove modulation belongs to Constraint B,

not A. Using max(|r_i - R_lock|) would penalize the groove amplitude

that B is supposed to evaluate, causing a perfect candidate to fail A

for the wrong reason.

 

Correct form:

    E_A = |mean(r_i) - R_lock|

 

Admissible insertion requires: E_A <= epsilon_A

 

A perfect candidate r(theta) = R_lock + A_lock*sin(...)

has mean(r) = R_lock exactly, so A passes.

Its modulation is captured entirely in g(theta) for Constraint B.

No double-counting. No hidden coupling between A and B.

 

Returns dict with:

    passes: bool

    E_A: float

    failure_mode: FailureMode or None

"""

E_A = float(np.abs(np.mean(r) - params.R_lock))

passes = E_A <= params.epsilon_A

 

return {

    "passes": passes,

    "E_A": E_A,

    "R_lock": params.R_lock,

    "epsilon_A": params.epsilon_A,

    "failure_mode": None if passes else FailureMode.CANNOT_INSERT

}

```

 

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

 

# Constraint B — Groove Alignment

 

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

 

def evaluate_constraint_B(r: np.ndarray,

thetas: np.ndarray,

params: WorldParameters) -> Dict[str, Any]:

“””

Constraint B: periodic groove alignment.

 

```

The lock's internal pins require a specific periodic structure.

This is not visual similarity — the phase, frequency, and amplitude

must satisfy explicit equations.

 

Step 1: remove DC component to isolate modulation

    g(theta) = r(theta) - mean(r(theta))

 

Step 2: find best-fit amplitude against the required pattern

    alpha* = argmin_alpha mean[(g - alpha * sin(omega*theta + phi))^2]

           = mean[g * sin(omega*theta + phi)] / mean[sin^2(omega*theta + phi)]

 

Step 3: compute residual

    E_B = mean[(g - alpha* * sin(omega*theta + phi))^2]

 

Step 4: check amplitude admissibility

    |alpha* - A_lock| <= epsilon_amp

 

Both E_B and amplitude checks must pass.

 

Failure: candidate passes A (can insert) but fails B — jams or

cannot rotate correctly because groove structure is wrong.

"""

# Isolate groove modulation (remove DC)

g = r - np.mean(r)

 

# Lock's required groove pattern

pattern = np.sin(params.omega_lock * thetas + params.phi_lock)

 

# Best-fit amplitude (closed-form least squares)

numerator = np.mean(g * pattern)

denominator = np.mean(pattern ** 2)

 

# Guard against degenerate pattern (should not occur with omega >= 1)

if abs(denominator) < 1e-12:

    alpha_star = 0.0

else:

    alpha_star = numerator / denominator

 

# Groove residual after best-fit amplitude removal

fitted = alpha_star * pattern

E_B = float(np.mean((g - fitted) ** 2))

 

# Amplitude admissibility

amplitude_ok = abs(alpha_star - params.A_lock) <= params.epsilon_amp

residual_ok = E_B <= params.epsilon_B

passes = residual_ok and amplitude_ok

 

failure_mode = None

if not passes:

    failure_mode = FailureMode.INSERTS_BUT_JAMS

 

return {

    "passes": passes,

    "E_B": E_B,

    "alpha_star": float(alpha_star),

    "A_lock": params.A_lock,

    "amplitude_ok": amplitude_ok,

    "residual_ok": residual_ok,

    "epsilon_B": params.epsilon_B,

    "epsilon_amp": params.epsilon_amp,

    "failure_mode": failure_mode

}

```

 

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

 

# Constraint C — Activation after 90-degree rotation

 

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

 

def evaluate_constraint_C(r: np.ndarray,

thetas: np.ndarray,

params: WorldParameters) -> Dict[str, Any]:

“””

Constraint C: activation after 90-degree rotation.

 

```

The candidate must sustain structural admissibility after a

quarter-turn rotation AND exceed a trigger integral threshold.

This is the mechanism engagement — not just correct alignment

at rest, but correct structural response to rotation.

 

Rotated profile:

    r_rot(theta) = r(theta + pi/2)

    implemented by circular shift of the sampled r array

 

Post-rotation groove:

    g_rot(theta) = r_rot(theta) - mean(r_rot(theta))

 

Rotated target pattern:

    p_rot(theta) = A_lock * sin(omega_lock * theta + phi_lock

                                + omega_lock * pi/2)

 

Residual:

    E_C = mean[(g_rot - alpha_rot* * p_rot_unit)^2]

 

Trigger integral (must exceed tau_trigger):

    T = mean[g_rot(theta_i) * sin(omega_lock*theta_i + phi_lock

                                   + omega_lock*pi/2)]

 

Both E_C <= epsilon_C and T >= tau_trigger required.

 

Failure: rotates but does not unlock (insufficient trigger response).

"""

M = len(r)

 

# Circular shift to simulate 90-degree rotation

# theta + pi/2 corresponds to advancing the array by M/4 positions

shift = M // 4

r_rot = np.roll(r, -shift)

 

# Zero-mean groove of rotated profile

g_rot = r_rot - np.mean(r_rot)

 

# Rotated target pattern

phase_rot = params.phi_lock + params.omega_lock * (np.pi / 2.0)

pattern_rot = np.sin(params.omega_lock * thetas + phase_rot)

 

# Best-fit amplitude for rotated groove

denom = np.mean(pattern_rot ** 2)

if abs(denom) < 1e-12:

    alpha_rot = 0.0

else:

    alpha_rot = np.mean(g_rot * pattern_rot) / denom

 

fitted_rot = alpha_rot * pattern_rot

E_C = float(np.mean((g_rot - fitted_rot) ** 2))

 

# Trigger integral

T = float(np.mean(g_rot * pattern_rot))

 

residual_ok = E_C <= params.epsilon_C

trigger_ok = T >= params.tau_trigger

passes = residual_ok and trigger_ok

 

failure_mode = None

if not passes:

    failure_mode = FailureMode.ROTATES_BUT_NO_TRIGGER

 

return {

    "passes": passes,

    "E_C": E_C,

    "T": T,

    "alpha_rot": float(alpha_rot),

    "residual_ok": residual_ok,

    "trigger_ok": trigger_ok,

    "epsilon_C": params.epsilon_C,

    "tau_trigger": params.tau_trigger,

    "failure_mode": failure_mode

}

```

 

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

 

# Admissibility pre-screen (used during GA search as hard veto)

 

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

 

def check_admissibility(geometry: np.ndarray,

params: WorldParameters = DEFAULT_WORLD) -> bool:

“””

Fast pre-screen used during GA evolution as a hard veto.

 

```

A candidate is inadmissible if it cannot possibly satisfy the world

constraints. Inadmissible candidates are eliminated immediately —

they do not receive an invariance score.

 

This is the admissibility filter that bounds the search space.

It is NOT a gradient toward success — it is a binary gate.

 

The world constraint participates in survival from the beginning,

but does not define a target. It defines admissibility.

 

For pre-screening, we check only Constraint A (boundary fit),

which is the necessary condition for all others.

B and C are evaluated only at full world evaluation time.

"""

try:

    r, _ = candidate_to_polar(geometry, params.M_samples)

    result_A = evaluate_constraint_A(r, params)

    return result_A["passes"]

except Exception:

    # Any geometry that cannot be evaluated is inadmissible

    return False

```

 

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

 

# Full world evaluation

 

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

 

def evaluate_world(geometry: np.ndarray,

candidate_id: str,

params: WorldParameters = DEFAULT_WORLD) -> WorldResult:

“””

Full evaluation of a candidate object against the world constraint.

 

```

The world enforces rules through equations. It does not recognize

solutions by lookup. Each constraint is evaluated independently.

Failure at any stage short-circuits to the appropriate failure mode.

 

Sequence:

    1. Convert geometry to polar profile

    2. Evaluate Constraint A (admission)

    3. If A passes: evaluate Constraint B (groove alignment)

    4. If B passes: evaluate Constraint C (activation)

    5. Report WorldResult with full diagnostics

 

Parameters

----------

geometry     : np.ndarray (N, 2) — candidate profile point cloud

candidate_id : identifier for logging

params       : world parameters (default: DEFAULT_WORLD)

 

Returns

-------

WorldResult

"""

mechanism_before = {"state": "locked", "rotation_deg": 0.0}

diagnostics = {}

 

# Convert to polar

r, thetas = candidate_to_polar(geometry, params.M_samples)

diagnostics["polar_r_mean"] = float(np.mean(r))

diagnostics["polar_r_std"] = float(np.std(r))

 

# --- Constraint A ---

result_A = evaluate_constraint_A(r, params)

diagnostics["constraint_A"] = result_A

 

if not result_A["passes"]:

    # Hard veto — cannot insert

    # Comments: this is inadmissibility, not a recognition failure.

    # The world enforces a boundary equation. The candidate violated it.

    return WorldResult(

        candidate_id=candidate_id,

        can_insert=False,

        can_rotate=False,

        can_activate=False,

        success=False,

        failure_mode=FailureMode.CANNOT_INSERT,

        mechanism_state_before=mechanism_before,

        mechanism_state_after={"state": "locked", "rotation_deg": 0.0},

        constraint_diagnostics=diagnostics

    )

 

# --- Constraint B ---

result_B = evaluate_constraint_B(r, thetas, params)

diagnostics["constraint_B"] = result_B

 

if not result_B["passes"]:

    # Inserted but jams — groove structure violates pin alignment

    return WorldResult(

        candidate_id=candidate_id,

        can_insert=True,

        can_rotate=False,

        can_activate=False,

        success=False,

        failure_mode=FailureMode.INSERTS_BUT_JAMS,

        mechanism_state_before=mechanism_before,

        mechanism_state_after={"state": "locked", "rotation_deg": 0.0},

        constraint_diagnostics=diagnostics

    )

 

# --- Constraint C ---

result_C = evaluate_constraint_C(r, thetas, params)

diagnostics["constraint_C"] = result_C

 

if not result_C["passes"]:

    # Rotates but fails to trigger — structural response insufficient

    return WorldResult(

        candidate_id=candidate_id,

        can_insert=True,

        can_rotate=True,

        can_activate=False,

        success=False,

        failure_mode=FailureMode.ROTATES_BUT_NO_TRIGGER,

        mechanism_state_before=mechanism_before,

        mechanism_state_after={"state": "locked", "rotation_deg": 90.0},

        constraint_diagnostics=diagnostics

    )

 

# --- All constraints satisfied — state transition ---

return WorldResult(

    candidate_id=candidate_id,

    can_insert=True,

    can_rotate=True,

    can_activate=True,

    success=True,

    failure_mode=FailureMode.NONE,

    mechanism_state_before=mechanism_before,

    mechanism_state_after={"state": "unlocked", "rotation_deg": 90.0},

    constraint_diagnostics=diagnostics

)

```

 

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

 

# Sanity checks — run directly to verify world equations

 

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

 

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

params = DEFAULT_WORLD

M = params.M_samples

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

 

```

print("=== WORLD CONSTRAINT SANITY CHECK ===")

print(f"R_lock={params.R_lock}, epsilon_A={params.epsilon_A}")

print(f"A_lock={params.A_lock}, omega_lock={params.omega_lock}, "

      f"phi_lock={params.phi_lock:.4f}")

print(f"epsilon_B={params.epsilon_B}, epsilon_amp={params.epsilon_amp}")

print(f"epsilon_C={params.epsilon_C}, tau_trigger={params.tau_trigger}")

print()

 

# --- Test 1: Perfect candidate — should pass all constraints ---

r_perfect = (params.R_lock

             + params.A_lock * np.sin(params.omega_lock * thetas

                                      + params.phi_lock))

# Convert polar back to Cartesian for evaluate_world

x_p = r_perfect * np.cos(thetas)

y_p = r_perfect * np.sin(thetas)

geom_perfect = np.stack([x_p, y_p], axis=1)

 

result = evaluate_world(geom_perfect, "perfect_candidate")

print("Test 1 — Perfect candidate:")

print(f"  can_insert={result.can_insert}, can_rotate={result.can_rotate}, "

      f"can_activate={result.can_activate}, success={result.success}")

print(f"  failure_mode={result.failure_mode}")

diag = result.constraint_diagnostics

print(f"  E_A={diag['constraint_A']['E_A']:.6f} "

      f"(limit {params.epsilon_A})")

if 'constraint_B' in diag:

    print(f"  E_B={diag['constraint_B']['E_B']:.6f} "

          f"(limit {params.epsilon_B}), "

          f"alpha*={diag['constraint_B']['alpha_star']:.4f} "

          f"(target {params.A_lock})")

if 'constraint_C' in diag:

    print(f"  E_C={diag['constraint_C']['E_C']:.6f} "

          f"(limit {params.epsilon_C}), "

          f"T={diag['constraint_C']['T']:.6f} "

          f"(min {params.tau_trigger})")

print()

 

# --- Test 2: Wrong radius — should fail Constraint A ---

r_wrong_radius = np.full(M, params.R_lock + 0.1)  # 10% too large

x_w = r_wrong_radius * np.cos(thetas)

y_w = r_wrong_radius * np.sin(thetas)

geom_wrong = np.stack([x_w, y_w], axis=1)

 

result2 = evaluate_world(geom_wrong, "wrong_radius")

print("Test 2 — Wrong radius (should fail A):")

print(f"  can_insert={result2.can_insert}, success={result2.success}, "

      f"failure_mode={result2.failure_mode}")

print(f"  E_A={result2.constraint_diagnostics['constraint_A']['E_A']:.6f}")

print()

 

# --- Test 3: Correct radius, wrong groove frequency ---

r_wrong_freq = (params.R_lock

                + params.A_lock * np.sin(5.0 * thetas + params.phi_lock))

x_f = r_wrong_freq * np.cos(thetas)

y_f = r_wrong_freq * np.sin(thetas)

geom_wrong_freq = np.stack([x_f, y_f], axis=1)

 

result3 = evaluate_world(geom_wrong_freq, "wrong_frequency")

print("Test 3 — Correct radius, wrong groove frequency (should fail B):")

print(f"  can_insert={result3.can_insert}, can_rotate={result3.can_rotate}, "

      f"success={result3.success}, failure_mode={result3.failure_mode}")

if 'constraint_B' in result3.constraint_diagnostics:

    print(f"  E_B={result3.constraint_diagnostics['constraint_B']['E_B']:.6f}")

print()

 

# --- Test 4: Correct A and B, check C fires ---

print("Test 4 — Perfect candidate Constraint C detail:")

diag_c = result.constraint_diagnostics.get('constraint_C', {})

print(f"  E_C={diag_c.get('E_C', 'N/A')}, "

      f"T={diag_c.get('T', 'N/A')}, "

      f"trigger_ok={diag_c.get('trigger_ok', 'N/A')}")

print()

 

print("=== ADMISSIBILITY PRE-SCREEN TEST ===")

print(f"Perfect candidate admissible: "

      f"{check_admissibility(geom_perfect)}")

print(f"Wrong radius admissible: "

      f"{check_admissibility(geom_wrong)}")

print()

print("PASS — world_constraint.py is operational.")

```


Back to site index