Ten Common AERMOD Jobs¶
Ten worked examples of the jobs AERMOD is most often run for, each done
end to end with pyaermod: build the project, validate it, write the
deck, run AERMOD, parse the results and draw a figure. Every code block
on this page is a complete script from
examples/use_cases/,
included here verbatim, and every figure is what that script drew when
it was run against AERMOD 26135.
Before you start¶
1. Install pyaermod with its plotting and GIS extras
(pip install "pyaermod[all]"), and put AERMOD on your PATH
(Install says how). pyaermod
writes and reads AERMOD's files; it does not ship the model. Check that it is
found:
Use case 8 also needs AERMAP on PATH, and downloads its terrain from USGS.
2. Get the meteorology. The scripts use one year (1988) of
AERMET-processed surface and profile data from the Lovett site in New
York's Hudson Valley, LOVETT.SFC and LOVETT.PFL, which EPA
distributes with the AERMOD test cases. Extract those files:
Use case 9 uses HOUSTON_ADJU.SFC/.PFL (Houston, 1996) instead,
because wet deposition needs hourly precipitation and every
precipitation value in LOVETT.SFC is missing.
For your own site, replace them with the .SFC/.PFL pair AERMET made
for it (see AERMET Tuning).
3. Run a script. Each script reads the met directory from
AERMOD_MET_DIR (default ./met) and writes its deck, AERMOD's
output and its figure under USE_CASE_OUT (default ./out):
The scripts are written to be copied: the inputs a user changes sit at the top, and nothing depends on the others. Emission rates, stack parameters and coordinates are illustrative, not from any real facility.
One year of met is a demonstration, not a permit analysis
Regulatory analyses use five years of representative National Weather Service data (or at least one year of site-specific data) and the averaging-period ranks the NAAQS sets. These examples use one year so each runs in under a minute or two.
1. Single stack, flat terrain: annual and 24-hour PM2.5¶
When you need it: You are permitting or screening a single new or modified stack. You need its annual and 24-hour PM2.5 impacts on a receptor grid to compare with the NAAQS or a significant impact level.
What it shows: Each AERMOD pathway built from pyaermod objects: ControlPathway, PointSource, CartesianGrid, MeteorologyPathway and OutputPathway, with period_plot_files writing one PLOTFILE per averaging period. Then Validator, run_aermod, the 8th-highest 24-hour summary table read with parse_aermod_output, and the per-receptor maps drawn from read_plotfile.
"""
Single stack, flat terrain: annual and 24-hour PM2.5.
One 40 m boiler stack on flat ground, a 4 km x 4 km Cartesian receptor grid and
a year of meteorology (EPA's LOVETT 1988 test data). Writes the AERMOD deck,
runs it, and maps the annual average and the highest 24-hour average.
"""
import os
from pathlib import Path
MET_DIR = Path(os.environ.get("AERMOD_MET_DIR", "met")) # holds LOVETT.SFC / LOVETT.PFL
WORK = Path(os.environ.get("USE_CASE_OUT", "out")) / "01_point_source"
WORK.mkdir(parents=True, exist_ok=True)
import matplotlib.pyplot as plt # noqa: E402
from pyaermod import ( # noqa: E402
AERMODProject,
CartesianGrid,
ControlPathway,
MeteorologyPathway,
OutputPathway,
PointSource,
PollutantType,
ReceptorPathway,
SourcePathway,
TerrainType,
Validator,
parse_aermod_output,
read_plotfile,
run_aermod,
)
# CO pathway: job title, pollutant and averaging periods. PM25 makes AERMOD
# average each 24-hour rank over the years of met data (the NAAQS form).
# MODELOPT FLAT only takes effect without DFAULT: under DFAULT AERMOD overrides
# it with ELEV (warning W206), so this flat-terrain run is non-regulatory.
control = ControlPathway(
title_one="Use case 1: single stack, flat terrain",
pollutant_id=PollutantType.PM25,
averaging_periods=["ANNUAL", "24"],
terrain_type=TerrainType.FLAT,
regulatory_default=False,
)
# SO pathway: one point source. Units are AERMOD's: m, K, m/s, g/s.
sources = SourcePathway()
sources.add_source(PointSource(
source_id="STACK1",
x_coord=0.0, y_coord=0.0, # m (local UTM-style coordinates)
stack_height=40.0, # m above ground
stack_temp=420.0, # K exit temperature
exit_velocity=12.0, # m/s
stack_diameter=1.5, # m
emission_rate=2.0, # g/s of primary PM2.5
))
# RE pathway: a 100 m Cartesian grid, 2 km out from the stack in every direction.
receptors = ReceptorPathway()
receptors.add_cartesian_grid(CartesianGrid.from_bounds(
x_min=-2000.0, x_max=2000.0, y_min=-2000.0, y_max=2000.0, spacing=100.0,
))
# ME pathway: the AERMET surface and profile files plus the station IDs and
# year from their headers, and the profile base elevation (m MSL).
meteorology = MeteorologyPathway(
surface_file=str((MET_DIR / "LOVETT.SFC").resolve()),
profile_file=str((MET_DIR / "LOVETT.PFL").resolve()),
surface_station_id=14735,
upper_air_station_id=14735,
data_start_year=1988,
profile_base_elevation=1.8,
)
# OU pathway: the summary tables in the .out file, plus one PLOTFILE per
# averaging period (the value at every receptor), which is what the maps need.
output = OutputPathway(
receptor_table=True, receptor_table_rank=8,
max_table=True, max_table_rank=10,
period_plot_files="pm25",
)
project = AERMODProject(control=control, sources=sources, receptors=receptors,
meteorology=meteorology, output=output)
# Validate before writing; warnings are allowed, errors stop here.
check = Validator.validate(project, check_files=True)
print(check)
if not check.is_valid:
raise SystemExit(1)
inp = project.write(WORK / "01_point_source.inp")
result = run_aermod(inp)
if not result.success:
raise SystemExit(f"AERMOD failed: {result.error_message}")
print(f"AERMOD finished in {result.runtime_seconds:.1f} s "
f"({result.warning_count} warnings)")
# The .out file's summary tables: one per averaging period and rank. For
# PM2.5 the 24-hour NAAQS design value uses the 8th-highest (98th percentile).
results = parse_aermod_output(result.output_file)
h8h = next(t for t in results.summaries if "8TH-HIGHEST 24-HR" in t.title).max_row
print(f"24-hour H8H: max {h8h['concentration']:.3f} ug/m3 at "
f"({h8h['x']:.0f}, {h8h['y']:.0f}) m")
# The plot files hold the annual average and the highest 24-hour average at
# every receptor. (The .out summary tables list only the top ten receptors,
# too few to contour, so the maps are drawn from the plot files.)
plot_names = output.period_plot_file_names(control.averaging_periods)
panels = [("ANNUAL", "Annual average"), ("24", "Highest 24-hour average (H1H)")]
fig, axes = plt.subplots(1, 2, figsize=(9, 5.4), constrained_layout=True)
for ax, (period, label) in zip(axes, panels):
plot = read_plotfile(WORK / plot_names[period])
df = plot.to_dataframe()
conc = df[plot.concentration_column]
peak = df.loc[conc.idxmax()]
print(f"{label}: max {conc.max():.3f} ug/m3 at "
f"({peak['X']:.0f}, {peak['Y']:.0f}) m")
cs = ax.tricontourf(df["X"], df["Y"], conc, levels=12, cmap="viridis")
ax.plot(0, 0, "^", ms=10, mfc="white", mec="black", label="STACK1")
ax.plot(peak["X"], peak["Y"], "*", ms=14, mfc="red", mec="black", label="Maximum")
ax.set(title=label, xlabel="Easting (m)", ylabel="Northing (m)", aspect="equal")
ax.legend(loc="lower right", fontsize=8)
fig.colorbar(cs, ax=ax, orientation="horizontal", label="Concentration (µg/m³)")
fig.suptitle("PM$_{2.5}$ from one 40 m stack (2 g/s), flat terrain, LOVETT 1988 met")
fig.savefig(WORK / "01_point_source.png", dpi=130)
print(f"Figure: {WORK / '01_point_source.png'}")
Result (AERMOD 26135, LOVETT 1988 met):

