spin_paper/archive/experimental-scripts/atomic_verification_clean.py

691 lines
26 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#!/usr/bin/env python3
"""
verify_atoms_balls_external_constants.py
Atomic scale verification using ONLY external authoritative constants
Proves: F = ℏ²/(γmr³) = ke²/r² for all elements
No hardcoded constants - all values fetched from:
- SI Digital Framework: https://si-digital-framework.org/constants
- NIST API: https://physics.nist.gov/cgi-bin/cuu/
- BIPM: https://www.bipm.org/en/measurement-units/
Author: Andre Heinecke & AI Collaborators
Date: June 2025
License: CC BY-SA 4.0
"""
import math
import sys
import urllib.request
import urllib.error
from decimal import Decimal, getcontext
# Set high precision for exact calculations
getcontext().prec = 50
class SIDigitalFrameworkConstants:
"""
Physical constants fetched from SI Digital Framework
Source: https://si-digital-framework.org/constants
No hardcoded fallback values - all from authoritative sources
"""
def __init__(self):
self.constants = {}
self.sources = {}
self._fetch_si_constants()
def _fetch_si_constants(self):
"""Fetch constants from SI Digital Framework"""
print("Fetching constants from SI Digital Framework...")
print("Source: https://si-digital-framework.org/constants")
# Try to fetch the RDF/TTL file first
ttl_url = "https://si-digital-framework.org/constants.ttl"
try:
import urllib.request
import urllib.error
# Set up request with proper headers
headers = {
'User-Agent': 'Scientific Research Script (CC BY-SA 4.0)',
'Accept': 'text/turtle, application/rdf+xml, text/plain, */*',
'Accept-Language': 'en-US,en;q=0.9'
}
req = urllib.request.Request(ttl_url, headers=headers)
with urllib.request.urlopen(req, timeout=30) as response:
ttl_data = response.read().decode('utf-8')
print(f"✓ Fetched {len(ttl_data)} characters from constants.ttl")
self._parse_ttl_constants(ttl_data)
return
except Exception as e:
print(f"⚠ Could not fetch constants.ttl: {e}")
print("Falling back to individual constant URLs...")
self._fetch_individual_constants()
def _parse_ttl_constants(self, ttl_data):
"""Parse TTL/RDF data to extract constants"""
print("Parsing TTL data for physical constants...")
# Basic TTL parsing for our needed constants
# This is a simple parser - for production use a proper RDF library
lines = ttl_data.split('\n')
current_resource = None
current_props = {}
# Constants we need and their likely identifiers
target_constants = {
'h': ['planck-constant', 'PlanckConstant', 'h'],
'hbar': ['reduced-planck-constant', 'ReducedPlanckConstant', 'hbar'],
'c': ['speed-of-light', 'SpeedOfLight', 'c'],
'e': ['elementary-charge', 'ElementaryCharge', 'e'],
'm_e': ['electron-mass', 'ElectronMass', 'me'],
'alpha': ['fine-structure-constant', 'FineStructureConstant', 'alpha'],
'a0': ['bohr-radius', 'BohrRadius', 'a0'],
'k': ['coulomb-constant', 'CoulombConstant', 'k'],
'epsilon0': ['vacuum-permittivity', 'VacuumPermittivity', 'epsilon0']
}
found_constants = {}
for line in lines:
line = line.strip()
# Skip comments and empty lines
if not line or line.startswith('#'):
continue
# Look for resource definitions
if line.startswith('<') and '>' in line and (' a ' in line or 'rdf:type' in line):
# This might be a constant definition
resource_match = line.split('<')[1].split('>')[0] if '<' in line and '>' in line else None
if resource_match:
# Check if this looks like one of our target constants
for const_name, identifiers in target_constants.items():
for identifier in identifiers:
if identifier.lower() in resource_match.lower():
current_resource = const_name
current_props = {'uri': resource_match}
break
# Look for properties of the current resource
elif current_resource and ':' in line:
if 'value' in line.lower() or 'numericalValue' in line.lower():
# Extract numerical value
value_match = self._extract_ttl_value(line)
if value_match:
current_props['value'] = value_match
elif 'uncertainty' in line.lower() or 'standardUncertainty' in line.lower():
# Extract uncertainty
uncertainty_match = self._extract_ttl_value(line)
if uncertainty_match:
current_props['uncertainty'] = uncertainty_match
elif 'unit' in line.lower():
# Extract unit
unit_match = self._extract_ttl_value(line)
if unit_match:
current_props['unit'] = unit_match
# End of resource definition
elif line.startswith('.') and current_resource and 'value' in current_props:
found_constants[current_resource] = current_props.copy()
current_resource = None
current_props = {}
if found_constants:
print(f"✓ Parsed {len(found_constants)} constants from TTL data")
for name, props in found_constants.items():
self.constants[name] = props
self.sources[name] = f"SI Digital Framework TTL: {props.get('uri', 'unknown')}"
else:
print("⚠ No constants found in TTL data, trying individual URLs")
self._fetch_individual_constants()
def _extract_ttl_value(self, line):
"""Extract value from TTL property line"""
# Simple extraction - look for quoted strings or numbers
import re
# Look for quoted values
quote_match = re.search(r'"([^"]+)"', line)
if quote_match:
return quote_match.group(1)
# Look for bare numbers
number_match = re.search(r'(\d+\.?\d*(?:[eE][+-]?\d+)?)', line)
if number_match:
return number_match.group(1)
return None
def _fetch_individual_constants(self):
"""Fetch constants from individual authoritative URLs"""
print("Fetching individual constants from authoritative sources...")
# Direct links to individual constants from SI Digital Framework and NIST
constant_urls = {
'h': {
'url': 'https://www.nist.gov/si-redefinition/meet-constants',
'value': '6.62607015e-34', # This should be fetched, not hardcoded
'source': 'SI 2019 definition (exact)'
},
'c': {
'url': 'https://physics.nist.gov/cgi-bin/cuu/Value?c',
'source': 'SI definition 1983 (exact)'
},
'e': {
'url': 'https://physics.nist.gov/cgi-bin/cuu/Value?e',
'source': 'SI 2019 definition (exact)'
}
# Add more individual URLs as needed
}
print("⚠ Individual constant fetching not yet implemented")
print("This requires either:")
print(" 1. Successful TTL parsing, or")
print(" 2. Implementation of individual NIST API calls")
print(" 3. Manual research of each constant's authoritative URL")
raise ValueError("No authoritative constant sources available")
def get_constant(self, name):
"""Get a constant by name, returning None if not available"""
return self.constants.get(name)
def get_value_as_decimal(self, name, precision=50):
"""Get constant value as high-precision Decimal"""
const = self.get_constant(name)
if not const or 'value' not in const:
return None
try:
return Decimal(str(const['value']))
except (ValueError, TypeError) as e:
print(f"⚠ Could not convert {name} to Decimal: {e}")
return None
def print_sources(self):
"""Print data sources for transparency"""
print("\nDATA SOURCES (From SI Digital Framework)")
print("="*50)
if not self.constants:
print("❌ No constants available - fetching failed")
return
for name, const in self.constants.items():
source = self.sources.get(name, "Unknown source")
value = const.get('value', 'Unknown')
uncertainty = const.get('uncertainty', 'Unknown')
unit = const.get('unit', 'Unknown')
print(f"{name:>6}: {value} ± {uncertainty} {unit}")
print(f" Source: {source}")
def verify_required_constants(self):
"""Verify we have all constants needed for atomic calculations"""
required = ['h', 'c', 'e', 'm_e', 'alpha']
missing = []
for const in required:
if const not in self.constants:
missing.append(const)
if missing:
print(f"❌ Missing required constants: {missing}")
print("Available constants:", list(self.constants.keys()))
return False
print("✓ All required constants available")
return True
def research_individual_constant_urls():
"""
Research and document individual URLs for each physical constant
This function helps build the authoritative URL database
"""
print("\n🔬 RESEARCH: Individual Constant URLs")
print("="*60)
constant_research = {
'Planck constant (h)': [
'https://physics.nist.gov/cgi-bin/cuu/Value?h',
'https://www.bipm.org/en/measurement-units/si-constants',
'https://si-digital-framework.org/SI/constants/h'
],
'Speed of light (c)': [
'https://physics.nist.gov/cgi-bin/cuu/Value?c',
'https://www.bipm.org/en/measurement-units/si-constants',
'https://si-digital-framework.org/SI/constants/c'
],
'Elementary charge (e)': [
'https://physics.nist.gov/cgi-bin/cuu/Value?e',
'https://www.bipm.org/en/measurement-units/si-constants',
'https://si-digital-framework.org/SI/constants/e'
],
'Electron mass (mₑ)': [
'https://physics.nist.gov/cgi-bin/cuu/Value?me',
'https://pdg.lbl.gov/', # Particle Data Group
'https://si-digital-framework.org/SI/constants/me'
],
'Fine structure constant (α)': [
'https://physics.nist.gov/cgi-bin/cuu/Value?alph',
'https://si-digital-framework.org/SI/constants/alpha'
],
'Bohr radius (a₀)': [
'https://physics.nist.gov/cgi-bin/cuu/Value?bohrrada0',
'https://si-digital-framework.org/SI/constants/a0'
]
}
print("Authoritative URLs for physical constants:")
for const_name, urls in constant_research.items():
print(f"\n{const_name}:")
for i, url in enumerate(urls, 1):
print(f" {i}. {url}")
print(f"\n📋 NEXT STEPS:")
print(f"1. Test each URL to verify it returns machine-readable data")
print(f"2. Implement parsers for each authoritative source format")
print(f"3. Build fallback chain: SI Digital → NIST → BIPM → PDG")
print(f"4. Add uncertainty and unit parsing for each source")
return constant_research
def fetch_from_nist_api(constant_name):
"""
Fetch individual constant from NIST Web API
Example: https://physics.nist.gov/cgi-bin/cuu/Value?h&n=json
"""
print(f"Fetching {constant_name} from NIST API...")
# NIST parameter mapping
nist_params = {
'h': 'h', # Planck constant
'hbar': 'hbar', # Reduced Planck constant
'c': 'c', # Speed of light
'e': 'e', # Elementary charge
'm_e': 'me', # Electron mass
'alpha': 'alph', # Fine structure constant
'a0': 'bohrrada0', # Bohr radius
'k': 'k', # Coulomb constant
'epsilon0': 'ep0' # Vacuum permittivity
}
if constant_name not in nist_params:
print(f"⚠ No NIST parameter known for {constant_name}")
return None
nist_param = nist_params[constant_name]
# Try different NIST API endpoints
endpoints = [
f"https://physics.nist.gov/cgi-bin/cuu/Value?{nist_param}&n=json",
f"https://physics.nist.gov/cgi-bin/cuu/Value?{nist_param}",
f"https://physics.nist.gov/cuu/Constants/Table/allascii.txt"
]
for endpoint in endpoints:
try:
import urllib.request
import urllib.error
import json
headers = {
'User-Agent': 'Scientific Research (atoms-are-balls verification)',
'Accept': 'application/json, text/plain, text/html, */*'
}
req = urllib.request.Request(endpoint, headers=headers)
with urllib.request.urlopen(req, timeout=15) as response:
data = response.read().decode('utf-8')
# Try to parse as JSON first
if 'json' in endpoint:
try:
json_data = json.loads(data)
return json_data
except json.JSONDecodeError:
pass
# Parse as HTML/text
return {'raw_data': data, 'source': endpoint}
except Exception as e:
print(f" Failed {endpoint}: {e}")
continue
print(f"❌ All NIST endpoints failed for {constant_name}")
return None
"""
Effective nuclear charge using Slater's rules
Reference: Slater, J.C. (1930). Phys. Rev. 36, 57-64
"""
Z = Decimal(str(Z))
if Z == 1:
return Decimal('1.0') # Hydrogen: no screening
elif Z == 2:
return Z - Decimal('0.3125') # Helium: precise value
else:
# For Z > 2, 1s electrons experience screening from other 1s electron
# Plus small additional screening from outer electrons
screening = Decimal('0.31') + Decimal('0.002') * (Z - Decimal('2')) / Decimal('98')
return Z - screening
def relativistic_gamma(Z, n=1):
"""
Relativistic correction factor γ = 1/√(1-(v/c)²)
For atomic electrons: v ≈ Z⋅α⋅c/n where α is fine structure constant
Reference: Bethe & Salpeter, "Quantum Mechanics of One- and Two-Electron Atoms"
"""
const = AuthoritativeConstants()
Z = Decimal(str(Z))
n = Decimal(str(n))
# Electron velocity as fraction of light speed
v_over_c = Z * const.alpha / n
if v_over_c < Decimal('0.1'):
# Taylor expansion for better numerical precision
v2 = v_over_c * v_over_c
gamma = Decimal('1') + v2 / Decimal('2') + Decimal('3') * v2 * v2 / Decimal('8')
else:
# Full relativistic formula
one = Decimal('1')
gamma = one / (one - v_over_c * v_over_c).sqrt()
# QED corrections for heavy elements (Z > 70)
if Z > 70:
alpha_sq = const.alpha * const.alpha
z_ratio_sq = (Z / Decimal('137')) * (Z / Decimal('137'))
qed_correction = Decimal('1') + alpha_sq * z_ratio_sq / Decimal('8')
gamma = gamma * qed_correction
return gamma
def verify_element_with_external_constants(Z, element_name="", verbose=False):
"""
Verify the fundamental identity using externally fetched constants
F = ℏ²/(γmr³) = ke²/r²
Returns:
dict: Results including forces, ratio, and systematic deviation, or None if constants unavailable
"""
# Get constants from external sources
const_fetcher = SIDigitalFrameworkConstants()
if not const_fetcher.verify_required_constants():
print(f"❌ Cannot verify element {Z} - missing required constants")
return None
try:
# Extract required constants with proper error handling
h = const_fetcher.get_value_as_decimal('h')
c = const_fetcher.get_value_as_decimal('c')
e = const_fetcher.get_value_as_decimal('e')
m_e = const_fetcher.get_value_as_decimal('m_e')
alpha = const_fetcher.get_value_as_decimal('alpha')
# Check for missing critical constants
missing = []
const_values = {'h': h, 'c': c, 'e': e, 'm_e': m_e, 'alpha': alpha}
for name, value in const_values.items():
if value is None:
missing.append(name)
if missing:
print(f"❌ Missing constant values: {missing}")
# Try to fetch individual constants
for const_name in missing:
fetched = fetch_from_nist_api(const_name)
if fetched:
print(f"✓ Fetched {const_name} from NIST API")
# Parse and use the fetched value
# This would need implementation based on NIST API response format
else:
print(f"❌ Could not fetch {const_name} from any source")
return None
# Calculate derived constants
pi = Decimal('3.141592653589793238462643383279502884197')
hbar = h / (2 * pi)
# Calculate Coulomb constant from other fundamental constants
# k = 1/(4πε₀) where ε₀ = 1/(μ₀c²) and μ₀ = 4π × 10⁻⁷
mu0 = 4 * pi * Decimal('1e-7') # H/m, exact by definition
epsilon0 = 1 / (mu0 * c * c)
k = 1 / (4 * pi * epsilon0)
# Calculate Bohr radius from fundamental constants
a0 = hbar * hbar / (m_e * k * e * e)
if verbose:
print(f"\nUsing externally fetched constants:")
const_fetcher.print_sources()
print(f"\nDerived constants:")
print(f" ℏ = h/(2π) = {float(hbar):.6e} J⋅s")
print(f" k = 1/(4πε₀) = {float(k):.6e} N⋅m²⋅C⁻²")
print(f" a₀ = ℏ²/(mₑke²) = {float(a0):.6e} m")
# Now proceed with the atomic calculation
Z_eff = slater_z_eff_decimal(Z)
r = a0 / Z_eff
gamma = relativistic_gamma_decimal(Z, alpha, c, n=1)
# Geometric force: F = ℏ²/(γmr³)
F_geometric = hbar * hbar / (gamma * m_e * r * r * r)
# Coulomb force: F = kZ_eff⋅e²/(γr²)
F_coulomb = k * Z_eff * e * e / (gamma * r * r)
# Mathematical ratio
ratio = F_geometric / F_coulomb
deviation_ppb = abs(Decimal('1') - ratio) * Decimal('1e9')
if verbose:
print(f"\n{element_name} (Z = {Z}) - Using External Constants")
print(f" Z_eff = {float(Z_eff):.6f}")
print(f" r = {float(r)*1e12:.3f} pm")
print(f" gamma = {float(gamma):.6f}")
if float(gamma) > 1.001:
v_c = float(Z * alpha)
print(f" v/c ≈ {v_c:.3f} (relativistic!)")
print(f" F_geometric = {float(F_geometric):.6e} N")
print(f" F_coulomb = {float(F_coulomb):.6e} N")
print(f" Ratio = {float(ratio):.15f}")
print(f" Deviation = {float(deviation_ppb):.6f} ppb")
return {
'Z': Z,
'element': element_name,
'Z_eff': float(Z_eff),
'radius_pm': float(r * 1e12),
'gamma': float(gamma),
'F_geometric': float(F_geometric),
'F_coulomb': float(F_coulomb),
'ratio': float(ratio),
'deviation_ppb': float(deviation_ppb),
'agreement_percent': float(ratio * 100),
'constants_source': 'SI Digital Framework + derived'
}
except Exception as e:
print(f"❌ Error in calculation for element {Z}: {e}")
import traceback
traceback.print_exc()
return None
def slater_z_eff_decimal(Z):
"""Calculate effective nuclear charge using Slater's rules (Decimal precision)"""
Z = Decimal(str(Z))
if Z == 1:
return Decimal('1.0') # Hydrogen: no screening
elif Z == 2:
return Z - Decimal('0.3125') # Helium: precise value
else:
# For Z > 2, 1s electrons experience screening from other 1s electron
# Plus small additional screening from outer electrons
screening = Decimal('0.31') + Decimal('0.002') * (Z - Decimal('2')) / Decimal('98')
return Z - screening
def relativistic_gamma_decimal(Z, alpha, c, n=1):
"""Calculate relativistic correction factor using external alpha and c"""
Z = Decimal(str(Z))
n = Decimal(str(n))
# Electron velocity as fraction of light speed
v_over_c = Z * alpha / n
if v_over_c < Decimal('0.1'):
# Taylor expansion for better numerical precision
v2 = v_over_c * v_over_c
gamma = Decimal('1') + v2 / Decimal('2') + Decimal('3') * v2 * v2 / Decimal('8')
else:
# Full relativistic formula
one = Decimal('1')
gamma = one / (one - v_over_c * v_over_c).sqrt()
# QED corrections for heavy elements (Z > 70)
if Z > 70:
alpha_sq = alpha * alpha
z_ratio_sq = (Z / Decimal('137')) * (Z / Decimal('137'))
qed_correction = Decimal('1') + alpha_sq * z_ratio_sq / Decimal('8')
gamma = gamma * qed_correction
return gamma
# Legacy function retained for comparison (uses hardcoded values)
def slater_z_eff(Z):
"""
NOTE: This function is retained only for comparison with literature
The main verification uses slater_z_eff_decimal() with external constants
"""
"""
Verify the fundamental identity: F = ℏ²/(γmr³) = ke²/r²
Returns:
dict: Results including forces, ratio, and systematic deviation
"""
const = AuthoritativeConstants()
# Calculate atomic parameters
Z_eff = slater_z_eff(Z)
r = const.a0 / Z_eff # 1s orbital radius
gamma = relativistic_gamma(Z, n=1)
# Geometric force: F = ℏ²/(γmr³)
F_geometric = const.hbar * const.hbar / (gamma * const.m_e * r * r * r)
# Coulomb force: F = kZ_eff⋅e²/(γr²)
F_coulomb = const.k * Z_eff * const.e * const.e / (gamma * r * r)
# Mathematical ratio
ratio = F_geometric / F_coulomb
deviation_ppb = abs(Decimal('1') - ratio) * Decimal('1e9')
if verbose:
print(f"\n{element_name} (Z = {Z})")
print(f" Z_eff = {float(Z_eff):.6f}")
print(f" r = {float(r)*1e12:.3f} pm")
print(f" gamma = {float(gamma):.6f}")
if float(gamma) > 1.001:
v_c = float(Z * const.alpha)
print(f" v/c ≈ {v_c:.3f} (relativistic!)")
print(f" F_geometric = {float(F_geometric):.6e} N")
print(f" F_coulomb = {float(F_coulomb):.6e} N")
print(f" Ratio = {float(ratio):.15f}")
print(f" Deviation = {float(deviation_ppb):.6f} ppb")
return {
'Z': Z,
'element': element_name,
'Z_eff': float(Z_eff),
'radius_pm': float(r * 1e12),
'gamma': float(gamma),
'F_geometric': float(F_geometric),
'F_coulomb': float(F_coulomb),
'ratio': float(ratio),
'deviation_ppb': float(deviation_ppb),
'agreement_percent': float(ratio * 100)
}
def demonstrate_systematic_deviation_with_external_constants():
"""
Demonstrate the universal systematic deviation using external constants
This replaces the old function that used hardcoded values
"""
print("\nSYSTEMATIC DEVIATION ANALYSIS (External Constants)")
print("="*60)
print("Testing representative elements for identical deviation...")
# Test elements across the periodic table
test_elements = [
(1, "Hydrogen"), (6, "Carbon"), (18, "Argon"),
(26, "Iron"), (47, "Silver"), (79, "Gold"), (92, "Uranium")
]
deviations = []
print(f"{'Element':>10} {'Z':>3} {'γ':>8} {'Ratio':>18} {'Dev (ppb)':>12}")
print("-" * 70)
for Z, name in test_elements:
result = verify_element_with_external_constants(Z, name)
if result:
deviations.append(result['deviation_ppb'])
print(f"{name:>10} {Z:>3} {result['gamma']:>8.4f} "
f"{result['ratio']:>18.12f} {result['deviation_ppb']:>12.6f}")
else:
print(f"{name:>10} {Z:>3} {'ERROR':>8} {'N/A':>18} {'N/A':>12}")
if deviations:
# Statistical analysis
mean_dev = sum(deviations) / len(deviations)
print("-" * 70)
print(f"Mean deviation: {mean_dev:.6f} ppb")
print(f"Range: {min(deviations):.6f} to {max(deviations):.6f} ppb")
# Check if all deviations are identical (within numerical precision)
identical_count = len(set(f"{d:.6f}" for d in deviations))
if identical_count == 1:
print(f"\n✓ IDENTICAL SYSTEMATIC DEVIATION CONFIRMED!")
print(f" Every element shows exactly {mean_dev:.3f} ppb deviation")
print(f" This proves the mathematical identity is exact!")
print(f" Deviation comes from measurement uncertainty, not physics!")
else:
print(f"\n⚠ Found {identical_count} different deviation values")
print(f" This might indicate calculation precision issues")
return mean_dev
else:
print("\n❌ No successful calculations with external constants")
return None
def demonstrate_unit_consistency():
"""
Prove both force expressions yield identical units (Newtons)
"""
print("\nUNIT VERIFICATION")
print("="*30)
print("Geometric force: F = ℏ²/(γmr³)")
print(" [ℏ²/(γmr³)] = [J²⋅s²]/([1][kg][m³])")
print(" = [kg²⋅m⁴⋅s⁻²]/[kg⋅m³]")
print(" = [kg⋅m⋅s⁻