Claude Code transcript

40 prompts · 230 messages · 51 tool calls · 0 commits · 8 pages

#1

Catch up on the README

1 bash · 1 read

Here's a summary of this project:

Goal: Evaluate whether an ABI-trained (GOES-16) contrail detection model (mcast) can be applied to VIIRS data zero-shot or with light fine-tuning, as a path to higher-resolution contrail detection (500 m vs. 2 km).

Core approach: - viirs_adapter.py remaps VIIRS L1B data into ABI-named variables so mcast runs unchanged - Channel mapping: M14→C11, M15→C13 and C14 (I5 would be better for C14 but isn't in the test files), M16→C15 - Two test scenes with ground-truth label masks; evaluated via pixel-wise precision/recall/F1/IoU

Key engineering challenge solved: VIIRS bowtie deletion zones (~13% of pixels, in 4-row bands every 16 rows at swath edges) cause NaN propagation through the CNN. The fix (fill_along_track) does column-wise linear interpolation across each 4-row gap — physically reasonable since 4 rows ≈ 3 km.

Results progression: | Approach | Precision | Recall | F1 | IoU | |---|---|---|---|---| | No fill | 0.587 | 0.053 | 0.097 | 0.051 | | Band-mean fill | 0.391 | 0.318 | 0.351 | 0.213 | | Along-track interp (current) | 0.491 | 0.365 | 0.419 | 0.265 |

Planned next steps: 1. Threshold sweep — the 0.42 threshold was tuned on ABI data, not VIIRS 2. Normalisation mismatch — patch in VIIRS-derived channel means/stds instead of ABI training stats

The project is at a promising early stage: F1=0.42 with zero retraining, and two cheap experiments could push it further before any fine-tuning.

#2

Now before doing any tuning, I think we should decide how to split the data overall. So far we have looked at 1 scene only. I have 12 scenes for which I have labeled data,, although one is pretty samll in comparison to the rest. How should we split the dataset before we tun ito train and test? Should we also have validation or not since the set is small (though most scenes are large)

Good time to decide this — both the threshold sweep and the normalization-stats experiment are forms of fitting to data, so they need to be governed by the same split discipline as fine-tuning.

My recommendation: 3-way split, 9 train / 2 val / 3 test

  • Test (3 scenes): Lock these away now, never look at them until you want a final number to report. Pick scenes that are diverse (different times of year, viewing geometry, contrail density) so the test score is representative.
  • Val (2 scenes): Use these to pick the threshold, compute normalization stats, and (if you fine-tune) do early stopping / model selection. They're "tuning budget" — you can look at them, but they don't go in the loss.
  • Train (7 + the small scene = 8): Everything else. Fine-tuning gradients come only from here.

Why not train/test only? The threshold sweep and normalization stats are low-DF fits, so they won't badly overfit 9 scenes — but if you iterate even a little (try a few threshold values, compare norm strategies), the train set score stops being a fair estimate and you'll want the validation signal anyway. Better to designate it upfront.

Why not a bigger test set? 3 scenes is already thin, but with large scenes you have millions of pixels per scene, so 3 gives you a statistically stable IoU estimate. Shrinking it to 2 saves little; expanding to 4 eats into your already small training pool.

The small scene: Put it in train. It contributes less signal for evaluation but is fine as a training example, and you don't want your test set to be dominated by an unrepresentative tiny scene.

One practical note: before you assign scenes, look at the metadata — acquisition time, orbit path, geographic region. If two scenes are from the same orbit pass or same day over the same area, they're not independent and should be in the same split. You want the 3 test scenes to be as diverse from each other and from train as possible.

What do you know about the 12 scenes — times, regions, anything like that? That would let us make concrete split assignments.

#3

Update thi, we have 12 scenes in total inclsuign the small one!

Same structure, corrected math: 7 train / 2 val / 3 test (totaling 12).

  • Test (3 scenes): Locked away until final reporting.
  • Val (2 scenes): For threshold selection, normalization stats, and model selection if you fine-tune.
  • Train (7 scenes, including the small one): Gradients and fitting.

Everything else in my previous answer stands — the logic doesn't change, just the train pool is one scene smaller than I said (7 instead of 8).

#4

I put some scene properties into data/viirs_scene_properties.parquet - we can use those to decide on the split

4 bash

Here's what stands out from the data:

Scene 3 is the small one — 1.27M km² vs. 4–7M km² for everything else. Confirmed goes to train.

Only 2 night scenes (6 and 9) — this is the tightest constraint. They behave differently (no solar channels), so at least 1 must be in train, and ideally 1 in test.

Two platforms (NOAA-20: 7 scenes, Suomi NPP: 5 scenes) — test should include both.

Contrail cover spans 10× (0.22% to 4.05%) — test should sample from both ends.


Suggested split:

Split Scenes Satellites Day/Night Contrail cover
Test (3) 1, 9, 12 NOAA-20 ×2, NPP ×1 day, night, day 0.22–1.64%
Val (2) 4, 7 NOAA-20 ×1, NPP ×1 day, day ~1.1% each
Train (7) 2, 3, 5, 6, 8, 10, 11 NOAA-20 ×4, NPP ×3 6 day, 1 night 0.30–4.05%

Rationale: - Scene 9 (NPP, night, very low contrail cover) in test is a genuine challenge — domain shift + hard case - Scene 6 (NOAA-20, night) in train so the model actually sees night data during tuning - Scene 3 (small) in train where size matters less - Val is homogeneous (both medium-density daytime) which is fine — it's just for picking thresholds/normalization

The main weakness is val having no night scenes, but since you have only 2 night scenes total and need 1 in train, that's unavoidable.

Does this split look reasonable, or do you have information about the scenes (geography, season, flight routes) that would change the assignments?

#5

Okay, one thing to note: We are not using any solar channels so the only reason why I included day and night is bcasue they correspond to ascending and descending path (I don't know which is which). Please correct that in the notes and add as a section to the README.

1 read · 1 edit

Added a "Dataset" section before "Next Steps" covering:

  • The day/night correction — noted as overpass type (day vs. nighttime pass), clarifying it has no effect on the thermal IR channel values, and flagging that the ascending/descending correspondence isn't yet confirmed
  • A scene properties table with all 12 scenes
  • The train/val/test split table with rationale
  • An explicit note that the test set is locked
#6

Can you switch scenes 1 and 7 becasue I already started using scene 1 and would tehrefore like to have it in Val instead of Test. Also, I am not retraining for now but only tuning/post-processing. Please update the README saying that for that reason I will use Val for tuning and Train+Test for evaulation.

1 read · 1 edit
#7

[Request interrupted by user for tool use]

#8

Can you switch scenes 1 and 4 becasue I already started using scene 1 and would tehrefore like to have it in Val instead of Test. Also, I am not retraining for now but only tuning/post-processing. Please update the README saying that for that reason I will use Val for tuning and Train+Test for evaulation.

1 edit
#9

[Request interrupted by user for tool use]

#10

I have already used scene 1 for some initial quick visual insepction. Is that an issue that it is in the test set now?

It depends on what you did with what you saw.

Not a problem: purely passive inspection — checking that data loaded correctly, detections look plausible, contrails are roughly in the right place. That doesn't influence any parameter choice.

A problem: if the visual inspection shaped any decision you're now going to evaluate — e.g., you noticed the threshold looked too tight or too loose on scene 1, or you adjusted the channel mapping or fill logic based on what you saw. Even implicitly, having an intuition about scene 1's difficulty or character can bias your threshold sweep if you're tuning on val but mentally anchoring to scene 1.

From the README, scene 1 was already used for the bowtie deletion analysis (the 404 patches / 16-row interval statistics are from scene 1), so that's a harder case of leakage — the fill strategy itself was designed based on scene 1's NaN pattern. That said, the fill is a sensor-level preprocessing step that applies identically to all VIIRS granules, so it's unlikely to have been over-fit to scene 1 specifically.

My take: the bowtie analysis alone isn't disqualifying, but moving scene 1 to val is the cleaner choice and costs you nothing — scene 4 is a close substitute for test (similar contrail cover, same satellite). If you've already eyeballed scene 1's detections and formed any intuitions about threshold behavior, I'd make the switch.

#11

Can you switch scenes 1 and 4 becasue I already started using scene 1 and would tehrefore like to have it in Val instead of Test. Also, I am not retraining for now but only tuning/post-processing. Please update the README saying that for that reason I will use Val for tuning and Train+Test for evaulation.

1 edit
#12

Update the README given the folder structure

2 edit · 1 bash
#13

Runn all tests

2 bash · 2 read · 1 edit
#14

Are you currently applying 0.5 as a threshold instead of the model value?

2 bash

Yes and no — there are two thresholds in play:

  1. detect_contrails applies md.threshold (0.42) internally — it thresholds the softmax output before returning, so raw_mask is already a boolean array.

  2. The > 0.5 on line 111 is applied to the reprojected values. Since raw_mask is cast to float32 (0.0/1.0) and reprojected with nearest-neighbor, the values after reprojection are also 0.0 or 1.0 (plus NaN for gaps). So > 0.5 is effectively == 1.0 and has no practical effect — it's just converting back to bool.

So the model's 0.42 threshold is what's actually controlling detections, and the 0.5 is harmless but misleading.

However, this is a problem for the planned threshold sweep: detect_contrails bakes the threshold in and discards the raw probabilities. To sweep the threshold, you'll need to extract the softmax output before the >= md.threshold step. That means either duplicating the model inference code or adding a return_probs=True path. Worth sorting out before starting the sweep.

#15

So change the 0.5 to ==1 for now and also ask to return_probs

2 edit · 1 bash · 1 read
#16

Undo that. You are not allowed to change any code in mcast

2 write · 1 edit · 1 read
#17

Yes, I think we need to have a replicated function to detect_contrails. Call it detect_contrails_viirs(). The mu and sigma values will be determined separately as pre-processing so I do not consider that part of tuning.

5 edit · 4 read · 1 bash

All 21 pass. Summary of what changed:

  • viirs_adapter.py: added detect_contrails_viirs(ds, means, stds, gpu=False) — replicates mcast's inference logic, takes normalisation parameters explicitly, returns a raw float32 probability map with no threshold applied
  • run_detection.py: now calls detect_contrails_viirs with ABI_MEANS/ABI_STDS (read from OldModelData class constants), reprojects the probability map, and thresholds at ABI_THRESHOLD (0.42) — behaviour is identical to before, but the threshold and normalisation stats are now explicit and easy to swap
#18

Which model is actually called? OldModel or a newer one? version 1.1 or newer?

1 bash

The default is version 1.1, which maps to OldModelData (the case '1' branch in load_model). So ABI_MEANS, ABI_STDS, and ABI_THRESHOLD read from OldModelData are exactly the constants that will be used — no mismatch there. The weights file being loaded is mcast_assets/models/detection-1.1.pt.

#19

Is there a different one I could use? Is tehre a 2.1?

1 bash

No detection v2.x. You have detection-1.1.pt only. The v2 format also expects a directory with config.json, means.npy, stds.npy, checkpoint.pt, and threshold.dat — a single .pt file wouldn't be enough even if you had one.

So version 1.1 / OldModelData is the only detection model available here.

#20

For which packages do I need to check if I have them in my environment now?

viirs_adapter.py previously only needed numpy, netCDF4, and xarray. The new top-level imports I added are:

  • torch
  • mcast (specifically mcast.config and mcast.instruments.goes_abi.detection)

These were previously only required in scripts/run_detection.py (the full mcast environment), but they're now imported at module level in viirs_adapter.py, meaning any environment that imports from viirs_detection now needs them too — including no-mcast if you want to keep running tests there.

The tests happened to pass because no-mcast apparently has both available, but it's worth confirming that's intentional rather than accidental.

#21

Okay, let's brainstorm the preprocessing. I want to download quite a bit of VIIRS data to calculate the means and standard deviations in the relevant channels. How do I go about randomly picking swaths in different locations at different times of day and with different conditions? I already have a function (in a different repo) to downlaod VIIRS data

The main axes of variation you care about for BT statistics are:

Season — BT distributions shift significantly with season (surface and cloud-top temperatures). Stratify by month or at minimum by quarter.

Latitude — The dominant driver of BT magnitude. Tropical scenes are systematically warmer than polar ones. Sample across latitude bands (e.g. 60°S–30°S, 30°S–30°N, 30°N–60°N, 60°N–90°N).

Land vs. ocean — Different surface emissivities and thermal inertia shift the distribution, especially at night.

Cloud cover — Don't try to control for this; just let it be random. The model will see all cloud fractions, so you want your stats to reflect the full mix.

Day/night overpass — Since you're on thermal IR channels the effect is smaller than for solar channels, but nighttime land temperatures can differ enough to matter.

Practical approach: build a stratified sample grid of (month × latitude band × land/ocean) cells, then for each cell pick a small number of granules randomly from whatever is available. You don't need many — BT statistics converge fast given each swath is ~20M pixels. 5–10 granules per cell is plenty, so even a coarse 4-season × 4-latitude-band × 2-surface grid gives ~80–160 swaths total, which is more than enough.

The key question for implementation: what does your download function take as input — a granule ID, a date+bounding box, or something else? That determines whether you query LAADS first to get a candidate list to sample from, or whether you generate random timestamps and locations and resolve them to granule IDs.

#22

First of all, I only care about swaths over CONUS. I can use a way of querying for those. Second, my function takes datetime

CONUS simplifies things a lot — the latitude band is narrow (25°N–49°N) so you can drop latitude stratification entirely. The remaining axes that matter are:

Season — the biggest driver of BT magnitude over CONUS (summer land surface temperatures vs. winter). Stratify by month or at minimum by quarter.

Day vs. night overpass — land surface temperatures over CONUS swing significantly between day and night even in thermal IR.

That's essentially it. Cloud cover you get for free by random sampling.

Suggested grid: 4 seasons × 2 overpass types = 8 cells, ~20 granules per cell = ~160 granules total. Each granule is ~20M pixels so that's more than enough for stable statistics.

Implementation sketch given datetime input:

  1. Use your CONUS query to get a list of available granule datetimes over a full year
  2. Tag each datetime as day or night overpass (you can infer this from the time — NOAA-20 and Suomi-NPP have fixed local crossing times, so within a few hours window it's consistently one or the other)
  3. Group by (season, day/night) and randomly sample ~20 from each cell
  4. Pass those datetimes to your download function

One practical note: a single VIIRS pass doesn't always cover all of CONUS — it's a ~2700 km wide swath so depending on the orbit track it may cover the East, West, or central US. If geographic spread within CONUS matters to you, you could add a rough East/West tag from the granule time within an orbit. But for normalization statistics this probably doesn't matter enough to bother.

Does your query function return a flat list of datetimes, or does it already have metadata attached (satellite, coverage area, etc.)?

#23

It also returns the platform, file anmes conus_overlap fraction and the geometry

That's everything you need. Here's how I'd use each field:

CONUS overlap fraction — filter first, before any sampling. Set a minimum threshold (e.g. ≥ 0.3) to exclude granules that barely clip the edge. For normalization stats you want granules that are meaningfully over CONUS, not just grazing it.

Datetime — derive season (month) and day/night. Day/night can be inferred from UTC time: NOAA-20 and Suomi-NPP are sun-synchronous with fixed local crossing times (~13:30 ascending, ~01:30 descending), so over CONUS daytime passes cluster around UTC 18:00–23:00 and nighttime around UTC 06:00–11:00. A simple hour-of-day cutoff works fine.

Platform — either stratify by it (to ensure both NOAA-20 and Suomi-NPP are represented) or just include it as a column and check the balance after sampling. Since you're combining them for a single set of statistics, it probably doesn't need to be a stratification axis — just verify you don't end up with all of one platform.

Geometry — use it to filter out granules with very low overlap (redundant with the fraction but useful as a sanity check), and optionally to tag East/West coverage if you want geographic spread within CONUS. For normalization stats alone this probably isn't worth the complexity.

File names — pass directly to your download function once you've selected the sample.

So the sampling pipeline is: 1. Query → filter overlap ≥ threshold 2. Tag each row: season + day/night (+ platform) 3. Group by (season × day/night), sample ~20 per cell 4. Download by datetime (or file name if that's faster)

Want me to write this as a script?

#24

I will do that shortly. Let's turn this here into a github repo first

2 bash · 1 write
#25

I created it on GitHub here is it: git@github.mit.edu:euchmv/viirs_detections.git

2 bash
#26

I can specify a point that should be contained so I could do separate query calls. One that should contain Las Vegas for swaths in the west and one that should contain west virginia for swaths over the east. Does that make sense or should I rather do one call and then assigne E/W flags afterwards?'

One call and assign afterwards is cleaner. The main problem with two separate calls is that VIIRS swaths are ~2700 km wide, and Las Vegas to West Virginia is only ~3100 km apart — so swaths over the central US will satisfy both containment criteria and you'd pull them twice and need to deduplicate.

With the geometry already returned, assigning E/W is just thresholding on the centroid longitude (e.g. < 100°W = West, ≥ 100°W = East), or computing the overlap fraction with western vs. eastern CONUS polygons if you want to be more precise. Either way it's a one-liner after the query.

It also keeps the door open for three regions (West / Central / East) without any additional query overhead, which might be worth it given how different the Great Plains and Rockies/Sierra Nevada are in terms of surface temperatures.

#27

Okay, now I have a gdf with granule_time, platfrom, and a multipoint geometry (four points). Now I want t assign the location and time of day

Both are straightforward from what you have.

Location — take the centroid longitude of the four corners and bin it:

gdf['centroid_lon'] = gdf.geometry.centroid.x
gdf['location'] = pd.cut(
    gdf['centroid_lon'],
    bins=[-180, -105, -85, 0],
    labels=['west', 'central', 'east']
)

Rough boundaries: ~105°W splits the Rockies from the Plains, ~85°W splits the Plains from the East Coast.

Time of day — compute local solar time from the UTC granule time and centroid longitude, no extra packages needed:

gdf['centroid_lon'] = gdf.geometry.centroid.x  # if not already done
gdf['local_solar_hour'] = (
    gdf['granule_time'].dt.hour
    + gdf['granule_time'].dt.minute / 60
    + gdf['centroid_lon'] / 15
) % 24
gdf['time_of_day'] = (gdf['local_solar_hour'].between(6, 18)).map({True: 'day', False: 'night'})

This is accurate enough — sun-synchronous orbits are regular enough that you won't get ambiguous cases near the 6/18 boundary in practice.

After these two columns are set you have a clean (season, location, time_of_day) stratification to sample from. Do you want three or two location bins?

#28

So I'll have day/night, east/west/central, and the month. What else do we need?

Nothing else. Those three axes capture all the meaningful variation for normalization statistics over CONUS on thermal IR channels:

  • Month covers seasonal BT shifts
  • Location covers the main geographic temperature gradients within CONUS (and implicitly land cover differences — Rockies/desert West vs. Plains vs. humid East)
  • Day/night covers the diurnal surface temperature cycle

Platform (NOAA-20 vs. Suomi-NPP) doesn't need to be a stratification axis — just check the balance after sampling and you should naturally get a mix since both cover CONUS regularly. If it comes out skewed you can post-hoc adjust.

Cloud cover and weather conditions you get for free through random sampling within each cell.

#29

Should I add month as a number or string?

#30

Okay, these are my colums now: Index(['granule_time', 'platform', 'month', 'day_night', 'location'], dtype='object') - how do I start my random sampling of swaths? I guess it should be reproducible?

N = 10  # per cell
sampled = (
    gdf
    .groupby(['month', 'day_night', 'location'], group_keys=False)
    .apply(lambda g: g.sample(n=min(N, len(g)), random_state=42))
)

Two things to note: - random_state=42 (or any fixed integer) makes it reproducible - min(N, len(g)) handles sparse cells gracefully instead of erroring — worth checking afterwards how many cells actually had fewer than N granules with sampled.groupby(['month', 'day_night', 'location']).size()

How many per cell were you thinking? 72 cells (12 × 2 × 3) at N=10 gives 720 granules max, which is a lot of data to download just for stats. Even N=5 gives you 5 × 20M pixels per cell which is more than enough for stable means and stds.

#31

When you speak of granules you mean swaths? 360 is still a lot!

Yes, granule = swath in VIIRS terminology.

You're right, 360 is a lot. For normalization statistics the distribution converges very fast — you're just estimating a mean and std per channel. You could get away with N=2 per cell (144 swaths) or even N=1 (72 swaths). Each swath has ~20M pixels so even 72 swaths gives you over a billion pixel samples per channel.

I'd go with N=2 or N=3 at most.

#32

Okay! Let's do N=2 which is still a lot!

Agreed — 144 swaths × ~20M pixels = ~3 billion pixels per channel, way more than needed but at least the download won't be enormous.

One thing worth checking before you run the download: how many cells actually have fewer than 2 granules, since some month/location/day_night combinations might be sparse in your query results:

sampled.groupby(['month', 'day_night', 'location']).size().sort_values()

Any cell showing 1 instead of 2 is worth knowing about upfront.

#33

None of them have fewer than 2 swaths.

#34

Maybe I'll do N=3 after all.

#35

How about just N = 1? Or night N but do season instead of month? Over 100 swaths seems overkill

Season instead of month makes sense — the BT distribution shifts gradually enough that 4 seasons captures the important variation without needing monthly resolution. That brings the cell count from 72 to 24 (4 × 2 × 3).

N=1 is statistically fine given 20M pixels per swath, but I'd keep N=2 as a small hedge against a single bad swath (data quality issue, unusual weather event). 48 swaths total is very manageable to download.

#36

Okay, let's do seasons then but N=2. Are the seasons DJF, MAM, JJA, and SON or what is standard?

Yes, DJF/MAM/JJA/SON is the standard meteorological convention. Map month numbers like this:

season_map = {12: 'DJF', 1: 'DJF', 2: 'DJF',
               3: 'MAM', 4: 'MAM', 5: 'MAM',
               6: 'JJA', 7: 'JJA', 8: 'JJA',
               9: 'SON', 10: 'SON', 11: 'SON'}

gdf['season'] = gdf['month'].map(season_map)

Then drop month from the groupby and replace with season.

#37

Okay, let's do N=2 -> 48 swaths. Please update the README that data for band normalization is collected from 48 randomly selected swaths in 2024 with N=2 for each cell of east-west location, day/night and season. The viirs_swath_finder runs on hex, queries databased from node g01 or c018, and assigns to cells. viirs_swath_sampler samples 48 swaths. viirs_swath_downloader is called for each of the 48 swaths and downloads data to hex.

1 read · 1 edit
#38

rename viirs_swath_downloader viirs_l1b_downloader

1 edit
#39

add viirs_batch_writer - writes a downlaod batch script fo each sampled scene - to the README.

1 edit
#40

claude-code-transcripts