A Worked Example in Python
Space weather forecasters face a very concrete trade-off every time a fast solar wind stream or a CME-driven shock approaches Earth: warn too early on noisy data and you get false alarms that erode public trust; wait too long to be sure and the warning becomes useless because the storm has already arrived. This article works through a simplified but physically grounded version of that problem, builds a cost-function optimization for it in Python, and visualizes the result — including a 3D cost surface.
1. The physical setup
Real-time solar wind monitors (like the ones sitting at the L1 Lagrange point, about 1.5 million km upstream of Earth) give operators a finite warning window before the same plasma reaches the magnetosphere. The nominal propagation time is
$$\tau = \frac{D_{L1}}{v_{sw}}$$
where $D_{L1} \approx 1.5\times10^{6},\text{km}$ and $v_{sw}$ is the solar wind speed. Faster wind means less warning time — a 400 km/s wind gives roughly an hour of lead time, while an 800 km/s shock front gives barely half that.
The classic trigger condition for a geomagnetic storm warning is a sustained southward turning of the interplanetary magnetic field ($B_z \ll 0$), because southward $B_z$ reconnects efficiently with Earth’s northward-pointing field and drives geomagnetic activity. In practice, raw $B_z$ measurements are noisy, so operators smooth the signal before comparing it against a threshold — but smoothing itself eats into the available lead time.
This gives us two knobs to tune:
- Smoothing window length $w$ (minutes) — larger $w$ suppresses noise but adds detection delay.
- Detection threshold $\theta$ (nT) — a less negative threshold triggers sooner but generates more false alarms.
2. Formulating the optimization problem
For a given $(w, \theta)$ pair, three quantities matter operationally:
- $P_{FA}(w,\theta)$ — probability that a quiet (non-storm) period crosses the threshold and triggers a false alarm.
- $P_{MD}(w,\theta)$ — probability that a real storm is missed (never crosses the threshold before impact).
- $\overline{L}(w,\theta)$ — the mean effective lead time, in minutes, among correctly detected storms.
We combine these into a single operational cost function to minimize:
$$C(w,\theta) = \alpha, P_{FA}(w,\theta) ;+; \beta, P_{MD}(w,\theta) ;-; \gamma, \frac{\overline{L}(w,\theta)}{L_{max}}$$
Here $\alpha, \beta, \gamma$ are relative weights (missed storms are usually considered worse than false alarms, so $\beta > \alpha$), and $L_{max}$ is the full observation window used for normalization. The optimal warning strategy is then

