wrolpi/modules/map/test/test_nuclear.py
lrnselfreliance d4d288f84a
A fallout simulator on the map: nuclear mode, targets, live winds aloft (#1007)
* A fallout model, checked against six Nevada tests

The local fallout of a surface burst lands where layered winds carry particles of every size
from the stabilized cloud.  Cloud and particle sizes come from DNAF-1, WSEG-10 and DELFIC;
the air is the 1976 standard atmosphere.  The six shots' wind profiles, measured contour
areas and plume bearings are in nts-shots.json with their sources, alongside HPAC's
predictions of the same contours.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* A prototype fallout panel on the map

Right-click "Simulate Fallout Here" draws the dose rate at H+1 of one surface burst, in one
wind or in the winds aloft of one of the six Nevada tests.  Nothing is saved.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Fallout lands where it meets the ground

A particle stops falling at the first level where it is at or below the ground under it, not
at a plane at the height of ground zero: early on a ridge in its way, later in a valley.  The
map panel reads the ground from the terrain files the user has downloaded; the Nevada tests
are checked against a small elevation grid of Mapterhorn terrain, as WROLPi publishes it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Fallout falls from the cloud's cap, skirt and stem

The cloud of a surface burst holds 77.5% of its activity in the cap, 15% in a skirt below it
and 7.5% in the stem (Philippe et al.); the stem starts as narrow as the early fireball at the
ground and widens up to the cap (DNAF-1).  More of the fallout lands near ground zero: a 1 Mt
burst now draws a 1000 R/hr contour.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Close-in fallout measured after three Nevada surface bursts

Jangle Sugar, Small Boy and Johnie Boy, from DNAF-1's Table 3: the area, hotline length and
azimuth of each contour from 35 to 1000 R/hr, as observed and as DNAF-1, DELFIC and WSEG-10
predicted them, with each shot's winds.  The deposition grid can look closely at part of the
fallout, and measures hotlines.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Fallout rises with the cloud, and heavy particles drop out low

All of the activity starts in the early fireball and rises with the cloud, whose base and top
climb with the square root of time (SIMFIC).  Each particle rises with the air less its own
settling speed, so a heavy one leaves the cloud low and early and lands near ground zero, and a
light one rides to the top.  A burst above the ground puts down less, by its scaled height.

Against the close-in fallout of Jangle Sugar and Small Boy this is within 2.4x in area and 1.7x
in hotline length (it was 100x short); across the six Nevada tests, 4.2x a priori (it was 8.9x).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* The fallout panel offers the weapons in service today

Weapons deployed or stockpiled by each country, each with its yield quoted from the 2025-2026
Nuclear Notebook or SIPRI Yearbook, and the improvised devices FEMA plans for; no retired or
historical weapons, and none whose yield no source gives.  Variable-yield weapons have one entry
for each published setting.  Fission shares are not public; they are assumed as Glasstone and
Dolan plan for, and the user may change them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* The fallout panel's dropdowns open above it

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* A variable-yield weapon is named once, with each setting's yield beside it

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* The fallout panel uses the forecast winds aloft

WROLPi fetches, on request, Open-Meteo's hourly forecast of the wind at nineteen pressure levels
(about 100 m to 24 km) and the rain, for the whole degree around the burst: the place is rounded
before it is sent.  The forecast is kept, so the panel can use it offline.  The panel picks the
hour nearest now, gives the forecast's age, and warns of rain, which brings fallout down in places
the map does not show.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* A nuclear mode on the map: targets, and fallout

A radiation button under the print button turns nuclear mode on and off.  In it, targets (likely
detonation sites) are shown alongside the pins, a pin added is saved as a target, and fallout can
be simulated at a target or anywhere on the map.  A pin's kind is kept in map_pins.yaml; a pin
without one is a plain pin, as every pin was.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Targets keep their weapon, and nuclear mode shows the fallout of all of them

A target keeps the weapon chosen for it (or a yield of the user's own) and its fission share in
map_pins.yaml.  Nuclear mode opens on the fallout of every saved target at once, in the forecast
winds aloft fetched most recently; a burst tried out from the map can be saved as a target.

A whole-degree latitude or longitude, which a browser sends as an integer, is a valid pin, and a
pin's label and color may be left out of an update.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* An improvised device is named once, with each yield beside it

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Fallout of many targets is calculated in seconds, and shown as it goes

A particle size's settling speed is read from a table by altitude rather than solved again for
every fall of every burst (a burst: 40 ms to 6 ms).  The view yields to the page only every 40 ms,
through a message channel, which a browser does not hold back in a hidden tab as it does timers;
it says how far it has got, and draws the fallout on flat ground while the terrain is read.

A target in the list shows its weapon, and is given a weapon picker when asked; one picker sets
every target's weapon.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* The fallout grid covers where fallout shows, not past the poles

The faintest particles of a burst are carried thousands of km in two days; with many targets the
grid stretched past 90 degrees and the map refused the image ("Invalid LngLat latitude").  The grid
now covers the spots which can reach the faintest band drawn, the image's corners stay within
Web Mercator's 85 degrees, and so does the area whose terrain is read.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Fallout across a continent is drawn where it lands

The map stretches an image evenly in Web Mercator between its corners, but the fallout grid's rows
are evenly apart in latitude; over tens of degrees (targets across a country) they part ways, and
the southern part of the image was drawn far from its targets.  Each image row now takes the grid
row at its own latitude.  A burst far from the first target keeps its plume as wide, east to west,
as at its own latitude.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Terrain across the antimeridian, and ground with no number, do not break the fallout

Targets in Alaska and Hawaii carry fallout west of 180 degrees, where the terrain's tile arithmetic
read past the tile's pixels; one sample with no number made every target's lowest ground NaN and
every spot fall off the map, and the grid's size Infinity.  Longitudes wrap, a sample with no number
is left out (of the lowest ground, and of the elevation between samples), and a spot not on the map
is left out of the grid rather than breaking it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Every target's weapon is set in one change

Setting it target by target, eight at once, lost most of the changes: each request wrote the whole
pin list, undoing the others (QA: 47 of 156 changed).  PUT /api/map/pins/targets/weapon gives
every target the weapon in one change of the config.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* The every-target weapon picker starts empty and always applies

It showed the first target's weapon, so choosing that weapon for all of them did nothing.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Fallout is carried by the winds where it is, region by region

A field of forecasts on a grid over the targets replaces the one forecast for
all of them. Each particle rises and falls through the wind at its place,
height and hour, read between the surrounding grid points, hours and heights.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* The winds aloft are fetched as a Job, ninety places a minute

The free forecast service allows 600 calls a minute and a place costs six, so
a field of up to 540 points is fetched in paced batches by a Job, which the
fallout panel follows, instead of inside one request.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* A small burst's hot fallout is kept on a grid over many, and the panel says what it shows

- Each burst's narrow close-in fallout is also put on a fine grid, so the
  lethal zone of a small target is not averaged away in the cells kilometers
  wide of a grid over targets far apart.
- The legend says the dose rate is as at one hour, with all the fallout down,
  and what R/hr is; the error quoted is the unscaled model's.
- The TNA's yield is 150 kt: its source gives only an upper bound below 300.
- Weapons show their fission share beside their yield.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* The fallout can be watched landing, hour by hour

A timeline under the legend plays, or steps through, the 48 hours after the
bursts: each hour shows only the fallout which has landed by then, at its
dose rate then (t^-1.2 from H+1), on the same cells as the whole of it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* The map can show the total dose of someone outdoors, hour by hour

A "Show" picker switches from the dose rate to the total dose (R) someone
outdoors gets from when the fallout arrives: t^-1.2 added up from each spot's
arrival to the hour on the timeline, or over the first two weeks. Its bands
say what each dose does to a person.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* The model is checked against the Army's fallout manuals

- FM 3-3-1's worked decay and dose problems are tests.
- FM 3-11.3's cloud and Zone I nomograms, read from their images, are a
  fixture; the model's cloud top is within 10% of them from 1 kt to 10 Mt,
  and its Zone I within 0.7-1.7 times from 10 kt to 1 Mt, the yields of
  modern weapons, which the test shots do not reach.
- The legend says real fallout may decay faster or slower than usual.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* The model is checked against two megaton bursts in the Pacific

Redwing Zuni (3.5 Mt), whose winds were measured above its cloud: the hot
fallout goes where it went and about as far. Castle Bravo (15 Mt), whose
winds were measured only below its cloud: its fallout arrives when it did,
and its hot fallout reaching a third as far is kept in view as a known gap.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Winds are read from the right points at every spacing, and cover the landing

- A field's points were filed by rounding (lat + 90) / spacing but looked up
  by flooring it: at 4 and 8 degrees, which do not divide 90, every point read
  half its neighbor's wind. Both now count whole spacings from the equator.
- The forecast starts at midnight UTC, so two days could end before the
  fallout of a burst this hour was down; three are fetched (the same call
  weight), and the panel says when the last hour's winds are held.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Bravo's known gap is not its unmeasured upper winds

Reanalysis winds above the 1954 sounding turn the plume to within 10 degrees
of the measured one but do not lengthen its hot contours; the fixture's caveat
and the test's explanation said otherwise, and now say what was found.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Rain takes fallout out of the air where it falls

A falling particle in rain loses a share of its activity every step: fast
inside the rain cloud ("rainout"), slower below it, by how hard it rains
("washout"), at Glasstone and Dolan's rates (Tables 9.74a and b), and none
above it. What is taken out comes down where the particle was. The forecast
now asks for relative humidity at 14 levels, and each hour's rain cloud is
taken as HYSPLIT takes it: from the lowest level 80% humid to the first above
it less than 60%.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* With no forecast, the fallout of 30 past days of the month

- wrolpi/scripts/build_fallout_climatology.py builds, from NOAA's reanalysis,
  the winds aloft of 30 days of each month (one from each year 1991-2020) over
  the whole world: a gzip file a month, about 4 MB, for the release download
  location.
- WROLPi fetches the months it lacks once, while there is the Internet, each
  checked against a sha256 pinned in modules/map/climatology.py (none pinned
  until the files are published), and serves them to the panel.
- The panel's "Past days of a month" wind runs the bursts in each day and shows
  on what share of the days each place had the chosen dose rate; it is chosen
  for us when there is no forecast, or it has run out.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* The climatology's months are published, and their sha256 pinned

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* The climatology worker waits for the Internet and the drive on startup

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Counting the past days says flat ground at once, not the forecast's terrain

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Past days' fallout reuses each yield's paths, about 10 times faster

On flat ground in a day's held winds, how each parcel rises with the cloud
and falls does not depend on the wind, so it is worked out once per yield
and kept for every burst and day.  The rising cloud is carried by the winds
over ground zero (it drifts about 10 km); the fall still reads the winds
where the particle is.  A field of one hour is read without its hours, and
the nearest point to a cell past the field is kept.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* The rising cloud reads the winds over ground zero from arrays, by level

Each parcel's rise is kept as the levels of the column it passes through
(steps in the same level as one) and their seconds, so a burst reads the
column once and sums.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* The fallout panel shows a progress bar while it calculates

At the top of the panel, filled as far as the bursts are done, or moving
without a count until there is one.  A calculation stopped by removing the
last target no longer leaves the panel busy.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Past days' fallout runs in Web Workers, with a Cancel button

The days are spread over workers, one for each core but one (left for the
page), at most 6, and at most 2 where the browser says it has 2 GB or less.
A worker is given the next day as it finishes one, and sends back only the
cells reached.  Where workers cannot be made, or fail, the days are
calculated on the page as before.

The days are counted on cells as wide as the coarsest day's grid, so the
count does not depend on which day finishes first.

Cancel, beside the progress bar, stops a calculation (and its workers) at
once; Calculate starts it again.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* The forecast's bursts are spread over Web Workers too

The workers now take any task: a past day, or a burst.  The page and the
workers build each burst's winds and terrain with the same functions
(work.js), so the fallout is the same either way; the flat pass and the
terrain pass each run on their own workers, and Cancel stops them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* The bursts' grid is made in parts by the Web Workers

The grid is a sum over the bursts' spots, sharpened by the most any burst
raises a cell, so it is made in a fixed number of parts (a burst's spots
in one) on one frame, and joined on the page.  The page makes the same
parts when there are no workers, so the grid is the same either way.

The forecast's warnings (bursts outside the winds, rain) are no longer
worked out again on every progress update.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* The forecast's hours are labeled once an hour, not on every progress update

Writing each hour's label (toLocaleString) took most of the page's time
while the workers calculated.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Faster forecast fallout: the nearest point outside the field, progress, and what workers are sent

- Outside the forecast's field, the nearest point is looked for only
  among the points which can be nearest somewhere in the grid cell (kept
  for each cell); the same point as looking through them all.  Longitudes
  are wrapped however far round the world a particle is carried.
- The progress is shown at most ten times a second.
- The workers are sent the forecast's arrays, not the forecast as fetched.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* The fallout panel in steps: the targets, then the fallout hour by hour or in total

Nuclear mode opens on the targets; nothing is calculated until the user goes on.
The winds and terrain wait under Options, with what is used said beside it.
The timeline runs from the first hour to two weeks, saying how much the fallout
has weakened since H+1; the view of all the fallout as if landed at H+1 is gone.
Going back and on again with nothing changed draws what was calculated.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* The fallout panel's winds: the forecast, past days, or one wind; no test shots' winds

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* The fallout panel's wind is a step of its own, between the targets and the fallout

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* The fallout panel says it is an estimate; how it compares with the test bursts goes in the help

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Targets are tried out until saved; the saved ones are loaded first, and saved all at once

Nuclear mode starts with no targets.  Targets added are tried out, and the saved
targets join them when the user loads them.  Saving replaces the saved targets
with the list, in one change, and is refused until they were loaded (or there are
none), so none are lost unseen.  A target can be taken out of the list.  The
burst tried out from the map's menu is gone: a target tried out does the same.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Nuclear targets are kept in their own config, map_nuclear.yaml, and listed apart from the pins

The pins are plain pins again.  The targets have their own endpoints, and their
own table on the Pins tab, where one can be deleted.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* The rest of keeping nuclear targets in map_nuclear.yaml: the config, its endpoints, and the table

The commit before this one was missing these files.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* The fallout panel's wind is the forecast when it has the winds until the fallout is down, else one wind

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* The weather is a subscription: a forecast around the saved targets, downloaded every day

The Open-Meteo fetch is a recurring Download (daily) instead of a Job the panel
starts.  The Manage tab has a Weather section: turning it on or off, what it
downloads, how its downloads went, and the forecast kept.  Only the newest
forecast is kept, and it covers four days.  The wind step asks the user to turn
the download on, and warns, there and beside the fallout, when the forecast runs
out before the fallout is down.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* The forecast service may take three minutes to answer, and a timeout says so

A batch of four days' forecasts took 43 seconds, near the old 60-second limit.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* The fallout panel's targets step has an Add a target button: the next click on the map places it

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 12:01:41 -07:00

98 lines
5.3 KiB
Python

import json
from http import HTTPStatus
import pytest
from modules.map import nuclear
def saved(config, *targets):
"""`targets` ({lat, lon, label, ...}) saved in place of none."""
return config.replace_targets(list(targets), loaded_ids=[t['id'] for t in config.targets])
def test_replace_targets(test_nuclear_config):
"""The targets given are saved in place of those loaded: kept ones keep their id and date, new ones
get ids, and removed ones are gone."""
a, b = saved(test_nuclear_config, {'lat': 1, 'lon': 1, 'label': 'A', 'weapon': 'yars'},
{'lat': 2, 'lon': 2, 'label': 'B', 'weapon': 'yars'})
assert (a['id'], b['id']) == (1, 2)
kept = test_nuclear_config.replace_targets([
{'id': a['id'], 'lat': 1, 'lon': 1, 'label': 'A', 'weapon': 'custom', 'yield_kt': 20, 'fission_fraction': 1},
{'lat': 3.1234567, 'lon': -3, 'label': ' C ', 'weapon': 'w88'},
], loaded_ids=[a['id'], b['id']])
assert [(t['id'], t['label']) for t in kept] == [(1, 'A'), (3, 'C')]
assert kept[0]['created'] == a['created'] and kept[0]['yield_kt'] == 20
assert kept[1] == dict(id=3, lat=3.123457, lon=-3, label='C', created=kept[1]['created'], weapon='w88')
assert test_nuclear_config.targets == kept
def test_replace_targets_refused(test_nuclear_config):
"""Nothing is saved over targets the user did not load, or which changed since; nor bad targets."""
a, = saved(test_nuclear_config, {'lat': 1, 'lon': 1, 'label': 'A'})
with pytest.raises(nuclear.TargetsChanged):
test_nuclear_config.replace_targets([{'lat': 2, 'lon': 2, 'label': 'B'}], loaded_ids=[])
with pytest.raises(nuclear.TargetsChanged):
test_nuclear_config.replace_targets([], loaded_ids=[a['id'], 99])
for bad in ({'lat': 1, 'lon': 1, 'label': ' '}, {'lat': 91, 'lon': 1, 'label': 'X'},
{'lat': 'north', 'lon': 1, 'label': 'X'}, {'lat': 1, 'lon': 1, 'label': 'X', 'yield_kt': -1},
{'lat': 1, 'lon': 1, 'label': 'X', 'fission_fraction': 2}, {'lat': 1, 'lon': 1, 'label': 'X', 'weapon': ''}):
with pytest.raises(ValueError):
test_nuclear_config.replace_targets([bad], loaded_ids=[a['id']])
with pytest.raises(ValueError):
test_nuclear_config.replace_targets([{'id': a['id'], 'lat': 1, 'lon': 1, 'label': 'A'}] * 2,
loaded_ids=[a['id']])
assert test_nuclear_config.targets == [a]
def test_replace_targets_with_none_saved(test_nuclear_config):
"""With no saved targets there is nothing to load first."""
assert [t['label'] for t in saved(test_nuclear_config, {'lat': 1, 'lon': 1, 'label': 'A'})] == ['A']
def test_delete_target(test_nuclear_config):
a, b = saved(test_nuclear_config, {'lat': 1, 'lon': 1, 'label': 'A'}, {'lat': 2, 'lon': 2, 'label': 'B'})
assert test_nuclear_config.delete_target(a['id']) is True
assert test_nuclear_config.delete_target(a['id']) is False
assert test_nuclear_config.targets == [b]
@pytest.mark.asyncio
async def test_targets_api(async_client, test_nuclear_config):
for i in range(20):
saved(test_nuclear_config, *test_nuclear_config.targets, {'lat': i, 'lon': i, 'label': f'Base {i}',
'weapon': 'yars'})
request, response = await async_client.get('/api/map/nuclear/targets')
assert response.status_code == HTTPStatus.OK
loaded = [t['id'] for t in response.json['targets']]
assert len(loaded) == 20
one = {'id': loaded[0], 'lat': 0, 'lon': 0, 'label': 'Base 0', 'weapon': 'w76-1', 'fission_fraction': 0.5}
# Not loaded: refused.
request, response = await async_client.put('/api/map/nuclear/targets',
content=json.dumps({'targets': [one], 'loaded_ids': []}))
assert response.status_code == HTTPStatus.CONFLICT
assert 'load them again' in response.json['error']
request, response = await async_client.put('/api/map/nuclear/targets',
content=json.dumps({'targets': [one], 'loaded_ids': loaded}))
assert response.status_code == HTTPStatus.OK
assert [t['weapon'] for t in response.json['targets']] == ['w76-1']
request, response = await async_client.put('/api/map/nuclear/targets', content=json.dumps(
{'targets': [{'lat': 0, 'lon': 0, 'label': ''}], 'loaded_ids': [loaded[0]]}))
assert response.status_code == HTTPStatus.BAD_REQUEST
request, response = await async_client.delete(f'/api/map/nuclear/targets/{loaded[0]}')
assert response.status_code == HTTPStatus.NO_CONTENT
request, response = await async_client.delete(f'/api/map/nuclear/targets/{loaded[0]}')
assert response.status_code == HTTPStatus.NOT_FOUND
request, response = await async_client.get('/api/map/nuclear/targets')
assert response.json['targets'] == []
@pytest.mark.asyncio
async def test_targets_apart_from_pins(async_client, test_nuclear_config, test_directory):
"""Targets are kept in their own config, and the pins hold none."""
saved(test_nuclear_config, {'lat': 1, 'lon': 1, 'label': 'A'})
test_nuclear_config.save()
assert 'label: A' in (test_directory / 'config/map_nuclear.yaml').read_text()
request, response = await async_client.get('/api/map/pins')
assert all(p['label'] != 'A' for p in response.json['pins'])