#!/usr/bin/env python3
"""
Hadron Structure Testing with s ≈ 0.17 Angular Momentum Constraint

Tests the discovered s ≈ 0.17 constraint (L ≈ 0.17ℏ for quarks) against:
1. Known hadron magnetic moments
2. Spin-orbit coupling in nucleons  
3. Regge trajectories (mass vs angular momentum)
4. Multi-quark systems (mesons, baryons)
5. Bag model predictions
6. Experimental form factors

Author: Andre Heinecke & AI Collaborators
Date: June 2025
License: CC BY-SA 4.0
Repository: https://git.esus.name/esus/spin_paper/
"""

import numpy as np
import sys

try:
    import scipy.constants as const
    from scipy.constants import physical_constants
    SCIPY_AVAILABLE = True
except ImportError:
    SCIPY_AVAILABLE = False

# ==============================================================================
# CONSTANTS AND PARAMETERS
# ==============================================================================

def get_constants():
    """Get fundamental constants"""
    if SCIPY_AVAILABLE:
        return {
            'hbar': const.hbar,
            'c': const.c, 
            'e': const.e,
            'me': const.m_e,
            'mp': const.m_p,
            'mn': const.m_n,
        }
    else:
        return {
            'hbar': 1.054571817e-34,
            'c': 299792458,
            'e': 1.602176634e-19,
            'me': 9.1093837015e-31,
            'mp': 1.67262192369e-27,
            'mn': 1.67492749804e-27,
        }

def get_hadron_data():
    """Known hadron properties for testing"""
    
    # Convert units
    if SCIPY_AVAILABLE:
        mev_to_kg = const.e * 1e6 / const.c**2
        mu_n = physical_constants['nuclear magneton'][0]  # Nuclear magneton
    else:
        mev_to_kg = 1.602176634e-19 * 1e6 / (299792458**2)
        mu_n = 5.0507837461e-27  # J/T, nuclear magneton
    
    hadrons = {
        # Baryons (qqq systems)
        'proton': {
            'mass': 938.3 * mev_to_kg,
            'charge': 1,
            'spin': 0.5,
            'magnetic_moment': 2.7928 * mu_n,  # Experimental value
            'quarks': ['u', 'u', 'd'],
            'angular_momentum': 0.5,  # Total J
        },
        'neutron': {
            'mass': 939.6 * mev_to_kg,
            'charge': 0,
            'spin': 0.5, 
            'magnetic_moment': -1.9130 * mu_n,
            'quarks': ['u', 'd', 'd'],
            'angular_momentum': 0.5,
        },
        'delta_plus': {
            'mass': 1232 * mev_to_kg,
            'charge': 1,
            'spin': 1.5,
            'magnetic_moment': None,  # To be calculated
            'quarks': ['u', 'u', 'd'],
            'angular_momentum': 1.5,
        },
        
        # Mesons (qq̄ systems)
        'pion_charged': {
            'mass': 139.6 * mev_to_kg,
            'charge': 1,
            'spin': 0,
            'magnetic_moment': None,
            'quarks': ['u', 'd̄'],  # or d, ū
            'angular_momentum': 0,
        },
        'rho_meson': {
            'mass': 775.3 * mev_to_kg,
            'charge': 1,
            'spin': 1,
            'magnetic_moment': None,
            'quarks': ['u', 'd̄'],
            'angular_momentum': 1,
        },
        
        # Heavy quarkonia for testing
        'j_psi': {
            'mass': 3097 * mev_to_kg,
            'charge': 0,
            'spin': 1,
            'magnetic_moment': None,
            'quarks': ['c', 'c̄'],
            'angular_momentum': 1,
        }
    }
    
    return hadrons, mu_n

# ==============================================================================
# ANGULAR MOMENTUM ANALYSIS
# ==============================================================================

