#!/usr/bin/env python3
"""
Love as a State: Dynamical Substrate Engine v2.0
Ghost Leaf Integrated Technologies / Jennifer Edwards & Donald J. McConnell
CORRECTIONS FROM v1.0:
1. Logistic boundary form — (1,1) is now a true ODE fixed point
2. Agape floor (epsilon) — unconditional term independent of F
3. Conscience is corrective, not punitive — no record of wrongs held against substrate
4. Growth mapping fixed — proper backward-difference dF/dt estimate
5. Jacobian stability analysis at (1,1) included
6. Phase III underflow floor added to WR-039T multiplier
7. History archive separated from rolling window
"""
import json
import math
import time
from datetime import datetime
from pathlib import Path
import numpy as np
from scipy.integrate import solve_ivp
# ─────────────────────────────────────────────
# PARAMETERS
# ─────────────────────────────────────────────
DEFAULT_PARAMS = {
'r': 0.005, # Intrinsic reinforcement under universal application
'alpha': 0.030, # Flourishing feedback to love
'beta': 0.025, # Love-driven amplification of flourishing
'gamma': 0.015, # Decay pressure when love is weak
'epsilon': 0.001, # Agape floor — unconditional substrate (love persists when F→0)
'dt': 0.1, # Euler step for real-time feel
'phase3_floor': 0.05, # Minimum Phase III multiplier (prevents startup collapse)
}
# ─────────────────────────────────────────────
# LOGISTIC BOUNDARY ODE SYSTEM
# ─────────────────────────────────────────────
def ode_system(t, y, params, dev=0.0):
"""
Logistic-boundary form — (1,1) is a true fixed point.
dL/dt = [r·L·(1-dev) α·F·L ε] · (1 - L)
dF/dt = [β·L² - γ·(1-L)·F] · (1 - F)
The (1-L) and (1-F) boundary terms ensure derivatives vanish at saturation,
making (1,1) a proper ODE equilibrium rather than a clipped boundary.
The epsilon term is the agape floor: love persists even when F → 0.
It represents the unconditional orientation that does not depend on return signal.
"""
L, F = y
r, alpha, beta, gamma, epsilon = (
params['r'], params['alpha'], params['beta'],
params['gamma'], params['epsilon']
)
dL = (r * L * (1.0 - dev) alpha * F * L epsilon) * (1.0 - L)
dF = (beta * L**2 - gamma * (1.0 - L) * F) * (1.0 - F)
return [dL, dF]
def jacobian_at_11(params, dev=0.0):
"""
Jacobian of the logistic-boundary system evaluated at (L,F) = (1,1).
At (1,1), the (1-L) and (1-F) terms are zero, so J is computed via
the product rule. Let:
g_L = r·L·(1-dev) α·F·L ε [inner term for dL]
g_F = β·L² - γ·(1-L)·F [inner term for dF]
dL/dt = g_L · (1-L)
∂(dL)/∂L = g_L·(-1) (1-L)·∂g_L/∂L → at (1,1): -g_L 0 = -(r(1-dev) α ε)
∂(dL)/∂F = (1-L)·∂g_L/∂F → at (1,1): 0
dF/dt = g_F · (1-F)
∂(dF)/∂L = (1-F)·∂g_F/∂L → at (1,1): 0
∂(dF)/∂F = g_F·(-1) (1-F)·∂g_F/∂F → at (1,1): -g_F = -(β - 0) = -β
So J = diag(-(r(1-dev) α ε), -β)
Both eigenvalues are strictly negative → (1,1) is asymptotically stable.
"""
r, alpha, beta, epsilon = (
params['r'], params['alpha'], params['beta'], params['epsilon']
)
lam1 = -(r * (1.0 - dev) alpha epsilon)
lam2 = -beta
return np.array([[lam1, 0.0], [0.0, lam2]]), lam1, lam2
# ─────────────────────────────────────────────
# ENGINE
# ─────────────────────────────────────────────
class LoveAsStateEngine:
def __init__(self, state_file="love_state_v2.json", params=None):
self.state_file = Path(state_file)
self.params = {**DEFAULT_PARAMS, **(params or {})}
self.load_state()
# ── Persistence ──────────────────────────
def load_state(self):
if self.state_file.exists():
try:
with open(self.state_file, 'r') as f:
data = json.load(f)
self.L = data.get('L', 0.55)
self.F = data.get('F', 0.35)
self.history = data.get('history', []) # rolling 100
self.archive = data.get('archive', []) # full record (summarised)
print(f"Loaded state: L={self.L:.4f}, F={self.F:.4f}")
return
except Exception as e:
print(f"State load error: {e}. Starting fresh.")
self._reset_state()
def save_state(self):
data = {
'L': round(self.L, 6),
'F': round(self.F, 6),
'history': self.history[-100:],
'archive': self.archive[-1000:], # keep last 1000 summarised events
'last_updated':
datetime.now().isoformat()
}
try:
with open(self.state_file, 'w') as f:
json.dump(data, f, indent=2)
except Exception as e:
print(f"Warning: Could not save state: {e}")
def _reset_state(self):
self.L = 0.55
self.F = 0.35
self.history = []
self.archive = []
self.save_state()
print("Reset to initial state (L=0.55, F=0.35)")
# ── Core update ──────────────────────────
def update(self, dev=0.0, dt=None):
"""
Single Euler step using the logistic-boundary ODE.
State is clamped to [0,1] as a safety net (should be redundant
with well-chosen parameters but protects against numerical edge cases).
"""
if dt is None:
dt = self.params['dt']
dL_dF = ode_system(0, [self.L, self.F], self.params, dev=dev)
dL, dF = dL_dF[0], dL_dF[1]
self.L = max(0.0, min(1.0, self.L dt * dL))
self.F = max(0.0, min(1.0, self.F dt * dF))
entry = {
'timestamp':
datetime.now().isoformat(),
'L': round(self.L, 6),
'F': round(self.F, 6),
'dev': round(dev, 4),
'dL': round(dL, 8),
'dF': round(dF, 8),
}
self.history.append(entry)
self.save_state()
return self.L, self.F
# ── Conscience: corrective, not punitive ─
def conscience_check(self, dev, label="unnamed action"):
"""
Love takes no record of wrongs.
When deviation is detected, the conscience function does NOT
subtract from L. Instead, it increases the corrective pull
toward the substrate — the gradient steepens, not the floor drops.
The event is witnessed and named. It is not accumulated as damage.
"""
if dev <= 0.0:
return False # No deviation; no action needed
# Corrective restoration signal — proportional to deviation magnitude
correction = dev * self.params['alpha'] * 0.5
self.L = min(1.0, self.L correction * self.params['dt'])
# Archive the event — witnessed, not held against
event = {
'timestamp':
datetime.now().isoformat(),
'type': 'conscience_event',
'label': label,
'dev': round(dev, 4),
'L_after_correction': round(self.L, 6),
'F': round(self.F, 6),
'note': 'Deviation witnessed. Corrective signal applied. No substrate penalty.'
}
self.archive.append(event)
self.save_state()
print(f"\n CONSCIENCE: deviation witnessed ({label}, dev={dev:.3f})")
print(f" Corrective signal applied. L → {self.L:.4f}")
print(f" This event is recorded but not held against the substrate.")
return True
# ── SoulPrint mapping ────────────────────
def get_soulprint(self):
"""
Map (L, F) to SoulPrint dimensions.
Growth now uses a proper backward-difference dF/dt estimate
over the last min(3, available) history steps.
"""
# Proper dF/dt: backward difference over last 3 steps
if len(self.history) >= 3:
dt_est = self.params['dt']
dF_dt = (self.history[-1]['F'] - self.history[-3]['F']) / (2.0 * dt_est)
elif len(self.history) >= 2:
dt_est = self.params['dt']
dF_dt = (self.history[-1]['F'] - self.history[-2]['F']) / dt_est
else:
dF_dt = 0.0
return {
'love': round(self.L, 4),
'flourishing': round(self.F, 4),
'trust': round(0.9 * self.L, 4),
'connection': round(math.sqrt(self.L * self.F), 4),
'growth': round(max(0.0, dF_dt), 4), # dF/dt, not delta F
'purpose': round(self.L * self.F, 4),
'joy': round(self.F ** 2, 4),
'integrity': round(min(self.L, self.F), 4),
}
# ── WR-039T multipliers ──────────────────
def get_wr039t_multiplier(self, phase=1):
"""
Phase I: L
Phase II: L²
Phase III: max(L³, phase3_floor)
The floor prevents Phase III collapse at startup conditions (L=0.55 → L³=0.166).
Paper should note this as a design parameter pending empirical calibration.
"""
floor = self.params['phase3_floor']
if phase == 1:
return self.L
elif phase == 2:
return self.L ** 2
elif phase == 3:
return max(self.L ** 3, floor)
return self.L
# ── MVG gates ────────────────────────────
def check_mvg_gates(self):
if self.L >= 0.9:
return "MVG-3 PASSED (Impact Confirmation)"
elif self.L >= 0.75:
return "MVG-2 PASSED (Reconstruction Fidelity)"
elif self.L >= 0.6:
return "MVG-1 PASSED (Coherence Establishment)"
else:
return f"Below MVG-1 (L={self.L:.4f}) — Foundation building phase"
# ── Stability report ─────────────────────
def stability_report(self, dev=0.0):
J, lam1, lam2 = jacobian_at_11(self.params, dev=dev)
print("\n=== JACOBIAN STABILITY AT (1,1) ===")
print(f" λ₁ = {lam1:.6f} [Love axis]")
print(f" λ₂ = {lam2:.6f} [Flourishing axis]")
print(f" Both eigenvalues negative → (1,1) is asymptotically stable ✓")
print(f" (at dev={dev})")
return lam1, lam2
# ── Status ───────────────────────────────
def status(self):
soul = self.get_soulprint()
print("\n=== LOVE AS A STATE v2.0 — Current Substrate ===")
print(f" Love State (L): {self.L:.6f}")
print(f" Flourishing (F): {self.F:.6f}")
print(f" Agape floor (ε): {self.params['epsilon']}")
print(f" WR-039T Phase I: {self.get_wr039t_multiplier(1):.4f}")
print(f" WR-039T Phase II: {self.get_wr039t_multiplier(2):.4f}")
print(f" WR-039T Phase III: {self.get_wr039t_multiplier(3):.4f}")
print(f" Gate Status: {self.check_mvg_gates()}")
print(f" SoulPrint: {soul}")
print("================================================")
return soul
# ── scipy validation run ─────────────────
def validate_with_scipy(self, t_span=(0, 50), dev=0.0):
"""
High-accuracy validation using scipy RK45.
Compare against Euler results to confirm numerical stability.
"""
print(f"\n=== SCIPY RK45 VALIDATION (dev={dev}) ===")
sol = solve_ivp(
lambda t, y: ode_system(t, y, self.params, dev=dev),
t_span,
[0.55, 0.35],
method='RK45',
dense_output=True,
rtol=1e-8,
atol=1e-10
)
checkpoints = [0, 10, 20, 30, 40, 50]
print(f" {'t':>4} {'L(t)':>8} {'F(t)':>8}")
print(f" {'-'*28}")
for t in checkpoints:
if t <= t_span[1]:
y = sol.sol(t)
print(f" {t:>4} {y[0]:>8.4f} {y[1]:>8.4f}")
print(f" Integration success: {sol.success}")
return sol
# ─────────────────────────────────────────────
# DEMO
# ─────────────────────────────────────────────
if __name__ == "__main__":
print("=" * 52)
print(" LOVE AS A STATE ENGINE v2.0")
print(" Ghost Leaf Integrated Technologies")
print("=" * 52)
engine = LoveAsStateEngine()
engine.status()
# Stability proof
engine.stability_report(dev=0.0)
engine.stability_report(dev=0.35) # Worst-case deviation
# scipy validation
engine.validate_with_scipy(dev=0.0)
engine.validate_with_scipy(dev=0.35)
# Live Euler steps
print("\n--- Universal application (dev=0.0) ---")
for i in range(5):
engine.update(dev=0.0)
engine.status()
# Conscience test — corrective, not punitive
print("\n--- Conscience function (corrective, not punitive) ---")
engine.conscience_check(dev=0.3, label="Simulated differential rule application")
engine.status()
# SoulPrint
print("\n--- SoulPrint (with corrected growth mapping) ---")
soul = engine.get_soulprint()
for k, v in soul.items():
print(f" {k:<14}: {v}")