Skip to content
anotherwolf7129Public

About

Offline CBRN training tools from public sources: a heat stress planner for protective gear (iPhone) and a chemical source tracking simulator (browser).

Topics

Resources

Stars

1 star

Watchers

0 watching

Forks

Repository files navigation

Source Tracking Simulator

Estimates where a chemical release came from, using detector reports and the weather. You enter what each detector reported and where it is. The page shows the most likely source, a search area that should hold the source 9 times in 10, the likely release rate, where the next report would help most, and where the air downwind is likely above a hazard level.

The goal is a practical decision support tool that runs on real terrain and real weather. It is not there yet. See ROADMAP.md for the steps and the validation it must pass first.

Prototype, not yet validated. Today it assumes a steady wind (typed, or spread from weather station files), simplified terrain flow and one release that starts once and may stop (its start and length are worked out from the report times, tested so far only on simulated data). Against one real tracer trial it did well in steady wind. In light wind under 2 m/s it is rough even with the meander and wider direction spread it now uses there (see validation). Do not base real decisions on it. Real incidents follow unit doctrine and approved systems.

Ground rules

  • Public data only. Public formulas, public elevation and weather data, and public field trial data for validation.
  • Never put real unit names, locations, detector positions, report formats or procedures in this repo, the hosted page or any chat. An operational setup with real locations belongs offline, outside this repo, and only after review through the chain of command.
  • No network, no accounts, no storage. Everything runs in the page.

Running

Quickest: on your own computer. Download the repo (Code, then Download ZIP), unzip it and double click index.html. It opens in your browser with nothing to install. This also works on a phone if you open the file from a files app.

In GitHub Codespaces. Create a new codespace on main. The repo has no dev container setup on purpose, so GitHub uses its default environment, which is already prepared and starts quickly. When the terminal appears, run

npm start

A pop-up offers to open port 8000. Click Open in Browser. If you miss it, open the Ports tab and click the globe icon next to port 8000. Press Ctrl+C in the terminal to stop it. A codespace made before this change keeps its old setup, so delete it and make a new one.

With Node installed. Run npm start and open http://localhost:8000.

Tests.

npm test

They also run in GitHub Actions on every push.

Keeping the blog in sync

The blog at anotherwolf7129/website serves its own copy of the simulator at /projects/source-tracking/play. It does not update by itself.

  • Whenever a simulator file (index.html, plume-core.js, terrain.js, wind.js, stations.js) changes on main, the blog sync reminder workflow opens an issue labelled blog-sync, or adds a comment to the one already open, listing the changes.

  • To update the blog, run this from a clone of this repo next to a clone of the website repo, then open a pull request on the website repo:

    node scripts/blog-copy.mjs ../website/public/projects/source-tracking

    It copies the scripts and writes play.html with the blog's colours, a link back to the write-up, absolute script paths and the commit it came from.

  • Close the blog-sync issue once the website pull request is merged.

Using it

The blue box above the map always says what the reports show so far and what to do next.

Incident mode (the default) is for entering reports.

  1. Choose the report type. Alarm or no alarm is a yes or no at the alarm level set under Advanced settings. Concentration reading is an amount in mg per m³.
  2. Enter what the detector reported. Tick Alarm confirmed when an alarm has been checked. That rules out a false alarm, which keeps the search area from spreading over the whole map when later reports are quiet.
  3. Enter its position in km east and north of the map's bottom left corner, or click it on the map. Click a report on the map to remove it.
  4. Set the weather at the time of the reports. Wind direction is where the wind comes from, so 250 means a wind from the west-southwest. The sky setting decides how quickly the cloud spreads sideways.
  5. Read the result. The blue shading is where the source could be, darker is more likely. The solid outline holds half the chance and the dashed outline holds 9 chances in 10. The X is the most likely source.
  6. To decide where the next report should come from, look at the dashed rings. Fill in the top suggestion puts the best one into the position boxes.
  7. Tick Downwind hazard to shade where the air is likely above a hazard level, given everything still uncertain about the source.

Load an example (under Mode) fills in a made-up incident on synthetic terrain centred at 0° N, 0° E, so the terrain wind and the estimate can be seen without an elevation file. It is not a real place.