The annual average peaks at 0.431 µg/m³, 450 m east-southeast of the stack at (400, -200) m, and falls off along the prevailing downwind direction. The highest 24-hour average (H1H) is 4.177 µg/m³ at (200, -100) m. The 24-hour map is patchier because each receptor's highest day comes from a different wind direction. The 8th-highest 24-hour value, the rank the PM2.5 NAAQS uses, is 2.327 µg/m³ at (400, -200) m.
Adapting it
- Change the
PointSourcestack parameters andemission_rate(g/s), and size theCartesianGridso the maximum is well inside it. Here it is within 500 m of a 40 m stack. - Under the regulatory
DFAULToption, AERMOD ignoresMODELOPT FLATand runs with elevated terrain, logging warning W206. That is why this example setsregulatory_default=False. For a regulatory run, keepDFAULTand give receptors real elevations from AERMAP. On flat ground with zero elevations both give the same numbers here. - Short-term plot files write the highest (
FIRST) value by default. For a map of the 8th-highest, setOutputPathway(plot_file_rank=8)(or"H8H"), withreceptor_table_rankat least 8. The script reads the 8th-highest from the.outsummary tables (results.summaries);max_daily_files(MAXDAILY) is the route for NAAQS work. The design value needs five years of met: the 24-hour H8H and the annual average, each averaged over those years. - Put your own AERMET
.SFC/.PFLinMET_DIR. Then setsurface_station_id,upper_air_station_idanddata_start_yearfrom the surface file's header, andprofile_base_elevationto the station's base elevation (m MSL).
2. Facility with several stacks: source groups and a polar grid¶
When you need it: A facility has several emission points, and you need each part's share of the total impact. Examples are a boiler house against process vents, or existing units against a proposed modification. That share tells you which units to control, or which ones a permit limit should cover.
What it shows: Several PointSource objects, grouped with SourceGroupDefinition (AERMOD's SRCGROUP; ALL is added for you). A PolarGrid is centred on the facility. OutputPathway.plot_file_groups writes one PLOTFILE per group, and each is read with read_plotfile.
"""
Facility with several stacks: source groups and a polar grid.
Two boiler stacks and two process vents, grouped with SRCGROUP into BOILERS,
PROCESS and ALL, modelled on a polar receptor grid centred on the facility.
Maps each group's annual PM10 and compares the groups' maxima.
"""
import os
from pathlib import Path
MET_DIR = Path(os.environ.get("AERMOD_MET_DIR", "met")) # holds LOVETT.SFC / LOVETT.PFL
WORK = Path(os.environ.get("USE_CASE_OUT", "out")) / "02_multi_source_groups"
WORK.mkdir(parents=True, exist_ok=True)
import matplotlib.pyplot as plt # noqa: E402
import numpy as np # noqa: E402
from matplotlib.colors import LogNorm # noqa: E402
from pyaermod import ( # noqa: E402
AERMODProject,
ControlPathway,
MeteorologyPathway,
OutputPathway,
PointSource,
PolarGrid,
PollutantType,
ReceptorPathway,
SourceGroupDefinition,
SourcePathway,
TerrainType,
Validator,
read_plotfile,
run_aermod,
)
control = ControlPathway(
title_one="Use case 2: facility with source groups",
pollutant_id=PollutantType.PM10,
averaging_periods=["ANNUAL"],
terrain_type=TerrainType.FLAT,
regulatory_default=False, # FLAT needs non-DFAULT (see use case 1)
)
# Four stacks around a facility centred on (0, 0):
# (id, x m, y m, height m, exit temp K, exit velocity m/s, diameter m, PM10 g/s)
STACKS = [
("BOIL1", -60.0, 40.0, 45.0, 450.0, 15.0, 2.0, 1.2),
("BOIL2", -20.0, 40.0, 45.0, 450.0, 15.0, 2.0, 1.2),
("DRYER", 50.0, -30.0, 18.0, 340.0, 10.0, 1.0, 0.5),
("KILN", 80.0, 10.0, 25.0, 380.0, 12.0, 1.2, 0.8),
]
sources = SourcePathway()
for sid, x, y, h, t, v, d, q in STACKS:
sources.add_source(PointSource(source_id=sid, x_coord=x, y_coord=y, stack_height=h,
stack_temp=t, exit_velocity=v, stack_diameter=d,
emission_rate=q))
# Source groups (SRCGROUP). AERMOD reports every result per group; ALL (every
# source) is written automatically, so only the subsets are defined here.
GROUPS = {"BOILERS": ["BOIL1", "BOIL2"], "PROCESS": ["DRYER", "KILN"]}
for name, members in GROUPS.items():
sources.add_group(SourceGroupDefinition(name, members))
# Polar grid: 36 radials every 10 deg, 20 rings from 100 m to 3 km.
receptors = ReceptorPathway()
receptors.add_polar_grid(PolarGrid(
grid_name="FENCE", x_origin=0.0, y_origin=0.0,
dist_init=100.0, dist_num=20, dist_delta=150.0,
dir_init=10.0, dir_num=36, dir_delta=10.0,
))
meteorology = MeteorologyPathway(
surface_file=str((MET_DIR / "LOVETT.SFC").resolve()),
profile_file=str((MET_DIR / "LOVETT.PFL").resolve()),
surface_station_id=14735, upper_air_station_id=14735,
data_start_year=1988, profile_base_elevation=1.8, # m MSL
)
# One annual PLOTFILE per group: (averaging period, group, file name).
group_names = [*GROUPS, "ALL"]
output = OutputPathway(
receptor_table=True, receptor_table_rank=2, max_table=True,
plot_file_groups=[("ANNUAL", g, f"{g.lower()}_annual.plt") for g in group_names],
)
project = AERMODProject(control=control, sources=sources, receptors=receptors,
meteorology=meteorology, output=output)
check = Validator.validate(project, check_files=True)
print(check)
if not check.is_valid:
raise SystemExit(1)
result = run_aermod(project.write(WORK / "02_multi_source_groups.inp"))
if not result.success:
raise SystemExit(f"AERMOD failed: {result.error_message}")
print(f"AERMOD finished in {result.runtime_seconds:.1f} s")
# Read each group's annual concentration at every polar receptor.
frames = {}
for g in group_names:
plot = read_plotfile(WORK / f"{g.lower()}_annual.plt")
df = plot.to_dataframe()
frames[g] = df.assign(CONC=df[plot.concentration_column])
peak = frames[g].loc[frames[g]["CONC"].idxmax()]
print(f"{g:8s} annual max {peak['CONC']:.3f} ug/m3 at "
f"({peak['X']:.0f}, {peak['Y']:.0f}) m")
# Each group's share at the receptor where ALL peaks (the groups add up to ALL).
top = frames["ALL"].loc[frames["ALL"]["CONC"].idxmax(), ["X", "Y"]]
for g in GROUPS:
at = frames[g].set_index(["X", "Y"]).loc[tuple(top), "CONC"]
print(f" {g} at the ALL maximum: {at:.3f} ug/m3")
# Three maps on one logarithmic colour scale (so the small BOILERS share still
# shows), with the polar receptors as dots, and a bar chart of the maxima.
fig, axd = plt.subplot_mosaic([group_names, ["bar"] * 3], figsize=(9, 6.5),
height_ratios=[1.8, 1], constrained_layout=True)
vmax = max(f["CONC"].max() for f in frames.values())
levels = np.geomspace(vmax / 100, vmax, 11)
colors = {"BOILERS": "#d55e00", "PROCESS": "#0072b2", "ALL": "0.35"}
for g in group_names:
ax, df = axd[g], frames[g]
cs = ax.tricontourf(df["X"], df["Y"], df["CONC"], levels=levels, cmap="viridis",
norm=LogNorm(), extend="min")
ax.plot(df["X"], df["Y"], ".", ms=1, color="white", alpha=0.5)
for sid, x, y, *_ in STACKS:
group = next(n for n, m in GROUPS.items() if sid in m)
ax.plot(x, y, "^", ms=6, mec="black",
mfc=colors[group] if g in (group, "ALL") else "white")
ax.set(title=f"{g}: annual PM$_{{10}}$", xlim=(-1200, 1200), ylim=(-1200, 1200),
xlabel="Easting (m)", aspect="equal")
axd[group_names[0]].set_ylabel("Northing (m)")
fig.colorbar(cs, ax=[axd[g] for g in group_names], format="%.2g", shrink=0.9,
label="Annual PM$_{10}$ (µg/m³)")
bar = axd["bar"]
maxima = [frames[g]["CONC"].max() for g in group_names]
bar.barh(group_names, maxima, color=[colors[g] for g in group_names])
bar.bar_label(bar.containers[0], fmt=" %.3f µg/m³")
bar.set(title="Highest annual PM$_{10}$ at any receptor, by source group",
xlabel="Concentration (µg/m³)", xlim=(0, 1.25 * vmax))
bar.invert_yaxis()
fig.suptitle("Source-group contributions: 4 stacks, polar receptor grid, LOVETT 1988 met")
fig.savefig(WORK / "02_multi_source_groups.png", dpi=130)
print(f"Figure: {WORK / '02_multi_source_groups.png'}")
Result (AERMOD 26135, LOVETT 1988 met):

The two short process stacks (18 m and 25 m) dominate the impact even though they emit less than the two 45 m boiler stacks (1.3 g/s against 2.4 g/s). The PROCESS group peaks at 1.099 µg/m³ at (217, -125) m. BOILERS peaks at only 0.239 µg/m³, farther out at (376, -137) m. ALL peaks at 1.284 µg/m³ at the PROCESS maximum. There BOILERS adds 0.186 µg/m³, and the two groups sum to ALL (to rounding). Group maxima generally fall at different receptors, so they do not add up to the ALL maximum.
Adapting it
- Edit the
STACKStable and theGROUPSmapping. Group IDs are at most 8 characters, and a source may belong to several groups. Don't defineALLyourself: pyaermod writesSRCGROUP ALL. - Set the polar grid's
dist_init/dist_delta/dist_numso the innermost ring sits at or just beyond the fence line. Polar grids are coarse far out (the ring at 1 km has receptors 175 m apart), so add a Cartesian or discrete grid where the maximum lands. plot_file_groupstakes(averaging period, group, filename), or(averaging period, group, filename, rank)for a lower rank such as"H2H". A short-term period writes the highest (FIRST) value per receptor unless a rank is given.- To get each source's contribution to one specific modelled event, rather than to the long-term average, use an EVENT run (
ControlPathway.eventfil). - A source can also name its groups itself,
source_groups=["BOILERS"]. Those cards are written with the definitions, after every source: AERMOD reports errorSO E140for a group card among the source cards (soset.f). NamingALLadds nothing, since every source is in it.
3. Building downwash with BPIP-PRIME¶
When you need it: A stack is shorter than its Good Engineering Practice (GEP) height, for example a 30 m stack next to a 22 m building. AERMOD must then model the building wake (PRIME). That needs 36 direction-specific building dimensions per source, which EPA's BPIP-PRIME normally computes.
What it shows: A Building footprint and PointSource.set_building_from_bpip, which runs BPIPCalculator and fills BUILDHGT, BUILDWID, BUILDLEN, XBADJ and YBADJ. gep_from_building gives the GEP height. The same deck is run with and without the building data through Validator and run_aermod. The maximum is read with parse_aermod_output and the maps are drawn from read_plotfile.
"""Building downwash with BPIP-PRIME.
A 30 m stack stands beside a 22 m warehouse, well below Good Engineering
Practice (GEP) height. pyaermod's BPIP module computes the 36 direction-specific
building dimensions; AERMOD is run with and without them and the maximum
1-hour concentrations are mapped side by side, with the building drawn.
"""
import copy
import os
from pathlib import Path
import matplotlib.pyplot as plt
import numpy as np
from pyaermod import (
AERMODProject,
Building,
CartesianGrid,
ControlPathway,
MeteorologyPathway,
OutputPathway,
PointSource,
ReceptorPathway,
SourcePathway,
Validator,
parse_aermod_output,
read_plotfile,
run_aermod,
)
from pyaermod.prime import gep_from_building
MET_DIR = Path(os.environ.get("AERMOD_MET_DIR", "met")) # holds LOVETT.SFC / LOVETT.PFL
WORK = Path(os.environ.get("USE_CASE_OUT", "out")) / "03_building_downwash"
WORK.mkdir(parents=True, exist_ok=True)
# --- Building and stack (local coordinates, m) ------------------------------
warehouse = Building(
building_id="WAREHSE",
corners=[(-60.0, -20.0), (20.0, -20.0), (20.0, 20.0), (-60.0, 20.0)], # 80 m x 40 m
height=22.0, # m
)
stack = PointSource(
source_id="STACK1", x_coord=30.0, y_coord=0.0, # 10 m east of the east wall
stack_height=30.0, # m, below GEP
stack_temp=420.0, # K
exit_velocity=12.0, # m/s
stack_diameter=1.2, # m
emission_rate=1.0, # g/s (unit emission rate)
)
print(f"GEP stack height: {gep_from_building(warehouse, stack.x_coord, stack.y_coord):.1f} m "
f"(stack is {stack.stack_height:.0f} m)")
# Direction-specific BUILDHGT/BUILDWID/BUILDLEN/XBADJ/YBADJ from BPIP
downwashed = copy.deepcopy(stack)
downwashed.set_building_from_bpip(warehouse)
print("BUILDWID 90/180/270/360 deg:",
[round(downwashed.building_width[i], 1) for i in (8, 17, 26, 35)])
def build_project(src, title, plot_file):
sources = SourcePathway()
sources.add_source(src)
receptors = ReceptorPathway()
receptors.add_cartesian_grid(CartesianGrid.from_bounds(-500, 500, -500, 500, spacing=20))
return AERMODProject(
control=ControlPathway(title_one=title, pollutant_id="OTHER",
averaging_periods=["1"],
terrain_type="ELEV"), # flat ground: all elevations 0 m
sources=sources,
receptors=receptors,
meteorology=MeteorologyPathway(
surface_file=str((MET_DIR / "LOVETT.SFC").resolve()),
profile_file=str((MET_DIR / "LOVETT.PFL").resolve()),
surface_station_id=14735, upper_air_station_id=14735, data_start_year=1988,
profile_base_elevation=1.8, # m, as in EPA's LOVETT test deck
),
output=OutputPathway(receptor_table=True, receptor_table_rank=1, # PLOTFILE FIRST needs RECTABLE
plot_file=plot_file, plot_file_averaging="1"),
)
frames = {}
for label, src, name in [("No downwash", stack, "no_downwash"),
("BPIP-PRIME downwash", downwashed, "downwash")]:
project = build_project(src, f"Use case 03: {label}", f"{name}_1hr.plt")
check = Validator.validate(project)
if not check.is_valid:
raise SystemExit(str(check))
project.write(WORK / f"{name}.inp")
run = run_aermod(WORK / f"{name}.inp")
if not run.success:
raise SystemExit(f"AERMOD failed for {name}: {run.error_message}")
mx = parse_aermod_output(run.output_file).get_max_concentration("1HR")
print(f"{label:>20}: 1-hr H1H max {mx['value']:7.2f} ug/m^3 at ({mx['x']:.0f}, {mx['y']:.0f})")
# The .out holds only the summary tables; the PLOTFILE has every receptor
plt_file = read_plotfile(WORK / f"{name}_1hr.plt")
frames[label] = plt_file.to_dataframe().rename(columns={plt_file.concentration_column: "conc"})
print("AERMOD version:", parse_aermod_output(run.output_file).run_info.version)
# --- Figure: H1H 1-hr maps on one colour scale, building drawn ---------------
levels = np.arange(0, max(df["conc"].max() for df in frames.values()) + 10, 10) # ug/m^3
fig, axes = plt.subplots(1, 2, figsize=(9, 5.8), sharey=True, constrained_layout=True)
for ax, (label, df) in zip(axes, frames.items()):
cf = ax.tricontourf(df["X"], df["Y"], df["conc"], levels=levels, cmap="viridis")
bx, by = zip(*[*warehouse.corners, warehouse.corners[0]])
ax.fill(bx, by, facecolor="white", edgecolor="black", lw=1.2, alpha=0.85, label="Building (22 m)")
ax.plot(stack.x_coord, stack.y_coord, "r^", ms=9, mec="black", label="Stack (30 m)")
i = df["conc"].idxmax()
ax.plot(df.at[i, "X"], df.at[i, "Y"], "wx", ms=10, mew=2.5, label="Maximum")
ax.set_title(f"{label}\n1-hr H1H, max {df['conc'].max():.1f} \u00b5g/m\u00b3", fontsize=11)
ax.set_xlabel("Easting from site origin (m)")
ax.set_aspect("equal")
ax.set_xlim(-300, 300)
ax.set_ylim(-300, 300)
axes[0].set_ylabel("Northing from site origin (m)")
axes[1].legend(loc="lower right", fontsize=8, framealpha=0.9)
fig.colorbar(cf, ax=axes, orientation="horizontal", shrink=0.7,
label="Highest (H1H) 1-hr concentration, \u00b5g/m\u00b3 per g/s emitted (LOVETT 1988 met)")
fig.savefig(WORK / "03_building_downwash.png", dpi=130)
print("Figure:", WORK / "03_building_downwash.png")
Result (AERMOD 26135, LOVETT 1988 met):

