Footprints And Particles#

Each simulation is one release run under one variant (Projects And Variants). It has up to two results in the output directory:

  • the particles, where every particle went, as a Parquet file

  • the footprint, when the variant has a grid, as a Parquet file of the cells the particles touched

Variants that differ only in footprint settings share one set of particles.

Look at both before you trust a batch. We plot the particles of a few simulations first, because they show where the air went whatever the footprint grid, and only then load the footprints for analysis. Summing Footprints: Areas And The Jacobian sums footprints over areas, and many at once into a Jacobian.

Quick look#

Open the project, pick a simulation, and plot it:

In [1]: import stilt

In [2]: project = stilt.Project("./my_project")

In [3]: sim = project.simulation("202101150800_-111.848_40.766_10", "hrrr")

In [4]: sim.footprint.stilt.plot.map();   # footprint, summed over time

In [5]: sim.particles.stilt.plot.map();   # particle paths

In [6]: sim.plot.map();                   # release, particles, and footprint together
../_images/outputs_footprint.png ../_images/outputs_particles.png ../_images/outputs_simulation.png

A simulation is named by its release id and its variant. To see them all, look at project.simulations, a DataFrame with one row per simulation:

In [7]: project.simulations[["release", "variant"]]
Out[7]: 
                           release variant
0  202101150600_-111.848_40.766_10    hrrr
1  202101150700_-111.848_40.766_10    hrrr
2  202101150800_-111.848_40.766_10    hrrr
3  202101150900_-111.848_40.766_10    hrrr

Plotting needs the visualization extra. If cartopy is installed, maps also show coastlines and state borders. There are a few other plots:

  • foot.stilt.plot.facet() draws one panel per hour.

  • release.plot.map() shows where the release is.

  • project.plot.availability() shows the release times at each location.

In [8]: sim.footprint.stilt.plot.facet();

In [9]: project.plot.availability();

In [10]: sim.release.plot.map();
../_images/outputs_facet.png ../_images/outputs_availability.png ../_images/outputs_release.png

A map takes a tiler, any cartopy tiler, to draw map tiles under the data. The maps in these docs are drawn on shaded-relief tiles of the USGS National Map, which are kept in the repository so that building the docs needs no network for them. Your own maps can use the same tiles. cartopy downloads them when the map is drawn, and cache=True keeps what it downloaded:

from cartopy.io.img_tiles import GoogleTiles

usgs = GoogleTiles(
    url="https://basemap.nationalmap.gov/arcgis/rest/services/USGSShadedReliefOnly/MapServer/tile/{z}/{y}/{x}",
    cache=True,
)
sim.plot.map(tiler=usgs)

Footprints#

A footprint is an xarray.DataArray:

In [11]: sim.has_footprint        # True once the footprint file exists
Out[11]: True

In [12]: foot = sim.footprint     # raises FileNotFoundError before that

It has dimensions (time, lat, lon), or (time, y, x) on a projected grid. There is one map for each hour back from the release time (each tres back, when the footprint settings give another length), in units of ppm per (µmol m⁻² s⁻¹). foot.sum("time") is one map of the whole run. Use xarray as you would on any other array:

In [13]: total = foot.sum("time")                                     # summed over time

In [14]: last_hours = foot.sel(time=slice("2021-01-15 02:00", "2021-01-15 07:00"))

Methods that need the release or the grid are under foot.stilt:

In [15]: foot.stilt.release      # the release
Out[15]: PointRelease(id='202101150800_-111.848_40.766_10', lon=-111.84800, lat=40.76600, alt=10 agl)

In [16]: foot.stilt.grid          # the grid it was made on
Out[16]: Grid(xmin=-113.0, xmax=-110.5, ymin=40.0, ymax=42.0, xres=0.01, yres=0.01, crs='+proj=longlat')

In [17]: foot.stilt.config        # all the footprint settings
Out[17]: FootprintConfig(grid=Grid(xmin=-113.0, xmax=-110.5, ymin=40.0, ymax=42.0, xres=0.01, yres=0.01, crs='+proj=longlat'), geometry=None, cells_per_target=4.0, smooth_factor=1.0, tres='1h', hnf_plume=True, footprint_depth=0.5, pbl_height=None, pbl_height_min=0.0, transforms=[], geometry_hash=None)

