Skip to content

runner

runner

PyAERMOD Runner

Executes AERMOD binaries from Python with error handling, progress monitoring, and batch processing capabilities.

AERMODMessage dataclass

One message from the message summary in an AERMOD .out file.

AERMOD prints each message on one line with the Fortran format (1X,A2,1X,A1,A3,I8,1X,A12,': ',A50,1X,A12), for example::

 MX E480      97         MAIN: Less than 1yr for MULTYEAR, MAXDCONT or ANNUAL Ave     NUMYRS=0

Attributes: severity: 'E' (fatal error), 'W' (warning) or 'I' (informational). pathway: The pathway that raised the message, such as 'CO', 'SO', 'RE', 'ME', 'OU' or 'MX' (the meteorological data). It is empty when AERMOD leaves it blank. code: The severity and number together, such as 'E480'. line: The line reference as AERMOD prints it. During setup this is the line of the input deck. During the run it is the record of the data file being read, such as the hour of met data for MX messages. module: The AERMOD routine that raised the message, such as 'MAIN'. text: The message text. AERMOD cuts it to 50 characters. detail: The detail field of up to 12 characters that follows the text, such as 'NUMYRS=0' or 'SURFFILE'. It is empty when AERMOD prints none.

AERMODRunResult dataclass

Result from an AERMOD execution.

success is True only when AERMOD exited with code 0, wrote its .out file, printed *** AERMOD Finishes Successfully *** there and reported no fatal errors. The exit code alone says nothing: AERMOD exits with 0 after a fatal error.

fatal_messages property

fatal_messages: List[AERMODMessage]

The fatal errors AERMOD listed (severity 'E').

warning_messages property

warning_messages: List[AERMODMessage]

The warnings AERMOD listed (severity 'W').

fatal_count property

fatal_count: int

Number of fatal errors, from AERMOD's own total when it printed one.

warning_count property

warning_count: int

Number of warnings, from AERMOD's own total when it printed one.

informational_count property

informational_count: int

Number of informational messages. AERMOD counts these but does not list them.

AERMODRunner

Execute AERMOD simulations from Python

Handles subprocess management, file I/O, error detection, and batch processing.

run

run(input_file: Union[str, Path], working_dir: Optional[Union[str, Path]] = None, timeout: int = 3600, capture_output: bool = True) -> AERMODRunResult

Execute AERMOD with given input file

Blocks until AERMOD ends. :meth:start runs AERMOD in the background instead, reporting its progress and allowing a cancel.

Args: input_file: Path to AERMOD input file (.inp) working_dir: Working directory for execution (defaults to input file location) timeout: Maximum execution time in seconds (default 1 hour) capture_output: Whether to capture stdout/stderr

Returns: AERMODRunResult with execution details and file paths

AERMOD reads <working_dir>/aermod.inp. The runner links the deck to that name for the run and renames aermod.out, .err and .sum after the deck. A deck that is already aermod.inp, or that aermod.inp links to, runs in place. When aermod.inp is another deck, the run fails without starting AERMOD, so that deck and its aermod.out are kept. Where links cannot be made, the deck is copied to aermod.inp instead; a copy the runner left behind (its process killed mid-run) is replaced, not taken for another deck.

start

start(input_file: Union[str, Path], working_dir: Optional[Union[str, Path]] = None, timeout: int = 3600, *, on_progress: Optional[Callable[[AERMODProgress], None]] = None, on_finish: Optional[Callable[[AERMODRunResult], None]] = None) -> AERMODRun

Start AERMOD in the background and return at once.

The run does what :meth:run does, in a thread of its own: it waits for the working directory's lock, points aermod.inp at the deck, runs AERMOD, renames its outputs and reads its verdict. The returned :class:AERMODRun reports AERMOD's progress, can be cancelled and can be waited for.

Args: input_file: Path to AERMOD input file (.inp) working_dir: Working directory for execution (defaults to input file location) timeout: Maximum execution time in seconds (default 1 hour) on_progress: Called with an :class:AERMODProgress for each "Now Processing Data For Day No." line AERMOD prints, from the thread that reads AERMOD's output. on_finish: Called with the :class:AERMODRunResult once the run has ended (cancelled=True after :meth:AERMODRun.cancel), from the run's own thread and before :meth:AERMODRun.wait returns, so it must not wait for the run itself.