GEP for this building is 65.0 m, so the 30 m stack is subject to downwash. BPIP gives a projected width of 40 m for winds from east and west and 80 m for winds from north and south. Without building data, the highest 1-hour concentration is 60.04 µg/m³ per g/s, at (0, -20). With BPIP-PRIME it rises to 110.74 µg/m³ per g/s at (-40, 100), almost double. The highest values sit in two lobes north and south of the building, where the wake brings the plume to the ground. The effect is not only local: in every distance band out to 600 m, the downwash run's highest 1-hour value is 1.6 to 3.5 times that of the run without building data.
Adapting it
- Replace
corners(any polygon of three or more vertices, in the same coordinates as the sources) andheightwith your building, and move the stack.set_building_from_bpipalso works onAreaSourceandVolumeSource. set_building_from_bpiptakes one building. With several buildings, EPA BPIP picks the controlling building for each direction.apply_bpip_to_projectinstead uses the single nearest building within 5L for each source. Multi-tier buildings are approximated (a warning says so). For a regulatory submittal, check the arrays against EPA BPIP-PRIME.- A short-term
PLOTFILE ... FIRSTneeds aRECTABLEfor that period. Without it AERMOD stops withE203 OUPLOT ... HIVALU, andValidatorreports it. Keepreceptor_table=True. - Under
DFAULT, AERMOD overridesMODELOPT FLAT(warning W206). This example keeps the regulatory default and usesELEVwith every elevation at 0 m, which gives the same result on flat ground.
4. Fugitive emissions: area, polygon and volume sources¶
When you need it: Storage piles, yards and unpaved haul roads at quarries, aggregate plants, landfills and construction sites release PM10 near the ground. A permit or a dust-control plan has to show their 24-hour impacts at the fenceline and beyond.
What it shows: Three of AERMOD's non-point source types from pyaermod's source classes. The irregular pile is an AreaPolySource, a rotated rectangular pad is an AreaSource, and the haul road is a string of VolumeSources laid out with EPA's 2012 haul-road recipe. Area-source emission rates are per square metre (g/s/m²); volume rates are g/s. The deck is checked with Validator and run with run_aermod. The H1H and H2H are read from the summary table with parse_aermod_output, and the per-receptor map from read_plotfile. The footprints are drawn with pyaermod.footprints.source_footprint, which reproduces the outline AERMOD builds from LOCATION/SRCPARAM/AREAVERT.
"""Fugitive PM10 emissions: area, polygon and volume sources.
An aggregate yard with an irregular storage pile (AREAPOLY), a rotated
laydown pad (AREA) and an unpaved haul road modelled as a string of VOLUME
sources (EPA 2012 haul-road guidance).
The script maps the highest 24-hour PM10 concentration with the footprints drawn.
"""
import os
from itertools import pairwise
from pathlib import Path
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.colors import BoundaryNorm
from matplotlib.patches import Polygon
from pyaermod import (
AERMODProject,
AreaPolySource,
AreaSource,
CartesianGrid,
ControlPathway,
MeteorologyPathway,
OutputPathway,
PollutantType,
ReceptorPathway,
SourcePathway,
Validator,
VolumeSource,
parse_aermod_output,
read_plotfile,
run_aermod,
)
from pyaermod.footprints import source_footprint
MET_DIR = Path(os.environ.get("AERMOD_MET_DIR", "met")) # holds LOVETT.SFC / LOVETT.PFL
WORK = Path(os.environ.get("USE_CASE_OUT", "out")) / "04_fugitive_sources"
WORK.mkdir(parents=True, exist_ok=True)
sources = SourcePathway()
# Irregular storage pile: AREAPOLY rates are per unit area (g/s/m^2)
pile_xy = [(-40, -20), (10, -35), (45, -5), (35, 30), (-10, 40), (-45, 15)]
x, y = np.array(pile_xy, dtype=float).T
pile_area = 0.5 * abs(np.dot(x, np.roll(y, 1)) - np.dot(y, np.roll(x, 1))) # m^2
sources.add_source(AreaPolySource(
source_id="PILE", vertices=pile_xy,
release_height=4.0, # m, about half the pile height
emission_rate=0.08 / pile_area, # 0.08 g/s wind erosion + handling
))
# Laydown pad, 60 m x 30 m, rotated 20 deg clockwise about its SW corner: AREA
sources.add_source(AreaSource(
source_id="PAD", x_coord=-170.0, y_coord=50.0,
initial_lateral_dimension=60.0, initial_vertical_dimension=30.0, angle=20.0,
release_height=1.0, emission_rate=0.02 / (60.0 * 30.0), # 0.02 g/s
))
# Unpaved haul road as adjacent VOLUME sources (EPA 2012 haul road guidance):
# 4 m trucks -> plume top 1.7*4 = 6.8 m; release height 3.4 m, sigma-z0 = 6.8/2.15;
# 8 m road + 6 m -> 14 m plume width = volume spacing, sigma-y0 = 14/2.15.
ROAD = [(-330.0, -230.0), (-120.0, -80.0), (60.0, -80.0)] # gate -> pile, m
WIDTH, ROAD_TOTAL = 14.0, 0.25 # m; g/s for the whole road (watered)
centres = []
for (x0, y0), (x1, y1) in pairwise(ROAD):
n = int(np.hypot(x1 - x0, y1 - y0) // WIDTH)
centres += [(x0 + (i + 0.5) / n * (x1 - x0), y0 + (i + 0.5) / n * (y1 - y0)) for i in range(n)]
for i, (vx, vy) in enumerate(centres, start=1):
sources.add_source(VolumeSource(
source_id=f"RD{i:03d}", x_coord=vx, y_coord=vy,
release_height=3.4, initial_lateral_dimension=WIDTH / 2.15,
initial_vertical_dimension=6.8 / 2.15, emission_rate=ROAD_TOTAL / len(centres),
))
print(f"Pile area {pile_area:.0f} m^2; haul road = {len(centres)} volume sources")
receptors = ReceptorPathway()
receptors.add_cartesian_grid(CartesianGrid.from_bounds(-450, 300, -330, 300, spacing=30))
project = AERMODProject(
control=ControlPathway(title_one="Use case 04: fugitive PM10", pollutant_id=PollutantType.PM10,
averaging_periods=["24"],
terrain_type="ELEV"), # flat ground: all elevations 0 m
sources=sources,
receptors=receptors,
meteorology=MeteorologyPathway(
surface_file=str((MET_DIR / "LOVETT.SFC").resolve()),
profile_file=str((MET_DIR / "LOVETT.PFL").resolve()),
surface_station_id=14735, upper_air_station_id=14735, data_start_year=1988,
profile_base_elevation=1.8, # m, as in EPA's LOVETT test deck
),
# PLOTFILE ranks need a RECTABLE at least that deep; SECOND gives H2H too
output=OutputPathway(receptor_table=True, receptor_table_rank=2,
plot_file="pm10_24hr.plt", plot_file_averaging="24"),
)
check = Validator.validate(project)
if not check.is_valid:
raise SystemExit(str(check))
project.write(WORK / "fugitive.inp")
run = run_aermod(WORK / "fugitive.inp")
if not run.success:
raise SystemExit(f"AERMOD failed: {run.error_message}")
results = parse_aermod_output(run.output_file)
table = results.concentrations["24HR"].data
print("AERMOD version:", results.run_info.version)
for _, row in table.sort_values("rank").groupby("rank").head(1).iterrows():
print(f"24-hr PM10 rank {int(row['rank'])}: {row['concentration']:.1f} ug/m^3 "
f"at ({row['x']:.0f}, {row['y']:.0f})")
# Every receptor's highest 24-hr value comes from the PLOTFILE
plotfile = read_plotfile(WORK / "pm10_24hr.plt")
df = plotfile.to_dataframe().rename(columns={plotfile.concentration_column: "conc"})
# --- Figure: H1H 24-hr PM10 with source footprints ---------------------------
levels = [0, 25, 50, 75, 100, 150, 200, 250, 300, 400] # ug/m^3
fig, ax = plt.subplots(figsize=(9, 6.5), constrained_layout=True)
cf = ax.tricontourf(df["X"], df["Y"], df["conc"], levels=levels, cmap="YlOrRd",
norm=BoundaryNorm(levels, 256), extend="max")
# 150 ug/m^3 is the 24-hr PM10 NAAQS level (its form is the H2H per year, so H1H is conservative)
naaqs = ax.tricontour(df["X"], df["Y"], df["conc"], levels=[150], colors="black", linestyles="--")
ax.clabel(naaqs, fmt="150 \u00b5g/m\u00b3", fontsize=8)
for src in sources.sources:
if isinstance(src, VolumeSource):
continue
ring = source_footprint(src).parts[0]
ax.add_patch(Polygon(ring, closed=True, fill=False, ec="black", lw=1.4))
ax.annotate(src.source_id, ring[0], xytext=(-4, 4), textcoords="offset points",
ha="right", fontsize=9, fontweight="bold")
cx, cy = zip(*centres)
ax.plot(cx, cy, "s", ms=4, mfc="none", mec="black", mew=0.8,
label=f"Haul road ({len(centres)} VOLUME sources)")
i = df["conc"].idxmax()
ax.plot(df.at[i, "X"], df.at[i, "Y"], "x", color="navy", ms=10, mew=2.5,
label=f"Maximum {df['conc'].max():.0f} µg/m³")
ax.set(xlim=(-450, 300), ylim=(-330, 300), aspect="equal",
xlabel="Easting from site origin (m)", ylabel="Northing from site origin (m)",
title="PM10 24-hr average, 1st-highest (H1H), LOVETT 1988 met")
ax.legend(loc="upper left", fontsize=9, framealpha=0.9)
fig.colorbar(cf, ax=ax, shrink=0.8, ticks=levels, label="Highest 24-hr PM10 (µg/m³)")
fig.savefig(WORK / "04_fugitive_sources.png", dpi=130)
print("Figure:", WORK / "04_fugitive_sources.png")
Result (AERMOD 26135, LOVETT 1988 met):

The haul road is split into 30 volume sources, 14 m apart, and the pile covers 4750 m². The highest 24-hour PM10 is 369.0 µg/m³ at (-150, 90), just north of the laydown pad. The highest second-high (H2H) is 327.6 µg/m³ at (-120, 60). The pad emits only 0.02 g/s but releases at 1 m, so on stable, light-wind days it dominates its immediate surroundings. The road's contribution follows its length. The dashed line is 150 µg/m³, the level of the 24-hour PM10 NAAQS. It encloses the whole yard and a 50–100 m band along the road. Ground-level fugitive sources typically give the highest near-field impacts of any source type.
Adapting it
- Set
ROADto your road's vertices andWIDTHto the road width + 6 m. For other truck heights, set the release height to half of 1.7 × the truck height and σz0 to 1.7 × the truck height ÷ 2.15. Divide the road's total g/s evenly among the volumes. Area sources take g/s/m², so divide each total by its footprint area. - Area sources are slow. This deck (about 570 receptors, one year) takes about 4 minutes. Receptor count drives the runtime, so use a coarse grid to explore and refine it near the maximum. An
AreaCircSourceis modelled as a 20-sided polygon and was the slowest type in a timing test. Lowernum_verticesif you use one. - For PM10, modelling compares the highest (N+1)-th-high over N years with 150 µg/m³: the H2H for one year and the H6H for five. That is the High-N+1-High rule of the AERMOD User's Guide (section 3.2.16.2); the standard itself (40 CFR 50.6(a), Appendix K) is one expected exceedance per year. The map shows the H1H, and the script takes the H2H from the summary table. To map the H2H instead, set
OutputPathway(plot_file_rank="H2H"). - Under
DFAULT, AERMOD overridesMODELOPT FLAT(warning W206). This example keepsDFAULTand usesELEVwith all elevations at 0 m. APLOTFILErank needs aRECTABLEat least that deep, or AERMOD stops with E203;Validatorchecks it.
5. Near-road roadway modeling with RLINE¶
When you need it: You need concentrations within a few hundred metres of a highway. Typical cases are a PM2.5 or CO hot-spot analysis for transportation conformity, a near-road exposure study, or siting a school, monitor or housing next to a road. AERMOD's RLINE source handles this. In AERMOD 26135 it runs under the regulatory DFAULT option. RLINEXT, by contrast, still requires ALPHA (E198).
What it shows: RLineSource with its emission rate computed from traffic volume and a per-vehicle emission factor. A non-uniform receptor network packed near the road is built with CartesianGrid x_points/y_points (GRIDCART XPNTS/YPNTS). The project is checked with Validator and run with run_aermod. The annual plot file (OutputPathway.period_plot_files) is read back with read_plotfile for the map and the cross-road profile.
"""Near-road PM2.5 from a six-lane highway with AERMOD's RLINE source.
A 1 km highway segment is modelled as one RLINE source with an emission rate
computed from traffic volume and a per-vehicle emission factor. The script maps
the annual-average PM2.5 within 300 m of the road and plots its fall-off with
distance along a transect perpendicular to the road.
"""
import os
from pathlib import Path
import matplotlib.pyplot as plt
from pyaermod.aermod_outputs import read_plotfile
from pyaermod.input_generator import (
AERMODProject,
CartesianGrid,
ControlPathway,
MeteorologyPathway,
OutputPathway,
PollutantType,
ReceptorPathway,
RLineSource,
SourcePathway,
TerrainType,
)
from pyaermod.output_parser import parse_aermod_output
from pyaermod.runner import run_aermod
from pyaermod.validator import Validator
MET_DIR = Path(os.environ.get("AERMOD_MET_DIR", "met")) # holds LOVETT.SFC / LOVETT.PFL
WORK = Path(os.environ.get("USE_CASE_OUT", "out")) / "05_roadway"
WORK.mkdir(parents=True, exist_ok=True)
# Traffic -> RLINE emission rate. RLINE's SRCPARAM rate is per unit AREA of
# road surface, g/(s·m²): AERMOD multiplies it by the road width.
AADT = 100_000 # vehicles/day, both directions
EF_PM25 = 0.010 # g/(vehicle·km), exhaust + brake + tyre wear (illustrative; use MOVES)
ROAD_WIDTH = 24.0 # m, six 3.6 m lanes plus shoulders
per_metre = AADT / 86400 * EF_PM25 / 1000 # g/(s·m) of road length
EMIS = per_metre / ROAD_WIDTH # g/(s·m²)
control = ControlPathway(
title_one="Use case 05: near-road PM2.5 from a highway (RLINE)",
pollutant_id=PollutantType.PM25,
averaging_periods=["ANNUAL"],
terrain_type=TerrainType.ELEVATED, # DFAULT ignores FLAT (W206); all elevations are 0 m
)
sources = SourcePathway()
sources.add_source(RLineSource(
source_id="HWY",
x_start=-500.0, y_start=0.0, x_end=500.0, y_end=0.0, # 1 km, west to east
release_height=0.5, # m, tailpipe height
initial_lateral_dimension=ROAD_WIDTH, # m, full road width (AERMOD's "Width")
initial_vertical_dimension=1.5, # m, initial sigma-z from vehicle wakes
emission_rate=EMIS, # g/(s·m²)
))
# Receptors on lines across the road, packed close to it where the gradient is
# steep. RLINE costs far more per receptor than a point source (run time grows
# with receptors x road length x hours), so keep this network lean.
DISTANCES = [15, 20, 30, 40, 50, 75, 100, 150, 200, 300] # m from centreline
receptors = ReceptorPathway()
receptors.add_cartesian_grid(CartesianGrid(
grid_name="ROADNET",
x_points=[-400.0 + 100.0 * i for i in range(9)],
y_points=sorted([-d for d in DISTANCES] + DISTANCES),
))
meteorology = MeteorologyPathway(
surface_file=str((MET_DIR / "LOVETT.SFC").resolve()),
profile_file=str((MET_DIR / "LOVETT.PFL").resolve()),
surface_station_id=14735, upper_air_station_id=14735,
data_start_year=1988, profile_base_elevation=1.8,
)
output = OutputPathway(receptor_table=False, max_table=True, period_plot_files="hwy")
project = AERMODProject(control=control, sources=sources, receptors=receptors,
meteorology=meteorology, output=output)
check = Validator.validate(project)
assert check.is_valid, check.errors
inp = WORK / "hwy.inp"
project.write(inp)
run = run_aermod(inp)
assert run.success, run.error_message
res = parse_aermod_output(run.output_file)
top = res.get_max_concentration("ANNUAL")
grid = read_plotfile(WORK / "hwy_ANNUAL.plt").to_dataframe()
line = grid[grid["X"] == 0.0].sort_values("Y") # the transect across mid-road
print(f"AERMOD {res.run_info.version}; RLINE emission {per_metre:.3e} g/(s·m) = {EMIS:.3e} g/(s·m²)")
print(f"Max annual PM2.5: {top['value']:.3f} ug/m3 at ({top['x']:.0f}, {top['y']:.0f}) m")
for d in (20, 50, 100, 300):
north = line.loc[line["Y"] == d, "AVERAGE_CONC"].iloc[0]
south = line.loc[line["Y"] == -d, "AVERAGE_CONC"].iloc[0]
print(f" {d:>3} m from centreline: north {north:.3f}, south {south:.3f} ug/m3")
fig, (ax, ax2) = plt.subplots(1, 2, figsize=(9, 6.5), gridspec_kw={"width_ratios": [1.6, 1]})
g = grid.pivot(index="Y", columns="X", values="AVERAGE_CONC")
levels = [0.25, 0.375, 0.5, 0.75, 1, 1.5, 2, 2.5, 3, 3.5, 4] # finer where it falls off
cs = ax.contourf(g.columns, g.index, g.values, levels=levels, cmap="viridis", extend="both")
ax.plot(grid["X"], grid["Y"], "w.", ms=2, alpha=0.6)
fig.colorbar(cs, ax=ax, orientation="horizontal", pad=0.12, label="Annual PM₂.₅ (µg/m³)")
ax.axhspan(-ROAD_WIDTH / 2, ROAD_WIDTH / 2, color="0.6", alpha=0.85, label="Highway (RLINE)")
ax.plot(line["X"], line["Y"], "wo", ms=4, mec="k", label="Transect (right panel)")
ax.set_xlabel("x (m)")
ax.set_ylabel("y (m), distance from road centreline")
ax.set_aspect("equal")
ax.legend(loc="upper right", fontsize=8)
for sign, colour, label in ((1, "#1b9e77", "North side"), (-1, "#d95f02", "South side")):
side = line[line["Y"] * sign > 0]
ax2.plot(side["Y"].abs(), side["AVERAGE_CONC"], "o-", color=colour, label=label)
ax2.axvline(ROAD_WIDTH / 2, color="0.5", ls=":", label="Road edge")
ax2.set_xlabel("Distance from road centreline (m)")
ax2.set_ylabel("Annual PM₂.₅ (µg/m³)")
ax2.set_xlim(0, 310)
ax2.set_ylim(bottom=0)
ax2.grid(alpha=0.3)
ax2.legend(fontsize=8)
fig.suptitle(f"Annual-average PM₂.₅ near a highway (RLINE, AADT {AADT:,}) — LOVETT 1988 met",
fontsize=11)
fig.tight_layout()
png = WORK / "05_roadway.png"
fig.savefig(png, dpi=130, bbox_inches="tight")
print(f"Figure: {png}")
Result (AERMOD 26135, LOVETT 1988 met):

100,000 vehicles/day at 0.010 g/(veh·km) is 1.157e-05 g/(s·m) of road, or 4.823e-07 g/(s·m²) over the 24 m width. That gives a maximum annual PM2.5 increment of 4.323 µg/m³ at 15 m from the centreline (3 m past the road edge). The increment falls to about half by 50 m (1.988 north, 1.892 south), to 1.172 / 1.124 µg/m³ at 100 m and to 0.428 / 0.404 µg/m³ at 300 m. That steep near-road gradient is why receptors are packed close to the road. The north side is only ~5 % higher, so in this met year winds from the south and from the north across this east-west road are nearly balanced. At a site with a dominant cross-road wind, the downwind side is clearly higher.
Adapting it
- Units:
RLineSource.emission_rateis per unit area, g/(s·m²). AERMOD multiplies it by the road width (initial_lateral_dimension, the full width, not half). Turn a MOVES rate per vehicle-mile into g/(s·m) of road with the traffic volume, then divide by the width, as the script does.RLineExtSourcetakes g/(s·m) per unit length instead. - Run time: RLINE integrates along the line for every receptor and hour, so run time grows with receptors × road length × hours. This 180-receptor, 1 km, one-year run takes ~6 min. A uniform 20 m grid (1,581 receptors) over a 2 km road would take an estimated 2+ h. Split long corridors into segments and keep receptors where you need them.
- Endpoint release heights, barriers (
RBARRIER), depressed roads (RDEPRESS) and vegetation (VBARRIER) needRLineExtSource(RLINEXT). RLINEXT needsControlPathway(alpha=True, regulatory_default=False)in 26135 (E198), and the barrier and depression options also need FLAT terrain (E713). Plain RLINE, as here, needs neither. - Model each direction of a divided highway, or each link with its own traffic, as its own source. Put them in a source group (
source_groups=["ROADS"]) to see the road total separately from other sources.
6. 1-hour NO2 with Tier 2 and Tier 3 chemistry¶
When you need it: A combustion source emits NOx, but the 1-hour NAAQS is for NO2. EPA's Guideline (Appendix W §4.2.3.4) lets you go beyond Tier 1 (all NOx is NO2). Tier 2 is ARM2, an empirical NO2/NOx ratio. Tier 3 is OLM or PVMRM (and GRSM under the 2024 revision), which limit conversion by the ambient ozone available and need consultation with the EPA Regional Office. A source that fails with ARM2 often passes with a Tier 3 method.
What it shows: one project built three times with only ChemistryOptions changed: ChemistryMethod.ARM2, .OLM and .PVMRM. The Tier 3 runs take a uniform background ozone (OzoneData, written as OZONEVAL) and an in-stack NO2/NOx ratio (default_no2_ratio, written as NO2STACK). Each project is checked with Validator and run with run_aermod. The ranked tables come from AERMODResults.summaries (parse_aermod_output). The maps come from per-period plot files (OutputPathway.period_plot_files, read with read_plotfile).
"""1-hour NO2 from one combustion stack with Tier 2 (ARM2) and Tier 3 (OLM, PVMRM) chemistry.
The same project is run three times, changing only the NO2 conversion method,
and the script prints the highest and 8th-highest daily-maximum 1-hour NO2 for
each, then maps the highest values side by side with a bar chart of both ranks.
"""
import os
from pathlib import Path
import matplotlib.pyplot as plt
from pyaermod.aermod_outputs import read_plotfile
from pyaermod.input_generator import (
AERMODProject,
CartesianGrid,
ControlPathway,
MeteorologyPathway,
OutputPathway,
PointSource,
PollutantType,
ReceptorPathway,
SourcePathway,
TerrainType,
)
from pyaermod.output_parser import parse_aermod_output
from pyaermod.pathways import ChemistryMethod, ChemistryOptions, OzoneData
from pyaermod.runner import run_aermod
from pyaermod.validator import Validator
MET_DIR = Path(os.environ.get("AERMOD_MET_DIR", "met")) # holds LOVETT.SFC / LOVETT.PFL
WORK = Path(os.environ.get("USE_CASE_OUT", "out")) / "06_no2_chemistry"
WORK.mkdir(parents=True, exist_ok=True)
OZONE_PPB = 40.0 # uniform background ozone for OLM / PVMRM
IN_STACK_RATIO = 0.1 # in-stack NO2/NOx ratio (NO2STACK), typical of a gas-fired boiler
NOX_GS = 40.0 # NOx emission rate, g/s (as NO2)
METHODS = ["ARM2", "OLM", "PVMRM"]
def build_project(method: str) -> AERMODProject:
# ARM2 scales total NOx by an empirical ratio (0.5-0.9) and takes no ozone
# or in-stack ratio; AERMOD rejects OZONEVAL/NO2STACK with it (E600).
tier3 = method != "ARM2"
chemistry = ChemistryOptions(
method=ChemistryMethod[method],
ozone_data=OzoneData(uniform_value=OZONE_PPB, uniform_units="PPB") if tier3 else None,
default_no2_ratio=IN_STACK_RATIO,
)
control = ControlPathway(
title_one=f"Use case 06: 1-hr NO2 with {method}",
pollutant_id=PollutantType.NO2,
averaging_periods=["1"],
# DFAULT ignores FLAT (W206), so say ELEV; every elevation is 0 m.
terrain_type=TerrainType.ELEVATED,
chemistry=chemistry,
)
sources = SourcePathway()
sources.add_source(PointSource(
source_id="BOILER",
x_coord=0.0, y_coord=0.0, base_elevation=0.0,
stack_height=35.0, # m
stack_temp=450.0, # K
exit_velocity=15.0, # m/s
stack_diameter=2.0, # m
emission_rate=NOX_GS, # g/s
))
receptors = ReceptorPathway()
receptors.add_cartesian_grid(CartesianGrid.from_bounds(
x_min=-2500, x_max=2500, y_min=-2500, y_max=2500, spacing=125))
meteorology = MeteorologyPathway(
surface_file=str((MET_DIR / "LOVETT.SFC").resolve()),
profile_file=str((MET_DIR / "LOVETT.PFL").resolve()),
surface_station_id=14735, upper_air_station_id=14735,
data_start_year=1988, profile_base_elevation=1.8,
)
# RECTABLE 1-8 makes AERMOD tabulate the 1st..8th-highest daily maxima.
output = OutputPathway(receptor_table=True, receptor_table_rank=8, max_table=True,
period_plot_files=f"no2_{method.lower()}")
return AERMODProject(control=control, sources=sources, receptors=receptors,
meteorology=meteorology, output=output)
results, grids = {}, {}
for method in METHODS:
project = build_project(method)
check = Validator.validate(project)
assert check.is_valid, check.errors
inp = WORK / f"no2_{method.lower()}.inp"
project.write(inp)
run = run_aermod(inp)
assert run.success, run.error_message
res = parse_aermod_output(run.output_file)
# For NO2 1-hr under DFAULT AERMOD ranks the daily-maximum 1-hr values.
ranked = {s.title.split()[4]: s for s in res.summaries if s.averaging_period == "1HR"}
results[method] = (ranked["1ST-HIGHEST"], ranked["8TH-HIGHEST"])
grids[method] = read_plotfile(WORK / f"no2_{method.lower()}_01H.plt").to_dataframe()
print(f"AERMOD {res.run_info.version}, NOx {NOX_GS:g} g/s, O3 {OZONE_PPB:g} ppb, NO2/NOx in stack {IN_STACK_RATIO}")
print(f"{'method':<7}{'H1H (ug/m3)':>13}{'H8H (ug/m3)':>13} at (x, y) m")
for method, (h1, h8) in results.items():
print(f"{method:<7}{h1.max_value:>13.1f}{h8.max_value:>13.1f} "
f"({h1.max_location[0]:.0f}, {h1.max_location[1]:.0f})")
# Three maps on one colour scale, plus a bar chart of H1H and H8H.
fig = plt.figure(figsize=(9, 6.5))
gs = fig.add_gridspec(2, 3, height_ratios=[1.25, 1], hspace=0.45, wspace=0.08)
vmax = max(h1.max_value for h1, _ in results.values())
levels = [vmax * f for f in (0.05, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0001)]
for i, method in enumerate(METHODS):
ax = fig.add_subplot(gs[0, i])
g = grids[method].pivot(index="Y", columns="X", values="AVERAGE_CONC")
cs = ax.contourf(g.columns, g.index, g.values, levels=levels, cmap="YlOrRd", extend="min")
ax.plot(0, 0, "k^", ms=7, label="Stack")
h1 = results[method][0]
ax.plot(*h1.max_location, "b*", ms=11, mec="w", label="Max")
ax.set_title(f"{method}: max {h1.max_value:.0f} µg/m³", fontsize=10)
ax.set_aspect("equal")
ax.set_xlabel("x (m)")
ax.tick_params(labelsize=8)
if i == 0:
ax.set_ylabel("y (m)")
ax.legend(loc="lower left", fontsize=7)
else:
ax.set_yticklabels([])
fig.colorbar(cs, ax=fig.axes, orientation="vertical", fraction=0.025, pad=0.02,
label="1-hr NO₂ (µg/m³)", format="%.0f")
ax = fig.add_subplot(gs[1, :])
x = range(len(METHODS))
h1s = [results[m][0].max_value for m in METHODS]
h8s = [results[m][1].max_value for m in METHODS]
b1 = ax.bar([i - 0.2 for i in x], h1s, 0.4, color="#d95f02", label="Highest (H1H)")
b8 = ax.bar([i + 0.2 for i in x], h8s, 0.4, color="#7570b3", label="8th-highest (H8H, 98th pct)")
ax.bar_label(b1, fmt="%.0f", fontsize=8)
ax.bar_label(b8, fmt="%.0f", fontsize=8)
ax.axhline(188, color="k", ls="--", lw=1)
ax.text(1.0, 191, "1-hr NO₂ NAAQS, 188 µg/m³", ha="center", va="bottom", fontsize=8)
ax.set_xticks(list(x), [f"{m} ({'Tier 2' if m == 'ARM2' else 'Tier 3'})" for m in METHODS])
ax.set_ylabel("Max daily 1-hr NO₂ (µg/m³)")
ax.set_ylim(0, max(260, max(h1s) * 1.4))
ax.legend(fontsize=8, loc="upper right", ncols=2)
fig.suptitle("1-hr NO₂ by chemistry method: maps show the highest daily maximum (H1H)\n"
f"{NOX_GS:g} g/s NOx, {OZONE_PPB:g} ppb O₃, LOVETT 1988 met", fontsize=11)
png = WORK / "06_no2_chemistry.png"
fig.savefig(png, dpi=130, bbox_inches="tight")
print(f"Figure: {png}")
Result (AERMOD 26135, LOVETT 1988 met):

With 40 g/s NOx, 40 ppb ozone and an in-stack ratio of 0.1, the highest daily-maximum 1-hour NO2 drops from 171.0 µg/m³ with ARM2 to 109.3 with OLM and 55.8 with PVMRM. ARM2 and OLM peak at (375, -250) m, PVMRM at (625, -375) m. The 8th-highest values (H8H) are 121.6, 90.7 and 44.2 µg/m³. For NO2 under DFAULT, AERMOD ranks daily maximum 1-hour values, so with one year of met data the H8H is the 98th percentile. The regulatory design value (H8H averaged over 5 years, plus background) is worked through in use case 7. PVMRM is lowest because it compares the ozone entrained into the whole plume volume with the plume's total NOx, and close to the stack that volume is small. OLM compares the ozone with the NOx concentration at each receptor. PVMRM's peak also sits farther out.
Adapting it
- Replace the uniform
OzoneData(uniform_value=...)with an hourly file (ozone_file=,OZONEFIL) from a representative monitor. Missing hours then fall back to the uniform value. Use the same ozone for every Tier 3 method you compare. - ARM2 takes no ozone and no in-stack ratio. AERMOD stops with E600 if
OZONEVALorNO2STACKappears with ARM2. pyaermod never writesNO2STACKfor ARM2, andValidatorrejectsozone_datawith it, so the script passesozone_data=Nonefor ARM2. ARM2's ratio bounds default to 0.5 to 0.9 (ControlPathway.arm2_ratios). - Use a measured or source-category
NO2STACK(0.1 here, typical of gas-fired boilers; diesel engines can be 0.2 to 0.5). Setno2_ratio=on a source to override it per stack. - PVMRM is the slowest of the three: most of the ~3 min run time is the PVMRM pass on this 1,681-receptor grid. Check the grid with ARM2 first.
7. NAAQS compliance: the 1-hour SO2 design value¶
When you need it: A permit or SIP demonstration has to show that the modelled design value plus background stays below the NAAQS at every receptor. For 1-hour SO2, the design value is the 99th percentile of daily maximum 1-hour values, which is the 4th-highest day of a full year, averaged over the years modelled.
What it shows: naaqs_output_pathway requests AERMOD's MAXDAILY, MXDYBYYR and MAXDCONT outputs at the rank 40 CFR 50 Appendix T gives. The script reads the daily series with read_maxdaily and builds the design value, background included, with naaqs_compliance_report. It cross-checks the result against AERMOD's own ranks with mxdybyyr_design_value and converts the 75 ppb standard to µg/m³ with get_naaqs(...).level_ugm3.
"""
NAAQS compliance: the 1-hour SO2 design value.
Models two SO2 stacks with AERMOD's MAXDAILY output, computes the 99th-percentile
(4th-highest) daily-maximum 1-hour design value at every receptor, adds a monitored
background and compares it with the 75 ppb NAAQS. Writes a design-value map and a
ranked bar chart of the highest receptors to ``07_naaqs_design_value.png``.
"""
import os
import warnings
from pathlib import Path
MET_DIR = Path(os.environ.get("AERMOD_MET_DIR", "met")) # holds LOVETT.SFC / LOVETT.PFL
WORK = Path(os.environ.get("USE_CASE_OUT", "out")) / "07_naaqs_design_value"
WORK.mkdir(parents=True, exist_ok=True)
import matplotlib.pyplot as plt # noqa: E402
import numpy as np # noqa: E402
from pyaermod import ( # noqa: E402
AERMODProject,
CartesianGrid,
ControlPathway,
MeteorologyPathway,
PointSource,
PollutantType,
ReceptorPathway,
SourcePathway,
Validator,
get_naaqs,
mxdybyyr_design_value,
naaqs_compliance_report,
naaqs_output_pathway,
read_maxdaily,
read_mxdybyyr,
run_aermod,
)
BACKGROUND = 20.0 # uniform SO2 background, ug/m3 (~7.6 ppb; use your monitor's design value)
# --- Project: POLLUTID SO2 + AVERTIME 1 switches on AERMOD's SO2 NAAQS processing
control = ControlPathway(
title_one="Use case 07: 1-hour SO2 design value",
pollutant_id=PollutantType.SO2,
averaging_periods=["1"],
terrain_type="ELEVATED", # sources and receptors at 0 m, so flat; FLAT is dropped under DFAULT
)
sources = SourcePathway()
sources.add_source(PointSource( # main boiler stack
source_id="BOILER", x_coord=0.0, y_coord=0.0,
stack_height=45.0, stack_temp=420.0, # m, K
exit_velocity=15.0, stack_diameter=2.2, # m/s, m
emission_rate=40.0, # g/s SO2
))
sources.add_source(PointSource( # smaller process heater
source_id="HEATER", x_coord=250.0, y_coord=-150.0,
stack_height=25.0, stack_temp=480.0,
exit_velocity=10.0, stack_diameter=1.0,
emission_rate=8.0,
))
receptors = ReceptorPathway()
receptors.add_cartesian_grid(CartesianGrid.from_bounds(-2000, 2000, -2000, 2000, spacing=100))
met = MeteorologyPathway(
surface_file=str((MET_DIR / "LOVETT.SFC").resolve()),
profile_file=str((MET_DIR / "LOVETT.PFL").resolve()),
surface_station_id=14735, upper_air_station_id=14735,
data_start_year=1988, profile_base_elevation=1.8, # PROFBASE, m MSL
)
# MAXDAILY (daily max 1-hr series), MXDYBYYR (AERMOD's ranks) and MAXDCONT,
# with the rank (4th highest) taken from 40 CFR 50 Appendix T
output = naaqs_output_pathway("SO2", stem="so2")
project = AERMODProject(control, sources, receptors, met, output)
# --- Validate, write, run
check = Validator.validate(project, check_files=True)
print(check)
if not check.is_valid:
raise SystemExit(1)
inp = WORK / "so2_dv.inp"
project.write(inp)
run = run_aermod(inp, timeout=1800)
if not run.success:
raise SystemExit(f"AERMOD failed: {run.error_message}")
print(f"AERMOD finished in {run.runtime_seconds:.0f} s, {run.warning_count} warning(s)")
# --- Design value from the daily-max series. One met year here; a regulatory
# run averages 5 years of NWS data (or 1-3 years of site-specific data).
daily = read_maxdaily(WORK / "so2_maxdaily.dat")
with warnings.catch_warnings():
warnings.simplefilter("ignore") # "defined over 3 years" -- we know we have 1
report = naaqs_compliance_report("SO2", daily, background=BACKGROUND, n_years=1)
aermod_dv = mxdybyyr_design_value(read_mxdybyyr(WORK / "so2_mxdybyyr.dat"), rank=4)
std = get_naaqs("SO2", "1-hour")
naaqs = std.level_ugm3 # 75 ppb -> 196.4 ug/m3, the level "exceeds" is checked against
top = report.nlargest(10, "design_value").reset_index(drop=True)
best = top.iloc[0]
print(f"Days in met year: {daily['date'].str[:6].nunique()}")
print(f"Max design value (incl. {BACKGROUND:g} ug/m3 background): "
f"{best.design_value:.1f} ug/m3 at ({best.x:.0f}, {best.y:.0f}) m")
print(f" modelled part {best.design_value - BACKGROUND:.1f} ug/m3; AERMOD's own "
f"4th-high (MXDYBYYR) max {aermod_dv['concentration'].max():.1f} ug/m3")
print(f"NAAQS {std.level:g} {std.units} = {naaqs:.1f} ug/m3; "
f"{int(report['exceeds'].sum())} of {len(report)} receptors exceed")
# --- Figure: DV map with the NAAQS contour, and the top receptors vs the standard
xs, ys = np.sort(report["x"].unique()), np.sort(report["y"].unique())
grid = report.pivot(index="y", columns="x", values="design_value").loc[ys, xs].to_numpy()
fig, (ax, bx) = plt.subplots(1, 2, figsize=(9, 6.5), gridspec_kw={"width_ratios": [1.5, 1]})
levels = np.arange(BACKGROUND, max(grid.max(), naaqs) + 20, 20)
cf = ax.contourf(xs, ys, grid, levels=levels, cmap="viridis")
ax.contour(xs, ys, grid, levels=[naaqs], colors="red", linewidths=2.2)
ax.plot([], [], "r-", lw=2.2, label=f"NAAQS contour {naaqs:.1f}")
for s in sources.sources:
ax.plot(s.x_coord, s.y_coord, "w^", ms=9, mec="k")
ax.annotate(s.source_id, (s.x_coord, s.y_coord), xytext=(-8, 8), ha="right",
textcoords="offset points", color="w", fontsize=8)
ax.plot(best.x, best.y, "*", color="orange", ms=13, mec="k",
label=f"max DV {best.design_value:.1f}")
ax.set(aspect="equal", xlabel="Easting (m)", ylabel="Northing (m)")
ax.set_xticks(np.arange(-2000, 2001, 1000))
ax.legend(loc="lower left", fontsize=8)
fig.colorbar(cf, ax=ax, orientation="horizontal", pad=0.1,
label="SO2 1-hr design value incl. background (µg/m³)")
labels = [f"({r.x:.0f}, {r.y:.0f})" for r in top.itertuples()]
bx.barh(labels, top["design_value"] - BACKGROUND, color="#3b528b", label="AERMOD")
bx.barh(labels, BACKGROUND, left=top["design_value"] - BACKGROUND, color="#bbbbbb",
label=f"background {BACKGROUND:g}")
bx.axvline(naaqs, color="red", lw=2, label=f"NAAQS {naaqs:.1f}")
bx.invert_yaxis()
bx.set(xlabel="Design value (µg/m³)", ylabel="Top 10 receptors (x, y in m)")
bx.tick_params(axis="y", labelsize=7)
bx.legend(fontsize=8, loc="lower center", bbox_to_anchor=(0.5, 1.0), frameon=False)
fig.suptitle("SO2 1-hour design value: 4th-highest daily max 1-hr (99th pct), "
"LOVETT 1988, one year", fontsize=11)
fig.tight_layout()
fig.savefig(WORK / "07_naaqs_design_value.png", dpi=130)
print(f"Figure: {WORK / '07_naaqs_design_value.png'}")
Result (AERMOD 26135, LOVETT 1988 met):

The highest design value is 264.8 µg/m³ at (400, -200) m, about 150 m downwind of the shorter HEATER stack. Of that, 244.8 µg/m³ is modelled and 20 µg/m³ is background. The modelled part matches AERMOD's own 4th-high from MXDYBYYR exactly (244.8 µg/m³). With the NAAQS at 75 ppb = 196.4 µg/m³, 7 of 1681 receptors exceed. They all lie inside the small red contour southeast of the stacks, so this facility would need a taller HEATER stack or lower emissions.
Adapting it
- This uses one year of met data. A regulatory run uses 5 years of NWS data (or 1 to 3 years of site-specific data). Pass
n_years=to match, and the design value becomes the multi-year mean of the annual 4th-highest values. naaqs_compliance_reportgives the standard in its own units (naaqs_level, 75 ppb) and in AERMOD's (naaqs_level_ugm3, 196.4 µg/m³). Itsexceedscolumn compares the design value with the µg/m³ level.- A uniform
background=is the simplest form.add_backgroundalso takes an hourly series keyed by YYMMDDHH, for temporally varying monitor data. terrain_type="FLAT"together with the defaultDFAULTis dropped by AERMOD (W206). The script usesELEVATEDwith all elevations at 0 m. Run AERMAP for real terrain.
8. Elevated and complex terrain with AERMAP¶
When you need it: any source whose plume can reach terrain near or above stack top: river valleys, ridges, hillside receptors. A regulatory AERMOD run uses elevated terrain (DFAULT forces it), so every source and receptor needs an elevation and a hill-height scale from AERMAP.
What it shows: downloading USGS 3DEP elevation tiles with DEMDownloader, running AERMAP and writing its elevations and hill heights back into the project with TerrainProcessor.process, screening AERMAP's receptor output with hill_height_diagnostics, and a TERRAIN ELEV vs FLAT comparison read back with parse_aermod_output and read_plotfile.
"""Elevated and complex terrain: AERMAP elevations and hill heights, ELEV vs FLAT.
Downloads USGS 3DEP 1 arc-second (~30 m) DEM tiles around a 145 m stack on the Hudson
River at Tomkins Cove, NY (site of EPA's Lovett complex-terrain study), runs AERMAP to give
the stack and a 9 km x 9 km receptor grid elevations and hill heights, then runs AERMOD
with TERRAIN ELEV and FLAT. Writes 08_complex_terrain.png: annual SO2 of both runs.
"""
import copy
import os
from pathlib import Path
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.colors import LightSource, LogNorm
from pyaermod import (
AERMAPOutputParser,
AERMODProject,
AERMODRunner,
CartesianGrid,
ControlPathway,
DEMDownloader,
MeteorologyPathway,
OutputPathway,
PointSource,
PollutantType,
ReceptorPathway,
SourcePathway,
TerrainProcessor,
TerrainType,
Validator,
hill_height_diagnostics,
parse_aermod_output,
read_plotfile,
)
MET_DIR = Path(os.environ.get("AERMOD_MET_DIR", "met")) # holds LOVETT.SFC / LOVETT.PFL
WORK = Path(os.environ.get("USE_CASE_OUT", "out")) / "08_complex_terrain"
WORK.mkdir(parents=True, exist_ok=True)
# Site: stack on the riverbank at 41.2590 N, 73.9790 W = UTM 18N (NAD83) 585531 E, 4568012 N.
STACK_X, STACK_Y = 585530.0, 4568010.0
UTM_ZONE = 18
HALF = 4500.0 # receptor grid half-width, m
SPACING = 150.0 # receptor spacing, m
BUFFER = 3000.0 # extra terrain AERMAP searches for hill heights, m
# DEM bounding box (west, south, east, north), degrees: grid + buffer, with margin.
BBOX = (-74.08, 41.18, -73.88, 41.34)
# 1. DEM: the newest USGS 3DEP 1 arc-second version of each tile in BBOX, rewritten
# uncompressed for AERMAP (USGS ships LZW tiles, which AERMAP cannot read).
dem = DEMDownloader(cache_dir=WORK / "dem", dataset="National Elevation Dataset (NED) 1 arc-second")
dem_files = dem.download_dem(BBOX)
print("DEM tiles:", ", ".join(p.name for p in dem_files))
# 2. The AERMOD project; base and receptor elevations come from AERMAP below.
control = ControlPathway(
title_one="Complex terrain: 145 m stack in the Hudson Highlands",
title_two="AERMAP elevations and hill heights from USGS 3DEP",
pollutant_id=PollutantType.SO2,
averaging_periods=["1", "ANNUAL"],
terrain_type=TerrainType.ELEVATED, # regulatory default (DFAULT)
)
sources = SourcePathway()
sources.add_source(PointSource(
source_id="STK1", x_coord=STACK_X, y_coord=STACK_Y,
stack_height=145.0, # m
stack_temp=382.0, # K
exit_velocity=23.1, # m/s
stack_diameter=4.5, # m
emission_rate=100.0, # g/s
))
receptors = ReceptorPathway()
receptors.add_cartesian_grid(CartesianGrid.from_bounds(
STACK_X - HALF, STACK_X + HALF, STACK_Y - HALF, STACK_Y + HALF, spacing=SPACING, grid_name="GRID1"))
met = MeteorologyPathway(
surface_file=str((MET_DIR / "LOVETT.SFC").resolve()),
profile_file=str((MET_DIR / "LOVETT.PFL").resolve()),
surface_station_id=14735, upper_air_station_id=14735, data_start_year=1988,
profile_base_elevation=1.8, # m MSL, as in EPA's lovett.inp
)
project = AERMODProject(control, sources, receptors, met,
OutputPathway(receptor_table_rank=1, period_plot_files="elev"))
# 3. AERMAP: write the deck, run it and copy every elevation into the project.
TerrainProcessor().process(
project, bounds=BBOX, working_dir=WORK / "aermap", utm_zone=UTM_ZONE, datum="NAD83",
skip_download=True, dem_files=dem_files, domain_buffer=BUFFER,
)
elev = np.array(receptors.cartesian_grids[0].grid_elevations)
hill = np.array(receptors.cartesian_grids[0].grid_hills)
print(f"Stack base {sources.sources[0].base_elevation:.1f} m; receptors {elev.min():.0f}-{elev.max():.0f} m, "
f"hill heights up to {hill.max():.0f} m")
aermap_rec = AERMAPOutputParser.parse_receptor_output(WORK / "aermap" / "aermap_receptors.out")
flags = hill_height_diagnostics(list(aermap_rec.itertuples()))
print(f"hill_height_diagnostics: {len(flags)} flag(s)", *sorted({f.reason for f in flags}), sep="\n ")
# 4. The FLAT twin. DFAULT overrides FLAT with ELEV (W206), so it drops DFAULT.
flat = copy.deepcopy(project)
flat.control.terrain_type = TerrainType.FLAT
flat.control.regulatory_default = False
flat.output.period_plot_files = "flat"
runner = AERMODRunner()
results, plots = {}, {}
for name, proj in (("ELEV", project), ("FLAT", flat)):
check = Validator.validate(proj)
if not check.is_valid:
raise SystemExit(str(check))
inp = proj.write(WORK / f"{name.lower()}.inp")
run = runner.run(inp, working_dir=WORK)
if not run.success:
raise SystemExit(f"AERMOD {name} failed: {run.error_message}")
results[name] = parse_aermod_output(run.output_file)
plots[name] = read_plotfile(WORK / f"{name.lower()}_ANNUAL.plt").to_dataframe()
print(f"AERMOD {results['ELEV'].run_info.version}, {len(elev.flat)} receptors")
for name, res in results.items():
for period in ("1HR", "ANNUAL"):
m = res.get_max_concentration(period)
print(f"{name:4s} {period:6s} max {m['value']:8.2f} ug/m3 at ({m['x']:.0f}, {m['y']:.0f}) "
f"{np.hypot(m['x'] - STACK_X, m['y'] - STACK_Y):.0f} m from the stack")
# 5. Figure: annual average of each run; colour only where it is above 1/30 of the
# highest, so the hillshade of the AERMAP elevations shows through elsewhere.
xs = receptors.cartesian_grids[0].x_values()
ys = receptors.cartesian_grids[0].y_values()
X, Y = ((np.array(v) - c) / 1000 for v, c in zip(np.meshgrid(xs, ys), (STACK_X, STACK_Y))) # km
shade = LightSource(azdeg=315, altdeg=40).hillshade(elev, vert_exag=2, dx=SPACING, dy=SPACING)
vmax = max(df["AVERAGE_CONC"].max() for df in plots.values())
levels = np.geomspace(vmax / 30, vmax, 9)
fig, axes = plt.subplots(1, 2, figsize=(9, 6.5), sharey=True, constrained_layout=True)
for ax, name in zip(axes, ("FLAT", "ELEV")):
conc = plots[name].sort_values(["Y", "X"])["AVERAGE_CONC"].to_numpy().reshape(elev.shape)
ax.imshow(shade, cmap="gray", origin="lower", extent=(X.min(), X.max(), Y.min(), Y.max()), vmin=-0.3)
cs = ax.contourf(X, Y, np.clip(conc, levels[0] / 10, None), levels=levels, norm=LogNorm(levels[0], vmax),
cmap="YlOrRd", alpha=0.75, extend="max")
tc = ax.contour(X, Y, elev, levels=[100, 200, 300], colors="k", linewidths=0.6, alpha=0.7)
ax.clabel(tc, fmt="%d m", fontsize=7)
m = results[name].get_max_concentration("ANNUAL")
ax.plot(0, 0, "^", ms=10, mfc="white", mec="black", label="Stack (145 m)")
ax.plot((m["x"] - STACK_X) / 1000, (m["y"] - STACK_Y) / 1000, "*", ms=15, mfc="cyan", mec="black",
label=f"Max {m['value']:.2f} µg/m³")
ax.set_title(f"TERRAIN {name}")
ax.set_xlabel("Easting from stack (km)")
ax.set_aspect("equal")
ax.legend(loc="lower left", fontsize=8)
axes[0].set_ylabel("Northing from stack (km)")
cb = fig.colorbar(cs, ax=axes, orientation="horizontal", shrink=0.7, format="%.2f",
label="Annual average SO₂ (µg/m³)")
cb.set_ticks(levels[::2])
fig.suptitle("Annual SO₂ from a 145 m stack, flat vs AERMAP terrain (100 m contours), LOVETT 1988 met")
fig.savefig(WORK / "08_complex_terrain.png", dpi=130)
print("Figure:", WORK / "08_complex_terrain.png")
Result (AERMOD 26135, AERMAP 24142, LOVETT 1988 met):

AERMAP put the stack base at 5.2 m on the riverbank. It gave the 3,721 receptors elevations from -54 m to 381 m and hill heights up to 395 m. With FLAT terrain the annual maximum is 0.99 µg/m³, 1.7 km east-south-east of the stack. With ELEV the plume reaches the ridge 2.9 km to the north-north-west, and the annual maximum rises to 2.72 µg/m³ on its 300 m crest. The 1-hour highest values show the same shift: 85.86 µg/m³ with FLAT and 267.91 µg/m³ with ELEV. Flat terrain understates this site's impacts about threefold, and it puts the maximum in the wrong place.
Adapting it
- Change
STACK_X,STACK_YandUTM_ZONEto your site, and widenBBOX(degrees) so that it covers the receptor grid plusBUFFERwith some margin. Otherwise AERMAP stops withE310 Domain Coordinate is NOT Inside a DEM File. TheBUFFERmust take in every hill that rises above a 10 % slope from any receptor. - USGS tiles come LZW-compressed, and AERMAP 24142 cannot read compressed GeoTIFFs: it stops with
E455 ... TiffTag: 259.DEMDownloader.download_demrewrites each tile uncompressed (this needsrasterio), and of the dated versions the TNM API lists for each tile it downloads only the newest. Relativedem_filespaths are fine:TerrainProcessor.processwrites them to the AERMAP deck as absolute paths. - DFAULT overrides
TerrainType.FLATwith elevated terrain (W206), so the FLAT run has to setregulatory_default=False. - Check the extremes AERMAP returns. Here the 3DEP surface goes down to -54 m in a depression south-west of the stack. Receptors over water or in pits may need their elevations reviewed before a real study.
9. Particle dry and wet deposition¶
When you need it: risk assessments for metals, dioxins and other persistent particulate pollutants. These need the mass that lands on soil, crops and water (multipathway or ecological exposure), not only what is in the air. Particulate deposition also matters for dust and ash sources where the larger particles settle out close to the fence line.
What it shows: Method 1 particle deposition inputs on a PointSource via ParticleDepositionParams (PARTDIAM / MASSFRAX / PARTDENS). ControlPathway's calculate_dry_deposition / calculate_wet_deposition switches write MODELOPT CONC DDEP WDEP. The script then reads the deposition tables from parse_aermod_output (results.deposition["DDEP"]["ANNUAL"]) and the per-receptor values from one multi-column plot file with read_plotfile.
"""Particle dry and wet deposition from a point source.
A 30 m stack emits PM in three size classes (PARTDIAM / MASSFRAX / PARTDENS, AERMOD's
Method 1); AERMOD calculates concentration plus dry (DDEP) and wet (WDEP) deposition for
a year. Uses EPA's HOUSTON_ADJU met (1996): LOVETT.SFC has no precipitation (every hour
is missing), and wet deposition needs it. Writes 09_deposition.png: annual dry vs wet maps.
"""
import os
from pathlib import Path
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.colors import LogNorm
from pyaermod import (
AERMODProject,
AERMODRunner,
CartesianGrid,
ControlPathway,
MeteorologyPathway,
OutputPathway,
ParticleDepositionParams,
PointSource,
PollutantType,
ReceptorPathway,
SourcePathway,
TerrainType,
Validator,
parse_aermod_output,
read_plotfile,
)
MET_DIR = Path(os.environ.get("AERMOD_MET_DIR", "met")) # holds HOUSTON_ADJU.SFC / .PFL
WORK = Path(os.environ.get("USE_CASE_OUT", "out")) / "09_deposition"
WORK.mkdir(parents=True, exist_ok=True)
Q = 2.0 # g/s of PM, all three size classes together
# 1. Source with Method 1 particle deposition inputs (one entry per size class).
sources = SourcePathway()
sources.add_source(PointSource(
source_id="KILN", x_coord=0.0, y_coord=0.0,
stack_height=30.0, # m
stack_temp=350.0, # K
exit_velocity=10.0, # m/s
stack_diameter=1.5, # m
emission_rate=Q,
particle_deposition=ParticleDepositionParams(
diameters=[1.0, 5.0, 15.0], # µm
mass_fractions=[0.30, 0.45, 0.25], # must sum to 1
densities=[2.0, 2.0, 2.0], # g/cm3
),
))
# 2. CONC + DDEP + WDEP. Method 1 particle deposition is allowed under DFAULT, and
# DFAULT means elevated terrain, so the flat site is ELEV with every height 0.
# Dry and wet plume depletion are on by default once a source has deposition inputs.
control = ControlPathway(
title_one="Particle dry and wet deposition from a 30 m stack",
pollutant_id=PollutantType.PM10,
averaging_periods=["ANNUAL"],
terrain_type=TerrainType.ELEVATED,
calculate_concentration=True, # CONC, ug/m3
calculate_dry_deposition=True, # DDEP, g/m2 over the period
calculate_wet_deposition=True, # WDEP, g/m2 over the period
)
receptors = ReceptorPathway()
receptors.add_cartesian_grid(CartesianGrid.from_bounds(-2500, 2500, -2500, 2500, spacing=100.0))
met = MeteorologyPathway(
surface_file=str((MET_DIR / "HOUSTON_ADJU.SFC").resolve()),
profile_file=str((MET_DIR / "HOUSTON_ADJU.PFL").resolve()),
surface_station_id=722430, upper_air_station_id=3937, data_start_year=1996,
profile_base_elevation=0.0, # m MSL, as in EPA's testprt2.inp
)
# The ANNUAL plot file holds one column per quantity: CONC, DRY DEPO, WET DEPO.
output = OutputPathway(plot_file="dep_annual.plt", plot_file_averaging="ANNUAL")
project = AERMODProject(control, sources, receptors, met, output)
# 3. Validate, write, run, parse.
check = Validator.validate(project)
print(check)
if not check.is_valid:
raise SystemExit(1)
inp = project.write(WORK / "deposition.inp")
run = AERMODRunner().run(inp, working_dir=WORK)
if not run.success:
raise SystemExit(f"AERMOD failed: {run.error_message}")
results = parse_aermod_output(run.output_file)
print(f"AERMOD {results.run_info.version}: {run.output_file}")
plot = read_plotfile(WORK / "dep_annual.plt").to_dataframe().sort_values(["Y", "X"])
print("Plot file columns:", list(plot.columns[:5]))
conc = results.concentrations["ANNUAL"]
print(f"Annual concentration max {conc.max_value:.3f} {conc.units} at ({conc.max_location[0]:.0f}, "
f"{conc.max_location[1]:.0f}) m")
emitted = Q * 8784 * 3600 # g over the 1996 met year (8784 hours)
cell = 100.0 * 100.0 # m2 per receptor
for kind, column in (("DDEP", "DRY_DEPO"), ("WDEP", "WET_DEPO")):
table = results.deposition[kind]["ANNUAL"]
within = plot[column].sum() * cell
x, y = table.max_location
print(f"{kind} max {table.max_value:.4f} {table.units} at ({x:.0f}, {y:.0f}) m; "
f"{within / 1000:.0f} kg in the 5 km x 5 km grid = {100 * within / emitted:.1f}% of the emissions")
# 4. Figure: annual dry and wet deposition on one log scale.
xs, ys = np.unique(plot["X"]), np.unique(plot["Y"])
X, Y = np.meshgrid(xs / 1000, ys / 1000) # km
vmax = plot[["DRY_DEPO", "WET_DEPO"]].to_numpy().max()
levels = np.geomspace(vmax / 1000, vmax, 13)
fig, axes = plt.subplots(1, 2, figsize=(9, 6.5), sharey=True, constrained_layout=True)
for ax, (column, label) in zip(axes, (("DRY_DEPO", "Dry (DDEP)"), ("WET_DEPO", "Wet (WDEP)"))):
dep = plot[column].to_numpy().reshape(len(ys), len(xs))
cs = ax.contourf(X, Y, np.clip(dep, levels[0] / 10, None), levels=levels,
norm=LogNorm(levels[0], vmax), cmap="viridis", extend="min")
ax.plot(0, 0, "^", ms=10, mfc="white", mec="black", label="Stack (30 m)")
ax.set_title(f"{label}: max {dep.max():.3f} g/m²/yr")
ax.set_xlabel("Easting (km)")
ax.set_aspect("equal")
ax.legend(loc="lower left", fontsize=8)
axes[0].set_ylabel("Northing (km)")
cb = fig.colorbar(cs, ax=axes, orientation="horizontal", shrink=0.7, format="%g",
label="Annual deposition (g/m²/yr)")
cb.set_ticks([t for t in (0.003, 0.01, 0.03, 0.1, 0.3, 1, 3) if levels[0] <= t <= vmax])
fig.suptitle(f"PM deposition, {Q:g} g/s from a 30 m stack (1, 5, 15 µm), HOUSTON 1996 met")
fig.savefig(WORK / "09_deposition.png", dpi=130)
print("Figure:", WORK / "09_deposition.png")
Result (AERMOD 26135, HOUSTON_ADJU 1996 met):

Dry deposition dominates. It peaks at 2.3132 g/m^2/yr 300 m north-north-west of the stack, downwind of Houston's prevailing south-easterlies, where the 15 µm particles settle out. Wet deposition is more symmetric, because it follows the wind directions of the 253 hours with rain, and it peaks at only 0.1622 g/m^2/yr next to the stack. Of the 63 t emitted in the year, 3723 kg (5.9%) lands as dry deposition and 130 kg (0.2%) as wet deposition inside the 5 km × 5 km grid. The rest is carried further away. The annual-average concentration peaks at 1.804 µg/m³.
Adapting it
- Wet deposition needs hourly precipitation in the
.SFCfile. EPA's LOVETT.SFC has every precipitation value missing (-9), which is why this example uses HOUSTON_ADJU.SFC. Check your own AERMET output before you trust a WDEP of zero. - Deposition comes out in g/m² totalled over the averaging period, so ANNUAL is g/m²/yr, not a flux per second. A run with CONC, DDEP and WDEP writes one plot-file column per quantity, all in the same file.
- Method 1 particle inputs run under DFAULT. DFAULT forces elevated terrain, though, so a flat site is ELEV with zero heights. To get FLAT you have to set
regulatory_default=False. Gas deposition (GasDepositionParams) andMETHOD_2also needalpha=Trueand no DFAULT. - Once any source has deposition inputs, dry and wet plume depletion are on (DRYDPLT WETDPLT), and every source in the run then needs deposition inputs (E242). Use
ControlPathway(dry_depletion=False, wet_depletion=False)for a CONC-only run that should not deplete.
10. Air-toxics screening with a unit emission rate (χ/Q) and GIS export¶
When you need it: A facility emits many hazardous air pollutants from the same stack, and a state air-toxics review asks for each one's maximum annual and short-term impact against a guideline concentration. One AERMOD run at 1 g/s gives the dispersion factor χ/Q. Multiplying it by each pollutant's emission rate gives every pollutant's impact without another model run.
What it shows: latlon_to_utm places the stack in UTM 18N. OutputPathway(period_plot_files=...) writes a PLOTFILE per averaging period, which read_plotfile reads at every receptor. The script exports the fields with export_concentration_geotiff and export_concentration_shapefile (GeoJSON points), and draws contours with ContourGenerator for a Google Earth file written by to_kmz.
"""
Air-toxics screening with a unit emission rate (chi/Q) and GIS export.
Runs one stack at 1 g/s, so every concentration AERMOD reports is a dispersion
factor chi/Q in (ug/m3)/(g/s). Scales the annual and 1-hour fields to several toxics'
emission rates, compares the maxima with illustrative screening levels, and exports
the fields as GeoTIFF, GeoJSON and KMZ (UTM zone 18N, near LOVETT's New York site).
"""
import os
from pathlib import Path
MET_DIR = Path(os.environ.get("AERMOD_MET_DIR", "met")) # holds LOVETT.SFC / LOVETT.PFL
WORK = Path(os.environ.get("USE_CASE_OUT", "out")) / "10_unit_emission_air_toxics"
WORK.mkdir(parents=True, exist_ok=True)
import matplotlib.pyplot as plt # noqa: E402
import numpy as np # noqa: E402
from pyaermod import ( # noqa: E402
AERMODProject,
CartesianGrid,
ContourGenerator,
ContourPolygon,
ControlPathway,
CoordinateTransformer,
MeteorologyPathway,
OutputPathway,
PointSource,
ReceptorPathway,
SourcePathway,
Validator,
export_concentration_geotiff,
export_concentration_shapefile,
latlon_to_utm,
parse_aermod_output,
read_plotfile,
run_aermod,
to_kmz,
)
# Emission rates (g/s) and screening levels (ug/m3) -- ILLUSTRATIVE numbers only;
# substitute your agency's annual and short-term guideline concentrations.
TOXICS = { # name: (rate g/s, annual level, 1-hr level)
"Benzene": (0.40, 0.15, 30.0),
"Formaldehyde": (0.10, 0.10, 50.0),
"Toluene": (2.0, 5000.0, 30000.0),
"Hydrogen chloride": (0.50, 20.0, 2000.0),
"Nickel": (0.002, 0.005, 0.2),
}
# --- Site: place the stack by lat/lon and model in UTM 18N metres
x0, y0, zone, hemi = latlon_to_utm(41.256, -73.986)
x0, y0 = round(x0), round(y0)
sources = SourcePathway()
sources.add_source(PointSource(
source_id="STACK", x_coord=x0, y_coord=y0,
stack_height=30.0, stack_temp=400.0, # m, K
exit_velocity=12.0, stack_diameter=1.0, # m/s, m
emission_rate=1.0, # unit rate: output is chi/Q
))
receptors = ReceptorPathway()
receptors.add_cartesian_grid(CartesianGrid.from_bounds(
x0 - 2000, x0 + 2000, y0 - 2000, y0 + 2000, spacing=100))
project = AERMODProject(
control=ControlPathway(
title_one="Use case 10: unit-emission chi/Q for air toxics",
pollutant_id="OTHER", averaging_periods=["1", "ANNUAL"],
terrain_type="ELEVATED", # all elevations 0 m; run AERMAP for real terrain
),
sources=sources, receptors=receptors,
meteorology=MeteorologyPathway(
surface_file=str((MET_DIR / "LOVETT.SFC").resolve()),
profile_file=str((MET_DIR / "LOVETT.PFL").resolve()),
surface_station_id=14735, upper_air_station_id=14735,
data_start_year=1988, profile_base_elevation=1.8,
),
# PLOTFILEs chiq_01H.plt / chiq_ANNUAL.plt hold the value at every receptor
output=OutputPathway(receptor_table_rank=1, max_table_rank=1, period_plot_files="chiq"),
)
# --- Validate, write, run, parse
check = Validator.validate(project, check_files=True)
print(check)
if not check.is_valid:
raise SystemExit(1)
project.write(WORK / "unit.inp")
run = run_aermod(WORK / "unit.inp", timeout=1800)
if not run.success:
raise SystemExit(f"AERMOD failed: {run.error_message}")
# chi/Q in (ug/m3)/(g/s) at every receptor; the 1-hr file is each receptor's highest
grids = {}
for period in ("ANNUAL", "01H"):
pf = read_plotfile(WORK / f"chiq_{period}.plt")
grids[period] = pf.to_dataframe().rename(
columns={"X": "x", "Y": "y", pf.concentration_column: "concentration"})
annual, hour1 = grids["ANNUAL"], grids["01H"]
summary = parse_aermod_output(run.output_file) # AERMOD's own maxima, as a cross-check
for period, df in (("ANNUAL", annual), ("1HR", hour1)):
m = summary.get_max_concentration(period)
print(f"Max {period} chi/Q {df.concentration.max():.4g} (ug/m3)/(g/s) at "
f"({m['x']:.0f}, {m['y']:.0f}); AERMOD summary {m['value']:.4g}")
# --- Scale chi/Q by each emission rate and compare with the screening levels
rows = []
for name, (rate, ann_lvl, hr_lvl) in TOXICS.items():
annual[name] = annual.concentration * rate
ann_max, hr_max = annual[name].max(), hour1.concentration.max() * rate
rows.append((name, ann_max / ann_lvl, hr_max / hr_lvl))
print(f"{name:18s} annual max {ann_max:9.4g} ug/m3 ({ann_max / ann_lvl:.2g} x level)"
f" 1-hr max {hr_max:9.4g} ug/m3 ({hr_max / hr_lvl:.2g} x level)")
# --- GIS export (UTM 18N): rasters of chi/Q, scaled points, Google Earth contours
files = [
export_concentration_geotiff(annual, WORK / "chiq_annual.tif", utm_zone=zone),
export_concentration_geotiff(hour1, WORK / "chiq_1hr.tif", utm_zone=zone),
export_concentration_shapefile(annual, WORK / "toxics_annual.geojson", utm_zone=zone,
as_contours=False, driver="GeoJSON"),
]
levels = [0.02, 0.05, 0.1, 0.15, 0.2, 0.25, 0.3, 0.4, 0.5] # chi/Q contours
cmap = plt.get_cmap("YlOrRd", len(levels))
top = annual.concentration.max()
polys = ContourGenerator(CoordinateTransformer(zone, hemi)).generate_contours_latlon(
annual, levels=[v for v in levels if v < top] + [top])
contours = [ContourPolygon(r.level_min, list(p.exterior.coords), f">= {r.level_min:g}")
for r in polys.itertuples()
for p in getattr(r.geometry, "geoms", [r.geometry])]
# One KML colour (aabbggrr) per contour level, lowest first, as on the map
kml = ["b0" + "".join(f"{round(255 * c):02x}" for c in cmap(levels.index(lv))[2::-1])
for lv in sorted({c.level for c in contours})]
files.append(to_kmz(WORK / "chiq_annual.kmz", sources=sources.sources, contours=contours,
utm_zone=zone, palette=kml, title="Annual chi/Q, (ug/m3)/(g/s)"))
print("GIS files:", ", ".join(f.name for f in files))
# --- Figure: annual chi/Q map + scaled maxima relative to the screening levels
fig, (ax, bx) = plt.subplots(1, 2, figsize=(9, 6.5), gridspec_kw={"width_ratios": [1.3, 1]})
xs, ys = np.sort(annual.x.unique()), np.sort(annual.y.unique())
grid = annual.pivot(index="y", columns="x", values="concentration").loc[ys, xs]
cf = ax.contourf(xs / 1000, ys / 1000, grid, levels=levels, cmap=cmap, extend="both")
best = annual.loc[annual.concentration.idxmax()]
ax.plot(best.x / 1000, best.y / 1000, "*", color="w", ms=13, mec="k",
label=f"max {best.concentration:.2f} (µg/m³)/(g/s)")
ax.plot(x0 / 1000, y0 / 1000, "k^", ms=9, label="STACK (1 g/s)")
ax.set(aspect="equal", xlabel="UTM 18N easting (km)", ylabel="UTM 18N northing (km)",
title="Annual-average χ/Q")
ax.ticklabel_format(useOffset=False)
ax.legend(loc="lower left", fontsize=8)
fig.colorbar(cf, ax=ax, orientation="horizontal", pad=0.12,
label="Annual χ/Q ((µg/m³)/(g/s))")
names = [r[0] for r in rows]
pos = np.arange(len(rows))
bx.barh(pos - 0.2, [r[1] for r in rows], 0.4, color="#fdae61", label="annual max / level")
bx.barh(pos + 0.2, [r[2] for r in rows], 0.4, color="#d7191c", label="1-hr max / level")
bx.axvline(1.0, color="k", ls="--", lw=1.2, label="screening level")
bx.set_yticks(pos, names)
bx.invert_yaxis()
bx.set_xscale("log")
for k, r in enumerate(rows):
for dy, v in ((-0.2, r[1]), (0.2, r[2])):
bx.text(v * 1.15, k + dy, f"{v:.2g}", va="center", fontsize=7)
bx.set_xlim(right=10)
bx.set(xlabel="Scaled max ÷ illustrative screening level (–)")
bx.legend(fontsize=8, loc="lower center", bbox_to_anchor=(0.5, 1.0), frameon=False)
fig.suptitle("Unit-emission (1 g/s) dispersion factor and scaled air-toxics maxima, "
"LOVETT 1988 met", fontsize=11)
fig.tight_layout()
fig.savefig(WORK / "10_unit_emission_air_toxics.png", dpi=130)
print(f"Figure: {WORK / '10_unit_emission_air_toxics.png'}")
Result (AERMOD 26135, LOVETT 1988 met):

The highest annual χ/Q is 0.5 (µg/m³)/(g/s) and the highest 1-hour χ/Q is 26.86 (µg/m³)/(g/s). Both occur at (585149, 4567572), about 220 m east-southeast of the stack, and both match AERMOD's own summary tables. Scaled by the example emission rates, benzene's annual maximum (0.2 µg/m³) is 1.3 times its illustrative screening level, so it would go on to a refined review. Every other pollutant and averaging period screens out, with formaldehyde's annual maximum (0.5 times its level) the next highest. The run writes chiq_annual.tif, chiq_1hr.tif, toxics_annual.geojson (one column per pollutant) and chiq_annual.kmz.
Adapting it
- Edit
TOXICS: emission rates in g/s, and your agency's annual and 1-hour guideline concentrations. The levels in the script are illustrative placeholders, not regulatory values. - Use the PLOTFILEs (or POSTFILEs) for maps and GIS.
parse_aermod_output(...).get_concentrations()returns AERMOD's summary tables (the top-N values), not the value at every receptor;AERMODVisualizer.plot_contours(plotfile=...)contours a plot file directly. to_kmztakes onepalettecolour per contour level, lowest first, and gives every ring of a level that colour.- χ/Q scaling holds only for pollutants modelled the same way: the same release, no deposition, decay or chemistry. Particle-phase metals with deposition need their own runs.
- Set the UTM zone and datum to your site (
latlon_to_utmpicks the zone for you). The GIS files are in EPSG:32618 (WGS 84 / UTM 18N), and the KMZ is in lon/lat.