import numpy as np
import matplotlib.pyplot as plt
# ------------------------
# Physical / model constants
# ------------------------
h = 6.62607015e-34 # Planck [J*s]
pi = np.pi
kB = 1.380649e-23 # Boltzmann [J/K]
h_over_pi = h / pi
CS_const = 1.0 # semantic coherence scale constant
xi = 1.0 # coupling for ΔC_S [J^-1·K★] so ΔC_S → [J^-1]
T0 = 300.0 # base semantic temperature [K★]
beta_T = 0.1 # scaling of grad_sigma into T
k_sem = 2.0 # semantic conductivity [J/(m*K★*s)]
E0 = 0.0 # baseline semantic energy density
kappa_E = 1.0 # semantic stiffness [J/m] - sets physical energy scale
# ------------------------
# Grid and contradiction scaffold field σ(x,y)
# ------------------------
grid_size = 100
x = np.linspace(-5, 5, grid_size)
y = np.linspace(-5, 5, grid_size)
X, Y = np.meshgrid(x, y)
# Contradiction scaffold field σ(x,y)
sigma = np.exp(-X**2 - Y**2) * np.sin(2*X) * np.cos(2*Y)
sigma_eps = 1e-6
sigma_pos = np.abs(sigma) + sigma_eps
# ------------------------
# Gradients & decoherence strength
# ------------------------
# Use spacing for proper gradient calculation
dy = y[1] - y[0]; dx = x[1] - x[0]
dsigma_dy, dsigma_dx = np.gradient(sigma, dy, dx)
grad_sigma_mag = np.sqrt(dsigma_dx**2 + dsigma_dy**2)
Gamma = grad_sigma_mag**2 / (1 + grad_sigma_mag**2)
# ------------------------
# Semantic temperature & heat flux (T★ = phase agitation energy, NOT thermodynamic temperature)
# ------------------------
# PHYSICS CHECK: T★ must be positive and physically meaningful
T_sem = T0 * (1 + beta_T * grad_sigma_mag / (grad_sigma_mag.max() + 1e-12)) # [K★] semantic temperature
# Ensure no division by zero and physically reasonable scaling
# FOURIER'S LAW for semantic heat conduction
dT_dy, dT_dx = np.gradient(T_sem, dy, dx) # [K★/m] temperature gradients
j_sem_x = -k_sem * dT_dx # [J/(m·K★·s)] × [K★/m] = [J/(m²·s)] semantic heat flux ✓
j_sem_y = -k_sem * dT_dy # Proper units for heat flux density
# ------------------------
# Mode 2 thermodynamic coherence: ΔC, ΔI with recursive self-reference
# ------------------------
tau_ref = 1e-2 # [s] - reference timescale
alpha_I = 1e-34 # [J²] - semantic impulse scaling (energy-squared for recursive self-reference)
# Mode 2: Energy-accepting recursive processing with dimensional consistency
# PHYSICS CHECK: Ensure proper J^-1 × J²·s = J·s dimensional structure
DeltaC_S = xi / (T_sem * sigma_pos) # [J^-1·K★] / ([K★] × [dimensionless]) = [J^-1] per-energy susceptibility
DeltaI = alpha_I * (grad_sigma_mag / (grad_sigma_mag.max() + 1e-12))**2 * tau_ref # [J²] × [dimensionless]² × [s] = [J²·s] energy-squared-time
# DIMENSIONAL CHECK: Product should equal h/π [J·s]
certainty_product = DeltaC_S * DeltaI # [J^-1] × [J²·s] = [J·s] ✓ semantic action
certainty_ratio = certainty_product / h_over_pi # [J·s] / [J·s] = dimensionless ✓
PhiC = certainty_product - h_over_pi # collapse functional [J·s]
collapse_mask = (PhiC < 0).astype(float)
# ------------------------
# Semantic entropy and free energy with thermodynamic consistency
# ------------------------
# COHERENCE CALCULATION: α ∈ (0,1] where 1 = perfect coherence, 0 = chaos
# Use smooth exponential instead of hard clipping to avoid artifacts
G0 = np.sqrt(np.mean(grad_sigma_mag**2)) # RMS gradient scale (robust)
alpha_coherence = np.exp(-(grad_sigma_mag / G0)**1.5) # smooth, bounded order parameter
# SEMANTIC ENTROPY: S_sem = C_S k_B ln(1/α) - contradiction processing intensity
# PHYSICS: High S_sem = intense contradiction metabolism (active ordering work)
# Low S_sem = stable regions (minimal semantic processing)
S_sem = CS_const * kB * np.log(1 / alpha_coherence) # [J/K] ✓
# SEMANTIC ENERGY: Internal energy + gradient penalty (represents contradiction stress)
E_sem = E0 + 0.5 * kappa_E * grad_sigma_mag**2 # [J/m³] energy density ✓
# HELMHOLTZ FREE ENERGY: F = E - TS (thermodynamically consistent)
F_sem = E_sem - T_sem * S_sem # [J/m³] - [K★] × [J/K] = [J/m³] ✓
# NOTE: T★ has units that make this dimensionally consistent for semantic systems
# ------------------------
# Figure 1: Semantic Work Landscape (2x2)
# ------------------------
def create_figure1():
import matplotlib.colors as mcolors
fig, axes = plt.subplots(2, 2, figsize=(12, 10))
# No suptitle - will be labeled in paper
# (A) Decoherence strength with PowerNorm to reveal peak structure
norm1 = mcolors.PowerNorm(gamma=0.5, vmin=0, vmax=np.max(Gamma))
im1 = axes[0,0].contourf(X, Y, Gamma, 40, cmap='viridis', norm=norm1)
axes[0,0].set_title("(A) Decoherence Strength Γ")
axes[0,0].set_xlabel('x'); axes[0,0].set_ylabel('y')
fig.colorbar(im1, ax=axes[0,0], label='Γ')
# (B) Semantic temperature + heat flux
im2 = axes[0,1].contourf(X, Y, T_sem, 40, cmap='plasma')
axes[0,1].quiver(X[::8, ::8], Y[::8, ::8], j_sem_x[::8, ::8], j_sem_y[::8, ::8],
scale=2000, color='black', alpha=0.7, width=0.003)
axes[0,1].set_title("(B) Semantic Temperature T★ & Heat Flux")
axes[0,1].set_xlabel('x'); axes[0,1].set_ylabel('y')
fig.colorbar(im2, ax=axes[0,1], label='T★ [semantic-K]')
# (C) Certainty ratio with PowerNorm for better contrast
norm3 = mcolors.PowerNorm(gamma=0.7, vmin=np.min(certainty_ratio), vmax=np.max(certainty_ratio))
im3 = axes[1,0].contourf(X, Y, certainty_ratio, 40, cmap='magma', norm=norm3)
axes[1,0].set_title("(C) Certainty Ratio R")
axes[1,0].set_xlabel('x'); axes[1,0].set_ylabel('y')
fig.colorbar(im3, ax=axes[1,0], label='R = (ΔC_S·ΔI)/(h/π)')
# (D) Collapse functional
im4 = axes[1,1].contourf(X, Y, PhiC, 40, cmap='coolwarm')
axes[1,1].set_title("(D) Collapse Functional Φ_C")
axes[1,1].set_xlabel('x'); axes[1,1].set_ylabel('y')
fig.colorbar(im4, ax=axes[1,1], label='Φ_C [J·s]')
plt.tight_layout()
plt.savefig('figure1_semantic_work_landscape.png', dpi=300, bbox_inches='tight')
plt.show()
return fig
# ------------------------
# Figure 2: Coherence Core Dynamics (Working Version that Shows Bilateral Structure)
# ------------------------
def create_figure2():
"""Create the working version that shows clear bilateral figure-8 structure"""
fig, axes = plt.subplots(1, 2, figsize=(12, 5))
# No suptitle - will be labeled in paper
# Use the working zoom
zoom_xlim = (-2.5, 2.5)
zoom_ylim = (-2.5, 2.5)
# (A) Semantic entropy - ENHANCED contrast for better visibility
S_sem_centered = S_sem.copy()
S_sem_centered = S_sem_centered - S_sem_centered.min() # Shift to start at 0
S_sem_centered = S_sem_centered / S_sem_centered.max() # Normalize to [0,1]
# Apply stronger power scaling for much better contrast
S_sem_enhanced = np.power(S_sem_centered, 0.4) # Stronger enhancement to reveal structure
im1 = axes[0].contourf(X, Y, S_sem_enhanced, 60, cmap='plasma') # 'plasma' colormap for maximum contrast
axes[0].set_title("(A) Contradiction Processing Intensity")
axes[0].set_xlabel('x'); axes[0].set_ylabel('y')
axes[0].set_xlim(zoom_xlim)
axes[0].set_ylim(zoom_ylim)
cbar1 = fig.colorbar(im1, ax=axes[0], label='S_sem (enhanced contrast)')
# (B) Free energy with PowerNorm to reveal bilateral structure
import matplotlib.colors as mcolors
# Print the actual range to help debug
print(f"F_sem range: {F_sem.min():.6f} to {F_sem.max():.6f}")
# Use PowerNorm to enhance contrast in the structured regions
# Shift F_sem to be positive for PowerNorm
F_shifted = F_sem - F_sem.min() + 1e-6 # Add small epsilon to avoid zero
norm2 = mcolors.PowerNorm(gamma=0.6, vmin=F_shifted.min(), vmax=F_shifted.max())
im2 = axes[1].contourf(X, Y, F_shifted, 60, cmap='RdBu_r', norm=norm2)
axes[1].set_title("(B) Free Energy (Bilateral Minima)")
axes[1].set_xlabel('x'); axes[1].set_ylabel('y')
axes[1].set_xlim(zoom_xlim)
axes[1].set_ylim(zoom_ylim)
cbar2 = fig.colorbar(im2, ax=axes[1], label='F_sem [J/m³]')
plt.tight_layout()
plt.savefig('figure2_coherence_core_dynamics.png', dpi=300, bbox_inches='tight')
plt.show()
return fig
# Alternative version with maximum zoom and contrast
def create_figure2_maximum_zoom():
"""Create maximum zoom version focusing on coherence core"""
fig, axes = plt.subplots(1, 2, figsize=(12, 5))
# No suptitle - will be labeled in paper
# (A) Semantic entropy - extreme zoom with custom scaling
S_sem_centered = S_sem.copy()
# Focus only on the very center where the action is
zoom_xlim = (-1.0, 1.0)
zoom_ylim = (-1.0, 1.0)
# Create mask for the zoom region to get local statistics
zoom_mask = (X >= zoom_xlim[0]) & (X <= zoom_xlim[1]) & (Y >= zoom_ylim[0]) & (Y <= zoom_ylim[1])
S_zoom = S_sem_centered[zoom_mask]
# Use local statistics for better contrast
vmin_s = np.percentile(S_zoom, 10)
vmax_s = np.percentile(S_zoom, 90)
im1 = axes[0].contourf(X, Y, S_sem_centered, 50, cmap='YlOrRd',
vmin=vmin_s, vmax=vmax_s)
axes[0].set_title("(A) Contradiction Processing Intensity")
axes[0].set_xlabel('x'); axes[0].set_ylabel('y')
axes[0].set_xlim(zoom_xlim)
axes[0].set_ylim(zoom_ylim)
# Add grid for better reference
axes[0].grid(True, alpha=0.3, linewidth=0.5)
cbar1 = fig.colorbar(im1, ax=axes[0], label='S_sem [J/K] (Processing Intensity)')
# (B) Free energy with extreme zoom
F_zoom = F_sem[zoom_mask]
vmin_f = np.percentile(F_zoom, 5)
vmax_f = np.percentile(F_zoom, 95)
im2 = axes[1].contourf(X, Y, F_sem, 50, cmap='viridis_r',
vmin=vmin_f, vmax=vmax_f)
axes[1].set_title("(B) Free Energy (Core Region)")
axes[1].set_xlabel('x'); axes[1].set_ylabel('y')
axes[1].set_xlim(zoom_xlim)
axes[1].set_ylim(zoom_ylim)
# Add grid for better reference
axes[1].grid(True, alpha=0.3, linewidth=0.5)
cbar2 = fig.colorbar(im2, ax=axes[1], label='F_sem [J/m³]')
plt.tight_layout()
plt.savefig('figure2_coherence_core_maximum_zoom.png', dpi=300, bbox_inches='tight')
plt.show()
return fig
# Alternative version with even more contrast
def create_figure2_high_contrast():
"""Create high-contrast version focusing on central features"""
fig, axes = plt.subplots(1, 2, figsize=(12, 5))
# No suptitle - will be labeled in paper
# Create masks for central region analysis
center_region = (np.abs(X) <= 2.5) & (np.abs(Y) <= 2.5)
# (A) Semantic entropy - normalized and enhanced
S_sem_centered = S_sem.copy()
S_sem_centered = S_sem_centered - S_sem_centered.min() # Shift to start at 0
S_sem_centered = S_sem_centered / S_sem_centered.max() # Normalize to [0,1]
# Apply power scaling for better contrast
S_sem_enhanced = np.power(S_sem_centered, 0.3) # Power < 1 enhances low values
im1 = axes[0].contourf(X, Y, S_sem_enhanced, 40, cmap='YlOrRd')
axes[0].set_title("(A) Semantic Entropy (Enhanced Contrast)")
axes[0].set_xlabel('x'); axes[0].set_ylabel('y')
axes[0].set_xlim(-2.5, 2.5)
axes[0].set_ylim(-2.5, 2.5)
cbar1 = fig.colorbar(im1, ax=axes[0], label='S_sem (normalized)')
# (B) Free energy with adaptive scaling
F_sem_centered = F_sem.copy()
# Focus on the central region dynamics
F_central = F_sem_centered[center_region]
F_med = np.median(F_central)
F_std = np.std(F_central)
# Clip outliers for better contrast
vmin_adaptive = F_med - 2*F_std
vmax_adaptive = F_med + 2*F_std
im2 = axes[1].contourf(X, Y, F_sem_centered, 40, cmap='viridis_r',
vmin=vmin_adaptive, vmax=vmax_adaptive)
axes[1].set_title("(B) Free Energy (Central Focus)")
axes[1].set_xlabel('x'); axes[1].set_ylabel('y')
axes[1].set_xlim(-2.5, 2.5)
axes[1].set_ylim(-2.5, 2.5)
cbar2 = fig.colorbar(im2, ax=axes[1], label='F_sem [J/m³]')
plt.tight_layout()
plt.savefig('figure2_thermodynamic_potentials_high_contrast.png', dpi=300, bbox_inches='tight')
plt.show()
return fig
# ------------------------
# Individual Single Figures (if needed)
# ------------------------
def create_individual_figures():
"""Create individual single-panel figures for detailed analysis"""
# Individual Figure: Decoherence Strength
fig1, ax1 = plt.subplots(1, 1, figsize=(8, 6))
im1 = ax1.contourf(X, Y, Gamma, 40, cmap='viridis')
ax1.set_title("Decoherence Strength Γ (Semantic Work Density)", fontsize=14)
ax1.set_xlabel('x'); ax1.set_ylabel('y')
fig1.colorbar(im1, ax=ax1, label='Γ')
plt.tight_layout()
plt.savefig('decoherence_strength_individual.png', dpi=300, bbox_inches='tight')
plt.show()
# Individual Figure: Semantic Temperature with Heat Flux
fig2, ax2 = plt.subplots(1, 1, figsize=(8, 6))
im2 = ax2.contourf(X, Y, T_sem, 40, cmap='plasma')
ax2.quiver(X[::8, ::8], Y[::8, ::8], j_sem_x[::8, ::8], j_sem_y[::8, ::8],
scale=2000, color='black', alpha=0.7, width=0.003)
ax2.set_title("Semantic Temperature T★ & Heat Flux (Phase Agitation)", fontsize=14)
ax2.set_xlabel('x'); ax2.set_ylabel('y')
fig2.colorbar(im2, ax=ax2, label='T★ [semantic-K]')
plt.tight_layout()
plt.savefig('semantic_temperature_individual.png', dpi=300, bbox_inches='tight')
plt.show()
# Individual Figure: Certainty Ratio
fig3, ax3 = plt.subplots(1, 1, figsize=(8, 6))
im3 = ax3.contourf(X, Y, certainty_ratio, 40, cmap='magma')
ax3.set_title("Certainty Ratio R (Recursive Self-Reference Signature)", fontsize=14)
ax3.set_xlabel('x'); ax3.set_ylabel('y')
fig3.colorbar(im3, ax=ax3, label='R = (ΔC_S·ΔI)/(h/π)')
plt.tight_layout()
plt.savefig('certainty_ratio_individual.png', dpi=300, bbox_inches='tight')
plt.show()
# ------------------------
# Generate Figures
# ------------------------
print("Generating Figure 1: Semantic Work Landscape (2x2)...")
fig1 = create_figure1()
print("\nGenerating Figure 2: Coherence Core Dynamics...")
fig2 = create_figure2()
# Uncomment to generate individual figures
# print("\nGenerating Individual Figures...")
# create_individual_figures()
# ------------------------
# Analysis with updated units
# ------------------------
print("\n" + "="*60)
print("THERMODYNAMIC COHERENCE ANALYSIS")
print("Mode 2: Energy-Accepting Recursive Semantic Processing")
print("="*60)
print(f"\nContradiction Scaffold σ(x,y):")
print(f" Range: {sigma.min():.3e} to {sigma.max():.3e}")
print(f" Gradient magnitude: {grad_sigma_mag.min():.3e} to {grad_sigma_mag.max():.3e}")
print(f"\nSemantic Temperature T★ (Phase Agitation Energy, NOT thermodynamic temperature):")
print(f" Range: {T_sem.min():.2f} K★ to {T_sem.max():.2f} K★")
print(f" Baseline T₀: {T0:.1f} K★ (semantic ground state)")
print(f" Note: These are NOT Kelvin - they are scaled phase agitation units")
print(f"\nRecursive Self-Reference Dynamics:")
print(f" ΔC_S [J⁻¹] range: {DeltaC_S.min():.3e} to {DeltaC_S.max():.3e}")
print(f" ΔI [J²·s] range: {DeltaI.min():.3e} to {DeltaI.max():.3e}")
print(f" Semantic action ΔC_S·ΔI: {certainty_product.min():.3e} to {certainty_product.max():.3e} [J·s]")
print(f"\nQuantum Threshold Analysis:")
print(f" Planck threshold h/π: {h_over_pi:.3e} [J·s]")
print(f" Certainty ratio range: {certainty_ratio.min():.6f} to {certainty_ratio.max():.6f}")
print(f" Mean certainty ratio: {certainty_ratio.mean():.6f}")
print(f" Sub-threshold operation: {(certainty_ratio < 1.0).sum() / certainty_ratio.size * 100:.1f}%")
print(f"\nDimensional Consistency Verification:")
print(f" xi units: [J^-1·K★] for proper ΔC_S scaling")
print(f" ΔC_S units: [J^-1·K★] / [K★] = [J^-1] ✓")
print(f" alpha_I units: [J²] for energy-squared scaling")
print(f" ΔI units: [J²] × [dimensionless]² × [s] = [J²·s] ✓")
print(f" Product ΔC_S·ΔI: [J^-1] × [J²·s] = [J·s] ✓")
print(f" Planck threshold h/π: {h_over_pi:.3e} [J·s] ✓")
print(f" Ratio is dimensionless: {certainty_ratio.mean():.6f} ✓")
print(f" Energy density with stiffness: [J/m] × [1/m²] = [J/m³] ✓")
# Add correlation calculation that was missing
correlation = np.corrcoef(grad_sigma_mag.flatten(),
np.sqrt(j_sem_x**2 + j_sem_y**2).flatten())[0, 1]
print(f"\nThermodynamic Consistency Check:")
print(f" Heat flux ∝ ∇T★ correlation: {correlation:.3f} (should be positive)")
print(f" Free energy F = E - T★S units: [J/m³] ✓")
print(f" Semantic entropy S_sem > 0: {(S_sem > 0).all()} ✓")
print(f" Coherence α ∈ (0,1]: min={alpha_coherence.min():.6f}, max={alpha_coherence.max():.6f} ✓")
print(f"\nFigure-8 Loop Architecture Analysis:")
# Identify central coherence core (highest processing intensity)
center_mask = (np.abs(X) < 1) & (np.abs(Y) < 1)
central_processing = S_sem[center_mask].mean()
central_free_energy = F_sem[center_mask].mean()
print(f" Central processing intensity: {central_processing:.2e} J/K (contradiction metabolism)")
print(f" Central free energy: {central_free_energy:.2e} J/m³")
# Identify loop regions
upper_loop = (Y > 0) & (np.abs(X) < 2)
lower_loop = (Y < 0) & (np.abs(X) < 2)
upper_processing = S_sem[upper_loop].mean()
lower_processing = S_sem[lower_loop].mean()
print(f" Upper loop processing: {upper_processing:.2e} J/K")
print(f" Lower loop processing: {lower_processing:.2e} J/K")
print(f"\nPhysical Interpretation:")
print(f" • High-intensity regions in entropy plots = maximum contradiction processing (active ordering)")
print(f" • Low-intensity regions = stable/passive zones (minimal semantic work)")
print(f" • Central core = recursive identity maintaining itself through intense processing")
print(f" • Figure-8 loops = differential contradiction metabolism pathways")
print(f" • High S_sem ≠ disorder; it indicates maximum meaning-making activity")
print("\n" + "="*60)