The Missing Sun

When I edited my only YouTube video, I worked with images of the Sun taken in different wavelength bands. Sometimes a frame is missing in the band I’m using for the edit, even though images from the other bands are available. I wanted to know whether those images contained enough information to estimate the missing frame.

I know Python, but I’d never trained a model in PyTorch. To learn how, I chose times when all three observations were available. I set one image aside, reconstruct it from the other two, then compare my result with what the satellite measured. If I started with a frame that was actually missing, I couldn’t make that comparison.

The observations

I used SDOML, a public dataset prepared from observations made by NASA’s AIA instrument. The band labels, 171, 193 and 211 Å, give their wavelengths in angstroms. I use the 171 and 193 Å images as inputs. The 211 Å image is the target: it’s the image I’m trying to reconstruct.

I thought I’d have to calculate intensity from red, green and blue values. The files already contain one number per pixel: the detector signal per second of exposure. Switch bands below to read the signal at the same spot on the Sun.

Observation at 171 Å

Input 1 ·
Pixel at the crosshair:

Observations from August 2010. All three images use the same grayscale. DN/s means digital counts per second.

To train on my own computer, I reduced the resolution by replacing each four-by-four block of pixels with its mean. The image still covers the whole solar disk, just in less detail. I do this for all three bands.

Here’s how I prepare one example for PyTorch. In the three Python snippets in this notebook, I use my first observation, from August 28. I keep the same pixel throughout so I can follow the calculation. This example is separate from the days used for the test score.

Python · Preparing the input and target
import torch
from triplet import load_triplet

# Convert each NumPy array to a tensor, preserving the band order.
i171, i193, i211 = map(torch.from_numpy, load_triplet())
x = torch.stack([i171, i193])
y = i211.unsqueeze(0)  # One band: [1, 128, 128].

print(x[:, 64, 64])  # ":" selects both bands at the same pixel.
print(y[0, 64, 64])

tensor([76.6720, 56.4242])
tensor(14.3407)

The first line shows the two intensities the model gets to see. The second is the intensity it should predict. stack puts the two input bands into x. unsqueeze gives the target a band dimension even though it contains only one band.

Image dimensions and alignment

Each image goes from 512 × 512 to 128 × 128 pixels. I check that the three grids have the same center, orientation and pixel scale. The exposures aren’t quite simultaneous: I allow up to 12 seconds between the first and the last. A rapidly changing feature may have moved or changed brightness in that time.

Training a first model

I started with a formula I could check by hand. To estimate one pixel, I take the intensities at the same position in the two input bands. I multiply each by a weight, add the results, then add a constant. I use the same three parameters at every pixel.

predicted 211 = a × measured 171 + b × measured 193 + c

PyTorch starts with random parameter values. To work out how to adjust them, I compare the calculated image with the observation I set aside. At each pixel I take the size of the difference, ignoring its sign. I average those differences over the solar disk. That’s the mean absolute error, or MAE. I exclude the background because predicting black there would already give a small error.

At each training step, PyTorch calculates how the error changes with each parameter. The optimizer uses that information to update the parameters. I first checked that I could reduce the error on a single image. Then I used the same loop on observations from several days.

Images taken a few minutes apart can be almost identical, so I split the data by date. I use the training images to adjust the parameters. On other dates, called the validation set, I measure the error without changing the model. The chart shows both measurements over the course of training.

TrainingValidation
800 / 800

MAE: 9.900 on training data, 8.537 on validation data (DN/s).

Parameters at this step

Weights for 171 and 193 Å: . Bias: DN/s.

211 Å observation from the validation set
Observation
Reconstruction at the selected training step
At step 800
Observation time: . The image on the left stays fixed. Move the slider to reconstruct it with the weights from a different training step.

Once training is over, I can apply the formula directly without calling the network. I read the saved weights in the original intensity units and check the pixel I used earlier.

Python · Applying the learned parameters
import json
from preparer_courbe import CACHE

path = CACHE / "scores_32_800_cpu.json"
run = json.loads(path.read_text())[0]  # This file contains a single run.
a, b = run["poids"]  # The saved weights, in band order.
# x[0] and x[1] are images, so this calculates every pixel at once.
linear = a * x[0] + b * x[1] + run["biais"]

print(f"{linear[64, 64]:.2f} DN/s")

11.42 DN/s

The linear model estimates 11.42 DN/s where the satellite measured 14.34 DN/s. The difference of 2.92 DN/s is the error at this pixel only.

I also tried increasing the number of training examples. For each run I started from the same parameters and used the same number of updates. The validation error barely changed. Some of the extra examples were images taken close together on the same days. This doesn’t tell me that a few images would be enough for other periods.