Test mode hides a release on the map and simulates every report from it, so the method can be checked against a known answer. It opens with one confirmed alarm inside the true cloud. Add detectors by clicking or with the top suggestion, then Reveal true source to see the true source, its true cloud and how far off the estimate was.

Find a place and background map (Map area). Type a place name or address and press Search, then pick a result to centre the map there. Background map draws OpenStreetMap, or VWorld street and satellite maps when the page has a VWorld key, under the estimate. Both are online services run by others: the search receives the words typed and the map service receives the area viewed. For practice that is fine. For a real location that must stay private, leave them off and type the latitude and longitude, which works fully offline. The background map is off by default and turns on only when chosen, or after a place search from the same service.

Map area sets the map size (4, 8 or 16 km across) and, optionally, where on Earth it is. With a centre latitude and longitude set, reports can be entered and read in latitude and longitude, and the result shows the most likely source in both. Load an elevation file to draw shaded relief and read the elevation under the pointer. Moving or resizing the map keeps entered reports at the same place on the ground.

With elevation loaded and Let the wind and the plume follow the terrain ticked (the default), the wind bends around hills and along valleys and every plume follows it (see Terrain wind below). Show wind arrows draws the field. Untick the box to compare with flat ground.

Elevation without a file. On the blog copy of the page, Load elevation automatically fetches the Copernicus GLO-30 elevation under the map through the blog's relay, which reads the tile from the public Copernicus collection on AWS and averages it to about 90 m. Only the 1° square (about 110 km across) is sent, never the map position. Squares with no tile are open sea and are set to sea level. The setting is remembered in the browser, and loading a file turns it off.

Getting elevation data. The page reads GeoTIFF and ESRI ASCII grid files in latitude and longitude (EPSG:4326), one band, uncompressed, LZW or Deflate. That covers the Copernicus DEM GLO-30 tiles, which are free and 30 m resolution. They can be downloaded after a free registration from the Copernicus Data Space Ecosystem, or through OpenTopography. Each tile covers one degree by one degree, so pick the tile that contains the area. Files in a projected system, such as UTM or the Korea 2000 grids, are refused with a message. Convert them first with GDAL, for example gdalwarp -t_srs EPSG:4326 in.tif out.tif. Use public data only (see Ground rules).

