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

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