The release id is also a coordinate, foot.release. It stays on the array through sums and arithmetic.

stilt.read_footprint opens a footprint file from the output directory, such as sim.footprint_path, with nothing else around it. To write one as NetCDF for other tools, see Results in other tools.

Particles#

In [18]: sim.has_particles           # True once the particle file exists
Out[18]: True

In [19]: particles = sim.particles   # raises FileNotFoundError before that

sim.particles is a pandas DataFrame with one row per particle per time step.

The columns you are most likely to use:

Column

Meaning

lon / lat

Particle longitude and latitude (STILT-R’s long / lati)

zagl

Particle height above ground, m

age

Minutes since release, negative for a backward run (STILT-R’s time)

time

Time of the row, UTC, built from age when the table is read

foot

The particle’s influence from the surface at this step, in ppm per (µmol m⁻² s⁻¹)

particle

Particle number (STILT-R’s indx)

release_height

Release height, for column and multipoint releases (STILT-R’s xhgt)

mlht, sigw, tlgr, pres

Mixed-layer height, vertical velocity spread, Lagrangian time scale, and pressure

The Particle Table says what each column is, its units, and what a transport model must write.

PYSTILT’s methods for the particle table are under particles.stilt:

In [20]: particles.stilt.endpoints()    # where each particle ends, one row each
Out[20]: 
         age  particle       lon  ...   sigw   tlgr                time
63040 -334.0       1.0 -112.1365  ...  0.776  100.0 2021-01-15 02:26:00
74674 -547.0       2.0 -112.3070  ...  0.071  100.0 2021-01-14 22:53:00
65550 -359.0       3.0 -112.2374  ...  0.949  100.0 2021-01-15 02:01:00
55455 -282.0       4.0 -112.1046  ...  0.237  100.0 2021-01-15 03:18:00
59587 -308.0       5.0 -112.1333  ...  0.283  100.0 2021-01-15 02:52:00
...      ...       ...       ...  ...    ...    ...                 ...
49317 -247.0     196.0 -112.2293  ...  0.205  100.0 2021-01-15 03:53:00
50840 -255.0     197.0 -112.1957  ...  0.185  100.0 2021-01-15 03:45:00
63617 -338.0     198.0 -112.1395  ...  0.791  100.0 2021-01-15 02:22:00
69517 -421.0     199.0 -112.2789  ...  0.356  100.0 2021-01-15 00:59:00
64255 -344.0     200.0 -112.1801  ...  0.628  100.0 2021-01-15 02:16:00

[200 rows x 13 columns]

In [21]: particles.stilt.plot.map();    # map of every particle position
../_images/outputs_all_particles.png

To open a particle file without a project:

path = (
    "output/particles/settings=hrrr-a3f9c2/date=2021-01-15/"
    "202101150800_-111.848_40.766_10.parquet"
)
particles = stilt.read_particles(path)
meta = runtraj.particles.particles_metadata(path)
meta.release, meta.settings, meta.met_files, meta.realization

The file holds the release, the meteorology files the run read, and the settings it ran with, the same ones as its folder’s _settings.yaml. realization is which realization of an ensemble the file is, or None for a single run. Output Layout lists every key.

Empty footprints#

A footprint that no particle reached is a file with no cells: the simulation is complete, sim.has_footprint is true, and sim.footprint is None. project.footprints() lists it in attrs["empty"], and a Jacobian in H.empty. It is not a footprint of zeros; Checking A Run says what it means and what to do.

Many simulations at once#

project.simulations is a table with one row per release under each variant. Its columns are:

  • release, the release id

  • variant, the variant name

  • realization, 0 to N - 1 for a variant declared with realizations: N, and empty for one that runs once.

  • time, kind, and location of the release

  • one column for each extra column of releases.csv

Select rows the way you would in pandas, then hand the selection to the project to load its results:

In [22]: sims = project.simulations

