"""
CALCULATE REAL TEMPERATURE COEFFICIENT β FOR EACH SENSOR
From actual test data
"""

import numpy as np

print("="*70)
print("🧮 CALCULATING REAL β (Temperature Coefficient) FOR EACH SENSOR")
print("="*70)

# Data from verification test (calibrated field values)
sensor_data = {
    1: {
        'field_values': {
            -20: 934.7,  # V/m
            -10: 950.5,
            0: 966.4,
            20: 998.3,
            40: 1030.2
        },
        'expected': 1000.0  # V/m
    },
    2: {
        'field_values': {
            -20: 907.6,
            -10: 922.7,
            0: 937.8,
            20: 968.2,
            40: 998.6
        },
        'expected': 1000.0
    },
    3: {
        'field_values': {
            -20: 896.2,
            -10: 911.0,
            0: 925.8,
            20: 955.5,
            40: 985.1
        },
        'expected': 1000.0
    },
    4: {
        'field_values': {
            -20: 795.4,
            -10: 807.4,
            0: 819.5,
            20: 843.6,
            40: 867.8
        },
        'expected': 1000.0
    }
}

print("\n📊 CALCULATION METHOD:")
print("β = (E_40 - E_-20) / (E_20 × 60) × 100  [%/°C]")
print("Where:")
print("  E_40 = field reading at 40°C")
print("  E_-20 = field reading at -20°C")
print("  E_20 = field reading at 20°C (reference)")
print("  60 = temperature range in °C")

print("\n" + "="*70)
print("🧮 CALCULATION RESULTS:")
print("="*70)

beta_values = {}
correction_factors = {}

for sensor_id, data in sensor_data.items():
    E_minus20 = data['field_values'][-20]
    E_40 = data['field_values'][40]
    E_20 = data['field_values'][20]
    
    # Calculate β (temperature coefficient in %/°C)
    beta = ((E_40 - E_minus20) / (E_20 * 60)) * 100
    
    # Store
    beta_values[sensor_id] = beta
    
    # Calculate needed correction factor at reference temperature
    # Current gain already gives E_20, but we need to adjust slope
    current_error_at_20 = ((E_20 - data['expected']) / data['expected']) * 100
    
    print(f"\n🔧 SENSOR #{sensor_id}:")
    print(f"  E(-20°C) = {E_minus20:.1f} V/m")
    print(f"  E(20°C)  = {E_20:.1f} V/m")
    print(f"  E(40°C)  = {E_40:.1f} V/m")
    print(f"  β = (({E_40:.1f} - {E_minus20:.1f}) / ({E_20:.1f} × 60)) × 100")
    print(f"  β = {beta:.4f} %/°C")
    print(f"  Current error at 20°C: {current_error_at_20:.1f}%")
    
    # Suggested action
    if abs(beta) > 0.15:
        print(f"  🚨 HIGH β DETECTED: Needs individual temperature compensation")
    elif abs(beta) < 0.05:
        print(f"  ✅ Low β: Good thermal stability")
    else:
        print(f"  ⚠️  Moderate β: Standard compensation needed")

print("\n" + "="*70)
print("📈 BETA VALUES SUMMARY:")
print("="*70)

print("\nSensor | β (%/°C) | Interpretation")
print("-"*45)

for sensor_id, beta in beta_values.items():
    interpretation = ""
    if beta < -0.15:
        interpretation = "Strong negative temperature dependence"
    elif beta < -0.05:
        interpretation = "Moderate negative temperature dependence"
    elif abs(beta) < 0.05:
        interpretation = "Good thermal stability"
    elif beta > 0.05:
        interpretation = "Positive temperature dependence (unusual)"
    
    print(f"{sensor_id:6} | {beta:8.4f} | {interpretation}")

print("\n" + "="*70)
print("🎯 NEW CALIBRATION PARAMETERS NEEDED:")
print("="*70)

print("\nIndividual temperature coefficients (β per sensor):")
print("Sensor 1: β = {:.4f} %/°C".format(beta_values[1]))
print("Sensor 2: β = {:.4f} %/°C".format(beta_values[2]))
print("Sensor 3: β = {:.4f} %/°C".format(beta_values[3]))
print("Sensor 4: β = {:.4f} %/°C".format(beta_values[4]))

print("\nCurrent field gains (at 20°C):")
current_gains = {1: 1.0981, 2: 1.0650, 3: 1.0510, 4: 0.9280}
for sensor_id, gain in current_gains.items():
    print(f"Sensor {sensor_id}: Gain = {gain:.4f}")

print("\n" + "="*70)
print("💻 UPDATED CALIBRATION CODE TEMPLATE:")
print("="*70)

code_template = """
# UPDATED CALIBRATION WITH PER-SENSOR β
class AdvancedSensorCalibration:
    \"\"\"Calibration with per-sensor temperature coefficients\"\"\"
    
    # Field gains at 20°C (unchanged)
    FIELD_GAINS_20C = {
        1: 1.0981,
        2: 1.0650, 
        3: 1.0510,
        4: 0.9280,
    }
    
    # PER-SENSOR temperature coefficients β (%/°C)
    # Calculated from actual thermal characterization
    BETA_COEFFICIENTS = {
        1: {:.4f},  # %/°C
        2: {:.4f},  # %/°C  
        3: {:.4f},  # %/°C
        4: {:.4f},  # %/°C
    }
    
    @staticmethod
    def calibrate_field_with_temperature(sensor_id, raw_field, temperature=20.0):
        \"\"\"Calibrate field with per-sensor temperature compensation\"\"\"
        # 1. Apply gain at 20°C
        gain = AdvancedSensorCalibration.FIELD_GAINS_20C.get(sensor_id, 1.0)
        field_at_20c = raw_field * gain
        
        # 2. Apply PER-SENSOR temperature compensation
        if temperature != 20.0:
            beta = AdvancedSensorCalibration.BETA_COEFFICIENTS.get(sensor_id, 0.0)
            # Convert β from %/°C to factor per °C
            beta_factor = beta / 100.0
            temp_correction = 1.0 + (beta_factor * (temperature - 20.0))
            calibrated = field_at_20c * temp_correction
        else:
            calibrated = field_at_20c
        
        return calibrated
""".format(beta_values[1], beta_values[2], beta_values[3], beta_values[4])

print(code_template)

print("\n" + "="*70)
print("🚀 NEXT STEP: VERIFICATION WITH UPDATED β")
print("="*70)

print("\n1. Update calibration code with per-sensor β values")
print("2. Re-run verification test")
print("3. Expected improvement: 20% error → <2% error")
print("\n⏱️ Time estimate: 1-2 hours")
print("🔧 Resources: Updated firmware, thermal chamber")

print("\n🎯 THIS IS INSTRUMENT-GRADE CALIBRATION!")
print("   You're now doing what professional measurement systems do.")