class HadronAngularMomentumAnalyzer:
    """Test s ≈ 0.17 constraint against hadron physics"""
    
    def __init__(self):
        self.constants = get_constants()
        self.hadrons, self.mu_n = get_hadron_data()
        self.s_quark = 0.17  # Discovered constraint
        self.s_electron = 0.5  # Atomic reference
        
    def calculate_quark_magnetic_moment(self, quark_type, s_factor):
        """Calculate magnetic moment with modified angular momentum"""
        
        # Quark charges (in units of e)
        quark_charges = {
            'u': 2.0/3.0,
            'd': -1.0/3.0,
            'c': 2.0/3.0,
            's': -1.0/3.0,
            'b': -1.0/3.0,
            't': 2.0/3.0
        }
        
        # Constituent quark masses (effective masses in hadrons)
        if SCIPY_AVAILABLE:
            mev_to_kg = const.e * 1e6 / const.c**2
        else:
            mev_to_kg = 1.602176634e-19 * 1e6 / (299792458**2)
            
        quark_masses = {
            'u': 350 * mev_to_kg,
            'd': 350 * mev_to_kg, 
            'c': 1500 * mev_to_kg,
            's': 500 * mev_to_kg,
            'b': 4800 * mev_to_kg,
            't': 173000 * mev_to_kg
        }
        
        q = quark_charges[quark_type] * self.constants['e']
        m = quark_masses[quark_type]
        
        # Magnetic moment: μ = q*L/(2m) where L = s*ℏ
        mu = q * s_factor * self.constants['hbar'] / (2 * m)
        
        return mu, q, m
    
    def test_nucleon_magnetic_moments(self):
        """Test if s ≈ 0.17 can explain proton/neutron magnetic moments"""
        
        print("NUCLEON MAGNETIC MOMENT ANALYSIS")
        print("="*50)
        print("Testing whether s ≈ 0.17 constraint explains experimental values")
        print()
        
        for nucleon in ['proton', 'neutron']:
            data = self.hadrons[nucleon]
            quarks = data['quarks']
            mu_exp = data['magnetic_moment']
            
            print(f"{nucleon.upper()} ({' '.join(quarks)}):")
            print(f"  Experimental μ = {mu_exp/self.mu_n:.3f} μ_N")
            
            # Calculate with s ≈ 0.17
            mu_total_s017 = 0
            for quark in quarks:
                quark_clean = quark.replace('̄', '')  # Remove antiparticle bar
                sign = -1 if '̄' in quark else 1
                mu_q, q, m = self.calculate_quark_magnetic_moment(quark_clean, self.s_quark)
                mu_total_s017 += sign * mu_q
                
            print(f"  Predicted (s=0.17): {mu_total_s017/self.mu_n:.3f} μ_N")
            
            # Calculate with standard s = 0.5 for comparison
            mu_total_s05 = 0
            for quark in quarks:
                quark_clean = quark.replace('̄', '')
                sign = -1 if '̄' in quark else 1
                mu_q, q, m = self.calculate_quark_magnetic_moment(quark_clean, self.s_electron)
                mu_total_s05 += sign * mu_q
                
            print(f"  Standard (s=0.5): {mu_total_s05/self.mu_n:.3f} μ_N")
            
            # Agreement ratios
            ratio_s017 = (mu_total_s017 / mu_exp) if mu_exp != 0 else 0
            ratio_s05 = (mu_total_s05 / mu_exp) if mu_exp != 0 else 0
            
            print(f"  Agreement s=0.17: {ratio_s017:.3f}")
            print(f"  Agreement s=0.5:  {ratio_s05:.3f}")
            print()
            
        return mu_total_s017, mu_total_s05
    
    def test_regge_trajectories(self):
        """Test angular momentum vs mass relationships"""
        
        print("REGGE TRAJECTORY ANALYSIS")
        print("="*40) 
        print("Testing mass vs angular momentum relationships")
        print()
        
        # Collect hadrons by angular momentum
        j_values = {}
        for name, data in self.hadrons.items():
            j = data['angular_momentum']
            mass = data['mass']
            if j not in j_values:
                j_values[j] = []
            j_values[j].append((name, mass))
        
        print(f"{'J':<5} {'Hadron':<15} {'Mass (MeV)':<12} {'s_eff implied':<12}")
        print("-" * 50)
        
        for j in sorted(j_values.keys()):
            for name, mass in j_values[j]:
                mass_mev = mass * self.constants['c']**2 / self.constants['e'] / 1e6
                
                # If this were orbital angular momentum: L = J*ℏ = s_eff*ℏ
                s_eff = j
                
                print(f"{j:<5.1f} {name:<15} {mass_mev:<12.1f} {s_eff:<12.1f}")
        
        print()
        print("Note: If quarks follow s ≈ 0.17, total hadron J should reflect")
        print("      combinations of individual quark angular momenta")
    
    def test_bag_model_connection(self):
        """Test connection to MIT bag model"""
        
        print("BAG MODEL CONNECTION")
        print("="*30)
        print("Testing if s ≈ 0.17 is consistent with bag confinement")
        print()
        
        # Typical bag parameters
        bag_constant = 145e6 * self.constants['e']  # 145 MeV in Joules
        bag_radius_proton = 0.8e-15  # 0.8 fm
        
        # In bag model: quark angular momentum from L = sqrt(j(j+1))*ℏ
        # For j = 1/2: L = sqrt(3/4)*ℏ = 0.866*ℏ
        # Our s ≈ 0.17 gives L = 0.17*ℏ
        
        j_bag_standard = 0.5  # Quark spin
        L_bag_standard = np.sqrt(j_bag_standard * (j_bag_standard + 1)) * self.constants['hbar']
        L_our_model = self.s_quark * self.constants['hbar']
        
        print(f"Bag model (j=1/2): L = {L_bag_standard/self.constants['hbar']:.3f}ℏ")
        print(f"Our model: L = {L_our_model/self.constants['hbar']:.3f}ℏ")
        print(f"Ratio: {L_our_model/L_bag_standard:.3f}")
        print()
        
        # Energy scale comparison
        E_bag = bag_constant
        E_geometric = self.constants['hbar']**2 * self.s_quark**2 / (
            350e6 * self.constants['e'] / self.constants['c']**2 * bag_radius_proton**3
        )
        
        print(f"Bag constant: {E_bag/self.constants['e']/1e6:.0f} MeV")
        print(f"Geometric energy: {E_geometric/self.constants['e']/1e6:.0f} MeV") 
        print(f"Scale ratio: {E_geometric/E_bag:.3f}")
    
    def test_multi_quark_systems(self):
        """Test how s ≈ 0.17 applies to different quark combinations"""
        
        print("\nMULTI-QUARK SYSTEM ANALYSIS")
        print("="*40)
        print("Testing s ≈ 0.17 in mesons vs baryons")
        print()
        
        print(f"{'System':<15} {'Quarks':<10} {'J_total':<8} {'s_individual':<12} {'Configuration'}")
        print("-" * 65)
        
        # Analyze different systems
        systems = [
            ('Pion', 'qq̄', 0, 'Antiparallel spins'),
            ('Rho meson', 'qq̄', 1, 'Parallel spins + L=0'),
            ('Proton', 'qqq', 0.5, 'Two parallel + one anti'),
            ('Delta', 'qqq', 1.5, 'All parallel spins'),
        ]
        
        for name, quarks, j_total, config in systems:
            # For our model: each quark contributes ≈ 0.17ℏ angular momentum
            n_quarks = len(quarks.replace('̄', ''))
            s_individual = self.s_quark
            
            print(f"{name:<15} {quarks:<10} {j_total:<8.1f} {s_individual:<12.2f} {config}")
        
        print()
        print("Key insight: If individual quarks have L ≈ 0.17ℏ,")
        print("total hadron angular momentum comes from vector combination")
        print("of reduced individual contributions plus relative motion")
    
    def experimental_predictions(self):
        """Generate testable predictions from s ≈ 0.17 constraint"""
        
        print("\nEXPERIMENTAL PREDICTIONS")
        print("="*35)
        print("Testable consequences of L_quark ≈ 0.17ℏ constraint")
        print()
        
        print("1. MAGNETIC MOMENT RATIOS:")
        print("   μ_p/μ_n should scale with s ≈ 0.17 rather than s = 0.5")
        print()
        
        print("2. FORM FACTOR SLOPES:")
        print("   Charge/magnetic form factors reflect reduced angular momentum")
        print("   Slope parameters should differ from point-particle predictions")
        print()
        
        print("3. SPIN-ORBIT COUPLING:")
        print("   Hyperfine structure in hadron spectra reflects L ≈ 0.17ℏ")
        print("   Different from atomic physics (L = 0.5ℏ)")
        print()
        
        print("4. DEEP INELASTIC SCATTERING:")
        print("   Parton angular momentum distributions affected")
        print("   Total quark contribution to nucleon spin modified")
        print()
        
        print("5. LATTICE QCD TESTS:")
        print("   Direct measurement of quark angular momentum in simulations")
        print("   Should find L ≈ 0.17ℏ for individual quarks")