In [23]: morning = sims[
   ....:     (sims.variant == "hrrr")
   ....:     & sims.time.between("2021-01-15 06:00", "2021-01-15 09:00")   # both ends included
   ....: ]
   ....: 

In [24]: footprints = project.footprints(morning)   # one dataset: release, hour, lat, lon

In [25]: particles = project.particles(morning)     # one table, with release and variant columns

Leave the selection out to load every simulation. Any table with release and variant columns works as a selection, such as your observations merged with sims, or a polars or pyarrow table, and so does a boolean mask over project.simulations.

The footprints of one variant come back as one xarray.Dataset with dimensions (release, hour, lat, lon). Releases at different times cannot share a time axis, so they line up on hour: the hours after each release’s time, where a backward run’s first hour is -1. With other layers the dimension is named for the unit tres is written in (day for 1D, minute for 15min) and counts in it. The time coordinate gives the clock time each release’s hours start:

In [26]: import numpy as np

In [27]: rid = morning.release.iloc[0]                         # the first release

In [28]: mean = footprints.foot.sum("hour").mean("release")    # the mean footprint

In [29]: np.log10(mean.where(mean > 0)).plot();                 # most cells are 0: use a log scale

In [30]: footprints.foot.sel(release=rid)                      # one release's hours
Out[30]: 
<xarray.DataArray 'foot' (hour: 14, lat: 200, lon: 250)> Size: 3MB
dask.array<getitem, shape=(14, 200, 250), dtype=float32, chunksize=(14, 200, 250), chunktype=numpy.ndarray>
Coordinates:
  * hour     (hour) int64 112B -14 -13 -12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1
    time     (hour) datetime64[us] 112B 2021-01-14T16:00:00 ... 2021-01-15T05...
  * lat      (lat) float64 2kB 40.01 40.02 40.02 40.03 ... 41.98 41.98 41.99
  * lon      (lon) float64 2kB -113.0 -113.0 -113.0 ... -110.5 -110.5 -110.5
    release  <U31 124B '202101150600_-111.848_40.766_10'
Attributes:
    units:         ppm m2 s umol-1
    long_name:     footprint
    grid_mapping:  crs

In [31]: footprints.time.sel(release=rid)                      # and when they start
Out[31]: 
<xarray.DataArray 'time' (hour: 14)> Size: 112B
array(['2021-01-14T16:00:00.000000', '2021-01-14T17:00:00.000000',
       '2021-01-14T18:00:00.000000', '2021-01-14T19:00:00.000000',
       '2021-01-14T20:00:00.000000', '2021-01-14T21:00:00.000000',
       '2021-01-14T22:00:00.000000', '2021-01-14T23:00:00.000000',
       '2021-01-15T00:00:00.000000', '2021-01-15T01:00:00.000000',
       '2021-01-15T02:00:00.000000', '2021-01-15T03:00:00.000000',
       '2021-01-15T04:00:00.000000', '2021-01-15T05:00:00.000000'],
      dtype='datetime64[us]')
Coordinates:
  * hour     (hour) int64 112B -14 -13 -12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1
    time     (hour) datetime64[us] 112B 2021-01-14T16:00:00 ... 2021-01-15T05...
    release  <U31 124B '202101150600_-111.848_40.766_10'
Attributes:
    standard_name:  time
    axis:           T
../_images/outputs_mean_footprint.png

The values are read from the files only when a computation needs them, a day’s releases at a time, so opening a month of footprints is quick. Loading them all at once takes about 35 MB per footprint on a 300 by 300 grid over 24 hours. Select one variant first, as above; a selection of several raises an error. Releases whose footprint is empty are listed in footprints.attrs["empty"], and those not run yet in footprints.attrs["missing"].

For one release, project.simulation(rid, "hrrr").footprint is its footprint as a xarray.DataArray with absolute times, which the foot.stilt methods work on.

To sum a selection’s footprints onto your flux cells, as one matrix, use project.jacobian (Summing Footprints: Areas And The Jacobian).

The particles come back as one table, so pandas can group them:

In [32]: particles.groupby("release")["foot"].sum()
Out[32]: 
release
202101150600_-111.848_40.766_10     88.836758
202101150700_-111.848_40.766_10     95.820162
202101150800_-111.848_40.766_10    165.770876
202101150900_-111.848_40.766_10    279.965419
Name: foot, dtype: float64

