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>
This commit is contained in:
lrnselfreliance 2026-11-25 12:01:13 -07:00 • committed by Roland
parent 72b507116e
commit d4d288f84a
No known key found for this signature in database
GPG key ID: 1BA620CE6C9A4680
50 changed files with 8663 additions and 38 deletions

View file

@ -78,7 +78,10 @@
},
"transformIgnorePatterns": [
"node_modules/(?!(react-hotkeys-hook|three|@mapbox/vector-tile|@mapbox/point-geometry|pbf)/)"
]
],
"moduleNameMapper": {
"^(.*)/falloutWorker(\\.js)?$": "$1/falloutWorker.stub.js"
}
},
"overrides": {
"@babel/code-frame": "7.29.0",

View file

@ -1712,6 +1712,88 @@ export async function mapUnsubscribe(region) {
}
}
// Which months of the fallout climatology are kept: {version, months, missing, published}, or null.
export async function getFalloutClimatology() {
const response = await apiGet(`${API_URI}/map/fallout/climatology`);
return response.ok ? await response.json() : null;
}
// One month of the fallout climatology, as kept (gzip bytes), or null.
export async function getFalloutClimatologyMonth(month) {
const response = await apiGet(`${API_URI}/map/fallout/climatology/${month}`);
return response.ok ? await response.arrayBuffer() : null;
}
// The field of forecast winds aloft fetched most recently (the fallout simulator), or null.
export async function getLatestFalloutWinds() {
const response = await apiGet(`${API_URI}/map/fallout/winds/latest`);
if (response.ok) {
return (await response.json()).winds;
}
return null;
}
// The saved nuclear targets ([{id, lat, lon, label, created, weapon, yield_kt?, fission_fraction?}]), or
// undefined when they could not be fetched.
export async function getMapTargets() {
const response = await apiGet(`${API_URI}/map/nuclear/targets`);
if (response.ok) {
return (await response.json()).targets;
}
}
export async function deleteMapTarget(targetId) {
const response = await apiDelete(`${API_URI}/map/nuclear/targets/${targetId}`);
if (!response.ok) {
const message = await getErrorMessage(response, 'Could not delete the target');
toast({type: 'error', title: 'Map Error', description: message, time: 5000});
}
return response.ok;
}
// Save `targets` ([{lat, lon, label, weapon, yield_kt?, fission_fraction?, id?}]) in place of the
// saved targets, which are those of `loadedIds` (refused if they are not): the saved targets, or null.
export async function saveMapTargets(targets, loadedIds) {
const response = await apiPut(`${API_URI}/map/nuclear/targets`, {targets, loaded_ids: loadedIds});
if (!response.ok) {
const message = await getErrorMessage(response, 'Could not save the targets');
toast({type: 'error', title: 'Map Error', description: message, time: 5000});
return null;
}
return (await response.json()).targets;
}
// The weather subscription (a forecast around the nuclear targets, downloaded every day): {enabled,
// download, targets, spacing, points, seconds, field}, or undefined when it could not be fetched.
export async function getWeather() {
const response = await apiGet(`${API_URI}/map/weather`);
if (response.ok) {
return await response.json();
}
}
// Subscribe to the weather, or not: the subscription as it is then, or null.
export async function setWeatherSubscription(enabled) {
const response = await apiPut(`${API_URI}/map/weather`, {enabled});
if (response.ok) {
return await response.json();
}
const message = await getErrorMessage(response, 'Could not change the weather download');
toast({type: 'error', title: 'Map Error', description: message, time: 5000});
return null;
}
// Download the weather now, rather than when it is next due: the subscription as it is then, or null.
export async function downloadWeatherNow() {
const response = await apiPost(`${API_URI}/map/weather/download`);
if (response.ok) {
return await response.json();
}
const message = await getErrorMessage(response, 'Could not download the weather');
toast({type: 'error', title: 'Map Error', description: message, time: 5000});
return null;
}
export async function getMapPins() {
const response = await apiGet(`${API_URI}/map/pins`);
if (response.ok) {

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,736 @@
import {WEAPON_CHOICES} from './FalloutPanel';
import {serveFallout} from '../map-shared/fallout/work.js';
import {loadTerrainGrid} from './falloutTerrain';
// No terrain files under Jest, until a test gives a grid.
jest.mock('./falloutTerrain', () => ({loadTerrainGrid: jest.fn(async () => null)}));
// No forecast (unless a test gives one), past days or fetches under Jest.
let mockLatestWinds = null;
let mockWeather = {enabled: true, download: {status: 'complete'}, targets: 1, spacing: 1, points: 160, seconds: 61,
field: null};
const mockWeatherSet = [];
jest.mock('../api', () => ({
getFalloutClimatology: async () => null,
getFalloutClimatologyMonth: async () => null,
getWeather: async () => mockWeather,
setWeatherSubscription: (enabled) => {
mockWeatherSet.push(enabled);
return Promise.resolve({...mockWeather, enabled});
},
downloadWeatherNow: async () => mockWeather,
getLatestFalloutWinds: async () => mockLatestWinds,
}));
// Fallout workers serving their tasks (as fallout.worker.js does) here, as a browser's would on
// another thread: messages arrive later, copied. `made` are those made since it was emptied.
const made = [];
const copy = (v) => {
if (v instanceof ArrayBuffer) return v.slice(0);
if (ArrayBuffer.isView(v)) return v.slice();
if (Array.isArray(v)) return v.map(copy);
if (v && typeof v === 'object') return Object.fromEntries(Object.entries(v).map(([k, x]) => [k, copy(x)]));
return v;
};
function worker({fail = false} = {}) {
const scope = {postMessage: (data) => setTimeout(() => !w.terminated && w.onmessage?.({data}), 0)};
serveFallout(scope);
const w = {
terminated: false, onmessage: null, onerror: null, given: [], kind: null,
postMessage(data) {
if (data.type === 'start') {
w.kind = data.kind;
w.start = data;
}
if (data.type === 'task') w.given.push(data.k);
const copied = copy(data);
setTimeout(() => {
if (w.terminated) return;
if (fail && data.type === 'task') w.onerror?.({message: 'No such script'});
else scope.onmessage({data: copied});
}, 0);
},
terminate() {
w.terminated = true;
},
};
made.push(w);
return w;
}
describe('the fallout panel\'s weapons', () => {
test('are grouped by country, then a yield of one\'s own', () => {
const groups = WEAPON_CHOICES.map((g) => g.group);
expect(groups[0]).toBe('United States');
expect(groups).toContain('Russia');
expect(groups).toContain('Improvised nuclear device');
expect(groups[groups.length - 1]).toBe('Other');
expect(WEAPON_CHOICES[groups.length - 1].items.map((i) => i.value)).toEqual(['custom']);
});
test('each read differently, by name and yield', () => {
const labels = WEAPON_CHOICES.flatMap((g) => g.items.map((i) => i.label));
expect(new Set(labels).size).toBe(labels.length);
expect(labels).toContain('B61-12 bomb, 0.3 kt, half fission');
});
test('say their yield', () => {
const w88 = WEAPON_CHOICES[0].items.find((i) => i.value === 'w88');
expect(w88.label).toBe('W88 (Trident II D5), 455 kt, half fission');
});
});
describe('the fallout panel\'s winds', () => {
const {windProfile, hourLabel} = require('./FalloutPanel');
test('fall back to one wind at every height until there is a forecast', () => {
const profile = windProfile({direction: 270, speed: 10});
expect(profile).toHaveLength(1);
expect(profile[0][1]).toBeGreaterThan(0);
});
test('mark the hour nearest now', () => {
expect(hourLabel('2026-11-22T00:00Z', true)).toMatch(/\(now\)$/);
expect(hourLabel('2026-11-22T00:00Z', false)).not.toMatch(/now/);
});
});
describe('the fallout of several bursts', () => {
const {simulateBursts} = require('./FalloutPanel');
const {prepareField} = require('../map-shared/fallout/winds.js');
const winds = {profile: [[0, 10, 0]]};
const bursts = [
{lat: 40, lon: -105, yieldKt: 10, fissionFraction: 0.5},
{lat: 40.5, lon: -104, yieldKt: 100, fissionFraction: 0.5},
];
// A forecast over 39-42 N, 106-103 W, every degree, whose wind turns from the west to the
// south-west over the hours, on ground rising to the east.
const HOURS = ['2026-11-22T00:00Z', '2026-11-22T01:00Z', '2026-11-22T02:00Z'];
function forecast() {
const points = [];
for (const lat of [39, 40, 41, 42]) for (const lon of [-106, -105, -104, -103]) points.push({lat, lon, elevation: 1500 + (lon + 106) * 100});
return {
source: 'Open-Meteo', fetched_at: '2026-11-22T00:30:00+00:00', spacing: 1, points, hours: HOURS,
winds: points.map(() => HOURS.map((_, h) => [[10, 12, 270 - 20 * h], [20000, 30, 260 - 20 * h]])),
rain: points.map(() => HOURS.map(() => 0)),
};
}
const fieldWinds = () => ({prepared: prepareField(forecast()), startMs: Date.parse(HOURS[0])});
test('carries each burst by the winds where it is, from the ground there', async () => {
const ran = await simulateBursts(bursts, {winds: fieldWinds(), useTerrain: false});
expect(ran.grid.values.some((v) => v > 0)).toBe(true);
// Not as one wind would carry them.
const one = await simulateBursts(bursts, {winds, useTerrain: false});
expect(ran.grid.values.length === one.grid.values.length
&& ran.grid.values.every((v, i) => v === one.grid.values[i])).toBe(false);
});
test('is drawn on one grid around the first burst', async () => {
const one = await simulateBursts(bursts.slice(0, 1), {winds, useTerrain: false});
const both = await simulateBursts(bursts, {winds, useTerrain: false});
expect(both.origin).toBe(bursts[0]);
const sum = (g) => g.values.reduce((a, v) => a + v, 0) * g.cell ** 2;
expect(sum(both.grid)).toBeGreaterThan(sum(one.grid) * 5);
expect(both.terrainStatus).toMatch(/terrain is off/);
});
test('stops when it is no longer wanted', async () => {
expect(await simulateBursts(bursts, {winds, useTerrain: false, cancelled: () => true})).toBeNull();
});
const MANY = Array.from({length: 7}, (_, i) => ({lat: 40 + 0.2 * i, lon: -105 + 0.3 * i, yieldKt: 5 * (i + 1), fissionFraction: 0.5}));
// Whether two results have the same grid (said quickly: Jest's diff of such arrays takes minutes).
const same = (a, b) => a.grid.cell === b.grid.cell && a.grid.values.length === b.grid.values.length
&& a.grid.values.every((v, i) => v === b.grid.values[i]);
test('spreads the bursts over workers, as the page calculates them', async () => {
for (const w of [winds, fieldWinds()]) {
made.length = 0;
const here = await simulateBursts(MANY, {winds: w, useTerrain: false});
const heard = [];
const spread = await simulateBursts(MANY, {winds: w, useTerrain: false, workers: 3, makeWorker: () => worker(),
onProgress: (done, total) => heard.push([done, total])});
// The bursts by three workers, then the grid's parts by three more.
const burstWorkers = made.filter((x) => x.kind === 'bursts');
const gridWorkers = made.filter((x) => x.kind === 'grid');
expect(burstWorkers).toHaveLength(3);
expect(gridWorkers).toHaveLength(3);
expect(burstWorkers.flatMap((x) => x.given).sort()).toEqual([0, 1, 2, 3, 4, 5, 6]);
expect(gridWorkers.flatMap((x) => x.given).length).toBeGreaterThan(3);
expect(made.every((x) => x.given.length > 0 && x.terminated)).toBe(true);
expect(heard[heard.length - 1]).toEqual([7, 7]);
expect(same(spread, here)).toBe(true);
expect(JSON.stringify(spread.spots) === JSON.stringify(here.spots)).toBe(true);
// Given the forecast's arrays, not the forecast as fetched.
if (w.prepared) {
const {prepared} = burstWorkers[0].start;
expect(prepared.u).toBeInstanceOf(Float32Array);
expect(prepared.field.winds).toBeUndefined();
expect(prepared.field.points).toHaveLength(16);
}
}
});
test('shows its progress every so often, and when all is done', () => {
const {everySoOften} = require('./FalloutPanel');
jest.useFakeTimers();
try {
const heard = [];
const report = everySoOften((done, total) => heard.push(done));
for (let done = 1; done <= 10; done++) {
report(done, 10);
jest.advanceTimersByTime(30);
}
// The first, one in every four after it (30 ms apart), and the last.
expect(heard).toEqual([1, 5, 9, 10]);
} finally {
jest.useRealTimers();
}
});
test('gives its workers the terrain, when it is read', async () => {
// Ground rising to the north-east of the bursts.
const nx = 81, ny = 81, step = 0.05;
const grid = {west: -107, south: 38, step, nx, ny, values: new Float32Array(nx * ny)};
for (let j = 0; j < ny; j++) for (let i = 0; i < nx; i++) grid.values[j * nx + i] = 1500 + 40 * (i + j);
loadTerrainGrid.mockImplementation(async () => ({grid, zoom: 9, coverage: 1}));
try {
const flat = await simulateBursts(MANY, {winds: fieldWinds(), useTerrain: false});
const here = await simulateBursts(MANY, {winds: fieldWinds(), useTerrain: true});
made.length = 0;
const heard = [];
const spread = await simulateBursts(MANY, {winds: fieldWinds(), useTerrain: true, workers: 2,
makeWorker: () => worker(), onProgress: (done, total) => heard.push([done, total])});
expect(here.terrainStatus).toMatch(/Follows the terrain/);
expect(same(here, flat)).toBe(false);
expect(same(spread, here)).toBe(true);
// A pass on flat ground, then another over the terrain, each by its own workers.
expect(made.map((x) => x.kind)).toEqual(['bursts', 'bursts', 'grid', 'grid', 'bursts', 'bursts', 'grid', 'grid']);
expect(heard[heard.length - 1]).toEqual([14, 14]);
} finally {
loadTerrainGrid.mockImplementation(async () => null);
}
});
test('stops its workers at once when cancelled', async () => {
made.length = 0;
const controller = new AbortController();
const running = simulateBursts(MANY, {winds, useTerrain: false, workers: 3, makeWorker: () => worker(),
signal: controller.signal});
controller.abort();
expect(await running).toBeNull();
expect(made).toHaveLength(3);
expect(made.every((x) => x.terminated)).toBe(true);
});
test('calculates on the page when its workers fail, or there are none', async () => {
made.length = 0;
const error = jest.spyOn(console, 'error').mockImplementation(() => null);
const here = await simulateBursts(MANY, {winds, useTerrain: false});
const ran = await simulateBursts(MANY, {winds, useTerrain: false, workers: 2, makeWorker: () => worker({fail: true})});
expect(error).toHaveBeenCalled();
error.mockRestore();
expect(made.every((x) => x.terminated)).toBe(true);
expect(same(ran, here)).toBe(true);
const none = await simulateBursts(MANY, {winds, useTerrain: false, workers: 2, makeWorker: () => null});
expect(same(none, here)).toBe(true);
});
});
describe('the fallout image', () => {
const {imageRows} = require('./FalloutPanel');
test('takes each row from the grid row at its own latitude', () => {
// A grid from 20 to 80 degrees north, around 40: a tenth of a degree a row.
const grid = {y0: -20 * 111320, cell: 11132, ny: 600, nx: 1};
const rows = imageRows(grid, 40, 600);
// The top row is the grid's northernmost, the bottom its southernmost.
expect(rows[0]).toBe(599);
expect(rows[599]).toBe(0);
// Halfway down the image, in Web Mercator, is well north of halfway in latitude (50 degrees).
expect(rows[300]).toBeGreaterThan(330);
for (let r = 1; r < 600; r++) expect(rows[r]).toBeLessThanOrEqual(rows[r - 1]);
});
test('is the plain grid over a small area', () => {
const grid = {y0: -5000, cell: 100, ny: 100, nx: 1};
const rows = imageRows(grid, 40, 100);
expect(rows[0]).toBe(99);
expect(Math.abs(rows[50] - 49)).toBeLessThanOrEqual(1);
});
});
describe('the fallout timeline', () => {
const {screen, fireEvent} = require('@testing-library/react');
const {renderWithProviders} = require('../test-utils');
const {Timeline, HOURS, afterLabel, weakerThanH1} = require('./FalloutPanel');
test('runs from the first hour to two weeks, in longer steps as it goes', () => {
expect(HOURS[0]).toBe(1);
expect(HOURS[HOURS.length - 1]).toBe(336);
for (let k = 1; k < HOURS.length; k++) expect(HOURS[k]).toBeGreaterThan(HOURS[k - 1]);
expect(HOURS.map(afterLabel)).toEqual(['1 hour', '2 hours', '3 hours', '6 hours', '12 hours', '1 day',
'2 days', '3 days', '5 days', '1 week', '2 weeks']);
});
test('says how much the fallout has weakened since H+1', () => {
// t^-1.2: about 10 times weaker for every 7 times longer.
expect(weakerThanH1(7)).toBe('10');
expect(weakerThanH1(3)).toBe('3.7');
expect(weakerThanH1(48)).toBe('100');
expect(weakerThanH1(336)).toBe('1,100');
});
test('says what it shows, and moves and plays the hours', () => {
const onAfter = jest.fn(), onPlaying = jest.fn();
const {unmount} = renderWithProviders(<Timeline after={1} onAfter={onAfter} playing={false}
onPlaying={onPlaying} startMs={null}/>);
expect(screen.getByText(/^H\+1: the fallout landed by then\.$/)).toBeTruthy();
// Each step of the slider is one of the hours.
fireEvent.change(screen.getByLabelText('Time after the bursts'), {target: {value: String(HOURS.indexOf(48))}});
expect(onAfter).toHaveBeenCalledWith(48);
fireEvent.click(screen.getByLabelText('Play'));
expect(onPlaying).toHaveBeenCalledWith(true);
unmount();
renderWithProviders(<Timeline after={6} onAfter={onAfter} playing={true} onPlaying={onPlaying}
startMs={Date.parse('2026-11-22T00:00Z')}/>);
expect(screen.getByText(/^H\+6, .*: the fallout landed by then, about 8\.6 times weaker than at H\+1\.$/)).toBeTruthy();
expect(screen.getByLabelText('Time after the bursts').getAttribute('aria-valuetext')).toBe('6 hours');
fireEvent.click(screen.getByLabelText('Pause'));
expect(onPlaying).toHaveBeenLastCalledWith(false);
});
});
describe('the total dose view', () => {
const {TOTAL_BANDS, DOSE_BANDS, legendHeading, legendText} = require('./FalloutPanel');
test('has its own bands, each saying what it does to a person', () => {
expect(TOTAL_BANDS.map((b) => b.rate)).toEqual([1000, 450, 100, 25, 5]);
for (const b of TOTAL_BANDS) expect(b.meaning.length).toBeGreaterThan(5);
// The same colors, highest first.
expect(TOTAL_BANDS.map((b) => b.color)).toEqual(DOSE_BANDS.map((b) => b.color));
});
test('says what is shown, by the hour', () => {
expect(legendHeading('total', 6)).toBe('Total dose outdoors in the first two weeks');
expect(legendHeading('rate', 1)).toBe('Dose rate 1 hour after the bursts');
expect(legendHeading('rate', 120)).toBe('Dose rate 5 days after the bursts');
expect(legendText('total')).toMatch(/outdoors the whole time/);
expect(legendText('rate')).toMatch(/landed by then/);
expect(legendText('rate')).toMatch(/weakens/);
});
});
describe('the forecast\'s warning', () => {
const {forecastShortText} = require('./FalloutPanel');
const hourMs = Math.floor(Date.now() / 3600000) * 3600000;
const of = (from, count) => ({hours: Array.from({length: count}, (_, h) => new Date(hourMs + (from + h) * 3600000).toISOString())});
test('says when it has run out, or ends before the fallout is down, and else nothing', () => {
expect(forecastShortText(null, 0)).toBeNull();
expect(forecastShortText(of(-30, 10), 9)).toMatch(/has run out/);
expect(forecastShortText(of(-1, 30), 1)).toMatch(/ends at .*, before all the fallout is down/);
expect(forecastShortText(of(-1, 96), 1)).toBeNull();
});
});
describe('the targets simulated', () => {
const {withSavedTargets, targetsUnsaved, withWeapon} = require('./FalloutPanel');
const saved = [{id: 1, label: 'A', lat: 1, lon: 1, kind: 'target', weapon: 'yars'},
{id: 2, label: 'B', lat: 2, lon: 2, kind: 'target', weapon: 'custom', yield_kt: 20, fission_fraction: 1}];
const tried = {key: 'new-1', label: 'C', lat: 3, lon: 3, weapon: 'w88'};
test('are the saved ones once loaded, then those tried out', () => {
const loaded = withSavedTargets(saved, [tried]);
expect(loaded.map((t) => t.key)).toEqual(['saved-1', 'saved-2', 'new-1']);
// Loading again keeps the tried ones once, and the saved ones as saved.
expect(withSavedTargets(saved, loaded).map((t) => t.key)).toEqual(['saved-1', 'saved-2', 'new-1']);
});
test('are unsaved when they differ from the saved ones', () => {
expect(targetsUnsaved([], saved, false)).toBe(false);
expect(targetsUnsaved([tried], saved, false)).toBe(true);
const loaded = withSavedTargets(saved, []);
expect(targetsUnsaved(loaded, saved, true)).toBe(false);
expect(targetsUnsaved(loaded.slice(1), saved, true)).toBe(true);
expect(targetsUnsaved([withWeapon(loaded[0], {weapon: 'w88'}), loaded[1]], saved, true)).toBe(true);
expect(targetsUnsaved([...loaded, tried], saved, true)).toBe(true);
});
test('take a new weapon in place of the old', () => {
expect(withWeapon(saved[1], {weapon: 'w88', fission_fraction: 0.5})).toEqual(
{id: 2, label: 'B', lat: 2, lon: 2, kind: 'target', weapon: 'w88', fission_fraction: 0.5});
});
});
describe('the fallout panel\'s steps', () => {
const {screen, fireEvent, waitFor, act, cleanup} = require('@testing-library/react');
const {renderWithProviders} = require('../test-utils');
const FalloutPanel = require('./FalloutPanel').default;
// A map which keeps the one image source and layer the panel draws.
function fakeMap() {
const map = {
source: null, layer: false, added: 0,
getSource: () => map.source,
addSource: (id, s) => {
map.added++;
map.source = {...s, updateImage: (i) => Object.assign(map.source, i)};
},
addLayer: () => {
map.layer = true;
},
getLayer: () => map.layer,
removeLayer: () => {
map.layer = false;
},
removeSource: () => {
map.source = null;
},
on: () => null, off: () => null,
getCenter: () => ({lat: 40, lng: -100}),
};
return map;
}
const target = {key: 'saved-1', id: 1, label: 'Somewhere', lat: 40, lon: -100, weapon: 'w88'};
let getContext, toDataURL;
beforeEach(() => {
loadTerrainGrid.mockClear();
// jsdom draws no canvas: an image of the right size is all the map is given.
getContext = jest.spyOn(HTMLCanvasElement.prototype, 'getContext').mockImplementation(() => ({
createImageData: (w, h) => ({data: new Uint8ClampedArray(w * h * 4)}),
putImageData: () => null,
}));
toDataURL = jest.spyOn(HTMLCanvasElement.prototype, 'toDataURL').mockImplementation(() => 'data:');
});
afterEach(() => {
cleanup();
getContext.mockRestore();
toDataURL.mockRestore();
});
test('ask for targets first, and calculate nothing until there are some', async () => {
const map = fakeMap();
renderWithProviders(<FalloutPanel map={map} targets={[]} onClose={() => null}/>);
expect(screen.getByText('Step 2 of 4: Choose the targets')).toBeTruthy();
expect(screen.getByText('No targets yet')).toBeTruthy();
expect(screen.getByText(/Right-clicking the map adds one too/)).toBeTruthy();
expect(screen.getByRole('button', {name: 'Next: the wind'}).disabled).toBe(true);
// The wind is a step of its own.
expect(screen.queryByRole('textbox', {name: 'Wind'})).toBeNull();
await act(async () => new Promise((r) => setTimeout(r, 60)));
expect(map.added).toBe(0);
});
test('show the targets\' fallout only once the user goes on, hour by hour or in total', async () => {
const map = fakeMap();
renderWithProviders(<FalloutPanel map={map} targets={[target]} onClose={() => null}/>);
expect(screen.getByText('1 target')).toBeTruthy();
await act(async () => new Promise((r) => setTimeout(r, 60)));
expect(map.added).toBe(0);
fireEvent.click(screen.getByRole('button', {name: 'Next: the wind'}));
expect(screen.getByText('Step 3 of 4: The wind')).toBeTruthy();
// Its fields are all shown; the winds a user can choose are the forecast or one wind of their
// own, and no test shots' winds.
expect(screen.getByRole('checkbox', {name: 'Follow the terrain'})).toBeTruthy();
expect(screen.getByRole('textbox', {name: 'Speed (mph)'})).toBeTruthy();
Element.prototype.scrollIntoView = Element.prototype.scrollIntoView || (() => null);
fireEvent.click(screen.getByRole('textbox', {name: 'Wind'}));
const winds = (await screen.findAllByRole('option')).map((o) => o.textContent);
expect(winds).toEqual(['Forecast winds aloft', 'One wind at every height']);
await act(async () => new Promise((r) => setTimeout(r, 60)));
expect(map.added).toBe(0);
fireEvent.click(screen.getByRole('button', {name: 'Next: the fallout'}));
expect(screen.getByText('Step 4 of 4: The fallout')).toBeTruthy();
expect(screen.getByRole('button', {name: 'Hour by hour'}).getAttribute('aria-pressed')).toBe('true');
expect(screen.getByText('Dose rate 1 hour after the bursts')).toBeTruthy();
await waitFor(() => expect(loadTerrainGrid).toHaveBeenCalledTimes(1), {timeout: 20000});
await waitFor(() => expect(screen.queryByText(/Calculating/)).toBeNull(), {timeout: 20000});
expect(map.layer).toBe(true);
// A later hour, then the total, which has no timeline.
fireEvent.change(screen.getByLabelText('Time after the bursts'), {target: {value: '5'}});
expect(screen.getByText('Dose rate 1 day after the bursts')).toBeTruthy();
fireEvent.click(screen.getByRole('button', {name: 'Total dose'}));
expect(screen.getByText('Total dose outdoors in the first two weeks')).toBeTruthy();
expect(screen.queryByLabelText('Time after the bursts')).toBeNull();
// Back to the wind clears the map; on again, with nothing changed, it is not calculated again.
fireEvent.click(screen.getByRole('button', {name: 'Back'}));
expect(screen.getByText('Step 3 of 4: The wind')).toBeTruthy();
expect(map.layer).toBe(false);
fireEvent.click(screen.getByRole('button', {name: 'Back'}));
expect(screen.getByText('Step 2 of 4: Choose the targets')).toBeTruthy();
fireEvent.click(screen.getByRole('button', {name: 'Next: the wind'}));
fireEvent.click(screen.getByRole('button', {name: 'Next: the fallout'}));
await waitFor(() => expect(map.layer).toBe(true));
expect(screen.queryByText(/Calculating/)).toBeNull();
expect(loadTerrainGrid).toHaveBeenCalledTimes(1);
}, 60000);
test('default to the forecast when it has the winds until the fallout is down, else one wind', async () => {
Element.prototype.scrollIntoView = Element.prototype.scrollIntoView || (() => null);
const windShown = async () => {
fireEvent.click(screen.getByRole('button', {name: 'Next: the wind'}));
await act(async () => new Promise((r) => setTimeout(r, 20)));
return screen.getByRole('textbox', {name: 'Wind'}).value;
};
// No forecast.
renderWithProviders(<FalloutPanel map={fakeMap()} targets={[target]}/>);
expect(await windShown()).toBe('One wind at every height');
cleanup();
// A forecast from the hour before now, for 3 days: it has the winds.
const hourMs = Math.floor(Date.now() / 3600000) * 3600000;
const hours = (count) => Array.from({length: count}, (_, h) => new Date(hourMs + (h - 1) * 3600000).toISOString());
const forecastOf = (count) => ({source: 'Open-Meteo', fetched_at: new Date(hourMs).toISOString(), spacing: 3,
points: [{lat: 40, lon: -100, elevation: 0}], hours: hours(count),
winds: [hours(count).map(() => [[10, 10, 270], [20000, 20, 270]])], rain: [hours(count).map(() => 0)]});
mockLatestWinds = forecastOf(72);
try {
renderWithProviders(<FalloutPanel map={fakeMap()} targets={[target]}/>);
expect(await windShown()).toBe('Forecast winds aloft');
cleanup();
// One ending a day from now does not: the fallout is still coming down then.
mockLatestWinds = forecastOf(24);
renderWithProviders(<FalloutPanel map={fakeMap()} targets={[target]}/>);
expect(await windShown()).toBe('One wind at every height');
} finally {
mockLatestWinds = null;
}
});
test('ask to download the forecast on the wind step, when it is not', async () => {
const before = mockWeather;
mockWeather = {...before, enabled: false, download: null};
try {
renderWithProviders(<FalloutPanel map={fakeMap()} targets={[target]}/>);
fireEvent.click(screen.getByRole('button', {name: 'Next: the wind'}));
await act(async () => new Promise((r) => setTimeout(r, 20)));
mockWeatherSet.length = 0;
fireEvent.click(screen.getByRole('button', {name: 'Download the forecast every day'}));
await act(async () => new Promise((r) => setTimeout(r, 20)));
expect(mockWeatherSet).toEqual([true]);
expect(screen.queryByRole('button', {name: 'Download the forecast every day'})).toBeNull();
} finally {
mockWeather = before;
}
cleanup();
// Subscribed: nothing asked.
renderWithProviders(<FalloutPanel map={fakeMap()} targets={[target]}/>);
fireEvent.click(screen.getByRole('button', {name: 'Next: the wind'}));
await act(async () => new Promise((r) => setTimeout(r, 20)));
expect(screen.queryByRole('button', {name: 'Download the forecast every day'})).toBeNull();
});
test('warn when the forecast chosen runs out before the fallout is down', async () => {
Element.prototype.scrollIntoView = Element.prototype.scrollIntoView || (() => null);
const hourMs = Math.floor(Date.now() / 3600000) * 3600000;
const hours = Array.from({length: 24}, (_, h) => new Date(hourMs - (100 - h) * 3600000).toISOString());
mockLatestWinds = {source: 'Open-Meteo', fetched_at: new Date(hourMs - 100 * 3600000).toISOString(), spacing: 3,
points: [{lat: 40, lon: -100, elevation: 0}], hours,
winds: [hours.map(() => [[10, 10, 270], [20000, 20, 270]])], rain: [hours.map(() => 0)]};
try {
renderWithProviders(<FalloutPanel map={fakeMap()} targets={[target]}/>);
fireEvent.click(screen.getByRole('button', {name: 'Next: the wind'}));
await act(async () => new Promise((r) => setTimeout(r, 20)));
// Too old: one wind is chosen for the user.
expect(screen.getByRole('textbox', {name: 'Wind'}).value).toBe('One wind at every height');
await act(async () => new Promise((r) => setTimeout(r, 50)));
fireEvent.click(screen.getByRole('textbox', {name: 'Wind'}));
fireEvent.click([...document.querySelectorAll('[role=option]')].find((o) => o.textContent === 'Forecast winds aloft'));
expect(screen.getByText(/This forecast has run out: its last hour's winds are held/)).toBeTruthy();
fireEvent.click(screen.getByRole('button', {name: 'Next: the fallout'}));
expect(screen.getByText(/This forecast has run out/)).toBeTruthy();
} finally {
mockLatestWinds = null;
}
});
test('add a target where the map is clicked next, until stopped', () => {
const onPlaceTarget = jest.fn();
const {rerender} = renderWithProviders(<FalloutPanel map={fakeMap()} targets={[]}
onPlaceTarget={onPlaceTarget}/>);
fireEvent.click(screen.getByRole('button', {name: 'Add a target'}));
expect(onPlaceTarget).toHaveBeenLastCalledWith(true);
rerender(<FalloutPanel map={fakeMap()} targets={[]} placingTarget onPlaceTarget={onPlaceTarget}/>);
expect(screen.getByText('Click the map where the target is.')).toBeTruthy();
expect(screen.queryByRole('button', {name: 'Add a target'})).toBeNull();
fireEvent.click(screen.getByRole('button', {name: 'Stop'}));
expect(onPlaceTarget).toHaveBeenLastCalledWith(false);
// Going on to the wind stops it too.
onPlaceTarget.mockClear();
rerender(<FalloutPanel map={fakeMap()} targets={[target]} placingTarget onPlaceTarget={onPlaceTarget}/>);
fireEvent.click(screen.getByRole('button', {name: 'Next: the wind'}));
expect(onPlaceTarget).toHaveBeenCalledWith(false);
});
test('load the saved targets before saving over them', () => {
const onLoad = jest.fn(), onSave = jest.fn();
const tried = {key: 'new-1', label: 'Tried', lat: 41, lon: -101, weapon: 'w88'};
const {rerender} = renderWithProviders(<FalloutPanel map={fakeMap()} targets={[tried]} savedCount={156}
unsaved onLoad={onLoad} onSave={onSave}/>);
// Only the target being tried out is simulated until the saved ones are loaded.
expect(screen.getByText('1 target')).toBeTruthy();
expect(screen.getByText('(not saved)')).toBeTruthy();
expect(screen.getByText('Not saved.')).toBeTruthy();
const save = screen.getByRole('button', {name: 'Save Targets'});
expect(save.disabled).toBe(true);
expect(screen.getByText(/Saving replaces the saved targets: load them first/)).toBeTruthy();
fireEvent.click(screen.getByRole('button', {name: 'Load Saved Targets (156)'}));
expect(onLoad).toHaveBeenCalledTimes(1);
rerender(<FalloutPanel map={fakeMap()} targets={[target, tried]} savedCount={156} loaded unsaved
onLoad={onLoad} onSave={onSave}/>);
expect(screen.queryByRole('button', {name: /Load Saved Targets/})).toBeNull();
expect(screen.queryByText(/load them first/)).toBeNull();
fireEvent.click(screen.getByRole('button', {name: 'Save Targets'}));
expect(onSave).toHaveBeenCalledTimes(1);
});
test('save targets when none are saved, and take one out of the list', () => {
const onRemoveTarget = jest.fn();
const tried = {key: 'new-1', label: 'Tried', lat: 41, lon: -101, weapon: 'w88'};
const {rerender} = renderWithProviders(<FalloutPanel map={fakeMap()} targets={[]} savedCount={0}/>);
expect(screen.queryByRole('button', {name: /Load Saved Targets/})).toBeNull();
expect(screen.getByRole('button', {name: 'Save Targets'}).disabled).toBe(true);
rerender(<FalloutPanel map={fakeMap()} targets={[tried]} savedCount={0} unsaved
onRemoveTarget={onRemoveTarget}/>);
expect(screen.getByRole('button', {name: 'Save Targets'}).disabled).toBe(false);
fireEvent.click(screen.getByRole('button', {name: 'Remove Tried'}));
expect(onRemoveTarget).toHaveBeenCalledWith(tried);
});
});
describe('the fallout of past days', () => {
const {simulateClimate, CLIMATE_BANDS} = require('./FalloutPanel');
const {parseClimatology} = require('../map-shared/fallout/climatology.js');
// Days on a coarse grid (lat 90..-90 every 30, lon 0..330 every 30), each one wind [east, north].
function climate(days) {
const header = {version: 1, levels_hpa: [1000, 500], lat: [90, -30, 7], lon: [0, 30, 12],
days: days.map((_, k) => `200${k}-05-01`)};
const head = new TextEncoder().encode(JSON.stringify(header));
const size = 2 * 7 * 12;
const bytes = new Uint8Array(10 + head.length + 2 * size + days.length * 2 * size);
bytes.set([87, 70, 67, 76], 0);
const view = new DataView(bytes.buffer);
view.setUint16(4, 1, true);
view.setUint32(6, head.length, true);
bytes.set(head, 10);
let at = 10 + head.length;
for (let c = 0; c < size; c++) view.setInt16(at + 2 * c, c < size / 2 ? 100 : 5500, true);
at += 2 * size;
for (const [e, n] of days) {
for (let c = 0; c < size; c++) view.setInt8(at + c, e);
for (let c = 0; c < size; c++) view.setInt8(at + size + c, n);
at += 2 * size;
}
return parseClimatology(bytes);
}
test('counts the days each place was reached, for all the bursts at once', async () => {
const bursts = [{lat: 30, lon: -120, yieldKt: 10, fissionFraction: 1}, {lat: 31, lon: -118, yieldKt: 10, fissionFraction: 1}];
const heard = [];
const ran = await simulateClimate(bursts, climate([[10, 0], [10, 0], [0, 10]]),
{rate: 1, onProgress: (done, total) => heard.push([done, total])});
expect(ran.origin).toBe(bursts[0]);
expect(ran.grid.days).toBe(3);
const most = ran.grid.values.reduce((a, v) => Math.max(a, v), 0);
expect(most).toBeGreaterThan(0.3);
expect(most).toBeLessThanOrEqual(1);
expect(heard[heard.length - 1]).toEqual([6, 6]);
// The bands go from most days to any.
expect(CLIMATE_BANDS.map((b) => b.rate)).toEqual([...CLIMATE_BANDS.map((b) => b.rate)].sort((a, b) => b - a));
});
test('stops when cancelled', async () => {
const bursts = [{lat: 30, lon: -120, yieldKt: 10, fissionFraction: 1}];
expect(await simulateClimate(bursts, climate([[10, 0], [0, 10]]), {cancelled: () => true})).toBeNull();
});
const BURSTS = [{lat: 30, lon: -120, yieldKt: 10, fissionFraction: 1}, {lat: 31, lon: -118, yieldKt: 10, fissionFraction: 1}];
const DAYS = [[10, 0], [10, 0], [0, 10], [-8, 4], [3, -9]];
test('spreads the days over workers, and counts them as the page does', async () => {
made.length = 0;
const clim = climate(DAYS);
const here = await simulateClimate(BURSTS, clim, {rate: 1});
const heard = [];
const spread = await simulateClimate(BURSTS, clim, {rate: 1, workers: 2, makeWorker: () => worker(),
onProgress: (done, total) => heard.push([done, total])});
expect(made).toHaveLength(2);
// Every day given once, to one worker or the other, and both given some.
expect(made.flatMap((w) => w.given).sort()).toEqual([0, 1, 2, 3, 4]);
expect(made.every((w) => w.given.length > 0)).toBe(true);
expect(made.every((w) => w.terminated)).toBe(true);
expect(heard[heard.length - 1]).toEqual([10, 10]);
expect(spread.grid.days).toBe(5);
expect(spread.grid.cell).toBe(here.grid.cell);
expect(Array.from(spread.grid.values)).toEqual(Array.from(here.grid.values));
});
test('stops its workers at once when cancelled', async () => {
made.length = 0;
const controller = new AbortController();
const running = simulateClimate(BURSTS, climate(DAYS), {rate: 1, workers: 3, makeWorker: () => worker(),
signal: controller.signal});
controller.abort();
expect(await running).toBeNull();
expect(made).toHaveLength(3);
expect(made.every((w) => w.terminated)).toBe(true);
});
test('calculates on the page when its workers fail', async () => {
made.length = 0;
const error = jest.spyOn(console, 'error').mockImplementation(() => null);
const clim = climate(DAYS);
const here = await simulateClimate(BURSTS, clim, {rate: 1});
const ran = await simulateClimate(BURSTS, clim, {rate: 1, workers: 2, makeWorker: () => worker({fail: true})});
expect(error).toHaveBeenCalled();
error.mockRestore();
expect(made.every((w) => w.terminated)).toBe(true);
expect(Array.from(ran.grid.values)).toEqual(Array.from(here.grid.values));
// And where there are none to be had.
const none = await simulateClimate(BURSTS, clim, {rate: 1, workers: 2, makeWorker: () => null});
expect(Array.from(none.grid.values)).toEqual(Array.from(here.grid.values));
});
});
describe('the fallout panel\'s progress', () => {
const {screen} = require('@testing-library/react');
const {renderWithProviders} = require('../test-utils');
const {FalloutProgress} = require('./FalloutPanel');
test('is a bar filled as far as the bursts are calculated', () => {
const {unmount} = renderWithProviders(<FalloutProgress busy={true} progress={{done: 1170, total: 4680}}/>);
const bar = screen.getByRole('progressbar');
expect(bar.getAttribute('aria-valuenow')).toBe('25');
expect(screen.getByText('Calculating 1,170 of 4,680')).toBeTruthy();
unmount();
});
test('has a button which cancels the calculation', () => {
const {fireEvent} = require('@testing-library/react');
const onCancel = jest.fn();
const {unmount} = renderWithProviders(<FalloutProgress busy={true} progress={{done: 1, total: 2}} onCancel={onCancel}/>);
fireEvent.click(screen.getByRole('button', {name: 'Cancel'}));
expect(onCancel).toHaveBeenCalledTimes(1);
unmount();
});
test('moves without a count until there is one, and is gone when done', () => {
const {rerender, unmount} = renderWithProviders(<FalloutProgress busy={true} progress={null}/>);
expect(screen.getByRole('progressbar').getAttribute('aria-valuenow')).toBeNull();
expect(screen.getByText('Calculating…')).toBeTruthy();
rerender(<FalloutProgress busy={false} progress={null}/>);
expect(screen.queryByRole('progressbar')).toBeNull();
unmount();
});
});

View file

@ -11,14 +11,17 @@ import {
} from "./Common";
import {Route, Routes, useNavigate} from "react-router";
import {
deleteMapFile, deleteMapPin, fetchMapSubscriptions, getMapFiles, getMapPins,
deleteMapFile, deleteMapPin, deleteMapTarget, fetchMapSubscriptions, getMapFiles, getMapPins, getMapTargets,
mapSubscribe, mapUnsubscribe, rebuildMapSearchIndex, setMapFileVisible, updateMapPin
} from "../api";
import {targetWeapon} from "../map-shared/fallout/targets.js";
import {formatYieldAndFission} from "../map-shared/fallout/weapons.js";
import {Button, Divider, Group, Header, Icon, Modal, Table, TextInput, Toggle} from "./ui";
import {SortableTable} from "./SortableTable";
import {Media, StatusContext} from "../contexts/contexts";
import {MAP_VIEWER_URI} from "./Vars";
import MapViewer from "./MapViewer";
import {WeatherSection} from "./MapWeather";
import {AddToPlaylistButton} from "./AddToPlaylist";
import {solarCalculatorPath} from "./calculators/solar";
import maplibregl from "maplibre-gl";
@ -501,6 +504,10 @@ function ManageMap() {
</p>
</InfoMessage>
<Divider/>
<WeatherSection/>
<HandPointMessage>
<p>You can also view the map at <a href={MAP_VIEWER_URI}>{MAP_VIEWER_URI}</a></p>
</HandPointMessage>
@ -743,6 +750,103 @@ function MapPins() {
emptyRow={emptyRow}
/>
</Media>
<MapTargets filter={lowerFilter}/>
</>;
}
// The saved nuclear targets (map_nuclear.yaml), apart from the pins: what each is and where, and
// deleting one. `filter` (lower case) matches a name or coordinates.
export function MapTargets({filter = ''}) {
// null = pending, undefined = fetch failed, [] = no targets.
const [targets, setTargets] = useState(null);
const navigate = useNavigate();
const gen = useRef(0);
const fetchTargets = async () => {
const mine = ++gen.current;
const saved = await getMapTargets();
if (mine === gen.current) setTargets(saved);
};
useEffect(() => {
fetchTargets();
}, []);
const handleDelete = async (targetId) => {
await deleteMapTarget(targetId);
await fetchTargets();
};
const weaponOf = (target) => {
const chosen = targetWeapon(target);
return `${chosen.weapon ? chosen.weapon.name : 'A yield of my own'}, `
+ formatYieldAndFission(chosen.yieldKt, chosen.fissionFraction);
};
const place = (target) => {
const to = `/map?lat=${target.lat}&lon=${target.lon}&z=10`;
return <a href={to} onClick={(e) => {
e.preventDefault();
navigate(to);
}}>{target.lat.toFixed(4)}, {target.lon.toFixed(4)}</a>;
};
const deleteButton = (target) => <APIButton
size='xs'
role='danger'
icon='trash'
aria-label={`Delete ${target.label}`}
confirmContent='Delete this target?'
confirmButton='Delete'
onClick={() => handleDelete(target.id)}
/>;
const fullHeaders = [
{key: 'label', text: 'Target', sortBy: i => i.label.toLowerCase()},
{key: 'weapon', text: 'Weapon', sortBy: i => targetWeapon(i).yieldKt},
{key: 'coords', text: 'Coordinates', sortBy: i => i.lat},
{key: 'created', text: 'Created', sortBy: i => i.created},
{key: 'actions', text: '', sortBy: null},
];
const fullRowFunc = (target) => <Table.Row key={target.id}>
<Table.Cell><span aria-hidden>☢ </span>{target.label}</Table.Cell>
<Table.Cell>{weaponOf(target)}</Table.Cell>
<Table.Cell>{place(target)}</Table.Cell>
<Table.Cell>{target.created}</Table.Cell>
<Table.Cell>{deleteButton(target)}</Table.Cell>
</Table.Row>;
const mobileHeaders = [
{key: 'label', text: 'Target', sortBy: i => i.label.toLowerCase()},
{key: 'actions', text: '', sortBy: null},
];
const mobileRowFunc = (target) => <Table.Row key={target.id}>
<Table.Cell>
<span aria-hidden>☢ </span>{target.label}
<div style={{fontSize: '0.6875rem', color: 'var(--muted)'}}>{weaponOf(target)}</div>
<div style={{fontSize: '0.6875rem'}}>{place(target)}</div>
</Table.Cell>
<Table.Cell>{deleteButton(target)}</Table.Cell>
</Table.Row>;
const emptyRow = <Table.Row>
<Table.Cell colSpan={5}>No targets. Turn on nuclear mode (☢) on the map to add and save some.</Table.Cell>
</Table.Row>;
const shown = filter && targets
? targets.filter(t => (t.label || '').toLowerCase().includes(filter) ||
`${t.lat.toFixed(4)}, ${t.lon.toFixed(4)}`.includes(filter))
: targets;
return <>
<Header as='h3'>Nuclear Targets</Header>
{targets === undefined ? <ErrorMessage>Could not fetch the nuclear targets</ErrorMessage> : <>
<Media at='mobile'>
<SortableTable tableHeaders={mobileHeaders} data={shown} rowFunc={mobileRowFunc} rowKey='id'
defaultSortColumn='label' emptyRow={emptyRow}/>
</Media>
<Media greaterThanOrEqual='tablet'>
<SortableTable tableHeaders={fullHeaders} data={shown} rowFunc={fullRowFunc} rowKey='id'
defaultSortColumn='label' emptyRow={emptyRow}/>
</Media>
</>}
</>;
}

View file

@ -102,6 +102,7 @@ const CATALOG = [
jest.mock('../api', () => ({
...jest.requireActual('../api'),
getWeather: async () => ({enabled: false, download: null, targets: 0, field: null}),
getMapFiles: jest.fn(),
fetchMapSubscriptions: jest.fn(),
getMapPins: jest.fn(),

View file

@ -28,6 +28,11 @@ jest.mock('../api', () => ({
getMapFiles: jest.fn(),
fetchMapSubscriptions: jest.fn(),
getMapPins: jest.fn(),
getMapTargets: jest.fn(),
getWeather: jest.fn(),
setWeatherSubscription: jest.fn(),
downloadWeatherNow: jest.fn(),
deleteMapTarget: jest.fn(),
setMapFileVisible: jest.fn(),
rebuildMapSearchIndex: jest.fn(),
}));
@ -38,6 +43,7 @@ const pending = () => new Promise(() => {
});
const NO_PINS = /No pins\. Right-click/;
const NO_RESULTS = /^No results$/;
const WEATHER_OFF = {enabled: false, download: null, targets: 3, spacing: 1, points: 160, seconds: 61, field: null};
// The pins page renders one table per breakpoint through `Media`, so the real media provider is
// needed; the queries below tolerate either variant being in the tree.
@ -59,6 +65,9 @@ beforeEach(() => {
api.getMapFiles.mockResolvedValue({files: []});
api.fetchMapSubscriptions.mockResolvedValue({catalog: [], subscriptions: []});
api.getMapPins.mockResolvedValue({pins: []});
api.getMapTargets.mockResolvedValue([]);
api.deleteMapTarget.mockResolvedValue(true);
api.getWeather.mockResolvedValue(WEATHER_OFF);
});
describe('the Pins tab', () => {
@ -106,6 +115,61 @@ describe('the Pins tab', () => {
});
});
describe('the Pins tab\'s nuclear targets', () => {
const {within} = require('@testing-library/react');
const targets = [
{id: 1, lat: 40.1, lon: -111.2, label: 'Base', created: '2026-11-24', weapon: 'w88', fission_fraction: 0.5},
{id: 2, lat: 41, lon: -112, label: 'Depot', created: '2026-11-24', weapon: 'custom', yield_kt: 20,
fission_fraction: 1},
];
test('are listed in their own table, apart from the pins', async () => {
api.getMapPins.mockResolvedValue({pins: [{id: 1, lat: 40.1, lon: -111.2, label: 'Camp', color: '#f00'}]});
api.getMapTargets.mockResolvedValue(targets);
renderAt('/map/pins');
await act(async () => {
});
const tables = screen.getAllByRole('table');
expect(tables).toHaveLength(2);
const [pinsTable, table] = tables;
expect(within(pinsTable).queryByText('Base')).toBeNull();
expect(within(pinsTable).getByText('Camp')).toBeTruthy();
expect(within(table).queryByText('Camp')).toBeNull();
expect(within(table).getByText('Base')).toBeTruthy();
expect(within(table).getByText(/W88.*455 kt, half fission/)).toBeTruthy();
expect(within(table).getByText(/A yield of my own, 20 kt/)).toBeTruthy();
});
test('says when there are none, and when they could not be fetched', async () => {
const {unmount} = renderAt('/map/pins');
await act(async () => {
});
expect(screen.getAllByText(/No targets\. Turn on nuclear mode/).length).toBeGreaterThan(0);
unmount();
api.getMapTargets.mockResolvedValue(undefined);
renderAt('/map/pins');
await act(async () => {
});
expect(screen.getByText('Could not fetch the nuclear targets')).toBeTruthy();
expect(screen.queryAllByText(/No targets\./)).toHaveLength(0);
});
test('delete one, and are fetched again', async () => {
api.getMapTargets.mockResolvedValueOnce(targets).mockResolvedValueOnce(targets.slice(1));
renderAt('/map/pins');
await act(async () => {
});
fireEvent.click(screen.getAllByRole('button', {name: 'Delete Base'})[0]);
// The delete is confirmed first.
await act(async () => {
fireEvent.click(await screen.findByRole('button', {name: 'Delete'}));
});
expect(api.deleteMapTarget).toHaveBeenCalledWith(1);
expect(api.getMapTargets).toHaveBeenCalledTimes(2);
expect(screen.queryAllByText('Base')).toHaveLength(0);
});
});
describe('the Manage tab subscriptions table', () => {
test('pending: shows a placeholder, not "No results"', async () => {
api.fetchMapSubscriptions.mockReturnValue(pending());
@ -234,3 +298,65 @@ describe('the Manage tab files table', () => {
expect(api.setMapFileVisible).toHaveBeenCalledWith('satellite.pmtiles', true);
});
});
describe('the Manage tab\'s weather', () => {
const hour = 3600000;
const field = (fromHours, toHours) => ({
fetched_at: new Date().toISOString(), spacing: 1, points: 160, size: 5 * 1024 * 1024,
first_hour: new Date(Date.now() + fromHours * hour).toISOString(),
last_hour: new Date(Date.now() + toHours * hour).toISOString(),
});
test('is turned on with its toggle, and says what it downloads', async () => {
api.setWeatherSubscription.mockResolvedValue({...WEATHER_OFF, enabled: true,
download: {status: 'new', next_download: null, last_successful_download: null}});
renderAt('/map/manage');
await act(async () => {
});
expect(screen.getByText('Weather')).toBeInTheDocument();
expect(screen.getByText(/Around 3 targets: 160 places every 1°, which takes about 2 minutes/)).toBeInTheDocument();
expect(screen.getByText('No forecast has been downloaded.')).toBeInTheDocument();
expect(screen.queryByRole('button', {name: 'Download now'})).toBeNull();
await act(async () => {
fireEvent.click(screen.getByRole('switch', {name: /Download the weather forecast from Open-Meteo/}));
});
expect(api.setWeatherSubscription).toHaveBeenCalledWith(true);
expect(screen.getByText('Downloading the forecast…')).toBeInTheDocument();
expect(screen.getByRole('button', {name: 'Download now'})).toBeDisabled();
});
test('shows the forecast kept, and whether it is recent enough for bursts now', async () => {
const done = {status: 'complete', last_successful_download: new Date().toISOString(),
next_download: new Date(Date.now() + 24 * hour).toISOString()};
api.getWeather.mockResolvedValue({...WEATHER_OFF, enabled: true, download: done, field: field(-5, 90)});
api.downloadWeatherNow.mockResolvedValue({...WEATHER_OFF, enabled: true, download: {...done, status: 'new'}});
const {unmount} = renderAt('/map/manage');
await act(async () => {
});
expect(screen.getByText(/Forecast kept: .* 160 places every 1°, 5.0 MB/)).toBeInTheDocument();
expect(screen.getByText(/It has the winds for bursts now/)).toBeInTheDocument();
expect(screen.getByText(/Last downloaded .*\. Next /)).toBeInTheDocument();
await act(async () => {
fireEvent.click(screen.getByRole('button', {name: 'Download now'}));
});
expect(api.downloadWeatherNow).toHaveBeenCalled();
unmount();
// Ending a day from now: too old for bursts now.
api.getWeather.mockResolvedValue({...WEATHER_OFF, enabled: true,
download: {status: 'failed', error: 'The forecast service answered HTTP 500'}, field: field(-60, 24)});
renderAt('/map/manage');
await act(async () => {
});
expect(screen.getByText(/It is too old for bursts now/)).toBeInTheDocument();
expect(screen.getByText(/The last download failed: The forecast service answered HTTP 500/)).toBeInTheDocument();
});
test('says when there are no targets to download around', async () => {
api.getWeather.mockResolvedValue({...WEATHER_OFF, targets: 0, spacing: null, points: null});
renderAt('/map/manage');
await act(async () => {
});
expect(screen.getByText(/No nuclear targets are saved/)).toBeInTheDocument();
});
});

View file

@ -1,4 +1,4 @@
import React, {useCallback, useContext, useEffect, useRef, useState} from "react";
import React, {useCallback, useContext, useEffect, useMemo, useRef, useState} from "react";
import {useNavigate, useSearchParams} from "react-router";
import maplibregl from "maplibre-gl";
import "maplibre-gl/dist/maplibre-gl.css";
@ -12,7 +12,9 @@ import {
getMapQuadName,
getMapFiles,
getMapPins,
getMapTargets,
searchMap,
saveMapTargets,
setMapDefaultLocation,
} from "../api";
import {MAP_VIEWER_URI} from "./Vars";
@ -28,6 +30,7 @@ import {mapFlavor, mapSprite} from "../themes/names";
import {poiPopupHtml} from "./mapPoiPopup";
import {solarCalculatorPath} from "./calculators/solar";
import {
escapeHtml,
addOverlaysToStyle,
labelsOverGround,
buildOverlayLayers,
@ -51,6 +54,8 @@ import {
} from "./mapOverlays";
import {addMissingOverlayIcon, loadOverlayStyles, OVERLAY_ICONS_SPRITE_ID} from "./mapOverlayStyle";
import MapQuadPicker, {QUAD_LAYER_PREFIX} from "./MapQuadPicker";
import FalloutPanel, {targetsUnsaved, WeaponPicker, withSavedTargets, withWeapon} from "./FalloutPanel";
import {DEFAULT_WEAPON} from "../map-shared/fallout/targets.js";
import {contourInterval, contourThresholds, DEFAULT_TERRAIN_MAX_ZOOM, terrainMaxZoom} from "../map-shared/terrain.js";
import {quadAt} from "./mapQuads";
import {
@ -509,9 +514,17 @@ function LayerControl({
const PIN_COLORS = ["red", "blue", "green", "yellow", "orange", "purple"];
function AddPinDialog({lat, lon, onSubmit, onCancel}) {
// A button in a marker's popup (which is HTML), calling `onclick`.
const popupButton = (onclick, text, color) => `<button onclick="${onclick}" `
+ `style="margin-top:4px;margin-right:4px;padding:2px 8px;cursor:pointer;color:${color};`
+ `border:1px solid ${color};background:none;border-radius:3px;">${text}</button>`;
function AddPinDialog({lat, lon, target = false, weapon: initialWeapon = null, onSubmit, onCancel}) {
const [label, setLabel] = useState("");
const [color, setColor] = useState("red");
// A target's weapon, kept with it.
const [weapon, setWeapon] = useState(initialWeapon || {weapon: DEFAULT_WEAPON});
const submit = () => label.trim() && onSubmit(label.trim(), color, target ? weapon : null);
// A floating dialog over the canvas — page chrome, not map data, so it is never
// filtered and keeps flat, bordered surfaces like the rest of the app (no shadow).
@ -520,17 +533,23 @@ function AddPinDialog({lat, lon, onSubmit, onCancel}) {
zIndex: 1002, background: "var(--panel)", border: "1px solid var(--border)", color: "var(--text)",
padding: "1rem", minWidth: "15.625rem",
}}>
<div style={{fontWeight: 600, marginBottom: "0.5rem"}}>Add Pin</div>
<div style={{fontWeight: 600, marginBottom: "0.5rem"}}>{target ? "Add Target" : "Add Pin"}</div>
{target && <div style={{fontSize: '0.75rem', color: "var(--muted)", marginBottom: "0.5rem"}}>
A likely detonation site, tried out until you save the targets.
</div>}
<div style={{fontSize: '0.75rem', color: "var(--muted)", marginBottom: "0.5rem"}}>{lat.toFixed(4)}, {lon.toFixed(4)}</div>
<TextInput
placeholder="Label"
value={label}
onChange={e => setLabel(e.target.value)}
autoFocus
onKeyDown={e => e.key === "Enter" && label.trim() && onSubmit(label.trim(), color)}
onKeyDown={e => e.key === "Enter" && submit()}
style={{marginBottom: "0.5rem"}}
/>
<div style={{display: "flex", gap: "0.375rem", marginBottom: "0.75rem"}}>
{target && <div style={{marginBottom: "0.5rem"}}>
<WeaponPicker label="Weapon" value={weapon} onChange={setWeapon}/>
</div>}
{!target && <div style={{display: "flex", gap: "0.375rem", marginBottom: "0.75rem"}}>
{PIN_COLORS.map(c =>
<div
key={c}
@ -541,13 +560,13 @@ function AddPinDialog({lat, lon, onSubmit, onCancel}) {
}}
/>
)}
</div>
</div>}
<div style={{display: "flex", gap: "0.5rem", justifyContent: "flex-end"}}>
<Button role='cancel' size='sm' onClick={onCancel}>Cancel</Button>
<Button
role='primary'
size='sm'
onClick={() => label.trim() && onSubmit(label.trim(), color)}
onClick={submit}
disabled={!label.trim()}
>
Add
@ -721,8 +740,28 @@ export default function MapViewer() {
const [error, setError] = useState(null);
const [contextMenu, setContextMenu] = useState(null);
const navigate = useNavigate();
const [addingPin, setAddingPin] = useState(null); // {lat, lon} when pin dialog is open
const [addingPin, setAddingPin] = useState(null); // {lat, lon, kind} when pin dialog is open
// Nuclear mode: targets (likely detonation sites) are shown, pins added are targets, and fallout
// can be simulated.
const [nuclear, setNuclear] = useState(false);
const nuclearRef = useRef(false);
const nuclearButtonRef = useRef(null);
// The fallout view (nuclear mode): open or not.
const [falloutOpen, setFalloutOpen] = useState(false);
// The saved nuclear targets (map_nuclear.yaml).
const [savedTargets, setSavedTargets] = useState([]);
const markersRef = useRef([]);
// Nuclear mode's targets, those simulated ({key, id (if saved), lat, lon, label, weapon, ...}):
// tried out, and the saved ones once loaded. `loadedIds` are the ids the saved targets had when
// they were loaded (null until then): saving replaces them, so it is refused until they are.
const [targets, setTargets] = useState([]);
const [loadedIds, setLoadedIds] = useState(null);
const nextTargetKey = useRef(1);
const targetMarkersRef = useRef([]);
// Placing a target: the next click on the map is where it is. The ref tells the map's own click
// handlers to stand by.
const [placingTarget, setPlacingTarget] = useState(false);
const placingTargetRef = useRef(false);
const pinsVisibleRef = useRef(true);
// Choosing a quadrangle to export: null, or {quad} (the quadrangle to start with, if any). While
// choosing, a click on the map chooses, so the ref tells the map's own click handlers to stand by.
@ -859,11 +898,8 @@ export default function MapViewer() {
pinToggle.style.cssText = "font-size:18px;width:29px;height:29px;border:none;cursor:pointer;background:white;border-radius:4px;display:flex;align-items:center;justify-content:center;";
pinToggle.addEventListener("click", () => {
pinsVisibleRef.current = !pinsVisibleRef.current;
const display = pinsVisibleRef.current ? "" : "none";
pinToggle.style.opacity = pinsVisibleRef.current ? "1" : "0.5";
for (const m of markersRef.current) {
m.getElement().style.display = display;
}
showPins();
});
const pinControl = {
onAdd: () => {
@ -898,6 +934,29 @@ export default function MapViewer() {
onRemove: () => {},
}, "top-right");
// Nuclear mode: targets, and fallout.
const nuclearButton = document.createElement("button");
nuclearButton.type = "button";
nuclearButton.title = "Nuclear mode: targets and fallout";
nuclearButton.setAttribute("aria-label", "Nuclear mode");
nuclearButton.setAttribute("aria-pressed", "false");
nuclearButton.textContent = "☢️";
nuclearButton.style.cssText = pinToggle.style.cssText;
nuclearButton.addEventListener("click", () => {
if (destroyed) return;
setNuclear(on => !on);
});
nuclearButtonRef.current = nuclearButton;
map.addControl({
onAdd: () => {
const container = document.createElement("div");
container.className = "maplibregl-ctrl maplibregl-ctrl-group";
container.appendChild(nuclearButton);
return container;
},
onRemove: () => {},
}, "top-right");
// Right-click context menu (desktop).
map.on("contextmenu", (e) => {
if (destroyed) return;
@ -926,7 +985,7 @@ export default function MapViewer() {
const featuresAt = (point, layers) =>
layers.length ? map.queryRenderedFeatures(point, {layers}) : [];
map.on("click", (e) => {
if (destroyed || pickingQuadRef.current) return;
if (destroyed || pickingQuadRef.current || placingTargetRef.current) return;
const html = overlayPopupHtml(featuresAt(e.point, overlayLayerIds()))
|| poiPopupHtml(featuresAt(e.point, poiLayerIds()), e.lngLat);
if (!html) return;
@ -937,7 +996,7 @@ export default function MapViewer() {
});
map.on("mousemove", (e) => {
if (destroyed) return;
if (pickingQuadRef.current) {
if (pickingQuadRef.current || placingTargetRef.current) {
map.getCanvas().style.cursor = "crosshair";
return;
}
@ -1098,6 +1157,26 @@ export default function MapViewer() {
if (map) map.getCanvas().style.cursor = pickingQuad ? "crosshair" : "";
}, [pickingQuad]);
// Placing a target: a click on the map opens the dialog which adds it there; Escape stops.
useEffect(() => {
placingTargetRef.current = placingTarget;
const map = mapRef.current;
if (!map || !placingTarget) return;
map.getCanvas().style.cursor = "crosshair";
const onClick = (e) => {
setPlacingTarget(false);
setAddingPin({lat: e.lngLat.lat, lon: e.lngLat.lng, kind: "target"});
};
const onKey = (e) => e.key === "Escape" && setPlacingTarget(false);
map.on("click", onClick);
document.addEventListener("keydown", onKey);
return () => {
map.off("click", onClick);
document.removeEventListener("keydown", onKey);
map.getCanvas().style.cursor = "";
};
}, [placingTarget]);
const handleExportQuad = useCallback(() => {
if (!contextMenu) return;
// Start with the quadrangle which was clicked; not while another is being exported.
@ -1207,6 +1286,15 @@ export default function MapViewer() {
}, []);
// --- Pins ---
// Show the pins the toggle and the mode allow: pins while pins are shown, and targets only in
// nuclear mode too.
const showPins = useCallback(() => {
for (const m of [...markersRef.current, ...targetMarkersRef.current]) {
const shown = pinsVisibleRef.current && (!m.wrolpiTarget || nuclearRef.current);
m.getElement().style.display = shown ? "" : "none";
}
}, []);
const loadPins = useCallback(async () => {
const map = mapRef.current;
if (!map) return;
@ -1218,8 +1306,9 @@ export default function MapViewer() {
const data = await getMapPins();
if (!data?.pins) return;
data.pins.forEach((pin, index) => {
data.pins.forEach((pin) => {
const el = document.createElement("div");
el.style.cursor = "pointer";
el.style.width = "24px";
el.style.height = "24px";
el.style.borderRadius = "50% 50% 50% 0";
@ -1227,29 +1316,101 @@ export default function MapViewer() {
el.style.border = "2px solid white";
el.style.boxShadow = "0 1px 4px rgba(0,0,0,0.4)";
el.style.transform = "rotate(-45deg)";
el.style.cursor = "pointer";
const popup = new maplibregl.Popup({offset: 15}).setHTML(
`<div style="font-size:13px">` +
`<strong>${pin.label || "Pin"}</strong><br/>` +
`<strong>${escapeHtml(pin.label || "Pin")}</strong><br/>` +
`<small>${pin.lat.toFixed(4)}, ${pin.lon.toFixed(4)}</small><br/>` +
`<button onclick="window.__deleteMapPin(${pin.id})" ` +
`style="margin-top:4px;padding:2px 8px;cursor:pointer;color:red;border:1px solid red;background:none;border-radius:3px;">` +
`Delete</button></div>`
popupButton(`window.__deleteMapPin(${pin.id})`, "Delete", "red") +
`</div>`
);
const marker = new maplibregl.Marker({element: el})
.setLngLat([pin.lon, pin.lat])
.setPopup(popup)
.addTo(map);
if (!pinsVisibleRef.current) {
marker.getElement().style.display = "none";
}
markersRef.current.push(marker);
});
showPins();
}, [showPins]);
// The targets simulated, on the map in nuclear mode.
useEffect(() => {
const map = mapRef.current;
for (const m of targetMarkersRef.current) m.remove();
targetMarkersRef.current = [];
if (!mapReady || !map || !nuclear) return;
for (const t of targets) {
const el = document.createElement("div");
el.textContent = "☢";
el.style.cssText = "cursor:pointer;width:26px;height:26px;border-radius:50%;background:#ffd43b;"
+ "color:#000;border:2px solid #000;box-shadow:0 1px 4px rgba(0,0,0,0.4);display:flex;"
+ "align-items:center;justify-content:center;font-size:18px;line-height:1;"
+ (t.id ? "" : "border-style:dashed;");
const popup = new maplibregl.Popup({offset: 15}).setHTML(
`<div style="font-size:13px">` +
`<strong>${escapeHtml(t.label || "Target")}</strong><br/>` +
`<small>${t.id ? "Target" : "Target, not saved"}</small><br/>` +
`<small>${t.lat.toFixed(4)}, ${t.lon.toFixed(4)}</small><br/>` +
popupButton(`window.__removeTarget('${t.key}')`, "Remove", "red") +
`</div>`
);
const marker = new maplibregl.Marker({element: el}).setLngLat([t.lon, t.lat]).setPopup(popup).addTo(map);
marker.wrolpiTarget = true;
targetMarkersRef.current.push(marker);
}
showPins();
}, [mapReady, nuclear, targets, showPins]);
// Whether the targets simulated differ from the saved ones.
const unsaved = useMemo(() => targetsUnsaved(targets, savedTargets, loadedIds !== null),
[targets, savedTargets, loadedIds]);
// The saved targets join those being tried out.
const handleLoadTargets = useCallback(() => {
setTargets((tried) => withSavedTargets(savedTargets, tried));
setLoadedIds(savedTargets.map((t) => t.id));
}, [savedTargets]);
// The targets simulated, saved in place of the saved ones.
const handleSaveTargets = useCallback(async () => {
const plain = targets.map(({key, ...t}) => t);
const saved = await saveMapTargets(plain, loadedIds || []);
if (!saved) return;
setSavedTargets(saved);
setTargets(withSavedTargets(saved, []));
setLoadedIds(saved.map((t) => t.id));
}, [targets, loadedIds]);
const handleRemoveTarget = useCallback((target) => {
setTargets((list) => list.filter((t) => t.key !== target.key));
}, []);
useEffect(() => {
window.__removeTarget = (key) => setTargets((list) => list.filter((t) => t.key !== key));
return () => { delete window.__removeTarget; };
}, []);
const handleTargetWeapon = useCallback((target, weapon) => {
setTargets((list) => list.map((t) => t.key === target.key ? withWeapon(t, weapon) : t));
}, []);
const handleAllTargetsWeapon = useCallback((weapon) => {
setTargets((list) => list.map((t) => withWeapon(t, weapon)));
}, []);
// Nuclear mode on or off: the button says so, targets are shown or hidden, and leaving it closes
// the fallout simulation.
useEffect(() => {
nuclearRef.current = nuclear;
const button = nuclearButtonRef.current;
if (button) {
button.style.background = nuclear ? "#ffd43b" : "white";
button.setAttribute("aria-pressed", String(nuclear));
}
showPins();
// Nuclear mode opens the fallout panel on its targets step; leaving it closes the panel.
setFalloutOpen(nuclear);
if (!nuclear) setPlacingTarget(false);
}, [nuclear, showPins]);
// Global callback for popup delete buttons.
useEffect(() => {
window.__deleteMapPin = async (pinId) => {
@ -1259,6 +1420,16 @@ export default function MapViewer() {
return () => { delete window.__deleteMapPin; };
}, [loadPins]);
// The saved targets, when nuclear mode is first used.
useEffect(() => {
if (!nuclear) return;
let cancelled = false;
getMapTargets().then((saved) => !cancelled && saved && setSavedTargets(saved));
return () => {
cancelled = true;
};
}, [nuclear]);
// Load pins when map is ready.
useEffect(() => {
if (mapReady) loadPins();
@ -1266,9 +1437,9 @@ export default function MapViewer() {
const handleAddPin = useCallback(() => {
if (!contextMenu) return;
setAddingPin({lat: contextMenu.lat, lon: contextMenu.lon});
setAddingPin({lat: contextMenu.lat, lon: contextMenu.lon, kind: nuclear ? "target" : "pin"});
setContextMenu(null);
}, [contextMenu]);
}, [contextMenu, nuclear]);
const handleSolar = useCallback(() => {
if (!contextMenu) return;
@ -1286,10 +1457,16 @@ export default function MapViewer() {
setContextMenu(null);
}, [fetchSettings]);
const handleSubmitPin = useCallback(async (label, color) => {
const handleSubmitPin = useCallback(async (label, color, weapon) => {
if (!addingPin) return;
const {lat, lon} = addingPin;
const {lat, lon, kind} = addingPin;
setAddingPin(null); // Prevent double-submit.
// A target is tried out until the targets are saved.
if (kind === "target") {
const key = `new-${nextTargetKey.current++}`;
setTargets((list) => [...list, {key, lat, lon, label, ...weapon}]);
return;
}
await addMapPin(lat, lon, label, color);
await loadPins();
}, [addingPin, loadPins]);
@ -1370,7 +1547,7 @@ export default function MapViewer() {
onMouseLeave={e => e.target.style.background = "transparent"}
onClick={handleAddPin}
>
Add Pin Here
{nuclear ? "Add Target Here" : "Add Pin Here"}
</div>
<div
style={{padding: "0.5rem 0.75rem", cursor: "pointer", userSelect: "none"}}
@ -1406,9 +1583,29 @@ export default function MapViewer() {
setPickingQuad(null);
}}
/>}
{mapReady && nuclear && falloutOpen && <FalloutPanel
map={mapRef.current}
targets={targets}
savedCount={savedTargets.length}
loaded={loadedIds !== null}
unsaved={unsaved}
onLoad={handleLoadTargets}
onSave={handleSaveTargets}
onRemoveTarget={handleRemoveTarget}
onTargetWeapon={handleTargetWeapon}
onAllTargetsWeapon={handleAllTargetsWeapon}
placingTarget={placingTarget}
onPlaceTarget={setPlacingTarget}
onClose={() => {
setPlacingTarget(false);
setFalloutOpen(false);
}}
/>}
{addingPin && <AddPinDialog
lat={addingPin.lat}
lon={addingPin.lon}
target={addingPin.kind === "target"}
weapon={addingPin.weapon}
onSubmit={handleSubmitPin}
onCancel={() => setAddingPin(null)}
/>}

View file

@ -0,0 +1,112 @@
import React, {useCallback, useEffect, useState} from "react";
import {downloadWeatherNow, getWeather, setWeatherSubscription} from "../api";
import {ErrorMessage, humanFileSize} from "./Common";
import {Button, Header, Toggle} from "./ui";
import {LANDING_HOURS} from "../map-shared/fallout/winds.js";
// The weather subscription: a forecast of the winds aloft around the saved nuclear targets,
// downloaded every day (a recurring Download), for the fallout simulator.
// How often (ms) the subscription is asked again while it downloads.
const REFRESH_MS = 10000;
// Whether a download of the weather is waiting or running.
export const weatherDownloading = (weather) => ['new', 'pending'].includes(weather?.download?.status);
// The weather subscription, asked again while it downloads: {weather (null while pending, undefined
// when it could not be fetched), downloading, setEnabled(enabled), downloadNow()}.
export function useWeather() {
const [weather, setWeather] = useState(null);
const refresh = useCallback(async () => setWeather(await getWeather()), []);
useEffect(() => {
refresh();
}, [refresh]);
const downloading = weatherDownloading(weather);
useEffect(() => {
if (!downloading) return;
const timer = setInterval(refresh, REFRESH_MS);
return () => clearInterval(timer);
}, [downloading, refresh]);
const setEnabled = async (enabled) => {
const changed = await setWeatherSubscription(enabled);
if (changed) setWeather(changed);
};
const downloadNow = async () => {
const changed = await downloadWeatherNow();
if (changed) setWeather(changed);
};
return {weather, downloading, setEnabled, downloadNow};
}
// Whether the forecast kept (`field`, as the subscription tells it) has the winds for bursts now,
// until all their fallout is down.
export function fieldCoversNow(field, when = new Date()) {
if (!field) return false;
const first = Date.parse(field.first_hour), last = Date.parse(field.last_hour);
return first <= when.getTime() + 3600000 && last >= when.getTime() + LANDING_HOURS * 3600000;
}
// About how long a download takes, as the user reads it.
export const downloadTime = (seconds) => !seconds || seconds < 60 ? "about a minute"
: `about ${Math.round(seconds / 60) + 1} minutes`;
const when = (time) => time ? new Date(time).toLocaleString(undefined, {
weekday: "short", month: "short", day: "numeric", hour: "numeric", minute: "2-digit",
}) : null;
// The Manage tab's section for the weather subscription: turning it on or off, what it downloads,
// how its downloads have gone, and the forecast kept.
export function WeatherSection() {
const {weather, downloading, setEnabled, downloadNow} = useWeather();
const muted = {color: "var(--muted)", fontSize: "0.875rem"};
const warning = {color: "var(--warning)", fontSize: "0.875rem"};
const header = <Header as='h3'>Weather</Header>;
if (weather === undefined) return <>{header}<ErrorMessage>Could not fetch the weather subscription</ErrorMessage></>;
if (!weather) return header;
const {download, field} = weather;
const failed = download && ['failed', 'deferred'].includes(download.status) && download.error;
return <>
{header}
<Toggle label="Download the weather forecast from Open-Meteo every day" checked={weather.enabled}
onChange={(e) => setEnabled(e.currentTarget.checked)}/>
<div style={muted}>
The winds aloft, hour by hour for four days, around the saved nuclear targets: the fallout simulator
carries fallout by them. Open-Meteo is told only places on whole degrees, never a target.
</div>
{weather.targets === 0
? <div style={warning}>
No nuclear targets are saved, so there is nowhere to download the forecast around. Save some in
nuclear mode (☢) on the map.
</div>
: <div style={muted}>
Around {weather.targets === 1 ? "1 target" : `${weather.targets} targets`}: {weather.points} places
every {weather.spacing}°, which takes {downloadTime(weather.seconds)} to download.
</div>}
{weather.enabled && <div style={{marginTop: "0.5rem"}}>
{downloading && <div>Downloading the forecast…</div>}
{download?.last_successful_download && <div style={muted}>
Last downloaded {when(download.last_successful_download)}.
{download.next_download && !downloading && ` Next ${when(download.next_download)}.`}
</div>}
{failed && <div style={warning}>The last download failed: {download.error}</div>}
<Button size='xs' style={{marginTop: "0.25rem"}} disabled={downloading || weather.targets === 0}
onClick={downloadNow}>Download now</Button>
</div>}
<div style={{marginTop: "0.5rem"}}>
{field
? <>
<div>
Forecast kept: {when(field.first_hour)} to {when(field.last_hour)}, {field.points} places
every {field.spacing}°, {humanFileSize(field.size)}.
</div>
{fieldCoversNow(field)
? <div style={muted}>It has the winds for bursts now, until their fallout is down.</div>
: <div style={warning}>
It is too old for bursts now: their fallout comes down over {LANDING_HOURS} hours, past
its end. {weather.enabled ? "Download it again." : "Turn on the download to get a new one."}
</div>}
</>
: <div style={muted}>No forecast has been downloaded.</div>}
</div>
</>;
}

View file

@ -0,0 +1,128 @@
import {PMTiles} from "pmtiles";
import {getMapFiles} from "../api";
import {mediaUrl} from "./mapOverlays";
// The ground under a fallout plume, read from the terrain files the user has downloaded (terrarium
// elevation tiles), as an elevation grid the model reads (map-shared/fallout/terrain.js).
// No more tiles than this are read for one plume; a wider plume is read at a coarser zoom.
const MAX_TILES = 36;
// Deeper than this adds nothing: a spot of fallout is at least a kilometer across.
const DEEPEST_ZOOM = 9;
// How many samples the grid has along its longer side.
const GRID_SAMPLES = 600;
function tileX(lon, z) {
return Math.floor((lon + 180) / 360 * 2 ** z);
}
// The tile column `x` names at zoom `z`, wrapped around the antimeridian.
function wrapTileX(x, z) {
const n = 2 ** z;
return ((x % n) + n) % n;
}
function tileY(lat, z) {
const r = lat * Math.PI / 180;
return Math.floor((1 - Math.log(Math.tan(r) + 1 / Math.cos(r)) / Math.PI) / 2 * 2 ** z);
}
async function decodeTile(data) {
const bitmap = await createImageBitmap(new Blob([data]));
const canvas = document.createElement("canvas");
canvas.width = bitmap.width;
canvas.height = bitmap.height;
const context = canvas.getContext("2d", {willReadFrequently: true});
context.drawImage(bitmap, 0, 0);
return context.getImageData(0, 0, bitmap.width, bitmap.height);
}
let terrainFiles = null;
// The terrain files, finest first: [{tiles (PMTiles), header}].
async function openTerrainFiles() {
if (terrainFiles) return terrainFiles;
const data = await getMapFiles();
const files = (data?.files || []).filter((f) => f.kind === "terrain");
const opened = await Promise.all(files.map(async (f) => {
const tiles = new PMTiles(`${window.location.origin}${mediaUrl(f.path)}`);
return {tiles, header: await tiles.getHeader()};
}));
terrainFiles = opened.sort((a, b) => b.header.maxZoom - a.header.maxZoom);
return terrainFiles;
}
// The terrarium elevation (m) at `lon`, `lat` of the read tiles, or null where none was read.
function sample(tiles, n, lon, lat) {
const r = lat * Math.PI / 180;
// A plume may cross the antimeridian: longitudes wrap.
const fx = ((((lon + 180) % 360) + 360) % 360) / 360 * n;
const fy = (1 - Math.log(Math.tan(r) + 1 / Math.cos(r)) / Math.PI) / 2 * n;
const image = tiles.get(`${Math.floor(fx)}/${Math.floor(fy)}`);
if (!image) return null;
const px = Math.min(Math.floor((fx % 1) * image.width), image.width - 1);
const py = Math.min(Math.floor((fy % 1) * image.height), image.height - 1);
const p = (py * image.width + px) * 4;
const d = image.data;
// Terrarium: meters = R * 256 + G + B / 256 - 32768. Below sea level is the sea floor, mostly:
// fallout lands on the water.
const meters = d[p] * 256 + d[p + 1] + d[p + 2] / 256 - 32768;
return Number.isFinite(meters) ? Math.max(0, meters) : null;
}
// An elevation grid over `bounds` ([west, south, east, north], degrees) around ground zero at `lon`,
// `lat`, or null when no terrain file covers ground zero. Where no file covers the grid, it is as
// high as ground zero (flat ground, as the model takes it without terrain). {grid, zoom, coverage
// (share of samples read from a file)}.
export async function loadTerrainGrid(bounds, lon, lat) {
const files = await openTerrainFiles();
if (!files.length) return null;
// Web Mercator tiles end at 85 degrees.
const [west, east] = [bounds[0], bounds[2]];
const [south, north] = [Math.max(bounds[1], -85), Math.min(bounds[3], 85)];
const covering = files.filter(({header: h}) =>
h.minLon < east && h.maxLon > west && h.minLat < north && h.maxLat > south);
if (!covering.length) return null;
let zoom = Math.min(DEEPEST_ZOOM, Math.max(...covering.map((f) => f.header.maxZoom)));
const count = (z) => (tileX(east, z) - tileX(west, z) + 1) * (tileY(south, z) - tileY(north, z) + 1);
while (zoom > 0 && count(zoom) > MAX_TILES) zoom--;
// Each tile from the finest file which has it.
const tiles = new Map();
const reads = [];
for (let x = tileX(west, zoom); x <= tileX(east, zoom); x++) {
for (let y = tileY(north, zoom); y <= tileY(south, zoom); y++) {
reads.push((async () => {
for (const {tiles: file, header} of covering) {
if (header.maxZoom < zoom) continue;
const tile = await file.getZxy(zoom, wrapTileX(x, zoom), y);
if (tile?.data) {
tiles.set(`${wrapTileX(x, zoom)}/${y}`, await decodeTile(tile.data));
return;
}
}
})());
}
}
await Promise.all(reads);
if (!tiles.size) return null;
const n = 2 ** zoom;
const groundZero = sample(tiles, n, lon, lat);
if (groundZero === null) return null;
const step = Math.max(east - west, north - south) / GRID_SAMPLES;
const nx = Math.ceil((east - west) / step) + 1;
const ny = Math.ceil((north - south) / step) + 1;
const values = new Float32Array(nx * ny);
let read = 0;
for (let j = 0; j < ny; j++) {
for (let i = 0; i < nx; i++) {
const v = sample(tiles, n, west + i * step, south + j * step);
values[j * nx + i] = v === null ? groundZero : v;
if (v !== null) read++;
}
}
return {grid: {west, south, step, nx, ny, values}, zoom, coverage: read / (nx * ny)};
}

View file

@ -0,0 +1,77 @@
// The air a fallout particle falls through, and how fast it falls. Shared by the app's map viewer
// and the standalone viewer: no imports from the app, no dependencies.
//
// The air is the U.S. Standard Atmosphere, 1976, up to 32 km, which is above the top of the cloud
// of any weapon in the list. A particle is a sphere of fused soil, and falls at the speed at which
// the drag of the air holds up its weight.
const GRAVITY = 9.80665;
// The gas constant of dry air, J/(kg K).
const AIR_GAS_CONSTANT = 287.053;
// Fallout particles are mostly fused soil and glass.
export const PARTICLE_DENSITY = 2600;
// The temperature (K) and pressure (Pa) of the air `altitude` meters above sea level.
export function standardAir(altitude) {
const h = Math.max(0, Math.min(altitude, 32000));
if (h <= 11000) {
const temperature = 288.15 - 0.0065 * h;
return {temperature, pressure: 101325 * Math.pow(temperature / 288.15, 5.255877)};
}
if (h <= 20000) {
return {temperature: 216.65, pressure: 22632.06 * Math.exp(-0.00015768852 * (h - 11000))};
}
const temperature = 216.65 + 0.001 * (h - 20000);
return {temperature, pressure: 5474.889 * Math.pow(temperature / 216.65, -34.163195)};
}
// The density (kg/m^3) and viscosity (Pa s, by Sutherland's law) of the air at `altitude`.
export function airProperties(altitude) {
const {temperature, pressure} = standardAir(altitude);
return {
density: pressure / (AIR_GAS_CONSTANT * temperature),
viscosity: 1.458e-6 * Math.pow(temperature, 1.5) / (temperature + 110.4),
};
}
// The drag coefficient of a sphere at Reynolds number `re` (Clift and Gauvin), good from creeping
// flow up to the drag crisis, which no fallout particle reaches.
export function sphereDrag(re) {
return 24 / re * (1 + 0.15 * Math.pow(re, 0.687)) + 0.42 / (1 + 42500 * Math.pow(re, -1.16));
}
// The speed (m/s) at which a particle of `diameter` meters falls at `altitude` meters above sea
// level, once it has stopped speeding up (which takes it well under a second).
export function settlingSpeed(diameter, altitude) {
const {density, viscosity} = airProperties(altitude);
// The Best number: drag coefficient times the Reynolds number squared, which does not depend on
// the speed; the Reynolds number which matches it is found by bisection, since Cd Re^2 only grows.
const best = 4 / 3 * density * (PARTICLE_DENSITY - density) * GRAVITY * diameter ** 3 / viscosity ** 2;
let low = 1e-12, high = 1e6;
for (let i = 0; i < 80; i++) {
const re = Math.sqrt(low * high);
if (sphereDrag(re) * re * re < best) low = re; else high = re;
}
return Math.sqrt(low * high) * viscosity / (density * diameter);
}
// Settling speeds by altitude, every SPEED_STEP meters, for each diameter asked for: a table read
// many times (every fall of every burst), where solving the drag balance each time would cost most
// of the model's time.
const SPEED_STEP = 25;
const SPEED_LOWEST = -3000;
const SPEED_HIGHEST = 40000;
const speedTables = new Map();
// settlingSpeed, read from a table: linear between altitudes SPEED_STEP meters apart.
export function settlingSpeedAt(diameter, altitude) {
let table = speedTables.get(diameter);
if (!table) {
table = new Float64Array(Math.ceil((SPEED_HIGHEST - SPEED_LOWEST) / SPEED_STEP) + 1);
for (let i = 0; i < table.length; i++) table[i] = settlingSpeed(diameter, SPEED_LOWEST + i * SPEED_STEP);
speedTables.set(diameter, table);
}
const f = Math.min(Math.max((altitude - SPEED_LOWEST) / SPEED_STEP, 0), table.length - 1.000001);
const i = Math.floor(f);
return table[i] + (f - i) * (table[i + 1] - table[i]);
}

View file

@ -0,0 +1,176 @@
// The climatology: the winds aloft of 30 real past days of a month, the whole world, as
// wrolpi/scripts/build_fallout_climatology.py writes them. With no forecast to go on, the fallout of
// the bursts is found in each day's winds, and the map shows on how many of the days it reached each
// place. Shared by the app's map viewer and the standalone viewer: no imports from the app.
//
// A month's file (after gzip): 'WFCL', version (uint16 LE), header length (uint32 LE), the header
// (JSON), the heights of the levels (int16 LE, [level][lat][lon], m), then each day's u and v (int8,
// [level][lat][lon], m/s).
import {depositionGrid, landingSpots, sharpenGrid} from './model.js';
import {combineBursts} from './targets.js';
import {fieldWinds, prepareField} from './winds.js';
// How far around the bursts a day's winds are read (degrees).
export const CLIMATE_MARGIN = 12;
// A day's grid reaches as far as this dose rate (R/hr at H+1): the faintest band the map draws.
const DAY_FLOOR = 0.1;
// The bytes of a gzip file, unzipped (in a browser).
export async function gunzip(buffer) {
const DecompressionStream = typeof window === 'undefined' ? undefined : window.DecompressionStream;
if (!DecompressionStream) throw new Error('This browser cannot unzip the past days\' winds');
const stream = new Blob([buffer]).stream().pipeThrough(new DecompressionStream('gzip'));
return new Uint8Array(await new Response(stream).arrayBuffer());
}
// A month, from its unzipped bytes: {header, levels, nlat, nlon, heights, day(k) -> {u, v}, days}.
export function parseClimatology(bytes) {
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
const magic = String.fromCharCode(...bytes.subarray(0, 4));
if (magic !== 'WFCL') throw new Error('Not a fallout climatology file');
const version = view.getUint16(4, true);
if (version !== 1) throw new Error(`A climatology of version ${version} is not understood`);
const headLength = view.getUint32(6, true);
const header = JSON.parse(new TextDecoder().decode(bytes.subarray(10, 10 + headLength)));
const levels = header.levels_hpa.length, nlat = header.lat[2], nlon = header.lon[2];
const size = levels * nlat * nlon;
let at = 10 + headLength;
// Int16 may not be aligned in the file: copied out.
const heights = new Int16Array(size);
for (let i = 0; i < size; i++) heights[i] = view.getInt16(at + 2 * i, true);
at += 2 * size;
const days = header.days.length;
if (bytes.byteLength < at + days * 2 * size) throw new Error('The climatology file is short');
const start = at;
const day = (k) => ({
u: new Int8Array(bytes.buffer, bytes.byteOffset + start + k * 2 * size, size),
v: new Int8Array(bytes.buffer, bytes.byteOffset + start + k * 2 * size + size, size),
});
return {bytes, header, levels, nlat, nlon, heights, day, days};
}
// The latitude and longitude of grid row `j` and column `i` (longitude from -180 to 180).
function place(clim, j, i) {
const [lat0, dlat] = clim.header.lat, [lon0, dlon] = clim.header.lon;
return [lat0 + j * dlat, ((lon0 + i * dlon + 180) % 360 + 360) % 360 - 180];
}
// Day `k`'s winds over `bounds` ([south, west, north, east], degrees, widened by CLIMATE_MARGIN), as
// a field of one hour (winds.js), at `time` (its hour, any time: the winds are held).
export function dayField(clim, k, bounds, time = '2000-01-01T12:00Z') {
const [south, west, north, east] = bounds;
const lonMargin = CLIMATE_MARGIN / Math.cos(Math.min(Math.max(Math.abs(south), Math.abs(north)), 80) * Math.PI / 180);
const {u, v} = clim.day(k);
const plane = clim.nlat * clim.nlon;
const points = [], winds = [];
for (let j = 0; j < clim.nlat; j++) {
for (let i = 0; i < clim.nlon; i++) {
const [lat, lon] = place(clim, j, i);
if (lat < south - CLIMATE_MARGIN || lat > north + CLIMATE_MARGIN) continue;
// Between west and east, with the margin, either side of the antimeridian.
if (![lon, lon - 360, lon + 360].some((l) => l >= west - lonMargin && l <= east + lonMargin)) continue;
const rows = [];
for (let l = 0; l < clim.levels; l++) {
const c = l * plane + j * clim.nlon + i;
const e = u[c], n = v[c];
rows.push([clim.heights[c], Math.hypot(e, n), (Math.atan2(-e, -n) * 180 / Math.PI + 360) % 360]);
}
points.push({lat, lon, elevation: 0});
winds.push([rows]);
}
}
return {source: 'climatology', fetched_at: time, spacing: clim.header.lat[1] < 0 ? -clim.header.lat[1] : clim.header.lat[1],
points, hours: [time], winds, rain: points.map(() => [0])};
}
// The south, west, north, east of `bursts` ({lat, lon}).
export function burstBounds(bursts) {
const lats = bursts.map((b) => b.lat), lons = bursts.map((b) => b.lon);
return [Math.min(...lats), Math.min(...lons), Math.max(...lats), Math.max(...lons)];
}
// The fallout of `bursts` ([{lat, lon, yieldKt, fissionFraction}]) in day `k` of `clim`, on flat
// ground at sea level: a grid around the first burst, as depositionGrid gives it. `onBurst()` hears
// each burst done, and is awaited (to let the page draw); null once `stopped()`.
export async function climateDay(clim, k, bursts, {onBurst = () => null, stopped = () => false} = {}) {
const prepared = prepareField(dayField(clim, k, burstBounds(bursts)));
const startMs = Date.parse(prepared.field.hours[0]);
const runs = [];
for (const b of bursts) {
const winds = fieldWinds(prepared, {lat0: b.lat, lon0: b.lon, groundElevation: 0, startMs});
const spots = landingSpots({yieldKt: b.yieldKt, winds, siteElevation: 0})
.filter((s) => Number.isFinite(s.x) && Number.isFinite(s.y) && s.sigma > 0);
runs.push({burst: b, spots, yieldKt: b.yieldKt, fissionFraction: b.fissionFraction});
await onBurst();
if (stopped()) return null;
}
const spots = combineBursts(bursts[0], runs);
return sharpenGrid(depositionGrid(spots, {yieldKt: 1, boundsFloor: DAY_FLOOR}), spots);
}
// The cells of `grid` at or above `rate`: {x0, y0, cell, nx, indexes}, small enough to pass from a
// worker.
export function reachedCells(grid, rate) {
const indexes = [];
for (let c = 0; c < grid.values.length; c++) if (grid.values[c] >= rate) indexes.push(c);
return {x0: grid.x0, y0: grid.y0, cell: grid.cell, nx: grid.nx, indexes: Int32Array.from(indexes)};
}
// How many days reached each place: a counter of days' grids (as depositionGrid gives them, all
// around the same origin), at or above `rate`, on cells `cell` meters wide.
export function dayCounter(rate, cell) {
const counts = new Map();
let days = 0;
return {
// A day: its grid, or the cells of it reached (as reachedCells gives them).
add(day) {
days++;
const {x0, y0, cell: size, nx, indexes} = day.indexes ? day : reachedCells(day, rate);
const seen = new Set();
for (const c of indexes) {
const x = x0 + (c % nx + 0.5) * size, y = y0 + (Math.floor(c / nx) + 0.5) * size;
seen.add(`${Math.floor(x / cell)},${Math.floor(y / cell)}`);
}
for (const key of seen) counts.set(key, (counts.get(key) || 0) + 1);
},
// The share of days (0..1) on a grid of `cell` cells around the places reached, each the
// average over itself and its neighbors within `smooth` cells.
grid(smooth = 1) {
if (!counts.size) return null;
let i0 = Infinity, i1 = -Infinity, j0 = Infinity, j1 = -Infinity;
for (const key of counts.keys()) {
const [i, j] = key.split(',').map(Number);
i0 = Math.min(i0, i); i1 = Math.max(i1, i); j0 = Math.min(j0, j); j1 = Math.max(j1, j);
}
i0 -= smooth; j0 -= smooth; i1 += smooth; j1 += smooth;
const nx = i1 - i0 + 1, ny = j1 - j0 + 1;
const raw = new Float64Array(nx * ny);
for (const [key, n] of counts) {
const [i, j] = key.split(',').map(Number);
raw[(j - j0) * nx + (i - i0)] = n / days;
}
const values = new Float64Array(nx * ny);
const width = (2 * smooth + 1) ** 2;
for (let j = 0; j < ny; j++) {
for (let i = 0; i < nx; i++) {
let sum = 0;
for (let b = -smooth; b <= smooth; b++) {
const jj = j + b;
if (jj < 0 || jj >= ny) continue;
for (let a = -smooth; a <= smooth; a++) {
const ii = i + a;
if (ii >= 0 && ii < nx) sum += raw[jj * nx + ii];
}
}
values[j * nx + i] = sum / width;
}
}
return {x0: i0 * cell, y0: j0 * cell, cell, nx, ny, values, days};
},
get days() {
return days;
},
};
}

View file

@ -0,0 +1,89 @@
import {burstBounds, dayCounter, dayField, parseClimatology} from './climatology.js';
import {depositionGrid, landingSpots} from './model.js';
import {fieldWinds, prepareField} from './winds.js';
// A month file of `days` days on a coarse grid (lat 90..-90 every 30, lon 0..330 every 30), two
// levels, each day with one wind everywhere: [east, north] m/s.
function file(days) {
const header = {version: 1, month: 5, levels_hpa: [1000, 500], lat: [90, -30, 7], lon: [0, 30, 12],
days: days.map((_, k) => `200${k}-05-01`), hour_utc: 12};
const head = new TextEncoder().encode(JSON.stringify(header));
const size = 2 * 7 * 12;
const bytes = new Uint8Array(10 + head.length + 2 * size + days.length * 2 * size);
bytes.set([...'WFCL'].map((c) => c.charCodeAt(0)), 0);
const view = new DataView(bytes.buffer);
view.setUint16(4, 1, true);
view.setUint32(6, head.length, true);
bytes.set(head, 10);
let at = 10 + head.length;
for (let c = 0; c < size; c++) view.setInt16(at + 2 * c, c < size / 2 ? 100 : 5500, true);
at += 2 * size;
days.forEach(([e, n]) => {
for (let c = 0; c < size; c++) view.setInt8(at + c, e);
for (let c = 0; c < size; c++) view.setInt8(at + size + c, n);
at += 2 * size;
});
return bytes;
}
describe('the climatology', () => {
test('is read from its file', () => {
const clim = parseClimatology(file([[10, 0], [-5, 3]]));
expect(clim.days).toBe(2);
expect([clim.levels, clim.nlat, clim.nlon]).toEqual([2, 7, 12]);
expect(clim.heights[0]).toBe(100);
expect(clim.day(1).u[0]).toBe(-5);
expect(clim.day(1).v[0]).toBe(3);
expect(() => parseClimatology(new Uint8Array(20))).toThrow('Not a fallout climatology');
});
test('gives a day\'s winds around the bursts, as a field the model reads', () => {
const clim = parseClimatology(file([[10, 0]]));
const field = dayField(clim, 0, burstBounds([{lat: 30, lon: -120}, {lat: 30, lon: -90}]));
// Only the points near the bursts: latitudes 30 +- 12 on this grid are 30; longitudes
// -120 to -90 with the margin.
expect(new Set(field.points.map((p) => p.lat))).toEqual(new Set([30]));
expect(field.points.map((p) => p.lon).sort((a, b) => a - b)).toEqual([-120, -90]);
// A west wind: from 270 degrees, 10 m/s, at the levels' heights.
expect(field.winds[0][0]).toEqual([[100, 10, 270], [5500, 10, 270]]);
expect(field.spacing).toBe(30);
});
test('takes in either side of the antimeridian', () => {
const clim = parseClimatology(file([[10, 0]]));
const lons = dayField(clim, 0, burstBounds([{lat: 0, lon: 179}])).points.map((p) => p.lon);
expect(lons).toContain(180 - 360);
});
test('counts on how many days each place was reached', () => {
const counter = dayCounter(1, 1000);
const grid = (cells) => ({x0: 0, y0: 0, cell: 1000, nx: 3, ny: 1, values: cells});
counter.add(grid([5, 0, 0]));
counter.add(grid([5, 2, 0]));
counter.add(grid([0, 0, 0.5]));
const shares = counter.grid(0);
expect(shares.days).toBe(3);
expect(Array.from(shares.values)).toEqual([2 / 3, 1 / 3]);
// Smoothed over neighbors (a cell all round): spread out, the total kept.
const smooth = counter.grid(1);
expect([smooth.nx, smooth.ny]).toEqual([4, 3]);
expect(smooth.values.reduce((a, v) => a + v, 0)).toBeCloseTo(1, 10);
expect(Math.max(...smooth.values)).toBeCloseTo(1 / 9, 10);
});
test('shows the fallout of each day\'s winds: two days east, one north', () => {
const clim = parseClimatology(file([[10, 0], [10, 0], [0, 10]]));
const burst = {lat: 30, lon: -120};
const counter = dayCounter(1, 4000);
for (let k = 0; k < clim.days; k++) {
const winds = fieldWinds(prepareField(dayField(clim, k, burstBounds([burst]))),
{lat0: burst.lat, lon0: burst.lon, startMs: Date.parse('2000-01-01T12:00Z')});
counter.add(depositionGrid(landingSpots({yieldKt: 10, winds}), {yieldKt: 10, boundsFloor: 1}));
}
const shares = counter.grid(0);
const at = (x, y) => shares.values[Math.floor((y - shares.y0) / shares.cell) * shares.nx + Math.floor((x - shares.x0) / shares.cell)];
// 60 km east: two days of three; 60 km north: one.
expect(at(60000, 0)).toBeCloseTo(2 / 3, 10);
expect(at(0, 60000)).toBeCloseTo(1 / 3, 10);
});
});

View file

@ -0,0 +1,5 @@
/* eslint-disable no-restricted-globals */
// A worker for the fallout (pool.js): the past days', or the bursts'.
import {serveFallout} from './work.js';
serveFallout(self);

View file

@ -0,0 +1,6 @@
// A fallout worker (fallout.worker.js), or null where a browser has none. Alone in its own file:
// Jest cannot read import.meta, so it is given a stand-in (package.json, "jest").
export function makeFalloutWorker() {
if (typeof Worker === 'undefined') return null;
return new Worker(new URL('./fallout.worker.js', import.meta.url));
}

View file

@ -0,0 +1,4 @@
// Jest's stand-in for falloutWorker.js: no workers, so the fallout is calculated on the page.
export function makeFalloutWorker() {
return null;
}

View file

@ -0,0 +1,15 @@
{
"_source": "FM 3-11.3, Multiservice Tactics, Techniques, and Procedures for Chemical, Biological, Radiological, and Nuclear Contamination Avoidance (2006), Appendix G. Approved for public release; distribution is unlimited.",
"_how": "Read by eye from the nomograms (Figures G-21 and G-22), to about 5%. Figure G-22's scales are logarithmic; their pixel rows (on the 1103 x 1400 image) were fitted as row = a - b log10(value / c), which reproduces the appendix's two worked examples (50 kt at 9 km/h: 22 km; 100 kt at 16 knots: 30 nautical miles) to 2%.",
"cloud": {
"_what": "Figure G-21, Radioactive Cloud and Stem Parameters, stabilized at H+10 minutes: [yield kt, cloud top km, cloud bottom km, cloud radius km], above the burst.",
"rows": [[1, 3.8, 2.05, 1.0], [10, 8.3, 5.0, 2.6], [50, 12.8, 8.4, 5.6], [100, 14.3, 9.3, 6.9], [300, 17.0, 11.0, 11.0], [1000, 21.8, 13.5, 19.0], [10000, 33.0, 19.3, 46.0]]
},
"zone1": {
"_what": "Figure G-22, Determination of Zone I, Downwind Distance: a straight line from the effective downwind speed (left) to the yield (right) crosses the distance (middle). Zone I: where someone outdoors may get 125 cGy or more within 4 hours of the fallout arriving. Surface burst, all fission.",
"wind_kmh": {"x": 148, "a": 604, "b": 188, "c": 100},
"yield_kt": {"x": 940, "a": 538, "b": 195, "c": 100},
"distance_km": {"x": 522, "a": 577, "b": 194, "c": 100},
"examples": [[50, 9, 22], [100, 29.6, 55.6]]
}
}

View file

@ -0,0 +1,852 @@
// Where the local fallout of a burst at the ground lands, and how radioactive the ground is there.
// Shared by the app's map viewer and the standalone viewer: no imports from the app, no
// dependencies.
//
// All of the activity starts in the early fireball, on particles of every size, and rises with the
// cloud [SIMFIC]. The cloud's base and top rise with the square root of time to their stabilized
// heights; inside it the air rises as fast as the cloud, and below it ever slower toward the
// ground. Each particle rises with the air less its own settling speed, so a heavy particle drops
// out of the cloud low and early, near ground zero (the stem's close-in fallout), and a light one
// rides to the top of the cloud and falls far downwind. Every particle is carried by the wind at
// the height it is at, while it rises and while it falls, and lands where it first meets the
// ground. Each (size, starting height) lands as a Gaussian spot, as wide as the cloud was where it
// left it, and widened by the turbulence of the air on the way down.
//
// Sources (each where it is used):
// [SIMFIC] H. G. Norment, SIMFIC: A Simple, Efficient Fallout Prediction Model, DNA 5193F
// (1979), DTIC ADA089187: the rising cloud, the particles' paths in it, how wide each is
// when it leaves it, its widening by turbulence, and the share of the activity which
// comes down for a burst above the ground. SIMFIC matched DELFIC, the Department of
// Defense's fallout code, on five test shots from 0.5 to 3380 kt.
// [DNAF-1] H. G. Norment, DNAF-1: An Analytical Fallout Prediction Model and Code, DNA 6299F
// (1981), DTIC ADA130291: the stabilized cloud's heights (Wilsey and Crisco's fits to
// observed clouds, which SIMFIC uses too), DELFIC's standard particle size distribution,
// and the exposure rate of a kiloton of fission products spread over unit area.
import {settlingSpeedAt} from './atmosphere.js';
const FEET = 0.3048;
const MPH = 0.44704;
const SQ_KM_PER_SQ_MI = 2.589988;
// The exposure rate at H+1 hour, a meter above an ideal flat plane, of the fission products of one
// kiloton spread over one square kilometer: (R/hr) km^2 / kt [DNAF-1, (31)]: 6.9733e9 R m^2/(hr kt).
// (Glasstone and Dolan, 9.14, give 2900 rad/hr for a kiloton over a square mile: 7511 per km^2.)
// It is for all of the activity; the model decides how much of it lands locally.
export const SOURCE_NORMALIZATION = 6973.3;
// DELFIC's standard distribution of the number of particles over diameter [DNAF-1]: lognormal.
const NUMBER_MEDIAN_DIAMETER = 0.407e-6;
const GEOMETRIC_SD = 4.0;
// Activity is carried both through the volume of a particle (condensed into it while molten) and
// on its surface (condensed onto it later). This share by volume makes the activity-weighted mean
// diameter 229 um, the "nominal particle" which DNAF-1 computed from DELFIC [DNAF-1, section 2.4].
export const VOLUME_ACTIVITY_SHARE = 0.6;
// Particles are tracked from 1 um to 4 mm. Activity on smaller ones stays aloft for weeks (it is
// not local fallout); what is on larger ones is put on the largest.
const SMALLEST_DIAMETER = 1e-6;
const LARGEST_DIAMETER = 4e-3;
const SIZE_BINS = 48;
// How many heights in the early fireball each particle size starts from.
const SUBDIVISIONS = 10;
// How finely a fall is integrated, in meters of height.
const FALL_STEP = 50;
// The longest step (m) and time (s) a particle falls in at once through winds which change with
// place and time.
const FIELD_STEP = 250;
const FIELD_SECONDS = 1200;
// Rain's taking of fallout out of the air [Glasstone and Dolan, Tables 9.74a and b]: inside the rain
// cloud, per hour; below it, per hour in light, moderate and heavy rain (mm an hour).
const RAINOUT_PER_HOUR = Math.LN2 / 0.16;
const WASHOUT = [[1.27, Math.LN2 / 19], [5.08, Math.LN2 / 3.8], [11.94, Math.LN2 / 1.9]];
// What rain takes out on the way is put down as a spot for every so many meters (m).
const WET_MERGE = 10000;
// No wind: the profile of fall paths when the winds are taken where and when a particle is.
const CALM = [[0, 0, 0]];
// When the cloud stops rising (s) [SIMFIC, Table 1, from DELFIC], for yields of 10^-3 to 10^5 kt.
const STOP_TIMES = [300, 300, 300, 300, 300, 280, 200, 160, 150];
// A wind table, as rows of [altitude (ft above sea level), direction the wind blows FROM (degrees),
// speed (mph)], as a profile of [height above ground (m), east (m/s), north (m/s)].
export function profileFromTable(rows, siteElevationFt) {
return rows
.map(([altitude, from, speed]) => {
const toward = (from + 180) * Math.PI / 180;
const s = speed * MPH;
return [(altitude - siteElevationFt) * FEET, s * Math.sin(toward), s * Math.cos(toward)];
})
.sort((a, b) => a[0] - b[0]);
}
// The wind (east, north; m/s) at `height` meters above the ground: linear between the heights of
// the profile, and as the nearest one beyond them.
export function windAt(profile, height) {
if (height <= profile[0][0]) return [profile[0][1], profile[0][2]];
const last = profile[profile.length - 1];
if (height >= last[0]) return [last[1], last[2]];
let i = 1;
while (profile[i][0] < height) i++;
const [z0, u0, v0] = profile[i - 1];
const [z1, u1, v1] = profile[i];
const f = (height - z0) / (z1 - z0);
return [u0 + f * (u1 - u0), v0 + f * (v1 - v0)];
}
// One wind, as a uniform-wind model takes it: the mean of the profile over the height of the cloud.
export function uniformProfile(profile, top) {
let u = 0, v = 0;
const steps = 200;
for (let i = 0; i < steps; i++) {
const [du, dv] = windAt(profile, (i + 0.5) / steps * top);
u += du / steps;
v += dv / steps;
}
return [[0, u, v]];
}
// The stabilized cloud of a `yieldKt` burst: cap base and top heights above the burst [DNAF-1, (3)
// and (4)] and its radius [SIMFIC, (2.6.7)], in meters.
export function stabilizedCloud(yieldKt) {
const w = yieldKt;
const base = w <= 4.07 ? 2228 * Math.pow(w, 0.3463) : 2661 * Math.pow(w, 0.2198);
let top;
if (w < 2.29) top = 3597 * Math.pow(w, 0.2553);
else if (w < 19) top = 3170 * Math.pow(w, 0.4077);
else top = 6474 * Math.pow(w, 0.1650);
const ln = Math.log(w);
const radius = Math.exp(6.7553 + 0.32055 * ln + 0.01137478 * ln * ln);
return {base, top, radius};
}
// The rising cloud of a `yieldKt` burst `burstHeight` meters above the ground [SIMFIC, 2.6]: it
// starts (s after the burst) as the fireball, `initialRadius` wide, between `initialBase` and
// `initialTop` (m above the ground), and rises until `stop` to between `base` and `top`, `radius`
// wide. `stabilized` ({base, top}, m above the burst) is the cloud as observed, if it was.
export function risingCloud(yieldKt, burstHeight = 0, stabilized = null) {
const w = yieldKt;
const fit = {...stabilizedCloud(w), ...(stabilized || {})};
const y = Math.min(Math.max(Math.log10(w), -3), 5) + 3;
const k = Math.min(Math.floor(y), STOP_TIMES.length - 2);
const initialRadius = 108 * Math.pow(w, 0.33);
const initialBase = burstHeight + 90 * Math.cbrt(w);
return {
start: 2.07 * Math.pow(w, 0.13),
stop: STOP_TIMES[k] + (y - k) * (STOP_TIMES[k + 1] - STOP_TIMES[k]),
initialRadius,
initialBase,
initialTop: initialBase + 1.32288 * initialRadius,
base: burstHeight + fit.base,
top: burstHeight + Math.max(fit.top, fit.base + 1),
radius: fit.radius,
};
}
// The share of the activity which comes down as local fallout from a burst `burstHeight` meters
// above the ground [SIMFIC, (2.8.2), from DASA 1251 Volume 5]: all of it from a burst on the
// ground, ever less as the fireball touches the ground less.
export function activityDown(yieldKt, burstHeight) {
const scaled = burstHeight / FEET / Math.cbrt(yieldKt);
return scaled > 0 ? Math.pow(0.45345, scaled / 65) : 1;
}
// The error function (Abramowitz and Stegun 7.1.26; error under 1.5e-7).
function erf(x) {
const sign = x < 0 ? -1 : 1;
const t = 1 / (1 + 0.3275911 * Math.abs(x));
const y = 1 - ((((1.061405429 * t - 1.453152027) * t + 1.421413741) * t - 0.284496736) * t
+ 0.254829592) * t * Math.exp(-x * x);
return sign * y;
}
// The share of a lognormal distribution (median, geometric standard deviation) below `x`.
function lognormalBelow(x, median, gsd) {
return 0.5 * (1 + erf(Math.log(x / median) / (Math.log(gsd) * Math.SQRT2)));
}
// The particle sizes: [{diameter (m), activity}], where activity is the share of all of the
// activity of the burst on particles of that size. The shares add up to less than one: the rest is
// on particles too small to track.
export function particleSizes(volumeShare = VOLUME_ACTIVITY_SHARE) {
const s2 = Math.log(GEOMETRIC_SD) ** 2;
// Weighting the number distribution by d^3 (volume) or d^2 (surface) moves its median.
const volumeMedian = NUMBER_MEDIAN_DIAMETER * Math.exp(3 * s2);
const surfaceMedian = NUMBER_MEDIAN_DIAMETER * Math.exp(2 * s2);
const below = (d) => volumeShare * lognormalBelow(d, volumeMedian, GEOMETRIC_SD)
+ (1 - volumeShare) * lognormalBelow(d, surfaceMedian, GEOMETRIC_SD);
const sizes = [];
const step = Math.log(LARGEST_DIAMETER / SMALLEST_DIAMETER) / SIZE_BINS;
for (let i = 0; i < SIZE_BINS; i++) {
const low = SMALLEST_DIAMETER * Math.exp(i * step);
const high = low * Math.exp(step);
const upper = i === SIZE_BINS - 1 ? 1 : below(high);
sizes.push({diameter: Math.sqrt(low * high), activity: upper - below(low)});
}
return sizes;
}
// The fall of a particle of `diameter` from `top` down to `bottom` meters (zero or below: ground
// lower than ground zero): at each level (every FALL_STEP meters, from `bottom` up), how far it goes
// east and north, and for how many seconds, from there down to `bottom`.
function fall(diameter, top, bottom, profile, siteElevation) {
const steps = Math.ceil((top - bottom) / FALL_STEP);
const east = new Float64Array(steps + 1);
const north = new Float64Array(steps + 1);
const seconds = new Float64Array(steps + 1);
for (let i = 1; i <= steps; i++) {
const middle = bottom + (i - 0.5) * FALL_STEP;
const dt = FALL_STEP / settlingSpeedAt(diameter, siteElevation + middle);
const [u, v] = windAt(profile, middle);
east[i] = east[i - 1] + u * dt;
north[i] = north[i - 1] + v * dt;
seconds[i] = seconds[i - 1] + dt;
}
return {east, north, seconds};
}
// The settling speed (m/s) on `path` at `height`.
function speedOn(path, height, bottom) {
const i = Math.min(Math.max(Math.floor((height - bottom) / FALL_STEP) + 1, 1), path.seconds.length - 1);
return FALL_STEP / (path.seconds[i] - path.seconds[i - 1]);
}
// Where a particle falling from `height`, `x0` m east and `y0` m north of ground zero, lands: the
// first level on the way down at which it is at or below the ground under it. [east, north,
// seconds] of where it lands and how long it took.
function landing(path, height, x0, y0, bottom, ground) {
const {east, north, seconds} = path;
const start = Math.min(Math.max(Math.round((height - bottom) / FALL_STEP), 0), seconds.length - 1);
for (let m = start - 1; m > 0; m--) {
const x = x0 + east[start] - east[m];
const y = y0 + north[start] - north[m];
if (bottom + m * FALL_STEP <= ground(x, y)) return [x, y, seconds[start] - seconds[m]];
}
return [x0 + east[start] - east[0], y0 + north[start] - north[0], seconds[start] - seconds[0]];
}
// The cloud's base and top (m) and how fast they rise (m/s) `t` seconds after the burst
// [SIMFIC, (2.2.1), (2.2.2)].
function cloudAt(cloud, t) {
const span = Math.sqrt(cloud.stop) - Math.sqrt(cloud.start);
if (t >= cloud.stop) return {base: cloud.base, top: cloud.top, baseSpeed: 0, topSpeed: 0};
const s = (Math.sqrt(t) - Math.sqrt(cloud.start)) / span;
return {
base: cloud.initialBase + s * (cloud.base - cloud.initialBase),
top: cloud.initialTop + s * (cloud.top - cloud.initialTop),
baseSpeed: (cloud.base - cloud.initialBase) / (2 * Math.sqrt(t) * span),
topSpeed: (cloud.top - cloud.initialTop) / (2 * Math.sqrt(t) * span),
};
}
// How fast the air rises (m/s) at `height` `t` seconds after the burst: inside the cloud, linear
// between its base and top; below it, slowing linearly to nothing at the ground [SIMFIC, (2.2.3),
// (2.2.4)]; nothing once the cloud stops.
function updraft(cloud, height, t) {
const c = cloudAt(cloud, t);
if (c.baseSpeed === 0) return 0;
if (height >= c.base) {
const f = Math.min((height - c.base) / Math.max(c.top - c.base, 1), 1);
return c.baseSpeed + f * (c.topSpeed - c.baseSpeed);
}
return c.baseSpeed * Math.max(height, 0) / c.base;
}
// The rise of a particle from `height` in the fireball, until the cloud stops: {height, x, y (m),
// highest (m), highest at (s), landed (whether it met the ground first), seconds}. `ground` is
// ignored when it is null.
function rise(cloud, path, height, profile, bottom, ground, winds = null) {
let z = height, x = 0, y = 0, t = cloud.start, highest = z, highestAt = t;
while (t < cloud.stop) {
const dt = Math.min(Math.max(0.02 * t, 0.2), 5, cloud.stop - t);
const w1 = updraft(cloud, z, t) - speedOn(path, z, bottom);
const zMid = z + w1 * dt / 2;
const w2 = updraft(cloud, zMid, t + dt / 2) - speedOn(path, zMid, bottom);
const [u, v] = winds ? winds.at(x, y, zMid, t + dt / 2) : windAt(profile, zMid);
z += w2 * dt;
x += u * dt;
y += v * dt;
t += dt;
if (z > highest) {
highest = z;
highestAt = t;
}
if (ground && z <= ground(x, y)) return {height: z, x, y, highest, highestAt, landed: true, seconds: t};
if (!ground && z < bottom) break;
}
return {height: z, x, y, highest, highestAt, landed: false, seconds: t};
}
// How fast rain takes fallout out of the air (per second), at `altitude` (m above sea level) in rain
// of `mmPerHour` falling from `cloud` ([bottom, top], m above sea level, or null where unknown)
// [Glasstone and Dolan, 9.74 and Tables 9.74a and b]. Inside the rain cloud ("rainout") half is
// taken in about 0.16 hour, whatever the rain; below it ("washout") half in 19, 3.8 and 1.9 hours of
// light, moderate and heavy rain (0.05, 0.20 and 0.47 inch an hour). Above the cloud, none.
export function scavengingRate(mmPerHour, altitude, cloud) {
if (!(mmPerHour > 0)) return 0;
if (cloud && altitude > cloud[1]) return 0;
if (cloud && altitude >= cloud[0]) return RAINOUT_PER_HOUR / 3600;
// Between the three rains, on a straight line in log rain against log rate; beyond them, along
// the nearest stretch of it.
const k = mmPerHour <= WASHOUT[1][0] ? 0 : 1;
const [[r0, l0], [r1, l1]] = [WASHOUT[k], WASHOUT[k + 1]];
const slope = Math.log(l1 / l0) / Math.log(r1 / r0);
return l0 * Math.pow(mmPerHour / r0, slope) / 3600;
}
// Where a particle falling from `height`, `x0` m east and `y0` m north of ground zero, `t0` seconds
// after the burst, lands, carried by `winds` (see landingSpots) where and when it is: {at: [east,
// north, seconds] of where it lands and how long it took, or null if it is still falling at
// `maxSeconds`; remaining: the share of it not taken out by rain on the way}. What rain takes out
// is put in `wet` ([{x, y, seconds (after the burst), share}]), a spot for every WET_MERGE meters of
// its way through rain. It falls by up to FIELD_STEP meters at a time, and for no longer than
// FIELD_SECONDS, when the winds change little; it lands where the line of its last step meets the
// ground.
function landingThrough(winds, diameter, siteElevation, height, x0, y0, t0, bottom, ground, maxSeconds, wet) {
let z = height, x = x0, y = y0, t = t0, above = z - ground(x, y);
let remaining = 1, washed = null;
const flush = () => {
if (washed && washed.share > 0) {
wet.push({x: washed.sx / washed.share, y: washed.sy / washed.share, seconds: washed.st / washed.share,
share: washed.share});
}
washed = null;
};
const raining = wet && winds.rainAt;
while (z > bottom) {
const speed = settlingSpeedAt(diameter, siteElevation + z);
const step = Math.min(FIELD_STEP, Math.max(speed * FIELD_SECONDS, FALL_STEP), z - bottom);
const middle = z - step / 2;
const dt = step / settlingSpeedAt(diameter, siteElevation + middle);
const [u, v] = winds.at(x, y, middle, t + dt / 2);
if (raining) {
const mx = x + u * dt / 2, my = y + v * dt / 2;
const [mm, cloud] = winds.rainAt(mx, my, t + dt / 2);
const rate = scavengingRate(mm, siteElevation + middle, cloud);
if (rate > 0) {
// What little would be left is taken with the rest.
let taken = remaining * (1 - Math.exp(-rate * dt));
if (remaining - taken < 1e-4) taken = remaining;
remaining -= taken;
if (!washed) washed = {share: 0, sx: 0, sy: 0, st: 0, x0: mx, y0: my};
washed.share += taken;
washed.sx += taken * mx;
washed.sy += taken * my;
washed.st += taken * (t + dt / 2);
if (Math.hypot(mx - washed.x0, my - washed.y0) > WET_MERGE) flush();
if (remaining <= 0) {
flush();
return {at: null, remaining: 0};
}
} else {
flush();
}
}
const nextAbove = z - step - ground(x + u * dt, y + v * dt);
if (nextAbove <= 0) {
// Down to the ground, part of the way.
const f = above > 0 ? above / (above - nextAbove) : 0;
if (raining) flush();
return {at: [x + f * u * dt, y + f * v * dt, t + f * dt - t0], remaining};
}
x += u * dt;
y += v * dt;
t += dt;
z -= step;
above = nextAbove;
if (t > maxSeconds) {
if (raining) flush();
return {at: null, remaining};
}
}
if (raining) flush();
return {at: [x, y, t - t0], remaining};
}
// How wide (sigma, m) a spot is when it lands: as wide as the cloud was where it left it,
// `sigma0`, widened by the turbulence of the air while it fell from `highest` m at `speed` m/s
// on average [SIMFIC, (2.7.3), (2.7.4), after Walton and Wilkins].
export function landedSigma(sigma0, highest, speed) {
const a = Math.pow(sigma0, 2 / 3);
const z = Math.pow(Math.max(highest, 1), 2 / 3);
if (z < 3.83155 * speed * (1e3 - a)) return Math.sqrt((a + 0.26099 * z / speed) ** 3);
return Math.sqrt(7.8297e5 * z / speed + 3e6 * a - 2e9);
}
// The spots where the activity lands: [{x, y (m east and north of ground zero), sigma (m),
// activity (share of the burst's activity), hours (after the burst), diameter (m, of its
// particles), highest (m, the highest they rose)}].
//
// `yieldKt` and `burstHeight` (m above the ground) are of the burst; `profile` is as
// profileFromTable gives it; `maxHours` is when the ground is looked at: what lands later is not
// counted. `stabilized` is the cloud as observed ({base, top}, m above the burst), if it was.
//
// `terrain`, if given, is {ground(x, y), lowest}: the height (m) of the ground x meters east and y
// north of ground zero, above the ground at ground zero, and the lowest it gets. A particle lands
// where it first meets the ground: early on a ridge in its way, late in a valley. Without it the
// ground is flat.
//
// `winds`, if given, is {at(x, y, z, t)}: the wind [east, north] (m/s) x meters east and y north of
// ground zero, z meters above its ground, t seconds after the burst; a particle is then carried by
// the wind where it is, at the height it is, when it is there, and `profile` is not used. If it
// also has rainAt(x, y, t), [mm an hour, cloud ([bottom, top], m above sea level) or null], rain
// takes fallout out of the air on the way down and puts it down there (spots with `wet`).
export function landingSpots({yieldKt, burstHeight = 0, profile, siteElevation = 0, maxHours = 48,
volumeShare = VOLUME_ACTIVITY_SHARE, terrain = null, stabilized = null,
winds = null}) {
if (winds && winds.held && !winds.rainAt && !terrain && !stabilized) {
return heldLandingSpots({yieldKt, burstHeight, siteElevation, maxHours, volumeShare, winds});
}
if (winds) profile = CALM;
const cloud = risingCloud(yieldKt, Math.max(burstHeight, 0), stabilized);
const down = activityDown(yieldKt, burstHeight);
// Paths go down to 2 km below ground zero: the first parcel of a size to leave the cloud is
// followed below the ground until the cloud stops [SIMFIC, 2.6], and valleys may be that deep.
const bottom = Math.min(-2000, terrain ? Math.floor(terrain.lowest / FALL_STEP) * FALL_STEP : 0);
const ground = terrain ? terrain.ground : () => 0;
const top = Math.max(cloud.top, cloud.initialTop) + 500;
const spots = [];
for (const {diameter, activity} of particleSizes(volumeShare)) {
if (activity <= 0) continue;
const path = fall(diameter, top, bottom, profile, siteElevation);
// The first of this size to leave the cloud does so from the base of the fireball, as wide as
// it; those which leave later, higher, are wider, up to the stabilized cloud [SIMFIC, (2.6.8)].
const first = rise(cloud, path, cloud.initialBase, profile, bottom, null);
for (let j = 0; j < SUBDIVISIONS; j++) {
const start = cloud.initialBase + (j + 0.5) / SUBDIVISIONS * (cloud.initialTop - cloud.initialBase);
const r = rise(cloud, path, start, profile, bottom, ground, winds);
let radius;
if (!r.landed && r.height >= cloud.base) radius = cloud.radius;
else {
const f = (r.height - first.height) / Math.max(cloud.base - first.height, 1);
radius = cloud.initialRadius + Math.min(Math.max(f, 0), 1) * (cloud.radius - cloud.initialRadius);
}
const parcel = activity * down / SUBDIVISIONS;
// A spot where some of this parcel lands, `seconds` after the burst.
const put = (x, y, seconds, share, wet) => {
if (seconds > maxHours * 3600 || !(share > 0)) return;
const falling = Math.max(seconds - r.highestAt, 1);
const sigma = landedSigma(radius / 2, r.highest, Math.max(r.highest, 1) / falling);
spots.push({x, y, sigma, diameter, highest: r.highest, activity: parcel * share, hours: seconds / 3600,
...(wet ? {wet: true} : {})});
};
if (r.landed) {
put(r.x, r.y, r.seconds, 1);
} else if (winds) {
const wet = [];
const landed = landingThrough(winds, diameter, siteElevation, r.height, r.x, r.y, r.seconds, bottom,
ground, maxHours * 3600, wet);
for (const w of wet) put(w.x, w.y, w.seconds, w.share, true);
if (landed.at) put(landed.at[0], landed.at[1], r.seconds + landed.at[2], landed.remaining);
} else {
const [x, y, fallSeconds] = landing(path, r.height, r.x, r.y, bottom, ground);
put(x, y, r.seconds + fallSeconds, 1);
}
}
}
return spots;
}
// The parcels of a burst on flat ground, without the wind: how each rises with the cloud and then
// falls, which the wind does not change (it only carries them). [{diameter, activity, radius,
// landed, highest, highestAt, seconds, riseLevels, riseSeconds: of each step while the cloud rises,
// fall: [middle height, seconds, ...] of each step of the fall, with `lands`, the part of the last step
// before it meets the ground}]. The rise is kept as the level of the winds over ground zero each step
// is in (every FALL_STEP m from 2 km below it) and its seconds. The same for every burst of a yield,
// so kept.
const PARCELS = new Map();
const MOST_KEPT = 64;
const COLUMN_BOTTOM = -2000;
function heldParcels(yieldKt, burstHeight, siteElevation, volumeShare) {
const key = `${yieldKt},${burstHeight},${siteElevation},${volumeShare}`;
if (PARCELS.has(key)) return PARCELS.get(key);
const cloud = risingCloud(yieldKt, Math.max(burstHeight, 0));
const down = activityDown(yieldKt, burstHeight);
const bottom = -2000;
const top = Math.max(cloud.top, cloud.initialTop) + 500;
const parcels = [];
for (const {diameter, activity} of particleSizes(volumeShare)) {
if (activity <= 0) continue;
const path = fall(diameter, top, bottom, CALM, siteElevation);
const first = rise(cloud, path, cloud.initialBase, CALM, bottom, null);
for (let j = 0; j < SUBDIVISIONS; j++) {
const start = cloud.initialBase + (j + 0.5) / SUBDIVISIONS * (cloud.initialTop - cloud.initialBase);
// As rise, on flat ground, with the middle of each step kept.
let z = start, t = cloud.start, highest = z, highestAt = t, landed = false;
const levels = [], seconds = [];
while (t < cloud.stop) {
const dt = Math.min(Math.max(0.02 * t, 0.2), 5, cloud.stop - t);
const w1 = updraft(cloud, z, t) - speedOn(path, z, bottom);
const zMid = z + w1 * dt / 2;
const w2 = updraft(cloud, zMid, t + dt / 2) - speedOn(path, zMid, bottom);
// Steps one after another in the same level are one.
const level = Math.max(Math.floor((zMid - COLUMN_BOTTOM) / FALL_STEP), 0);
if (levels[levels.length - 1] === level) seconds[seconds.length - 1] += dt;
else {
levels.push(level);
seconds.push(dt);
}
z += w2 * dt;
t += dt;
if (z > highest) {
highest = z;
highestAt = t;
}
if (z <= 0) {
landed = true;
break;
}
}
let radius;
if (!landed && z >= cloud.base) radius = cloud.radius;
else {
const f = (z - first.height) / Math.max(cloud.base - first.height, 1);
radius = cloud.initialRadius + Math.min(Math.max(f, 0), 1) * (cloud.radius - cloud.initialRadius);
}
// As landingThrough, on flat ground.
const falls = [];
let lands = 1;
if (!landed) {
let height = z, above = z;
while (height > bottom) {
const speed = settlingSpeedAt(diameter, siteElevation + height);
const step = Math.min(FIELD_STEP, Math.max(speed * FIELD_SECONDS, FALL_STEP), height - bottom);
const middle = height - step / 2;
falls.push(middle, step / settlingSpeedAt(diameter, siteElevation + middle));
const nextAbove = height - step;
if (nextAbove <= 0) {
lands = above > 0 ? above / (above - nextAbove) : 0;
break;
}
height -= step;
above = nextAbove;
}
}
parcels.push({diameter, activity: activity * down / SUBDIVISIONS, radius, landed, highest, highestAt,
seconds: t, riseLevels: Int32Array.from(levels), riseSeconds: Float64Array.from(seconds),
fall: Float64Array.from(falls), lands});
}
}
if (PARCELS.size >= MOST_KEPT) PARCELS.clear();
PARCELS.set(key, parcels);
return parcels;
}
// landingSpots, on flat ground, in winds which hold through the hours (`winds.held`: one hour of a
// past day), with no rain. While the cloud rises the parcels are carried by the winds over ground
// zero (they go a few km at most); then each falls through the winds where it is.
function heldLandingSpots({yieldKt, burstHeight, siteElevation, maxHours, volumeShare, winds}) {
const parcels = heldParcels(yieldKt, burstHeight, siteElevation, volumeShare);
const maxSeconds = maxHours * 3600;
// The winds over ground zero, in the middle of each level, read as the parcels reach them.
let size = 0;
for (const p of parcels) for (const l of p.riseLevels) size = Math.max(size, l + 1);
const east = new Float64Array(size), north = new Float64Array(size), read = new Uint8Array(size);
const spots = [];
for (const p of parcels) {
let x = 0, y = 0;
const {riseLevels, riseSeconds} = p;
for (let i = 0; i < riseLevels.length; i++) {
const l = riseLevels[i];
if (!read[l]) {
[east[l], north[l]] = winds.at(0, 0, COLUMN_BOTTOM + (l + 0.5) * FALL_STEP, 0);
read[l] = 1;
}
x += east[l] * riseSeconds[i];
y += north[l] * riseSeconds[i];
}
let t = p.seconds, at = [x, y];
if (!p.landed) {
at = null;
for (let i = 0; i < p.fall.length; i += 2) {
const dt = p.fall[i + 1];
const [u, v] = winds.at(x, y, p.fall[i], t + dt / 2);
if (i + 2 >= p.fall.length) {
at = [x + p.lands * u * dt, y + p.lands * v * dt];
t += p.lands * dt;
break;
}
x += u * dt;
y += v * dt;
t += dt;
if (t > maxSeconds) break;
}
}
if (!at || t > maxSeconds) continue;
const falling = Math.max(t - p.highestAt, 1);
const sigma = landedSigma(p.radius / 2, p.highest, Math.max(p.highest, 1) / falling);
spots.push({x: at[0], y: at[1], sigma, diameter: p.diameter, highest: p.highest, activity: p.activity,
hours: t / 3600});
}
return spots;
}
// The share of a spot (center `mean`, `sigma`) which lands in each cell of a row of cells
// (`start`, `cell` wide); [first cell, shares].
function cellShares(mean, sigma, start, cell, count) {
const first = Math.max(0, Math.floor((mean - 4 * sigma - start) / cell));
const last = Math.min(count - 1, Math.floor((mean + 4 * sigma - start) / cell));
const shares = [];
let previous = erf((start + first * cell - mean) / (sigma * Math.SQRT2));
for (let i = first; i <= last; i++) {
const next = erf((start + (i + 1) * cell - mean) / (sigma * Math.SQRT2));
shares.push((next - previous) / 2);
previous = next;
}
return [first, shares];
}
// The cells of a grid around `spots`, as depositionGrid would make it (with the same options): {x0,
// y0 (m, the south-west corner), cell (m), nx, ny}.
export function gridFrame(spots, {yieldKt, fissionFraction = 1, normalization = SOURCE_NORMALIZATION,
maxCells = 1200, bounds = null, cellSize = null, boundsFloor = 0}) {
let west = Infinity, east = -Infinity, south = Infinity, north = -Infinity, narrowest = Infinity;
// The grid covers the spots which can raise the dose rate to `boundsFloor` (R/hr) by themselves:
// the faintest are carried thousands of km, and would stretch the grid past where anything is
// drawn (or past the poles). Spots outside it are left out.
const peak = (s) => s.activity * normalization * yieldKt * fissionFraction / (2 * Math.PI * (s.sigma / 1000) ** 2);
const counted = boundsFloor > 0 && spots.some((s) => peak(s) >= boundsFloor)
? spots.filter((s) => peak(s) >= boundsFloor) : spots;
for (const s of counted) {
west = Math.min(west, s.x - 3 * s.sigma);
east = Math.max(east, s.x + 3 * s.sigma);
south = Math.min(south, s.y - 3 * s.sigma);
north = Math.max(north, s.y + 3 * s.sigma);
narrowest = Math.min(narrowest, s.sigma);
}
// A grid over `bounds` ([west, south, east, north], m from ground zero) with cells `cellSize`
// wide, when given: a close look at part of the fallout.
if (bounds) [west, south, east, north] = bounds;
const span = Math.max(east - west, north - south);
const cell = cellSize || Math.max(span / maxCells, Math.min(narrowest / 2, 250), 25);
return {x0: west, y0: south, cell, nx: Math.ceil((east - west) / cell), ny: Math.ceil((north - south) / cell)};
}
// The dose rate at H+1 hour (R/hr, three feet above the ground) on a grid of square cells around
// the spots: {x0, y0 (m, the south-west corner), cell (m), nx, ny, values (row by row, from the
// south)}. `bounds` and `cellSize` give a closer look at part of it; `boundsFloor` keeps the grid to
// where the dose rate can reach it; `frame` (as gridFrame gives it) gives its cells.
export function depositionGrid(spots, options) {
const {yieldKt, fissionFraction = 1, normalization = SOURCE_NORMALIZATION} = options;
const frame = options.frame || gridFrame(spots, options);
const {x0: west, y0: south, cell, nx, ny} = frame;
const values = new Float64Array(nx * ny);
const cellKm2 = (cell / 1000) ** 2;
const perShare = normalization * yieldKt * fissionFraction / cellKm2;
for (const s of spots) {
const [ix, xs] = cellShares(s.x, s.sigma, west, cell, nx);
const [iy, ys] = cellShares(s.y, s.sigma, south, cell, ny);
const amount = s.activity * perShare;
for (let j = 0; j < ys.length; j++) {
const row = (iy + j) * nx + ix;
const a = amount * ys[j];
for (let i = 0; i < xs.length; i++) values[row + i] += a * xs[i];
}
}
return {x0: west, y0: south, cell, nx, ny, values};
}
// The finest cell (m) a burst's narrow spots are looked at on, and how many of them a coarse cell is
// split into across, at most.
const FINE_CELL = 250;
const MOST_SPLITS = 32;
// `grid` (as depositionGrid gives it, of `spots`), with the peaks of narrow spots kept.
//
// A grid over many bursts far apart has cells kilometers wide, and a cell's value is the average over
// it: the hot, narrow fallout close to a small burst's ground zero, hundreds of meters wide, would be
// averaged down into a lower band. So each burst's spots narrower than half a cell (spots of one
// `run`, as combineBursts gives them; all one run without it) are also put on a fine grid, and each
// cell gains the most any part of it is above the cell's average, by the burst which raises it most.
// The cell's average, which sums the bursts, is kept beneath.
export function sharpenGrid(grid, spots, options = {}) {
const extra = sharpening(grid, spots, options);
if (!extra) return grid;
const values = Float64Array.from(grid.values, (v, k) => v + extra[k]);
return {...grid, values};
}
// What sharpenGrid adds to each cell of a grid with the cells of `grid` (as gridFrame gives them),
// or null where it adds nothing: the most any burst of `spots` raises it.
export function sharpening(grid, spots, {yieldKt = 1, fissionFraction = 1, normalization = SOURCE_NORMALIZATION} = {}) {
const coarse = grid.cell;
const runs = new Map();
for (const s of spots) {
if (!(s.sigma < coarse / 2)) continue;
const run = s.run ?? 0;
if (!runs.has(run)) runs.set(run, []);
runs.get(run).push(s);
}
if (!runs.size) return null;
const extra = new Float64Array(grid.nx * grid.ny);
for (const narrow of runs.values()) {
const narrowest = Math.min(...narrow.map((s) => s.sigma));
const splits = Math.min(Math.ceil(coarse / Math.max(Math.min(narrowest / 2, FINE_CELL), 25)), MOST_SPLITS);
if (splits < 2) continue;
// The coarse cells the narrow spots reach.
let i0 = Infinity, i1 = -Infinity, j0 = Infinity, j1 = -Infinity;
for (const s of narrow) {
i0 = Math.min(i0, Math.floor((s.x - 3 * s.sigma - grid.x0) / coarse));
i1 = Math.max(i1, Math.floor((s.x + 3 * s.sigma - grid.x0) / coarse));
j0 = Math.min(j0, Math.floor((s.y - 3 * s.sigma - grid.y0) / coarse));
j1 = Math.max(j1, Math.floor((s.y + 3 * s.sigma - grid.y0) / coarse));
}
i0 = Math.max(i0, 0);
j0 = Math.max(j0, 0);
i1 = Math.min(i1, grid.nx - 1);
j1 = Math.min(j1, grid.ny - 1);
if (i1 < i0 || j1 < j0) continue;
const cols = i1 - i0 + 1, rows = j1 - j0 + 1;
const fine = depositionGrid(narrow, {
yieldKt, fissionFraction, normalization, cellSize: coarse / splits,
bounds: [grid.x0 + i0 * coarse, grid.y0 + j0 * coarse, grid.x0 + (i1 + 1) * coarse, grid.y0 + (j1 + 1) * coarse],
});
for (let j = 0; j < rows; j++) {
for (let i = 0; i < cols; i++) {
let most = 0, sum = 0;
for (let b = 0; b < splits; b++) {
const row = (j * splits + b) * fine.nx + i * splits;
if (j * splits + b >= fine.ny) break;
for (let a = 0; a < splits && i * splits + a < fine.nx; a++) {
const v = fine.values[row + a];
sum += v;
if (v > most) most = v;
}
}
const k = (j0 + j) * grid.nx + i0 + i;
const above = most - sum / (splits * splits);
if (above > extra[k]) extra[k] = above;
}
}
}
return extra;
}
// How much stronger (or weaker) fallout is `hours` after a burst than at H+1: the Way-Wigner
// t^-1.2 of fission products' decay [Glasstone and Dolan, 9.145], good from about half an hour to
// months.
export function decayFromH1(hours) {
return Math.pow(hours, -1.2);
}
// The earliest a spot is taken to land (hours): t^-1.2 is fitted from about half an hour, and
// grows without bound towards the burst.
const EARLIEST_ARRIVAL = 0.1;
// A grid like `like` (as depositionGrid gives it), of the spots landed by `hours`, each counted
// `weight(spot)` times its H+1 dose rate. Every hour's grid has `like`'s cells, so it is drawn in
// the same place.
function timedGrid(spots, like, hours, weight, options) {
const landed = [];
for (const s of spots) {
if (s.hours > hours) continue;
const w = weight(s);
if (w > 0) landed.push({...s, activity: s.activity * w});
}
let grid = depositionGrid(landed, {
...options, cellSize: like.cell,
bounds: [like.x0, like.y0, like.x0 + like.nx * like.cell, like.y0 + like.ny * like.cell],
});
// The same cells as `like`, though rounding may have made one more.
if (grid.nx !== like.nx || grid.ny !== like.ny) {
const values = new Float64Array(like.nx * like.ny);
for (let j = 0; j < like.ny; j++) {
for (let i = 0; i < like.nx; i++) values[j * like.nx + i] = grid.values[j * grid.nx + i] || 0;
}
grid = {...like, values};
}
return sharpenGrid(grid, landed, options);
}
// The dose rate (R/hr) `hours` after the bursts on a grid like `like` (of `spots`): only the
// fallout which has landed by then, as strong as it is then.
export function landedGrid(spots, like, hours, {yieldKt = 1, fissionFraction = 1, normalization = SOURCE_NORMALIZATION} = {}) {
const decay = decayFromH1(hours);
return timedGrid(spots, like, hours, () => decay, {yieldKt, fissionFraction, normalization});
}
// The dose (R) someone outdoors gets from fallout which has fallen at `arrival` hours, from then
// until `hours`, for each R/hr of its H+1 dose rate: the integral of t^-1.2, 5 (ta^-0.2 - t^-0.2).
export function doseFromH1(arrival, hours) {
const from = Math.max(arrival, EARLIEST_ARRIVAL);
return hours > from ? 5 * (Math.pow(from, -0.2) - Math.pow(hours, -0.2)) : 0;
}
// The total dose (R) by `hours` after the bursts, of someone outdoors everywhere on a grid like
// `like` (of `spots`), from when each spot's fallout landed there.
export function doseGrid(spots, like, hours, {yieldKt = 1, fissionFraction = 1, normalization = SOURCE_NORMALIZATION} = {}) {
return timedGrid(spots, like, hours, (s) => doseFromH1(s.hours, hours), {yieldKt, fissionFraction, normalization});
}
// The area (square miles) where the dose rate is at least each of `doseRates`.
export function contourAreas(grid, doseRates, scale = 1) {
const cellSqMi = (grid.cell / 1000) ** 2 / SQ_KM_PER_SQ_MI;
return doseRates.map((rate) => {
let n = 0;
for (const v of grid.values) if (v * scale >= rate) n++;
return n * cellSqMi;
});
}
// The grounded unit time reference dose rate, (R/hr) km^2 / kt, as [HPAC] measures it from
// contours: each place counts as the highest of `doseRates` it is above, times its area.
export function groundedUtrdr(grid, doseRates, yieldKt, scale = 1) {
const rates = [...doseRates].sort((a, b) => b - a);
const cellKm2 = (grid.cell / 1000) ** 2;
let sum = 0;
for (const v of grid.values) {
const r = v * scale;
for (const rate of rates) {
if (r >= rate) {
sum += rate;
break;
}
}
}
return sum * cellKm2 / yieldKt;
}
// The scale on the grid at which its grounded UTRDR is `target`.
export function scaleToUtrdr(grid, doseRates, yieldKt, target) {
let low = 1e-6, high = 1e6;
for (let i = 0; i < 60; i++) {
const mid = Math.sqrt(low * high);
if (groundedUtrdr(grid, doseRates, yieldKt, mid) < target) low = mid; else high = mid;
}
return Math.sqrt(low * high);
}
// How far (km) the furthest place where the dose rate is at least each of `doseRates` is from ground
// zero, and in which direction (degrees clockwise from north): the hotline length and azimuth.
export function hotlines(grid, doseRates, scale = 1) {
return doseRates.map((rate) => {
let far = -1, azimuth = null;
for (let j = 0; j < grid.ny; j++) {
for (let i = 0; i < grid.nx; i++) {
if (grid.values[j * grid.nx + i] * scale < rate) continue;
const x = grid.x0 + (i + 0.5) * grid.cell, y = grid.y0 + (j + 0.5) * grid.cell;
const d = Math.hypot(x, y);
if (d > far) {
far = d;
azimuth = (Math.atan2(x, y) * 180 / Math.PI + 360) % 360;
}
}
}
return far < 0 ? {km: 0, azimuth: null} : {km: far / 1000, azimuth};
});
}
// The direction (degrees clockwise from north) from ground zero to the middle of the activity
// where the dose rate is at least `rate`.
export function plumeBearing(grid, rate, scale = 1) {
let sx = 0, sy = 0;
for (let j = 0; j < grid.ny; j++) {
for (let i = 0; i < grid.nx; i++) {
const v = grid.values[j * grid.nx + i] * scale;
if (v < rate) continue;
sx += v * (grid.x0 + (i + 0.5) * grid.cell);
sy += v * (grid.y0 + (j + 0.5) * grid.cell);
}
}
return (Math.atan2(sx, sy) * 180 / Math.PI + 360) % 360;
}

View file

@ -0,0 +1,455 @@
import {airProperties, settlingSpeed} from './atmosphere.js';
import {
activityDown,
contourAreas,
decayFromH1,
depositionGrid,
doseFromH1,
doseGrid,
hotlines,
landedGrid,
landingSpots,
particleSizes,
plumeBearing,
risingCloud,
SOURCE_NORMALIZATION,
stabilizedCloud,
windAt,
} from './model.js';
import {meanError, runNearField, runShot} from './validation.js';
import data from './nts-shots.json';
import nearField from './near-field-shots.json';
import fm from './fm-3-11-3.json';
// A profile of one wind at every height, blowing toward `toward` degrees at `speed` m/s.
function steady(toward, speed) {
const r = toward * Math.PI / 180;
return [[0, speed * Math.sin(r), speed * Math.cos(r)]];
}
function run(profile, yieldKt = 10) {
const spots = landingSpots({yieldKt, profile});
return {spots, grid: depositionGrid(spots, {yieldKt})};
}
// The distance (km) from ground zero to the middle of the activity of `spots`.
function reach(spots) {
let sx = 0, sy = 0, sum = 0;
for (const s of spots) {
sx += s.activity * s.x;
sy += s.activity * s.y;
sum += s.activity;
}
return Math.hypot(sx / sum, sy / sum) / 1000;
}
function angleBetween(a, b) {
const d = Math.abs(a - b) % 360;
return d > 180 ? 360 - d : d;
}
describe('the air', () => {
test('is the standard atmosphere at sea level', () => {
const {density, viscosity} = airProperties(0);
expect(density).toBeCloseTo(1.225, 3);
expect(viscosity).toBeCloseTo(1.789e-5, 7);
});
test('a 100 um particle falls slower than Stokes speed, slowed by drag', () => {
// Stokes: 2600 * 9.81 * (1e-4)^2 / (18 * 1.789e-5) = 0.79 m/s, at which Re is 5.4: past
// Stokes flow, so drag holds it to about 0.57 m/s, as for 100 um quartz sand.
const speed = settlingSpeed(100e-6, 0);
expect(speed).toBeGreaterThan(0.5);
expect(speed).toBeLessThan(0.65);
});
test('larger particles fall faster, and all fall faster in thinner air', () => {
expect(settlingSpeed(300e-6, 0)).toBeGreaterThan(settlingSpeed(100e-6, 0));
expect(settlingSpeed(100e-6, 10000)).toBeGreaterThan(settlingSpeed(100e-6, 0));
});
});
describe('the cloud', () => {
test('stabilizes higher and wider for a larger yield', () => {
let previous = {base: 0, top: 0, radius: 0};
for (const yieldKt of [0.1, 1, 10, 100, 1000]) {
const cloud = stabilizedCloud(yieldKt);
expect(cloud.top).toBeGreaterThan(cloud.base);
expect(cloud.base).toBeGreaterThan(previous.base);
expect(cloud.top).toBeGreaterThan(previous.top);
expect(cloud.radius).toBeGreaterThan(previous.radius);
previous = cloud;
}
});
test('rises from the fireball to its stabilized height', () => {
const cloud = risingCloud(10);
expect(cloud.initialTop).toBeLessThan(cloud.base);
expect(cloud.initialRadius).toBeLessThan(cloud.radius);
// SIMFIC Table 1: 300 s for 1-10 kt, 280 s for 100 kt, 200 s for 1 Mt.
expect(risingCloud(1).stop).toBeCloseTo(300, 6);
expect(risingCloud(100).stop).toBeCloseTo(280, 6);
expect(risingCloud(1000).stop).toBeCloseTo(200, 6);
expect(risingCloud(10).start).toBeGreaterThan(0);
});
test('rises from as high as the burst was', () => {
const ground = risingCloud(15, 0), tower = risingCloud(15, 91);
expect(tower.initialBase - ground.initialBase).toBeCloseTo(91, 6);
expect(tower.top - ground.top).toBeCloseTo(91, 6);
});
test('carries its activity on particles averaging about DELFIC\'s nominal 229 um', () => {
const sizes = particleSizes();
const total = sizes.reduce((a, s) => a + s.activity, 0);
const mean = sizes.reduce((a, s) => a + s.activity * s.diameter, 0) / total;
expect(total).toBeLessThanOrEqual(1);
expect(total).toBeGreaterThan(0.95);
expect(mean * 1e6).toBeGreaterThan(229 * 0.9);
expect(mean * 1e6).toBeLessThan(229 * 1.1);
});
});
describe('the activity which comes down', () => {
test('is all of it for a burst on or under the ground', () => {
expect(activityDown(10, 0)).toBe(1);
expect(activityDown(10, -5)).toBe(1);
});
test('is less the higher the burst, by its height scaled to the yield', () => {
// George: 15 kt on a 300 ft tower, 121 ft/kt^(1/3): 0.45345^(121/65) = 0.23.
expect(activityDown(15, 300 * 0.3048)).toBeCloseTo(0.229, 2);
expect(activityDown(15, 200)).toBeLessThan(activityDown(15, 100));
expect(activityDown(1000, 100)).toBeGreaterThan(activityDown(1, 100));
});
});
describe('the winds', () => {
test('are read between the heights of the profile, and as the nearest beyond them', () => {
const profile = [[0, 0, 0], [1000, 10, -10]];
expect(windAt(profile, 500)).toEqual([5, -5]);
expect(windAt(profile, -10)).toEqual([0, 0]);
expect(windAt(profile, 5000)).toEqual([10, -10]);
});
});
describe('particles in the rising cloud', () => {
const cloud = risingCloud(10);
const {spots} = run(steady(90, 10));
const heavy = spots.filter((s) => s.diameter > 1e-3);
const light = spots.filter((s) => s.diameter > 60e-6 && s.diameter < 150e-6);
test('drop out low if they are heavy: the stem', () => {
expect(heavy.length).toBeGreaterThan(0);
expect(Math.max(...heavy.map((s) => s.highest))).toBeLessThan(cloud.base);
});
test('ride to the stabilized cloud if they are light', () => {
expect(Math.min(...light.map((s) => s.highest))).toBeGreaterThan(cloud.base * 0.9);
});
test('land near ground zero if heavy, far downwind if light', () => {
expect(reach(heavy)).toBeLessThan(reach(light) / 5);
});
});
describe('a burst in a steady wind', () => {
test('puts its plume downwind', () => {
for (const toward of [0, 90, 200, 300]) {
const {grid} = run(steady(toward, 10));
expect(angleBetween(plumeBearing(grid, 0.1), toward)).toBeLessThan(2);
}
});
test('carries it about twice as far in twice the wind', () => {
const ratio = reach(run(steady(90, 20)).spots) / reach(run(steady(90, 10)).spots);
expect(ratio).toBeGreaterThan(1.8);
expect(ratio).toBeLessThan(2.2);
});
test('spreads it evenly around ground zero in a calm', () => {
expect(reach(run(steady(0, 0)).spots)).toBeLessThan(0.01);
});
test('loses none of the activity which lands', () => {
const yieldKt = 10;
const {spots, grid} = run(steady(45, 15), yieldKt);
const landed = spots.reduce((a, s) => a + s.activity, 0);
const total = grid.values.reduce((a, v) => a + v, 0) * (grid.cell / 1000) ** 2;
expect(total / (SOURCE_NORMALIZATION * yieldKt * landed)).toBeCloseTo(1, 2);
});
test('puts down less of it, the higher the burst', () => {
const share = (burstHeight) => landingSpots({yieldKt: 10, burstHeight, profile: steady(90, 10)})
.reduce((a, s) => a + s.activity, 0);
expect(share(100)).toBeLessThan(share(0) * 0.5);
});
test('measures how far downwind each contour reaches, and in which direction', () => {
const {spots} = run(steady(90, 10));
const grid = depositionGrid(spots, {yieldKt: 10, bounds: [-50000, -50000, 150000, 50000], cellSize: 250});
// Contours which end inside the grid: one cut off by its edge reaches only as far as that.
const [high, low] = hotlines(grid, [100, 10]);
expect(low.km).toBeGreaterThan(high.km);
expect(low.km).toBeLessThan(140);
expect(angleBetween(low.azimuth, 90)).toBeLessThan(3);
expect(hotlines(grid, [1e9])[0]).toEqual({km: 0, azimuth: null});
});
test('draws a smaller area at a higher dose rate', () => {
const [high, low] = contourAreas(run(steady(90, 10)).grid, [10, 1]);
expect(high).toBeGreaterThan(0);
expect(low).toBeGreaterThan(high);
});
test('covers only where the dose rate can reach a floor, when given one', () => {
const {spots} = run(steady(90, 30));
const all = depositionGrid(spots, {yieldKt: 10});
const kept = depositionGrid(spots, {yieldKt: 10, boundsFloor: 0.01});
expect(kept.nx * kept.cell).toBeLessThan(all.nx * all.cell);
// What shows (0.1 R/hr and up) is all inside the smaller grid.
const [shown, shownAll] = [contourAreas(kept, [0.1])[0], contourAreas(all, [0.1])[0]];
expect(Math.abs(shown / shownAll - 1)).toBeLessThan(0.02);
});
test('of a megaton, draws a 1000 R/hr contour near ground zero', () => {
const spots = landingSpots({yieldKt: 1000, profile: steady(90, 6.7)});
const grid = depositionGrid(spots, {yieldKt: 1000, bounds: [-30000, -30000, 120000, 30000], cellSize: 250});
expect(contourAreas(grid, [1000])[0]).toBeGreaterThan(10);
});
});
describe('a burst in winds which turn with height', () => {
test('puts its plume between them, toward the winds the activity fell through', () => {
const top = stabilizedCloud(10).top;
const bearing = plumeBearing(run([[0, 15, 0], [top, 0, 15]]).grid, 0.1);
expect(bearing).toBeGreaterThan(10);
expect(bearing).toBeLessThan(80);
});
test('puts the plume of a higher cloud further toward the winds higher up', () => {
const winds = [[0, 15, 0], [20000, 0, 15]];
const low = plumeBearing(run(winds, 1).grid, 0.1);
const high = plumeBearing(run(winds, 1000).grid, 0.1);
expect(low - high).toBeGreaterThan(10);
});
});
// Close-in fallout measured after three Nevada surface bursts (near-field-shots.json): contours of
// 35 to 1000 R/hr within a few km of ground zero. These hold the model to what was measured; a
// change which makes it worse should fail here.
describe('the close-in fallout of three surface bursts', () => {
const results = Object.fromEntries(nearField.shots.map((shot) => [shot.name, runNearField(shot)]));
test('of Jangle Sugar and Small Boy, is matched within about a factor of two to three', () => {
// Measured: Sugar 2.36 in area, 1.69 in hotline length (DELFIC 1.40/1.43, WSEG-10
// 2.14/1.64); Small Boy 1.99/1.42 (DELFIC 2.92/1.96).
for (const name of ['Jangle Sugar', 'Small Boy']) {
expect(results[name].area.error).toBeLessThan(2.6);
expect(results[name].hotline.error).toBeLessThan(1.9);
}
});
test('of Johnie Boy, is within a factor of four below its crater', () => {
// Its 1000 R/hr contour (0.28 km^2) is debris thrown out of the crater, which no model
// here has; DELFIC drew it 10 times too small, and this model draws none. The 100 and 50
// R/hr contours were measured 3.7 and 3.8 times too big.
const r = results['Johnie Boy'];
const observed = nearField.shots.find((s) => s.name === 'Johnie Boy').contours.observed.area_km2;
for (const i of [1, 2]) {
expect(r.area.values[i] / observed[i]).toBeLessThan(4.2);
expect(r.area.values[i] / observed[i]).toBeGreaterThan(1);
}
});
test('lies in the direction measured', () => {
// Measured: within 9 degrees for every contour but Small Boy's two highest (47 and 29).
for (const r of Object.values(results)) {
const shot = nearField.shots.find((s) => s.name === r.name);
r.azimuth.forEach((azimuth, i) => {
if (azimuth === null || shot.contours.rates[i] >= 500) return;
expect(angleBetween(azimuth, shot.contours.observed.azimuth[i])).toBeLessThan(12);
});
}
});
});
// Six Nevada tests (nts-shots.json), measured out to hundreds of km.
describe('the fallout measured after six Nevada tests', () => {
const results = data.shots.map((shot) => [shot, runShot(shot)]);
test('is matched within about a factor of two in area, given the amount of activity which landed', () => {
// Measured 1.92. HPAC 4.03 and 4.04 were off by 2.61 and 3.27 on the same contours, though
// they were not given the amount which landed.
const error = meanError(results.map(([, r]) => r), (r) => r.transport);
expect(error).toBeLessThan(2.1);
});
test('is over-predicted a priori by a factor of about four', () => {
// Measured 4.18 (George 4.8, Ess 5.0, Zucchini 7.9, Priscilla 3.9, Smoky 1.9, Johnie Boy 3.8),
// every shot too high. Without SIMFIC's height-of-burst factor it was 8.9.
const error = meanError(results.map(([, r]) => r), (r) => r.apriori);
expect(error).toBeLessThan(4.6);
for (const [, r] of results) expect(r.apriori.bias).toBeGreaterThan(1);
});
test('is downwind on the bearing the winds aloft give, for most of the shots', () => {
// Measured: within 8 degrees for four, 43 (Ess) and 24 (Johnie Boy) for the others. The wind
// is one sounding at H-hour, which is not the wind the plume met hours later and 100 miles
// away.
const misses = results.map(([shot, r]) => angleBetween(r.transport.bearing, shot.observed_bearing_deg));
misses.sort((a, b) => a - b);
expect(misses[3]).toBeLessThan(10);
expect(misses[5]).toBeLessThan(50);
});
});
describe('fallout hour by hour', () => {
const spots = landingSpots({yieldKt: 10, profile: steady(90, 10)});
const all = depositionGrid(spots, {yieldKt: 10, boundsFloor: 0.1});
const sum = (grid) => grid.values.reduce((a, v) => a + v, 0);
test('decays as t^-1.2 from H+1', () => {
expect(decayFromH1(1)).toBe(1);
// The 7-10 rule: seven times later, about a tenth.
expect(decayFromH1(7)).toBeCloseTo(0.097, 3);
});
test('shows only what has landed, on the same cells, as strong as it is then', () => {
const early = landedGrid(spots, all, 1, {yieldKt: 10});
const late = landedGrid(spots, all, 48, {yieldKt: 10});
for (const grid of [early, late]) {
expect([grid.x0, grid.y0, grid.cell, grid.nx, grid.ny]).toEqual([all.x0, all.y0, all.cell, all.nx, all.ny]);
}
// By an hour, the fallout close in has landed, and not the far: less than all of it.
const landedSoon = spots.filter((s) => s.hours <= 1).reduce((a, s) => a + s.activity, 0);
const landed = spots.reduce((a, s) => a + s.activity, 0);
expect(landedSoon / landed).toBeGreaterThan(0.2);
expect(landedSoon / landed).toBeLessThan(0.95);
// The far end of the plume is still empty an hour in.
const far = (grid) => {
let v = 0;
for (let j = 0; j < grid.ny; j++) v += grid.values[j * grid.nx + grid.nx - 3];
return v;
};
expect(far(all)).toBeGreaterThan(0);
expect(far(early)).toBe(0);
// Two days in, everything that lands is down, at 48^-1.2 of its H+1 rate (sharpening only adds).
expect(sum(late)).toBeGreaterThanOrEqual(sum(all) * decayFromH1(48) * 0.999);
expect(sum(late)).toBeLessThan(sum(all) * decayFromH1(48) * 1.2);
});
});
describe('the total dose, outdoors', () => {
const spots = landingSpots({yieldKt: 10, profile: steady(90, 10)});
const all = depositionGrid(spots, {yieldKt: 10, boundsFloor: 0.1});
const sum = (grid) => grid.values.reduce((a, v) => a + v, 0);
test('adds up t^-1.2 from when the fallout lands', () => {
// Landed at H+1, forever: 5 times the H+1 rate.
expect(doseFromH1(1, Infinity)).toBeCloseTo(5, 10);
// From H+1 to H+7: 5 (1 - 7^-0.2).
expect(doseFromH1(1, 7)).toBeCloseTo(1.612, 3);
// Not yet landed: nothing.
expect(doseFromH1(8, 7)).toBe(0);
// Very early fallout is counted from 6 minutes.
expect(doseFromH1(0.001, 1)).toBeCloseTo(doseFromH1(0.1, 1), 10);
});
test('is the dose rate of each spot, from when it lands, on the same cells', () => {
const hours = 12;
const grid = doseGrid(spots, all, hours, {yieldKt: 10});
expect([grid.x0, grid.y0, grid.cell, grid.nx, grid.ny]).toEqual([all.x0, all.y0, all.cell, all.nx, all.ny]);
// On a grid of the H+1 rates, each spot weighted by its dose by then (sharpening only adds).
const weighted = spots.filter((s) => s.hours <= hours)
.map((s) => ({...s, activity: s.activity * doseFromH1(s.hours, hours)}));
const expected = sum(depositionGrid(weighted, {
yieldKt: 10, cellSize: all.cell, bounds: [all.x0, all.y0, all.x0 + all.nx * all.cell, all.y0 + all.ny * all.cell],
}));
expect(sum(grid)).toBeGreaterThanOrEqual(expected * 0.999);
expect(sum(grid)).toBeLessThan(expected * 1.2);
// More by two weeks than by half a day, and close in, more than the H+1 rate.
const later = doseGrid(spots, all, 336, {yieldKt: 10});
expect(sum(later)).toBeGreaterThan(sum(grid));
const most = (grid) => grid.values.reduce((a, v) => Math.max(a, v), 0);
expect(most(later)).toBeGreaterThan(most(all));
});
});
// Worked problems of the Army's manual, FM 3-3-1 Nuclear Contamination Avoidance (1994), with
// standard decay (n = 1.2). Its nomograms are read by eye, to a few percent.
describe('the decay and dose of FM 3-3-1', () => {
test('a reading at H+5 is normalized to H+1 (Appendix F, Situation 1)', () => {
// 100 cGy/h at H+5 was 690 cGy/h at H+1.
expect(100 / decayFromH1(5)).toBeCloseTo(689.86, 1);
});
test('a stay from H+5 to H+8 under an H+1 rate of 400 (Chapter 6, overlapping fallout, Problem 2)', () => {
// The nomogram gives 125 cGy.
expect(400 * doseFromH1(5, 8)).toBeGreaterThan(125 * 0.95);
expect(400 * doseFromH1(5, 8)).toBeLessThan(125 * 1.05);
});
test('crossing fallout from H+3 for half an hour at an average H+1 rate of 100 (Chapter 6)', () => {
// 12 cGy.
expect(100 * doseFromH1(3, 3.5)).toBeGreaterThan(12 * 0.95);
expect(100 * doseFromH1(3, 3.5)).toBeLessThan(12 * 1.05);
});
});
// The Army's planning figures, FM 3-11.3 Appendix G (2006): what the model should roughly agree with
// from a kiloton to megatons, the yields of modern weapons, which the test shots above do not reach.
describe('the cloud and Zone I of FM 3-11.3', () => {
test('the stabilized cloud top is within about 10% from 1 kt to 10 Mt', () => {
for (const [kt, top] of fm.cloud.rows) {
const ratio = stabilizedCloud(kt).top / 1000 / top;
expect(ratio).toBeGreaterThan(0.88);
expect(ratio).toBeLessThan(1.1);
}
});
test('the cloud bottom is within about 25%, and the radius is narrower, up to a third', () => {
for (const [kt, , bottom, radius] of fm.cloud.rows) {
const c = stabilizedCloud(kt);
expect(c.base / 1000 / bottom).toBeGreaterThan(0.74);
expect(c.base / 1000 / bottom).toBeLessThan(1.12);
expect(c.radius / 1000 / radius).toBeGreaterThan(0.6);
expect(c.radius / 1000 / radius).toBeLessThan(1.0);
}
});
// The Zone I downwind distance of the nomogram, as its scales were read.
function fmZone1(kt, kmh) {
const {wind_kmh: w, yield_kt: y, distance_km: d} = fm.zone1;
const row = (s, v) => s.a - s.b * Math.log10(v / s.c);
const f = (d.x - w.x) / (y.x - w.x);
return d.c * Math.pow(10, (d.a - (row(w, kmh) + f * (row(y, kt) - row(w, kmh)))) / d.b);
}
// The model's: the furthest downwind someone outdoors gets 125 cGy (as R) in 4 hours from arrival.
function ourZone1(kt, kmh) {
const spots = landingSpots({yieldKt: kt, profile: [[0, kmh / 3.6, 0]]})
.map((s) => ({...s, activity: s.activity * doseFromH1(s.hours, s.hours + 4)}));
const grid = depositionGrid(spots, {yieldKt: kt});
let far = 0;
for (let j = 0; j < grid.ny; j++) {
for (let i = 0; i < grid.nx; i++) {
if (grid.values[j * grid.nx + i] >= 125) far = Math.max(far, grid.x0 + (i + 1) * grid.cell);
}
}
return far / 1000;
}
test('the nomogram is read as the manual reads it', () => {
for (const [kt, kmh, km] of fm.zone1.examples) expect(Math.abs(fmZone1(kt, kmh) / km - 1)).toBeLessThan(0.03);
});
test('Zone I reaches about as far, from 10 kt to 1 Mt', () => {
for (const [kt, kmh] of [[10, 32], [50, 9], [100, 30], [300, 32], [1000, 32]]) {
const ratio = ourZone1(kt, kmh) / fmZone1(kt, kmh);
expect(ratio).toBeGreaterThan(0.7);
expect(ratio).toBeLessThan(1.7);
}
});
});

View file

@ -0,0 +1,90 @@
{
"_sources": {
"contours": "DNAF-1: An Analytical Fallout Prediction Model and Code, DNA 6299F (1981), DTIC ADA130291, Table 3 (observed and predicted fallout pattern statistics) and Table 2 (test shot data). Areas in km^2 inside each H+1 hour exposure-rate contour (R/hr), hotline length (km: the furthest distance from ground zero on the contour) and azimuth (degrees clockwise from north to that furthest point), as observed and as predicted by DNAF-1, DELFIC and WSEG-10.",
"shots": "Compilation of Local Fallout Data from Test Detonations 1945-1962 Extracted from DASA 1251, Volume I (DNA 1251-1-EX, 1979), DTIC ADA079309: shot data pages and wind tables (Buster-Jangle Sugar: Table 12, H-hour; Sunbeam Small Boy: Table 109, H+5 minutes; Sunbeam Johnie Boy: Table 108, H-hour)."
},
"_notes": [
"These are the bursts nearest the ground with well-measured close-in fallout: Sugar was a surface burst 3.5 ft up, Small Boy on a 10 ft tower, Johnie Boy 23 inches underground. All three are within the fireball-on-the-ground case the map models.",
"Altitudes are feet above mean sea level, speeds statute miles per hour, directions the wind blows FROM. Rows the tables leave blank are left out.",
"Fission yields: Sugar and Johnie Boy as DNAF-1 Table 2 gives them (all fission). Small Boy's yield is classified in both sources ('low'); 1.65 kt is its later declassified yield, and it is taken to be all fission, as the other two are.",
"Small Boy's longitude is printed as 115 deg 55' 89.2\", which cannot be; it is read as 115 deg 56' 29.2\" (Frenchman Flat).",
"DNAF-1 gives no WSEG-10 prediction for Small Boy."
],
"shots": [
{
"name": "Jangle Sugar",
"date": "1951-11-19T17:00Z",
"yield_kt": 1.2,
"fission_kt": 1.2,
"burst_height_ft": 3.5,
"placement": "surface",
"site_elevation_ft": 4215,
"lat": 37.13167,
"lon": -116.03861,
"cloud_top_ft_msl": 15000,
"cloud_bottom_ft_msl": 11000,
"wind": [
[4215, 190, 2], [6000, 170, 15], [8000, 180, 30], [10000, 200, 37], [12000, 200, 42],
[14000, 210, 46], [16000, 210, 51], [18000, 200, 72], [20000, 200, 62], [25000, 210, 71],
[30000, 210, 80], [35000, 210, 90]
],
"contours": {
"rates": [500, 300, 100, 35],
"observed": {"area_km2": [0.117, 0.386, 1.44, 3.11], "hotline_km": [0.69, 1.50, 3.74, 5.06], "azimuth": [342, 346, 1, 6]},
"dnaf1": {"area_km2": [0.390, 0.821, 2.64, 6.99], "hotline_km": [1.64, 2.49, 4.97, 9.07], "azimuth": [15, 15, 15, 15]},
"delfic": {"area_km2": [0.144, 0.316, 2.24, 5.08], "hotline_km": [1.00, 1.23, 5.87, 7.68], "azimuth": [353, 354, 355, 355]},
"wseg10": {"area_km2": [null, null, 0.55, 5.45], "hotline_km": [null, null, 2.8, 10.2], "azimuth": [null, null, 10, 10]}
}
},
{
"name": "Small Boy",
"date": "1962-07-14T18:30Z",
"yield_kt": 1.65,
"fission_kt": 1.65,
"burst_height_ft": 10,
"placement": "tower",
"site_elevation_ft": 3078,
"lat": 36.80250,
"lon": -115.94144,
"cloud_top_ft_msl": 19000,
"cloud_bottom_ft_msl": null,
"wind": [
[3078, 135, 2.3], [4000, 300, 1.2], [5000, 310, 1.2], [6000, 330, 2.3], [7000, 280, 2.3],
[8000, 250, 6.9], [9000, 240, 13.8], [10000, 240, 18.4], [12000, 240, 9.2], [14000, 240, 9.2],
[16000, 240, 9.2], [18000, 280, 16.1], [20000, 280, 28.8]
],
"contours": {
"rates": [1000, 500, 200, 100, 50],
"observed": {"area_km2": [0.216, 0.528, 0.942, 3.75, 9.03], "hotline_km": [1.00, 1.62, 2.22, 5.66, 8.10], "azimuth": [71, 73, 72, 72, 75]},
"dnaf1": {"area_km2": [0.302, 0.703, 1.75, 3.35, 6.45], "hotline_km": [0.92, 1.49, 2.62, 3.90, 5.69], "azimuth": [64, 64, 64, 64, 64]},
"delfic": {"area_km2": [0.047, 0.135, 0.564, 1.10, 4.38], "hotline_km": [0.25, 0.56, 1.69, 3.72, 6.47], "azimuth": [66, 80, 73, 74, 72]}
}
},
{
"name": "Johnie Boy",
"date": "1962-07-11T16:45Z",
"yield_kt": 0.5,
"fission_kt": 0.5,
"burst_height_ft": -1.9,
"placement": "subsurface",
"site_elevation_ft": 5153,
"lat": 37.12250,
"lon": -116.33304,
"cloud_top_ft_msl": 17000,
"cloud_bottom_ft_msl": 12500,
"wind": [
[5153, 195, 8.1], [6000, 170, 8.1], [7000, 160, 8.1], [8000, 160, 12.7], [9000, 160, 18.4],
[10000, 170, 17.3], [11000, 180, 13.8], [12000, 180, 17.3], [13000, 190, 20.0], [14000, 200, 24.2],
[15000, 200, 25.3], [16000, 200, 25.3], [17000, 200, 31.1], [18000, 200, 31.1], [19000, 210, 29.9],
[20000, 200, 26.5]
],
"contours": {
"rates": [1000, 100, 50],
"observed": {"area_km2": [0.278, 0.539, 1.27], "hotline_km": [1.38, 2.73, 4.10], "azimuth": [359, 345, 343]},
"dnaf1": {"area_km2": [0.038, 1.00, 1.90], "hotline_km": [0.38, 2.18, 3.21], "azimuth": [351, 351, 351]},
"delfic": {"area_km2": [0.029, 0.77, 1.79], "hotline_km": [0.032, 2.58, 4.13], "azimuth": [0, 344, 343]},
"wseg10": {"area_km2": [null, 1.17, 4.57], "hotline_km": [null, 3.7, 8.9], "azimuth": [null, 344, 344]}
}
}
]
}

View file

@ -0,0 +1,207 @@
{
"_sources": {
"shots": "Compilation of Local Fallout Data from Test Detonations 1945-1962 Extracted from DASA 1251, Volume I - Continental U.S. Tests (DNA 1251-1-EX, 1979), DTIC ADA079309. Shot data pages and wind data tables, transcribed from the scan.",
"areas": "A Comparison of Hazard Prediction and Assessment Capability (HPAC) Software Dose-Rate Contour Plots to a Sample of Local Fallout Data From Test Detonations in the Continental United States, 1945-1962 (AFIT thesis, 2005), DTIC ADA438146. Tables 4, 7, 10, 13, 16, 19: contour areas in square miles, at H+1 hour, 3 ft above the ground, of the observed (DASA-EX) patterns and of HPAC 4.03 and 4.04's predictions; grounded unit time reference dose rate in (R/hr)(km^2)/kt."
},
"_notes": [
"Altitudes are feet above mean sea level, speeds are statute miles per hour, directions are degrees the wind blows FROM, as the tables give them. 'Calm' is written as speed 0.",
"An observed area is left out (null) where it is smaller than the area of a higher dose rate: a lower contour must contain a higher one, so the survey did not close it (George 0.008, Zucchini 0.008, Smoky 1 and 0.1).",
"observed_bearing_deg is read by eye off the off-site pattern (the direction from ground zero to the middle of the plume, out to about 60 miles), good to about 10 degrees; Johnie Boy's figure has no legible axis labels, so its bearing is good to about 20.",
"Each shot's wind table is the one nearest H-hour: George, Ess, Zucchini, Smoky, Johnie Boy at H-hour; Priscilla at H+1 hour (the first it gives)."
],
"shots": [
{
"name": "George",
"lat": 37.04806,
"lon": -116.02111,
"observed_bearing_deg": 3,
"observed_bearing_figure": "Figure 62",
"operation": "Tumbler-Snapper",
"date": "1952-06-01T11:55Z",
"yield_kt": 15,
"burst_height_ft": 300,
"placement": "tower",
"site_elevation_ft": 4028,
"cloud_top_ft_msl": 37000,
"cloud_bottom_ft_msl": null,
"wind_table": "Table 20, H-hour",
"wind": [
[4028, 0, 0], [5000, 0, 0], [6000, 170, 20], [7000, 170, 21], [8000, 170, 20],
[9000, 160, 20], [10000, 160, 17], [12000, 180, 20], [14000, 180, 30], [15000, 170, 30],
[16000, 170, 33], [18000, 190, 35], [20000, 190, 51], [25000, 200, 48], [30000, 190, 41]
],
"areas_sq_mi": {
"dose_rates": [2, 0.8, 0.2, 0.08, 0.02, 0.008],
"observed": [62.6, 246.7, 810.8, 1278.6, 5122.2, null],
"hpac_4_03": [266.3, 256.5, 1317.2, 2681.7, 2995.7, 2030.6],
"hpac_4_04": [120.2, 74.4, 353.1, 1269.5, 3497.5, 1546.8]
},
"grounded_utrdr": {"observed": 122.3, "hpac_4_03": 223.0, "hpac_4_04": 95.7}
},
{
"name": "Ess",
"lat": 37.16833,
"lon": -116.04389,
"observed_bearing_deg": 110,
"observed_bearing_figure": "Figure 135",
"operation": "Teapot",
"date": "1955-03-23T20:30Z",
"yield_kt": 1,
"burst_height_ft": -67,
"placement": "subsurface",
"site_elevation_ft": 4288,
"cloud_top_ft_msl": 12000,
"cloud_bottom_ft_msl": null,
"wind_table": "Table 39, H-hour",
"wind": [
[4288, 310, 12], [5000, 310, 14], [6000, 310, 17], [7000, 320, 17], [8000, 320, 18],
[9000, 330, 23], [10000, 340, 29], [11000, 350, 26], [12000, 360, 29], [13000, 340, 26],
[14000, 330, 29], [15000, 330, 36], [16000, 310, 39], [17000, 300, 40], [18000, 290, 41],
[19000, 290, 40], [20000, 290, 43], [21000, 290, 43], [22000, 290, 46], [23000, 290, 50],
[24000, 290, 55], [25000, 290, 54], [30000, 290, 66], [35000, 300, 59]
],
"areas_sq_mi": {
"dose_rates": [2, 0.8, 0.2, 0.08, 0.02, 0.008],
"observed": [22.2, 52.9, 276.5, 382.8, 1548.7, 1557.6],
"hpac_4_03": [58.4, 58.2, 346.5, 606.6, 1794.7, 2038.5],
"hpac_4_04": [76.5, 48.7, 303.2, 485.3, 1341.5, 1335.5]
},
"grounded_utrdr": {"observed": 559.4, "hpac_4_03": 862.9, "hpac_4_04": 851.7}
},
{
"name": "Zucchini",
"lat": 37.09472,
"lon": -116.02389,
"observed_bearing_deg": 95,
"observed_bearing_figure": "Figure 160",
"operation": "Teapot",
"date": "1955-05-15T12:00Z",
"yield_kt": 28,
"burst_height_ft": 500,
"placement": "tower",
"site_elevation_ft": 4245,
"cloud_top_ft_msl": 40000,
"cloud_bottom_ft_msl": 25200,
"wind_table": "Table 46, H-hour",
"wind": [
[4245, 320, 7], [5000, 330, 14], [6000, 340, 13], [7000, 340, 8], [8000, 340, 7],
[9000, 330, 9], [10000, 310, 13], [11000, 300, 17], [12000, 310, 25], [13000, 310, 29],
[14000, 310, 35], [15000, 310, 40], [16000, 310, 45], [17000, 300, 48], [18000, 300, 49],
[19000, 290, 46], [20000, 290, 46], [21000, 290, 49], [22000, 280, 59], [23000, 270, 59],
[24000, 270, 63], [25000, 260, 69], [26000, 260, 74], [27000, 260, 77], [28000, 260, 82],
[29000, 270, 83], [30000, 270, 83], [31000, 270, 82], [32000, 260, 80], [33000, 260, 77],
[34000, 260, 75], [35000, 250, 74], [36000, 250, 74], [37000, 250, 76], [38000, 250, 79],
[39000, 260, 80], [40000, 260, 78], [41000, 260, 72], [42000, 260, 63], [43000, 260, 67],
[44000, 260, 41], [45000, 250, 39], [46000, 240, 41], [47000, 230, 46], [48000, 240, 45],
[49000, 250, 40], [50000, 250, 31]
],
"areas_sq_mi": {
"dose_rates": [2, 0.8, 0.2, 0.08, 0.02, 0.008],
"observed": [38.3, 88.5, 925.5, 1284.0, 3667.7, null],
"hpac_4_03": [203.3, 493.7, 1572.7, 2483.9, 12022.9, 14416.9],
"hpac_4_04": [58.0, 66.2, 469.2, 559.6, 3627.1, 12535.8]
},
"grounded_utrdr": {"observed": 48.8, "hpac_4_03": 154.5, "hpac_4_04": 44.4}
},
{
"name": "Priscilla",
"lat": 36.79806,
"lon": -115.92889,
"observed_bearing_deg": 67,
"observed_bearing_figure": "Figure 179",
"operation": "Plumbbob",
"date": "1957-06-24T13:30Z",
"yield_kt": 37,
"burst_height_ft": 700,
"placement": "balloon",
"site_elevation_ft": 3076,
"cloud_top_ft_msl": 43000,
"cloud_bottom_ft_msl": 24000,
"wind_table": "Table 51, H+1 hour",
"wind": [
[3076, 0, 0], [4000, 0, 0], [5000, 220, 3], [6000, 220, 7], [7000, 220, 7],
[8000, 230, 9], [9000, 240, 9], [10000, 230, 9], [11000, 230, 7], [12000, 230, 8],
[13000, 210, 9], [14000, 210, 8], [15000, 220, 7], [16000, 240, 8], [17000, 260, 12],
[18000, 250, 13], [20000, 260, 9], [21000, 250, 6], [22000, 230, 5], [23000, 240, 5],
[24000, 250, 8], [25000, 250, 9], [26000, 250, 10], [27000, 250, 16], [28000, 250, 17],
[29000, 250, 20], [30000, 250, 20], [31000, 250, 18], [32000, 260, 16], [33000, 280, 12],
[34000, 260, 15], [35000, 240, 15], [36000, 240, 20], [37000, 240, 23], [38000, 240, 26],
[39000, 240, 32], [40000, 250, 41], [41000, 260, 46], [42000, 260, 49], [43000, 260, 51],
[44000, 250, 51], [45000, 250, 52], [46000, 260, 51], [47000, 260, 48], [48000, 260, 46],
[49000, 260, 45], [50000, 270, 40], [51000, 270, 29], [52000, 270, 29], [53000, 270, 29],
[54655, 270, 29]
],
"areas_sq_mi": {
"dose_rates": [10, 0.2, 0.1, 0.02],
"observed": [76.1, 346.8, 587.0, 4210.4],
"hpac_4_03": [2.2, 243.1, 178.9, 1261.4],
"hpac_4_04": [3.6, 74.0, 35.1, 331.9]
},
"grounded_utrdr": {"observed": 168.1, "hpac_4_03": 19.6, "hpac_4_04": 10.5}
},
{
"name": "Smoky",
"lat": 37.18722,
"lon": -116.06778,
"observed_bearing_deg": 100,
"observed_bearing_figure": "Figure 207",
"operation": "Plumbbob",
"date": "1957-08-31T12:30Z",
"yield_kt": 44,
"burst_height_ft": 700,
"placement": "tower",
"site_elevation_ft": 4479,
"cloud_top_ft_msl": 38000,
"cloud_bottom_ft_msl": null,
"wind_table": "Table 61, H-hour",
"wind": [
[4479, 0, 0], [5000, 0, 0], [5179, 0, 0], [6000, 340, 6], [7000, 10, 7],
[8000, 10, 7], [9000, 10, 10], [10000, 360, 12], [11000, 360, 9], [12000, 360, 7],
[13000, 360, 7], [14000, 20, 7], [15000, 340, 9], [16000, 290, 13], [17000, 280, 18],
[18000, 290, 22], [19000, 290, 21], [20000, 280, 24], [21000, 280, 29], [22000, 280, 29],
[23000, 280, 30], [24000, 270, 35], [25000, 270, 36], [26000, 280, 36], [27000, 270, 33],
[28000, 270, 31], [29000, 280, 36], [30000, 280, 37], [31000, 280, 33], [32000, 280, 36],
[33000, 270, 38], [34000, 270, 37], [35000, 270, 37], [36000, 270, 40], [37000, 270, 44],
[38000, 270, 43], [39000, 270, 39], [40000, 270, 35], [41000, 270, 32], [42000, 270, 36],
[43000, 260, 38], [44000, 250, 35], [45000, 250, 38], [46000, 230, 45], [47000, 250, 40],
[48000, 260, 36], [49000, 250, 35], [50000, 240, 31]
],
"areas_sq_mi": {
"dose_rates": [20, 10, 2, 1, 0.2, 0.1, 0.02],
"observed": [18.5, 77.0, 419.9, null, 2199.5, null, 4383.4],
"hpac_4_03": [4.3, 8.8, 65.2, 85.3, 504.0, 592.3, 4966.6],
"hpac_4_04": [4.8, 2.2, 15.7, 25.9, 127.4, 137.6, 1905.3]
},
"grounded_utrdr": {"observed": 163.1, "hpac_4_03": 38.2, "hpac_4_04": 14.8}
},
{
"name": "Johnie Boy",
"lat": 37.12250,
"lon": -116.33304,
"observed_bearing_deg": 15,
"observed_bearing_figure": "Figure 327",
"operation": "Sunbeam",
"date": "1962-07-11T16:45Z",
"yield_kt": 0.5,
"burst_height_ft": -2,
"placement": "subsurface",
"site_elevation_ft": 5153,
"cloud_top_ft_msl": 17000,
"cloud_bottom_ft_msl": 12500,
"wind_table": "Table 108, H-hour",
"wind": [
[5153, 195, 8.1], [6000, 170, 8.1], [7000, 160, 8.1], [8000, 160, 12.7], [9000, 160, 18.4],
[10000, 170, 17.3], [11000, 180, 13.8], [12000, 180, 17.3], [13000, 190, 20.0], [14000, 200, 24.2],
[15000, 200, 25.3], [16000, 200, 25.3], [17000, 200, 31.1], [18000, 200, 31.1], [19000, 210, 29.9],
[20000, 200, 26.5]
],
"areas_sq_mi": {
"dose_rates": [10, 1, 0.5, 0.1, 0.05, 0.01],
"observed": [7.4, 25.9, 72.7, 175.2, 208.0, 641.6],
"hpac_4_03": [7.1, 29.8, 50.1, 432.9, 463.4, 2482.7],
"hpac_4_04": [13.3, 84.6, 47.1, 341.9, 500.7, 2671.3]
},
"grounded_utrdr": {"observed": 884.3, "hpac_4_03": 1121.7, "hpac_4_04": 1696.2}
}
]
}

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1,845 @@
{
"_sources": {
"DNA1251-2": "DNA 1251-2-EX, Compilation of Local Fallout Data From Test Detonations 1945-1962, Extracted From DASA 1251, Volume II, Oceanic U.S. Tests (1979). Approved for public release; distribution unlimited.",
"GLASSTONE": "S. Glasstone and P. J. Dolan, The Effects of Nuclear Weapons, 3rd ed. (1977), Fig. 9.105 and Table 9.109.",
"MOROZ": "B. E. Moroz, H. L. Beck, A. Bouville, S. L. Simon, Predictions of dispersion and deposition of fallout from nuclear testing using the NOAA-HYSPLIT meteorological model, Health Physics 99(2) (2010), Table 3."
},
"_notes": [
"Contour reaches and positions are read by eye from the figures, to about 5 miles.",
"Fission yields of U.S. thermonuclear tests remain classified (Moroz 2010): none is given here.",
"Winds are [ft MSL, direction FROM (degrees), mph], as the tables give them.",
"The Pacific patterns were drawn from island readings and ocean surveys; the faint contours of an ocean survey are short where the survey ended and where activity sank below the mixing layer (DNA 1251-2-EX, p. 111)."
],
"shots": [
{
"name": "Zuni",
"operation": "Redwing",
"date": "1956-05-27T17:56Z",
"lat": 11.4967,
"lon": 165.3692,
"yield_kt": 3500,
"burst_height_ft": 9,
"placement": "surface, coral soil and water",
"site_elevation_ft": 0,
"cloud_top_ft_msl": 79000,
"cloud_bottom_ft_msl": 49000,
"source": "DNA1251-2 pp. 111-119 (Table 20, Figure 72)",
"wind": {
"H": [
[
0,
50,
22
],
[
1000,
80,
26
],
[
2000,
70,
25
],
[
3000,
70,
28
],
[
4000,
90,
28
],
[
5000,
90,
24
],
[
6000,
100,
22
],
[
7000,
100,
22
],
[
8000,
100,
22
],
[
9000,
100,
22
],
[
10000,
100,
23
],
[
12000,
90,
24
],
[
14000,
90,
17
],
[
15000,
100,
15
],
[
16000,
110,
12
],
[
18000,
100,
12
],
[
20000,
140,
12
],
[
25000,
160,
18
],
[
30000,
170,
14
],
[
35000,
220,
29
],
[
40000,
220,
46
],
[
45000,
210,
40
],
[
50000,
240,
29
],
[
55000,
240,
3
],
[
60000,
80,
17
],
[
65000,
90,
30
],
[
70000,
90,
30
],
[
75000,
90,
40
],
[
80000,
100,
48
],
[
85000,
100,
48
],
[
90000,
100,
48
]
],
"H+3": [
[
0,
60,
30
],
[
1000,
60,
26
],
[
2000,
60,
26
],
[
3000,
70,
30
],
[
4000,
70,
31
],
[
5000,
90,
29
],
[
6000,
90,
29
],
[
7000,
100,
23
],
[
8000,
120,
23
],
[
9000,
110,
24
],
[
10000,
100,
22
],
[
12000,
90,
17
],
[
14000,
80,
16
],
[
15000,
80,
15
],
[
16000,
70,
14
],
[
18000,
90,
13
],
[
20000,
110,
10
],
[
25000,
170,
20
],
[
30000,
160,
18
],
[
35000,
200,
35
],
[
40000,
210,
50
],
[
45000,
220,
43
],
[
50000,
250,
31
],
[
55000,
250,
21
],
[
60000,
90,
16
],
[
65000,
90,
31
],
[
70000,
90,
37
],
[
75000,
90,
38
],
[
80000,
100,
48
],
[
85000,
100,
46
],
[
90000,
100,
43
]
],
"H+6": [
[
0,
90,
24
],
[
1000,
70,
28
],
[
2000,
80,
35
],
[
3000,
90,
31
],
[
4000,
100,
30
],
[
5000,
100,
28
],
[
6000,
100,
30
],
[
7000,
100,
31
],
[
8000,
90,
29
],
[
9000,
100,
30
],
[
10000,
100,
30
],
[
12000,
90,
26
],
[
14000,
90,
24
],
[
15000,
90,
24
],
[
16000,
90,
25
],
[
18000,
90,
17
],
[
20000,
90,
17
],
[
25000,
260,
2
],
[
30000,
180,
13
],
[
35000,
230,
35
],
[
40000,
260,
50
],
[
45000,
230,
61
],
[
50000,
240,
32
],
[
55000,
240,
20
],
[
60000,
80,
22
],
[
65000,
90,
32
],
[
70000,
90,
30
],
[
75000,
90,
35
],
[
80000,
100,
41
],
[
85000,
100,
41
],
[
90000,
100,
41
]
]
},
"reach": {
"_what": "Figure 72, off-site dose rate contours (R/hr at H+1): [rate, reach (statute miles from GZ), bearing (degrees)]",
"rows": [
[
150,
52,
343
],
[
100,
73,
0
],
[
50,
82,
345
],
[
30,
95,
0
],
[
10,
157,
290
],
[
3,
151,
349
],
[
1,
226,
354
]
]
}
},
{
"name": "Bravo",
"operation": "Castle",
"date": "1954-02-28T18:45Z",
"lat": 11.6908,
"lon": 165.2736,
"yield_kt": 15000,
"burst_height_ft": 7,
"placement": "surface, coral soil",
"site_elevation_ft": 0,
"cloud_top_ft_msl": 114000,
"cloud_bottom_ft_msl": 55300,
"source": "DNA1251-2 pp. 63-70 (Table 12, Figures 41-43); GLASSTONE; MOROZ",
"_caveat": "The wind table ends at 57,000 ft, at the base of a cloud reaching 114,000 ft. Filling the winds above from the NCEP/NCAR Reanalysis 1 (1954) turns the plume to within about 10 degrees of the measured one, but does not lengthen its hot contours: the model's 1000 R/hr contour reaches about a third as far as NRDL's and RAND's, and it reads the island measurements about 2 times low. Smaller particles do not close it, and landing spots a third as wide reach only about two thirds as far. The contours are partly model-built over open ocean (Glasstone 9.105 notes a hot-spot reading of Rongelap's north).",
"wind": {
"H": [
[
0,
60,
14
],
[
1000,
70,
20
],
[
2000,
90,
21
],
[
3000,
90,
20
],
[
4000,
90,
16
],
[
5000,
100,
10
],
[
6000,
120,
5
],
[
7000,
310,
5
],
[
8000,
310,
5
],
[
9000,
320,
8
],
[
10000,
310,
6
],
[
12000,
310,
12
],
[
14000,
290,
16
],
[
15000,
290,
15
],
[
16000,
290,
15
],
[
18000,
290,
15
],
[
20000,
280,
15
],
[
25000,
260,
22
],
[
30000,
250,
30
],
[
35000,
240,
40
],
[
40000,
230,
40
],
[
45000,
250,
52
],
[
50000,
250,
36
],
[
55000,
200,
18
],
[
57000,
340,
31
]
]
},
"reach": {
"_what": "Figure 41 (NRDL) and Figure 42 (RAND), off-site dose rate contours (R/hr at H+1): [rate, NRDL reach mi, RAND reach mi]",
"rows": [
[
3000,
110,
112
],
[
2000,
125,
123
],
[
1000,
146,
150
],
[
500,
182,
168
],
[
100,
343,
null
]
]
},
"dose_96h_reach": {
"_what": "GLASSTONE Fig. 9.105: total dose by 96 hours (rads): [dose, reach mi]",
"rows": [
[
3000,
162
],
[
1000,
225
],
[
300,
290
]
]
},
"arrival": {
"_what": "Fallout arrival: [statute miles, hours]: GLASSTONE Fig. 9.105's effective arrival time scale; NRDL's time lines (Figure 41); MOROZ's best estimate at Rongelap (180 km)",
"glasstone": [
[
85,
6.6
],
[
130,
7.8
],
[
255,
14.0
]
],
"nrdl": [
[
85,
3
],
[
130,
6
],
[
255,
12
]
],
"moroz_rongelap": [
112,
5.6
]
},
"islands_h1": {
"_what": "Figure 41: island dose rates (R/hr at H+1), at their places on the chart: [name, miles east, miles north, R/hr]",
"rows": [
[
"Rongelap",
127,
-21,
1080
],
[
"Rongelap",
119,
-21,
1150
],
[
"Rongelap",
109,
-18,
1950
],
[
"Rongelap",
99,
-19,
2420
],
[
"Rongelap",
117,
-40,
342
],
[
"Rongelap",
106,
-40,
132
],
[
"Rongerik",
153,
-30,
770
],
[
"Rongerik",
157,
-25,
308
],
[
"Ailinginae",
89,
-40,
108
],
[
"Ailinginae",
77,
-41,
77
],
[
"Utirik",
310,
-24,
23
],
[
"Bikar",
335,
35,
93
]
]
}
}
]
}

View file

@ -0,0 +1,81 @@
// The model against two megaton bursts on coral in the Pacific (pacific-shots.json): the yields of
// modern weapons, which the Nevada shots do not reach.
import {depositionGrid, hotlines, landingSpots, profileFromTable} from './model.js';
import data from './pacific-shots.json';
const FEET = 0.3048;
const MILE = 1.609344;
const shot = (name) => data.shots.find((s) => s.name === name);
// The landing spots of a shot, in its winds at H-hour, from its cloud as observed.
function spots(s, wind = s.wind.H) {
return landingSpots({
yieldKt: s.yield_kt,
burstHeight: s.burst_height_ft * FEET,
profile: profileFromTable(wind, s.site_elevation_ft),
stabilized: {base: s.cloud_bottom_ft_msl * FEET, top: s.cloud_top_ft_msl * FEET},
});
}
// The smallest angle between two bearings (degrees).
const turn = (a, b) => Math.abs(((a - b + 540) % 360) - 180);
describe('Redwing Zuni, 3.5 Mt, its winds measured above its cloud', () => {
const zuni = shot('Zuni');
const landed = spots(zuni);
// Its fission yield is not public; a quarter of its yield brings the hot contours closest.
const grid = depositionGrid(landed, {yieldKt: zuni.yield_kt, fissionFraction: 0.25});
const hot = zuni.reach.rows.filter(([rate]) => rate >= 30);
const lines = hotlines(grid, hot.map(([rate]) => rate));
test('the hot fallout goes where it went: north-northwest, across winds which turn with height', () => {
hot.forEach(([, , bearing], k) => expect(turn(lines[k].azimuth, bearing)).toBeLessThan(25));
});
test('and as far: the 150 to 30 R/hr contours within half again', () => {
hot.forEach(([, miles], k) => {
const ratio = lines[k].km / MILE / miles;
expect(ratio).toBeGreaterThan(0.67);
expect(ratio).toBeLessThan(1.5);
});
});
});
describe('Castle Bravo, 15 Mt, its winds measured only below its cloud', () => {
const bravo = shot('Bravo');
const landed = spots(bravo);
// The hour at which the activity landing about `miles` downwind lands, on the average.
function arrival(miles) {
const near = landed.filter((s) => Math.abs(s.x / 1000 / MILE - miles) < 10);
const total = near.reduce((a, s) => a + s.activity, 0);
return near.reduce((a, s) => a + s.activity * s.hours, 0) / total;
}
test('the fallout arrives when it did: about as Glasstone, NRDL and Moroz have it', () => {
for (const [miles, glasstone] of bravo.arrival.glasstone) {
const nrdl = bravo.arrival.nrdl.find(([m]) => m === miles)[1];
// Between the two estimates, give or take a quarter.
expect(arrival(miles)).toBeGreaterThan(Math.min(glasstone, nrdl) * 0.75);
expect(arrival(miles)).toBeLessThan(Math.max(glasstone, nrdl) * 1.25);
}
const [miles, hours] = bravo.arrival.moroz_rongelap;
expect(Math.abs(arrival(miles) / hours - 1)).toBeLessThan(0.5);
});
// A known gap, kept in view: the model brings Bravo's hot fallout down about three times closer
// than NRDL and RAND drew it. It is not the unmeasured winds above 57,000 ft (the reanalysis
// winds there turn the plume right but do not lengthen it), nor the particle sizes; a plume a
// third as wide reaches about two thirds as far (see the fixture's caveat). If this starts to fail, the gap has closed:
// update the caveat and these bounds.
test('the hot fallout reaches about a third as far as it was drawn (a known gap)', () => {
const grid = depositionGrid(landed, {yieldKt: bravo.yield_kt, fissionFraction: 0.5});
const rows = bravo.reach.rows.filter(([rate]) => rate >= 500 && rate <= 1000);
const lines = hotlines(grid, rows.map(([rate]) => rate));
rows.forEach(([, nrdl], k) => {
const ratio = lines[k].km / MILE / nrdl;
expect(ratio).toBeGreaterThan(0.25);
expect(ratio).toBeLessThan(0.6);
});
});
});

View file

@ -0,0 +1,96 @@
// The fallout, spread over workers (fallout.worker.js), each on its own core: a worker is given a
// task (a past day, or a burst), and when it is done, the next not yet given. No imports from the
// app.
// The most workers run at once: past this, more add heat more than speed.
export const MOST_WORKERS = 6;
// How many workers to run on a device which says it has `hardwareConcurrency` cores and
// `deviceMemory` GB (navigator; either may be missing): one core is left for the page, and a
// device with little memory runs few (each worker of the past days holds a month, about 40-60 MB
// in all).
export function workerCount({hardwareConcurrency, deviceMemory} = {}) {
const cores = Number(hardwareConcurrency) || 2;
let count = Math.min(Math.max(cores - 1, 1), MOST_WORKERS);
if (deviceMemory && deviceMemory <= 2) count = Math.min(count, 2);
return count;
}
// `tasks` tasks (0..tasks-1) done by `count` workers from `makeWorker()`, each given `start` (a
// message: what every task needs), then a task (with what `payload(k)` gives, if it needs more),
// and when it is done the next not yet given: the results, in the order of the tasks, or null if
// `signal` (an AbortSignal) is aborted, which stops the workers at once. A task's worker says how much of it is done ('progress'), then its result
// ('done'); `onProgress(done, total)` hears how much of all of them is done, of `total`. Rejects if
// a worker fails (or cannot be made). The workers answer as work.js's serveFallout does.
export function runPool({tasks, start, payload = () => null, total, count, makeWorker, signal, onProgress = () => null}) {
return new Promise((resolve, reject) => {
const workers = [];
const results = new Array(tasks).fill(null);
const doneOf = new Array(tasks).fill(0);
let next = 0, finished = 0, over = false;
const stop = () => {
over = true;
for (const w of workers) w.terminate();
signal?.removeEventListener('abort', aborted);
};
const aborted = () => {
if (over) return;
stop();
resolve(null);
};
const fail = (error) => {
if (over) return;
stop();
reject(error);
};
const progress = () => onProgress(doneOf.reduce((a, n) => a + n, 0), total);
const give = (worker) => {
if (next >= tasks) return;
const k = next++;
worker.postMessage({type: 'task', k, ...payload(k)});
};
const heard = (worker, data) => {
if (over) return;
if (data.type === 'error') {
fail(new Error(data.message));
return;
}
doneOf[data.k] = data.done;
if (data.type === 'done') {
results[data.k] = data.result;
finished++;
if (finished === tasks) {
stop();
progress();
resolve(results);
return;
}
give(worker);
}
progress();
};
const failed = (e) => fail(new Error(e.message || 'A fallout worker failed'));
if (signal?.aborted) {
resolve(null);
return;
}
if (!tasks) {
resolve(results);
return;
}
signal?.addEventListener('abort', aborted);
try {
for (let i = 0; i < Math.min(count, tasks); i++) {
const worker = makeWorker();
if (!worker) throw new Error('No worker could be made');
workers.push(worker);
worker.onerror = failed;
worker.onmessage = ({data}) => heard(worker, data);
worker.postMessage({type: 'start', ...start});
give(worker);
}
} catch (e) {
fail(e);
}
});
}

View file

@ -0,0 +1,21 @@
import {MOST_WORKERS, workerCount} from './pool.js';
describe('how many fallout workers run', () => {
test('one for each core but one, left for the page', () => {
expect(workerCount({hardwareConcurrency: 4})).toBe(3);
expect(workerCount({hardwareConcurrency: 2})).toBe(1);
expect(workerCount({hardwareConcurrency: 1})).toBe(1);
});
test('no more than a few, however many cores', () => {
expect(workerCount({hardwareConcurrency: 8})).toBe(MOST_WORKERS);
expect(workerCount({hardwareConcurrency: 64})).toBe(MOST_WORKERS);
});
test('few on a device with little memory, or which does not say', () => {
expect(workerCount({hardwareConcurrency: 8, deviceMemory: 2})).toBe(2);
expect(workerCount({hardwareConcurrency: 8, deviceMemory: 8})).toBe(MOST_WORKERS);
expect(workerCount({})).toBe(1);
expect(workerCount()).toBe(1);
});
});

View file

@ -0,0 +1,56 @@
// Several bursts at once: each target's weapon, and the fallout of all of them on one map. Shared by
// the app's map viewer and the standalone viewer: no imports from the app, no dependencies.
import {weaponByKey} from './weapons.js';
const METERS_PER_DEGREE = 111320;
// The weapon a target has when none was chosen for it.
export const DEFAULT_WEAPON = 'w87-0';
export const CUSTOM_WEAPON = 'custom';
// What a target (a pin of kind "target", or any {weapon, yield_kt, fission_fraction}) will be
// burst with: {key, yieldKt, fissionFraction, weapon (as weapons.json has it, or null for a yield
// of the user's own)}. A target's own fission share is kept over its weapon's.
export function targetWeapon(target) {
const key = target?.weapon || DEFAULT_WEAPON;
if (key === CUSTOM_WEAPON) {
return {
key, weapon: null,
yieldKt: target.yield_kt > 0 ? target.yield_kt : 100,
fissionFraction: target.fission_fraction > 0 ? target.fission_fraction : 0.5,
};
}
const weapon = weaponByKey(key) || weaponByKey(DEFAULT_WEAPON);
return {
key: weapon.key, weapon,
yieldKt: weapon.yield_kt,
fissionFraction: target?.fission_fraction > 0 ? target.fission_fraction : weapon.fission_fraction,
};
}
// Where `point` ({lat, lon}) is from `origin`: [m east, m north].
export function offsetFrom(origin, point) {
const perLon = METERS_PER_DEGREE * Math.cos(origin.lat * Math.PI / 180);
return [(point.lon - origin.lon) * perLon, (point.lat - origin.lat) * METERS_PER_DEGREE];
}
// The landing spots of several bursts on one map, around `origin`: runs are [{burst ({lat, lon}),
// spots (as landingSpots gives them, around the burst), yieldKt, fissionFraction}]. Each spot is
// moved to where it is from `origin`, and carries its burst's fission yield (kt), so the spots of
// every burst go on one grid as if of a single kiloton of fission (depositionGrid with yieldKt 1).
// Each spot also keeps which run it is of (`run`), for sharpenGrid.
//
// The grid's meters east are degrees of longitude at the origin's latitude (as offsetFrom, and the
// map image, take them); a burst's own meters east are shorter or longer there by how much a degree
// is at its latitude, so they are scaled to the grid's.
export function combineBursts(origin, runs) {
const combined = [];
runs.forEach(({burst, spots, yieldKt, fissionFraction}, run) => {
const [dx, dy] = offsetFrom(origin, burst);
const east = Math.cos(origin.lat * Math.PI / 180) / Math.cos(burst.lat * Math.PI / 180);
const kt = yieldKt * fissionFraction;
for (const s of spots) combined.push({...s, x: dx + s.x * east, y: s.y + dy, activity: s.activity * kt, run});
});
return combined;
}

View file

@ -0,0 +1,102 @@
import {combineBursts, CUSTOM_WEAPON, DEFAULT_WEAPON, offsetFrom, targetWeapon} from './targets.js';
import {depositionGrid, landingSpots, sharpenGrid, SOURCE_NORMALIZATION} from './model.js';
describe('a target\'s weapon', () => {
test('is the one chosen for it, with its yield and fission share', () => {
expect(targetWeapon({weapon: 'w88'})).toMatchObject({key: 'w88', yieldKt: 455, fissionFraction: 0.5});
});
test('is the default when none was chosen, or the one chosen is no longer offered', () => {
expect(targetWeapon({}).key).toBe(DEFAULT_WEAPON);
expect(targetWeapon({weapon: 'retired-thing'}).key).toBe(DEFAULT_WEAPON);
});
test('keeps the target\'s own fission share over the weapon\'s', () => {
expect(targetWeapon({weapon: 'w88', fission_fraction: 0.8}).fissionFraction).toBe(0.8);
});
test('may be a yield of the user\'s own', () => {
expect(targetWeapon({weapon: CUSTOM_WEAPON, yield_kt: 20, fission_fraction: 1}))
.toMatchObject({weapon: null, yieldKt: 20, fissionFraction: 1});
});
});
describe('several bursts', () => {
test('are placed from one origin', () => {
const [x, y] = offsetFrom({lat: 0, lon: 0}, {lat: 1, lon: 1});
expect(x).toBeCloseTo(111320, 0);
expect(y).toBeCloseTo(111320, 0);
});
test('put down the fallout of each, by its fission yield, on one grid', () => {
const profile = [[0, 10, 0]];
const a = {lat: 40, lon: -105}, b = {lat: 40, lon: -104};
const spots = landingSpots({yieldKt: 10, profile});
const combined = combineBursts(a, [
{burst: a, spots, yieldKt: 10, fissionFraction: 0.5},
{burst: b, spots, yieldKt: 10, fissionFraction: 1},
]);
expect(combined.length).toBe(spots.length * 2);
const grid = depositionGrid(combined, {yieldKt: 1});
const landed = spots.reduce((s, x) => s + x.activity, 0);
const total = grid.values.reduce((s, v) => s + v, 0) * (grid.cell / 1000) ** 2;
// 5 kt + 10 kt of fission.
expect(total / (SOURCE_NORMALIZATION * 15 * landed)).toBeCloseTo(1, 2);
// The second burst's spots are a degree of longitude east.
expect(combined[spots.length].x - combined[0].x).toBeCloseTo(111320 * Math.cos(40 * Math.PI / 180), 0);
});
});
describe('bursts far apart', () => {
test('keep their plumes as wide east to west as at their own latitude', () => {
const spot = {x: 1000, y: 0, sigma: 1, activity: 1, hours: 1};
const origin = {lat: 40, lon: -75}, south = {lat: 25, lon: -80};
const [combined] = combineBursts(origin, [{burst: south, spots: [spot], yieldKt: 1, fissionFraction: 1}]);
const [dx] = offsetFrom(origin, south);
// 1000 m east at 25 degrees is more of a degree of longitude than 1000 m at 40.
expect(combined.x - dx).toBeCloseTo(1000 * Math.cos(40 * Math.PI / 180) / Math.cos(25 * Math.PI / 180), 6);
});
});
describe('a small burst far from a large one', () => {
// The highest dose rate (R/hr) on `grid` within `radius` m of x, y.
function hottest(grid, x, y, radius) {
let most = 0;
for (let j = 0; j < grid.ny; j++) {
for (let i = 0; i < grid.nx; i++) {
const cx = grid.x0 + (i + 0.5) * grid.cell, cy = grid.y0 + (j + 0.5) * grid.cell;
if (Math.hypot(cx - x, cy - y) <= radius) most = Math.max(most, grid.values[j * grid.nx + i]);
}
}
return most;
}
test('keeps its hot fallout close to ground zero on a grid over both', () => {
const profile = [[0, 0, 10]];
const small = {lat: 40, lon: -100}, large = {lat: 40, lon: -95.3};
const smallSpots = landingSpots({yieldKt: 1, profile});
const alone = depositionGrid(smallSpots, {yieldKt: 1, boundsFloor: 0.1});
const own = hottest(alone, 0, 0, 4000);
expect(own).toBeGreaterThan(100);
const spots = combineBursts(small, [
{burst: small, spots: smallSpots, yieldKt: 1, fissionFraction: 1},
{burst: large, spots: landingSpots({yieldKt: 300, profile}), yieldKt: 300, fissionFraction: 0.5},
]);
const coarse = depositionGrid(spots, {yieldKt: 1, boundsFloor: 0.1});
expect(coarse.cell).toBeGreaterThan(1000);
// Averaged over cells kilometers wide, the 100 R/hr fallout is gone...
expect(hottest(coarse, 0, 0, 4000)).toBeLessThan(100);
// ...and sharpened, it is kept.
const sharp = sharpenGrid(coarse, spots);
expect(hottest(sharp, 0, 0, 4000)).toBeGreaterThan(Math.max(100, own * 0.6));
expect(hottest(sharp, 0, 0, 4000)).toBeLessThan(own * 1.2);
// Far downwind, where only wide fallout lands, the grid is as it was.
const [lx, ly] = offsetFrom(small, large);
const k = Math.floor((ly + 200000 - coarse.y0) / coarse.cell) * coarse.nx
+ Math.floor((lx - coarse.x0) / coarse.cell);
expect(coarse.values[k]).toBeGreaterThan(0);
expect(sharp.values[k]).toBe(coarse.values[k]);
});
});

View file

@ -0,0 +1,58 @@
// The ground under a fallout plume: an elevation grid, as the model reads it. Shared by the app's
// map viewer and the standalone viewer: no imports from the app, no dependencies.
//
// A grid is {west, south (degrees), step (degrees between samples), nx, ny, values (meters, row by
// row from the south)}.
const METERS_PER_DEGREE = 111320;
// A grid from its compact form: elevations as little-endian 16-bit integers, in base64.
export function decodeGrid({west, south, step, nx, ny, meters_int16_le_base64: data}) {
const bytes = Uint8Array.from(atob(data), (c) => c.charCodeAt(0));
const view = new DataView(bytes.buffer);
const values = new Float32Array(nx * ny);
for (let i = 0; i < values.length; i++) values[i] = view.getInt16(i * 2, true);
return {west, south, step, nx, ny, values};
}
// The elevation (m) at `lon`, `lat`: bilinear between the samples, and as the nearest edge beyond
// them.
export function elevationAt(grid, lon, lat) {
const fx = Math.min(Math.max((lon - grid.west) / grid.step, 0), grid.nx - 1);
const fy = Math.min(Math.max((lat - grid.south) / grid.step, 0), grid.ny - 1);
const i = Math.min(Math.floor(fx), grid.nx - 2);
const j = Math.min(Math.floor(fy), grid.ny - 2);
const dx = fx - i, dy = fy - j;
const v = grid.values;
// A sample with no number is left out, and the others weighed as they are.
let sum = 0, weight = 0;
for (const [a, b, w] of [[i, j, (1 - dx) * (1 - dy)], [i + 1, j, dx * (1 - dy)],
[i, j + 1, (1 - dx) * dy], [i + 1, j + 1, dx * dy]]) {
const value = v[b * grid.nx + a];
if (w > 0 && Number.isFinite(value)) {
sum += value * w;
weight += w;
}
}
return weight > 0 ? sum / weight : NaN;
}
// The terrain around a burst at `lon`, `lat`, as the model takes it: {ground(x, y), lowest, elevation}.
// ground(x, y) is the height of the ground x meters east and y north of ground zero above the ground
// at ground zero; lowest is the lowest it gets anywhere on the grid; elevation is that of ground zero.
export function terrainAround(grid, lon, lat) {
const elevation = elevationAt(grid, lon, lat);
const perLon = METERS_PER_DEGREE * Math.cos(lat * Math.PI / 180);
let lowest = Infinity;
for (const v of grid.values) if (Number.isFinite(v)) lowest = Math.min(lowest, v);
if (!Number.isFinite(lowest)) lowest = elevation;
return {
elevation,
lowest: lowest - elevation,
// Where the grid has no number, the ground is as high as ground zero.
ground: (x, y) => {
const e = elevationAt(grid, lon + x / perLon, lat + y / METERS_PER_DEGREE) - elevation;
return Number.isFinite(e) ? e : 0;
},
};
}

View file

@ -0,0 +1,97 @@
import {decodeGrid, elevationAt, terrainAround} from './terrain.js';
import {landingSpots} from './model.js';
import {meanError, runShot} from './validation.js';
import shots from './nts-shots.json';
import ntsTerrain from './nts-terrain.json';
// A grid from plain values (row by row from the south), in its compact form.
function encode(values, nx, ny, west = -1, south = -1, step = 0.5) {
const bytes = new Uint8Array(values.length * 2);
const view = new DataView(bytes.buffer);
values.forEach((v, i) => view.setInt16(i * 2, v, true));
return {west, south, step, nx, ny, meters_int16_le_base64: btoa(String.fromCharCode(...bytes))};
}
describe('an elevation grid', () => {
const grid = decodeGrid(encode([0, 100, 200, 300], 2, 2));
test('is decoded as it was written', () => {
expect(Array.from(grid.values)).toEqual([0, 100, 200, 300]);
});
test('is read between its samples, and as the nearest edge beyond them', () => {
expect(elevationAt(grid, -1, -1)).toBe(0);
expect(elevationAt(grid, -0.75, -1)).toBe(50);
expect(elevationAt(grid, -0.75, -0.75)).toBe(150);
expect(elevationAt(grid, 10, 10)).toBe(300);
});
test('around a burst, is the height above the ground at ground zero', () => {
const terrain = terrainAround(grid, -1, -1);
expect(terrain.elevation).toBe(0);
expect(terrain.ground(0, 0)).toBe(0);
// Half a step (0.25 degrees) north is 100 m up.
expect(terrain.ground(0, 0.25 * 111320)).toBeCloseTo(100, 0);
expect(terrain.lowest).toBe(0);
});
test('around a burst, makes do where the grid has no number', () => {
const holey = {west: -1, south: -1, step: 0.5, nx: 2, ny: 2, values: Float32Array.from([0, NaN, 200, 300])};
const terrain = terrainAround(holey, -1, -1);
expect(Number.isFinite(terrain.lowest)).toBe(true);
expect(terrain.ground(0.5 * 111320 * Math.cos(-Math.PI / 180), 0)).toBe(0);
});
test('of the Nevada Test Site, has its shots at the elevations recorded for them', () => {
const nts = decodeGrid(ntsTerrain);
for (const shot of shots.shots) {
// Within 60 m: the grid is sampled every 0.03 degrees (about 3 km).
expect(Math.abs(elevationAt(nts, shot.lon, shot.lat) - shot.site_elevation_ft * 0.3048)).toBeLessThan(60);
}
});
});
describe('fallout over terrain', () => {
// Blowing east at 15 m/s at every height.
const profile = [[0, 15, 0]];
const flat = landingSpots({yieldKt: 10, profile});
test('lands as on flat ground, when the ground is flat', () => {
const spots = landingSpots({yieldKt: 10, profile, terrain: {ground: () => 0, lowest: 0}});
expect(spots).toEqual(flat);
});
// A ridge 1500 m high, from 20 to 40 km downwind.
const ridge = {ground: (x) => (x > 20000 && x < 40000 ? 1500 : 0), lowest: 0};
const share = (spots, test) => spots.filter((s) => test(s.x)).reduce((a, s) => a + s.activity, 0);
test('piles up on a ridge in its way, and spares the valley behind it', () => {
const spots = landingSpots({yieldKt: 10, profile, terrain: ridge});
const onRidge = (x) => x > 20000 && x < 40000;
const behind = (x) => x >= 40000 && x < 80000;
expect(share(spots, onRidge)).toBeGreaterThan(1.3 * share(flat, onRidge));
expect(share(spots, behind)).toBeLessThan(share(flat, behind));
});
test('lands sooner on the ridge, having fallen less far', () => {
const spots = landingSpots({yieldKt: 10, profile, terrain: ridge});
const hours = (list) => list.filter((s) => s.x > 20000 && s.x < 40000)
.reduce((a, s) => a + s.activity * s.hours, 0) / share(list, (x) => x > 20000 && x < 40000);
expect(hours(spots)).toBeLessThan(hours(flat));
});
test('lands further on in a valley below ground zero', () => {
const valley = {ground: (x) => (x > 5000 ? -1000 : 0), lowest: -1000};
const spots = landingSpots({yieldKt: 10, profile, terrain: valley});
const reach = (list) => list.reduce((a, s) => a + s.activity * s.x, 0) / list.reduce((a, s) => a + s.activity, 0);
expect(reach(spots)).toBeGreaterThan(reach(flat));
});
test('of the six Nevada tests, matches them as well as on flat ground', () => {
// Measured 2.00 with and without terrain: their close-in fallout fell on the flats where they
// were fired, and terrain moves what fell 50 to 400 km away by 0.5 to 25 km.
const terrain = decodeGrid(ntsTerrain);
const results = shots.shots.map((shot) => runShot(shot, {terrain}));
expect(meanError(results, (r) => r.transport)).toBeLessThan(2.2);
});
});

View file

@ -0,0 +1,130 @@
// How well the model matches the fallout measured after six Nevada tests (nts-shots.json), and how
// well HPAC, the DoD's hazard model, matched the same measurements.
//
// The measure is the area inside each measured dose-rate contour: predicted / observed. A shot's
// error is the geometric mean of how far off each contour is (2 = off by a factor of two, either
// way); its bias is the geometric mean of the ratios (above 1 = too big).
//
// Two questions are kept apart:
// transport: with the right amount of activity on the ground, does it land in the right places?
// The prediction is scaled so its grounded UTRDR (the measured amount) matches.
// a priori: with nothing taken from the measurements, as the map would run.
import {
contourAreas,
depositionGrid,
groundedUtrdr,
hotlines,
landingSpots,
plumeBearing,
profileFromTable,
risingCloud,
scaleToUtrdr,
stabilizedCloud,
uniformProfile,
} from './model.js';
import {terrainAround} from './terrain.js';
const FEET = 0.3048;
const SQ_KM_PER_SQ_MI = 2.589988;
// The geometric mean of how far off each ratio is, and of the ratios.
export function areaError(predicted, observed) {
const logs = [];
predicted.forEach((p, i) => {
const o = observed[i];
if (o === null || o === undefined) return;
// A contour predicted nowhere counts as off by the smallest area the grid could show.
logs.push(Math.log(Math.max(p, 0.01) / o));
});
const n = logs.length;
return {
error: Math.exp(logs.reduce((a, l) => a + Math.abs(l), 0) / n),
bias: Math.exp(logs.reduce((a, l) => a + l, 0) / n),
contours: n,
};
}
// The stabilized cloud of a shot as observed ({base, top}, m above the burst), or null where its top
// was not measured; a base which was not measured is taken from the fit.
export function observedCloud(shot) {
if (!shot.cloud_top_ft_msl) return null;
const above = shot.site_elevation_ft + Math.max(shot.burst_height_ft, 0);
const top = (shot.cloud_top_ft_msl - above) * FEET;
const fit = stabilizedCloud(shot.yield_kt);
const base = shot.cloud_bottom_ft_msl ? (shot.cloud_bottom_ft_msl - above) * FEET : Math.min(fit.base, top * 0.6);
return {base, top};
}
// The landing spots of a shot. options: uniform (one wind, the mean over the cloud), surface (one
// wind, the one at the ground: what a person would read off a weather report), observedCloud (the
// cloud as observed, not as the fits give it), volumeShare, terrain (an elevation grid, as
// decodeGrid gives it: particles land on the ground under them, not on a plane at the height of
// ground zero).
export function shotSpots(shot, options = {}) {
const burstHeight = Math.max(shot.burst_height_ft, 0) * FEET;
const stabilized = options.observedCloud ? observedCloud(shot) : null;
let profile = profileFromTable(shot.wind, shot.site_elevation_ft);
if (options.uniform) profile = uniformProfile(profile, risingCloud(shot.yield_kt, burstHeight, stabilized).top);
if (options.surface) profile = [profile[0]];
return landingSpots({
yieldKt: shot.yield_kt,
burstHeight,
profile,
siteElevation: shot.site_elevation_ft * FEET,
volumeShare: options.volumeShare,
stabilized,
terrain: options.terrain ? terrainAround(options.terrain, shot.lon, shot.lat) : null,
});
}
// Run the model on one of the six shots (nts-shots.json); options as shotSpots takes them.
export function runShot(shot, options = {}) {
const grid = depositionGrid(shotSpots(shot, options), {yieldKt: shot.yield_kt});
const {dose_rates: rates, observed} = shot.areas_sq_mi;
const lowest = Math.min(...rates);
const priori = contourAreas(grid, rates);
const scale = scaleToUtrdr(grid, rates, shot.yield_kt, shot.grounded_utrdr.observed);
const transport = contourAreas(grid, rates, scale);
return {
name: shot.name,
rates,
observed,
apriori: {areas: priori, ...areaError(priori, observed),
utrdr: groundedUtrdr(grid, rates, shot.yield_kt), bearing: plumeBearing(grid, lowest)},
transport: {areas: transport, scale, ...areaError(transport, observed),
bearing: plumeBearing(grid, lowest, scale)},
hpac403: areaError(shot.areas_sq_mi.hpac_4_03, observed),
hpac404: areaError(shot.areas_sq_mi.hpac_4_04, observed),
};
}
// Run the model on one of the three close-in shots (near-field-shots.json), on a fine grid around
// ground zero: the area (km^2), hotline (km) and azimuth of each contour, and how far off each is,
// beside how far off DNAF-1, DELFIC and WSEG-10 were.
export function runNearField(shot, options = {}) {
const grid = depositionGrid(shotSpots(shot, options), {
yieldKt: shot.yield_kt, fissionFraction: shot.fission_kt / shot.yield_kt,
bounds: [-20000, -20000, 20000, 20000], cellSize: 40,
});
const {rates, observed} = shot.contours;
const area = contourAreas(grid, rates).map((a) => a * SQ_KM_PER_SQ_MI);
const lines = hotlines(grid, rates);
const others = {};
for (const model of ['dnaf1', 'delfic', 'wseg10']) {
const p = shot.contours[model];
if (p) others[model] = {area: areaError(p.area_km2, observed.area_km2), hotline: areaError(p.hotline_km, observed.hotline_km)};
}
return {
name: shot.name,
area: {values: area, ...areaError(area, observed.area_km2)},
hotline: {values: lines.map((l) => l.km), ...areaError(lines.map((l) => l.km), observed.hotline_km)},
azimuth: lines.map((l) => l.azimuth),
others,
};
}
// The geometric mean of the shots' errors.
export function meanError(results, pick) {
return Math.exp(results.reduce((a, r) => a + Math.log(pick(r).error), 0) / results.length);
}

View file

@ -0,0 +1,33 @@
// The weapons the fallout simulator offers (weapons.json): deployed or stockpiled today, each with
// its yield as a cited source gives it. Shared by the app's map viewer and the standalone viewer: no
// imports from the app, no dependencies.
import data from './weapons.json';
// [{name (of the country, or kind), weapons: [{key, name, yield_kt, yield_range_kt?,
// fission_fraction, status, source, quote}]}], in the order they are offered.
export const WEAPON_GROUPS = data.groups;
// The sources the weapons cite: {key: citation}.
export const WEAPON_SOURCES = data.sources;
const BY_KEY = new Map(WEAPON_GROUPS.flatMap((g) => g.weapons.map((w) => [w.key, {...w, group: g.name}])));
// The weapon with `key` (with the name of its group), or undefined.
export function weaponByKey(key) {
return BY_KEY.get(key);
}
// A yield as it is written: kilotons, or megatons from 1000 kt up.
export function formatYield(kt) {
if (kt >= 1000) return `${+(kt / 1000).toFixed(2)} Mt`;
return `${+kt.toFixed(1)} kt`;
}
// A yield with how much of it is fission, which is what makes fallout: "300 kt, half fission";
// "15 kt" when all of it is.
export function formatYieldAndFission(kt, fissionFraction) {
if (fissionFraction >= 1) return formatYield(kt);
const share = fissionFraction === 0.5 ? 'half' : `${Math.round(fissionFraction * 100)}%`;
return `${formatYield(kt)}, ${share} fission`;
}

View file

@ -0,0 +1,117 @@
{
"_about": "Nuclear weapons which are deployed or in active stockpiles (as of the 2025-2026 sources below), for the fallout simulator. No retired or historical weapons. Every yield is quoted from its source.",
"_rules": [
"yield_kt is the most recent source's single figure; where the sources give only a range, or disagree, it is the top of it (the case with the most fallout). yield_range_kt is the range the sources give.",
"Variable-yield weapons have one entry for each setting a source gives.",
"No public source gives the fission share of any warhead. fission_fraction is assumed, as Glasstone and Dolan (1977, 9.94) plan for: 0.5 for a two-stage thermonuclear weapon (most derive at least half their yield from fission), 1.0 for a fission or boosted-fission weapon, and for the W76-2, which the source says uses only its fission primary.",
"Weapons whose yield no source gives are left out (see _omitted)."
],
"sources": {
"SIPRI26": "SIPRI Yearbook 2026, chapter 8, World nuclear forces, Tables 8A.2-8A.10 (data as of January 2026). https://www.sipri.org/sites/default/files/YB26%2008%20World%20Nuclear%20Forces.pdf",
"US26": "H. M. Kristensen, M. Korda et al., United States nuclear weapons, 2026, Bulletin of the Atomic Scientists 82(2):119-150, doi:10.1080/00963402.2026.2633029.",
"RU26": "Kristensen, Korda et al., Russian nuclear weapons, 2026, Bulletin of the Atomic Scientists 82(3):221-254, Table 1. https://thebulletin.org/wp-content/uploads/2026/05/rbul_a_2659527_t0001-full.pdf",
"CN26": "Kristensen, Korda et al., Chinese nuclear weapons, 2026, Bulletin of the Atomic Scientists (July 2026), Table 1. https://thebulletin.org/wp-content/uploads/2026/07/rbul_a_2691662_t0001.pdf",
"CN24": "Chinese nuclear weapons, 2024, Bulletin of the Atomic Scientists, Table 1. https://thebulletin.org/wp-content/uploads/2024/01/rbul_a_2295206_t0001_withnotes.pdf",
"IN26": "Indian nuclear weapons, 2026, Bulletin of the Atomic Scientists 82(5):373-392, Table 1. https://thebulletin.org/wp-content/uploads/2026/09/rbul_a_2718785_t0001_full.pdf",
"PK25": "Pakistan nuclear weapons, 2025, Bulletin of the Atomic Scientists 81(5):386-408, Table 1. https://thebulletin.org/wp-content/uploads/2025/09/rbul_a_2543685_t0001-full.png",
"NK24": "North Korean nuclear weapons, 2024, Bulletin of the Atomic Scientists (July 2024). https://thebulletin.org/premium/2024-07/north-korean-nuclear-weapons-2024/",
"FAS16": "Federation of American Scientists, B61-12 earth penetration (2016). https://fas.org/blogs/security/2016/01/b61-12_earth-penetration",
"FEMA": "FEMA, Planning Guidance for Response to a Nuclear Detonation (third edition, 2022): planning scenarios of improvised nuclear devices of 0.1 to 10 kt detonated at ground level."
},
"groups": [
{
"name": "United States",
"weapons": [
{"key": "w78", "name": "W78 (Minuteman III)", "yield_kt": 335, "fission_fraction": 0.5, "status": "deployed", "source": "SIPRI26", "quote": "1-3 x W78 x 335 kt"},
{"key": "w87-0", "name": "W87-0 (Minuteman III)", "yield_kt": 300, "fission_fraction": 0.5, "status": "deployed", "source": "US26", "quote": "a 300-kiloton W87/Mk21"},
{"key": "w76-1", "name": "W76-1 (Trident II D5)", "yield_kt": 90, "fission_fraction": 0.5, "status": "deployed", "source": "SIPRI26", "quote": "1-8 x W76-1 x 90 kt"},
{"key": "w76-2", "name": "W76-2 low-yield (Trident II D5)", "yield_kt": 8, "fission_fraction": 1.0, "status": "deployed", "source": "US26", "quote": "only uses the warhead fission primary to produce a yield of about 8 kilotons"},
{"key": "w88", "name": "W88 (Trident II D5)", "yield_kt": 455, "fission_fraction": 0.5, "status": "deployed", "source": "SIPRI26", "quote": "1-8 x W88 x 455 kt"},
{"key": "w80-1-low", "name": "W80-1 cruise missile", "yield_kt": 5, "fission_fraction": 0.5, "status": "deployed", "source": "SIPRI26", "quote": "AGM-86B ALCMs x 5-150 kt"},
{"key": "w80-1-high", "name": "W80-1 cruise missile", "yield_kt": 150, "fission_fraction": 0.5, "status": "deployed", "source": "SIPRI26", "quote": "AGM-86B ALCMs x 5-150 kt"},
{"key": "b61-11", "name": "B61-11 earth-penetrating bomb", "yield_kt": 400, "fission_fraction": 0.5, "status": "deployed", "source": "SIPRI26", "quote": "Up to 16 x B61-11 x 400 kt"},
{"key": "b61-12-0.3", "name": "B61-12 bomb", "yield_kt": 0.3, "fission_fraction": 0.5, "status": "deployed", "source": "FAS16", "quote": "four selectable explosive yields: 0.3 kilotons (kt), 1.5 kt, 10 kt and 50 kt"},
{"key": "b61-12-1.5", "name": "B61-12 bomb", "yield_kt": 1.5, "fission_fraction": 0.5, "status": "deployed", "source": "FAS16", "quote": "four selectable explosive yields: 0.3 kilotons (kt), 1.5 kt, 10 kt and 50 kt"},
{"key": "b61-12-10", "name": "B61-12 bomb", "yield_kt": 10, "fission_fraction": 0.5, "status": "deployed", "source": "FAS16", "quote": "four selectable explosive yields: 0.3 kilotons (kt), 1.5 kt, 10 kt and 50 kt"},
{"key": "b61-12-50", "name": "B61-12 bomb", "yield_kt": 50, "fission_fraction": 0.5, "status": "deployed", "source": "US26", "quote": "maximum yield of approximately 50 kilotons and several lower-yield options"},
{"key": "b61-13", "name": "B61-13 bomb", "yield_kt": 360, "fission_fraction": 0.5, "status": "in production", "source": "US26", "quote": "will have a maximum yield close to the B61-7's 360 kilotons"},
{"key": "b83-1", "name": "B83-1 bomb", "yield_kt": 1200, "fission_fraction": 0.5, "status": "stockpile (being retired)", "source": "US26", "quote": "explosive yield of up to 1.2 megaton"}
]
},
{
"name": "Russia",
"weapons": [
{"key": "rs-20v", "name": "RS-20V Voevoda (SS-18) ICBM", "yield_kt": 800, "yield_range_kt": [500, 800], "fission_fraction": 0.5, "status": "deployed", "source": "RU26", "quote": "10 x 500-800 (MIRV)"},
{"key": "topol-m", "name": "Topol-M (SS-27 Mod 1) ICBM", "yield_kt": 800, "fission_fraction": 0.5, "status": "deployed", "source": "RU26", "quote": "1 x 800"},
{"key": "yars", "name": "RS-24 Yars (SS-27 Mod 2) ICBM", "yield_kt": 250, "yield_range_kt": [100, 250], "fission_fraction": 0.5, "status": "deployed", "source": "RU26, SIPRI26", "quote": "RU26: 3 x 100? (MIRV); SIPRI26: 1-3 x 250 kt"},
{"key": "sarmat", "name": "RS-28 Sarmat (SS-29) ICBM", "yield_kt": 500, "fission_fraction": 0.5, "status": "being deployed", "source": "RU26", "quote": "10 x 500? (MIRV)"},
{"key": "sineva", "name": "Sineva (SS-N-23) submarine missile", "yield_kt": 100, "fission_fraction": 0.5, "status": "deployed", "source": "RU26", "quote": "4 x 100 (MIRV)"},
{"key": "bulava", "name": "Bulava (SS-N-32) submarine missile", "yield_kt": 100, "fission_fraction": 0.5, "status": "deployed", "source": "RU26", "quote": "6 x 100 (MIRV)"},
{"key": "ru-alcm", "name": "Kh-55 / Kh-102 cruise missile", "yield_kt": 200, "fission_fraction": 0.5, "status": "deployed", "source": "SIPRI26", "quote": "Up to 14 x 200 kt ALCMs, bombs"},
{"key": "oreshnik", "name": "Oreshnik intermediate-range missile", "yield_kt": 250, "fission_fraction": 0.5, "status": "deployed", "source": "RU26", "quote": "6 x 250"},
{"key": "iskander-m", "name": "Iskander-M short-range missile", "yield_kt": 100, "yield_range_kt": [10, 100], "fission_fraction": 0.5, "status": "stockpile", "source": "RU26", "quote": "1 x 10-100"},
{"key": "9m729", "name": "9M729 (SSC-8) cruise missile", "yield_kt": 100, "yield_range_kt": [10, 100], "fission_fraction": 0.5, "status": "stockpile", "source": "RU26", "quote": "1 x 10-100"},
{"key": "redut", "name": "Redut coastal missile", "yield_kt": 350, "fission_fraction": 0.5, "status": "stockpile", "source": "RU26", "quote": "1 x 350"}
]
},
{
"name": "China",
"_note": "CN26 gives 425 kt for most warheads (updated from Zhang 2025); the 2024 table gave 200-300 kt for the same warheads.",
"weapons": [
{"key": "df-5a", "name": "DF-5A ICBM", "yield_kt": 4500, "yield_range_kt": [4000, 5000], "fission_fraction": 0.5, "status": "deployed", "source": "CN26, CN24", "quote": "CN26: 1 x 4.5 MT; CN24: 1 x 4,000-5,000"},
{"key": "df-5b", "name": "DF-5B ICBM", "yield_kt": 425, "yield_range_kt": [200, 425], "fission_fraction": 0.5, "status": "deployed", "source": "CN26, CN24", "quote": "CN26: Up to 5 x 425"},
{"key": "df-41", "name": "DF-41 ICBM", "yield_kt": 425, "yield_range_kt": [200, 425], "fission_fraction": 0.5, "status": "deployed", "source": "CN26, CN24", "quote": "CN26: Up to 3 x 425"},
{"key": "df-31", "name": "DF-31A / DF-31AG ICBM", "yield_kt": 425, "yield_range_kt": [200, 425], "fission_fraction": 0.5, "status": "deployed", "source": "CN26, CN24", "quote": "CN26: 1 x 425"},
{"key": "df-26", "name": "DF-26 intermediate-range missile", "yield_kt": 425, "yield_range_kt": [200, 425], "fission_fraction": 0.5, "status": "deployed", "source": "CN26, CN24", "quote": "CN26: 1 x 425; CN24: 1 x 200-300"},
{"key": "jl-3", "name": "JL-3 submarine missile", "yield_kt": 425, "fission_fraction": 0.5, "status": "deployed", "source": "CN26", "quote": "1 x 425"}
]
},
{
"name": "United Kingdom",
"weapons": [
{"key": "holbrook", "name": "Holbrook (Trident II D5)", "yield_kt": 100, "fission_fraction": 0.5, "status": "deployed", "source": "SIPRI26", "quote": "1-8 x 100 kt"}
]
},
{
"name": "France",
"_note": "SIPRI26: the TNA's yield is only bounded (less than 300 kt; MBDA calls it 'medium energy'), and it is thought to follow the TNO design, 150 kt. The old TN 81's 300 kt is not this warhead's.",
"weapons": [
{"key": "tno", "name": "TNO / TNO-2 (M51 submarine missile)", "yield_kt": 150, "fission_fraction": 0.5, "status": "deployed", "source": "SIPRI26", "quote": "4-6 x 150 kt TNO"},
{"key": "tna", "name": "TNA (ASMPA-R cruise missile)", "yield_kt": 150, "fission_fraction": 0.5, "status": "deployed", "source": "SIPRI26", "quote": "ASMPA-R/1 x [<300 kt]"}
]
},
{
"name": "India",
"_note": "IN26: the yields of India's nuclear warheads are not known, perhaps up to 40 kt.",
"weapons": [
{"key": "in-12", "name": "Bomb, Prithvi-II or K-15 (12 kt)", "yield_kt": 12, "fission_fraction": 1.0, "status": "deployed", "source": "IN26", "quote": "1 x 12 kt"},
{"key": "agni", "name": "Agni missiles", "yield_kt": 40, "yield_range_kt": [10, 40], "fission_fraction": 1.0, "status": "deployed", "source": "IN26", "quote": "1 x 10-40 kt"}
]
},
{
"name": "Pakistan",
"_note": "PK25: yields are based on the range measured in the 1998 nuclear tests.",
"weapons": [
{"key": "pk-short", "name": "Bomb or short-range missile", "yield_kt": 12, "yield_range_kt": [5, 12], "fission_fraction": 1.0, "status": "stockpile", "source": "PK25", "quote": "1 x 5-12 kt"},
{"key": "pk-medium", "name": "Shaheen-II / Ghauri missile", "yield_kt": 40, "yield_range_kt": [10, 40], "fission_fraction": 1.0, "status": "stockpile", "source": "PK25", "quote": "1 x 10-40 kt"}
]
},
{
"name": "North Korea",
"weapons": [
{"key": "kp-fission", "name": "Fission warhead", "yield_kt": 20, "yield_range_kt": [10, 20], "fission_fraction": 1.0, "status": "deployed", "source": "NK24", "quote": "single-stage fission weapons with yields possibly between 10 and 20 kilotons"}
]
},
{
"name": "Improvised nuclear device",
"weapons": [
{"key": "ind-1", "name": "Improvised device", "yield_kt": 1, "fission_fraction": 1.0, "status": "planning scenario", "source": "FEMA", "quote": "improvised nuclear devices of 0.1 to 10 kt detonated at ground level"},
{"key": "ind-10", "name": "Improvised device", "yield_kt": 10, "fission_fraction": 1.0, "status": "planning scenario", "source": "FEMA", "quote": "improvised nuclear devices of 0.1 to 10 kt detonated at ground level"}
]
}
],
"_omitted": [
"Avangard (Russia), Poseidon (Russia, not deployed), S-300/S-400 and 53T6 interceptors (Russia, air and missile defense), DF-5C, DF-61 and H-6N bombs (China), Israel's arsenal, North Korea's thermonuclear warhead: no source gives a yield.",
"W87-1, W93, SLCM-N (United States): not deployed, and no yield is given."
]
}

View file

@ -0,0 +1,61 @@
import {formatYield, formatYieldAndFission, WEAPON_GROUPS, WEAPON_SOURCES, weaponByKey} from './weapons.js';
const weapons = WEAPON_GROUPS.flatMap((g) => g.weapons);
describe('the weapons offered', () => {
test('each have a unique key and a yield', () => {
expect(new Set(weapons.map((w) => w.key)).size).toBe(weapons.length);
for (const w of weapons) {
expect(w.yield_kt).toBeGreaterThan(0);
if (w.yield_range_kt) {
const [low, high] = w.yield_range_kt;
expect(low).toBeLessThan(high);
expect(w.yield_kt).toBeGreaterThanOrEqual(low);
expect(w.yield_kt).toBeLessThanOrEqual(high);
}
expect(w.fission_fraction).toBeGreaterThan(0);
expect(w.fission_fraction).toBeLessThanOrEqual(1);
}
});
test('each quote their yield from a cited source', () => {
for (const w of weapons) {
expect(w.quote.length).toBeGreaterThan(3);
for (const key of w.source.split(', ')) expect(WEAPON_SOURCES[key]).toBeTruthy();
}
});
test('are below a yield their source gives only as an upper bound', () => {
for (const w of weapons) {
const bound = w.quote.match(/<\s*([\d.]+)\s*(kt|Mt)/);
if (!bound) continue;
const kt = Number(bound[1]) * (bound[2] === 'Mt' ? 1000 : 1);
expect(w.yield_kt).toBeLessThan(kt);
if (w.yield_range_kt) expect(w.yield_range_kt[1]).toBeLessThan(kt);
}
expect(weaponByKey('tna').yield_kt).toBe(150);
});
test('are in service today: none retired, none historical', () => {
for (const w of weapons) expect(w.status).not.toMatch(/retired$|historical|dismantled/i);
const historical = /little boy|fat man|tsar|ivy mike|castle|b53|b28|w56/i;
for (const w of weapons) expect(w.name).not.toMatch(historical);
});
test('are found by key, with their group', () => {
expect(weaponByKey('w88')).toMatchObject({yield_kt: 455, group: 'United States'});
expect(weaponByKey('nope')).toBeUndefined();
});
});
describe('a yield', () => {
test('is written in kilotons, or megatons from 1000 kt up', () => {
expect(formatYield(0.3)).toBe('0.3 kt');
expect(formatYield(455)).toBe('455 kt');
expect(formatYieldAndFission(300, 0.5)).toBe('300 kt, half fission');
expect(formatYieldAndFission(15, 1)).toBe('15 kt');
expect(formatYieldAndFission(100, 0.25)).toBe('100 kt, 25% fission');
expect(formatYield(1200)).toBe('1.2 Mt');
expect(formatYield(4500)).toBe('4.5 Mt');
});
});

View file

@ -0,0 +1,373 @@
// The field of forecast winds aloft (as the API gives it: modules/map/winds.py), as the fallout model
// reads it. Shared by the app's map viewer and the standalone viewer: no imports from the app, no
// dependencies.
//
// A field is {source, fetched_at, spacing (degrees), points: [{lat, lon, elevation}], hours: [time],
// winds: [for each point: [for each hour: [[height (m above sea level), speed (m/s), direction the
// wind blows FROM (degrees)]]]], rain: [for each point: [mm in each hour]]}. Its points are on whole
// multiples of its spacing.
//
// The model asks for the wind many times for every particle (where it is, how high, and when), so a
// field is first prepared: each point's winds, hour by hour, resampled to altitudes LEVEL_STEP apart.
// A wind is then read between the four points around a place, the two hours around a time, and the
// two altitudes around a height.
const METERS_PER_DEGREE = 111320;
const LEVEL_STEP = 250;
const LOWEST_LEVEL = -500;
const HIGHEST_LEVEL = 30000;
const LEVELS = Math.round((HIGHEST_LEVEL - LOWEST_LEVEL) / LEVEL_STEP) + 1;
// The hour of `hours` (UTC times) nearest `when` (a Date): its index.
export function nearestHour(hours, when = new Date()) {
let best = 0, gap = Infinity;
hours.forEach((time, i) => {
const g = Math.abs(Date.parse(time) - when.getTime());
if (g < gap) {
best = i;
gap = g;
}
});
return best;
}
// How old (hours) `field` was at `when`.
export function forecastAge(field, when = new Date()) {
return (when.getTime() - Date.parse(field.fetched_at)) / 3600000;
}
// Whether `field` runs out before `when`: the last hour it has is before it.
export function forecastExpired(field, when = new Date()) {
return Date.parse(field.hours[field.hours.length - 1]) < when.getTime();
}
// The hours a burst's fallout comes down in.
export const LANDING_HOURS = 48;
// When the forecast runs out for a burst at hour `index` of `field`: the time (ms) of its last hour, if
// that is before the burst's fallout is down (LANDING_HOURS after it), or null. From then on the
// last hour's winds are held.
export function forecastRunsOut(field, index) {
const last = Date.parse(field.hours[field.hours.length - 1]);
return Date.parse(field.hours[index]) + LANDING_HOURS * 3600000 > last ? last : null;
}
// Whether `field` has the winds for fallout from bursts at `when`: an hour within one of then, and
// the winds until all the fallout is down (LANDING_HOURS after). After that the fallout on the ground
// only weakens, which takes no winds.
export function forecastCoversFallout(field, when = new Date()) {
if (!field?.hours?.length) return false;
const index = nearestHour(field.hours, when);
if (Math.abs(Date.parse(field.hours[index]) - when.getTime()) > 3600000) return false;
return forecastRunsOut(field, index) === null;
}
// One point's winds in one hour, as east and north (m/s) at each altitude of the levels.
function resample(winds, u, v, offset) {
const sorted = [...winds].sort((a, b) => a[0] - b[0]);
const east = sorted.map(([, speed, from]) => -speed * Math.sin(from * Math.PI / 180));
const north = sorted.map(([, speed, from]) => -speed * Math.cos(from * Math.PI / 180));
let k = 0;
for (let l = 0; l < LEVELS; l++) {
const altitude = LOWEST_LEVEL + l * LEVEL_STEP;
while (k < sorted.length - 2 && sorted[k + 1][0] < altitude) k++;
let e, n;
if (sorted.length === 1 || altitude <= sorted[0][0]) {
e = east[0];
n = north[0];
} else if (altitude >= sorted[sorted.length - 1][0]) {
e = east[sorted.length - 1];
n = north[sorted.length - 1];
} else {
const f = (altitude - sorted[k][0]) / (sorted[k + 1][0] - sorted[k][0]);
e = east[k] + f * (east[k + 1] - east[k]);
n = north[k] + f * (north[k + 1] - north[k]);
}
u[offset + l] = e;
v[offset + l] = n;
}
}
// A field, prepared for reading winds from it quickly.
export function prepareField(field) {
const nPoints = field.points.length, nHours = field.hours.length;
const u = new Float32Array(nPoints * nHours * LEVELS);
const v = new Float32Array(nPoints * nHours * LEVELS);
for (let p = 0; p < nPoints; p++) {
for (let h = 0; h < nHours; h++) resample(field.winds[p][h], u, v, (p * nHours + h) * LEVELS);
}
// Each point's rain (mm in each hour) and the cloud it falls from ([bottom, top], m above sea
// level; NaN where there is none, or the field does not say).
const rain = new Float32Array(nPoints * nHours);
const cloudBottom = new Float32Array(nPoints * nHours).fill(NaN);
const cloudTop = new Float32Array(nPoints * nHours).fill(NaN);
let rains = false;
for (let p = 0; p < nPoints; p++) {
for (let h = 0; h < nHours; h++) {
const mm = field.rain?.[p]?.[h] || 0;
rain[p * nHours + h] = mm;
if (mm > 0) rains = true;
const cloud = field.clouds?.[p]?.[h];
if (cloud) {
cloudBottom[p * nHours + h] = cloud[0];
cloudTop[p * nHours + h] = cloud[1];
}
}
}
// The points by where they are on the world's grid of the field's spacing: rows and columns
// count whole spacings from the equator and the prime meridian (the points are on multiples of
// the spacing, which divides 360 but need not divide 90 or 180), rows from the south pole's.
const spacing = field.spacing;
const columns = Math.round(360 / spacing);
const rowOffset = Math.ceil(90 / spacing);
const rows = 2 * rowOffset + 1;
const index = new Int32Array(columns * rows).fill(-1);
field.points.forEach((point, p) => {
const row = Math.round(point.lat / spacing) + rowOffset;
const column = ((Math.round(point.lon / spacing) % columns) + columns) % columns;
index[row * columns + column] = p;
});
return {field, u, v, rain, cloudBottom, cloudTop, rains, nHours, spacing, columns, rows, rowOffset, index,
hoursMs: field.hours.map((t) => Date.parse(t))};
}
// The point of `prepared` at a grid row and column, or -1.
function pointAt(prepared, row, column) {
if (row < 0 || row >= prepared.rows) return -1;
const c = ((column % prepared.columns) + prepared.columns) % prepared.columns;
return prepared.index[row * prepared.columns + c];
}
// The degrees of longitude from `lon` east to `to`, -180 to 180, however far round the world either
// is (a particle may be carried round it).
function lonGap(to, lon) {
let gap = (to - lon + 540) % 360;
if (gap < 0) gap += 360;
return gap - 180;
}
// The point of `prepared` nearest `lat`, `lon`.
export function nearestPoint(prepared, lat, lon) {
let best = 0, gap = Infinity;
prepared.field.points.forEach((point, p) => {
const dLon = lonGap(point.lon, lon);
const g = (point.lat - lat) ** 2 + (dLon * Math.cos(lat * Math.PI / 180)) ** 2;
if (g < gap) {
best = p;
gap = g;
}
});
return best;
}
// The point of `prepared` nearest `lat`, `lon`, in its grid cell `row`, `column`: as nearestPoint
// finds it, but looking only through the points which can be nearest somewhere in the cell (kept for
// each cell). Particles carried past the field enter many cells, and looking through all the points
// for each was most of the time a burst took.
export function nearestAround(prepared, row, column, lat, lon) {
if (!prepared.nearCandidates) prepared.nearCandidates = new Map();
const key = row * 100000 + column;
let near = prepared.nearCandidates.get(key);
if (!near) {
near = candidatesOf(prepared, row, column);
prepared.nearCandidates.set(key, near);
}
const points = prepared.field.points;
let best = near[0], gap = Infinity;
// As nearestPoint reckons it, in the same order: the same point, even where two are as near.
for (const p of near) {
const point = points[p];
const dLon = lonGap(point.lon, lon);
const g = (point.lat - lat) ** 2 + (dLon * Math.cos(lat * Math.PI / 180)) ** 2;
if (g < gap) {
best = p;
gap = g;
}
}
return best;
}
// The points of `prepared` (in order) which can be the nearest somewhere in grid cell `row`,
// `column`: those which, at their nearest to the cell, are as near as the point nearest at its
// farthest.
function candidatesOf(prepared, row, column) {
const {spacing, rowOffset} = prepared;
const south = (row - rowOffset) * spacing, north = south + spacing;
const middle = (column + 0.5) * spacing, halfWidth = spacing / 2;
// How much a degree of longitude counts in the cell, at least and at most (by |cos(lat)|).
const scale = (degrees) => Math.abs(Math.cos(degrees * Math.PI / 180));
const crosses = (period, offset) => Math.floor((south - offset) / period) !== Math.floor((north - offset) / period);
const least = crosses(180, 90) ? 0 : Math.min(scale(south), scale(north));
const most = crosses(180, 0) ? 1 : Math.max(scale(south), scale(north));
const points = prepared.field.points;
const nearest = new Float64Array(points.length), farthest = new Float64Array(points.length);
let bound = Infinity;
points.forEach((point, p) => {
const dLat0 = Math.max(0, south - point.lat, point.lat - north);
const dLat1 = Math.max(Math.abs(point.lat - south), Math.abs(point.lat - north));
const d = Math.abs(lonGap(point.lon, middle));
const dLon0 = Math.max(0, d - halfWidth), dLon1 = Math.min(180, d + halfWidth);
nearest[p] = dLat0 ** 2 + (dLon0 * least) ** 2;
farthest[p] = dLat1 ** 2 + (dLon1 * most) ** 2;
bound = Math.min(bound, farthest[p]);
});
// A little past the bound: rounding is not to leave out a point which is as near.
const limit = bound * (1 + 1e-9) + 1e-12;
const near = [];
for (let p = 0; p < points.length; p++) if (nearest[p] <= limit) near.push(p);
return Int32Array.from(near);
}
// Whether `prepared` has points around `lat`, `lon` (all four of the grid cell it is in).
export function fieldCovers(prepared, lat, lon) {
const row = Math.floor(lat / prepared.spacing) + prepared.rowOffset;
const column = Math.floor(lon / prepared.spacing);
return [[0, 0], [1, 0], [0, 1], [1, 1]].every(([r, c]) => pointAt(prepared, row + r, column + c) >= 0);
}
// The winds of `prepared` as the model takes them for a burst at `lat0`, `lon0`, whose ground is
// `groundElevation` m above sea level, at `startMs` (a time): {at(x, y, z, t)}, the wind (east, north;
// m/s) x meters east and y north of ground zero, z meters above its ground, t seconds after the burst.
export function fieldWinds(prepared, {lat0, lon0, groundElevation = 0, startMs}) {
const {u, v, nHours, spacing, rowOffset, hoursMs} = prepared;
const perLon = METERS_PER_DEGREE * Math.cos(lat0 * Math.PI / 180);
const hour0 = hoursMs[0];
const corners = [[0, 0], [1, 0], [0, 1], [1, 1]];
let lastCell = null, cellPoints = null;
// One hour (a past day's): the winds hold through the hours, and are read without them.
if (nHours === 1) return {held: true, at: heldAt(prepared, lat0, lon0, perLon, groundElevation)};
return {
at(x, y, z, t) {
const lat = lat0 + y / METERS_PER_DEGREE;
const lon = lon0 + x / perLon;
const fr = lat / spacing + rowOffset, fc = lon / spacing;
const row = Math.floor(fr), column = Math.floor(fc);
const dr = fr - row, dc = fc - column;
// The points around a place are looked up once for every grid cell a particle is in.
const cell = row * 100000 + column;
if (cell !== lastCell) {
lastCell = cell;
cellPoints = corners.map(([r, c]) => pointAt(prepared, row + r, column + c));
if (cellPoints.every((p) => p < 0)) cellPoints = [nearestAround(prepared, row, column, lat, lon), -1, -1, -1];
}
const fh = Math.min(Math.max((startMs + t * 1000 - hour0) / 3600000, 0), nHours - 1);
const h0 = Math.min(Math.floor(fh), nHours - 2 < 0 ? 0 : nHours - 2), dh = nHours > 1 ? fh - h0 : 0;
const fl = Math.min(Math.max((groundElevation + z - LOWEST_LEVEL) / LEVEL_STEP, 0), LEVELS - 1.000001);
const l0 = Math.floor(fl), dl = fl - l0;
let east = 0, north = 0, weight = 0;
for (let k = 0; k < 4; k++) {
const p = cellPoints[k];
if (p < 0) continue;
const [r, c] = corners[k];
// A lone nearest point (outside the field) has all of the weight.
const w = cellPoints[1] < 0 && cellPoints[2] < 0 && cellPoints[3] < 0 && k === 0
? 1 : (r ? dr : 1 - dr) * (c ? dc : 1 - dc);
if (w <= 0) continue;
const base0 = (p * nHours + h0) * LEVELS + l0;
const base1 = base0 + (nHours > 1 ? LEVELS : 0);
const e0 = u[base0] + dl * (u[base0 + 1] - u[base0]), e1 = u[base1] + dl * (u[base1 + 1] - u[base1]);
const n0 = v[base0] + dl * (v[base0 + 1] - v[base0]), n1 = v[base1] + dl * (v[base1 + 1] - v[base1]);
east += w * (e0 + dh * (e1 - e0));
north += w * (n0 + dh * (n1 - n0));
weight += w;
}
return weight > 0 ? [east / weight, north / weight] : [0, 0];
},
// The rain (mm an hour) x meters east and y north of ground zero, t seconds after the burst,
// between the points around and the hours around, and the cloud it falls from at the
// nearest of them ([bottom, top], m above sea level, or null). Absent where the field has
// no rain at all.
...(prepared.rains ? {rainAt: (x, y, t) => rainAt(prepared, lat0 + y / METERS_PER_DEGREE, lon0 + x / perLon,
Math.min(Math.max((startMs + t * 1000 - hour0) / 3600000, 0), nHours - 1))} : {}),
};
}
// The point of `prepared` nearest the middle of a grid cell outside it, kept: particles carried far
// past the field enter many such cells.
function nearestOfCell(prepared, row, column) {
if (!prepared.nearestOfCell) prepared.nearestOfCell = new Map();
const cell = row * 100000 + column;
let p = prepared.nearestOfCell.get(cell);
if (p === undefined) {
p = nearestPoint(prepared, (row - prepared.rowOffset + 0.5) * prepared.spacing, (column + 0.5) * prepared.spacing);
prepared.nearestOfCell.set(cell, p);
}
return p;
}
// fieldWinds' at(x, y, z) of a field of one hour.
function heldAt(prepared, lat0, lon0, perLon, groundElevation) {
const {u, v, spacing, rowOffset} = prepared;
let lastCell = null, p00 = -1, p10 = -1, p01 = -1, p11 = -1, lone = false;
return (x, y, z) => {
const lat = lat0 + y / METERS_PER_DEGREE;
const lon = lon0 + x / perLon;
const fr = lat / spacing + rowOffset, fc = lon / spacing;
const row = Math.floor(fr), column = Math.floor(fc);
const dr = fr - row, dc = fc - column;
const cell = row * 100000 + column;
if (cell !== lastCell) {
lastCell = cell;
p00 = pointAt(prepared, row, column);
p10 = pointAt(prepared, row + 1, column);
p01 = pointAt(prepared, row, column + 1);
p11 = pointAt(prepared, row + 1, column + 1);
lone = p00 < 0 && p10 < 0 && p01 < 0 && p11 < 0;
if (lone) p00 = nearestOfCell(prepared, row, column);
}
const fl = Math.min(Math.max((groundElevation + z - LOWEST_LEVEL) / LEVEL_STEP, 0), LEVELS - 1.000001);
const l0 = Math.floor(fl), dl = fl - l0;
let east = 0, north = 0, weight = 0;
const add = (p, w) => {
if (p < 0 || w <= 0) return;
const b = p * LEVELS + l0;
east += w * (u[b] + dl * (u[b + 1] - u[b]));
north += w * (v[b] + dl * (v[b + 1] - v[b]));
weight += w;
};
if (lone) add(p00, 1);
else {
add(p00, (1 - dr) * (1 - dc));
add(p10, dr * (1 - dc));
add(p01, (1 - dr) * dc);
add(p11, dr * dc);
}
return weight > 0 ? [east / weight, north / weight] : [0, 0];
};
}
// The rain of `prepared` at `lat`, `lon`, `fh` hours into it: [mm an hour, cloud or null].
function rainAt(prepared, lat, lon, fh) {
const {rain, cloudBottom, cloudTop, nHours, spacing, rowOffset} = prepared;
const fr = lat / spacing + rowOffset, fc = lon / spacing;
const row = Math.floor(fr), column = Math.floor(fc), dr = fr - row, dc = fc - column;
const h0 = Math.min(Math.floor(fh), Math.max(nHours - 2, 0)), dh = nHours > 1 ? fh - h0 : 0;
const h1 = nHours > 1 ? h0 + 1 : h0;
let mm = 0, weight = 0, best = -1, bestWeight = -1;
for (const [r, c] of [[0, 0], [1, 0], [0, 1], [1, 1]]) {
const p = pointAt(prepared, row + r, column + c);
if (p < 0) continue;
const w = (r ? dr : 1 - dr) * (c ? dc : 1 - dc);
mm += w * (rain[p * nHours + h0] * (1 - dh) + rain[p * nHours + h1] * dh);
weight += w;
if (w > bestWeight) {
best = p;
bestWeight = w;
}
}
if (best < 0) {
best = nearestAround(prepared, row, column, lat, lon);
mm = rain[best * nHours + h0] * (1 - dh) + rain[best * nHours + h1] * dh;
weight = 1;
}
const k = best * nHours + (dh < 0.5 ? h0 : h1);
const cloud = Number.isFinite(cloudBottom[k]) ? [cloudBottom[k], cloudTop[k]] : null;
return [weight > 0 ? mm / weight : 0, cloud];
}
// How much rain (mm) the field has near `lat`, `lon` from hour `index` for `hours` hours: rain washes
// fallout down in places the model does not show.
export function rainNear(prepared, lat, lon, index, hours = 6) {
const rain = prepared.field.rain?.[nearestPoint(prepared, lat, lon)] || [];
return rain.slice(index, index + hours).reduce((a, mm) => a + (mm || 0), 0);
}

View file

@ -0,0 +1,340 @@
import {landingSpots, scavengingRate} from './model.js';
import {
fieldCovers,
fieldWinds,
forecastAge,
forecastCoversFallout,
forecastExpired,
forecastRunsOut,
nearestAround,
nearestHour,
nearestPoint,
prepareField,
rainNear,
} from './winds.js';
const HOURS = ['2026-11-22T00:00Z', '2026-11-22T01:00Z', '2026-11-22T02:00Z'];
const START = Date.parse(HOURS[0]);
// A field over 60-62 N, 150-148 W, every degree, whose wind at every point, hour and height is given
// by `wind(lat, lon, hour)` as [speed, from].
function field(wind = () => [10, 270], {lats = [60, 61, 62], lons = [-150, -149, -148], rain = 0} = {}) {
const points = [];
for (const lat of lats) for (const lon of lons) points.push({lat, lon, elevation: 0});
return {
source: 'Open-Meteo', fetched_at: '2026-11-22T00:30:00+00:00', spacing: 1, points, hours: HOURS,
winds: points.map(({lat, lon}) => HOURS.map((_, h) => {
const [speed, from] = wind(lat, lon, h);
return [[10, speed, from], [20000, speed, from]];
})),
rain: points.map(() => HOURS.map(() => rain)),
};
}
// The middle of the activity of `spots` (km east, km north of ground zero).
function middle(spots) {
let sx = 0, sy = 0, sum = 0;
for (const s of spots) {
sx += s.activity * s.x;
sy += s.activity * s.y;
sum += s.activity;
}
return [sx / sum / 1000, sy / sum / 1000];
}
describe('a field of winds aloft', () => {
test('finds the hour nearest a time, how old it is, and when it runs out', () => {
expect(nearestHour(HOURS, new Date('2026-11-22T00:20Z'))).toBe(0);
expect(nearestHour(HOURS, new Date('2026-11-22T00:40Z'))).toBe(1);
expect(nearestHour(HOURS, new Date('2026-11-23T00:00Z'))).toBe(2);
const f = field();
expect(forecastAge(f, new Date('2026-11-22T03:30Z'))).toBeCloseTo(3, 10);
expect(forecastExpired(f, new Date('2026-11-22T01:00Z'))).toBe(false);
expect(forecastExpired(f, new Date('2026-11-22T03:00Z'))).toBe(true);
});
test('knows when it ends before a burst\'s fallout is down', () => {
const hours = Array.from({length: 72}, (_, h) => new Date(START + h * 3600000).toISOString());
const f = {hours};
// A burst at the first hour has its 48 hours; one at the 30th does not.
expect(forecastRunsOut(f, 0)).toBeNull();
expect(forecastRunsOut(f, 23)).toBeNull();
expect(forecastRunsOut(f, 30)).toBe(Date.parse(hours[71]));
});
test('reads the wind as east and north; a west wind blows east', () => {
const winds = fieldWinds(prepareField(field()), {lat0: 61, lon0: -149, startMs: START});
const [east, north] = winds.at(0, 0, 1000, 0);
expect(east).toBeCloseTo(10, 4);
expect(north).toBeCloseTo(0, 4);
});
test('reads between the points around a place, between hours, and between heights', () => {
// The wind gets stronger to the east, and with time.
const prepared = prepareField(field((lat, lon, h) => [10 * (lon + 151) + h * 6, 270]));
const winds = fieldWinds(prepared, {lat0: 61, lon0: -149, startMs: START});
const perLon = 111320 * Math.cos(61 * Math.PI / 180);
expect(winds.at(0, 0, 1000, 0)[0]).toBeCloseTo(20, 3);
expect(winds.at(perLon / 2, 0, 1000, 0)[0]).toBeCloseTo(25, 3);
expect(winds.at(0, 0, 1000, 1800)[0]).toBeCloseTo(23, 3);
// Beyond its hours, the nearest.
expect(winds.at(0, 0, 1000, 99 * 3600)[0]).toBeCloseTo(32, 3);
// Calm below, windy above.
const sheared = field();
sheared.winds = sheared.winds.map((hours) => hours.map(() => [[0, 0, 270], [2000, 20, 270]]));
const up = fieldWinds(prepareField(sheared), {lat0: 61, lon0: -149, groundElevation: 500, startMs: START});
expect(up.at(0, 0, 500, 0)[0]).toBeCloseTo(10, 3);
});
test('knows where it reaches, and outside it uses the nearest point', () => {
const prepared = prepareField(field((lat, lon) => [lon === -148 ? 30 : 10, 270]));
expect(fieldCovers(prepared, 61.5, -148.5)).toBe(true);
expect(fieldCovers(prepared, 63.5, -148.5)).toBe(false);
expect(prepared.field.points[nearestPoint(prepared, 61.2, -147.6)]).toMatchObject({lat: 61, lon: -148});
const winds = fieldWinds(prepared, {lat0: 61, lon0: -140, startMs: START});
expect(winds.at(0, 0, 1000, 0)[0]).toBeCloseTo(30, 3);
// The points which can be nearest in each cell outside it are found once, and kept.
expect(prepared.nearCandidates.size).toBe(1);
expect(winds.at(0, 0, 3000, 600)[0]).toBeCloseTo(30, 3);
expect(prepared.nearCandidates.size).toBe(1);
});
test('finds the nearest point anywhere as quickly as it may, and the same one', () => {
// Points 3 degrees apart, some missing, near the antimeridian and the pole.
const points = [];
for (let lat = 63; lat <= 87; lat += 3) {
for (const lon of [168, 171, 174, 177, 180, -177, -174, -171]) {
if ((lat * 7 + lon) % 5 !== 0) points.push({lat, lon: lon === 180 ? -180 : lon, elevation: 0});
}
}
const prepared = prepareField({spacing: 3, points, hours: HOURS,
winds: points.map(() => HOURS.map(() => [[10, 10, 270]])), rain: points.map(() => HOURS.map(() => 0))});
let seed = 7;
const random = () => (seed = (seed * 16807) % 2147483647) / 2147483647;
for (let i = 0; i < 5000; i++) {
// Some carried round the world, more than once.
const lat = 40 + 50 * random(), lon = 140 + 80 * random() - (random() < 0.5 ? 360 : 0) + 360 * Math.floor(7 * random() - 3);
const row = Math.floor(lat / 3) + prepared.rowOffset, column = Math.floor(lon / 3);
expect(nearestAround(prepared, row, column, lat, lon)).toBe(nearestPoint(prepared, lat, lon));
}
// Each cell's points looked through are kept, and are fewer than all of them.
const kept = [...prepared.nearCandidates.values()];
expect(Math.max(...kept.map((near) => near.length))).toBeLessThan(points.length);
});
test('outside it, rains as its nearest point does', () => {
const prepared = prepareField(field(() => [10, 270], {rain: 4}));
const winds = fieldWinds(prepared, {lat0: 61, lon0: -140, startMs: START});
expect(winds.rainAt(0, 0, 0)[0]).toBeCloseTo(4, 6);
expect(prepared.nearCandidates.size).toBe(1);
});
test('wraps at the antimeridian', () => {
const prepared = prepareField(field((lat, lon) => [lon === 179 ? 10 : 20, 270],
{lats: [51, 52], lons: [179, -180]}));
expect(fieldCovers(prepared, 51.5, 179.5)).toBe(true);
const winds = fieldWinds(prepared, {lat0: 51.5, lon0: 179.5, startMs: START});
expect(winds.at(0, 0, 1000, 0)[0]).toBeCloseTo(15, 3);
});
test('reads a point\'s own wind there, and half of each between two, at spacings which do not divide 90', () => {
for (const spacing of [4, 8]) {
const lats = [32, 32 + spacing, 32 + 2 * spacing], lons = [-120, -120 + spacing, -120 + 2 * spacing];
const f = field((lat, lon) => [lat + (lon + 200) / 1000, 270], {lats, lons});
f.spacing = spacing;
const prepared = prepareField(f);
const at = (lat, lon) => fieldWinds(prepared, {lat0: lat, lon0: lon, startMs: START}).at(0, 0, 1000, 0)[0];
const own = (lat, lon) => lat + (lon + 200) / 1000;
expect(at(lats[1], lons[1])).toBeCloseTo(own(lats[1], lons[1]), 4);
expect(at(lats[1] + spacing / 2, lons[1])).toBeCloseTo((own(lats[1], lons[1]) + own(lats[2], lons[1])) / 2, 4);
expect(at(lats[1], lons[1] + spacing / 2)).toBeCloseTo((own(lats[1], lons[1]) + own(lats[1], lons[2])) / 2, 4);
expect(fieldCovers(prepared, lats[1] + 1, lons[1] + 1)).toBe(true);
expect(fieldCovers(prepared, lats[2] + 1, lons[1] + 1)).toBe(false);
}
});
test('adds up the rain near a place', () => {
expect(rainNear(prepareField(field(undefined, {rain: 0.5})), 61, -149, 1, 6)).toBeCloseTo(1, 10);
});
});
describe('fallout in a field of winds', () => {
test('a field of one wind lands the fallout where that wind does', () => {
const steady = landingSpots({yieldKt: 10, profile: [[0, 10, 0]]});
const fromField = landingSpots({
yieldKt: 10, winds: fieldWinds(prepareField(field()), {lat0: 61, lon0: -149, startMs: START}),
});
const [a, b] = [middle(steady), middle(fromField)];
expect(Math.abs(b[0] / a[0] - 1)).toBeLessThan(0.01);
expect(Math.abs(b[1])).toBeLessThan(0.5);
});
test('meets the ground where that wind does, over a ridge', () => {
// A slope from 100 km downwind up to a ridge 3 km high at 130 km: what falls below its top
// lands on it.
const terrain = {lowest: 0, ground: (x) => Math.min(Math.max((x - 100000) / 10, 0), 3000)};
const steady = landingSpots({yieldKt: 10, profile: [[0, 10, 0]], terrain});
const fromField = landingSpots({
yieldKt: 10, terrain, winds: fieldWinds(prepareField(field()), {lat0: 61, lon0: -149, startMs: START}),
});
const onRidge = (spots) => spots.filter((s) => s.x > 100000 && s.x < 131000)
.reduce((a, s) => a + s.activity, 0);
expect(onRidge(steady)).toBeGreaterThan(0.01);
expect(Math.abs(onRidge(fromField) / onRidge(steady) - 1)).toBeLessThan(0.1);
});
test('the plume turns where the wind turns', () => {
// West winds west of 149 W, south winds east of it: fallout carried east, about 100 km, is then
// carried north, and goes no further east.
const turning = field((lat, lon) => [10, lon <= -149 ? 270 : 180],
{lats: [60, 61, 62, 63, 64, 65], lons: [-151, -150, -149, -148, -147, -146]});
const spots = landingSpots({
yieldKt: 100, winds: fieldWinds(prepareField(turning), {lat0: 61, lon0: -150.9, startMs: START}),
});
const far = spots.filter((s) => Math.hypot(s.x, s.y) > 200000);
expect(far.length).toBeGreaterThan(0);
expect(Math.max(...far.map((s) => s.x))).toBeLessThan(160000);
expect(middle(far)[1]).toBeGreaterThan(150);
});
test('the plume turns when the wind turns', () => {
// West winds for the first hour, then south winds.
const later = field((lat, lon, h) => [10, h === 0 ? 270 : 180], {lats: [58, 59, 60, 61, 62, 63, 64]});
const spots = landingSpots({
yieldKt: 100, winds: fieldWinds(prepareField(later), {lat0: 61, lon0: -149, startMs: START}),
});
const late = spots.filter((s) => s.hours > 3);
expect(middle(late)[1]).toBeGreaterThan(middle(late)[0]);
});
});
describe('rain', () => {
// The hours for half to be taken out at a rate (per second).
const half = (rate) => Math.LN2 / rate / 3600;
test('takes fallout out of the air as Glasstone has it', () => {
const cloud = [1000, 5000];
// Inside the rain cloud, half in 0.16 hour whatever the rain.
expect(half(scavengingRate(1, 3000, cloud))).toBeCloseTo(0.16, 6);
expect(half(scavengingRate(20, 3000, cloud))).toBeCloseTo(0.16, 6);
// Below it, half in 19, 3.8 and 1.9 hours of light, moderate and heavy rain.
expect(half(scavengingRate(1.27, 500, cloud))).toBeCloseTo(19, 6);
expect(half(scavengingRate(5.08, 500, cloud))).toBeCloseTo(3.8, 6);
expect(half(scavengingRate(11.94, 500, cloud))).toBeCloseTo(1.9, 6);
// Between and beyond them, more rain takes more.
expect(scavengingRate(3, 500, cloud)).toBeGreaterThan(scavengingRate(2, 500, cloud));
expect(scavengingRate(30, 500, cloud)).toBeGreaterThan(scavengingRate(11.94, 500, cloud));
// Above the rain cloud, and without rain, none; where the cloud is not known, washout.
expect(scavengingRate(10, 6000, cloud)).toBe(0);
expect(scavengingRate(0, 3000, cloud)).toBe(0);
expect(half(scavengingRate(5.08, 3000, null))).toBeCloseTo(3.8, 6);
});
// A field of west winds, rain falling from a cloud 1 to 4 km high where `raining(lat, lon)`.
function rainy(raining, mm = 5) {
const f = field(undefined, {lats: [59, 60, 61, 62, 63], lons: [-150, -149, -148, -147, -146, -145, -144, -143]});
f.rain = f.points.map(({lat, lon}) => HOURS.map(() => (raining(lat, lon) ? mm : 0)));
f.clouds = f.points.map(() => HOURS.map(() => [1000, 4000]));
return f;
}
const run = (f, maxHours = 48) => landingSpots({yieldKt: 10, maxHours,
winds: fieldWinds(prepareField(f), {lat0: 61, lon0: -149.5, startMs: START})});
const total = (spots) => spots.reduce((a, s) => a + s.activity, 0);
const between = (spots, x0, x1) => total(spots.filter((s) => s.x >= x0 && s.x < x1));
test('moves fallout, but does not make or lose any', () => {
// However long it takes to come down: without rain, the finest takes longer than 48 hours.
const dry = run(rainy(() => false), 1e6);
const wet = run(rainy(() => true), 1e6);
expect(dry.some((s) => s.wet)).toBe(false);
expect(wet.some((s) => s.wet)).toBe(true);
expect(total(wet)).toBeCloseTo(total(dry), 10);
// In 48 hours, rain brings down some of what would still be in the air.
expect(total(run(rainy(() => true)))).toBeGreaterThan(total(run(rainy(() => false))));
// Taken out on the way, it comes down sooner, and nearer.
const reach = (spots) => spots.reduce((a, s) => a + s.activity * s.x, 0) / total(spots);
expect(reach(wet)).toBeLessThan(reach(dry) * 0.8);
});
test('brings fallout down where it rains: a hot spot downwind', () => {
// Rain at the points from 147 W to 145 W: read between the points, it falls from 148 W to
// 144 W, about 80 to 300 km downwind.
const dry = run(rainy(() => false));
const band = run(rainy((lat, lon) => lon >= -147 && lon <= -145));
const perLon = 111320 * Math.cos(61 * Math.PI / 180);
const [x0, x1] = [(-148 + 149.5) * perLon, (-144 + 149.5) * perLon];
expect(between(band, x0, x1)).toBeGreaterThan(between(dry, x0, x1) * 1.5);
// Taken out on the way, less is left to come down beyond it.
expect(between(band, x1, 1e7)).toBeLessThan(between(dry, x1, 1e7) * 0.7);
// Upwind of the rain, nothing changes.
expect(between(band, -1e6, x0 - 30000)).toBeCloseTo(between(dry, -1e6, x0 - 30000), 10);
});
});
describe('a field of one hour (a past day\'s)', () => {
// Winds which change from place to place, but not from hour to hour.
const wind = (lat, lon) => [10 + (lat - 60) * 5 + (lon + 150) * 3, 250];
const hours = field(wind);
const oneHour = {...hours, hours: [HOURS[0]], winds: hours.winds.map((w) => [w[0]]), rain: hours.rain.map(() => [0])};
test('holds its winds through the hours, as read from a field of the same winds every hour', () => {
const held = fieldWinds(prepareField(oneHour), {lat0: 61, lon0: -149, startMs: START});
const each = fieldWinds(prepareField(hours), {lat0: 61, lon0: -149, startMs: START});
expect(held.held).toBe(true);
expect(each.held).toBeUndefined();
for (const [x, y, z] of [[0, 0, 0], [20000, -30000, 5000], [-45000, 50000, 15000], [10000, 10000, 30000]]) {
const [e1, n1] = held.at(x, y, z, 3600);
const [e2, n2] = each.at(x, y, z, 3600);
expect(e1).toBeCloseTo(e2, 6);
expect(n1).toBeCloseTo(n2, 6);
}
// Far past the field: the wind of its nearest point.
const [e, n] = held.at(0, 900000, 5000, 0);
const [speed] = wind(62, -149);
expect(Math.hypot(e, n)).toBeCloseTo(speed, 6);
});
test('carries a burst\'s fallout where the full model does, with the paths kept', () => {
const winds = fieldWinds(prepareField(oneHour), {lat0: 60.5, lon0: -149.5, startMs: START});
for (const yieldKt of [15, 250, 1000]) {
const held = landingSpots({yieldKt, winds});
const full = landingSpots({yieldKt, winds: {...winds, held: false}});
expect(held.length).toBe(full.length);
const sum = (spots) => spots.reduce((a, s) => a + s.activity, 0);
expect(sum(held)).toBeCloseTo(sum(full), 10);
const [hx, hy] = middle(held), [fx, fy] = middle(full);
const reach = Math.hypot(fx, fy);
expect(reach).toBeGreaterThan(50);
expect(Math.hypot(hx - fx, hy - fy) / reach).toBeLessThan(0.01);
// Spot by spot: the winds over ground zero carry the rising cloud (which drifts about
// 10 km) much as the winds where it is.
const apart = Math.max(...held.map((s, i) => Math.hypot(s.x - full[i].x, s.y - full[i].y)));
expect(apart).toBeLessThan(4000);
}
// Kept: a second burst of the same yield gives the same spots.
expect(landingSpots({yieldKt: 250, winds})).toEqual(landingSpots({yieldKt: 250, winds}));
});
});
describe('a forecast covering the fallout', () => {
// 60 hours from START.
const long = {hours: Array.from({length: 60}, (_, h) => new Date(START + h * 3600000).toISOString())};
const at = (hours) => new Date(START + hours * 3600000);
test('has the winds from now until all the fallout is down', () => {
expect(forecastCoversFallout(long, at(0))).toBe(true);
expect(forecastCoversFallout(long, at(11.4))).toBe(true);
// Its last hour (59) is before the fallout of bursts at 12 is down (48 hours after).
expect(forecastCoversFallout(long, at(12))).toBe(false);
});
test('has an hour near now', () => {
expect(forecastCoversFallout(long, at(-2))).toBe(false);
expect(forecastCoversFallout(long, at(70))).toBe(false);
expect(forecastCoversFallout({hours: HOURS}, at(0))).toBe(false);
expect(forecastCoversFallout(null)).toBe(false);
expect(forecastCoversFallout({hours: []})).toBe(false);
});
});

View file

@ -0,0 +1,148 @@
// The fallout's work, as the page or a worker (fallout.worker.js, by pool.js) does it: the same
// functions either way, so the fallout is the same. No imports from the app.
import {climateDay, parseClimatology, reachedCells} from './climatology.js';
import {depositionGrid, gridFrame, landingSpots, sharpening} from './model.js';
import {terrainAround} from './terrain.js';
import {fieldWinds, nearestPoint} from './winds.js';
// The winds over bursts, from `winds`: {prepared (a field, as prepareField gives it), startMs}, each
// burst carried by the winds where it is from that time; or {profile}, one profile over them all.
// {windsFor(burst, groundElevation), as landingSpots takes them; groundOf(burst), how high (m) its
// ground is until the terrain is read: the field's ground near it, or the sea's}.
export function burstWinds({prepared = null, startMs = 0, profile = null}) {
if (!prepared) return {windsFor: () => ({profile}), groundOf: () => 0};
return {
windsFor: (b, groundElevation) => ({winds: fieldWinds(prepared, {lat0: b.lat, lon0: b.lon, groundElevation, startMs})}),
groundOf: (b) => prepared.field.points[nearestPoint(prepared, b.lat, b.lon)].elevation,
};
}
// `prepared` (a field, as prepareField gives it) as a worker is sent it: its arrays and points, not
// the forecast as fetched (copying its nested lists to each worker was slow), nor what was kept from
// reading it.
export function portablePrepared(prepared) {
if (!prepared) return null;
// eslint-disable-next-line no-unused-vars
const {field, nearestOfCell, nearCandidates, ...arrays} = prepared;
return {...arrays, field: {hours: field.hours, points: field.points.map(({lat, lon, elevation}) => ({lat, lon, elevation}))}};
}
// Where the fallout of `burst` lands, in `windsFor` (as burstWinds gives them), over `terrain` (an
// elevation grid, as terrain.js reads it) or flat ground from `groundOf(burst)`: {spots (those on
// the map), offMap (whether some were not)}.
export function burstSpots(burst, {windsFor, groundOf, terrain = null}) {
const around = terrain ? terrainAround(terrain, burst.lon, burst.lat) : null;
const ground = around ? around.elevation : groundOf(burst);
const spots = landingSpots({yieldKt: burst.yieldKt, ...windsFor(burst, ground), terrain: around,
siteElevation: Math.max(ground, 0)});
// A spot not on the map (from ground with no number under it) would break the whole grid.
const finite = spots.filter((s) => Number.isFinite(s.x) && Number.isFinite(s.y) && s.sigma > 0);
return {spots: finite, offMap: finite.length < spots.length};
}
// How many parts the bursts' grid is made in (by as many workers, at most). Always as many, by the
// page or by workers: the parts are added up in the same order, so the grid is the same.
export const GRID_PARTS = 6;
// The spots of bursts (as combineBursts gives them, each with its `run`) in GRID_PARTS parts of
// about as many spots, a burst's spots all in one part (sharpening looks at a burst's at once).
export function gridParts(spots) {
const runs = new Map();
for (const s of spots) {
if (!runs.has(s.run)) runs.set(s.run, []);
runs.get(s.run).push(s);
}
const parts = Array.from({length: GRID_PARTS}, () => []);
// The largest first, each to the part with the fewest so far.
for (const run of [...runs.values()].sort((a, b) => b.length - a.length)) {
let least = 0;
for (let p = 1; p < GRID_PARTS; p++) if (parts[p].length < parts[least].length) least = p;
for (const s of run) parts[least].push(s);
}
return parts.filter((p) => p.length);
}
// The frame (as gridFrame gives it) of the bursts' grid, of their `spots`: as far as the faintest
// band drawn, `floor` (R/hr at H+1); no further, where nothing would show.
export function burstsFrame(spots, floor) {
return gridFrame(spots, {yieldKt: 1, boundsFloor: floor});
}
// One part of the bursts' grid, on `frame`: the dose rates of the part's `spots`, and how much they
// sharpen each cell (or null), as Float64Arrays.
export function gridPart(frame, spots) {
return {values: depositionGrid(spots, {yieldKt: 1, frame}).values, extra: sharpening(frame, spots)};
}
// The bursts' grid from its parts (in order): the dose rates added up, and each cell sharpened by
// the most any part sharpens it. The hot fallout close to a small burst is not averaged away in a
// grid over them all (sharpenGrid).
export function joinParts(frame, parts) {
const values = new Float64Array(frame.nx * frame.ny);
const extra = new Float64Array(frame.nx * frame.ny);
for (const part of parts) {
for (let k = 0; k < values.length; k++) values[k] += part.values[k];
if (part.extra) for (let k = 0; k < extra.length; k++) if (part.extra[k] > extra[k]) extra[k] = part.extra[k];
}
for (let k = 0; k < values.length; k++) values[k] += extra[k];
return {...frame, values};
}
// How many bursts of a day a worker does between the progress it reports.
const PROGRESS_EVERY = 8;
// The tasks of a worker, from what pool.js starts it with, `start`: `kind` 'days' (a past day each:
// `bytes`, the month unzipped; `bursts`; `rate`), 'bursts' (a burst each: `bursts`; `prepared` (a
// forecast, as portablePrepared gives it) and `startMs`, or `profile`; `terrain`, or null), or 'grid' (a part of the bursts' grid
// each, on `frame`; the task gives its `spots`). (task, progress(done)) => {result, transfer (what
// of it to transfer), done}.
function tasksOf(start) {
if (start.kind === 'days') {
const clim = parseClimatology(new Uint8Array(start.bytes));
const {bursts, rate} = start;
return async ({k}, progress) => {
let done = 0;
const grid = await climateDay(clim, k, bursts, {
onBurst: () => {
if (++done % PROGRESS_EVERY === 0) progress(done);
},
});
const reached = reachedCells(grid, rate);
return {result: reached, transfer: [reached.indexes.buffer], done};
};
}
if (start.kind === 'grid') {
return async ({spots}) => {
const part = gridPart(start.frame, spots);
return {result: part, transfer: [part.values.buffer, ...(part.extra ? [part.extra.buffer] : [])], done: 1};
};
}
const {bursts, prepared, startMs, profile, terrain} = start;
const winds = burstWinds({prepared, startMs, profile});
return async ({k}) => ({result: burstSpots(bursts[k], {...winds, terrain}), transfer: [], done: 1});
}
// Answer pool.js's messages to a worker, `scope` (its self): 'start' says what the tasks need; each
// 'task' (`k`, and what else it needs) it does, saying how much of it it has done ('progress'), then its result ('done'), or
// why it could not ('error').
export function serveFallout(scope) {
let task = null;
scope.onmessage = async ({data}) => {
if (data.type === 'start') {
try {
task = tasksOf(data);
} catch (e) {
scope.postMessage({type: 'error', message: String(e?.stack || e)});
}
return;
}
if (data.type !== 'task' || !task) return;
const {k} = data;
try {
const {result, transfer, done} = await task(data, (n) => scope.postMessage({type: 'progress', k, done: n}));
scope.postMessage({type: 'done', k, done, result}, transfer);
} catch (e) {
scope.postMessage({type: 'error', k, message: String(e?.stack || e)});
}
};
}

View file

@ -0,0 +1,42 @@
import {depositionGrid, profileFromTable, sharpenGrid} from './model.js';
import {combineBursts} from './targets.js';
import {burstsFrame, burstSpots, burstWinds, GRID_PARTS, gridPart, gridParts, joinParts} from './work.js';
describe('the bursts\' grid, in parts', () => {
const winds = burstWinds({profile: profileFromTable([[0, 270, 20], [30000, 260, 50]], 0)});
const bursts = Array.from({length: 9}, (_, i) => ({lat: 35 + 0.3 * i, lon: -110 + 0.6 * i, yieldKt: [1, 20, 300][i % 3],
fissionFraction: 0.5}));
const spots = combineBursts(bursts[0], bursts.map((b) => ({burst: b, spots: burstSpots(b, winds).spots,
yieldKt: b.yieldKt, fissionFraction: b.fissionFraction})));
test('keeps each burst\'s spots in one part, and every spot once', () => {
const parts = gridParts(spots);
expect(parts.length).toBe(GRID_PARTS);
expect(parts.reduce((n, p) => n + p.length, 0)).toBe(spots.length);
const partOf = new Map();
parts.forEach((p, i) => p.forEach((s) => {
expect(partOf.get(s.run) ?? i).toBe(i);
partOf.set(s.run, i);
}));
expect(partOf.size).toBe(bursts.length);
});
test('is the grid of all the spots at once, sharpened', () => {
const frame = burstsFrame(spots, 1);
const joined = joinParts(frame, gridParts(spots).map((p) => gridPart(frame, p)));
const whole = sharpenGrid(depositionGrid(spots, {yieldKt: 1, boundsFloor: 1}), spots);
expect([joined.x0, joined.y0, joined.cell, joined.nx, joined.ny]).toEqual([whole.x0, whole.y0, whole.cell, whole.nx, whole.ny]);
let most = 0, gap = 0;
for (let k = 0; k < whole.values.length; k++) {
most = Math.max(most, whole.values[k]);
gap = Math.max(gap, Math.abs(joined.values[k] - whole.values[k]));
}
expect(most).toBeGreaterThan(100);
// The same but for the order the numbers are added in.
expect(gap).toBeLessThan(most * 1e-12);
// And the narrow hot spots are kept: sharper than the plain grid.
const plain = depositionGrid(spots, {yieldKt: 1, frame});
const peak = (g) => g.values.reduce((a, v) => Math.max(a, v), 0);
expect(peak(joined)).toBeGreaterThan(peak(plain) * 1.01);
});
});

View file

@ -5,7 +5,8 @@ from sanic import Request, response, Blueprint
from sanic_ext import validate
from sanic_ext.extensions.openapi import openapi
from modules.map import export, export_job, lib, quads, schema, search
from modules.map import climatology, export, export_job, lib, quads, schema, search, winds
from modules.map.nuclear import TargetsChanged, get_map_nuclear_config
from modules.map.pins import get_map_pins_config
from modules.map.sheet import legend_as_sent
from wrolpi.api_utils import json_response
@ -119,6 +120,33 @@ async def update_pin(_: Request, pin_id: int, body: schema.MapPinUpdateRequest):
return response.json({'error': 'Pin not found'}, HTTPStatus.NOT_FOUND)
@map_bp.get('/nuclear/targets')
@openapi.description('Get the saved nuclear targets')
def get_targets(_: Request):
return json_response(dict(targets=get_map_nuclear_config().targets), HTTPStatus.OK)
@map_bp.put('/nuclear/targets')
@openapi.description('Save the nuclear targets: the ones given replace the saved ones, which must be those loaded')
@validate(schema.MapTargetsRequest)
async def put_targets(_: Request, body: schema.MapTargetsRequest):
try:
targets = get_map_nuclear_config().replace_targets(body.targets, body.loaded_ids)
except TargetsChanged as e:
return response.json({'error': str(e)}, HTTPStatus.CONFLICT)
except ValueError as e:
return response.json({'error': str(e)}, HTTPStatus.BAD_REQUEST)
return json_response(dict(targets=targets), HTTPStatus.OK)
@map_bp.delete('/nuclear/targets/<target_id:int>')
@openapi.description('Delete a saved nuclear target by ID')
async def delete_target(_: Request, target_id: int):
if get_map_nuclear_config().delete_target(target_id):
return response.empty(HTTPStatus.NO_CONTENT)
return response.json({'error': 'Target not found'}, HTTPStatus.NOT_FOUND)
@map_bp.get('/search')
@openapi.description('Search for places in map search indexes')
async def search_places(request: Request):
@ -318,3 +346,50 @@ async def get_export_pdf(_: Request, export_id: str):
except EXPORT_ERRORS as e:
return _export_error(e)
return await response.file(pdf, mime_type='application/pdf', filename='map.pdf')
@map_bp.get('/fallout/climatology')
@openapi.description('Which months of the fallout climatology (30 past days of winds each) are kept')
def get_fallout_climatology(_: Request):
return json_response(climatology.status(), HTTPStatus.OK)
@map_bp.get('/fallout/climatology/<month:int>')
@openapi.description('One month of the fallout climatology, as kept (gzip)')
async def get_fallout_climatology_month(_: Request, month: int):
path = climatology.month_path(month)
if not path:
return response.json({'error': f'Month {month} of the climatology is not kept'}, HTTPStatus.NOT_FOUND)
return await response.file(path, mime_type='application/octet-stream')
@map_bp.get('/fallout/winds/latest')
@openapi.description('The field of forecast winds aloft fetched most recently')
def get_latest_fallout_winds(_: Request):
return json_response(dict(winds=winds.latest_field()), HTTPStatus.OK)
@map_bp.get('/weather')
@openapi.description('The weather subscription: whether it is on, its download, and the forecast kept')
def get_weather(request: Request):
return json_response(winds.weather_status(request.ctx.session), HTTPStatus.OK)
@map_bp.put('/weather')
@openapi.description('Subscribe to the weather (a forecast around the nuclear targets, every day), or not')
@validate(schema.MapWeatherRequest)
@wrol_mode_check
async def put_weather(request: Request, body: schema.MapWeatherRequest):
with request.ctx.db.write() as session:
winds.set_weather_subscription(session, bool(body.enabled))
return json_response(winds.weather_status(request.ctx.session), HTTPStatus.OK)
@map_bp.post('/weather/download')
@openapi.description('Download the weather now, rather than when it is next due')
@wrol_mode_check
async def post_weather_download(request: Request):
with request.ctx.db.write() as session:
if not winds.download_weather_now(session):
return response.json({'error': 'The weather is not subscribed to'}, HTTPStatus.BAD_REQUEST)
return json_response(winds.weather_status(request.ctx.session), HTTPStatus.OK)

134
modules/map/climatology.py Normal file
View file

@ -0,0 +1,134 @@
"""The fallout simulator's climatology: the winds aloft of 30 real days of each month, the whole
world (built by wrolpi/scripts/build_fallout_climatology.py from NOAA's reanalysis). With no
forecast to go on, the simulator runs a burst in each of a month's days and shows how often its
fallout lands where.
The month files are fetched once from the release download location, while there is the Internet,
and each is checked against the sha256 pinned here before it is kept. From then on it is used
offline.
"""
import asyncio
import hashlib
from pathlib import Path
from typing import List, Optional
from modules.map.lib import get_map_directory
from wrolpi import flags
from wrolpi.api_utils import perpetual_signal
from wrolpi.common import aiohttp_get, logger, wrol_mode_enabled
logger = logger.getChild(__name__)
VERSION = 1
BASE_URL = f'https://wrolpi.nyc3.cdn.digitaloceanspaces.com/fallout/climatology-v{VERSION}'
# The sha256 of each month's file (wrolpi/scripts/build_fallout_climatology.py prints them).
MONTHS = {
1: '245d5eed9b7ca292e88f99885a93d9fe0ddb67ff7b7d8efea2eae038426892d6',
2: '6b54b071357f50bfa35949242e80198248ef8e64d687ce76e4a82af631c439bd',
3: 'bc116ea3477aac20b557e704702248edb4160eaadd4abbea3cab4f0a21bfb4b1',
4: '22662792dd7afe4ebbceb821c507aaafc3b0c87429f792c6e32990f4d041df46',
5: '48a4d9bbaaec72b1b8b91f81c9710c9f170bd099a0bb93267df9b57f950da6c2',
6: '5da9c91788d89f31e0443e966e8258049495eb8f65c70d621a355205e74a8d4b',
7: '371d0959c7b14d3f3fb96001b73535dc40f52a83651ce1e507b786c32fcd7996',
8: '6cd5de2d9bdbf8156a8cc78b4c84b2eed8cb4690cbf5234a9751d28b676dc213',
9: 'b12b75249fc56d1bd3e63440588a75ceb35e95dacf20d941345d410ed1c8a8d3',
10: '23c58a03d7e0f1eb8db92de36d43a6623c32cfa6ebfd230ccfd737c42b94aea3',
11: '7adb5825f4330d8e82f79cd05b7b41291308f754025766ef69289a2684a5ec1b',
12: 'd76941dccfac0e997b6cd804b43efd05e5d09ae333efe3380df2bef6eb645784',
}
TIMEOUT = 300
# How often (s) missing months are looked for.
CHECK_SECONDS = 3600
class ClimatologyError(Exception):
"""A month could not be fetched, or was not what it should be."""
def climatology_directory() -> Path:
"""Where the months are kept: a hidden directory, which the file lists and search skip."""
directory = get_map_directory() / '.fallout-climatology' / f'v{VERSION}'
directory.mkdir(parents=True, exist_ok=True)
return directory
def month_name(month: int) -> str:
return f'month-{month:02d}.bin.gz'
def month_path(month: int) -> Optional[Path]:
"""The kept file of `month`, or None."""
if month not in MONTHS:
return None
path = climatology_directory() / month_name(month)
return path if path.is_file() else None
def months_kept() -> List[int]:
return [month for month in MONTHS if month_path(month)]
def status() -> dict:
kept = months_kept()
return dict(version=VERSION, months=kept, missing=[m for m in MONTHS if m not in kept],
published=all(MONTHS.values()))
async def fetch_month(month: int) -> Path:
"""Fetch `month` from the release download location, check it, and keep it."""
expected = MONTHS.get(month)
if not expected:
raise ClimatologyError(f'No sha256 is known for month {month}')
url = f'{BASE_URL}/{month_name(month)}'
try:
async with aiohttp_get(url, timeout=TIMEOUT) as response:
if response.status != 200:
raise ClimatologyError(f'{url} answered HTTP {response.status}')
data = await response.read()
except ClimatologyError:
raise
except Exception as e:
raise ClimatologyError(f'Could not fetch {url}: {e}') from e
actual = hashlib.sha256(data).hexdigest()
if actual != expected:
raise ClimatologyError(f'{url} is not the file expected (sha256 {actual})')
path = climatology_directory() / month_name(month)
temporary = path.with_suffix('.tmp')
temporary.write_bytes(data)
temporary.replace(path)
logger.info(f'Kept the fallout climatology of month {month} ({len(data) / 1e6:.1f} MB)')
return path
async def fetch_missing() -> List[int]:
"""Fetch every month not yet kept, one after another; the months fetched."""
fetched = []
for month in MONTHS:
if month_path(month) or not MONTHS[month]:
continue
try:
await fetch_month(month)
fetched.append(month)
except ClimatologyError as e:
logger.warning(f'Could not fetch the fallout climatology: {e}')
break
# Spread out, as a courtesy to the download location.
await asyncio.sleep(1)
return fetched
@perpetual_signal(sleep=CHECK_SECONDS)
async def climatology_worker():
"""Fetch the months not yet kept, once there is the Internet and the drive (not in WROL Mode).
Waits for the flags, rather than returning, so a new WROLPi fetches as soon as it is online, not an hour
after startup."""
if not any(MONTHS.values()):
return
async with flags.have_internet.wait_for():
pass
async with flags.media_mounted.wait_for():
pass
if wrol_mode_enabled() or not [m for m in MONTHS if MONTHS[m] and not month_path(m)]:
return
await fetch_missing()

View file

@ -58,3 +58,14 @@ def map_export_root(tmp_path, monkeypatch) -> Path:
root = tmp_path / 'map-export'
monkeypatch.setattr(export_job, 'EXPORT_ROOT', root)
return root
@pytest.fixture
def test_nuclear_config(test_directory, monkeypatch):
"""The map's nuclear targets, kept in the test's media directory."""
from modules.map import nuclear
(test_directory / 'config').mkdir(exist_ok=True)
config = nuclear.MapNuclearConfig()
config.initialize()
monkeypatch.setattr(nuclear, 'TEST_MAP_NUCLEAR_CONFIG', config)
yield config

122
modules/map/nuclear.py Normal file
View file

@ -0,0 +1,122 @@
"""The map's nuclear targets: likely detonation sites, simulated in the map's nuclear mode. Kept apart
from the pins, in their own config."""
from dataclasses import dataclass, field
from typing import List
from wrolpi.common import ConfigFile, logger
from wrolpi.dates import now
from wrolpi.switches import register_switch_handler, ActivateSwitchMethod
logger = logger.getChild(__name__)
class TargetsChanged(ValueError):
"""The saved targets are not the ones the user started from."""
def check_weapon(weapon: str = None, yield_kt: float = None, fission_fraction: float = None) -> dict:
"""A target's weapon, as it is kept: the key of a weapon the simulator offers (or "custom"), its
yield (kt) when it is a yield of the user's own, and the share of the yield from fission."""
fields = dict()
if weapon is not None:
if not isinstance(weapon, str) or not weapon.strip():
raise ValueError('A weapon is named by its key')
fields['weapon'] = weapon.strip()
if yield_kt is not None:
if not isinstance(yield_kt, (int, float)) or not 0 < yield_kt <= 1e5:
raise ValueError('A yield is more than 0 and at most 100,000 kt')
fields['yield_kt'] = yield_kt
if fission_fraction is not None:
if not isinstance(fission_fraction, (int, float)) or not 0 < fission_fraction <= 1:
raise ValueError('A fission share is more than 0 and at most 1')
fields['fission_fraction'] = fission_fraction
return fields
@dataclass
class MapNuclearConfigValidator:
version: int = None
targets: list = field(default_factory=list)
class MapNuclearConfig(ConfigFile):
file_name = 'map_nuclear.yaml'
default_config = dict(
version=0,
targets=[],
)
validator = MapNuclearConfigValidator
@property
def targets(self) -> List[dict]:
return list(self._config.get('targets', []))
@targets.setter
def targets(self, value: List[dict]):
self.update({'targets': value})
def replace_targets(self, targets: List[dict], loaded_ids: List[int]) -> List[dict]:
"""Make `targets` the saved targets, in one change of the config.
Each target is {lat, lon, label, weapon?, yield_kt?, fission_fraction?, id?}: a target with
the id of a saved target keeps that target's id and date, the others are new. `loaded_ids`
are the ids of the saved targets the user started from: if the saved targets are not those
(they were not loaded, or have changed since), nothing is saved, so none are lost unseen.
Returns the saved targets."""
saved = {t['id']: t for t in self.targets}
if set(saved) != set(loaded_ids):
raise TargetsChanged('The saved targets are not the ones loaded: load them again, then save')
next_id = max(saved, default=0) + 1
kept = []
for target in targets:
label = str(target.get('label') or '').strip()
if not label:
raise ValueError('Every target has a name')
lat, lon = target.get('lat'), target.get('lon')
if not isinstance(lat, (int, float)) or not isinstance(lon, (int, float)) \
or not -90 <= lat <= 90 or not -180 <= lon <= 180:
raise ValueError(f'{label} is not at a latitude and longitude')
weapon_fields = check_weapon(target.get('weapon'), target.get('yield_kt'), target.get('fission_fraction'))
old = saved.get(target.get('id'))
if old:
target_id, created = old['id'], old.get('created')
else:
target_id, created = next_id, str(now().date())
next_id += 1
kept.append(dict(id=target_id, lat=round(lat, 6), lon=round(lon, 6), label=label, created=created,
**weapon_fields))
if len({t['id'] for t in kept}) != len(kept):
raise ValueError('A saved target is given more than once')
self.targets = kept
save_map_nuclear_config.activate_switch()
return kept
def delete_target(self, target_id: int) -> bool:
targets = self.targets
kept = [t for t in targets if t.get('id') != target_id]
if len(kept) == len(targets):
return False
self.targets = kept
save_map_nuclear_config.activate_switch()
return True
MAP_NUCLEAR_CONFIG: MapNuclearConfig = MapNuclearConfig()
# Test override.
TEST_MAP_NUCLEAR_CONFIG = None
def get_map_nuclear_config() -> MapNuclearConfig:
global TEST_MAP_NUCLEAR_CONFIG
if isinstance(TEST_MAP_NUCLEAR_CONFIG, ConfigFile):
return TEST_MAP_NUCLEAR_CONFIG
return MAP_NUCLEAR_CONFIG
@register_switch_handler('save_map_nuclear_config')
def save_map_nuclear_config():
get_map_nuclear_config().save()
save_map_nuclear_config: ActivateSwitchMethod

View file

@ -1,4 +1,5 @@
from dataclasses import dataclass
from typing import Optional
@dataclass
@ -15,13 +16,28 @@ class MapFileVisibleRequest:
@dataclass
class MapPinRequest:
lat: float
lon: float
# A browser sends a whole number of degrees as an integer.
lat: float | int
lon: float | int
label: str
color: str = "red"
@dataclass
class MapPinUpdateRequest:
label: str = None
color: str = None
label: Optional[str] = None
color: Optional[str] = None
@dataclass
class MapWeatherRequest:
# Whether the weather (a forecast around the nuclear targets) is downloaded every day.
enabled: bool
@dataclass
class MapTargetsRequest:
# The targets to save ([{lat, lon, label, weapon?, yield_kt?, fission_fraction?, id?}]), and the ids
# of the saved targets they were started from.
targets: list
loaded_ids: list

View file

@ -0,0 +1,118 @@
import asyncio
import gzip
import hashlib
from http import HTTPStatus
from unittest import mock
import pytest
from modules.map import climatology
from wrolpi import flags
class FakeResponse:
def __init__(self, status, body):
self.status, self.body = status, body
async def read(self):
return self.body
def fake_get(bodies):
"""aiohttp_get answering each URL from `bodies` (url -> (status, body)), keeping the URLs asked."""
asked = []
class Context:
def __init__(self, url, timeout=None):
asked.append(url)
self.url = url
async def __aenter__(self):
return FakeResponse(*bodies.get(self.url, (404, b'')))
async def __aexit__(self, *args):
return False
return Context, asked
@pytest.fixture
def published():
"""Months 1 and 2 published, with their sha256 pinned; the rest not yet."""
data = {1: gzip.compress(b'WFCL one'), 2: gzip.compress(b'WFCL two')}
months = {m: (hashlib.sha256(data[m]).hexdigest() if m in data else None) for m in range(1, 13)}
bodies = {f'{climatology.BASE_URL}/{climatology.month_name(m)}': (200, d) for m, d in data.items()}
with mock.patch.object(climatology, 'MONTHS', months):
yield data, bodies
@pytest.mark.asyncio
async def test_fetch_missing(test_directory, published):
"""Each published month is fetched once, checked, and kept where the file lists do not look."""
data, bodies = published
get, asked = fake_get(bodies)
with mock.patch('modules.map.climatology.aiohttp_get', get), mock.patch('modules.map.climatology.asyncio.sleep'):
assert await climatology.fetch_missing() == [1, 2]
assert climatology.month_path(1).read_bytes() == data[1]
# Kept: not fetched again.
assert await climatology.fetch_missing() == []
assert len(asked) == 2
assert climatology.climatology_directory().parent.name.startswith('.')
assert climatology.status() == dict(version=climatology.VERSION, months=[1, 2],
missing=list(range(3, 13)), published=False)
@pytest.mark.asyncio
async def test_fetch_month_refuses_what_is_not_expected(test_directory, published):
data, bodies = published
url = f'{climatology.BASE_URL}/{climatology.month_name(1)}'
get, _ = fake_get({url: (200, b'something else')})
with mock.patch('modules.map.climatology.aiohttp_get', get):
with pytest.raises(climatology.ClimatologyError, match='not the file expected'):
await climatology.fetch_month(1)
assert climatology.month_path(1) is None
get, _ = fake_get({url: (503, b'')})
with mock.patch('modules.map.climatology.aiohttp_get', get):
with pytest.raises(climatology.ClimatologyError, match='HTTP 503'):
await climatology.fetch_month(1)
# A month with no sha256 pinned is never fetched.
with pytest.raises(climatology.ClimatologyError, match='No sha256'):
await climatology.fetch_month(3)
@pytest.mark.asyncio
async def test_climatology_api(async_client, test_directory, published):
data, bodies = published
request, response = await async_client.get('/api/map/fallout/climatology')
assert response.status_code == HTTPStatus.OK and response.json['months'] == []
request, response = await async_client.get('/api/map/fallout/climatology/1')
assert response.status_code == HTTPStatus.NOT_FOUND
get, _ = fake_get(bodies)
with mock.patch('modules.map.climatology.aiohttp_get', get), mock.patch('modules.map.climatology.asyncio.sleep'):
await climatology.fetch_missing()
request, response = await async_client.get('/api/map/fallout/climatology')
assert response.json['months'] == [1, 2]
request, response = await async_client.get('/api/map/fallout/climatology/2')
assert response.status_code == HTTPStatus.OK and response.body == data[2]
@pytest.mark.asyncio
async def test_worker_waits_for_internet_and_drive(test_directory, published, flags_lock):
"""Started before the Internet and the drive are known (as on startup), the worker waits for them and then
fetches, rather than giving up until its next hourly check."""
flags.have_internet.clear()
flags.media_mounted.clear()
fetch = mock.AsyncMock(return_value=[1, 2])
with mock.patch('modules.map.climatology.fetch_missing', fetch), \
mock.patch('modules.map.climatology.wrol_mode_enabled', return_value=False):
worker = asyncio.create_task(climatology.climatology_worker())
await asyncio.sleep(0.3)
assert not worker.done() and not fetch.called
flags.have_internet.set()
await asyncio.sleep(0.3)
assert not worker.done() and not fetch.called
flags.media_mounted.set()
await asyncio.wait_for(worker, timeout=5)
fetch.assert_awaited_once()

View file

@ -0,0 +1,98 @@
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'])

View file

@ -0,0 +1,321 @@
import json
from http import HTTPStatus
from unittest import mock
import pytest
from modules.map import winds
from wrolpi import flags
from wrolpi.conftest import make_test_ctx
from wrolpi.downloader import Download, DownloadFrequency
@pytest.fixture(autouse=True)
def unpaced():
"""Requests are not a minute apart in tests, and a field is fetched in one."""
with mock.patch('modules.map.winds.BATCH_SECONDS', 0), mock.patch('modules.map.winds.BATCH', 1000):
yield
def forecast(lat=61.0, lon=-149.0, elevation=100.0, hours=2):
"""An Open-Meteo forecast for one place, with three pressure levels, one of them below the ground."""
hourly = {'time': [f'2026-11-22T{h:02d}:00' for h in range(hours)],
'wind_speed_10m': [2.0] * hours, 'wind_direction_10m': [180] * hours,
'precipitation': [0.0, 1.5][:hours]}
for level, height, speed, direction in [(1000, 50.0, 5.0, 190), (850, 1500.0, 10.0, 220),
(500, 5600.0, 25.0, 260)]:
hourly[f'geopotential_height_{level}hPa'] = [height] * hours
hourly[f'wind_speed_{level}hPa'] = [speed] * hours
hourly[f'wind_direction_{level}hPa'] = [direction] * hours
# Humid from 925 to 700 hPa (a cloud from about 800 m to 3,000 m), dry above.
for level, height, rh in [(1000, 50.0, 70), (975, 300.0, 75), (950, 550.0, 78), (925, 800.0, 85),
(900, 1000.0, 90), (850, 1500.0, 95), (800, 2000.0, 90), (700, 3000.0, 82),
(600, 4200.0, 55), (500, 5600.0, 40), (400, 7200.0, 30), (300, 9200.0, 20)]:
hourly[f'relative_humidity_{level}hPa'] = [rh] * hours
hourly.setdefault(f'geopotential_height_{level}hPa', [height] * hours)
return {'latitude': lat, 'longitude': lon, 'elevation': elevation, 'hourly': hourly}
def fake_service(requested):
"""A forecast service which answers every place asked of it, and keeps the URLs asked."""
async def request(url):
requested.append(url)
query = dict(part.split('=', 1) for part in url.split('?', 1)[1].split('&'))
lats = query['latitude'].replace('%2C', ',').split(',')
lons = query['longitude'].replace('%2C', ',').split(',')
return [forecast(float(a), float(b)) for a, b in zip(lats, lons)]
return request
def test_field_points_around_one_place():
"""Close together around one place: every whole degree within the margin."""
spacing, points = winds.field_points([(61.2, -149.3)])
assert spacing == 1
assert (61, -149) in points and (55, -155) not in points and (56, -155) in points
assert all(abs(lat - 61.2) <= winds.MARGIN and abs(lon + 149.3) <= winds.MARGIN for lat, lon in points)
assert len(points) <= winds.MAX_POINTS
def test_field_points_spread_out():
"""Over a country, further apart, to stay within MAX_POINTS; points of nearby places are shared."""
places = [(40.6, -75.4), (33.6, -84.4), (47.4, -122.3), (25.8, -80.3), (61.2, -149.9), (19.7, -155.0)]
spacing, points = winds.field_points(places)
assert spacing > 1
assert len(points) <= winds.MAX_POINTS
assert all(lat % spacing == 0 and lon % spacing == 0 for lat, lon in points)
assert len(set(points)) == len(points)
def test_field_points_wrap():
"""Around the antimeridian, longitudes wrap."""
spacing, points = winds.field_points([(52.0, 179.0)])
assert all(-180 <= lon < 180 for _, lon in points)
assert any(lon < -170 for _, lon in points) and any(lon > 170 for _, lon in points)
def test_forecast_url_asks_for_every_place_and_level():
url = winds.forecast_url([(61, -149), (60, -150)])
assert url.startswith(winds.OPEN_METEO_URL)
assert 'latitude=61%2C60' in url and 'longitude=-149%2C-150' in url
for level in winds.PRESSURE_LEVELS:
assert f'geopotential_height_{level}hPa' in url
for level in winds.HUMIDITY_LEVELS:
assert f'relative_humidity_{level}hPa' in url
assert 'wind_speed_unit=ms' in url
# The forecast starts at midnight UTC: a third day covers the 48 hours after a burst this hour.
assert f'forecast_days={winds.FORECAST_DAYS}' in url and winds.FORECAST_DAYS >= 3
def test_parse_forecast():
"""Each hour's winds go up from 10 m above the ground; a level below the ground is left out."""
parsed = winds.parse_forecast(forecast())
assert parsed['elevation'] == 100.0
assert [h['time'] for h in parsed['hours']] == ['2026-11-22T00:00Z', '2026-11-22T01:00Z']
assert parsed['hours'][0]['winds'] == [[110, 2.0, 180], [1500, 10.0, 220], [5600, 25.0, 260]]
assert parsed['hours'][1]['precipitation'] == 1.5
# The cloud rain falls from: from the first level at least 80% humid to the first above it below 60%.
assert parsed['hours'][0]['cloud'] == [800, 4200]
def test_cloud_layer():
assert winds.cloud_layer(0, [(100, 50), (1000, 70)]) is None
# Levels below the ground are left out; humid to the top: the top is the highest level.
assert winds.cloud_layer(500, [(100, 95), (1000, 85), (2000, 90)]) == [1000, 2000]
assert winds.cloud_layer(0, [(100, 85), (1000, None), (2000, 59), (3000, 90)]) == [100, 2000]
def test_parse_forecast_rejects_nonsense():
with pytest.raises(winds.WindsError):
winds.parse_forecast({'error': True, 'reason': 'nope'})
@pytest.mark.asyncio
async def test_fetch_wind_field(test_directory):
"""A field is fetched in batches, kept, and found again as the latest."""
requested, heard, slept = [], [], []
async def sleep(seconds):
slept.append(seconds)
places = [(61.2, -149.3), (40.6, -75.4)]
with mock.patch('modules.map.winds.request_forecast', fake_service(requested)), \
mock.patch('modules.map.winds.BATCH', 50), mock.patch('modules.map.winds.BATCH_SECONDS', 61), \
mock.patch('modules.map.winds.asyncio.sleep', sleep):
field = await winds.fetch_wind_field(places, lambda done, total: heard.append((done, total)))
spacing, points = winds.field_points(places)
assert len(requested) == -(-len(points) // 50)
# Each request after the first waits out the rest of a minute from the one before it.
assert len(slept) == len(requested) - 1 and all(50 < s <= 61 for s in slept)
assert heard[-1] == (len(points), len(points)) and len(heard) == len(requested)
assert field['spacing'] == spacing
assert [(p['lat'], p['lon']) for p in field['points']] == points
assert len(field['winds']) == len(points) and len(field['winds'][0]) == len(field['hours']) == 2
assert field['winds'][0][0][0] == [110, 2.0, 180]
assert field['rain'][0] == [0.0, 1.5]
assert field['clouds'][0] == [[800, 4200], [800, 4200]]
assert winds.latest_field() == field
# Kept where the file lists do not look.
assert winds.winds_directory().name.startswith('.')
@pytest.mark.asyncio
async def test_fetch_wind_field_keeps_the_newest(test_directory):
"""Only the newest field is kept: a simulation is of bursts now."""
assert winds.KEPT_FIELDS == 1
with mock.patch('modules.map.winds.request_forecast', fake_service([])), \
mock.patch('modules.map.winds.now') as fake_now:
from datetime import datetime, timezone
for minute in range(3):
fake_now.return_value = datetime(2026, 11, 22, 0, minute, tzinfo=timezone.utc)
await winds.fetch_wind_field([(10, 10)])
kept = sorted(winds.winds_directory().glob('field-*.json'))
assert len(kept) == 1
assert winds.latest_field()['fetched_at'].startswith('2026-11-22T00:02')
@pytest.mark.asyncio
async def test_fetch_wind_field_cancelled(test_directory):
"""Cancelled between requests, nothing is kept, and the field before stays."""
with mock.patch('modules.map.winds.request_forecast', fake_service([])):
before = await winds.fetch_wind_field([(10, 10)])
asked = []
with mock.patch('modules.map.winds.request_forecast', fake_service(asked)), \
mock.patch('modules.map.winds.BATCH', 1):
with pytest.raises(winds.WindsError, match='Cancelled'):
await winds.fetch_wind_field([(61, -149)], cancelled=lambda: bool(asked))
assert len(asked) == 1
assert winds.latest_field() == before
@pytest.mark.asyncio
async def test_fetch_wind_field_failure(test_directory):
async def unreachable(url):
raise OSError('no route to host')
with mock.patch('modules.map.winds.request_forecast', unreachable):
with pytest.raises(winds.WindsError):
await winds.fetch_wind_field([(61, -149)])
assert winds.latest_field() is None
async def short(url):
return [forecast()]
with mock.patch('modules.map.winds.request_forecast', short):
with pytest.raises(winds.WindsError):
await winds.fetch_wind_field([(61, -149)])
@pytest.mark.asyncio
async def test_fetch_wind_field_says_why(test_directory):
"""A request which takes too long, or fails without a message, still says why."""
import asyncio
async def slow(url):
raise asyncio.TimeoutError()
with mock.patch('modules.map.winds.request_forecast', slow):
with pytest.raises(winds.WindsError, match=f'did not answer within {winds.TIMEOUT} seconds'):
await winds.fetch_wind_field([(61, -149)])
async def silent(url):
raise ConnectionResetError()
with mock.patch('modules.map.winds.request_forecast', silent):
with pytest.raises(winds.WindsError, match='ConnectionResetError'):
await winds.fetch_wind_field([(61, -149)])
assert winds.TIMEOUT >= 120
@pytest.mark.asyncio
async def test_fetch_wind_field_slows_down(test_directory):
"""Told too many have been asked of it, the service is asked again a minute later, once."""
answers = [winds.WindsError('The forecast service answered HTTP 429')]
slept = []
async def sleep(seconds):
slept.append(seconds)
service = fake_service([])
async def busy_then_fine(url):
if answers:
raise answers.pop()
return await service(url)
with mock.patch('modules.map.winds.request_forecast', busy_then_fine), \
mock.patch('modules.map.winds.asyncio.sleep', sleep):
field = await winds.fetch_wind_field([(10, 10)])
assert len(slept) == 1 and field['points']
async def always_busy(url):
raise winds.WindsError('The forecast service answered HTTP 429')
with mock.patch('modules.map.winds.request_forecast', always_busy), \
mock.patch('modules.map.winds.asyncio.sleep', sleep):
with pytest.raises(winds.WindsError, match='429'):
await winds.fetch_wind_field([(10, 10)])
@pytest.mark.asyncio
async def test_latest_winds_api(async_client, test_directory):
request, response = await async_client.get('/api/map/fallout/winds/latest')
assert response.status_code == HTTPStatus.OK
assert response.json['winds'] is None
with mock.patch('modules.map.winds.request_forecast', fake_service([])):
await winds.fetch_wind_field([(61.2, -149.3)])
request, response = await async_client.get('/api/map/fallout/winds/latest')
assert response.json['winds']['points'][0]['elevation'] == 100.0
@pytest.mark.asyncio
async def test_weather_subscription(async_client, test_session, test_directory, test_nuclear_config):
"""Subscribing makes one daily Download of the weather, due now; unsubscribing deletes it."""
request, response = await async_client.get('/api/map/weather')
assert response.status_code == HTTPStatus.OK
assert response.json == dict(enabled=False, download=None, targets=0, spacing=None, points=None, seconds=None,
field=None)
test_nuclear_config.replace_targets([{'lat': 61.2, 'lon': -149.3, 'label': 'A'}], loaded_ids=[])
request, response = await async_client.put('/api/map/weather', content=json.dumps({'enabled': True}))
assert response.status_code == HTTPStatus.OK
assert response.json['enabled'] is True and response.json['targets'] == 1
assert response.json['spacing'] == 1 and response.json['points'] > 0
download, = test_session.query(Download).all()
assert (download.url, download.downloader, download.frequency, download.status) == \
(winds.WEATHER_URL, 'open_meteo', DownloadFrequency.daily, 'new')
# Subscribing again changes nothing.
request, response = await async_client.put('/api/map/weather', content=json.dumps({'enabled': True}))
assert test_session.query(Download).count() == 1
# Downloaded now, though not due.
download.status = 'complete'
test_session.commit()
request, response = await async_client.post('/api/map/weather/download')
assert response.status_code == HTTPStatus.OK
test_session.expire_all()
assert test_session.query(Download).one().status == 'new'
request, response = await async_client.put('/api/map/weather', content=json.dumps({'enabled': False}))
assert response.json['enabled'] is False
assert test_session.query(Download).count() == 0
request, response = await async_client.post('/api/map/weather/download')
assert response.status_code == HTTPStatus.BAD_REQUEST
@pytest.mark.asyncio
async def test_weather_downloader(test_session, test_directory, test_nuclear_config):
"""The downloader fetches a field around the saved targets, telling how far it has got."""
downloader = winds.weather_downloader
# No targets: nothing to download, and nothing wrong.
prepared = downloader.prepare_download(test_session, None)
assert prepared.places == []
executed = await downloader.execute_download(prepared, make_test_ctx())
assert downloader.finalize_download(test_session, None, executed).success is True
assert winds.latest_field() is None
test_nuclear_config.replace_targets([{'lat': 61.2, 'lon': -149.3, 'label': 'A'},
{'lat': 40.6, 'lon': -75.4, 'label': 'B'}], loaded_ids=[])
prepared = downloader.prepare_download(test_session, None)
assert prepared.places == [(61.2, -149.3), (40.6, -75.4)]
heard, cleared = [], []
with mock.patch('modules.map.winds.request_forecast', fake_service([])), mock.patch('modules.map.winds.BATCH', 50):
executed = await downloader.execute_download(prepared, make_test_ctx(
report_progress=heard.append, clear_progress=lambda: cleared.append(True)))
result = downloader.finalize_download(test_session, None, executed)
assert result.success is True and result.location == '/map/manage'
assert heard[-1] == dict(percent=100) and cleared == [True]
summary = winds.field_summary()
assert summary['points'] == executed.points == len(winds.latest_field()['points'])
assert summary['first_hour'] < summary['last_hour'] and summary['size'] > 0
async def broken(url):
raise winds.WindsError('The forecast service answered HTTP 500')
with mock.patch('modules.map.winds.request_forecast', broken):
executed = await downloader.execute_download(prepared, make_test_ctx())
result = downloader.finalize_download(test_session, None, executed)
assert result.success is False and 'HTTP 500' in result.error
# The field before stays.
assert winds.field_summary() == summary

403
modules/map/winds.py Normal file
View file

@ -0,0 +1,403 @@
"""The winds aloft over a region, from a weather forecast, for the fallout simulator.
Fallout falls from a cloud kilometers high, for hours, across hundreds of kilometers, through winds
which change with height, with place, and with time. So the simulator takes a field of forecasts:
the wind at every height, hour by hour, at points on a grid over the region around the targets, and
carries each particle by the wind where it is, at the height it is, at the hour it is there.
Open-Meteo (https://open-meteo.com) forecasts the wind at nineteen pressure levels, from about 100 m
up to about 24 km, free and without an API key, for many places in one request. When the user
subscribes (the map's Manage tab), a field around the saved nuclear targets is downloaded every day,
as a recurring Download, and kept so the simulator can use it offline. Only the newest is kept:
a simulation is of bursts now. Its points are on whole degrees, so the forecast service is never
told where a target is.
The free service allows 600 calls a minute and 10,000 a day, a place costing about one call for
every ten variables asked of it (here sixty). So a field is kept to MAX_POINTS points, by spacing
them further apart over a wide region, and is fetched as a Job, BATCH places a minute: a field over
a whole country takes a few minutes.
"""
import asyncio
import json
from dataclasses import dataclass
import time
import math
from pathlib import Path
from typing import List, Optional, Sequence, Tuple
from urllib.parse import urlencode
from sqlalchemy.orm import Session
from modules.map.lib import get_map_directory
from modules.map.nuclear import get_map_nuclear_config
from wrolpi.common import aiohttp_get, logger
from wrolpi.dates import now
from wrolpi.downloader import Download, DownloadContext, Downloader, DownloadFrequency, DownloadResult, \
download_manager, save_downloads_config
logger = logger.getChild(__name__)
OPEN_METEO_URL = 'https://api.open-meteo.com/v1/forecast'
# The pressure levels (hPa) Open-Meteo forecasts, from near the ground up.
PRESSURE_LEVELS = (1000, 975, 950, 925, 900, 850, 800, 700, 600, 500, 400, 300, 250, 200, 150, 100, 70, 50, 30)
# Long enough for fallout to come down: the forecast starts at midnight UTC, and the 48 hours after a
# burst this hour must be in it until the next day's download. Open-Meteo counts up to a week of a
# place as one call, so the extra days cost nothing.
FORECAST_DAYS = 4
# The pressure levels whose relative humidity is asked for: where a rain cloud may be, up to the tops of
# thunderstorms (about 200 hPa).
HUMIDITY_LEVELS = (1000, 975, 950, 925, 900, 850, 800, 700, 600, 500, 400, 300, 250, 200)
# A cloud's bottom is the lowest level at least this humid, its top the first above that is less than
# CLOUD_TOP_RH (percent): HYSPLIT's rule (Moroz et al. 2010, after Draxler and Hess 1997).
CLOUD_BOTTOM_RH = 80
CLOUD_TOP_RH = 60
# How long (s) the forecast service may take to answer one request: it takes most of a minute for a
# batch of places at times.
TIMEOUT = 180
# How far around each target the field reaches (degrees): as far as fallout which shows is carried.
MARGIN = 6
# No more points than this in a field: up to about 4,000 of the free service's 5,000 calls an hour and
# 10,000 a day, fetched in about seven minutes.
MAX_POINTS = 540
# The spacings (degrees) a field's points may have, the closest first.
SPACINGS = (1, 2, 3, 4, 5, 6, 8, 10)
# Places asked for in one request (each costs 7.4 calls: 74 variables, a call for every ten; 600 calls
# a minute are allowed), and how long (s) from one request to the next.
BATCH = 80
BATCH_SECONDS = 61
# Fields kept on disk: only the newest, which is the one used. It is replaced only once a newer one
# has been downloaded.
KEPT_FIELDS = 1
class WindsError(Exception):
"""A forecast could not be fetched, or was not understood."""
def field_points(places: Sequence[Tuple[float, float]], margin: float = MARGIN,
max_points: int = None) -> Tuple[int, List[Tuple[int, int]]]:
"""The points of a field over `places` ([(lat, lon)]): the spacing (degrees), and the points
([(lat, lon)], on whole multiples of the spacing) within `margin` degrees of any place, as close
together as `max_points` allows."""
if not places:
raise WindsError('A field needs at least one place')
max_points = max_points or MAX_POINTS
for spacing in SPACINGS:
points = set()
for lat, lon in places:
south = math.ceil(max(lat - margin, -85) / spacing) * spacing
north = math.floor(min(lat + margin, 85) / spacing) * spacing
west = math.ceil((lon - margin) / spacing) * spacing
east = math.floor((lon + margin) / spacing) * spacing
for point_lat in range(south, north + 1, spacing):
for point_lon in range(west, east + 1, spacing):
# Longitudes wrap at the antimeridian.
points.add((point_lat, ((point_lon + 180) % 360) - 180))
if len(points) <= max_points:
return spacing, sorted(points)
raise WindsError(f'The places are too spread out for a field of {max_points} points')
def forecast_url(points: Sequence[Tuple[int, int]]) -> str:
hourly = ['wind_speed_10m', 'wind_direction_10m', 'precipitation']
for level in PRESSURE_LEVELS:
hourly += [f'wind_speed_{level}hPa', f'wind_direction_{level}hPa', f'geopotential_height_{level}hPa']
hourly += [f'relative_humidity_{level}hPa' for level in HUMIDITY_LEVELS]
query = dict(latitude=','.join(str(p[0]) for p in points), longitude=','.join(str(p[1]) for p in points),
hourly=','.join(hourly), forecast_days=FORECAST_DAYS, wind_speed_unit='ms', timezone='GMT')
return f'{OPEN_METEO_URL}?{urlencode(query)}'
def parse_forecast(data: dict) -> dict:
"""An Open-Meteo forecast for one place as the simulator reads it:
{elevation (m, of the forecast's ground), hours: [{time (UTC, ISO), precipitation (mm in the
hour), cloud: [bottom, top] (m above sea level, of the cloud rain would fall from) or None,
winds: [[height (m above sea level), speed (m/s), direction (degrees the wind blows FROM)],
...]}]}
Each hour's winds start with the wind 10 m above the ground and go up the pressure levels. A
level below the ground (high pressure over high ground) is left out, as is anything missing."""
try:
elevation = float(data['elevation'])
hourly = data['hourly']
times = hourly['time']
except (KeyError, TypeError, ValueError) as e:
raise WindsError(f'The forecast was not understood: {e}') from e
def at(name, i):
values = hourly.get(name)
return values[i] if values and i < len(values) else None
hours = []
for i, time in enumerate(times):
winds = []
speed, direction = at('wind_speed_10m', i), at('wind_direction_10m', i)
if speed is not None and direction is not None:
winds.append([round(elevation + 10), round(speed, 1), round(direction)])
for level in PRESSURE_LEVELS:
height = at(f'geopotential_height_{level}hPa', i)
speed, direction = at(f'wind_speed_{level}hPa', i), at(f'wind_direction_{level}hPa', i)
if None in (height, speed, direction) or height <= elevation + 10:
continue
winds.append([round(height), round(speed, 1), round(direction)])
if not winds:
continue
winds.sort(key=lambda w: w[0])
hours.append(dict(time=f'{time}Z', precipitation=at('precipitation', i) or 0, winds=winds,
cloud=cloud_layer(elevation, [(at(f'geopotential_height_{level}hPa', i),
at(f'relative_humidity_{level}hPa', i))
for level in HUMIDITY_LEVELS])))
if not hours:
raise WindsError('The forecast had no winds')
return dict(elevation=elevation, hours=hours)
def cloud_layer(elevation: float, levels: Sequence[Tuple[Optional[float], Optional[float]]]) -> Optional[List[int]]:
"""The cloud rain would fall from, as [bottom, top] (m above sea level), from the (height,
relative humidity) of each level going up; None without one. Its bottom is the lowest level
above the ground at least CLOUD_BOTTOM_RH humid, its top the first above that which is less than
CLOUD_TOP_RH humid (or the highest level)."""
known = [(h, rh) for h, rh in levels if h is not None and rh is not None and h > elevation]
bottom = next((k for k, (_, rh) in enumerate(known) if rh >= CLOUD_BOTTOM_RH), None)
if bottom is None:
return None
top = next((k for k in range(bottom + 1, len(known)) if known[k][1] < CLOUD_TOP_RH), len(known) - 1)
return [round(known[bottom][0]), round(known[top][0])]
def winds_directory() -> Path:
"""Where fields are kept: a hidden directory, which the file lists and search skip."""
directory = get_map_directory() / '.fallout-winds'
directory.mkdir(parents=True, exist_ok=True)
return directory
def latest_field() -> Optional[dict]:
"""The field fetched most recently, or None."""
for path in sorted(winds_directory().glob('field-*.json'), reverse=True):
try:
return json.loads(path.read_text())
except (OSError, ValueError) as e:
logger.warning(f'Could not read the winds kept in {path}', exc_info=e)
return None
async def request_forecast(url: str) -> list:
"""The forecasts of a request, one for each of its places."""
async with aiohttp_get(url, timeout=TIMEOUT) as response:
if response.status != 200:
raise WindsError(f'The forecast service answered HTTP {response.status}')
data = await response.json()
# One place is answered with a forecast, several with a list of them.
return data if isinstance(data, list) else [data]
async def request_batch(url: str) -> list:
"""The forecasts of a request; asked once more, a minute later, when the service says too many
have been asked of it."""
for attempt in range(2):
try:
return await request_forecast(url)
except WindsError as e:
if attempt or 'HTTP 429' not in str(e):
raise
logger.warning('The forecast service asked us to slow down; trying again in a minute')
await asyncio.sleep(BATCH_SECONDS)
except asyncio.TimeoutError as e:
raise WindsError(f'The forecast service did not answer within {TIMEOUT} seconds') from e
except Exception as e:
raise WindsError(f'Could not reach the forecast service: {str(e) or type(e).__name__}') from e
async def fetch_wind_field(places: Sequence[Tuple[float, float]], progress=None, cancelled=None) -> dict:
"""Fetch the field over `places` ([(lat, lon)]), keep it, and return it:
{source, fetched_at, spacing (degrees), points: [{lat, lon, elevation}], hours: [time (UTC,
ISO)], winds: [for each point: [for each hour: [[height (m above sea level), speed (m/s),
direction FROM (degrees)], ...]]], rain: [for each point: [mm in each hour]], clouds: [for each
point: [for each hour: [bottom, top] (m above sea level) or None]]}
`progress(done, total)`, if given, hears how many points have been fetched; once `cancelled()`, if
given, is true, it stops (WindsError) and keeps nothing."""
spacing, points = field_points(places)
forecasts = []
last = None
for start in range(0, len(points), BATCH):
batch = points[start:start + BATCH]
if last is not None:
await asyncio.sleep(max(BATCH_SECONDS - (time.monotonic() - last), 0))
if cancelled and cancelled():
raise WindsError('Cancelled')
last = time.monotonic()
answered = await request_batch(forecast_url(batch))
if len(answered) != len(batch):
raise WindsError(f'The forecast service answered for {len(answered)} of {len(batch)} places')
forecasts.extend(parse_forecast(f) for f in answered)
if progress:
progress(len(forecasts), len(points))
# Every point has the same hours (Open-Meteo forecasts the same hours everywhere); a point which
# is short of any is given its last.
hours = [h['time'] for h in max(forecasts, key=lambda f: len(f['hours']))['hours']]
winds, rain, clouds = [], [], []
for forecast in forecasts:
by_time = {h['time']: h for h in forecast['hours']}
last = forecast['hours'][-1]
winds.append([by_time.get(t, last)['winds'] for t in hours])
rain.append([by_time.get(t, last)['precipitation'] for t in hours])
clouds.append([by_time.get(t, last).get('cloud') for t in hours])
field = dict(
source='Open-Meteo',
fetched_at=now().isoformat(),
spacing=spacing,
points=[dict(lat=lat, lon=lon, elevation=f['elevation']) for (lat, lon), f in zip(points, forecasts)],
hours=hours,
winds=winds,
rain=rain,
clouds=clouds,
)
logger.info(f'Fetched a field of winds aloft: {len(points)} points every {spacing} degrees')
directory = winds_directory()
path = directory / f'field-{now().strftime("%Y%m%d-%H%M%S")}.json'
temporary = path.with_suffix('.tmp')
temporary.write_text(json.dumps(field, separators=(',', ':')))
temporary.replace(path)
for old in sorted(directory.glob('field-*.json'), reverse=True)[KEPT_FIELDS:]:
old.unlink(missing_ok=True)
return field
def field_summary() -> Optional[dict]:
"""What the newest field is, without its winds: {fetched_at, spacing, points, first_hour, last_hour,
size (bytes)}, or None."""
for path in sorted(winds_directory().glob('field-*.json'), reverse=True):
stat = path.stat()
key = (str(path), stat.st_mtime, stat.st_size)
if _summary_cache.get('key') != key:
try:
field = json.loads(path.read_text())
except Exception as e:
logger.warning(f'Could not read the winds kept in {path}', exc_info=e)
continue
_summary_cache.update(key=key, summary=dict(
fetched_at=field['fetched_at'], spacing=field['spacing'], points=len(field['points']),
first_hour=field['hours'][0], last_hour=field['hours'][-1], size=stat.st_size))
return _summary_cache['summary']
return None
_summary_cache = dict()
# The weather subscription: one recurring Download of a field around the saved targets.
WEATHER_URL = OPEN_METEO_URL
WEATHER_DOWNLOADER = 'open_meteo'
def target_places() -> List[Tuple[float, float]]:
"""The places a field is downloaded around: the saved nuclear targets."""
return [(t['lat'], t['lon']) for t in get_map_nuclear_config().targets]
def get_weather_download(session: Session) -> Optional[Download]:
return session.query(Download).filter_by(url=WEATHER_URL, downloader=WEATHER_DOWNLOADER).one_or_none()
def set_weather_subscription(session: Session, enabled: bool):
"""Subscribe to the weather (a Download every day, the first now), or not (no Download)."""
download = get_weather_download(session)
if enabled and not download:
download = download_manager.get_or_create_download(session, WEATHER_URL, reset_attempts=True,
override_skip=True)
download.downloader = WEATHER_DOWNLOADER
download.frequency = DownloadFrequency.daily
download.location = '/map/manage'
download.settings = {}
download.renew(reset_attempts=True)
elif not enabled and download:
session.delete(download)
else:
return
session.commit()
save_downloads_config.activate_switch()
def download_weather_now(session: Session) -> bool:
"""Download the weather now (it is subscribed to), rather than when it is next due."""
download = get_weather_download(session)
if not download:
return False
download.renew(reset_attempts=True)
session.commit()
return True
def weather_status(session: Session) -> dict:
"""The weather subscription: whether it is on, its Download, the targets it is around, and the
field kept."""
download = get_weather_download(session)
places = target_places()
spacing = points = None
if places:
try:
spacing, field = field_points(places)
points = len(field)
except WindsError:
pass
return dict(
enabled=download is not None,
download=dict(download.__json__(), error=download.error) if download else None,
targets=len(places),
spacing=spacing,
points=points,
# About how long a download takes (s): the forecast service allows so many places a minute.
seconds=BATCH_SECONDS * ((points - 1) // BATCH) if points else None,
field=field_summary(),
)
@dataclass
class PreparedWeather:
places: List[Tuple[float, float]]
@dataclass
class ExecutedWeather:
points: int = 0
error: Optional[str] = None
class WeatherDownloader(Downloader):
"""Downloads the field of forecast winds aloft around the saved nuclear targets."""
name = WEATHER_DOWNLOADER
pretty_name = 'Open-Meteo weather'
listable = False
def prepare_download(self, session: Session, download: Download) -> PreparedWeather:
return PreparedWeather(places=target_places())
async def execute_download(self, prepared: PreparedWeather, ctx: DownloadContext,
download: Download = None) -> ExecutedWeather:
# No targets: nothing to download around, and nothing wrong.
if not prepared.places:
return ExecutedWeather()
try:
field = await fetch_wind_field(
prepared.places,
progress=lambda done, total: ctx.report_progress(dict(percent=100 * done / total)),
cancelled=ctx.is_cancelled)
except WindsError as e:
return ExecutedWeather(error=str(e))
finally:
ctx.clear_progress()
return ExecutedWeather(points=len(field['points']))
def finalize_download(self, session: Session, download: Download, executed: ExecutedWeather) -> DownloadResult:
if executed.error:
return DownloadResult(success=False, error=executed.error)
return DownloadResult(success=True, location='/map/manage')
weather_downloader = WeatherDownloader()

View file

@ -499,6 +499,7 @@ SYNCED_CONFIG_FILE_NAMES = frozenset({
'domains.yaml',
'download_manager.yaml',
'inventory/catalog.yaml',
'map_nuclear.yaml',
'map_pins.yaml',
'maps.yaml',
'playlists.yaml',
@ -1512,6 +1513,10 @@ def get_all_configs() -> Dict[str, ConfigFile]:
if map_pins_config := get_map_pins_config():
all_configs[map_pins_config.file_name] = map_pins_config
from modules.map.nuclear import get_map_nuclear_config
if map_nuclear_config := get_map_nuclear_config():
all_configs[map_nuclear_config.file_name] = map_nuclear_config
from modules.map.config import get_maps_config
if maps_config := get_maps_config():
all_configs[maps_config.file_name] = maps_config
@ -1700,6 +1705,16 @@ async def import_all_db_configs() -> dict[str, bool]:
logger.warning(f'Failed to import map pins config: {e}')
results['map_pins'] = False
# The map's nuclear targets (YAML-only, no DB)
try:
from modules.map.nuclear import get_map_nuclear_config
await asyncio.to_thread(get_map_nuclear_config().import_config)
results['map_nuclear'] = True
logger.debug('map nuclear config imported')
except Exception as e:
logger.warning(f'Failed to import map nuclear config: {e}')
results['map_nuclear'] = False
# Maps (YAML-only, no DB)
try:
from modules.map.config import get_maps_config

View file

@ -40,6 +40,7 @@ def attach_shared_contexts(app: Sanic):
app.shared_ctx.archive_downloader_config = manager.dict()
app.shared_ctx.download_cache_config = manager.dict()
app.shared_ctx.map_pins_config = manager.dict()
app.shared_ctx.map_nuclear_config = manager.dict()
app.shared_ctx.maps_config = manager.dict()
app.shared_ctx.flasher_config = manager.dict()
app.shared_ctx.bookmarks_config = manager.dict()
@ -343,6 +344,12 @@ def initialize_configs_contexts(app: Sanic):
except Exception as e:
logger.error(f'Failed to initialize in-memory map pins config: {e}')
try:
from modules.map.nuclear import MAP_NUCLEAR_CONFIG
MAP_NUCLEAR_CONFIG.initialize(app.shared_ctx.map_nuclear_config)
except Exception as e:
logger.error(f'Failed to initialize in-memory map nuclear config: {e}')
try:
from modules.map.config import MAPS_CONFIG
MAPS_CONFIG.initialize(app.shared_ctx.maps_config)

View file

@ -0,0 +1,149 @@
#!/usr/bin/env python3
"""Build the fallout simulator's climatology: the winds aloft of 30 real days of each month, the
whole world, for running a burst in each and counting where its fallout lands how often.
Usage:
python wrolpi/scripts/build_fallout_climatology.py <output_dir> [--cache DIR] [--months 1,2,...]
Run by the maintainers, once (and when the period changes), on a machine with the Internet. It
writes month-01.bin.gz ... month-12.bin.gz and manifest.json to <output_dir>, for the release
download location (fallout/climatology-v1/). The sha256 of each file is then pinned in
modules/map/climatology.py; WROLPi fetches them from there.
Source: NCEP/NCAR Reanalysis 1 (NOAA PSL; public domain), through PSL's OPeNDAP server, one small
binary request for each day and wind component, spaced out:
- the days: for each month, one day from each year 1991-2020 (30 days), spread across the month,
at 12Z; which year gets which day is shuffled with a fixed seed;
- u and v (m/s) at 14 pressure levels (1000-50 hPa), 2.5 degrees;
- the heights of the levels: the 1991-2020 monthly mean geopotential height.
A month's file (before gzip): b'WFCL', version (uint16 LE), header length (uint32 LE), the header
(JSON: month, levels, the grid, the days, the source), then the heights (int16 LE, [level][lat][lon],
m), then each day's u and v (int8, [level][lat][lon], m/s rounded; |wind| <= 127).
"""
import argparse
import calendar
import gzip
import hashlib
import json
import random
import struct
import sys
import time
import urllib.request
from pathlib import Path
import numpy as np
VERSION = 1
BASE = 'https://psl.noaa.gov/thredds/dodsC/Datasets/ncep.reanalysis'
HEIGHTS = f'{BASE}/Monthlies/pressure/hgt.mon.ltm.1991-2020.nc'
LEVELS = (1000, 925, 850, 700, 600, 500, 400, 300, 250, 200, 150, 100, 70, 50) # the first 14 of 17
YEARS = range(1991, 2021)
SEED = 20261122
NLAT, NLON = 73, 144 # 90 to -90, 0 to 357.5, every 2.5 degrees
# Between two requests (s): PSL's server is shared.
PAUSE = 2
USER_AGENT = 'WROLPi'
def days_of_month(month: int):
"""The 30 sampled days of `month`: one in each year, spread across the month."""
rng = random.Random(SEED + month)
years = list(YEARS)
rng.shuffle(years)
out = []
for k, year in enumerate(years):
length = calendar.monthrange(year, month)[1]
day = 1 + (k * length) // len(years)
out.append(f'{year}-{month:02d}-{day:02d}')
return sorted(out)
def fetch(url: str, cache: Path) -> bytes:
"""`url`'s body, from the cache if it has it."""
path = cache / hashlib.sha256(url.encode()).hexdigest()
if path.exists():
return path.read_bytes()
for attempt in range(5):
try:
request = urllib.request.Request(url, headers={'User-Agent': USER_AGENT})
with urllib.request.urlopen(request, timeout=300) as response:
body = response.read()
break
except Exception as e: # noqa: BLE001 - retried, then raised
if attempt == 4:
raise
print(f' retrying in {PAUSE * 2 ** (attempt + 2)} s: {e}', file=sys.stderr)
time.sleep(PAUSE * 2 ** (attempt + 2))
time.sleep(PAUSE)
path.write_bytes(body)
return body
def dods_array(body: bytes, shape) -> np.ndarray:
"""The one Float32 array of an OPeNDAP binary (.dods) response for `var.var[...]`."""
at = body.index(b'\nData:\n') + len(b'\nData:\n')
n, n2 = struct.unpack('>II', body[at:at + 8])
if n != n2 or n != int(np.prod(shape)):
raise ValueError(f'Expected {np.prod(shape)} values, got {n}')
return np.frombuffer(body[at + 8:at + 8 + 4 * n], dtype='>f4').astype(np.float32).reshape(shape)
def day_winds(day: str, cache: Path):
year = int(day[:4])
# The index of 12Z of `day` in its year's 6-hourly file.
t = int((np.datetime64(day) - np.datetime64(f'{year}-01-01')).astype(int)) * 4 + 2
shape = (len(LEVELS), NLAT, NLON)
out = []
for var in ('uwnd', 'vwnd'):
url = f'{BASE}/pressure/{var}.{year}.nc.dods?{var}.{var}[{t}][0:{len(LEVELS) - 1}][0:{NLAT - 1}][0:{NLON - 1}]'
out.append(dods_array(fetch(url, cache), (1,) + shape)[0])
return out
def build_month(month: int, heights: np.ndarray, cache: Path, output: Path) -> dict:
days = days_of_month(month)
header = dict(
version=VERSION, month=month, levels_hpa=list(LEVELS),
lat=[90.0, -2.5, NLAT], lon=[0.0, 2.5, NLON], days=days, hour_utc=12,
source='NCEP/NCAR Reanalysis 1, NOAA PSL (public domain); heights: 1991-2020 monthly mean geopotential height',
seed=SEED, wind='int8 m/s, rounded', height='int16 m',
)
head = json.dumps(header, separators=(',', ':')).encode()
parts = [b'WFCL', struct.pack('<HI', VERSION, len(head)), head,
np.round(heights[month - 1]).astype('<i2').tobytes()]
largest = 0
for k, day in enumerate(days):
u, v = day_winds(day, cache)
largest = max(largest, float(np.abs(u).max()), float(np.abs(v).max()))
parts += [np.clip(np.round(u), -127, 127).astype(np.int8).tobytes(),
np.clip(np.round(v), -127, 127).astype(np.int8).tobytes()]
print(f' {day} ({k + 1}/{len(days)})', file=sys.stderr)
data = gzip.compress(b''.join(parts), 9)
name = f'month-{month:02d}.bin.gz'
(output / name).write_bytes(data)
print(f'{name}: {len(data) / 1e6:.1f} MB, fastest wind {largest:.0f} m/s', file=sys.stderr)
return dict(name=name, sha256=hashlib.sha256(data).hexdigest(), size=len(data), days=days)
def main():
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument('output')
parser.add_argument('--cache', default=None, help='Where fetched responses are kept (default: <output>/.cache)')
parser.add_argument('--months', default=','.join(str(m) for m in range(1, 13)))
args = parser.parse_args()
output = Path(args.output)
output.mkdir(parents=True, exist_ok=True)
cache = Path(args.cache) if args.cache else output / '.cache'
cache.mkdir(parents=True, exist_ok=True)
heights = dods_array(fetch(f'{HEIGHTS}.dods?hgt.hgt[0:11][0:{len(LEVELS) - 1}][0:{NLAT - 1}][0:{NLON - 1}]', cache),
(12, len(LEVELS), NLAT, NLON))
files = [build_month(int(m), heights, cache, output) for m in args.months.split(',')]
manifest = dict(version=VERSION, files=files)
(output / 'manifest.json').write_text(json.dumps(manifest, indent=1))
print(json.dumps({f['name']: f['sha256'] for f in files}, indent=1))
if __name__ == '__main__':
main()