Results by training set size
MAE on the same validation dates after 400 updates
Training times sampled481632
MAE (DN/s)8.4568.5498.5448.537

With 32 examples I also tried 800 updates. The training error stayed at 9.900 DN/s to three decimal places.

Using neighboring pixels

With the first formula, two pixels with the same input intensities always get the same estimate. The surrounding region plays no part in the calculation. I wanted to see whether the model could use that information, particularly where it underestimated bright regions.

I trained a small convolutional neural network, or CNN. At each position, it reads a square around the pixel in both input bands. It learns several ways to combine those measurements, then uses the results to estimate a single intensity at 211 Å. It can see the neighbors, but it also has more parameters. This experiment compares the two models; it can’t tell me how much of the difference is due to the neighbors alone.

CNN architecture and training settings

Eight 3 × 3 filters produce eight maps. An operation called ReLU sets their negative values to zero. A final 1 × 1 convolution combines the maps. The CNN has 161 parameters, compared with three for the linear model.

Both models use the same 32 training examples and the same disk mask. I divide intensities by 100 for both, run 800 updates with Adam, and keep the weights from the final step.

Watch the CNN learn

I kept the same validation image I used for the linear model. Press Replay to start with the CNN’s random weights, or move the slider one update at a time. Only the weights change. The two curves show the error over all the training and validation images; the pair below shows what that change looks like on one example.

TrainingValidation
800 / 800

MAE: on training data, on validation data (DN/s).

Measured 211 Å image from the validation set
Observation
CNN reconstruction at the selected training step
Reconstruction at step 800
Both views use the same intensity scale. Each step shows the CNN’s actual output for this observation.

Most of the drop comes early. By step 100, the validation error has fallen from 32.69 to 7.17 DN/s. It reaches 6.59 at step 800, but it doesn’t go down at every update. Zoom in on the plateau to see those smaller changes.

Comparing reconstructions

I used two other days for the test. The parameters stay fixed. At each observation time, I give both models exactly the same input images. I only use the measured 211 Å image to calculate their errors.

Python · Checking the CNN on the same August 28 pixel
from exercice_cnn import PetitCNN

cnn = PetitCNN()
weights = torch.load(CACHE / "cnn_800.pt", weights_only=True)
cnn.load_state_dict(weights)  # Replace the initial weights with the learned ones.
cnn.eval()
# For prediction, PyTorch doesn't need to track gradients.
with torch.inference_mode():
    prediction = 100 * cnn(x / 100)  # Input in hundreds of DN/s; convert back to DN/s.

p = prediction[0, 64, 64]
print(f"Estimate: {p:.2f} DN/s")
print(f"Absolute error: {abs(p - y[0, 64, 64]):.2f} DN/s")

Estimate: 13.34 DN/s
Absolute error: 1.00 DN/s

The CNN was trained in hundreds of DN/s, so I divide the input by 100 and multiply the output by 100 to get back to DN/s. The prediction depends only on x. I read y afterward to measure the error. The viewer below applies the same calculation to the test images.

211 Å observation at the selected time
211 Å observation
Reconstruction at the selected time

On these two test days, using the CNN brings the mean absolute error down from 7.55 to 5.16 DN/s. I also checked the brightest regions separately. Both models underestimate their intensity on average, but the CNN underestimates it by less.

Scores by model and definition of bright regions
Errors on the solar disk in DN/s
Dataset and modelMAEMean signed error on bright pixels

For the last column, I make the predictions first, then select pixels where the observation is at least 200 DN/s. I subtract the measurement from the estimate and keep the sign. A negative value means the reconstruction is too dark on average at those pixels.

Match the observation and the two models

All three images show the same observation time and use the same grayscale. Drag a line from each image to its label with your mouse or finger. To change an answer, draw the connection again. You can also select an image and then a label by clicking or using the keyboard.

What I learned

I enjoyed learning PyTorch with images of the Sun. I wouldn’t call myself a data scientist, but I have a better idea of what it takes to prepare examples, train a model and check how it does on images it hasn’t seen before.

I’ve worked with quite a few data scientists over the years. We generally agreed that 80% of the job is getting the data, cleaning it up and getting it ready to use. I still agree with that.

What I liked about this project was how much of that work had already been done. I started with NASA’s solar observations as prepared by the SDOML team. They’d already corrected the intensities for exposure time, and the images came with timestamps. I still had to match the bands and choose the training and test dates. That left me time for the part I wanted to learn: training the two models and figuring out where they go wrong. If you’d like to try it, the dataset is freely available on AWS, and the SDOMLv2 preparation scripts show how the images were processed.

I’d like to get back to making videos of the Sun and try this on a sequence with a real missing frame. I want to see how the reconstruction looks between the frames on either side, with a note in the edit to say it’s an estimate. One day, when I have the time.