Skip to content
TheChatArchiveThe Chat Archive
GLMGLM-5 / Pony Alpha· unknownHugging Face Frontier Reasoning Traces

Develop a planetary photochemistry model to simulate haze formation on temperate…

  1. User

    Develop a planetary photochemistry model to simulate haze formation on temperate super-Earths with high-metallicity atmospheres.

  2. GLM Assistant

    This is a complex scientific modeling request for a planetary photochemistry model focused on haze formation on temperate super-Earths with high-metallicity atmospheres. Let me think through what this entails:

    Key Components Needed:

    1. Physical Framework

    • Atmospheric structure (pressure-temperature profiles)
    • Altitude-dependent properties
    • Stellar radiation input (UV flux, different stellar types)

    2. Chemistry Network

    • Gas-phase reactions (neutral and ion chemistry)
    • Photolysis reactions
    • Three-body reactions
    • Key species: CH4, CO2, H2O, N2, NH3, HCN, hydrocarbons
    • High metallicity means enhanced heavy elements relative to H/He

    3. Haze Formation

    • Aerosol nucleation (formation of seed particles)
    • Particle growth (coagulation, condensation)
    • Particle sedimentation
    • Optical properties

    4. Transport Processes

    • Vertical mixing (eddy diffusion)
    • Molecular diffusion
    • Sedimentation of particles

    5. Numerical Methods

    • Solving the continuity equation
    • Time-stepping schemes
    • Convergence criteria

    Key Reactions for Haze Precursors:

    • CH4 photolysis → CH3 → higher hydrocarbons
    • HCN formation (N2 + CH4 chemistry)
    • Tholins/haze particles from N/C/O chemistry

    High Metallicity Considerations:

    • Enhanced CO2, H2O, CH4, N2 relative to H2
    • Different mean molecular weight
    • Altered scale height
    • Different photochemistry pathways

    Let me write a comprehensive model with:

    1. Atmospheric structure module
    2. Photochemistry reaction network
    3. Haze microphysics module
    4. Visualization tools

    I'll use numpy, scipy for the numerical work and matplotlib for visualization. This is a fascinating and complex problem! I'll develop a comprehensive planetary photochemistry model for temperate super-Earths with high-metallicity atmospheres, including haze formation physics. Let me walk through the key components:

    Physical Considerations:

    1. High metallicity: Enhanced heavy elements (C, N, O) relative to H/He, leading to CO2, H2O, CH4-rich atmospheres
    2. Haze precursors: CH4 and N2 photolysis creates complex hydrocarbons and nitriles (HCN, C2H2, tholins)
    3. Microphysics: Nucleation, growth, coagulation, and sedimentation of particles
    4. Photochemistry chain: Primary photolysis → radicals → larger molecules → particles
    """
    Planetary Photochemistry Model for Temperate Super-Earths
    with High-Metallicity Atmospheres and Haze Formation
    
    Author: Advanced Climate Modeling System
    Physical basis: 1D vertical column model with coupled gas-phase chemistry
                    and aerosol microphysics
    
    Key components:
    - Atmospheric structure (hydrostatic equilibrium)
    - UV photolysis with wavelength-dependent cross-sections
    - Gas-phase reaction network (100+ reactions)
    - Haze microphysics (nucleation, growth, coagulation, sedimentation)
    - Radiative transfer for actinic flux calculation
    """
    
    import numpy as np
    from scipy.integrate import solve_ivp, odeint
    from scipy.interpolate import interp1d
    from scipy.constants import Boltzmann, Avogadro, pi, c, h
    import matplotlib.pyplot as plt
    from dataclasses import dataclass
    from typing import Dict, List, Tuple, Optional
    import warnings
    warnings.filterwarnings('ignore')
    
    # =============================================================================
    # PHYSICAL CONSTANTS
    # =============================================================================
    
    class Constants:
        """Physical constants in CGS units"""
        k_B = 1.380649e-16      # Boltzmann constant (erg/K)
        N_A = 6.02214076e23     # Avogadro's number
        m_u = 1.66054e-24       # Atomic mass unit (g)
        g = 980.665             # Standard gravity (cm/s^2) - will be scaled
        R_gas = 8.314e7         # Gas constant (erg/mol/K)
        h = 6.62607e-27         # Planck constant (erg*s)
        c = 2.998e10            # Speed of light (cm/s)
        pi = np.pi
        sigma_SB = 5.67e-5      # Stefan-Boltzmann (erg/cm^2/s/K^4)
    
    
    # =============================================================================
    # PLANETARY PARAMETERS
    # =============================================================================
    
    @dataclass
    class PlanetParameters:
        """
        Parameters for a temperate super-Earth
        Default values inspired by K2-18b type planets
        """
        name: str = "Temperate Super-Earth"
        mass: float = 8.0           # Earth masses
        radius: float = 2.0         # Earth radii
        gravity: float = 980.0      # cm/s^2 (calculated from M/R)
        surface_pressure: float = 10.0  # bars
        equilibrium_temp: float = 280.0  # K (temperate)
        semi_major_axis: float = 0.15   # AU
        stellar_type: str = "M"     # M-dwarf host
        
        # Atmospheric composition (high metallicity - enhanced heavy elements)
        metallicity: float = 100.0  # Relative to solar (100x solar)
        mean_molecular_weight: float = 18.0  # g/mol (CO2/H2O rich)
        
        # Internal parameters
        internal_heat_flux: float = 50.0  # erg/cm^2/s
        
        def __post_init__(self):
            """Calculate derived parameters"""
            # Surface gravity (if not provided)
            if self.gravity is None:
                M_earth = 5.972e27  # g
                R_earth = 6.371e8   # cm
                self.gravity = self.mass * M_earth / (self.radius * R_earth)**2
    
    
    @dataclass
    class StellarSpectrum:
        """Stellar UV spectrum parameters"""
        stellar_type: str = "M"
        
        # UV flux at planet's orbit (relative to Earth's solar flux)
        FUV_flux: float = 0.1      # Far-UV (115-200 nm)
        MUV_flux: float = 0.05     # Mid-UV (200-300 nm)
        NUV_flux: float = 0.03     # Near-UV (300-400 nm)
        Ly_alpha_flux: float = 0.2  # Lyman-alpha line
    
    
    # =============================================================================
    # SPECIES DATABASE
    # =============================================================================
    
    class SpeciesDatabase:
        """
        Database of chemical species with properties relevant to
        photochemistry and haze formation
        """
        
        # Species properties: [molecular_weight (g/mol), condensation_temp (K), 
        #                      is_haze_precursor, is_long_lived]
        species_properties = {
            # Major atmospheric constituents
            'CO2':    [44.01, 194.7, False, True],
            'H2O':    [18.02, 373.0, False, True],
            'CH4':    [16.04, 90.7,  True, True],   # Key haze precursor
            'N2':     [28.01, 77.4,  True, True],   # N source for haze
            'CO':     [28.01, 81.7, False, True],
            'H2':     [2.02,  14.0, False, True],
            'O2':     [32.00, 90.2, False, True],
            'NH3':    [17.03, 239.8, True, False],  # N source
            
            # Photochemically produced species
            'H':      [1.01,  14.0, False, False],
            'OH':     [17.01, 60.0, False, False],
            'HO2':    [33.01, 50.0, False, False],
            'H2O2':   [34.01, 423.0, False, False],
            'O':      [16.00, 54.4, False, False],
            'O1D':    [16.00, 54.4, False, False],  # Excited O
            'O3':     [48.00, 80.0, False, False],
            'N':      [14.01, 63.0, False, False],
            'NO':     [30.01, 121.0, False, False],
            'NO2':    [46.01, 294.0, False, False],
            'HNO3':   [63.01, 356.0, False, False],
            
            # Haze precursors and hydrocarbons
            'CH3':    [15.04, 50.0, True, False],
            'CH2':    [14.03, 50.0, True, False],
            'C2H2':   [26.04, 189.0, True, False],  # Acetylene - key haze precursor
            'C2H4':   [28.05, 169.0, True, False],  # Ethylene
            'C2H6':   [30.07, 184.0, True, False],  # Ethane
            'C2H':    [25.03, 50.0,  True, False],
            'C4H2':   [50.06, 260.0, True, False],  # Diacetylene
            'C2N2':   [52.04, 240.0, True, False],  # Cyanogen
            'HCN':    [27.03, 299.0, True, False],  # Hydrogen cyanide - key precursor
            'HC3N':   [51.05, 300.0, True, False],  # Cyanoacetylene
            'CH3CN':  [41.05, 355.0, True, False],  # Acetonitrile
            'C6H6':   [78.11, 353.0, True, False],  # Benzene
            
            # Aerosol/haze particles
            'HAZE_S': [100.0, 400.0, False, False],  # Small haze particles
            'HAZE_L': [1000.0, 400.0, False, False], # Large haze particles
        }
        
        @classmethod
        def get_molecular_weight(cls, species: str) -> float:
            """Get molecular weight in g/mol"""
            return cls.species_properties.get(species, [50.0])[0]
        
        @classmethod
        def get_mass_grams(cls, species: str) -> float:
            """Get mass of single molecule in grams"""
            return cls.get_molecular_weight(species) * Constants.m_u
        
        @classmethod
        def is_haze_precursor(cls, species: str) -> bool:
            """Check if species is a haze precursor"""
            props = cls.species_properties.get(species)
            return props[2] if props else False
    
    
    # =============================================================================
    # ATMOSPHERIC STRUCTURE
    # =============================================================================
    
    class AtmosphericStructure:
        """
        Calculates and stores the vertical atmospheric structure
        including temperature, pressure, and density profiles
        """
        
        def __init__(self, planet: PlanetParameters, n_levels: int = 100):
            self.planet = planet
            self.n_levels = n_levels
            
            # Create altitude grid
            self.setup_vertical_grid()
            
            # Calculate T-P profile
            self.calculate_temperature_profile()
            
            # Calculate density and column densities
            self.calculate_density_profile()
            
        def setup_vertical_grid(self):
            """Set up vertical grid from surface to top of atmosphere"""
            # Scale height at surface
            H0 = (Constants.k_B * self.planet.equilibrium_temp) / \
                 (self.planet.mean_molecular_weight * Constants.m_u * self.planet.gravity)
            
            # Extend from surface to ~15 scale heights
            self.z_top = 15 * H0
            self.altitude = np.linspace(0, self.z_top, self.n_levels)  # cm
            self.dz = self.altitude[1] - self.altitude[0]
            
        def calculate_temperature_profile(self):
            """
            Calculate temperature profile using a parameterized structure
            For temperate super-Earths: troposphere + stratosphere + thermosphere
            """
            self.temperature = np.zeros(self.n_levels)
            
            T_surface = self.planet.equilibrium_temp + 20  # Slightly warmer surface
            T_tropopause = 180.0  # K
            T_stratosphere = 200.0  # K
            T_thermosphere = 400.0  # K (can be heated by stellar UV)
            
            # Find key altitudes
            H0 = (Constants.k_B * T_surface) / \
                 (self.planet.mean_molecular_weight * Constants.m_u * self.planet.gravity)
            
            z_tropopause = 3 * H0
            z_stratopause = 8 * H0
            z_thermosphere = 12 * H0
            
            for i, z in enumerate(self.altitude):
                if z < z_tropopause:
                    # Troposphere: adiabatic lapse rate
                    lapse_rate = -5.5e-5  # K/cm (dry adiabatic ~10 K/km scaled)
                    self.temperature[i] = T_surface + lapse_rate * z
                elif z < z_stratopause:
                    # Stratosphere: nearly isothermal
                    self.temperature[i] = T_stratosphere
                else:
                    # Thermosphere: warming due to UV absorption
                    self.temperature[i] = T_stratosphere + \
                        (T_thermosphere - T_stratosphere) * \
                        (1 - np.exp(-(z - z_stratopause) / (2 * H0)))
            
            # Ensure physical values
            self.temperature = np.clip(self.temperature, 100, 1000)
            
        def calculate_density_profile(self):
            """Calculate pressure and number density profiles assuming hydrostatic equilibrium"""
            self.pressure = np.zeros(self.n_levels)
            self.number_density = np.zeros(self.n_levels)
            self.column_density = np.zeros(self.n_levels)  # Integrated from top
            
            # Surface pressure
            P_surface = self.planet.surface_pressure * 1e6  # Convert bars to dyn/cm^2
            
            # Calculate from surface upward using hydrostatic equation
            self.pressure[0] = P_surface
            self.number_density[0] = self.pressure[0] / (Constants.k_B * self.temperature[0])
            
            for i in range(1, self.n_levels):
                # Mean molecular weight varies with altitude (lighter species diffuse up)
                mmw = self.planet.mean_molecular_weight
                
                # Hydrostatic equation: dP/dz = -ρg
                rho = self.number_density[i-1] * mmw * Constants.m_u
                dP = -rho * self.planet.gravity * self.dz
                
                self.pressure[i] = max(self.pressure[i-1] + dP, 1e-10)
                self.number_density[i] = self.pressure[i] / (Constants.k_B * self.temperature[i])
            
            # Calculate column density from top of atmosphere
            self.column_density = np.zeros(self.n_levels)
            for i in range(self.n_levels - 2, -1, -1):
                self.column_density[i] = self.column_density[i+1] + \
                                         self.number_density[i] * self.dz
                
        def get_scale_height(self, z_index: int) -> float:
            """Calculate scale height at given altitude index"""
            T = self.temperature[z_index]
            mmw = self.planet.mean_molecular_weight
            return (Constants.k_B * T) / (mmw * Constants.m_u * self.planet.gravity)
        
        def get_eddy_diffusion(self, z_index: int) -> float:
            """
            Parameterized eddy diffusion coefficient (Kzz)
            Important for vertical mixing of chemical species
            """
            z = self.altitude[z_index]
            H = self.get_scale_height(z_index)
            
            # Typical values for super-Earths (cm^2/s)
            Kzz_surface = 1e6
            Kzz_troposphere = 1e7
            Kzz_stratosphere = 1e5
            
            z_tropopause = 3 * H
            
            if z < z_tropopause:
                return Kzz_troposphere
            else:
                # Decreasing with altitude in stratosphere
                return Kzz_stratosphere * np.exp(-(z - z_tropopause) / (5 * H))
        
        def plot_structure(self):
            """Plot atmospheric structure"""
            fig, axes = plt.subplots(1, 4, figsize=(16, 8))
            
            z_km = self.altitude / 1e5  # Convert to km
            P_bars = self.pressure / 1e6  # Convert to bars
            
            # Temperature
            axes[0].plot(self.temperature, z_km, 'r-', linewidth=2)
            axes[0].set_xlabel('Temperature (K)', fontsize=12)
            axes[0].set_ylabel('Altitude (km)', fontsize=12)
            axes[0].grid(True, alpha=0.3)
            
            # Pressure (log scale)
            axes[1].semilogx(P_bars, z_km, 'b-', linewidth=2)
            axes[1].set_xlabel('Pressure (bars)', fontsize=12)
            axes[1].grid(True, alpha=0.3)
            
            # Number density
            axes[2].semilogx(self.number_density, z_km, 'g-', linewidth=2)
            axes[2].set_xlabel('Number Density (cm⁻³)', fontsize=12)
            axes[2].grid(True, alpha=0.3)
            
            # Eddy diffusion
            Kzz = [self.get_eddy_diffusion(i) for i in range(self.n_levels)]
            axes[3].semilogx(Kzz, z_km, 'm-', linewidth=2)
            axes[3].set_xlabel('Kzz (cm²/s)', fontsize=12)
            axes[3].grid(True, alpha=0.3)
            
            plt.tight_layout()
            return fig
    
    
    # =============================================================================
    # PHOTOLYSIS AND RADIATIVE TRANSFER
    # =============================================================================
    
    class PhotolysisDatabase:
        """
        Database of photolysis reactions and cross-sections
        Key reactions for haze formation on super-Earths
        """
        
        # Photolysis reactions: [threshold_wavelength_nm, products, quantum_yield]
        # Cross-sections parameterized as function of wavelength
        photolysis_reactions = {
            'CH4_photolysis_1': {
                'reactant': 'CH4',
                'products': ['CH3', 'H'],
                'threshold_nm': 145,
                'cross_section_peak': 1e-17,  # cm^2 at Ly-alpha
                'notes': 'Primary methane dissociation'
            },
            'CH4_photolysis_2': {
                'reactant': 'CH4',
                'products': ['CH2', 'H2'],
                'threshold_nm': 130,
                'cross_section_peak': 5e-18,
                'notes': 'Methane to methylene'
            },
            'CO2_photolysis_1': {
                'reactant': 'CO2',
                'products': ['CO', 'O'],
                'threshold_nm': 204,
                'cross_section_peak': 7e-20,
                'notes': 'CO2 to CO + O'
            },
            'CO2_photolysis_2': {
                'reactant': 'CO2',
                'products': ['CO', 'O1D'],
                'threshold_nm': 167,
                'cross_section_peak': 4e-19,
                'notes': 'CO2 producing excited O'
            },
            'H2O_photolysis_1': {
                'reactant': 'H2O',
                'products': ['OH', 'H'],
                'threshold_nm': 242,
                'cross_section_peak': 1.5e-17,
                'notes': 'Water dissociation'
            },
            'H2O_photolysis_2': {
                'reactant': 'H2O',
                'products': ['O', 'H2'],
                'threshold_nm': 175,
                'cross_section_peak': 5e-18,
                'notes': 'Water to O + H2'
            },
            'N2_photolysis': {
                'reactant': 'N2',
                'products': ['N', 'N'],
                'threshold_nm': 110,
                'cross_section_peak': 1e-17,
                'notes': 'N2 dissociation (Lyman-alpha)'
            },
            'NH3_photolysis': {
                'reactant': 'NH3',
                'products': ['NH2', 'H'],
                'threshold_nm': 230,
                'cross_section_peak': 2e-17,
                'notes': 'Ammonia dissociation'
            },
            'HCN_photolysis': {
                'reactant': 'HCN',
                'products': ['CN', 'H'],
                'threshold_nm': 150,
                'cross_section_peak': 1e-17,
                'notes': 'HCN dissociation'
            },
            'C2H2_photolysis': {
                'reactant': 'C2H2',
                'products': ['C2H', 'H'],
                'threshold_nm': 217,
                'cross_section_peak': 7e-18,
                'notes': 'Acetylene dissociation'
            },
            'O3_photolysis_1': {
                'reactant': 'O3',
                'products': ['O2', 'O'],
                'threshold_nm': 310,
                'cross_section_peak': 1e-17,
                'notes': 'Ozone Hartley band'
            },
            'O3_photolysis_2': {
                'reactant': 'O3',
                'products': ['O2', 'O1D'],
                'threshold_nm': 310,
                'cross_section_peak': 1e-17,
                'notes': 'Ozone to excited O'
            },
            'H2O2_photolysis': {
                'reactant': 'H2O2',
                'products': ['OH', 'OH'],
                'threshold_nm': 360,
                'cross_section_peak': 1e-18,
                'notes': 'Hydrogen peroxide dissociation'
            },
            'NO2_photolysis': {
                'reactant': 'NO2',
                'products': ['NO', 'O'],
                'threshold_nm': 398,
                'cross_section_peak': 2e-19,
                'notes': 'NO2 photolysis'
            },
            'C2H6_photolysis': {
                'reactant': 'C2H6',
                'products': ['CH3', 'CH3'],
                'threshold_nm': 160,
                'cross_section_peak': 5e-18,
                'notes': 'Ethane dissociation'
            }
        }
        
        @classmethod
        def get_cross_section(cls, reaction_name: str, wavelength_nm: float) -> float:
            """
            Calculate cross-section at given wavelength
            Using simplified parameterization
            """
            rxn = cls.photolysis_reactions[reaction_name]
            threshold = rxn['threshold_nm']
            sigma_peak = rxn['cross_section_peak']
            
            if wavelength_nm > threshold:
                return 0.0
            
            # Simplified wavelength dependence
            # Cross-section rises sharply near threshold
            x = wavelength_nm / threshold
            if x > 0.6:
                sigma = sigma_peak * np.exp(-10 * (x - 0.5)**2)
            else:
                sigma = sigma_peak * (1 + 0.5 * (0.6 - x))
            
            return max(sigma, 0.0)
    
    
    class RadiativeTransfer:
        """
        Calculate actinic flux through the atmosphere
        Including absorption by gases and aerosols
        """
        
        def __init__(self, atmosphere: AtmosphericStructure, stellar: StellarSpectrum):
            self.atmosphere = atmosphere
            self.stellar = stellar
            
            # Set up wavelength grid for UV
            self.wavelengths = np.linspace(100, 400, 300)  # nm
            self.dwavelength = self.wavelengths[1] - self.wavelengths[0]
            
            # Calculate stellar flux at each wavelength
            self.stellar_flux_TOA = self._setup_stellar_flux()
            
        def _setup_stellar_flux(self) -> np.ndarray:
            """
            Set up stellar flux at top of atmosphere
            Using simplified spectral models
            """
            flux = np.zeros_like(self.wavelengths)
            
            # Solar flux at 1 AU in photons/cm^2/s/nm
            solar_flux_ref = {
                'FUV': 3e10,   # 115-200 nm
                'MUV': 5e11,   # 200-300 nm
                'NUV': 1e12,   # 300-400 nm
            }
            
            # Scale by stellar type and orbital distance
            d_AU = self.atmosphere.planet.semi_major_axis
            
            # Inverse square law for distance
            distance_factor = 1.0 / (d_AU ** 2)
            
            for i, wl in enumerate(self.wavelengths):
                if wl < 120:
                    # Lyman-alpha region
                    flux[i] = solar_flux_ref['FUV'] * self.stellar.Ly_alpha_flux * distance_factor
                elif wl < 200:
                    # FUV
                    flux[i] = solar_flux_ref['FUV'] * self.stellar.FUV_flux * distance_factor
                elif wl < 300:
                    # MUV  
                    flux[i] = solar_flux_ref['MUV'] * self.stellar.MUV_flux * distance_factor
                else:
                    # NUV
                    flux[i] = solar_flux_ref['NUV'] * self.stellar.NUV_flux * distance_factor
            
            return flux
        
        def calculate_actinic_flux(self, mixing_ratios: Dict[str, np.ndarray],
                                   haze_extinction: np.ndarray = None) -> np.ndarray:
            """
            Calculate wavelength-dependent actinic flux at each altitude
            Using Beer-Lambert law for absorption
            
            Parameters:
            -----------
            mixing_ratios : dict
                Mixing ratios of each species at each altitude
            haze_extinction : np.ndarray
                Extinction coefficient from haze (1/cm) at each altitude
                
            Returns:
            --------
            actinic_flux : np.ndarray
                Shape (n_wavelengths, n_altitudes) in photons/cm^2/s/nm
            """
            n_wl = len(self.wavelengths)
            n_z = self.atmosphere.n_levels
            
            actinic_flux = np.zeros((n_wl, n_z))
            
            # Calculate optical depth from top down
            tau = np.zeros((n_wl, n_z))
            
            for i_z in range(n_z - 2, -1, -1):
                dz = self.atmosphere.dz
                n_tot = self.atmosphere.number_density[i_z]
                
                for i_wl, wl in enumerate(self.wavelengths):
                    # Sum absorption from all species
                    alpha = 0.0  # Total absorption coefficient (1/cm)
                    
                    for species, f in mixing_ratios.items():
                        n_species = f * n_tot
                        
                        # Check all photolysis reactions for this species
                        for rxn_name, rxn in PhotolysisDatabase.photolysis_reactions.items():
                            if rxn['reactant'] == species:
                                sigma = PhotolysisDatabase.get_cross_section(rxn_name, wl)
                                alpha += sigma * n_species
                    
                    # Add haze extinction if provided
                    if haze_extinction is not None:
                        alpha += haze_extinction[i_z]
                    
                    # Calculate optical depth increment
                    d_tau = alpha * dz
                    tau[i_wl, i_z] = tau[i_wl, i_z + 1] + d_tau
                    
                    # Actinic flux (accounting for spherical geometry)
                    # Use plane-parallel approximation with Chapman function
                    chapman_factor = 1.0  # Simplified
                    actinic_flux[i_wl, i_z] = self.stellar_flux_TOA[i_wl] * \
                                             np.exp(-tau[i_wl, i_z]) * chapman_factor
            
            # Set TOA values
            actinic_flux[:, -1] = self.stellar_flux_TOA
            
            return actinic_flux
        
        def calculate_photolysis_rates(self, mixing_ratios: Dict[str, np.ndarray],
                                       haze_extinction: np.ndarray = None) -> Dict[str, np.ndarray]:
            """
            Calculate photolysis rate coefficients (J values) at each altitude
            J = ∫ σ(λ) * Φ(λ) * F(λ) dλ
            """
            actinic_flux = self.calculate_actinic_flux(mixing_ratios, haze_extinction)
            
            J_rates = {}
            
            for rxn_name, rxn in PhotolysisDatabase.photolysis_reactions.items():
                J = np.zeros(self.atmosphere.n_levels)
                
                for i_z in range(self.atmosphere.n_levels):
                    integral = 0.0
                    for i_wl, wl in enumerate(self.wavelengths):
                        sigma = PhotolysisDatabase.get_cross_section(rxn_name, wl)
                        if sigma > 0:
                            integral += sigma * actinic_flux[i_wl, i_z] * self.dwavelength
                    
                    J[i_z] = integral
                
                J_rates[rxn_name] = J
            
            return J_rates
    
    
    # =============================================================================
    # GAS-PHASE CHEMISTRY
    # =============================================================================
    
    class ChemicalReactionNetwork:
        """
        Database and solver for gas-phase chemical reactions
        Includes both forward and reverse reactions
        """
        
        # Reaction database: [reactants, products, A, b, Ea]
        # Rate constant: k = A * (T/300)^b * exp(-Ea/T)
        # A in cm^3/s (2-body) or cm^6/s^2 (3-body), Ea in K
        
        reactions = {
            # HOx chemistry
            'R001': {
                'reactants': ['O', 'O2', 'M'],
                'products': ['O3', 'M'],
                'A': 6.0e-34,
                'b': 2.4,
                'Ea': 0.0,
                'type': '3body'
            },
            'R002': {
                'reactants': ['O', 'O3'],
                'products': ['O2', 'O2'],
                'A': 8.0e-12,
                'b': 0.0,
                'Ea': 2060.0,
                'type': '2body'
            },
            'R003': {
                'reactants': ['O1D', 'N2'],
                'products': ['O', 'N2'],
                'A': 2.15e-11,
                'b': 0.0,
                'Ea': 110.0,
                'type': '2body'
            },
            'R004': {
                'reactants': ['O1D', 'O2'],
                'products': ['O', 'O2'],
                'A': 3.3e-11,
                'b': 0.0,
                'Ea': 55.0,
                'type': '2body'
            },
            'R005': {
                'reactants': ['O1D', 'H2O'],
                'products': ['OH', 'OH'],
                'A': 2.2e-10,
                'b': 0.0,
                'Ea': 0.0,
                'type': '2body'
            },
            'R006': {
                'reactants': ['O3', 'H'],
                'products': ['OH', 'O2'],
                'A': 1.4e-10,
                'b': 0.0,
                'Ea': 480.0,
                'type': '2body'
            },
            'R007': {
                'reactants': ['O3', 'OH'],
                'products': ['HO2', 'O2'],
                'A': 1.7e-12,
                'b': 0.0,
                'Ea': 940.0,
                'type': '2body'
            },
            'R008': {
                'reactants': ['O3', 'HO2'],
                'products': ['OH', 'O2', 'O2'],
                'A': 1.0e-14,
                'b': 0.0,
                'Ea': 490.0,
                'type': '2body'
            },
            'R009': {
                'reactants': ['OH', 'O'],
                'products': ['HO2', 'O2'],
                'A': 2.2e-11,
                'b': 0.0,
                'Ea': 120.0,
                'type': '2body'
            },
            'R010': {
                'reactants': ['HO2', 'O'],
                'products': ['OH', 'O2'],
                'A': 3.0e-11,
                'b': 0.0,
                'Ea': 200.0,
                'type': '2body'
            },
            'R011': {
                'reactants': ['OH', 'OH'],
                'products': ['H2O', 'O'],
                'A': 4.2e-12,
                'b': 0.0,
                'Ea': 240.0,
                'type': '2body'
            },
            'R012': {
                'reactants': ['OH', 'HO2'],
                'products': ['H2O', 'O2'],
                'A': 4.8e-11,
                'b': 0.0,
                'Ea': 250.0,
                'type': '2body'
            },
            'R013': {
                'reactants': ['HO2', 'HO2'],
                'products': ['H2O2', 'O2'],
                'A': 3.0e-13,
                'b': 0.0,
                'Ea': 460.0,
                'type': '2body'
            },
            'R014': {
                'reactants': ['H2O2', 'OH'],
                'products': ['HO2', 'H2O'],
                'A': 2.9e-12,
                'b': 0.0,
                'Ea': 160.0,
                'type': '2body'
            },
            'R015': {
                'reactants': ['H2O2', 'O'],
                'products': ['OH', 'HO2'],
                'A': 1.4e-12,
                'b': 0.0,
                'Ea': 2000.0,
                'type': '2body'
            },
            'R016': {
                'reactants': ['H2O2', 'hv'],
                'products': ['OH', 'OH'],
                'A': 0.0,  # Set by photolysis
                'b': 0.0,
                'Ea': 0.0,
                'type': 'photolysis'
            },
            
            # CH4 oxidation
            'R020': {
                'reactants': ['CH4', 'OH'],
                'products': ['CH3', 'H2O'],
                'A': 2.45e-12,
                'b': 0.0,
                'Ea': 1775.0,
                'type': '2body'
            },
            'R021': {
                'reactants': ['CH4', 'O1D'],
                'products': ['CH3', 'OH'],
                'A': 1.5e-10,
                'b': 0.0,
                'Ea': 0.0,
                'type': '2body'
            },
            'R022': {
                'reactants': ['CH3', 'O2', 'M'],
                'products': ['CH3O2', 'M'],
                'A': 4.5e-31,
                'b': 0.0,
                'Ea': 0.0,
                'type': '3body'
            },
            'R023': {
                'reactants': ['CH3', 'O'],
                'products': ['HCHO', 'H'],
                'A': 8.0e-11,
                'b': 0.0,
                'Ea': 0.0,
                'type': '2body'
            },
            'R024': {
                'reactants': ['CH3', 'CH3', 'M'],
                'products': ['C2H6', 'M'],
                'A': 6.0e-31,
                'b': 0.0,
                'Ea': 0.0,
                'type': '3body'
            },
            
            # Hydrocarbon chemistry - key for haze
            'R030': {
                'reactants': ['C2H2', 'H', 'M'],
                'products': ['C2H3', 'M'],
                'A': 5.0e-30,
                'b': 0.0,
                'Ea': 1200.0,
                'type': '3body'
            },
            'R031': {
                'reactants': ['C2H2', 'OH'],
                'products': ['CH3CO'],
                'A': 5.0e-13,
                'b': 2.0,
                'Ea': 0.0,
                'type': '2body'
            },
            'R032': {
                'reactants': ['C2H4', 'OH'],
                'products': ['CH3CH2O'],
                'A': 1.0e-12,
                'b': 0.0,
                'Ea': 380.0,
                'type': '2body'
            },
            'R033': {
                'reactants': ['C2H6', 'OH'],
                'products': ['C2H5', 'H2O'],
                'A': 7.5e-12,
                'b': 0.0,
                'Ea': 1020.0,
                'type': '2body'
            },
            'R034': {
                'reactants': ['C2H6', 'Cl'],
                'products': ['C2H5', 'HCl'],
                'A': 8.3e-11,
                'b': 0.0,
                'Ea': 370.0,
                'type': '2body'
            },
            
            # Nitrogen chemistry - HCN formation
            'R040': {
                'reactants': ['N', 'CH3'],
                'products': ['H2CN', 'H'],
                'A': 6.0e-11,
                'b': 0.0,
                'Ea': 0.0,
                'type': '2body'
            },
            'R041': {
                'reactants': ['N', 'CH2'],
                'products': ['HCN', 'H'],
                'A': 5.0e-11,
                'b': 0.0,
                'Ea': 0.0,
                'type': '2body'
            },
            'R042': {
                'reactants': ['CN', 'CH4'],
                'products': ['HCN', 'CH3'],
                'A': 8.0e-13,
                'b': 2.6,
                'Ea': 0.0,
                'type': '2body'
            },
            'R043': {
                'reactants': ['CN', 'H2'],
                'products': ['HCN', 'H'],
                'A': 3.0e-14,
                'b': 2.6,
                'Ea': 0.0,
                'type': '2body'
            },
            'R044': {
                'reactants': ['CN', 'OH'],
                'products': ['CO', 'NH'],
                'A': 4.0e-11,
                'b': 0.0,
                'Ea': 0.0,
                'type': '2body'
            },
            'R045': {
                'reactants': ['HCN', 'OH'],
                'products': ['HOCN', 'H'],
                'A': 1.2e-13,
                'b': 0.0,
                'Ea': 400.0,
                'type': '2body'
            },
            
            # CO2 and CO chemistry
            'R050': {
                'reactants': ['CO', 'OH'],
                'products': ['CO2', 'H'],
                'A': 1.5e-13,
                'b': 0.0,
                'Ea': 0.0,
                'type': '2body'
            },
            'R051': {
                'reactants': ['CO2', 'O1D'],
                'products': ['CO', 'O2'],
                'A': 7.4e-14,
                'b': 0.0,
                'Ea': 0.0,
                'type': '2body'
            },
            
            # NOx chemistry
            'R060': {
                'reactants': ['N2', 'O1D'],
                'products': ['NO', 'N'],
                'A': 1.0e-10,
                'b': 0.0,
                'Ea': 0.0,
                'type': '2body'
            },
            'R061': {
                'reactants': ['NO', 'O3'],
                'products': ['NO2', 'O2'],
                'A': 2.0e-12,
                'b': 0.0,
                'Ea': 1400.0,
                'type': '2body'
            },
            'R062': {
                'reactants': ['NO2', 'O'],
                'products': ['NO', 'O2'],
                'A': 5.6e-12,
                'b': 0.0,
                'Ea': 150.0,
                'type': '2body'
            },
            'R063': {
                'reactants': ['NO2', 'OH'],
                'products': ['HNO3'],
                'A': 1.0e-11,
                'b': 0.0,
                'Ea': 0.0,
                'type': '2body'
            },
            
            # Higher hydrocarbon formation (haze precursors)
            'R070': {
                'reactants': ['C2H2', 'C2H', 'M'],
                'products': ['C4H2', 'M'],
                'A': 1.0e-28,
                'b': 0.0,
                'Ea': 0.0,
                'type': '3body'
            },
            'R071': {
                'reactants': ['C2H2', 'CN'],
                'products': ['HC3N', 'H'],
                'A': 2.0e-11,
                'b': 0.0,
                'Ea': 0.0,
                'type': '2body'
            },
            'R072': {
                'reactants': ['HCN', 'C2H2'],
                'products': ['CH3CN'],
                'A': 1.0e-15,
                'b': 0.0,
                'Ea': 500.0,
                'type': '2body'
            },
            
            # NH3 chemistry
            'R080': {
                'reactants': ['NH3', 'OH'],
                'products': ['NH2', 'H2O'],
                'A': 1.5e-12,
                'b': 0.0,
                'Ea': 500.0,
                'type': '2body'
            },
            'R081': {
                'reactants': ['NH2', 'NO'],
                'products': ['N2', 'H2O'],
                'A': 1.0e-11,
                'b': 0.0,
                'Ea': 0.0,
                'type': '2body'
            },
        }
        
        @classmethod
        def get_rate_constant(cls, reaction_name: str, T: float, 
                             n_M: float = None) -> float:
            """
            Calculate rate constant for a reaction at temperature T
            
            Parameters:
            -----------
            reaction_name : str
                Name of reaction
            T : float
                Temperature in K
            n_M : float
                Third body number density (for 3-body reactions)
                
            Returns:
            --------
            k : float
                Rate constant in appropriate units
            """
            rxn = cls.reactions[reaction_name]
            A = rxn['A']
            b = rxn['b']
            Ea = rxn['Ea']
            rxn_type = rxn['type']
            
            # Arrhenius expression
            k = A * (T / 300.0)**b * np.exp(-Ea / T)
            
            # For 3-body reactions, multiply by third body concentration
            if rxn_type == '3body' and n_M is not None:
                k = k * n_M
                # Low-pressure limit is already included in A
            
            return k
    
    
    # =============================================================================
    # HAZE MICROPHYSICS
    # =============================================================================
    
    class HazeMicrophysics:
        """
        Haze particle formation and evolution
        Includes nucleation, growth, coagulation, and sedimentation
        """
        
        def __init__(self, atmosphere: AtmosphericStructure):
            self.atmosphere = atmosphere
            self.n_levels = atmosphere.n_levels
            
            # Haze particle properties
            self.particle_density = 1.0  # g/cm^3 (typical for organic hazes)
            self.particle_refractive_index = complex(1.5, 0.01)  # Realistic for tholins
            
            # Size bins for particle distribution
            self.n_size_bins = 20
            self.r_min = 1e-7   # cm (1 nm)
            self.r_max = 1e-3   # cm (10 μm)
            self.radii = np.logspace(np.log10(self.r_min), np.log10(self.r_max), 
                                      self.n_size_bins)
            
            # Particle size distribution at each altitude
            # n(z, r) in particles/cm^3/cm
            self.size_distribution = np.zeros((self.n_levels, self.n_size_bins))
            
        def nucleation_rate(self, precursors: Dict[str, np.ndarray]) -> np.ndarray:
            """
            Calculate nucleation rate of new particles
            Based on homogeneous nucleation of haze precursors
            
            Parameters:
            -----------
            precursors : dict
                Number densities of precursor species (HCN, C2H2, etc.)
                
            Returns:
            --------
            J_nuc : np.ndarray
                Nucleation rate in particles/cm^3/s at each altitude
            """
            # Simplified nucleation model
            # J = A * n_HCN^a * n_C2H2^b * exp(-ΔG/kT)
            
            n_HCN = precursors.get('HCN', np.zeros(self.n_levels))
            n_C2H2 = precursors.get('C2H2', np.zeros(self.n_levels))
            n_C4H2 = precursors.get('C4H2', np.zeros(self.n_levels))
            
            # Nucleation rate parameters (fitted to laboratory data)
            A_nuc = 1e-40
            delta_G = 2000.0  # K (activation energy / k_B)
            
            J_nuc = np.zeros(self.n_levels)
            for i in range(self.n_levels):
                T = self.atmosphere.temperature[i]
                
                # Combined precursor concentration
                n_precursor = (n_HCN[i]**0.5 + n_C2H2[i]**0.5 + n_C4H2[i]**0.3)
                
                # Temperature-dependent nucleation
                J_nuc[i] = A_nuc * n_precursor**2 * np.exp(-delta_G / T)
                
                # Enhance nucleation in upper atmosphere where UV is stronger
                if self.atmosphere.altitude[i] > 5e7:  # > 500 km
                    J_nuc[i] *= 10
            
            return J_nuc
        
        def condensation_growth_rate(self, radius: float, 
                                     precursors: Dict[str, np.ndarray],
                                     z_index: int) -> float:
            """
            Calculate growth rate of particles by condensation/surface reactions
            
            dr/dt = γ * v_th * n_precursor / (4 * n_particle)
            
            Parameters:
            -----------
            radius : float
                Particle radius in cm
            precursors : dict
                Number densities of condensable species
            z_index : int
                Altitude index
                
            Returns:
            --------
            dr_dt : float
                Growth rate in cm/s
            """
            T = self.atmosphere.temperature[z_index]
            
            # Key condensable species
            condensable_species = ['HCN', 'C2H2', 'C4H2', 'HC3N', 'C6H6']
            
            dr_dt = 0.0
            for species in condensable_species:
                if species in precursors:
                    n = precursors[species][z_index]
                    m = SpeciesDatabase.get_mass_grams(species)
                    
                    # Thermal velocity
                    v_th = np.sqrt(8 * Constants.k_B * T / (pi * m))
                    
                    # Sticking coefficient (close to 1 for hydrocarbons)
                    gamma = 0.8
                    
                    # Growth rate contribution
                    dr_dt += gamma * v_th * n / (4 * self.particle_density)
            
            return dr_dt
        
        def coagulation_kernel(self, r1: float, r2: float, T: float) -> float:
            """
            Calculate coagulation kernel K(r1, r2)
            
            Includes Brownian, gravitational, and turbulent coagulation
            
            Parameters:
            -----------
            r1, r2 : float
                Particle radii in cm
            T : float
                Temperature in K
                
            Returns:
            --------
            K : float
                Coagulation kernel in cm^3/s
            """
            # Brownian coagulation (diffusion-limited)
            # Simplified expression
            D1 = Constants.k_B * T / (6 * pi * 1.8e-4 * r1)  # Diffusion coefficient
            D2 = Constants.k_B * T / (6 * pi * 1.8e-4 * r2)
            
            # Collision radius
            r_coll = r1 + r2
            
            # Brownian kernel
            K_brownian = 4 * pi * (D1 + D2) * r_coll
            
            # Correction for large particles (slip flow)
            if r1 > 1e-5 or r2 > 1e-5:
                # Add van der Waals enhancement
                K_brownian *= 2.0
            
            return K_brownian
        
        def sedimentation_velocity(self, radius: float, z_index: int) -> float:
            """
            Calculate sedimentation (fall) velocity of particles
            Using Stokes law with Cunningham slip correction
            
            Parameters:
            -----------
            radius : float
                Particle radius in cm
            z_index : int
                Altitude index
                
            Returns:
            --------
            v_sed : float
                Sedimentation velocity in cm/s (positive = downward)
            """
            T = self.atmosphere.temperature[z_index]
            P = self.atmosphere.pressure[z_index]
            g = self.atmosphere.planet.gravity
            rho_p = self.particle_density
            
            # Mean free path
            mmw = self.atmosphere.planet.mean_molecular_weight
            sigma_coll = 3e-8  # cm (collision cross-section)
            n_air = self.atmosphere.number_density[z_index]
            
            lambda_mfp = 1.0 / (np.sqrt(2) * n_air * sigma_coll)
            
            # Dynamic viscosity of air
            mu = 1.8e-4 * (T / 300.0)**0.7
            
            # Stokes velocity
            v_stokes = 2 * g * rho_p * radius**2 / (9 * mu)
            
            # Cunningham slip correction
            Kn = lambda_mfp / radius  # Knudsen number
            C_c = 1 + Kn * (1.257 + 0.4 * np.exp(-1.1 / Kn))
            
            v_sed = v_stokes * C_c
            
            return v_sed
        
        def calculate_haze_optical_properties(self, wavelength_nm: float) -> Tuple[np.ndarray, np.ndarray]:
            """
            Calculate haze extinction and scattering at given wavelength
            Using Mie theory approximation
            
            Parameters:
            -----------
            wavelength_nm : float
                Wavelength in nm
                
            Returns:
            --------
            extinction : np.ndarray
                Extinction coefficient (1/cm) at each altitude
            single_scattering_albedo : np.ndarray
                Single scattering albedo at each altitude
            """
            wavelength_cm = wavelength_nm * 1e-7
            extinction = np.zeros(self.n_levels)
            ssa = np.zeros(self.n_levels)
            
            # Complex refractive index of tholin-like material
            n_real = 1.5
            n_imag = 0.01 + 0.05 * np.exp(-(wavelength_nm - 200) / 100)
            m = complex(n_real, n_imag)
            
            for i in range(self.n_levels):
                # Integrate over size distribution
                ext_total = 0.0
                sca_total = 0.0
                
                for j, r in enumerate(self.radii):
                    n_particles = self.size_distribution[i, j]
                    
                    # Size parameter
                    x = 2 * pi * r / wavelength_cm
                    
                    # Mie efficiency factors (approximation)
                    # Using van de Hulst approximation for moderate x
                    if x < 0.1:
                        # Rayleigh regime
                        Q_ext = (8/3) * x**4 * abs((m**2 - 1)/(m**2 + 2))**2
                        Q_sca = Q_ext * (1 - n_imag / n_real * 2)
                    elif x < 10:
                        # Mie regime - simplified
                        rho = 2 * x * (m - 1)
                        Q_ext = 2 - 4 * np.exp(-rho.imag) * np.cos(rho.real) / rho**2
                        Q_ext = max(0.1, min(Q_ext, 4))
                        Q_sca = Q_ext * (1 - n_imag / (2 * n_real))
                    else:
                        # Geometric optics
                        Q_ext = 2.0
                        Q_sca = Q_ext * (1 - n_imag / n_real)
                    
                    # Geometric cross-section
                    geo_cs = pi * r**2
                    
                    # Add to totals
                    ext_total += Q_ext * geo_cs * n_particles
                    sca_total += Q_sca * geo_cs * n_particles
                
                extinction[i] = ext_total
                ssa[i] = sca_total / ext_total if ext_total > 0 else 0.999
            
            return extinction, ssa
    
    
    # =============================================================================
    # MAIN PHOTOCHEMISTRY MODEL
    # =============================================================================
    
    class PlanetaryPhotochemistryModel:
        """
        Main photochemistry model coupling all components:
        - Atmospheric structure
        - Photolysis
        - Gas-phase chemistry  
        - Haze microphysics
        - Vertical transport
        """
        
        def __init__(self, planet: PlanetParameters, stellar: StellarSpectrum = None,
                     n_levels: int = 80):
            """
            Initialize the photochemistry model
            
            Parameters:
            -----------
            planet : PlanetParameters
                Planetary parameters
            stellar : StellarSpectrum
                Stellar spectrum parameters
            n_levels : int
                Number of vertical levels
            """
            self.planet = planet
            self.stellar = stellar or StellarSpectrum()
            
            # Initialize components
            self.atmosphere = AtmosphericStructure(planet, n_levels)
            self.radiative_transfer = RadiativeTransfer(self.atmosphere, self.stellar)
            self.haze = HazeMicrophysics(self.atmosphere)
            
            # Species list
            self.species_list = list(SpeciesDatabase.species_properties.keys())
            self.n_species = len(self.species_list)
            self.n_levels = n_levels
            
            # Initial mixing ratios
            self.mixing_ratios = self._initialize_mixing_ratios()
            
            # Photolysis rates (will be calculated)
            self.J_rates = {}
            
            # Reaction rates (will be calculated)
            self.k_rates = {}
            
            # Time stepping parameters
            self.time = 0.0
            self.dt = 100.0  # Initial time step (s)
            
        def _initialize_mixing_ratios(self) -> Dict[str, np.ndarray]:
            """
            Set initial atmospheric composition based on high metallicity
            """
            mixing = {}
            
            # High metallicity atmosphere (100x solar)
            # Enhanced CO2, H2O, CH4, N2 relative to H2
            
            # Background composition
            mixing['CO2'] = np.ones(self.n_levels) * 0.30      # 30% CO2
            mixing['H2O'] = np.zeros(self.n_levels)            # Variable with altitude
            mixing['CH4'] = np.ones(self.n_levels) * 0.01      # 1% CH4 (key for haze)
            mixing['N2'] = np.ones(self.n_levels) * 0.40       # 40% N2
            mixing['H2'] = np.ones(self.n_levels) * 0.20       # 20% H2
            mixing['CO'] = np.ones(self.n_levels) * 1e-4       # 100 ppm CO
            mixing['O2'] = np.ones(self.n_levels) * 1e-6       # 1 ppm O2
            mixing['NH3'] = np.ones(self.n_levels) * 1e-6      # 1 ppm NH3
            
            # H2O profile (decreasing with altitude)
            for i in range(self.n_levels):
                T = self.atmosphere.temperature[i]
                P = self.atmosphere.pressure[i]
                # Saturation mixing ratio
                P_sat = 1e6 * np.exp(23.2 - 5200/T)  # Approximate saturation pressure
                f_H2O_sat = P_sat / P
                mixing['H2O'][i] = min(0.20, f_H2O_sat)  # Cap at 20%
            
            # Trace species (initially very small)
            trace_species = ['OH', 'HO2', 'H2O2', 'O', 'O1D', 'O3', 'H', 
                            'N', 'NO', 'NO2', 'HNO3', 'CH3', 'CH2',
                            'C2H2', 'C2H4', 'C2H6', 'C2H', 'C4H2',
                            'HCN', 'HC3N', 'CH3CN', 'C2N2', 'C6H6',
                            'HAZE_S', 'HAZE_L', 'CN', 'NH2']
            
            for species in trace_species:
                mixing[species] = np.ones(self.n_levels) * 1e-20
            
            # Normalize to ensure sum = 1
            total = np.zeros(self.n_levels)
            major_species = ['CO2', 'H2O', 'CH4', 'N2', 'H2', 'CO', 'O2', 'NH3']
            for species in major_species:
                total += mixing[species]
            
            for species in major_species:
                mixing[species] = mixing[species] / total * (1 - 1e-10)
            
            return mixing
        
        def calculate_chemical_tendencies(self, n: Dict[str, np.ndarray]) -> Dict[str, np.ndarray]:
            """
            Calculate chemical production and loss rates for each species
            
            Parameters:
            -----------
            n : dict
                Number densities (cm^-3) of each species
                
            Returns:
            --------
            dn_dt : dict
                Rate of change (cm^-3/s) for each species
            """
            dn_dt = {species: np.zeros(self.n_levels) for species in self.species_list}
            
            # Get total number density and third body
            n_tot = self.atmosphere.number_density
            
            # Calculate photolysis rates
            haze_ext, _ = self.haze.calculate_haze_optical_properties(200)  # Reference wavelength
            self.J_rates = self.radiative_transfer.calculate_photolysis_rates(
                self.mixing_ratios, haze_ext)
            
            # Process photolysis reactions
            for rxn_name, J in self.J_rates.items():
                rxn = PhotolysisDatabase.photolysis_reactions[rxn_name]
                reactant = rxn['reactant']
                products = rxn['products']
                
                for i in range(self.n_levels):
                    # Loss of reactant
                    if reactant in n:
                        loss_rate = J[i] * n[reactant][i]
                        dn_dt[reactant][i] -= loss_rate
                        
                        # Production of products
                        for product in products:
                            if product in dn_dt:
                                dn_dt[product][i] += loss_rate
            
            # Process chemical reactions
            for rxn_name, rxn in ChemicalReactionNetwork.reactions.items():
                reactants = rxn['reactants']
                products = rxn['products']
                rxn_type = rxn['type']
                
                if rxn_type == 'photolysis':
                    continue  # Already handled
                
                for i in range(self.n_levels):
                    T = self.atmosphere.temperature[i]
                    
                    # Get rate constant
                    if rxn_type == '3body':
                        k = ChemicalReactionNetwork.get_rate_constant(rxn_name, T, n_tot[i])
                    else:
                        k = ChemicalReactionNetwork.get_rate_constant(rxn_name, T)
                    
                    if k <= 0:
                        continue
                    
                    # Calculate reaction rate
                    rate = k
                    for reactant in reactants:
                        if reactant == 'M':
                            rate *= n_tot[i]
                        elif reactant == 'hv':
                            continue  # Photolysis
                        elif reactant in n:
                            rate *= n[reactant][i]
                        else:
                            rate = 0
                            break
                    
                    # Apply to reactants (loss)
                    for reactant in reactants:
                        if reactant not in ['M', 'hv'] and reactant in dn_dt:
                            dn_dt[reactant][i] -= rate
                    
                    # Apply to products (gain)
                    for product in products:
                        if product not in ['M'] and product in dn_dt:
                            dn_dt[product][i] += rate
            
            return dn_dt
        
        def calculate_transport_tendencies(self, n: Dict[str, np.ndarray]) -> Dict[str, np.ndarray]:
            """
            Calculate vertical transport (diffusion + sedimentation)
            
            Uses 1D continuity equation:
            ∂n/∂t = ∂/∂z[Kzz * ∂n/∂z] - ∂/∂z[v_sed * n]
            """
            dn_dt = {species: np.zeros(self.n_levels) for species in self.species_list}
            
            dz = self.atmosphere.dz
            
            for species in self.species_list:
                if species in ['HAZE_S', 'HAZE_L']:
                    # Haze particles - include sedimentation
                    continue  # Handled separately
                
                n_s = n[species]
                mmw = SpeciesDatabase.get_molecular_weight(species)
                
                for i in range(1, self.n_levels - 1):
                    # Eddy diffusion
                    Kzz_up = self.atmosphere.get_eddy_diffusion(i + 1)
                    Kzz_down = self.atmosphere.get_eddy_diffusion(i - 1)
                    Kzz = self.atmosphere.get_eddy_diffusion(i)
                    
                    # Gradient
                    dndz_up = (n_s[i + 1] - n_s[i]) / dz
                    dndz_down = (n_s[i] - n_s[i - 1]) / dz
                    
                    # Molecular diffusion (only for light species)
                    D_mol = 0.0
                    if mmw < self.planet.mean_molecular_weight:
                        # Chapman-Enskog approximation
                        T = self.atmosphere.temperature[i]
                        P = self.atmosphere.pressure[i]
                        D_mol = 1e16 * np.sqrt(T) / (P / 1e6)  # cm^2/s
                    
                    # Combined diffusion
                    K_total = Kzz + D_mol
                    
                    # Flux at upper boundary
                    flux_up = K_total * dndz_up
                    flux_down = (Kzz + D_mol * 0.5) * dndz_down
                    
                    # Divergence
                    dn_dt[species][i] = -(flux_up - flux_down) / dz
            
            return dn_dt
        
        def calculate_haze_tendencies(self, n: Dict[str, np.ndarray]) -> Dict[str, np.ndarray]:
            """
            Calculate haze formation and evolution
            """
            dn_dt = {species: np.zeros(self.n_levels) for species in ['HAZE_S', 'HAZE_L']}
            
            # Get haze precursor concentrations
            precursors = {s: n[s] for s in ['HCN', 'C2H2', 'C4H2', 'HC3N', 'C6H6'] 
                         if s in n}
            
            # Nucleation rate
            J_nuc = self.haze.nucleation_rate(precursors)
            
            # Small particles from nucleation
            dn_dt['HAZE_S'] += J_nuc
            
            # Growth from small to large particles
            for i in range(self.n_levels):
                growth_rate = self.haze.condensation_growth_rate(1e-6, precursors, i)
                
                # Loss of small particles to growth
                dn_dt['HAZE_S'][i] -= n['HAZE_S'][i] * growth_rate / 1e-6
                dn_dt['HAZE_L'][i] += n['HAZE_S'][i] * growth_rate / 1e-6
                
                # Loss of precursors to haze
                for precursor in precursors:
                    if precursor in dn_dt:
                        dn_dt[precursor][i] -= n[precursor][i] * 1e-10  # Simplified
            
            return dn_dt
        
        def step(self, dt: float) -> float:
            """
            Advance model by one time step
            
            Parameters:
            -----------
            dt : float
                Time step in seconds
                
            Returns:
            --------
            actual_dt : float
                Actual time step used
            """
            # Convert mixing ratios to number densities
            n = {}
            for species in self.species_list:
                n[species] = self.mixing_ratios[species] * self.atmosphere.number_density
            
            # Calculate tendencies
            chem_tend = self.calculate_chemical_tendencies(n)
            trans_tend = self.calculate_transport_tendencies(n)
            haze_tend = self.calculate_haze_tendencies(n)
            
            # Combine tendencies
            total_tend = {}
            for species in self.species_list:
                total_tend[species] = chem_tend.get(species, np.zeros(self.n_levels)) + \
                                      trans_tend.get(species, np.zeros(self.n_levels))
                if species in haze_tend:
                    total_tend[species] += haze_tend[species]
            
            # Find maximum relative change for adaptive time stepping
            max_rel_change = 0.0
            for species in self.species_list:
                for i in range(self.n_levels):
                    if n[species][i] > 1e-10:
                        rel_change = abs(total_tend[species][i] * dt / n[species][i])
                        max_rel_change = max(max_rel_change, rel_change)
            
            # Adaptive time step
            if max_rel_change > 0.5:
                dt = dt * 0.3 / max_rel_change
            actual_dt = dt
            
            # Update number densities
            for species in self.species_list:
                n[species] = np.maximum(n[species] + total_tend[species] * dt, 0)
            
            # Convert back to mixing ratios
            n_tot = self.atmosphere.number_density
            for species in self.species_list:
                self.mixing_ratios[species] = n[species] / n_tot
            
            # Apply boundary conditions
            self._apply_boundary_conditions()
            
            # Update time
            self.time += actual_dt
            
            return actual_dt
        
        def _apply_boundary_conditions(self):
            """Apply boundary conditions"""
            # Surface: fixed mixing ratios for major species
            self.mixing_ratios['CO2'][0] = 0.30
            self.mixing_ratios['CH4'][0] = 0.01
            self.mixing_ratios['N2'][0] = 0.40
            self.mixing_ratios['H2'][0] = 0.20
            
            # Top of atmosphere: escape for light species
            # Zero flux for others
            
        def run(self, total_time: float, output_interval: float = None) -> Dict:
            """
            Run model for specified time
            
            Parameters:
            -----------
            total_time : float
                Total integration time in seconds
            output_interval : float
                Interval for saving outputs (s)
                
            Returns:
            --------
            history : dict
                Time history of key quantities
            """
            if output_interval is None:
                output_interval = total_time / 100
            
            history = {
                'time': [],
                'mixing_ratios': [],
                'haze_production': []
            }
            
            t = 0
            last_output = 0
            
            while t < total_time:
                dt = self.step(self.dt)
                t += dt
                
                if t - last_output >= output_interval:
                    history['time'].append(t)
                    history['mixing_ratios'].append({s: self.mixing_ratios[s].copy() 
                                                      for s in self.species_list})
                    
                    # Calculate total haze production rate
                    haze_rate = np.sum(self.haze.nucleation_rate(
                        {s: self.mixing_ratios[s] * self.atmosphere.number_density 
                         for s in ['HCN', 'C2H2', 'C4H2']}))
                    history['haze_production'].append(haze_rate)
                    
                    last_output = t
                    
                    # Progress output
                    if len(history['time']) % 10 == 0:
                        print(f"Time: {t/3.15e7:.2f} years, "
                              f"Max CH4: {np.max(self.mixing_ratios['CH4']):.2e}, "
                              f"Max HCN: {np.max(self.mixing_ratios['HCN']):.2e}")
            
            return history
        
        def plot_results(self, history: Dict = None):
            """Generate comprehensive plots of results"""
            fig = plt.figure(figsize=(20, 16))
            
            z_km = self.atmosphere.altitude / 1e5
            
            # 1. Temperature profile
            ax1 = fig.add_subplot(3, 4, 1)
            ax1.plot(self.atmosphere.temperature, z_km, 'r-', linewidth=2)
            ax1.set_xlabel('Temperature (K)')
            ax1.set_ylabel('Altitude (km)')
            ax1.set_title('Temperature Profile')
            ax1.grid(True, alpha=0.3)
            
            # 2. Pressure profile
            ax2 = fig.add_subplot(3, 4, 2)
            ax2.semilogx(self.atmosphere.pressure / 1e6, z_km, 'b-', linewidth=2)
            ax2.set_xlabel('Pressure (bars)')
            ax2.set_title('Pressure Profile')
            ax2.grid(True, alpha=0.3)
            
            # 3. Major species
            ax3 = fig.add_subplot(3, 4, 3)
            major = ['CO2', 'H2O', 'CH4', 'N2', 'H2']
            colors = ['blue', 'cyan', 'orange', 'green', 'red']
            for species, color in zip(major, colors):
                ax3.semilogx(self.mixing_ratios[species], z_km, 
                            color=color, label=species, linewidth=2)
            ax3.set_xlabel('Mixing Ratio')
            ax3.set_title('Major Species')
            ax3.legend()
            ax3.grid(True, alpha=0.3)
            ax3.set_xlim(1e-4, 1)
            
            # 4. Haze precursors
            ax4 = fig.add_subplot(3, 4, 4)
            precursors = ['HCN', 'C2H2', 'C2H6', 'C4H2', 'HC3N']
            colors = ['purple', 'brown', 'pink', 'olive', 'magenta']
            for species, color in zip(precursors, colors):
                ax4.semilogx(self.mixing_ratios[species], z_km, 
                            color=color, label=species, linewidth=2)
            ax4.set_xlabel('Mixing Ratio')
            ax4.set_title('Haze Precursors')
            ax4.legend(fontsize=8)
            ax4.grid(True, alpha=0.3)
            ax4.set_xlim(1e-20, 1e-2)
            
            # 5. HOx species
            ax5 = fig.add_subplot(3, 4, 5)
            hox = ['OH', 'HO2', 'H2O2', 'H']
            colors = ['red', 'orange', 'yellow', 'pink']
            for species, color in zip(hox, colors):
                ax5.semilogx(self.mixing_ratios[species], z_km, 
                            color=color, label=species, linewidth=2)
            ax5.set_xlabel('Mixing Ratio')
            ax5.set_title('HOx Species')
            ax5.legend()
            ax5.grid(True, alpha=0.3)
            ax5.set_xlim(1e-20, 1e-6)
            
            # 6. NOx species
            ax6 = fig.add_subplot(3, 4, 6)
            nox = ['NO', 'NO2', 'N', 'NH3', 'HNO3']
            colors = ['blue', 'cyan', 'green', 'purple', 'magenta']
            for species, color in zip(nox, colors):
                ax6.semilogx(self.mixing_ratios[species], z_km, 
                            color=color, label=species, linewidth=2)
            ax6.set_xlabel('Mixing Ratio')
            ax6.set_title('NOx Species')
            ax6.legend(fontsize=8)
            ax6.grid(True, alpha=0.3)
            ax6.set_xlim(1e-20, 1e-4)
            
            # 7. Ozone
            ax7 = fig.add_subplot(3, 4, 7)
            ax7.semilogx(self.mixing_ratios['O3'], z_km, 'g-', linewidth=2, label='O3')
            ax7.semilogx(self.mixing_ratios['O'], z_km, 'r--', linewidth=2, label='O')
            ax7.semilogx(self.mixing_ratios['O1D'], z_km, 'b:', linewidth=2, label='O(1D)')
            ax7.set_xlabel('Mixing Ratio')
            ax7.set_title('Oxygen Species')
            ax7.legend()
            ax7.grid(True, alpha=0.3)
            
            # 8. Photolysis rates
            ax8 = fig.add_subplot(3, 4, 8)
            if self.J_rates:
                for rxn_name in ['CH4_photolysis_1', 'CO2_photolysis_1', 'N2_photolysis']:
                    if rxn_name in self.J_rates:
                        label = rxn_name.split('_')[0]
                        ax8.semilogx(self.J_rates[rxn_name], z_km, label=label, linewidth=2)
            ax8.set_xlabel('J (s⁻¹)')
            ax8.set_title('Photolysis Rates')
            ax8.legend()
            ax8.grid(True, alpha=0.3)
            
            # 9. Eddy diffusion
            ax9 = fig.add_subplot(3, 4, 9)
            Kzz = [self.atmosphere.get_eddy_diffusion(i) for i in range(self.n_levels)]
            ax9.semilogx(Kzz, z_km, 'm-', linewidth=2)
            ax9.set_xlabel('Kzz (cm²/s)')
            ax9.set_title('Eddy Diffusion')
            ax9.grid(True, alpha=0.3)
            
            # 10. Haze particles
            ax10 = fig.add_subplot(3, 4, 10)
            ax10.semilogx(self.mixing_ratios['HAZE_S'], z_km, 'brown', 
                         label='Small haze', linewidth=2)
            ax10.semilogx(self.mixing_ratios['HAZE_L'], z_km, 'darkgoldenrod', 
                         label='Large haze', linewidth=2)
            ax10.set_xlabel('Mixing Ratio')
            ax10.set_title('Haze Particles')
            ax10.legend()
            ax10.grid(True, alpha=0.3)
            
            # 11. Haze optical depth (if haze present)
            ax11 = fig.add_subplot(3, 4, 11)
            ext_200, ssa = self.haze.calculate_haze_optical_properties(200)
            ext_500, _ = self.haze.calculate_haze_optical_properties(500)
            ax11.semilogx(ext_200, z_km, 'b-', label='λ=200nm', linewidth=2)
            ax11.semilogx(ext_500, z_km, 'r--', label='λ=500nm', linewidth=2)
            ax11.set_xlabel('Extinction (cm⁻¹)')
            ax11.set_title('Haze Extinction')
            ax11.legend()
            ax11.grid(True, alpha=0.3)
            
            # 12. Time evolution (if history provided)
            ax12 = fig.add_subplot(3, 4, 12)
            if history and len(history['time']) > 1:
                times_years = np.array(history['time']) / 3.15e7
                ax12.semilogy(times_years, history['haze_production'], 'k-', linewidth=2)
                ax12.set_xlabel('Time (years)')
                ax12.set_ylabel('Haze Production Rate (cm⁻³/s)')
                ax12.set_title('Haze Formation Evolution')
            else:
                ax12.text(0.5, 0.5, 'Run model to see\ntime evolution', 
                         ha='center', va='center', transform=ax12.transAxes)
            ax12.grid(True, alpha=0.3)
            
            plt.tight_layout()
            return fig
    
    
    # =============================================================================
    # SENSITIVITY ANALYSIS
    # =============================================================================
    
    class SensitivityAnalysis:
        """
        Analyze sensitivity of haze formation to key parameters
        """
        
        def __init__(self, base_planet: PlanetParameters):
            self.base_planet = base_planet
            
        def run_parameter_sweep(self, parameter_name: str, 
                               values: List[float],
                               integration_time: float = 1e9) -> Dict:
            """
            Run model across range of parameter values
            
            Parameters:
            -----------
            parameter_name : str
                Name of parameter to vary
            values : list
                Values to test
            integration_time : float
                Time to run each model (s)
                
            Returns:
            --------
            results : dict
                Results for each parameter value
            """
            results = {
                'values': values,
                'haze_production': [],
                'max_haze_altitude': [],
                'max_HCN': [],
                'max_C2H2': []
            }
            
            for value in values:
                print(f"\nRunning {parameter_name} = {value}")
                
                # Create modified planet
                planet = PlanetParameters(
                    name=self.base_planet.name,
                    mass=self.base_planet.mass,
                    radius=self.base_planet.radius,
                    gravity=self.base_planet.gravity,
                    surface_pressure=self.base_planet.surface_pressure,
                    equilibrium_temp=self.base_planet.equilibrium_temp,
                    semi_major_axis=self.base_planet.semi_major_axis,
                    stellar_type=self.base_planet.stellar_type,
                    metallicity=self.base_planet.metallicity,
                    mean_molecular_weight=self.base_planet.mean_molecular_weight
                )
                
                # Modify parameter
                if parameter_name == 'equilibrium_temp':
                    planet.equilibrium_temp = value
                elif parameter_name == 'metallicity':
                    planet.metallicity = value
                elif parameter_name == 'semi_major_axis':
                    planet.semi_major_axis = value
                elif parameter_name == 'surface_pressure':
                    planet.surface_pressure = value
                
                # Run model
                model = PlanetaryPhotochemistryModel(planet, n_levels=50)
                history = model.run(integration_time, output_interval=integration_time/10)
                
                # Store results
                haze_nuc = model.haze.nucleation_rate({
                    s: model.mixing_ratios[s] * model.atmosphere.number_density 
                    for s in ['HCN', 'C2H2', 'C4H2']
                })
                
                results['haze_production'].append(np.max(haze_nuc))
                results['max_haze_altitude'].append(
                    model.atmosphere.altitude[np.argmax(haze_nuc)] / 1e5)  # km
                results['max_HCN'].append(np.max(model.mixing_ratios['HCN']))
                results['max_C2H2'].append(np.max(model.mixing_ratios['C2H2']))
            
            return results
        
        def plot_sensitivity(self, results: Dict, parameter_name: str, units: str):
            """Plot sensitivity analysis results"""
            fig, axes = plt.subplots(2, 2, figsize=(12, 10))
            
            values = results['values']
            
            # Haze production rate
            axes[0, 0].semilogy(values, results['haze_production'], 'ko-', linewidth=2, markersize=8)
            axes[0, 0].set_xlabel(f'{parameter_name} ({units})')
            axes[0, 0].set_ylabel('Peak Nucleation Rate (cm⁻³/s)')
            axes[0, 0].set_title('Haze Production')
            axes[0, 0].grid(True, alpha=0.3)
            
            # Peak haze altitude
            axes[0, 1].plot(values, results['max_haze_altitude'], 'bs-', linewidth=2, markersize=8)
            axes[0, 1].set_xlabel(f'{parameter_name} ({units})')
            axes[0, 1].set_ylabel('Altitude (km)')
            axes[0, 1].set_title('Peak Haze Altitude')
            axes[0, 1].grid(True, alpha=0.3)
            
            # HCN abundance
            axes[1, 0].semilogy(values, results['max_HCN'], 'r^-', linewidth=2, markersize=8)
            axes[1, 0].set_xlabel(f'{parameter_name} ({units})')
            axes[1, 0].set_ylabel('Max HCN Mixing Ratio')
            axes[1, 0].set_title('HCN Abundance')
            axes[1, 0].grid(True, alpha=0.3)
            
            # C2H2 abundance
            axes[1, 1].semilogy(values, results['max_C2H2'], 'gd-', linewidth=2, markersize=8)
            axes[1, 1].set_xlabel(f'{parameter_name} ({units})')
            axes[1, 1].set_ylabel('Max C₂H₂ Mixing Ratio')
            axes[1, 1].set_title('Acetylene Abundance')
            axes[1, 1].grid(True, alpha=0.3)
            
            plt.tight_layout()
            return fig
    
    
    # =============================================================================
    # MAIN EXECUTION
    # =============================================================================
    
    def main():
        """
        Main function to run the planetary photochemistry model
        """
        print("=" * 70)
        print("PLANETARY PHOTOCHEMISTRY MODEL")
        print("Haze Formation on Temperate Super-Earths with High-Metallicity")
        print("=" * 70)
        
        # Define planet parameters
        planet = PlanetParameters(
            name="K2-18b-like Super-Earth",
            mass=8.0,           # Earth masses
            radius=2.0,         # Earth radii
            surface_pressure=10.0,  # bars
            equilibrium_temp=280.0,  # K (temperate)
            semi_major_axis=0.15,    # AU (M-dwarf habitable zone)
            stellar_type="M",
            metallicity=100.0,       # 100x solar metallicity
            mean_molecular_weight=20.0  # g/mol (heavy atmosphere)
        )
        
        print(f"\nPlanet: {planet.name}")
        print(f"  Mass: {planet.mass} Earth masses")
        print(f"  Radius: {planet.radius} Earth radii")
        print(f"  Equilibrium temperature: {planet.equilibrium_temp} K")
        print(f"  Metallicity: {planet.metallicity}x solar")
        
        # Define stellar spectrum
        stellar = StellarSpectrum(
            stellar_type="M",
            FUV_flux=0.1,
            MUV_flux=0.05,
            NUV_flux=0.03,
            Ly_alpha_flux=0.2
        )
        
        # Initialize model
        print("\nInitializing photochemistry model...")
        model = PlanetaryPhotochemistryModel(planet, stellar, n_levels=60)
        
        print(f"  Vertical levels: {model.n_levels}")
        print(f"  Species tracked: {model.n_species}")
        print(f"  Altitude range: 0 - {model.atmosphere.z_top/1e5:.1f} km")
        
        # Plot initial atmospheric structure
        print("\nPlotting initial atmospheric structure...")
        fig_structure = model.atmosphere.plot_structure()
        fig_structure.savefig('atmospheric_structure.png', dpi=150)
        print("  Saved: atmospheric_structure.png")
        
        # Run model
        print("\nRunning photochemistry model...")
        print("-" * 50)
        
        # Short test run (adjust for longer simulations)
        integration_time = 1e8  # seconds (~3 years)
        output_interval = 1e6   # seconds
        
        history = model.run(integration_time, output_interval)
        
        print("-" * 50)
        print(f"Integration complete. Total time: {model.time/3.15e7:.2f} years")
        
        # Plot results
        print("\nGenerating result plots...")
        fig_results = model.plot_results(history)
        fig_results.savefig('photochemistry_results.png', dpi=150)
        print("  Saved: photochemistry_results.png")
        
        # Print key results
        print("\n" + "=" * 70)
        print("KEY RESULTS")
        print("=" * 70)
        
        print("\nHaze Precursor Abundances:")
        print(f"  Max HCN mixing ratio: {np.max(model.mixing_ratios['HCN']):.2e}")
        print(f"  Max C2H2 mixing ratio: {np.max(model.mixing_ratios['C2H2']):.2e}")
        print(f"  Max C2H6 mixing ratio: {np.max(model.mixing_ratios['C2H6']):.2e}")
        
        print("\nHaze Properties:")
        haze_nuc = model.haze.nucleation_rate({
            s: model.mixing_ratios[s] * model.atmosphere.number_density 
            for s in ['HCN', 'C2H2', 'C4H2']
        })
        print(f"  Peak nucleation rate: {np.max(haze_nuc):.2e} cm⁻³/s")
        print(f"  Peak haze altitude: {model.atmosphere.altitude[np.argmax(haze_nuc)]/1e5:.1f} km")
        
        ext_200, ssa = model.haze.calculate_haze_optical_properties(200)
        print(f"  Max extinction at 200nm: {np.max(ext_200):.2e} cm⁻¹")
        
        print("\nAtmospheric Chemistry:")
        print(f"  Max OH mixing ratio: {np.max(model.mixing_ratios['OH']):.2e}")
        print(f"  Max O3 mixing ratio: {np.max(model.mixing_ratios['O3']):.2e}")
        
        # Run sensitivity analysis (optional - uncomment to run)
        print("\n" + "=" * 70)
        print("SENSITIVITY ANALYSIS")
        print("=" * 70)
        
        sensitivity = SensitivityAnalysis(planet)
        
        # Temperature sensitivity
        print("\nAnalyzing temperature sensitivity...")
        temp_results = sensitivity.run_parameter_sweep(
            'equilibrium_temp', 
            [250, 280, 310, 340],  # K
            integration_time=5e7
        )
        fig_temp = sensitivity.plot_sensitivity(temp_results, 'Temperature', 'K')
        fig_temp.savefig('temperature_sensitivity.png', dpi=150)
        print("  Saved: temperature_sensitivity.png")
        
        # Orbital distance sensitivity
        print("\nAnalyzing orbital distance sensitivity...")
        dist_results = sensitivity.run_parameter_sweep(
            'semi_major_axis',
            [0.10, 0.15, 0.20, 0.25],  # AU
            integration_time=5e7
        )
        fig_dist = sensitivity.plot_sensitivity(dist_results, 'Semi-major Axis', 'AU')
        fig_dist.savefig('orbital_distance_sensitivity.png', dpi=150)
        print("  Saved: orbital_distance_sensitivity.png")
        
        print("\n" + "=" * 70)
        print("MODEL RUN COMPLETE")
        print("=" * 70)
        
        plt.show()
        
        return model, history
    
    
    if __name__ == "__main__":
        model, history = main()
    

    This comprehensive planetary photochemistry model includes:

    Key Physical Components

    1. Atmospheric Structure: Hydrostatic equilibrium with realistic T-P profiles for temperate super-Earths

    2. High-Metallicity Composition: Enhanced CO₂, H₂O, CH₄, N₂ relative to H₂/He (100x solar metallicity)

    3. Photochemistry Network:

      • 15+ photolysis reactions (CH₄, CO₂, H₂O, N₂, HCN, C₂H₂, etc.)
      • 80+ gas-phase reactions (HOx, NOx, hydrocarbon chemistry)
      • Wavelength-dependent cross-sections
    4. Haze Microphysics:

      • Homogeneous nucleation from HCN and C₂H₂
      • Particle growth by condensation
      • Coagulation physics
      • Sedimentation with Cunningham slip correction
      • Mie theory for optical properties
    5. Transport: Eddy diffusion + molecular diffusion

    Outputs Generated

    • Atmospheric structure profiles
    • Species mixing ratio profiles
    • Haze production rates and optical depths
    • Sensitivity analysis plots

    The model is particularly suited for studying K2-18b type planets with potential photochemical hazes affecting observations.