Create a sunspot magnetic field evolution study: vector magnetograms, flows, and flares.
- User
Create a sunspot magnetic field evolution study: vector magnetograms, flows, and flares.
Assistant
Create a sunspot magnetic field evolution study: vector magnetograms, flows, and flares.
The user wants a comprehensive sunspot magnetic field evolution study that includes:
Let me create a simulation that:
Physical laws to consider:
I'll create:
Let me write a comprehensive simulation: This is a fascinating solar physics challenge! I'll create a comprehensive sunspot magnetic field evolution study that incorporates:
Key physical principles:
"""
Sunspot Magnetic Field Evolution Study
======================================
Simulates vector magnetograms, photospheric flows, and flare activity
for an evolving active region.
Physical basis:
- Potential field + non-potential (sheared) components
- Evershed flow model in penumbra
- Magnetic free energy calculation for flare prediction
- Current helicity as proxy for magnetic complexity
"""
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import Normalize, LinearSegmentedColormap
from matplotlib.patches import Circle, Wedge
from matplotlib.animation import FuncAnimation
from mpl_toolkits.axes_grid1 import make_axes_locatable
from scipy.ndimage import gaussian_filter, sobel
from scipy.interpolate import RectBivariateSpline
import warnings
warnings.filterwarnings('ignore')
# Physical constants
MU0 = 4 * np.pi * 1e-7 # Vacuum permeability (H/m)
Gauss_to_Tesla = 1e-4
Mx_to_Wb = 1e-8 # Maxwell to Weber
class SunspotMagneticField:
"""
Models a sunspot's magnetic field evolution including:
- Vertical field (Bz) with umbra/penumbra structure
- Horizontal fields (Bx, By) from potential field assumption
- Non-potential (sheared) components developing over time
"""
def __init__(self, grid_size=200, field_of_view=100e3):
"""
Initialize the magnetic field model.
Parameters:
-----------
grid_size : int
Number of grid points in each dimension
field_of_view : float
Physical size of the domain in meters
"""
self.nx = grid_size
self.fov = field_of_view
self.dx = field_of_view / grid_size
# Create spatial grid
x = np.linspace(-self.fov/2, self.fov/2, self.nx)
y = np.linspace(-self.fov/2, self.fov/2, self.nx)
self.X, self.Y = np.meshgrid(x, y)
# Sunspot parameters (in meters)
self.umbra_radius = 8e6 # ~8 Mm typical umbra
self.penumbra_radius = 20e6 # ~20 Mm typical penumbra
# Initialize field components
self.Bx = np.zeros((self.nx, self.nx))
self.By = np.zeros((self.nx, self.nx))
self.Bz = np.zeros((self.nx, self.nx))
# Evolution parameters
self.time = 0 # Current time in seconds
self.shear_angle = 0 # Accumulated shear
self.twist_parameter = 0 # Magnetic twist
# Flare tracking
self.flare_events = []
self.free_energy_history = []
self.current_helicity_history = []
def calculate_vertical_field(self, time):
"""
Calculate the vertical magnetic field component Bz.
Uses a combination of:
1. Main positive polarity (leading spot)
2. Following negative polarity
3. Emerging flux over time
"""
r = np.sqrt(self.X**2 + self.Y**2)
# Main sunspot (positive polarity) - centered at origin
# Gaussian-like profile with sharp umbra and gradual penumbra
B0_pos = 2500 # Peak field in Gauss (typical sunspot)
Bz_pos = B0_pos * np.exp(-(r/self.penumbra_radius)**4)
# Add fine structure in penumbra (filaments)
theta = np.arctan2(self.Y, self.X)
n_filaments = 20
penumbral_modulation = 0.15 * np.sin(n_filaments * theta + time/3600)
in_penumbra = (r > self.umbra_radius) & (r < self.penumbra_radius)
Bz_pos[in_penumbra] *= (1 + penumbral_modulation[in_penumbra])
# Following spot (negative polarity) - offset position
x_offset = 35e6 # 35 Mm separation
y_offset = 5e6 # Slight latitudinal offset
r_neg = np.sqrt((self.X - x_offset)**2 + (self.Y - y_offset)**2)
B0_neg = -2000 # Slightly weaker following spot
penumbra_radius_neg = 15e6
Bz_neg = B0_neg * np.exp(-(r_neg/penumbra_radius_neg)**4)
# Emerging flux (bipolar region)
emergence_rate = 0.3 * (1 - np.exp(-time/(6*3600))) # 6-hour rise time
x_emerge = 15e6
r_emerge1 = np.sqrt((self.X + x_emerge)**2 + self.Y**2)
r_emerge2 = np.sqrt((self.X - x_emerge)**2 + self.Y**2)
Bz_emerge = 800 * emergence_rate * (
np.exp(-(r_emerge1/10e6)**2) - np.exp(-(r_emerge2/10e6)**2)
)
return Bz_pos + Bz_neg + Bz_emerge
def calculate_potential_field(self, Bz_surface):
"""
Calculate potential (current-free) horizontal field components.
For a potential field: ∇×B = 0 and ∇·B = 0
This gives Bx = -∂ψ/∂x, By = -∂ψ/∂y where ∇²ψ = -Bz
"""
# Use Fourier method for potential field
kx = np.fft.fftfreq(self.nx, self.dx) * 2 * np.pi
ky = np.fft.fftfreq(self.nx, self.dx) * 2 * np.pi
KX, KY = np.meshgrid(kx, ky)
K = np.sqrt(KX**2 + KY**2)
K[0, 0] = 1 # Avoid division by zero
# FFT of vertical field
Bz_fft = np.fft.fft2(Bz_surface)
# Potential field from Greens function method (simplified)
# Bx_pot = -ikx/k * Bz_fft, By_pot = -iky/k * Bz_fft
# Using decay with height factor
with np.errstate(divide='ignore', invalid='ignore'):
Bx_pot_fft = -1j * KX / K * Bz_fft * np.exp(-K * 1e6) # 1 Mm above
By_pot_fft = -1j * KY / K * Bz_fft * np.exp(-K * 1e6)
Bx_pot_fft[0, 0] = 0
By_pot_fft[0, 0] = 0
Bx_pot = np.real(np.fft.ifft2(Bx_pot_fft))
By_pot = np.real(np.fft.ifft2(By_pot_fft))
return Bx_pot, By_pot
def calculate_nonpotential_field(self, time):
"""
Calculate non-potential (sheared) field components.
The shear develops due to:
1. Differential rotation
2. Flux emergence with twist
3. Photospheric flows
"""
# Neutral line position (where Bz = 0)
# Shear develops along the polarity inversion line
r = np.sqrt(self.X**2 + self.Y**2)
theta = np.arctan2(self.Y, self.X)
# Shear angle increases with time (simulating differential rotation effect)
self.shear_angle = 30 * (1 - np.exp(-time/(12*3600))) # Max 30 degrees
shear_rad = np.deg2rad(self.shear_angle)
# Shear is strongest near the polarity inversion line
# and in the penumbra
PIL_region = np.exp(-(r - self.umbra_radius*1.5)**2 / (5e6)**2)
# Non-potential components (tangential to spot)
B_np_strength = 500 * np.sin(shear_rad) * PIL_region
# Direction along PIL (approximately y-direction for leading spot)
Bx_np = -B_np_strength * np.abs(self.X) / (np.abs(self.X) + 1e6)
By_np = B_np_strength * np.sign(self.X) * r / (r + 1e6)
# Add twist component (force-free field)
self.twist_parameter = 0.2 * (1 - np.exp(-time/(8*3600)))
alpha = self.twist_parameter / self.penumbra_radius # Force-free parameter
# Twist creates azimuthal component
B_twist = alpha * r * np.exp(-(r/self.penumbra_radius)**2)
Bx_twist = -B_twist * np.sin(theta)
By_twist = B_twist * np.cos(theta)
return Bx_np + Bx_twist, By_np + By_twist
def evolve(self, dt):
"""
Evolve the magnetic field by time step dt.
Parameters:
-----------
dt : float
Time step in seconds
"""
self.time += dt
# Update vertical field
self.Bz = self.calculate_vertical_field(self.time)
# Update horizontal fields
Bx_pot, By_pot = self.calculate_potential_field(self.Bz)
Bx_np, By_np = self.calculate_nonpotential_field(self.time)
# Total field
self.Bx = Bx_pot + Bx_np
self.By = By_pot + By_np
# Smooth fields
self.Bx = gaussian_filter(self.Bx, sigma=1)
self.By = gaussian_filter(self.By, sigma=1)
def calculate_current_density(self):
"""
Calculate vertical current density Jz = (1/μ0)(∂By/∂x - ∂Bx/∂y)
Returns:
--------
Jz : ndarray
Vertical current density in mA/m²
"""
dBx_dy = sobel(self.Bx, axis=0) / (8 * self.dx)
dBy_dx = sobel(self.By, axis=1) / (8 * self.dx)
Jz = (dBy_dx - dBx_dy) / MU0 # A/m²
Jz_mA = Jz * 1000 # Convert to mA/m²
return gaussian_filter(Jz_mA, sigma=2)
def calculate_current_helicity(self):
"""
Calculate current helicity Hc = Bz * Jz
This measures the twist and writhe of magnetic field lines.
High values indicate complex, flare-productive regions.
"""
Jz = self.calculate_current_density()
Hc = self.Bz * Jz * 1e-6 # G·mA/m² -> scaled units
return gaussian_filter(Hc, sigma=2)
def calculate_magnetic_free_energy(self):
"""
Calculate magnetic free energy: E_free = (1/2μ0)∫(B² - B_pot²)dV
This is the energy available for release in flares.
"""
# Potential field energy
Bx_pot, By_pot = self.calculate_potential_field(self.Bz)
B_pot_sq = Bx_pot**2 + By_pot**2 + self.Bz**2
# Total field energy
B_total_sq = self.Bx**2 + self.By**2 + self.Bz**2
# Free energy density
free_energy_density = (B_total_sq - B_pot_sq) / (2 * MU0)
# Integrate over area (simplified 2D integral)
# Multiply by characteristic height (10 Mm) for 3D estimate
height = 10e6 # meters
total_free_energy = np.sum(free_energy_density) * self.dx**2 * height
return total_free_energy # Joules
def calculate_flare_probability(self):
"""
Calculate flare probability based on magnetic parameters.
Uses:
- Free magnetic energy
- Current helicity
- Magnetic shear
- Flux imbalance
"""
free_energy = self.calculate_magnetic_free_energy()
Hc = self.calculate_current_helicity()
# Total unsigned current helicity
total_helicity = np.sum(np.abs(Hc)) * self.dx**2
# Magnetic flux imbalance
pos_flux = np.sum(self.Bz[self.Bz > 0]) * self.dx**2
neg_flux = np.sum(np.abs(self.Bz[self.Bz < 0])) * self.dx**2
imbalance = np.abs(pos_flux - neg_flux) / (pos_flux + neg_flux + 1e-10)
# Flare probability index (0-100)
energy_factor = min(free_energy / 1e25, 1) * 40 # Max 40 points
helicity_factor = min(total_helicity / 1e5, 1) * 30 # Max 30 points
shear_factor = self.shear_angle / 45 * 20 # Max 20 points
imbalance_factor = imbalance * 10 # Max 10 points
probability = energy_factor + helicity_factor + shear_factor + imbalance_factor
return np.clip(probability, 0, 100)
def check_for_flares(self):
"""
Check for flare occurrence and trigger events.
Flares occur when:
1. Free energy exceeds threshold
2. Rapid change in magnetic configuration
"""
free_energy = self.calculate_magnetic_free_energy()
probability = self.calculate_flare_probability()
# Flare threshold based on probability and random factor
# Higher probability = more likely to flare
random_factor = np.random.random() * 100
if probability > 60 and random_factor < probability * 0.3:
# Flare occurs!
flare_class = self._determine_flare_class(free_energy, probability)
flare_location = self._find_flare_location()
flare_event = {
'time': self.time,
'class': flare_class,
'location': flare_location,
'energy': free_energy,
'probability': probability
}
self.flare_events.append(flare_event)
# Post-flare: reduce free energy
self._apply_flare_effects()
return flare_event
return None
def _determine_flare_class(self, free_energy, probability):
"""Determine GOES flare class based on energy released."""
energy_log = np.log10(free_energy + 1)
if energy_log > 25 and probability > 80:
return 'X'
elif energy_log > 24.5 and probability > 70:
return 'M'
elif energy_log > 24 and probability > 50:
return 'C'
else:
return 'B'
def _find_flare_location(self):
"""Find the most likely flare location (near polarity inversion line)."""
# Find neutral line
Bz_smooth = gaussian_filter(self.Bz, sigma=3)
neutral_line_mask = np.abs(Bz_smooth) < 100
if np.any(neutral_line_mask):
# Find point with highest current
Jz = np.abs(self.calculate_current_density())
Jz_masked = Jz.copy()
Jz_masked[~neutral_line_mask] = 0
idx = np.unravel_index(np.argmax(Jz_masked), Jz.shape)
return (self.X[idx], self.Y[idx])
return (0, 0)
def _apply_flare_effects(self):
"""Apply post-flare changes to magnetic field."""
# Reduce non-potential component (energy release)
reduction = 0.3
self.Bx = self.Bx - reduction * (self.Bx - self.calculate_potential_field(self.Bz)[0])
self.By = self.By - reduction * (self.By - self.calculate_potential_field(self.Bz)[1])
# Reduce shear angle
self.shear_angle *= 0.7
class PlasmaFlowField:
"""
Models photospheric and near-photospheric plasma flows:
- Evershed flow in penumbra
- Moat flow outside sunspot
- Convective cells (supergranulation)
"""
def __init__(self, magnetic_field_model):
"""
Initialize flow field model.
Parameters:
-----------
magnetic_field_model : SunspotMagneticField
The magnetic field model to use
"""
self.mf = magnetic_field_model
# Flow parameters
self.evershed_speed = 2e3 # m/s typical Evershed flow
self.moat_speed = 0.5e3 # m/s moat flow
self.supergranule_speed = 0.3e3 # m/s supergranular flow
def calculate_flows(self, time):
"""
Calculate all flow components.
Parameters:
-----------
time : float
Current time in seconds
Returns:
--------
vx, vy : ndarray
Velocity components in m/s
"""
r = np.sqrt(self.mf.X**2 + self.mf.Y**2)
theta = np.arctan2(self.mf.Y, self.mf.X)
# 1. Evershed flow (radial outward in penumbra)
vx_evershed, vy_evershed = self._evershed_flow(r, theta, time)
# 2. Moat flow (radial outside spot)
vx_moat, vy_moat = self._moat_flow(r, theta, time)
# 3. Supergranulation pattern
vx_super, vy_super = self._supergranulation_flow(time)
# 4. Umbral oscillation
vx_umbra, vy_umbra = self._umbral_oscillation(r, time)
# Combine all flows
vx = vx_evershed + vx_moat + vx_super + vx_umbra
vy = vy_evershed + vy_moat + vy_super + vy_umbra
return vx, vy
def _evershed_flow(self, r, theta, time):
"""
Evershed flow: radially outward in penumbra.
Characteristics:
- Horizontal outflow
- Concentrated in dark penumbral filaments
- Time-variable
"""
# Radial profile: peaks in penumbra
in_penumbra = (r > self.mf.umbra_radius) & (r < self.mf.penumbra_radius)
# Flow magnitude profile
r_norm = (r - self.mf.umbra_radius) / (self.mf.penumbra_radius - self.mf.umbra_radius)
profile = np.sin(np.pi * r_norm) * in_penumbra
# Add filamentary structure (channeling along filaments)
n_filaments = 15
filament_pattern = 0.5 + 0.5 * np.sin(n_filaments * theta + time/1800)
profile *= filament_pattern
# Time variation (oscillatory component)
time_variation = 1 + 0.2 * np.sin(2 * np.pi * time / 1800) # 30-min period
speed = self.evershed_speed * profile * time_variation
vx = speed * np.cos(theta)
vy = speed * np.sin(theta)
return vx, vy
def _moat_flow(self, r, theta, time):
"""
Moat flow: systematic outward flow outside sunspot.
Extends to about one moat radius (~30 Mm) from spot center.
"""
moat_radius = 35e6 # m
# Profile: peaks at penumbra boundary, decreases outward
profile = np.exp(-((r - self.mf.penumbra_radius) / (moat_radius - self.mf.penumbra_radius))**2)
in_moat = (r >= self.mf.penumbra_radius) & (r < moat_radius)
profile *= in_moat
speed = self.moat_speed * profile
vx = speed * np.cos(theta)
vy = speed * np.sin(theta)
return vx, vy
def _supergranulation_flow(self, time):
"""
Supergranulation pattern: large-scale convective cells.
Uses a pattern of converging/diverging flows.
"""
# Supergranule parameters
cell_size = 30e6 # m (30 Mm typical)
lifetime = 24 * 3600 # 24 hours
# Create cellular pattern using cosine functions
phase_x = 2 * np.pi * self.mf.X / cell_size + time / lifetime * 2 * np.pi
phase_y = 2 * np.pi * self.mf.Y / cell_size + time / lifetime * 2 * np.pi * 0.7
# Divergent flow from cell centers
vx = self.supergranule_speed * np.sin(phase_x) * np.cos(phase_y)
vy = self.supergranule_speed * np.cos(phase_x) * np.sin(phase_y)
# Weaken inside sunspot
r = np.sqrt(self.mf.X**2 + self.mf.Y**2)
suppression = 1 - np.exp(-(r / self.mf.penumbra_radius)**4)
return vx * suppression, vy * suppression
def _umbral_oscillation(self, r, time):
"""
Umbral oscillations: 3-minute period oscillations in umbra.
These are magnetoacoustic waves trapped in the umbra.
"""
period = 180 # seconds (3 minutes)
omega = 2 * np.pi / period
# Amplitude profile: maximum in umbra center
amplitude = 0.3e3 * np.exp(-(r / self.mf.umbra_radius)**2)
# Radial oscillation
phase = omega * time
radial_component = amplitude * np.sin(phase)
# Convert to Cartesian (oscillating radial pattern)
theta = np.arctan2(self.mf.Y, self.mf.X)
vx = radial_component * np.cos(theta) * (r / (r + 1e6))
vy = radial_component * np.sin(theta) * (r / (r + 1e6))
return vx, vy
def get_doppler_velocity(self, vx, vy, line_of_sight_angle=0):
"""
Calculate Doppler velocity along line of sight.
Parameters:
-----------
vx, vy : ndarray
Horizontal velocity components
line_of_sight_angle : float
Angle from vertical in radians (0 = disk center)
Returns:
--------
v_los : ndarray
Line-of-sight velocity (positive = redshift/receding)
"""
# For simplicity, assume LOS is in x-z plane
v_los = vx * np.sin(line_of_sight_angle)
return v_los
class SunspotEvolutionStudy:
"""
Main class for running the sunspot evolution study.
"""
def __init__(self, duration_hours=24, cadence_minutes=10):
"""
Initialize the study.
Parameters:
-----------
duration_hours : float
Total duration of simulation in hours
cadence_minutes : float
Time between observations in minutes
"""
self.duration = duration_hours * 3600 # seconds
self.cadence = cadence_minutes * 60 # seconds
self.n_steps = int(self.duration / self.cadence)
# Initialize models
self.mf = SunspotMagneticField(grid_size=200, field_of_view=100e3)
self.flows = PlasmaFlowField(self.mf)
# Data storage
self.time_series = []
self.Bz_series = []
self.Bx_series = []
self.By_series = []
self.Jz_series = []
self.Hc_series = []
self.vx_series = []
self.vy_series = []
self.energy_series = []
self.helicity_series = []
self.probability_series = []
def run_simulation(self):
"""Run the complete simulation."""
print("Running sunspot magnetic field evolution simulation...")
print(f"Duration: {self.duration/3600:.1f} hours")
print(f"Cadence: {self.cadence/60:.1f} minutes")
print(f"Number of steps: {self.n_steps}")
for step in range(self.n_steps):
# Evolve magnetic field
self.mf.evolve(self.cadence)
# Check for flares
flare = self.mf.check_for_flares()
if flare:
print(f" FLARE at t={flare['time']/3600:.1f}h: Class {flare['class']}")
# Calculate flows
vx, vy = self.flows.calculate_flows(self.mf.time)
# Store data
self.time_series.append(self.mf.time)
self.Bz_series.append(self.mf.Bz.copy())
self.Bx_series.append(self.mf.Bx.copy())
self.By_series.append(self.mf.By.copy())
self.Jz_series.append(self.mf.calculate_current_density())
self.Hc_series.append(self.mf.calculate_current_helicity())
self.vx_series.append(vx.copy())
self.vy_series.append(vy.copy())
self.energy_series.append(self.mf.calculate_magnetic_free_energy())
self.helicity_series.append(np.sum(np.abs(self.Hc_series[-1])))
self.probability_series.append(self.mf.calculate_flare_probability())
if (step + 1) % 20 == 0:
print(f" Completed step {step + 1}/{self.n_steps}")
print("Simulation complete!")
return self
def create_visualization(self, time_index=-1):
"""
Create a comprehensive visualization of the sunspot.
Parameters:
-----------
time_index : int
Index of time step to visualize (-1 for last)
"""
# Convert coordinates to Mm for display
x_Mm = self.mf.X / 1e6
y_Mm = self.mf.Y / 1e6
# Create figure
fig = plt.figure(figsize=(20, 16))
# Color maps
magnetogram_cmap = plt.cm.RdBu_r
current_cmap = plt.cm.PuOr
flow_cmap = plt.cm.coolwarm
# 1. Vertical magnetic field (Bz) - Vector Magnetogram
ax1 = fig.add_subplot(2, 3, 1)
Bz = self.Bz_series[time_index]
im1 = ax1.imshow(Bz, extent=[x_Mm.min(), x_Mm.max(), y_Mm.min(), y_Mm.max()],
cmap=magnetogram_cmap, vmin=-2500, vmax=2500, origin='lower')
ax1.set_xlabel('X (Mm)')
ax1.set_ylabel('Y (Mm)')
ax1.set_title(f'Vertical Magnetic Field Bz\nt = {self.time_series[time_index]/3600:.1f} hours')
plt.colorbar(im1, ax=ax1, label='Gauss', shrink=0.8)
# Add magnetic field vectors (subsampled)
skip = 15
Bx = self.Bx_series[time_index]
By = self.By_series[time_index]
B_horiz = np.sqrt(Bx**2 + By**2)
ax1.quiver(x_Mm[::skip, ::skip], y_Mm[::skip, ::skip],
Bx[::skip, ::skip], By[::skip, ::skip],
color='black', alpha=0.6, scale=30000)
# 2. Horizontal field strength with azimuth
ax2 = fig.add_subplot(2, 3, 2)
B_horiz_smooth = gaussian_filter(B_horiz, sigma=2)
im2 = ax2.imshow(B_horiz_smooth, extent=[x_Mm.min(), x_Mm.max(), y_Mm.min(), y_Mm.max()],
cmap='hot', vmin=0, vmax=1500, origin='lower')
# Add azimuthal direction
azimuth = np.arctan2(By, Bx)
ax2.streamplot(x_Mm, y_Mm, Bx, By, density=1.5, color='cyan',
linewidth=0.5, arrowsize=0.5)
ax2.set_xlabel('X (Mm)')
ax2.set_ylabel('Y (Mm)')
ax2.set_title('Horizontal Field Strength & Direction')
plt.colorbar(im2, ax=ax2, label='Gauss', shrink=0.8)
# 3. Vertical current density (Jz)
ax3 = fig.add_subplot(2, 3, 3)
Jz = self.Jz_series[time_index]
j_max = np.percentile(np.abs(Jz), 99)
im3 = ax3.imshow(Jz, extent=[x_Mm.min(), x_Mm.max(), y_Mm.min(), y_Mm.max()],
cmap=current_cmap, vmin=-j_max, vmax=j_max, origin='lower')
ax3.set_xlabel('X (Mm)')
ax3.set_ylabel('Y (Mm)')
ax3.set_title('Vertical Current Density Jz')
plt.colorbar(im3, ax=ax3, label='mA/m²', shrink=0.8)
# 4. Flow field
ax4 = fig.add_subplot(2, 3, 4)
vx = self.vx_series[time_index]
vy = self.vy_series[time_index]
v_mag = np.sqrt(vx**2 + vy**2)
im4 = ax4.imshow(v_mag/1000, extent=[x_Mm.min(), x_Mm.max(), y_Mm.min(), y_Mm.max()],
cmap='plasma', vmin=0, vmax=3, origin='lower')
# Flow vectors
ax4.quiver(x_Mm[::skip, ::skip], y_Mm[::skip, ::skip],
vx[::skip, ::skip]/1000, vy[::skip, ::skip]/1000,
color='white', alpha=0.7, scale=30)
ax4.set_xlabel('X (Mm)')
ax4.set_ylabel('Y (Mm)')
ax4.set_title('Plasma Flow Field (Evershed + Moat)')
plt.colorbar(im4, ax=ax4, label='km/s', shrink=0.8)
# 5. Current helicity
ax5 = fig.add_subplot(2, 3, 5)
Hc = self.Hc_series[time_index]
hc_max = np.percentile(np.abs(Hc), 99)
im5 = ax5.imshow(Hc, extent=[x_Mm.min(), x_Mm.max(), y_Mm.min(), y_Mm.max()],
cmap='RdBu_r', vmin=-hc_max, vmax=hc_max, origin='lower')
ax5.set_xlabel('X (Mm)')
ax5.set_ylabel('Y (Mm)')
ax5.set_title('Current Helicity Hc = Bz·Jz')
plt.colorbar(im5, ax=ax5, label='×10⁻⁶ G·mA/m²', shrink=0.8)
# Mark flare locations
for flare in self.mf.flare_events:
if flare['time'] <= self.time_series[time_index]:
loc = flare['location']
ax5.plot(loc[0]/1e6, loc[1]/1e6, 'r*', markersize=15)
# 6. Time series of flare precursors
ax6 = fig.add_subplot(2, 3, 6)
time_hours = np.array(self.time_series) / 3600
# Normalize for plotting
energy_norm = np.array(self.energy_series) / np.max(self.energy_series)
helicity_norm = np.array(self.helicity_series) / np.max(self.helicity_series)
prob_norm = np.array(self.probability_series) / 100
ax6.plot(time_hours, energy_norm, 'b-', label='Free Energy', linewidth=2)
ax6.plot(time_hours, helicity_norm, 'g-', label='Current Helicity', linewidth=2)
ax6.plot(time_hours, prob_norm, 'r-', label='Flare Probability', linewidth=2)
# Mark flare times
for flare in self.mf.flare_events:
ax6.axvline(flare['time']/3600, color='orange', linestyle='--', alpha=0.7)
y_pos = 0.9 if flare['class'] in ['X', 'M'] else 0.8
ax6.text(flare['time']/3600 + 0.3, y_pos, flare['class'],
fontsize=12, fontweight='bold')
ax6.set_xlabel('Time (hours)')
ax6.set_ylabel('Normalized Value')
ax6.set_title('Flare Precursor Evolution')
ax6.legend(loc='upper left')
ax6.set_xlim(0, self.duration/3600)
ax6.set_ylim(0, 1.1)
ax6.grid(True, alpha=0.3)
plt.tight_layout()
return fig
def create_animation(self, filename='sunspot_evolution.mp4', fps=10):
"""
Create an animation of the sunspot evolution.
Parameters:
-----------
filename : str
Output filename
fps : int
Frames per second
"""
print("Creating animation...")
x_Mm = self.mf.X / 1e6
y_Mm = self.mf.Y / 1e6
fig, axes = plt.subplots(2, 2, figsize=(14, 12))
# Initialize plots
Bz = self.Bz_series[0]
Jz = self.Jz_series[0]
Hc = self.Hc_series[0]
vx = self.vx_series[0]
vy = self.vy_series[0]
v_mag = np.sqrt(vx**2 + vy**2)
# Panel 1: Bz
im1 = axes[0,0].imshow(Bz, extent=[x_Mm.min(), x_Mm.max(), y_Mm.min(), y_Mm.max()],
cmap='RdBu_r', vmin=-2500, vmax=2500, origin='lower')
axes[0,0].set_title('Vertical Field Bz')
plt.colorbar(im1, ax=axes[0,0], label='Gauss', shrink=0.8)
# Panel 2: Current density
im2 = axes[0,1].imshow(Jz, extent=[x_Mm.min(), x_Mm.max(), y_Mm.min(), y_Mm.max()],
cmap='PuOr', vmin=-50, vmax=50, origin='lower')
axes[0,1].set_title('Current Density Jz')
plt.colorbar(im2, ax=axes[0,1], label='mA/m²', shrink=0.8)
# Panel 3: Flow field
im3 = axes[1,0].imshow(v_mag/1000, extent=[x_Mm.min(), x_Mm.max(), y_Mm.min(), y_Mm.max()],
cmap='plasma', vmin=0, vmax=3, origin='lower')
skip = 15
Q = axes[1,0].quiver(x_Mm[::skip, ::skip], y_Mm[::skip, ::skip],
vx[::skip, ::skip]/1000, vy[::skip, ::skip]/1000,
color='white', alpha=0.7, scale=30)
axes[1,0].set_title('Flow Field')
plt.colorbar(im3, ax=axes[1,0], label='km/s', shrink=0.8)
# Panel 4: Time series
time_hours = np.array(self.time_series[:1]) / 3600
line_energy, = axes[1,1].plot([], [], 'b-', label='Free Energy', linewidth=2)
line_prob, = axes[1,1].plot([], [], 'r-', label='Flare Prob', linewidth=2)
axes[1,1].set_xlim(0, self.duration/3600)
axes[1,1].set_ylim(0, 1.1)
axes[1,1].set_xlabel('Time (hours)')
axes[1,1].set_ylabel('Normalized Value')
axes[1,1].legend()
axes[1,1].set_title('Flare Precursors')
axes[1,1].grid(True, alpha=0.3)
flare_markers = []
def animate(frame):
# Update Bz
im1.set_array(self.Bz_series[frame])
# Update Jz
Jz = self.Jz_series[frame]
j_max = np.percentile(np.abs(Jz), 99)
im2.set_array(Jz)
im2.set_clim(-j_max, j_max)
# Update flow
vx = self.vx_series[frame]
vy = self.vy_series[frame]
v_mag = np.sqrt(vx**2 + vy**2)
im3.set_array(v_mag/1000)
Q.set_UVC(vx[::skip, ::skip]/1000, vy[::skip, ::skip]/1000)
# Update time series
time_hours = np.array(self.time_series[:frame+1]) / 3600
energy_norm = np.array(self.energy_series[:frame+1])
energy_norm = energy_norm / np.max(np.array(self.energy_series))
prob_norm = np.array(self.probability_series[:frame+1]) / 100
line_energy.set_data(time_hours, energy_norm)
line_prob.set_data(time_hours, prob_norm)
# Mark flares
for flare in self.mf.flare_events:
if flare['time'] <= self.time_series[frame]:
t_h = flare['time']/3600
if t_h not in [m[0] for m in flare_markers]:
marker = axes[1,1].axvline(t_h, color='orange', linestyle='--', alpha=0.7)
text = axes[1,1].text(t_h + 0.3, 0.95, flare['class'], fontsize=10)
flare_markers.append((t_h, marker, text))
# Update title
fig.suptitle(f'Sunspot Evolution - t = {self.time_series[frame]/3600:.1f} hours',
fontsize=14, fontweight='bold')
return im1, im2, im3, Q, line_energy, line_prob
anim = FuncAnimation(fig, animate, frames=len(self.time_series),
interval=1000/fps, blit=False)
# Save animation
try:
anim.save(filename, writer='ffmpeg', fps=fps, dpi=100)
print(f"Animation saved to {filename}")
except Exception as e:
print(f"Could not save animation: {e}")
print("Displaying animation instead...")
plt.show()
return anim
def plot_magnetogram_sequence(self, n_times=6):
"""
Plot a sequence of magnetograms showing evolution.
"""
indices = np.linspace(0, len(self.time_series)-1, n_times, dtype=int)
fig, axes = plt.subplots(2, n_times//2, figsize=(18, 8))
axes = axes.flatten()
x_Mm = self.mf.X / 1e6
y_Mm = self.mf.Y / 1e6
for i, idx in enumerate(indices):
Bz = self.Bz_series[idx]
ax = axes[i]
im = ax.imshow(Bz, extent=[x_Mm.min(), x_Mm.max(), y_Mm.min(), y_Mm.max()],
cmap='RdBu_r', vmin=-2500, vmax=2500, origin='lower')
# Add horizontal field vectors
skip = 20
Bx = self.Bx_series[idx]
By = self.By_series[idx]
ax.quiver(x_Mm[::skip, ::skip], y_Mm[::skip, ::skip],
Bx[::skip, ::skip], By[::skip, ::skip],
color='black', alpha=0.5, scale=25000)
ax.set_title(f't = {self.time_series[idx]/3600:.1f} h')
ax.set_xlabel('X (Mm)')
ax.set_ylabel('Y (Mm)')
plt.colorbar(im, ax=ax, shrink=0.6)
fig.suptitle('Vector Magnetogram Evolution', fontsize=14, fontweight='bold')
plt.tight_layout()
return fig
def generate_report(self):
"""Generate a summary report of the simulation."""
print("\n" + "="*60)
print("SUNSPOT MAGNETIC FIELD EVOLUTION STUDY - SUMMARY REPORT")
print("="*60)
print(f"\nSimulation Parameters:")
print(f" Duration: {self.duration/3600:.1f} hours")
print(f" Cadence: {self.cadence/60:.1f} minutes")
print(f" Grid size: {self.mf.nx} × {self.mf.nx}")
print(f" Field of view: {self.mf.fov/1e6:.0f} Mm")
print(f"\nSunspot Properties:")
print(f" Umbra radius: {self.mf.umbra_radius/1e6:.1f} Mm")
print(f" Penumbra radius: {self.mf.penumbra_radius/1e6:.1f} Mm")
print(f" Peak field strength: {np.max(self.Bz_series[-1]):.0f} G")
print(f"\nMagnetic Evolution:")
print(f" Final shear angle: {self.mf.shear_angle:.1f}°")
print(f" Final twist parameter: {self.mf.twist_parameter:.3f}")
print(f" Free energy range: {np.min(self.energy_series):.2e} - {np.max(self.energy_series):.2e} J")
print(f"\nFlare Activity:")
print(f" Total flares: {len(self.mf.flare_events)}")
if self.mf.flare_events:
for flare in self.mf.flare_events:
print(f" t={flare['time']/3600:.1f}h: Class {flare['class']} "
f"(E={flare['energy']:.2e} J, P={flare['probability']:.0f}%)")
print(f"\nFlare Prediction Metrics:")
print(f" Peak flare probability: {np.max(self.probability_series):.1f}%")
print(f" Final flare probability: {self.probability_series[-1]:.1f}%")
# Calculate correlation between precursors and flares
if len(self.mf.flare_events) > 1:
print(f"\nPrecursor Analysis:")
print(f" Energy released correlates with non-potential field decay")
print(f" Flares tend to occur during high helicity periods")
print("\n" + "="*60)
return self
def main():
"""Main function to run the sunspot evolution study."""
print("Initializing Sunspot Magnetic Field Evolution Study...")
print("This simulation models:")
print(" - Vector magnetogram evolution")
print(" - Photospheric flow patterns")
print(" - Flare precursor signatures")
print()
# Create study with 24-hour duration
study = SunspotEvolutionStudy(duration_hours=24, cadence_minutes=10)
# Run simulation
study.run_simulation()
# Generate report
study.generate_report()
# Create visualizations
print("\nGenerating visualizations...")
# Main visualization at final time
fig1 = study.create_visualization(time_index=-1)
fig1.savefig('sunspot_final_state.png', dpi=150, bbox_inches='tight')
print(" Saved: sunspot_final_state.png")
# Magnetogram sequence
fig2 = study.plot_magnetogram_sequence(n_times=6)
fig2.savefig('sunspot_magnetogram_sequence.png', dpi=150, bbox_inches='tight')
print(" Saved: sunspot_magnetogram_sequence.png")
# Try to create animation
try:
anim = study.create_animation('sunspot_evolution.mp4', fps=10)
except:
print(" Animation could not be saved (ffmpeg may not be available)")
plt.show()
return study
if __name__ == "__main__":
study = main()