A simulation whose result does not exist yet is left out. Loading particles takes 10 to 20 MB per simulation. For thousands of simulations, read the particles/ folder of the output directory with pyarrow, DuckDB, or polars instead. To find a single file, use sim.footprint_path or sim.particles_path.

To work with one simulation of a selection, look it up by its row:

In [33]: for release, variant in morning[["release", "variant"]].itertuples(index=False):
   ....:     sim = project.simulation(release, variant)
   ....: 

The extra columns of releases.csv select one satellite scene or one site:

scene = sims[(sims.variant == "hrrr") & (sims.scene == "A")]
ensemble = sims[sims.variant == "hrrr-err"]        # every realization of every release

To see what is left to do:

In [34]: project.incomplete()       # the simulations that are not complete
Out[34]: 
Empty DataFrame
Columns: [release, variant, realization, model, time, kind, location]
Index: []

In [35]: st = project.status()      # every simulation, with what it has and where it stands

In [36]: st.state.value_counts()
Out[36]: 
state
complete       4
failed         0
interrupted    0
pending        0
Name: count, dtype: int64

In [37]: st[st.state == "failed"]   # the failed simulations, and why
Out[37]: 
Empty DataFrame
Columns: [release, variant, realization, model, time, kind, location, particles, footprint, state, stage, reason, message]
Index: []

In [38]: project.status(morning)    # the same, for a selection
Out[38]: 
                           release variant  ... reason message
0  202101150600_-111.848_40.766_10    hrrr  ...   <NA>    <NA>
1  202101150700_-111.848_40.766_10    hrrr  ...   <NA>    <NA>
2  202101150800_-111.848_40.766_10    hrrr  ...   <NA>    <NA>
3  202101150900_-111.848_40.766_10    hrrr  ...   <NA>    <NA>

[4 rows x 13 columns]

None failed here, so the table of failed simulations is empty.

status() adds a particles and a footprint column that say whether each result exists, and a state column: complete, failed, interrupted, or pending. For a failed simulation, stage, reason, and message say why. Checking A Run explains each state and reason. status() opens no result file, so it is quick on a large project.

Results in other tools#

A footprint can be written as a CF NetCDF file, the particles as CF trajectories, and a footprint in the PARIS format that openghg reads.

Footprints as NetCDF#

In [39]: foot.stilt.to_netcdf("footprint_2021-01-15_08.nc")
Out[39]: PosixPath('footprint_2021-01-15_08.nc')

In [40]: foot = stilt.read_footprint("footprint_2021-01-15_08.nc")

The file follows the CF-1.8 conventions and records the release and the settings used to make it, so stilt.read_footprint reads it back whole.

Particles in trajan and other CF tools#

sim.particles.stilt.to_cf_trajectories() returns the particles as an xarray.Dataset that follows the CF-1.10 conventions for trajectories, which trajan, cf-xarray, and other tools that read CF trajectory files open:

In [41]: ds = sim.particles.stilt.to_cf_trajectories()

In [42]: ds
Out[42]: 
<xarray.Dataset> Size: 15MB
Dimensions:     (trajectory: 200, obs: 806)
Coordinates:
  * trajectory  (trajectory) int32 800B 1 2 3 4 5 6 ... 195 196 197 198 199 200
    time        (trajectory, obs) datetime64[ns] 1MB 2021-01-15T08:59:00 ... NaT
    lon         (trajectory, obs) float64 1MB -111.8 -111.8 -111.8 ... nan nan
    lat         (trajectory, obs) float64 1MB 40.77 40.77 40.77 ... nan nan nan
    zagl        (trajectory, obs) float64 1MB 13.15 16.08 18.86 ... nan nan nan