To generate realistic southward-turning events for the simulation, each synthetic storm’s $B_z$ ramp follows a logistic (sigmoid) onset:
$$B_z(t) = B_{z,\min}\cdot \sigma!\left(\frac{t - t_0}{\tau_{ramp}/4}\right), \qquad \sigma(x) = \frac{1}{1+e^{-x}}$$
on top of an AR(1) noise process representing normal solar wind fluctuations.
3. Python implementation
The code below simulates 3,000 synthetic solar wind passages (1,500 quiet, 1,500 storm), performs a full grid search over smoothing windows and thresholds, computes the cost surface, and produces a combined diagnostic figure. Everything is vectorized with NumPy — the only Python-level loops are over the (small) parameter grids themselves, not over individual events, so the whole search runs in a few seconds even in the free Colab tier.
1 | import numpy as np |
4. Walking through the code
Data simulation (sections 4–5). Rather than pulling live satellite data (which would make the article non-reproducible), the script generates 1,500 “quiet” and 1,500 “storm” synthetic passages. Quiet-time $B_z$ is a pure AR(1) noise process centered on zero, mimicking the natural jitter of the interplanetary magnetic field. Storm events add a logistic southward ramp on top of the same noise process, with a randomized onset time, ramp duration, and minimum $B_z$ — so every simulated storm looks slightly different, just like real events. Solar wind speed is generated the same way, rising together with the $B_z$ ramp to represent the arrival of a fast stream or shock.
Causal smoothing (section 7). A real-time forecasting system cannot use a centered moving average, because that would require future data it doesn’t have yet. causal_moving_average uses a cumulative-sum trick to compute, at each time step, the average of only the current and preceding samples — this is what an operational monitor actually sees. The associated delay is $\approx (w-1)/2$ samples, which is subtracted from the raw lead time to get the effective lead time.
Grid search (section 8). For each smoothing window $w$ in W_GRID, the whole ensemble of 3,000 time series is smoothed once, and then compared against every threshold in THETA_GRID simultaneously using NumPy broadcasting (smoothed[:, :, None] <= THETA_GRID[None, None, :]). This produces a 3D boolean array (events × time × thresholds) in one shot, letting argmax find each event’s first threshold-crossing instant for every threshold value without any Python-level loop over individual events. Only the outer loop over $w$ (12 values) and an inner loop over $\theta$ (21 values) run in Python — 252 iterations total, each doing large vectorized array operations, which is why the whole grid search finishes in a few seconds rather than minutes. This vectorized structure is effectively the “fast” version of what would otherwise be a triple nested loop over events, time, and thresholds.
Cost evaluation. For every $(w,\theta)$ cell, the script computes the false-alarm rate among quiet events, the missed-detection rate among storm events, and the mean effective lead time among storms that were correctly detected, then combines them into $C(w,\theta)$ using the weights $\alpha=1.0$, $\beta=2.0$, $\gamma=1.5$ — reflecting the operational reality that missing a real storm is treated as roughly twice as costly as a false alarm, while longer lead time is explicitly rewarded.
Finding the optimum. np.argmin(COST) combined with np.unravel_index locates the $(w^{}, \theta^{})$ pair that minimizes the full cost surface — this is the numerical solution to the optimization problem stated in Section 2.
5. Reading the plots
- Top-left (3D surface): the full cost landscape $C(w,\theta)$. You should see a bowl-shaped region — too small a window (noisy, high false-alarm cost) and too conservative a threshold (high missed-detection cost) both push the cost up, with a visible minimum marked in red.
- Top-middle (contour): the same surface viewed from above, useful for reading off the optimal region at a glance.
- Top-right (ROC-like curve): at the optimal window, this shows how detection rate trades off against false-alarm rate as the threshold varies — the classic signal-detection trade-off curve.
- Bottom-left (histogram): the spread of effective lead times actually achieved at the optimal settings — useful for communicating “how much warning time” to stakeholders, not just an average number.
- Bottom-right (example traces): a concrete illustration of one storm’s raw vs. smoothed $B_z$ crossing the optimal threshold, which makes the abstract optimization tangible.

Reference L1 -> Earth propagation time (tau = D_L1 / v_sw): v_sw = 400 km/s -> tau approx 62.5 min v_sw = 600 km/s -> tau approx 41.7 min v_sw = 800 km/s -> tau approx 31.2 min === Optimal warning-timing parameters === optimal smoothing window w* = 1 min optimal Bz threshold theta* = -7.00 nT minimum cost C* = -0.7656 false alarm rate at optimum = 2.20 % missed detection rate at optimum = 0.13 % mean effective lead time at optimum = 94.8 min
6. Takeaways and possible extensions
Even in this simplified model, the optimization consistently favors a short-to-moderate smoothing window paired with a moderately conservative threshold — reflecting the fundamental tension between noise suppression and warning latency. In a real operational system, this framework could be extended by:
- Using actual DSCOVR/ACE $B_z$ and speed time series instead of synthetic data.
- Making $\alpha, \beta, \gamma$ time-varying (e.g., raising the missed-detection penalty during solar maximum).
- Replacing the grid search with a continuous optimizer (
scipy.optimize.minimize) once the cost surface is confirmed to be reasonably smooth, as seen in the 3D plot above. - Incorporating multiple correlated parameters (e.g., $B_z$, speed, and density jointly) rather than a single threshold variable.