Returns: The running :class:AERMODRun.

Raises: NotImplementedError: under Pyodide, which has no threads; use :meth:run there.

run_batch

run_batch(input_files: Sequence[Union[str, Path]], n_workers: int = 4, timeout: int = 3600, stop_on_error: bool = False) -> List[AERMODRunResult]

Run multiple AERMOD simulations in parallel

The results come back in the order of input_files, whatever order the runs finish in: results[i] belongs to input_files[i], and its input_file is that deck's absolute path.

The runs happen in worker processes. On macOS and Windows those are started with spawn, which imports the calling script again in every worker, so a script must call run_batch from under if __name__ == "__main__":. Without the guard each worker stops with Python's "An attempt has been made to start a new process before the current process has finished its bootstrapping phase" and every run comes back failed with "A process in the process pool was terminated abruptly"::

if __name__ == "__main__":
    results = runner.run_batch(decks, n_workers=4)

Args: input_files: List of input file paths n_workers: Number of parallel workers timeout: Timeout per run (seconds) stop_on_error: Stop at the first failed run. Runs not yet started are cancelled and runs already started finish. The list still holds one result per deck: a cancelled deck's result has success=False and the error_message "Not run: the batch stopped after an earlier run failed".

Returns: List of AERMODRunResult objects, in the order of input_files

validate_input

validate_input(input_file: Union[str, Path]) -> Tuple[bool, List[str]]

Validate AERMOD input file (basic checks)

Args: input_file: Path to input file

Returns: (is_valid, list_of_issues)

AERMODProgress dataclass

How far a background AERMOD run has got.

Attributes: stage: "setup" (AERMOD is reading the deck), "day" (it is processing a day of met data) or "output" (it is writing the results). day: The Julian day of the latest "Now Processing Data For Day No." line, or 0 before the first. year: The year of that day, or 0 before the first. days_processed: How many of those lines AERMOD has printed so far. Compared with the number of days in the met data (see :func:pyaermod.aermet.read_surface_period) it gives the run's fraction done. line: The line as AERMOD printed it.

AERMODRun

An AERMOD run started in the background by :meth:AERMODRunner.start.

The run executes in a thread of its own. Its state can be read from any thread:

  • :attr:progress is the latest :class:AERMODProgress;
  • :attr:done says whether the run has ended, and :attr:result holds its :class:AERMODRunResult once it has;
  • :meth:cancel stops AERMOD (SIGTERM, then a kill after :data:CANCEL_GRACE_SECONDS), and the result then has cancelled=True and success=False;
  • :meth:wait blocks until the run has ended and returns the result.

The process is always waited for, so a cancelled or timed-out run leaves neither a running AERMOD nor a zombie behind.

pid property

pid: Optional[int]

AERMOD's process id once it has started, else None.

result property

result: Optional[AERMODRunResult]

The run's result once it has ended, else None.

cancel

cancel() -> bool

Stop the run. False if it has already ended or was already cancelled.

Returns at once; the run ends (and :meth:wait returns) once AERMOD has exited. A run cancelled before AERMOD started never starts it.

wait

wait(timeout: Optional[float] = None) -> AERMODRunResult

Block until the run has ended and return its result.

Raises: TimeoutError: if timeout seconds pass first.

SweepResults

Bases: Mapping

The results of :meth:BatchRunner.parameter_sweep, by sweep value.

A read-only mapping from each value of the sweep, in sweep order, to its :class:AERMODRunResult. Values need not be hashable: looking one up compares by ==, so results[psd] works for a :class:~pyaermod.sources.ParticleDepositionParams. keys(), items() and values() are the usual mapping views, in sweep order.

It is not a dict: isinstance(results, dict) is False, it cannot be changed, and json.dumps does not take it. When the values are hashable, dict(results) gives the dict parameter_sweep returned in pyaermod 2.2 and earlier.

items

items() -> ItemsView

(value, result) pairs in sweep order.

values

values() -> ValuesView

Results in sweep order.

BatchRunner

Helper class for running parameter sweeps and scenario comparisons

parameter_sweep

parameter_sweep(base_project, parameter_name: str, parameter_values: List, output_dir: Union[str, Path], n_workers: int = 4, source_index: int = 0) -> SweepResults

Run AERMOD over a sweep of one parameter on one source.