Weather stations. Under Weather, Load station wind files reads wind observations from several stations and spreads them over the map, so the wind can differ from one side of the map to the other. With elevation loaded the station winds are then bent around the terrain. Set the map centre first, since stations are placed by latitude and longitude.

  • Load one file with station, time, wind direction and wind speed, plus a station list with latitude and longitude if the observations lack them. Both can be chosen at once. Column names may be Korean or English (지점, 일시, 풍향, 풍속, 위도, 경도, or stn, time, wd, ws, lat, lon), and files may be UTF-8 or EUC-KR, the encoding of KMA data portal downloads. Gust columns are ignored.

  • Set Time of the reports. Each station's wind is the vector average over the chosen minutes up to that time. Times are compared as written, so use the same clock as the files (KST for KMA).

  • Stations within 30 km of the map centre are used, the nearer ones counting more (inverse distance squared). The table lists each station's distance and wind. The page warns when the nearest station is over 10 km away or when a station's wind swung around during the averaging time.

  • A KMA station number can be reused after a station moves. A station list with start and end dates (시작일, 종료일) is read so the position valid at the report time is used.

  • While station winds are on, the wind boxes show the wind at the map centre and cannot be edited. Untick Use station winds to type one again.

  • Air stability from measured weather. When KMA synoptic hourly data is loaded (the fetch includes it, or load a kma_sfctm2.php file), the page sets the stability class itself. By day it uses measured sunlight and wind (EPA's solar radiation method, SRDT). At night, or when sunlight was not measured, it uses Turner's method from cloud cover, cloud height and the sun's angle. Both are from US EPA, EPA-454/R-99-005, section 6.4. The nearest station within 60 km with a report in the last two hours is used, and the page says which and why. Untick Set air stability from measured cloud and sun to use the sky setting instead.

  • KMA API Hub text output is read as it comes: AWS minute data (nph-aws2_min), the AWS station list (stn_inf.php) and synoptic hourly data (kma_sfctm2.php, direction in tens of degrees). In KMA data a direction of 360 means calm.

  • The table shows each station's ground height. A station far above the others, such as one on a hilltop, is flagged. Untick it to leave it out.

Fetch winds from KMA appears on the blog copy of the page. It asks the blog's relay for every automatic weather station's 1 minute wind over the chosen minutes up to the report time, and the station list, then uses the stations near the map. The relay holds the API key, so it never reaches the browser, and the map position is not sent. Run from this repo the page has no relay, so load files instead.

Where to get the data. KMA automatic weather station (AWS) and synoptic (ASOS) observations, and the station list with positions, are published on the KMA data portal (data.kma.go.kr) as CSV downloads and through the KMA API Hub (apihub.kma.go.kr) with a free key and a usage application (활용신청) for each service. Data: Korea Meteorological Administration. Use public data only (see Ground rules).

Advanced settings holds air stability, city or open ground, how much to trust the wind report, the mixing depth for the terrain wind, the assumed release height and the alarm level.

How it works

File What it is
index.html The page. Canvas map, controls and report table
terrain.js Elevation reader (GeoTIFF, ASCII grid), local map frame, shaded relief
wind.js Terrain wind (mass-consistent layer), streamlines, plumes that follow them. Starts from one typed wind or from station winds
stability.js Air stability from measured weather: sun position (NOAA), Turner's method and EPA's SRDT method
basemap.js Optional background map tiles (OpenStreetMap, VWorld) placed on the local map frame, and place search
stations.js Reads weather station files (KMA AWS or any table with station, time, wind, position), averages them for the report time and spreads them over the map
plume-core.js Plume model, report likelihoods, grid inference, next detector hint, hazard sampling
test/plume-core.test.js Tests, including calibration and hint checks
test/terrain.test.js Elevation reader tests against synthetic GeoTIFF files in several encodings
test/wind.test.js Terrain wind tests: flat ground, mass conservation, hill, valley, calibration
test/fixtures/ The synthetic test files and how they were made
test/stability.test.js Sun position, sunrise and sunset, Turner and SRDT tables, worked cases
test/basemap.test.js Tile numbering, zoom choice, full coverage of the map with no gaps, search result reading
test/stations.test.js Station file reading (EUC-KR, Korean headers, relocation history), averaging, interpolation, and the wind solver with a varying starting wind
test/validation.test.js Fast checks on the field data file and its helpers
validation/sagebrush.mjs Scores the model and the estimate against Project Sagebrush Phase 1 (npm run validate)
validation/data/psb1.txt Compact copy of the NOAA tracer and weather data used
scripts/blog-copy.mjs Makes the blog's copy of the simulator
.github/workflows/blog-sync-reminder.yml Opens a reminder issue when the blog copy falls behind
scripts/serve.js Tiny preview server for npm start, no dependencies

Forward model. A steady Gaussian plume with full ground reflection.

C(x, y) = Q / (π u σy σz) · exp(−y² / 2σy²) · exp(−H² / 2σz²)

x is distance downwind, y is distance across the wind, u is wind speed and H is release height. Plume width σy and depth σz grow with x following Briggs (1973), with separate open country and urban curves for each Pasquill stability class. Split classes such as B‑C average the two neighbours. Wind below 1 m/s is raised to 1 m/s because the model has no meaning in calm air.

Inference. Every 125 m cell is tried as the source, with 30 release rates on a log scale from 0.1 to 10,000 g/s and 7 wind directions spread across ±2σ of the reported wind. Each combination is scored by how well its predicted concentrations match the reports.

  • A reading is compared on a log scale, so being off by a factor of two costs the same at any concentration.
  • A detect / clear report uses the chance that a detector alarms given the true concentration, with a 2% false alarm rate and a 5% miss rate.
  • The scoring adds a model error of about a factor of two on top of detector noise. Without it the grid and the plume model's own error made the answer overconfident and the true source fell outside the 90% area.

The scores are turned into probabilities. The map shows the total for each cell, and the release rate panel shows the median and 5 to 95% range.

Calibration on simulated data. Over 30 random simulated scenarios with 10 scattered detectors, the 90% area held the true source 28 times (93%). The test suite repeats this with 20 scenarios and fails below 75%. This checks the method against its own model only. The first real field data check, against Project Sagebrush Phase 1, is in validation/README.md.

First alarm. In test mode the first report of each scenario is placed where the real plume reads at least three times the alarm level, and it is treated as confirmed, so it cannot be a false alarm. Without that, a run of clear reports let the model explain everything as two false alarms plus a tiny release anywhere on the map, and the search area spread over most of it.

Next detector hint. About 120 likely source locations are drawn from the current answer, each with 8 draws of release rate and wind error. For every spot on a 24 × 24 grid the hint works out the chance of each possible report there. Detect / clear has two outcomes. Readings are grouped into ten bands from 0.003 to 30 mg/m³. The score is the expected information about the source location, in bits.

info = H(report) − average over locations of H(report | location)

Release rate and wind error are averaged out inside each location, so a spot that would only pin down the rate scores low. The three best spots are shown at least 1 km apart and never on top of an existing detector.

Does the hint help? Fourteen random scenarios started from the first alarm and two random detectors, then added six more either at random or at Try 1.

Reports Placement Median 90% area Median miss Truth inside 90% area
Detect / clear Random 9.8 km² 908 m 14 of 14
Detect / clear Hint 4.4 km² 350 m 14 of 14
Reading Random 8.3 km² 961 m 14 of 14
Reading Hint 1.0 km² 209 m 14 of 14

The tests check that the hint beats random placement for both report types.

Position spread. The true source can be anywhere inside its grid square, and a detector's reported position is never exact. The location answer is therefore smoothed by a Gaussian of 100 m or one grid square, whichever is larger. Before this, readings plus the hint pinned the source so tightly (0.3 km²) that the 90% area held the truth only 11 times in 14. With it, 14 of 14, at the cost of a somewhat larger area.

Terrain wind. With elevation loaded, the wind is the field closest to the reported wind that still conserves mass in a shallow layer of air. The layer's top is flat, at the lowest ground on the map plus a mixing depth, so it thins where the ground rises.

minimise ∫ h |v − v0|²  subject to  ∇·(h v) = 0
which gives  v = v0 + ∇λ  with  ∇·(h ∇λ) = −∇·(h v0)

h is the layer thickness and v0 the reported wind. The equation for λ is solved on a 64 × 64 grid by preconditioned conjugate gradients, with λ = 0 just outside the map so air can enter and leave. Ground that reaches above the layer top keeps 5% of the depth, so flow there is strongly blocked but not impossible. This is the idea behind diagnostic wind models such as the US Forest Service's WindNinja, reduced to a single layer.

The mixing depth decides how much the terrain matters. A shallow layer, typical of a clear night, sends air around hills and along valleys. A deep layer, typical of a sunny afternoon, lets it pass over them. The default comes from the stability class: 1,500 m for A down to 800 m for D, 400 m for E and 200 m for F. These are rough assumed values. Daytime mixed layers over land typically grow to between 1 and 4 km by late afternoon (AMS Glossary of Meteorology), and night layers are much shallower. Enter a measured or forecast depth under Advanced settings when one is available.

Each plume then follows the streamline from its source, traced in 125 m midpoint steps. Distance along the streamline and distance across it replace the straight downwind and crosswind distances in the plume formula, and the wind speed is the mean along the path. On flat ground the streamline is straight, and the tests check that the result is identical to the straight plume.

Calibration over terrain. Twenty-four simulated releases on each of two synthetic terrains (a winding valley between 450 m ridges, and two isolated hills), in stability C to F, starting from a confirmed alarm and adding five detectors at the top suggestion. Truth and model share the terrain wind, so this checks the estimate, not the wind model.

Terrain Reports Truth inside 90% area Median miss Median 90% area
Valley Alarm or no alarm 23 of 24 520 m 5.0 km²
Valley Reading 23 of 24 266 m 0.9 km²
Hills Alarm or no alarm 24 of 24 445 m 6.0 km²
Hills Reading 24 of 24 263 m 1.1 km²

Hazard area. 160 sources are drawn from the answer, each with its own rate and wind direction. A cell is shaded where at least 10% of those plumes pass the hazard level.

Verification log

Item Checked against Date Result
Briggs open country σy, σz (A to F) Hanna, Briggs and Hosker (1982), Table 4.5 2026‑11‑30 Match
Briggs urban σy, σz (A‑B, C, D) Same table 2026‑11‑30 Match
Briggs urban σz for E‑F Same table 2026‑11‑30 Open. Code uses 0.08x(1 + 0.0015x)^−½. The scanned text could also read 0.00015. Check the printed page.
Pasquill class from wind, sun and cloud Same handbook, Table 4.1 2026‑11‑30 Match for all legible cells
Night with wind under 2 m/s Same table 2026‑11‑30 Blank in the source. Code assumes F and the page says so.
Plume equation Standard ground reflected form 2026‑11‑30 Unit test against hand calculation
GeoTIFF reader Synthetic files from tifffile (none, Deflate with float predictor, LZW with integer predictor, big endian, tiled, pixel is point) 2026‑11‑30 Every value matches
GeoTIFF reader on a GDAL COG A 2400 × 2000 Cloud Optimized GeoTIFF written by GDAL like the Copernicus tiles (Deflate, float predictor, 1024 tiles, overviews) 2026‑11‑30 Sum, peak and bounds match exactly, read in about 0.5 s
Local map frame One degree of latitude 111.2 km, longitude scaled by cos(latitude) 2026‑11‑30 Unit test
Terrain wind on flat ground Reported wind 2026‑11‑30 Unchanged to machine precision
Curved plume on flat ground Straight plume 2026‑11‑30 Identical at 800 test points
Mass conservation Net flux of each cell 2026‑11‑30 Below 10⁻⁵ of one face's flux
Terrain wind behaviour Hill and valley tests 2026‑11‑30 Shallow layer goes round a hill and turns along a valley, deep layer goes over
Terrain wind against measured wind Not done. Needs field data
Station file reading Synthetic EUC-KR files with KMA style Korean headers, a missing value and a relocated station 2026‑12‑01 Unit tests
Station wind field One uniform station field against the typed wind, with terrain and with wind offsets 2026‑12‑01 Identical to 10⁻⁹
Varying station field Converging winds on flat ground 2026‑12‑01 Mass conserved, air leaves north and south
Station winds against real KMA files KMA API Hub output, central Seoul, 30 Nov 2022 09:00 KST: KMA's own 10 minute wind and the synoptic hourly report 2026‑12‑01 283.5° 4.07 m/s against 280.1° 4.1 m/s and 270° 4.1 m/s

Limits

  • The terrain wind is a single shallow layer with a flat top. It catches flow round hills and along valleys, but not slope winds at night, flow separation behind ridges, or wind that changes with height. It has not been compared with measured wind.
  • Station winds are spread by inverse distance, which knows nothing about terrain between stations. With elevation loaded the field is then adjusted to the terrain, but a station in a valley still speaks for the ridge beside it.
  • Station winds are measured near 10 m. The plume model uses that wind as is.
  • Steady state. No puffs, no wind shifts, no travel time.
  • With terrain on, an update takes about a second, because every possible source traces its own streamline. Moving the work off the page's main thread is on the roadmap.
  • One source, no deposition, no decay, no dense gas behaviour.
  • Briggs curves are fitted for 100 m to 10 km. Closer than 100 m the model extrapolates. The rough ground curves are the default because they matched the Project Sagebrush field data; that choice has been checked at one site only.

Roadmap

See ROADMAP.md.

Sources

  • Hanna, S. R., Briggs, G. A. and Hosker, R. P. (1982). Handbook on Atmospheric Diffusion. DOE/TIC‑11223, U.S. Department of Energy. OSTI record
  • NOAA Office of Response and Restoration, ALOHA, the free forward model used by emergency responders
  • Lawrence Livermore National Laboratory report on probabilistic source term estimation from field measurements with Markov chain Monte Carlo, OSTI 908126
  • Hutchinson, M., Oh, H. and Chen, W.‑H. (2017). A review of source term estimation methods for atmospheric dispersion events. Information Fusion 36, 130 to 148. Author copy

About

Offline CBRN training tools from public sources: a heat stress planner for protective gear (iPhone) and a chemical source tracking simulator (browser).

Topics

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages