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

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()