For each value in parameter_values:

  1. Deep-copy base_project
  2. Set parameter_name on the indicated source (or on the project if the name contains a dot, e.g. "control.title_one")
  3. Write the modified project to output_dir/run_{name}_{label}.inp
  4. Queue the file for batch execution

label is the value's own text when the value is a number, string or boolean whose text is short, holds only letters, digits and ._+- once every other character (a space, a /) is turned into _, and differs from every other value's: run_emission_rate_0.5.inp. Any other value, such as a :class:~pyaermod.sources.ParticleDepositionParams for a size-distribution sweep, is labelled by its position and the first 12 hex digits of the SHA-256 of its canonical JSON (:func:pyaermod.ensemble.canonical_json): run_particle_deposition_001_3fa9c0d27e41.inp.

Every output file the deck names (PLOTFILE, POSTFILE, ...) is renamed to run_{name}_{label}_<file name> in output_dir, so the runs do not overwrite each other's results. Files AERMOD names itself are not renamed, so the runs share them and the last run's copy is kept: the file of a debug option or ERRORFIL given without a name, DEPOS's GDEP.DAT, PDEP.DAT and DEPOS.DBG, and PVMRM's RelDisp.dbg.

All the decks share output_dir, whose lock lets one AERMOD run at a time there (see :meth:AERMODRunner.run), so the runs do not overlap whatever n_workers is. :func:pyaermod.ensemble.run_design gives each run its own directory and does run them in parallel.

Parameters:

Name Type Description Default
base_project AERMODProject

Template project that gets cloned for each run.

required
parameter_name str

Attribute to modify. If it contains ., it's interpreted as a dotted path relative to the project root (e.g. "control.flag_pole_height" or "output.receptor_table_rank"). Otherwise it's a field name on the source at source_index (e.g. "emission_rate", "stack_height").

required
parameter_values list

Values to substitute in. They need not be hashable, but no two may be equal.

required
output_dir Path

Directory for generated .inp files and AERMOD outputs.

required
n_workers int

Number of parallel AERMOD workers.

4
source_index int

Which source to mutate when parameter_name is a plain field name. Defaults to 0 (the first source).

0

Returns:

Type Description
SweepResults

Mapping of parameter value -> AERMODRunResult, in sweep order.

Raises:

Type Description
ValueError

When two values are equal: they would make the same run. Also when two of the deck's output files would get the same name once their directories are dropped (compared ignoring case), such as annual/result.plt and hourly/result.plt, or when a renamed file name is longer than AERMOD's 200 characters (:func:pyaermod.ensemble.rewrite_output_names).

parse_aermod_messages

parse_aermod_messages(output_file: Union[str, Path]) -> List[AERMODMessage]

Read the fatal errors and warnings AERMOD lists in a .out file.

The messages come from the file's final message summary, which includes the setup messages, in the order AERMOD lists them: fatal errors first, then warnings. AERMOD counts informational messages but does not list them in the .out file.

Args: output_file: Path to an AERMOD .out file.

Returns: The listed messages. The list is empty when the file has no message summary.

Raises: FileNotFoundError: If output_file does not exist.

find_aermod_executable

find_aermod_executable(path: Optional[Union[str, Path]] = None) -> Path

The AERMOD executable: path if given, else the first on PATH.

Under Pyodide, where no executable can run, this is the aermod.js of a WebAssembly build (see :mod:pyaermod.wasm_runner). Raises FileNotFoundError when path does not exist or nothing is found.

parse_progress_line

parse_progress_line(line: str) -> Optional[Tuple[int, int]]

(julian_day, year) from an AERMOD progress line, or None.

parse_progress_line("+Now Processing Data For Day No. 61 of 1988") (61, 1988)

stop_active_runs

stop_active_runs() -> None

Kill every background AERMOD run still going in this process.

Runs when Python exits normally (atexit), which covers a clean exit and Ctrl+C but not a process killed by a signal it does not handle, such as SIGTERM: a server should also call this from its own shutdown hook (the GUI does, from NiceGUI's app.on_shutdown).

run_aermod

run_aermod(input_file: Union[str, Path], executable_path: Optional[Union[str, Path]] = None, timeout: int = 3600) -> AERMODRunResult

Quick function to run AERMOD

Args: input_file: Path to input file executable_path: Optional path to AERMOD executable timeout: Timeout in seconds

Returns: AERMODRunResult