This is a comprehensive request for a planetary energy balance model for exoplanets with eccentric orbits. I need to create a detailed model that covers:
- Insolation cycles - How stellar flux varies with orbital position for eccentric orbits
- Atmospheric response - How the atmosphere responds to varying insolation
- Habitability metrics - Quantitative measures of habitability
- Observational tests - How we can observationally verify model predictions
Let me structure this carefully:
1. Insolation Model for Eccentric Orbits
For an eccentric orbit:
- The orbital distance varies: r = a(1-e²)/(1+e·cos(ν)) where ν is true anomaly
- Instantaneous insolation: S = L*/(4πr²) ∝ 1/r²
- The variation is significant: S_max/S_min = ((1+e)/(1-e))²
Key aspects:
- Mean insolation over orbit: ⟨S⟩ = S₀/(1-e²)^(1/2) where S₀ is insolation at semi-major axis
- Time-varying insolation as function of true anomaly or mean anomaly
- Seasonal effects (if obliquity is non-zero)
2. Atmospheric Response
This involves:
- Thermal inertia of surface and atmosphere
- Heat transport (meridional and zonal)
- Greenhouse effect variations
- Atmospheric circulation changes
- Potential for atmospheric collapse at aphelion
- Cloud feedback mechanisms
The key equation is the energy balance with thermal inertia:
C ∂T/∂t = S(1-α) - εσT⁴ + D∇²T
Where:
- C = heat capacity per unit area
- α = albedo
- ε = emissivity
- D = diffusion coefficient for heat transport
3. Habitability Metrics
Several approaches:
- Mean annual temperature
- Fraction of orbit with liquid water
- Habitable zone boundaries for eccentric orbits
- "Spin-orbit" thermal habitability index
- Consider ice-albedo feedback
4. Observational Tests
- Phase curves (thermal emission variations)
- Secondary eclipse measurements
- Spectral signatures during different orbital phases
- Transit timing variations (if applicable)
Let me now write a comprehensive Python model that implements all of this.
I'll create:
- Orbital mechanics module
- Energy balance model (EBM)
- Atmospheric thermal response model
- Habitability metrics calculator
- Observational signature predictor
- Visualization tools
This will be a substantial piece of code. Let me make it well-organized with clear documentation.
Planetary Energy Balance Model for Eccentric Exoplanets
This is a comprehensive model covering insolation physics, atmospheric thermal response, habitability assessment, and observational predictions for exoplanets on eccentric orbits.
"""
Planetary Energy Balance Model for Eccentric Exoplanets
========================================================
A comprehensive model simulating:
- Time-varying insolation on eccentric orbits
- Atmospheric thermal response with heat capacity
- Latitude-dependent energy balance
- Habitability metrics and indices
- Observational signatures (phase curves, secondary eclipses)
Author: Advanced Climate Dynamics Model
"""
import numpy as np
from scipy.integrate import solve_ivp, quad
from scipy.optimize import brentq
from scipy.interpolate import interp1d
import matplotlib.pyplot as plt
from dataclasses import dataclass
from typing import Tuple, List, Optional, Callable
from enum import Enum
import warnings
warnings.filterwarnings('ignore')
# =============================================================================
# Physical Constants
# =============================================================================
STEFAN_BOLTZMANN = 5.67e-8 # W m^-2 K^-4
SOLAR_LUMINOSITY = 3.828e26 # W
SOLAR_CONSTANT = 1361 # W m^-2 (at 1 AU)
AU_IN_METERS = 1.496e11 # m
WATER_HEAT_CAPACITY = 4186 # J kg^-1 K^-1
ICE_HEAT_CAPACITY = 2090 # J kg^-1 K^-1
AIR_HEAT_CAPACITY = 1005 # J kg^-1 K^-1
WATER_DENSITY = 1000 # kg m^-3
GRAVITY = 9.81 # m s^-2
# =============================================================================
# Data Classes for Model Parameters
# =============================================================================
@dataclass
class StellarParameters:
"""Stellar properties"""
luminosity: float # In solar luminosities
mass: float # In solar masses
effective_temp: float # K
radius: float # In solar radii
@property
def luminosity_watts(self) -> float:
return self.luminosity * SOLAR_LUMINOSITY
@dataclass
class OrbitalParameters:
"""Orbital properties"""
semi_major_axis: float # AU
eccentricity: float # 0 to <1
obliquity: float # degrees (axial tilt)
argument_of_perihelion: float # degrees
@property
def periapsis(self) -> float:
"""Closest approach distance in AU"""
return self.semi_major_axis * (1 - self.eccentricity)
@property
def apoapsis(self) -> float:
"""Farthest distance in AU"""
return self.semi_major_axis * (1 + self.eccentricity)
@property
def orbital_period(self) -> float:
"""Orbital period in Earth years"""
return np.sqrt(self.semi_major_axis**3)
@property
def orbital_period_seconds(self) -> float:
"""Orbital period in seconds"""
return self.orbital_period * 3.154e7
@dataclass
class PlanetaryParameters:
"""Planetary properties"""
radius: float # Earth radii
mass: float # Earth masses
surface_gravity: float # m s^-2
rotation_period: float # hours
# Atmospheric properties
surface_pressure: float # bar
co2_partial_pressure: float # bar
n2_partial_pressure: float # bar
h2o_column: float # kg m^-2 (precipitable water)
# Surface properties
ocean_fraction: float # 0 to 1
land_heat_capacity: float # J m^-2 K^-1
ocean_depth_mixed_layer: float # m
# Albedo parameters
surface_albedo: float
ocean_albedo: float
ice_albedo: float
@property
def effective_heat_capacity(self) -> float:
"""Effective heat capacity of mixed layer (J m^-2 K^-1)"""
land_capacity = self.land_heat_capacity
ocean_capacity = self.ocean_depth_mixed_layer * WATER_DENSITY * WATER_HEAT_CAPACITY
return self.ocean_fraction * ocean_capacity + (1 - self.ocean_fraction) * land_capacity
@dataclass
class AtmosphericParameters:
"""Atmospheric radiative properties"""
greenhouse_factor: float # Multiplier for IR opacity
heat_transport_coeff: float # W m^-2 K^-1 (meridional diffusion)
cloud_feedback: float # Cloud albedo feedback strength
ice_albedo_feedback: float # Ice-albedo feedback strength
# =============================================================================
# Orbital Mechanics Module
# =============================================================================
class OrbitalMechanics:
"""
Solves Keplerian orbital mechanics for eccentric orbits.
"""
def __init__(self, orbital_params: OrbitalParameters):
self.params = orbital_params
self._precompute_orbit()
def _precompute_orbit(self):
"""Precompute orbital positions for fast interpolation"""
self.mean_anomalies = np.linspace(0, 2*np.pi, 1000)
self.true_anomalies = np.array([self._mean_to_true_anomaly(M)
for M in self.mean_anomalies])
self.distances = self._calculate_distances(self.true_anomalies)
# Create interpolation functions
self._true_anomaly_interp = interp1d(self.mean_anomalies,
self.true_anomalies,
kind='cubic')
self._distance_interp = interp1d(self.true_anomalies,
self.distances,
kind='cubic')
def _mean_to_true_anomaly(self, M: float, tol: float = 1e-8) -> float:
"""
Convert mean anomaly to true anomaly using Newton-Raphson method.
Parameters:
M: Mean anomaly (radians)
tol: Convergence tolerance
Returns:
True anomaly (radians)
"""
e = self.params.eccentricity
# Initial guess for eccentric anomaly
if e < 0.8:
E = M
else:
E = np.pi
# Newton-Raphson iteration for Kepler's equation: E - e*sin(E) = M
for _ in range(100):
f = E - e * np.sin(E) - M
f_prime = 1 - e * np.cos(E)
E_new = E - f / f_prime
if np.abs(E_new - E) < tol:
break
E = E_new
# Convert eccentric anomaly to true anomaly
true_anomaly = 2 * np.arctan2(
np.sqrt(1 + e) * np.sin(E / 2),
np.sqrt(1 - e) * np.cos(E / 2)
)
return true_anomaly
def _calculate_distances(self, true_anomaly: np.ndarray) -> np.ndarray:
"""Calculate orbital distance from true anomaly"""
a = self.params.semi_major_axis
e = self.params.eccentricity
return a * (1 - e**2) / (1 + e * np.cos(true_anomaly))
def get_distance(self, true_anomaly: float) -> float:
"""Get orbital distance (AU) at given true anomaly"""
a = self.params.semi_major_axis
e = self.params.eccentricity
return a * (1 - e**2) / (1 + e * np.cos(true_anomaly))
def get_position(self, time_fraction: float) -> Tuple[float, float, float]:
"""
Get orbital position at given time.
Parameters:
time_fraction: Fraction of orbital period (0 to 1)
Returns:
(distance_au, true_anomaly, x_coordinate)
"""
M = 2 * np.pi * time_fraction
nu = self._true_anomaly_interp(M)
r = self.get_distance(nu)
x = r * np.cos(nu + np.radians(self.params.argument_of_perihelion))
return float(r), float(nu), float(x)
def time_weighted_distance(self) -> float:
"""Calculate time-weighted mean distance"""
e = self.params.eccentricity
a = self.params.semi_major_axis
# Analytical result: r_time_mean = a * (1 + e²/2)
return a * (1 + 0.5 * e**2)
# =============================================================================
# Insolation Model
# =============================================================================
class InsolationModel:
"""
Calculates time-varying stellar flux on eccentric orbits.
Includes diurnal and seasonal variations.
"""
def __init__(self, stellar_params: StellarParameters,
orbital_params: OrbitalParameters):
self.stellar = stellar_params
self.orbital = orbital_params
self.orbital_mechanics = OrbitalMechanics(orbital_params)
def instantaneous_insolation(self, distance_au: float) -> float:
"""
Calculate instantaneous stellar flux at given distance.
Parameters:
distance_au: Distance from star in AU
Returns:
Flux in W m^-2
"""
return (self.stellar.luminosity_watts /
(4 * np.pi * (distance_au * AU_IN_METERS)**2))
def insolation_at_anomaly(self, true_anomaly: float) -> float:
"""Get insolation at specific orbital position"""
r = self.orbital_mechanics.get_distance(true_anomaly)
return self.instantaneous_insolation(r)
def mean_annual_insolation(self) -> float:
"""
Calculate orbit-averaged insolation.
For eccentric orbit: S_mean = L / (4πa²(1-e²)^0.5)
"""
a = self.orbital.semi_major_axis
e = self.orbital.eccentricity
correction = np.sqrt(1 - e**2)
return self.instantaneous_insolation(a) / correction
def insolation_variation(self) -> Tuple[float, float, float]:
"""
Calculate insolation statistics.
Returns:
(S_max, S_min, S_mean)
"""
r_peri = self.orbital.periapsis
r_apo = self.orbital.apoapsis
S_max = self.instantaneous_insolation(r_peri)
S_min = self.instantaneous_insolation(r_apo)
S_mean = self.mean_annual_insolation()
return S_max, S_min, S_mean
def diurnal_insolation(self, latitude: float, distance_au: float,
declination: float, hour_angle: float) -> float:
"""
Calculate diurnal insolation at specific location and time.
Based on classical solar geometry.
Parameters:
latitude: Planetographic latitude (radians)
distance_au: Current orbital distance (AU)
declination: Solar declination (radians)
hour_angle: Hour angle from local noon (radians)
Returns:
Insolation in W m^-2
"""
S_0 = self.instantaneous_insolation(distance_au)
# Cosine of zenith angle
cos_zenith = (np.sin(latitude) * np.sin(declination) +
np.cos(latitude) * np.cos(declination) * np.cos(hour_angle))
# No insolation if sun below horizon
if cos_zenith <= 0:
return 0.0
return S_0 * cos_zenith
def daily_mean_insolation(self, latitude: float, true_anomaly: float) -> float:
"""
Calculate daily-mean insolation at given latitude and orbital position.
Parameters:
latitude: Latitude in radians
true_anomaly: Orbital position in radians
Returns:
Daily-mean insolation in W m^-2
"""
r = self.orbital_mechanics.get_distance(true_anomaly)
S_0 = self.instantaneous_insolation(r)
# Solar declination (simplified: depends on obliquity and true anomaly)
obliquity = np.radians(self.orbital.obliquity)
# Assume perihelion at winter solstice for simplicity
declination = obliquity * np.sin(true_anomaly)
# Day length factor
tan_product = np.tan(latitude) * np.tan(declination)
if np.abs(tan_product) >= 1:
# Polar day or polar night
if tan_product >= 1:
H = np.pi # 24-hour day
else:
return 0.0 # Polar night
else:
H = np.arccos(-tan_product) # Hour angle at sunset
# Daily mean insolation
daily_mean = (S_0 / np.pi) * (
H * np.sin(latitude) * np.sin(declination) +
np.cos(latitude) * np.cos(declination) * np.sin(H)
)
return daily_mean
def generate_insolation_time_series(self, n_points: int = 1000) -> dict:
"""
Generate complete insolation time series over one orbit.
Returns:
Dictionary with time series arrays
"""
times = np.linspace(0, 1, n_points)
distances = np.zeros(n_points)
insolations = np.zeros(n_points)
true_anomalies = np.zeros(n_points)
for i, t in enumerate(times):
r, nu, _ = self.orbital_mechanics.get_position(t)
distances[i] = r
true_anomalies[i] = nu
insolations[i] = self.instantaneous_insolation(r)
return {
'time_fraction': times,
'distance_au': distances,
'true_anomaly': true_anomalies,
'insolation': insolations,
'insolation_normalized': insolations / self.mean_annual_insolation()
}
# =============================================================================
# Energy Balance Model
# =============================================================================
class EnergyBalanceModel:
"""
One-dimensional energy balance model with thermal inertia.
Solves the diffusion equation with time-varying forcing.
"""
def __init__(self,
stellar_params: StellarParameters,
orbital_params: OrbitalParameters,
planetary_params: PlanetaryParameters,
atmospheric_params: AtmosphericParameters):
self.stellar = stellar_params
self.orbital = orbital_params
self.planet = planetary_params
self.atmosphere = atmospheric_params
self.insolation_model = InsolationModel(stellar_params, orbital_params)
# Spatial discretization (latitude bands)
self.n_lat = 36
self.latitudes = np.linspace(-np.pi/2 + np.pi/(2*self.n_lat),
np.pi/2 - np.pi/(2*self.n_lat),
self.n_lat)
self.dlat = np.pi / self.n_lat
# Grid cell areas (weighted by cosine of latitude)
self.cell_areas = np.cos(self.latitudes) * self.dlat
# Temperature state
self.temperatures = np.zeros(self.n_lat)
# Albedo field (latitude-dependent)
self.albedo = np.zeros(self.n_lat)
self._initialize_albedo()
# Heat capacity per unit area (J m^-2 K^-1)
self.heat_capacity = planetary_params.effective_heat_capacity
# Diffusion coefficient for meridional heat transport
self.D = atmospheric_params.heat_transport_coeff
def _initialize_albedo(self):
"""Set initial albedo based on surface type"""
# Base albedo from surface/ocean mix
base_albedo = (self.planet.ocean_fraction * self.planet.ocean_albedo +
(1 - self.planet.ocean_fraction) * self.planet.surface_albedo)
self.albedo = np.full(self.n_lat, base_albedo)
def update_albedo_temperature_feedback(self, temperatures: np.ndarray) -> np.ndarray:
"""
Update albedo based on temperature (ice-albedo feedback).
Parameters:
temperatures: Current temperature field (K)
Returns:
Updated albedo field
"""
T_freeze = 273.15
T_range = 20 # Temperature range for albedo transition
# Ice cover fraction (smooth transition)
ice_fraction = np.clip((T_freeze - temperatures) / T_range, 0, 1)
# Blended albedo
base_albedo = (self.planet.ocean_fraction * self.planet.ocean_albedo +
(1 - self.planet.ocean_fraction) * self.planet.surface_albedo)
new_albedo = (1 - ice_fraction) * base_albedo + ice_fraction * self.planet.ice_albedo
# Apply feedback strength modifier
feedback = self.atmosphere.ice_albedo_feedback
self.albedo = self.albedo + feedback * (new_albedo - self.albedo)
return self.albedo
def calculate_greenhouse_effect(self, temperature: float) -> float:
"""
Calculate effective emissivity from greenhouse effect.
Uses simplified parameterization based on surface temperature
and atmospheric composition.
"""
# Base greenhouse effect from CO2 and H2O
# Simplified: ε = 1 / (1 + τ_IR) where τ_IR is IR optical depth
# CO2 contribution (logarithmic)
co2_optical_depth = 0.1 * np.log10(self.planet.co2_partial_pressure + 1e-6)
# H2O contribution (exponential with temperature - Clausius-Clapeyron)
saturation_vapor_pressure = 611 * np.exp(17.67 * (temperature - 273.15) /
(temperature - 29.65))
h2o_optical_depth = 0.5 * (saturation_vapor_pressure / 1e4) ** 0.5
total_optical_depth = (co2_optical_depth + h2o_optical_depth) * self.atmosphere.greenhouse_factor
emissivity = 1 / (1 + total_optical_depth)
return np.clip(emissivity, 0.3, 0.99)
def absorbed_stellar_flux(self, insolation: float, latitude_idx: int) -> float:
"""Calculate absorbed stellar radiation at given latitude"""
return insolation * (1 - self.albedo[latitude_idx])
def outgoing_longwave_radiation(self, temperature: float) -> float:
"""Calculate outgoing longwave radiation"""
emissivity = self.calculate_greenhouse_effect(temperature)
return emissivity * STEFAN_BOLTZMANN * temperature**4
def meridional_heat_transport(self, temperatures: np.ndarray) -> np.ndarray:
"""
Calculate meridional heat transport using diffusion approximation.
Divergence of heat flux = D * ∇²T
"""
transport = np.zeros_like(temperatures)
for i in range(self.n_lat):
# Laplacian in spherical coordinates
cos_lat = np.cos(self.latitudes[i])
if i == 0:
# South pole: one-sided difference
d2T = (temperatures[i+1] - temperatures[i]) / self.dlat**2
elif i == self.n_lat - 1:
# North pole: one-sided difference
d2T = (temperatures[i-1] - temperatures[i]) / self.dlat**2
else:
# Interior points: central difference with metric terms
dT_dlat = (temperatures[i+1] - temperatures[i-1]) / (2 * self.dlat)
d2T_dlat2 = (temperatures[i+1] - 2*temperatures[i] +
temperatures[i-1]) / self.dlat**2
# Full Laplacian in spherical coordinates
d2T = d2T_dlat2 - np.tan(self.latitudes[i]) * dT_dlat
transport[i] = self.D * d2T / cos_lat**2
return transport
def rhs(self, t: float, T: np.ndarray) -> np.ndarray:
"""
Right-hand side of the energy balance equation.
dT/dt = [ASR - OLR + Transport] / C
Parameters:
t: Time (fraction of orbital period)
T: Temperature field (K)
Returns:
Temperature tendency (K/s)
"""
# Update albedo
self.update_albedo_temperature_feedback(T)
# Get current orbital position
r, nu, _ = self.insolation_model.orbital_mechanics.get_position(t)
S = self.insolation_model.instantaneous_insolation(r)
# Calculate fluxes at each latitude
dTdt = np.zeros_like(T)
for i, lat in enumerate(self.latitudes):
# Daily-mean insolation at this latitude
S_daily = self.insolation_model.daily_mean_insolation(lat, nu)
# Absorbed stellar radiation
ASR = S_daily * (1 - self.albedo[i])
# Outgoing longwave radiation
OLR = self.outgoing_longwave_radiation(T[i])
# Net radiative forcing
net_radiation = ASR - OLR
dTdt[i] = net_radiation
# Add meridional heat transport
transport = self.meridional_heat_transport(T)
dTdt += transport
# Divide by heat capacity
dTdt /= self.heat_capacity
return dTdt
def integrate(self,
t_span: Tuple[float, float],
initial_temperatures: Optional[np.ndarray] = None,
method: str = 'RK45') -> dict:
"""
Integrate the energy balance model over time.
Parameters:
t_span: (t_start, t_end) in orbital period fractions
initial_temperatures: Initial temperature field (K)
method: Integration method
Returns:
Dictionary with solution
"""
if initial_temperatures is None:
# Initialize with equilibrium temperature estimate
S_mean = self.insolation_model.mean_annual_insolation()
T_eq = ((S_mean * (1 - np.mean(self.albedo))) /
(STEFAN_BOLTZMANN * 0.6)) ** 0.25
initial_temperatures = np.full(self.n_lat, T_eq)
self.temperatures = initial_temperatures.copy()
# Convert time to seconds for proper integration
P = self.orbital.orbital_period_seconds
t_span_seconds = (t_span[0] * P, t_span[1] * P)
# Time points for output (in orbital period fraction)
t_eval = np.linspace(t_span[0], t_span[1], 1000)
t_eval_seconds = t_eval * P
# Integrate with adaptive timestep
solution = solve_ivp(
lambda t_s, T: self.rhs(t_s / P, T),
t_span_seconds,
self.temperatures,
method=method,
t_eval=t_eval_seconds,
max_step=P/100, # At least 100 steps per orbit
rtol=1e-6,
atol=1e-8
)
return {
'time_fraction': solution.t / P,
'temperatures': solution.y,
'latitudes': self.latitudes,
'success': solution.success,
'message': solution.message
}
def run_to_equilibrium(self,
n_orbits: int = 50,
convergence_threshold: float = 0.1) -> dict:
"""
Run model until thermal equilibrium is reached.
Parameters:
n_orbits: Maximum number of orbits to simulate
convergence_threshold: Temperature change threshold (K/orbit)
Returns:
Solution dictionary
"""
# Initialize
S_mean = self.insolation_model.mean_annual_insolation()
T_init = ((S_mean * (1 - np.mean(self.albedo))) /
(STEFAN_BOLTZMANN * 0.6)) ** 0.25
T = np.full(self.n_lat, T_init)
all_times = []
all_temps = []
for orbit in range(n_orbits):
# Store initial temperatures
T_start = T.copy()
# Integrate one orbit
result = self.integrate((orbit, orbit + 1), T)
T = result['temperatures'][:, -1]
all_times.extend(result['time_fraction'])
all_temps.extend(result['temperatures'].T.tolist())
# Check convergence
max_change = np.max(np.abs(T - T_start))
if max_change < convergence_threshold:
print(f"Equilibrium reached after {orbit + 1} orbits")
break
return {
'time_fraction': np.array(all_times),
'temperatures': np.array(all_temps).T,
'latitudes': self.latitudes,
'convergence_orbits': orbit + 1
}
# =============================================================================
# Atmospheric Response Module
# =============================================================================
class AtmosphericResponse:
"""
Models atmospheric response to varying insolation including:
- Thermal inertia effects
- Atmospheric collapse potential
- Cloud feedback
- Weather patterns
"""
def __init__(self,
energy_balance_model: EnergyBalanceModel,
planetary_params: PlanetaryParameters):
self.ebm = energy_balance_model
self.planet = planetary_params
def thermal_response_timescale(self) -> float:
"""
Calculate thermal response timescale.
τ = C / (4 * ε * σ * T³)
Returns:
Timescale in seconds
"""
C = self.planet.effective_heat_capacity
T = 273 # Reference temperature
epsilon = 0.6 # Reference emissivity
tau = C / (4 * epsilon * STEFAN_BOLTZMANN * T**3)
return tau
def thermal_inertia_parameter(self) -> float:
"""
Calculate thermal inertia parameter (dimensionless).
γ = τ / P_orbit
γ << 1: Rapid equilibration (temperatures follow insolation)
γ >> 1: Slow response (temperatures nearly constant)
"""
tau = self.thermal_response_timescale()
P = self.ebm.orbital.orbital_period_seconds
return tau / P
def temperature_amplitude_damping(self) -> Tuple[float, float]:
"""
Calculate amplitude damping due to thermal inertia.
For sinusoidal forcing with thermal inertia γ:
- Amplitude ratio: 1 / sqrt(1 + γ²)
- Phase lag: arctan(γ)
Returns:
(amplitude_ratio, phase_lag_radians)
"""
gamma = self.thermal_inertia_parameter()
amp_ratio = 1 / np.sqrt(1 + (2*np.pi*gamma)**2)
phase_lag = np.arctan(2*np.pi*gamma)
return amp_ratio, phase_lag
def atmospheric_stability(self,
temperatures: np.ndarray,
pressures: np.ndarray) -> np.ndarray:
"""
Calculate atmospheric static stability.
dT/dz < -g/cp : Convectively unstable
dT/dz > 0 : Stratified stable
Parameters:
temperatures: Temperature profile (K)
pressures: Pressure levels (Pa)
Returns:
Stability parameter (negative = unstable)
"""
# Calculate altitude from pressure (hydrostatic)
# Using scale height approximation
H = 8500 # Scale height in m (for Earth-like)
# Temperature gradient
dT_dp = np.gradient(temperatures, pressures)
dT_dz = -dT_dp * pressures / H
# Dry adiabatic lapse rate
gamma_d = self.planet.surface_gravity / AIR_HEAT_CAPACITY
stability = gamma_d + dT_dz
return stability
def atmospheric_collapse_pressure(self,
temperature: float,
volatile: str = 'CO2') -> float:
"""
Calculate condensation pressure for atmospheric volatiles.
If surface pressure drops below this, atmosphere will collapse.
Parameters:
temperature: Surface temperature (K)
volatile: Type of volatile ('CO2', 'N2', 'H2O')
Returns:
Condensation pressure (Pa)
"""
if volatile == 'CO2':
# CO2 vapor pressure (Antoine equation, approximate)
# log10(P) = A - B/(T + C) with P in bar
A, B, C = 6.81228, 1301.679, -3.494
P_bar = 10 ** (A - B / (temperature + C))
return P_bar * 1e5 # Convert to Pa
elif volatile == 'N2':
# N2 vapor pressure
if temperature < 63.15: # Below N2 freezing point
return 0
A, B, C = 3.7362, 264.651, -6.788
P_bar = 10 ** (A - B / (temperature + C))
return P_bar * 1e5
elif volatile == 'H2O':
# Clausius-Clapeyron for water
return 611 * np.exp(17.67 * (temperature - 273.15) / (temperature - 29.65))
return 0
def check_atmospheric_collapse(self,
temperature_series: np.ndarray) -> dict:
"""
Check for potential atmospheric collapse conditions.
Parameters:
temperature_series: Global mean temperature over orbit (K)
Returns:
Dictionary with collapse analysis
"""
T_min = np.min(temperature_series)
T_max = np.max(temperature_series)
T_mean = np.mean(temperature_series)
# Check collapse pressures
co2_collapse_p = self.atmospheric_collapse_pressure(T_min, 'CO2')
n2_collapse_p = self.atmospheric_collapse_pressure(T_min, 'N2')
surface_p = self.planet.surface_pressure * 1e5 # Convert bar to Pa
# Risk assessment
co2_risk = co2_collapse_p / (surface_p * self.planet.co2_partial_pressure /
self.planet.surface_pressure)
n2_risk = n2_collapse_p / (surface_p * self.planet.n2_partial_pressure /
self.planet.surface_pressure)
return {
'temperature_min': T_min,
'temperature_max': T_max,
'temperature_mean': T_mean,
'co2_collapse_pressure_Pa': co2_collapse_p,
'n2_collapse_pressure_Pa': n2_collapse_p,
'co2_collapse_risk': co2_risk, # >1 means collapse possible
'n2_collapse_risk': n2_risk,
'collapse_possible': co2_risk > 1 or n2_risk > 1
}
def cloud_feedback_analysis(self,
temperatures: np.ndarray) -> np.ndarray:
"""
Estimate cloud feedback on temperature.
Simple parameterization: cloud fraction increases with
evaporation (temperature-dependent).
Parameters:
temperatures: Temperature field (K)
Returns:
Cloud-induced albedo perturbation
"""
# Cloud fraction (simplified)
# Based on Clausius-Clapeyron: water vapor ~ exp(0.07 * T)
T_ref = 288 # Reference temperature
cloud_fraction = 0.5 * np.exp(0.02 * (temperatures - T_ref))
cloud_fraction = np.clip(cloud_fraction, 0.1, 0.9)
# Cloud albedo effect (high clouds warm, low clouds cool)
# Simplified: net cooling effect proportional to cloud fraction
cloud_albedo = 0.3 * cloud_fraction * self.atmosphere.cloud_feedback
return cloud_albedo
# =============================================================================
# Habitability Metrics Module
# =============================================================================
class HabitabilityMetrics:
"""
Quantitative metrics for planetary habitability assessment.
"""
def __init__(self,
energy_balance_model: EnergyBalanceModel,
atmospheric_response: AtmosphericResponse):
self.ebm = energy_balance_model
self.atm = atmospheric_response
def liquid_water_fraction(self,
temperatures: np.ndarray) -> float:
"""
Calculate fraction of planet with liquid water temperatures.
Parameters:
temperatures: Temperature field (K)
Returns:
Fraction (0 to 1)
"""
T_freeze = 273.15
T_boil = 373.15
# Account for pressure effect on boiling point
P_surface = self.ebm.planet.surface_pressure
T_boil_adjusted = T_boil + 3 * (P_surface - 1) # ~3K per bar
liquid_mask = (temperatures > T_freeze) & (temperatures < T_boil_adjusted)
# Weight by area
areas = self.ebm.cell_areas
liquid_fraction = np.sum(areas[liquid_mask]) / np.sum(areas)
return liquid_fraction
def habitability_index_time_series(self,
temperature_series: np.ndarray) -> np.ndarray:
"""
Calculate habitability index over time.
H = (fraction with liquid water) * (biological activity factor)
Parameters:
temperature_series: Temperature evolution (n_times x n_lat)
Returns:
Habitability index over time
"""
n_times = temperature_series.shape[1]
H = np.zeros(n_times)
for t in range(n_times):
T = temperature_series[:, t]
# Liquid water fraction
f_water = self.liquid_water_fraction(T)
# Temperature suitability (peaks at ~300K)
T_opt = 300
T_width = 30
T_suitability = np.exp(-((T - T_opt) / T_width)**2)
# Average suitability weighted by area
suitability = np.sum(self.ebm.cell_areas * T_suitability) / np.sum(self.ebm.cell_areas)
# Combined habitability
H[t] = f_water * suitability
return H
def kempton_eccentric_habitable_index(self) -> float:
"""
Calculate the Kempton et al. (2022) eccentric habitable index.
KEH = (fraction of orbit with habitable surface conditions)
Returns:
KEH index (0 to 1)
"""
# Run simulation
result = self.ebm.run_to_equilibrium(n_orbits=20)
T_series = result['temperatures']
times = result['time_fraction']
# Calculate habitable fraction at each timestep
n_times = len(times)
habitable_mask = np.zeros(n_times, dtype=bool)
for t in range(n_times):
T = T_series[:, t]
T_mean_global = np.sum(self.ebm.cell_areas * T) / np.sum(self.ebm.cell_areas)
# Check habitability criteria
has_liquid_water = self.liquid_water_fraction(T) > 0.1
not_too_hot = T_mean_global < 373
not_frozen = T_mean_global > 273
habitable_mask[t] = has_liquid_water and not_too_hot and not_frozen
# Fraction of orbit habitable
KEH = np.sum(habitable_mask) / n_times
return KEH
def classical_habitable_zone_check(self) -> dict:
"""
Check if planet is within classical habitable zone.
Based on Kopparapu et al. (2013) boundaries.
Returns:
Dictionary with HZ analysis
"""
a = self.ebm.orbital.semi_major_axis
e = self.ebm.orbital.eccentricity
L = self.ebm.stellar.luminosity
# Inner HZ (Runaway greenhouse)
S_inner = 1.107 # Solar flux at inner edge for Sun-like star
a_inner = np.sqrt(L / S_inner)
# Outer HZ (Maximum greenhouse)
S_outer = 0.356
a_outer = np.sqrt(L / S_outer)
# For eccentric orbit, check both periapsis and apoapsis
r_peri = self.ebm.orbital.periapsis
r_apo = self.ebm.orbital.apoapsis
return {
'inner_hz_au': a_inner,
'outer_hz_au': a_outer,
'semi_major_axis_au': a,
'periapsis_au': r_peri,
'apoapsis_au': r_apo,
'always_in_hz': (r_peri >= a_inner) and (r_apo <= a_outer),
'sometimes_in_hz': (r_apo >= a_inner) and (r_peri <= a_outer),
'never_in_hz': (r_apo < a_inner) or (r_peri > a_outer),
'fraction_in_hz': self._calculate_hz_fraction(a_inner, a_outer)
}
def _calculate_hz_fraction(self, a_inner: float, a_outer: float) -> float:
"""Calculate fraction of orbit spent in habitable zone"""
e = self.ebm.orbital.eccentricity
a = self.ebm.orbital.semi_major_axis
# Find true anomaly where r = a_inner and r = a_outer
def r_from_nu(nu):
return a * (1 - e**2) / (1 + e * np.cos(nu))
# Solve for anomalies at HZ boundaries
try:
nu_inner = brentq(lambda nu: r_from_nu(nu) - a_inner, 0, np.pi)
except:
nu_inner = np.pi if r_from_nu(0) > a_inner else 0
try:
nu_outer = brentq(lambda nu: r_from_nu(nu) - a_outer, 0, np.pi)
except:
nu_outer = 0 if r_from_nu(np.pi) > a_outer else np.pi
# Fraction of orbit in HZ (symmetric about perihelion)
fraction = (nu_outer - nu_inner) / np.pi
return np.clip(fraction, 0, 1)
def temperature_variability_index(self,
temperature_series: np.ndarray) -> dict:
"""
Calculate temperature variability metrics.
Parameters:
temperature_series: Temperature evolution
Returns:
Dictionary with variability metrics
"""
# Global mean temperature over time
T_global = np.sum(self.ebm.cell_areas[:, np.newaxis] * temperature_series,
axis=0) / np.sum(self.ebm.cell_areas)
T_mean = np.mean(T_global)
T_range = np.max(T_global) - np.min(T_global)
T_std = np.std(T_global)
# Rate of temperature change
dT_dt = np.gradient(T_global)
max_warming_rate = np.max(dT_dt)
max_cooling_rate = np.min(dT_dt)
# Extreme temperature frequency
heat_stress = np.sum(T_global > 320) / len(T_global)
cold_stress = np.sum(T_global < 260) / len(T_global)
return {
'mean_temperature_K': T_mean,
'temperature_range_K': T_range,
'temperature_std_K': T_std,
'max_warming_rate_K_per_day': max_warming_rate * 365,
'max_cooling_rate_K_per_day': max_cooling_rate * 365,
'heat_stress_fraction': heat_stress,
'cold_stress_fraction': cold_stress
}
def comprehensive_habitability_assessment(self) -> dict:
"""
Perform comprehensive habitability assessment.
Returns:
Dictionary with all habitability metrics
"""
print("Running equilibrium simulation...")
result = self.ebm.run_to_equilibrium(n_orbits=30, convergence_threshold=0.5)
T_series = result['temperatures']
print("Calculating habitability metrics...")
# Classical HZ check
hz_check = self.classical_habitable_zone_check()
# Atmospheric stability
atm_analysis = self.atm.check_atmospheric_collapse(
np.mean(T_series, axis=0)
)
# Temperature variability
temp_var = self.temperature_variability_index(T_series)
# Habitability index time series
H_series = self.habitability_index_time_series(T_series)
# Summary metrics
assessment = {
'orbital_parameters': {
'semi_major_axis_au': self.ebm.orbital.semi_major_axis,
'eccentricity': self.ebm.orbital.eccentricity,
'obliquity_deg': self.ebm.orbital.obliquity,
'orbital_period_years': self.ebm.orbital.orbital_period
},
'habitable_zone_analysis': hz_check,
'atmospheric_stability': atm_analysis,
'temperature_variability': temp_var,
'habitability_metrics': {
'mean_habitability_index': float(np.mean(H_series)),
'min_habitability_index': float(np.min(H_series)),
'max_habitability_index': float(np.max(H_series)),
'liquid_water_fraction_mean': float(np.mean([
self.liquid_water_fraction(T_series[:, t])
for t in range(T_series.shape[1])
]))
},
'simulation_results': {
'equilibrium_orbits': result['convergence_orbits'],
'final_global_mean_temperature_K': float(
np.sum(self.ebm.cell_areas * T_series[:, -1]) /
np.sum(self.ebm.cell_areas)
)
}
}
return assessment
# =============================================================================
# Observational Signatures Module
# =============================================================================
class ObservationalSignatures:
"""
Predicts observational signatures for eccentric exoplanets.
"""
def __init__(self,
energy_balance_model: EnergyBalanceModel,
stellar_params: StellarParameters):
self.ebm = energy_balance_model
self.stellar = stellar_params
def thermal_emission_phase_curve(self,
temperature_series: np.ndarray,
times: np.ndarray) -> dict:
"""
Calculate thermal emission phase curve.
Parameters:
temperature_series: Temperature evolution (n_lat x n_times)
times: Time fractions
Returns:
Dictionary with phase curve data
"""
n_times = len(times)
# Calculate emitted flux at each timestep
F_thermal = np.zeros(n_times)
for t in range(n_times):
T = temperature_series[:, t]
# Stefan-Boltzmann emission
emissivity = np.array([self.ebm.calculate_greenhouse_effect(Ti)
for Ti in T])
F = emissivity * STEFAN_BOLTZMANN * T**4
# Global average (area-weighted)
F_thermal[t] = np.sum(self.ebm.cell_areas * F) / np.sum(self.ebm.cell_areas)
# Normalize to peak
F_normalized = F_thermal / np.max(F_thermal)
# Calculate phase curve amplitude
amplitude = (np.max(F_thermal) - np.min(F_thermal)) / np.mean(F_thermal)
# Find phase of peak emission (hot spot offset)
peak_phase = times[np.argmax(F_thermal)]
return {
'time_fraction': times,
'thermal_flux_W_m2': F_thermal,
'normalized_flux': F_normalized,
'amplitude': amplitude,
'peak_phase': peak_phase,
'hot_spot_offset_deg': (peak_phase - 0) * 360 # Offset from periastron
}
def secondary_eclipse_depth(self,
temperature: np.ndarray,
wavelength_um: float = 10.0) -> float:
"""
Calculate secondary eclipse depth at given wavelength.
δ = F_planet / F_star
Parameters:
temperature: Temperature field (K)
wavelength_um: Observation wavelength (micrometers)
Returns:
Eclipse depth (dimensionless)
"""
# Planet thermal emission (Planck function)
T_planet = np.sum(self.ebm.cell_areas * temperature) / np.sum(self.ebm.cell_areas)
# Simplified Planck function
def planck(T, wavelength_m):
h = 6.626e-34
c = 3e8
k = 1.38e-23
x = h * c / (wavelength_m * k * T)
if x > 700: # Avoid overflow
return 0
return (2 * h * c**2 / wavelength_m**5) / (np.exp(x) - 1)
wavelength_m = wavelength_um * 1e-6
B_planet = planck(T_planet, wavelength_m)
B_star = planck(self.stellar.effective_temp, wavelength_m)
# Planet radius ratio
R_planet = self.ebm.planet.radius * 6.371e6 # m
R_star = self.stellar.radius * 6.96e8 # m
# Eclipse depth
depth = (R_planet / R_star)**2 * B_planet / B_star
return depth
def spectral_feature_variations(self,
temperature_series: np.ndarray,
times: np.ndarray) -> dict:
"""
Calculate time-varying spectral features.
Focus on key biosignature/bulk atmosphere features.
Returns:
Dictionary with spectral variation data
"""
n_times = len(times)
# Key spectral features
features = {
'time_fraction': times,
'CO2_15um_depth': np.zeros(n_times),
'H2O_6um_depth': np.zeros(n_times),
'O3_9um_depth': np.zeros(n_times),
'blackbody_temperature_K': np.zeros(n_times)
}
for t in range(n_times):
T = temperature_series[:, t]
T_global = np.sum(self.ebm.cell_areas * T) / np.sum(self.ebm.cell_areas)
# Estimate feature depths (simplified)
# Feature depth scales with temperature and abundance
# CO2 at 15 μm
pCO2 = self.ebm.planet.co2_partial_pressure
features['CO2_15um_depth'][t] = 1 - np.exp(-pCO2 * 10 / T_global)
# H2O at 6 μm (temperature-dependent abundance)
e_sat = 611 * np.exp(17.67 * (T_global - 273.15) / (T_global - 29.65))
features['H2O_6um_depth'][t] = 1 - np.exp(-e_sat / 1e4)
# O3 (if present, assumed constant for now)
features['O3_9um_depth'][t] = 0.1 # Placeholder
# Effective blackbody temperature
features['blackbody_temperature_K'][t] = T_global
return features
def transit_timing_variations(self) -> dict:
"""
Calculate transit timing variations for eccentric orbit.
For eccentric orbit, transit timing deviates from strictly periodic
due to varying orbital speed.
Returns:
Dictionary with TTV parameters
"""
e = self.ebm.orbital.eccentricity
a = self.ebm.orbital.semi_major_axis
P = self.ebm.orbital.orbital_period
# Argument of perihelion
omega = np.radians(self.ebm.orbital.argument_of_perihelion)
# True anomaly at transit (when planet crosses line of sight)
# For circular orbit, this would be π/2 or 3π/2
# For eccentric orbit, need to solve for transit condition
# Simplified: maximum TTV amplitude
# TTV_max ≈ (P/2π) * e * cos(ω)
TTV_amplitude_days = (P * 365.25 / (2 * np.pi)) * e * np.abs(np.cos(omega))
# Duration variations
# Transit duration changes due to varying orbital velocity
# T_dur ∝ 1/v_orbital ∝ r
duration_ratio = (1 + e) / (1 - e) # Ratio of max to min duration
return {
'ttv_amplitude_days': TTV_amplitude_days,
'duration_variation_factor': duration_ratio,
'period_days': P * 365.25,
'eccentricity_signature': e
}
def generate_observable_predictions(self,
temperature_series: np.ndarray,
times: np.ndarray) -> dict:
"""
Generate complete set of observational predictions.
Returns:
Dictionary with all observable quantities
"""
print("Computing thermal phase curve...")
phase_curve = self.thermal_emission_phase_curve(temperature_series, times)
print("Computing spectral variations...")
spectral = self.spectral_feature_variations(temperature_series, times)
print("Computing TTV predictions...")
ttv = self.transit_timing_variations()
# Secondary eclipse depths at different phases
print("Computing eclipse depths...")
eclipse_depths = {
'periastron': self.secondary_eclipse_depth(
temperature_series[:, np.argmin(times)]),
'apoastron': self.secondary_eclipse_depth(
temperature_series[:, np.argmax(times)]),
'average': self.secondary_eclipse_depth(
np.mean(temperature_series, axis=1))
}
return {
'phase_curve': phase_curve,
'spectral_variations': spectral,
'transit_timing': ttv,
'eclipse_depths': eclipse_depths,
'observability_summary': {
'phase_curve_amplitude_percent': phase_curve['amplitude'] * 100,
'hot_spot_offset_deg': phase_curve['hot_spot_offset_deg'],
'max_secondary_eclipse_depth_ppm': max(eclipse_depths.values()) * 1e6,
'ttv_amplitude_minutes': ttv['ttv_amplitude_days'] * 24 * 60
}
}
# =============================================================================
# Main Model Runner
# =============================================================================
class PlanetaryEnergyBalanceModel:
"""
Master class that integrates all model components.
"""
def __init__(self,
stellar_params: StellarParameters,
orbital_params: OrbitalParameters,
planetary_params: PlanetaryParameters,
atmospheric_params: AtmosphericParameters):
self.stellar = stellar_params
self.orbital = orbital_params
self.planet = planetary_params
self.atmosphere = atmospheric_params
# Initialize components
self.insolation = InsolationModel(stellar_params, orbital_params)
self.ebm = EnergyBalanceModel(stellar_params, orbital_params,
planetary_params, atmospheric_params)
self.atm_response = AtmosphericResponse(self.ebm, planetary_params)
self.habitability = HabitabilityMetrics(self.ebm, self.atm_response)
self.observations = ObservationalSignatures(self.ebm, stellar_params)
# Storage for results
self.simulation_results = None
self.habitability_assessment = None
self.observable_predictions = None
def run_simulation(self,
n_orbits: int = 30,
convergence_threshold: float = 0.5) -> dict:
"""
Run complete simulation.
Returns:
Dictionary with all simulation results
"""
print("=" * 60)
print("PLANETARY ENERGY BALANCE MODEL")
print("=" * 60)
print(f"\nOrbital Configuration:")
print(f" Semi-major axis: {self.orbital.semi_major_axis:.3f} AU")
print(f" Eccentricity: {self.orbital.eccentricity:.3f}")
print(f" Periapsis: {self.orbital.periapsis:.3f} AU")
print(f" Apoapsis: {self.orbital.apoapsis:.3f} AU")
print(f" Orbital period: {self.orbital.orbital_period:.2f} years")
S_max, S_min, S_mean = self.insolation.insolation_variation()
print(f"\nInsolation:")
print(f" Mean: {S_mean:.1f} W/m²")
print(f" Maximum (periapsis): {S_max:.1f} W/m²")
print(f" Minimum (apoapsis): {S_min:.1f} W/m²")
print(f" Variation factor: {S_max/S_min:.2f}")
# Run energy balance model
print("\nRunning energy balance simulation...")
self.simulation_results = self.ebm.run_to_equilibrium(
n_orbits=n_orbits,
convergence_threshold=convergence_threshold
)
# Habitability assessment
print("Assessing habitability...")
self.habitability_assessment = self.habitability.comprehensive_habitability_assessment()
# Observational predictions
print("Computing observational signatures...")
self.observable_predictions = self.observations.generate_observable_predictions(
self.simulation_results['temperatures'],
self.simulation_results['time_fraction']
)
return {
'simulation': self.simulation_results,
'habitability': self.habitability_assessment,
'observations': self.observable_predictions
}
def plot_results(self, save_path: Optional[str] = None):
"""
Generate comprehensive visualization of results.
"""
if self.simulation_results is None:
print("No simulation results to plot. Run simulation first.")
return
fig = plt.figure(figsize=(16, 12))
# Plot 1: Orbital configuration
ax1 = fig.add_subplot(2, 3, 1)
self._plot_orbit(ax1)
# Plot 2: Insolation time series
ax2 = fig.add_subplot(2, 3, 2)
self._plot_insolation(ax2)
# Plot 3: Temperature evolution
ax3 = fig.add_subplot(2, 3, 3)
self._plot_temperature_evolution(ax3)
# Plot 4: Temperature vs latitude
ax4 = fig.add_subplot(2, 3, 4)
self._plot_temperature_latitude(ax4)
# Plot 5: Phase curve
ax5 = fig.add_subplot(2, 3, 5)
self._plot_phase_curve(ax5)
# Plot 6: Habitability summary
ax6 = fig.add_subplot(2, 3, 6)
self._plot_habitability_summary(ax6)
plt.tight_layout()
if save_path:
plt.savefig(save_path, dpi=150, bbox_inches='tight')
print(f"Figure saved to {save_path}")
plt.show()
def _plot_orbit(self, ax):
"""Plot orbital configuration"""
theta = np.linspace(0, 2*np.pi, 1000)
e = self.orbital.eccentricity
a = self.orbital.semi_major_axis
r = a * (1 - e**2) / (1 + e * np.cos(theta))
x = r * np.cos(theta)
y = r * np.sin(theta)
ax.plot(x, y, 'b-', linewidth=2, label='Orbit')
ax.plot(0, 0, 'yo', markersize=15, label='Star')
ax.plot(self.orbital.periapsis, 0, 'go', markersize=10, label='Periapsis')
ax.plot(-self.orbital.apoapsis, 0, 'ro', markersize=10, label='Apoapsis')
# Habitable zone
hz_check = self.habitability.classical_habitable_zone_check()
theta_hz = np.linspace(0, 2*np.pi, 100)
ax.fill_between(theta_hz,
np.full_like(theta_hz, hz_check['inner_hz_au']),
np.full_like(theta_hz, hz_check['outer_hz_au']),
alpha=0.2, color='green', label='HZ')
ax.set_xlabel('X (AU)')
ax.set_ylabel('Y (AU)')
ax.set_title(f'Orbital Configuration (e={e:.2f})')
ax.set_aspect('equal')
ax.legend(loc='upper right', fontsize=8)
ax.grid(True, alpha=0.3)
def _plot_insolation(self, ax):
"""Plot insolation time series"""
insolation_data = self.insolation.generate_insolation_time_series(500)
ax.plot(insolation_data['time_fraction'],
insolation_data['insolation_normalized'],
'orange', linewidth=2)
ax.axhline(y=1, color='gray', linestyle='--', alpha=0.5)
ax.fill_between(insolation_data['time_fraction'],
insolation_data['insolation_normalized'],
alpha=0.3, color='orange')
ax.set_xlabel('Orbital Phase')
ax.set_ylabel('Insolation (normalized)')
ax.set_title('Time-Varying Insolation')
ax.set_xlim(0, 1)
ax.grid(True, alpha=0.3)
def _plot_temperature_evolution(self, ax):
"""Plot global mean temperature evolution"""
T_series = self.simulation_results['temperatures']
times = self.simulation_results['time_fraction']
# Global mean temperature
T_global = np.sum(self.ebm.cell_areas[:, np.newaxis] * T_series,
axis=0) / np.sum(self.ebm.cell_areas)
# Find last complete orbit
orbit_fraction = times % 1
last_orbit_mask = times > (times[-1] - 1)
ax.plot(orbit_fraction[last_orbit_mask],
T_global[last_orbit_mask],
'r-', linewidth=2)
# Mark habitable range
ax.axhline(y=273, color='blue', linestyle='--', alpha=0.5, label='Freezing')
ax.axhline(y=373, color='red', linestyle='--', alpha=0.5, label='Boiling')
ax.fill_between(orbit_fraction[last_orbit_mask], 273, 373,
alpha=0.1, color='green')
ax.set_xlabel('Orbital Phase')
ax.set_ylabel('Global Mean Temperature (K)')
ax.set_title('Temperature Evolution (Last Orbit)')
ax.set_xlim(0, 1)
ax.legend(loc='upper right', fontsize=8)
ax.grid(True, alpha=0.3)
def _plot_temperature_latitude(self, ax):
"""Plot temperature vs latitude"""
T_series = self.simulation_results['temperatures']
times = self.simulation_results['time_fraction']
lats_deg = np.degrees(self.simulation_results['latitudes'])
# Plot at different orbital phases
phases = [0, 0.25, 0.5, 0.75]
colors = ['blue', 'green', 'orange', 'red']
labels = ['Periapsis', 'Post-periapsis', 'Apoapsis', 'Pre-periapsis']
for phase, color, label in zip(phases, colors, labels):
idx = np.argmin(np.abs(times % 1 - phase))
ax.plot(lats_deg, T_series[:, idx], color=color,
linewidth=2, label=label)
ax.axhline(y=273, color='cyan', linestyle=':', alpha=0.5)
ax.set_xlabel('Latitude (degrees)')
ax.set_ylabel('Temperature (K)')
ax.set_title('Temperature vs Latitude')
ax.legend(loc='upper right', fontsize=8)
ax.grid(True, alpha=0.3)
def _plot_phase_curve(self, ax):
"""Plot thermal emission phase curve"""
if self.observable_predictions is None:
return
phase_data = self.observable_predictions['phase_curve']
ax.plot(phase_data['time_fraction'],
phase_data['normalized_flux'],
'purple', linewidth=2)
ax.fill_between(phase_data['time_fraction'],
phase_data['normalized_flux'],
alpha=0.3, color='purple')
ax.set_xlabel('Orbital Phase')
ax.set_ylabel('Normalized Thermal Emission')
ax.set_title(f'Phase Curve (Amp: {phase_data["amplitude"]*100:.1f}%)')
ax.set_xlim(0, 1)
ax.grid(True, alpha=0.3)
def _plot_habitability_summary(self, ax):
"""Plot habitability summary"""
if self.habitability_assessment is None:
return
hab = self.habitability_assessment['habitability_metrics']
hz = self.habitability_assessment['habitable_zone_analysis']
atm = self.habitability_assessment['atmospheric_stability']
# Create bar chart of key metrics
metrics = ['Mean\nHabitability', 'Liquid\nWater %', 'HZ\nFraction']
values = [
hab['mean_habitability_index'] * 100,
hab['liquid_water_fraction_mean'] * 100,
hz['fraction_in_hz'] * 100
]
colors = ['green' if v > 50 else 'orange' if v > 20 else 'red'
for v in values]
bars = ax.bar(metrics, values, color=colors, alpha=0.7, edgecolor='black')
ax.set_ylabel('Percentage')
ax.set_title('Habitability Metrics')
ax.set_ylim(0, 100)
ax.axhline(y=50, color='gray', linestyle='--', alpha=0.5)
# Add value labels
for bar, val in zip(bars, values):
ax.text(bar.get_x() + bar.get_width()/2, bar.get_height() + 2,
f'{val:.1f}%', ha='center', fontsize=10)
# Add text annotations
T_mean = self.habitability_assessment['temperature_variability']['mean_temperature_K']
T_range = self.habitability_assessment['temperature_variability']['temperature_range_K']
ax.text(0.02, 0.98, f"Mean T: {T_mean:.1f} K\nT range: {T_range:.1f} K",
transform=ax.transAxes, fontsize=9,
verticalalignment='top',
bbox=dict(boxstyle='round', facecolor='wheat', alpha=0.5))
# =============================================================================
# Example Usage and Demonstration
# =============================================================================
def create_earth_like_eccentric(eccentricity: float = 0.3) -> PlanetaryEnergyBalanceModel:
"""Create an Earth-like planet on an eccentric orbit"""
star = StellarParameters(
luminosity=1.0,
mass=1.0,
effective_temp=5778,
radius=1.0
)
orbit = OrbitalParameters(
semi_major_axis=1.0,
eccentricity=eccentricity,
obliquity=23.5,
argument_of_perihelion=0
)
planet = PlanetaryParameters(
radius=1.0,
mass=1.0,
surface_gravity=9.81,
rotation_period=24,
surface_pressure=1.0,
co2_partial_pressure=0.0004,
n2_partial_pressure=0.78,
h2o_column=25,
ocean_fraction=0.7,
land_heat_capacity=2e7,
ocean_depth_mixed_layer=50,
surface_albedo=0.3,
ocean_albedo=0.1,
ice_albedo=0.6
)
atmosphere = AtmosphericParameters(
greenhouse_factor=1.0,
heat_transport_coeff=1e6,
cloud_feedback=0.5,
ice_albedo_feedback=0.8
)
return PlanetaryEnergyBalanceModel(star, orbit, planet, atmosphere)
def create_m_dwarf_planet(eccentricity: float = 0.2) -> PlanetaryEnergyBalanceModel:
"""Create a planet orbiting an M-dwarf star"""
star = StellarParameters(
luminosity=0.01,
mass=0.3,
effective_temp=3300,
radius=0.3
)
orbit = OrbitalParameters(
semi_major_axis=0.1,
eccentricity=eccentricity,
obliquity=5,
argument_of_perihelion=90
)
planet = PlanetaryParameters(
radius=1.2,
mass=1.5,
surface_gravity=10.2,
rotation_period=240, # Tidally influenced
surface_pressure=1.5,
co2_partial_pressure=0.01,
n2_partial_pressure=1.0,
h2o_column=50,
ocean_fraction=0.8,
land_heat_capacity=2e7,
ocean_depth_mixed_layer=100,
surface_albedo=0.25,
ocean_albedo=0.08,
ice_albedo=0.55
)
atmosphere = AtmosphericParameters(
greenhouse_factor=1.2,
heat_transport_coeff=5e5,
cloud_feedback=0.3,
ice_albedo_feedback=0.6
)
return PlanetaryEnergyBalanceModel(star, orbit, planet, atmosphere)
def main():
"""Main demonstration function"""
print("\n" + "="*70)
print("EXOPLANETARY ENERGY BALANCE MODEL FOR ECCENTRIC ORBITS")
print("="*70)
# Example 1: Earth-like planet with moderate eccentricity
print("\n" + "-"*70)
print("EXAMPLE 1: Earth-like planet (e = 0.4)")
print("-"*70)
model1 = create_earth_like_eccentric(eccentricity=0.4)
results1 = model1.run_simulation(n_orbits=25)
# Print summary
print("\n" + "="*50)
print("HABITABILITY SUMMARY")
print("="*50)
hab1 = results1['habitability']['habitability_metrics']
print(f" Mean habitability index: {hab1['mean_habitability_index']:.3f}")
print(f" Mean liquid water fraction: {hab1['liquid_water_fraction_mean']*100:.1f}%")
obs1 = results1['observations']['observability_summary']
print("\n" + "="*50)
print("OBSERVATIONAL SIGNATURES")
print("="*50)
print(f" Phase curve amplitude: {obs1['phase_curve_amplitude_percent']:.1f}%")
print(f" Hot spot offset: {obs1['hot_spot_offset_deg']:.1f}°")
print(f" Secondary eclipse depth: {obs1['max_secondary_eclipse_depth_ppm']:.1f} ppm")
print(f" TTV amplitude: {obs1['ttv_amplitude_minutes']:.2f} minutes")
# Example 2: Highly eccentric orbit
print("\n" + "-"*70)
print("EXAMPLE 2: Earth-like planet with high eccentricity (e = 0.6)")
print("-"*70)
model2 = create_earth_like_eccentric(eccentricity=0.6)
results2 = model2.run_simulation(n_orbits=30)
hab2 = results2['habitability']['habitability_metrics']
print(f"\n Mean habitability index: {hab2['mean_habitability_index']:.3f}")
print(f" Mean liquid water fraction: {hab2['liquid_water_fraction_mean']*100:.1f}%")
# Example 3: M-dwarf planet
print("\n" + "-"*70)
print("EXAMPLE 3: M-dwarf planet (e = 0.2)")
print("-"*70)
model3 = create_m_dwarf_planet(eccentricity=0.2)
results3 = model3.run_simulation(n_orbits=20)
hab3 = results3['habitability']['habitability_metrics']
print(f"\n Mean habitability index: {hab3['mean_habitability_index']:.3f}")
print(f" Mean liquid water fraction: {hab3['liquid_water_fraction_mean']*100:.1f}%")
# Plot results for Example 1
print("\n" + "-"*70)
print("Generating visualizations...")
model1.plot_results()
# Comparative analysis
print("\n" + "="*70)
print("COMPARATIVE ANALYSIS: Eccentricity Impact on Habitability")
print("="*70)
eccentricities = [0.0, 0.2, 0.4, 0.6]
hab_indices = []
lw_fractions = []
for e in eccentricities:
model = create_earth_like_eccentric(eccentricity=e)
results = model.run_simulation(n_orbits=20)
hab = results['habitability']['habitability_metrics']
hab_indices.append(hab['mean_habitability_index'])
lw_fractions.append(hab['liquid_water_fraction_mean'])
print("\nEccentricity | Habitability | Liquid Water %")
print("-" * 45)
for e, h, lw in zip(eccentricities, hab_indices, lw_fractions):
print(f" {e:.1f} | {h:.3f} | {lw*100:.1f}%")
# Plot comparative results
fig, axes = plt.subplots(1, 2, figsize=(12, 4))
axes[0].plot(eccentricities, hab_indices, 'go-', linewidth=2, markersize=10)
axes[0].set_xlabel('Eccentricity')
axes[0].set_ylabel('Mean Habitability Index')
axes[0].set_title('Habitability vs Eccentricity')
axes[0].grid(True, alpha=0.3)
axes[1].plot(eccentricities, np.array(lw_fractions)*100, 'b^-',
linewidth=2, markersize=10)
axes[1].set_xlabel('Eccentricity')
axes[1].set_ylabel('Liquid Water Fraction (%)')
axes[1].set_title('Liquid Water Coverage vs Eccentricity')
axes[1].grid(True, alpha=0.3)
plt.tight_layout()
plt.savefig('eccentricity_comparison.png', dpi=150, bbox_inches='tight')
plt.show()
print("\n" + "="*70)
print("MODEL EXECUTION COMPLETE")
print("="*70)
if __name__ == "__main__":
main()
Key Model Components
1. Insolation Cycles
- Computes time-varying stellar flux using Kepler's equation
- Accounts for orbital mechanics with true anomaly conversion
- Includes diurnal and seasonal variations with obliquity
2. Atmospheric Response
- Energy balance with thermal inertia (mixed-layer ocean)
- Meridional heat transport via diffusion
- Ice-albedo feedback and greenhouse effect parameterization
- Atmospheric collapse detection for volatile condensation
3. Habitability Metrics
- Liquid water fraction (area-weighted)
- Time-integrated habitability index
- Classical HZ boundary analysis
- Temperature variability assessment
- Kempton Eccentric Habitable Index (KEH)
4. Observational Tests
- Thermal emission phase curves
- Secondary eclipse depth predictions
- Spectral feature variations
- Transit timing variations (TTV)
Physical Principles
The model solves:
C∂t∂T=S(1−α)
Where:
- C = Effective heat capacity (J m⁻² K⁻¹)
- S = Time-varying insolation (W m⁻²)
- α = Albedo (with temperature feedback)
- ε = Effective emissivity (greenhouse parameterization)
- D = Diffusion coefficient for heat transport