Dimensions without coordinates: obs
Data variables:
    age         (trajectory, obs) float64 1MB -1.0 -2.0 -3.0 ... nan nan nan
    foot        (trajectory, obs) float64 1MB 0.02121 0.02121 ... nan nan
    mlht        (trajectory, obs) float64 1MB 150.0 150.0 150.0 ... nan nan nan
    pres        (trajectory, obs) float64 1MB 860.8 860.3 859.8 ... nan nan nan
    dens        (trajectory, obs) float64 1MB 1.093 1.092 1.091 ... nan nan nan
    samt        (trajectory, obs) float64 1MB 1.0 1.0 1.0 1.0 ... nan nan nan
    sigw        (trajectory, obs) float64 1MB 0.001 0.001 0.002 ... nan nan nan
    tlgr        (trajectory, obs) float64 1MB 1.321e+04 1.298e+04 ... nan nan
Attributes:
    Conventions:  CF-1.10
    featureType:  trajectory
    title:        runtraj particle trajectories
    source:       runtraj particle table
    history:      Converted from a runtraj particle table

Write it with xarray.Dataset.to_netcdf(). A particle table from stilt.run_trajectories() converts the same way.

Each particle is one trajectory. The coordinates are:

trajectory

The particle number, marked cf_role: trajectory_id.

time

The particle table’s time, in UTC.

lon, lat

Longitude and latitude in degrees.

zagl

Height above ground in meters (standard_name: height).

age, the minutes since release, is a data variable, and so is every other numeric column of the table (foot, mlht, …). The columns PYSTILT and HYSPLIT write have units and long names; another column is kept without units. A table with several realizations is refused: select one first, particles[particles.realization == k].

Every variable has dimensions (trajectory, obs), CF’s incomplete multidimensional array (CF-1.10, appendix H.4). obs counts output steps from the release, so in a backward run time decreases along it. A particle that leaves the meteorology domain stops early, and the rest of its row is missing values.

trajan reads the file through its traj accessor:

import trajan  # registers ds.traj
import xarray as xr

ds.to_netcdf("trajectories.nc")
ds = xr.open_dataset("trajectories.nc", decode_timedelta=False)
ds.traj.plot()

decode_timedelta=False keeps age in minutes rather than reading it as a duration.

Footprints for openghg#

sim.footprint.stilt.to_paris(sim.particles) returns the footprint in the PARIS format, the NetCDF layout openghg reads with source_format="paris". openghg can then combine it with its fluxes and boundary conditions as it does footprints from NAME and FLEXPART. The footprint must have hourly layers (tres: 1h, the default) on a longitude and latitude grid and be backward.

In [43]: paris = sim.footprint.stilt.to_paris(sim.particles)

In [44]: paris
Out[44]: 
<xarray.Dataset> Size: 11MB
Dimensions:               (time: 1, latitude: 200, longitude: 250,
                           resolution: 24, height: 20)
Coordinates:
  * time                  (time) datetime64[ns] 8B 2021-01-15T09:00:00
  * latitude              (latitude) float64 2kB 40.01 40.02 ... 41.98 41.99
  * longitude             (longitude) float64 2kB -113.0 -113.0 ... -110.5
  * resolution            (resolution) float32 96B 0.0 1.0 2.0 ... 22.0 23.0
  * height                (height) float64 160B 500.0 1.5e+03 ... 1.95e+04
Data variables:
    srr                   (time, latitude, longitude) float64 400kB 0.0 ... 0.0
    srr_time_resolved     (time, latitude, longitude, resolution) float64 10MB ...
    srr_residual          (time, latitude, longitude) float64 400kB 0.0 ... 0.0
    particle_locations_n  (time, height, longitude) float64 40kB 0.0 0.0 ... 0.0
    particle_locations_e  (time, height, latitude) float64 32kB 0.0 0.0 ... 0.0
    particle_locations_s  (time, height, longitude) float64 40kB 0.0 0.0 ... 0.0
    particle_locations_w  (time, height, latitude) float64 32kB 0.0 0.0 ... 0.0
Attributes:
    Conventions:  CF-1.8
    model:        STILT
    source:       PYSTILT footprint
    release:      202101150900_-111.848_40.766_10
    history:      Converted from a PYSTILT footprint

openghg stores a time-resolved footprint along H_back, hours back from the footprint’s time, and pairs H_back = k with the flux hour that starts k hours before it. The footprint’s time is the release time. The first layer of a backward run, layer -1, covers the hour before the release time, so it goes to H_back = 1. With the release at 18:00:

H_back

Flux hour openghg pairs it with

PYSTILT layer

0

18:00 to 19:00

none, after the observation; always zero

1

17:00 to 18:00

-1

2

16:00 to 17:00

-2

23

19:00 to 20:00 the day before

-23

Layers -24 and earlier are summed into srr_residual, which openghg multiplies by a monthly mean flux, and srr is the sum of all layers. openghg resolves hours within one day, so 23 layers are kept by hour, not 24. The values are PYSTILT’s unchanged: ppm per (µmol m⁻² s⁻¹) is the same quantity as the PARIS units, (mol/mol)/(mol/m2/s).

In [45]: per_hour = paris.srr_time_resolved.sum(["latitude", "longitude"])

In [46]: per_hour.isel(time=0).values[:4]      # H_back 0 is empty; 1 is layer -1
Out[46]: array([0.        , 1.08723988, 0.01245038, 0.        ])

In [47]: float(paris.srr.sum() - paris.srr_time_resolved.sum() - paris.srr_residual.sum())
Out[47]: 0.0

One release of project.footprints().foot, footprints.foot.sel(release=rid), converts as sim.footprint does.

Pass the particles, as above: openghg also expects particle_locations_n, _e, _s and _w, the fraction of particles that first left the footprint grid through each edge, by cell along the edge and by 1 km height layer up to 20 km (grid_exits()). Without the particles these are left out, and openghg refuses the file unless told not to expect them. A particle that never left the grid counts nowhere, so the four add up to the share that left:

In [48]: float(sum(paris[f"particle_locations_{e}"].sum() for e in "nesw"))
Out[48]: 0.0

A PARIS file holds one site, with one entry along time for each release time. Convert each release, concatenate along time, write the file, and add it to openghg’s object store:

import xarray as xr

site = [project.simulation(r, v) for r, v in morning[["release", "variant"]].itertuples(index=False)]
ds = xr.concat(
    [s.footprint.stilt.to_paris(s.particles) for s in site],
    dim="time",
    combine_attrs="drop_conflicts",
)
ds.to_netcdf("WBB-10magl_STILT_HRRR_SLV_co2_202401.nc")

from openghg.standardise import standardise_footprint

standardise_footprint(
    filepath="WBB-10magl_STILT_HRRR_SLV_co2_202401.nc",
    source_format="paris",
    site="wbb",
    domain="slv",
    model="STILT",
    inlet="10m",
    met_model="hrrr",
    species="co2",
    time_resolved=True,
)

openghg is not a dependency of PYSTILT, and the versions of Python, pandas and numpy it supports can differ from PYSTILT’s. Write the files with PYSTILT and add them from an environment of their own (pip install openghg).

Without PYSTILT#

Output Layout describes every file and metadata key, for a reader in another language.

The output directory is a set of Parquet files in folders named settings=... and date=..., which many tools read as columns. With DuckDB, from Python, R, or its own shell, a question about thousands of simulations is one query:

-- footprints per settings folder and day
SELECT settings, date, count(DISTINCT release) AS footprints
FROM read_parquet('output/footprint/*/*/*.parquet', hive_partitioning = true)
GROUP BY settings, date
ORDER BY settings, date;

-- the total influence of each release's footprint
SELECT release, sum(foot) AS total
FROM read_parquet('output/footprint/settings=hrrr-93278c/*/*.parquet', hive_partitioning = true)
GROUP BY release;

-- where each particle of one day's releases ended up
SELECT release, particle, arg_min(lon, time) AS lon, arg_min(lat, time) AS lat
FROM read_parquet('output/particles/settings=hrrr-a3f9c2/date=2021-01-15/*.parquet', hive_partitioning = true)
GROUP BY release, particle;

A footprint file holds the cells the particles reached, as hour, y, and x (the cell’s row and column in the grid that the folder’s _settings.yaml gives) and foot. An empty footprint is a file with no rows, so a count of rows leaves it out. An ensemble’s folders have a realization=k level as well, so its files are one folder deeper (*/*/*/*.parquet) and realization is a column.