# ==============================================================================
# MAIN ANALYSIS
# ==============================================================================

def main():
    """Run hadron structure analysis with s ≈ 0.17 constraint"""
    
    print("HADRON STRUCTURE ANALYSIS: s ≈ 0.17 ANGULAR MOMENTUM CONSTRAINT")
    print("="*75)
    print("Testing discovered quark constraint L ≈ 0.17ℏ against hadron physics")
    print()
    
    analyzer = HadronAngularMomentumAnalyzer()
    
    # Test magnetic moments
    analyzer.test_nucleon_magnetic_moments()
    
    # Test Regge trajectories  
    analyzer.test_regge_trajectories()
    
    # Test bag model connection
    analyzer.test_bag_model_connection()
    
    # Test multi-quark systems
    analyzer.test_multi_quark_systems()
    
    # Generate experimental predictions
    analyzer.experimental_predictions()
    
    print(f"\n" + "="*75)
    print("ANALYSIS COMPLETE")
    print("="*75)

if __name__ == "__main__":
    if len(sys.argv) > 1 and sys.argv[1] in ['-h', '--help']:
        print("Usage: python hadron_structure_s017_test.py")
        print("  Tests s ≈ 0.17 angular momentum constraint against hadron physics")
        print("  Generates experimental predictions for verification")
        sys.exit(0)
    
    main()
