Skip to content

ensemble

ensemble

PyAERMOD ensembles: run a designed set of AERMOD runs and collect them.

A design is a list of rows, each a mapping of factor names to values ({"diameter_um": 10.0, "met": "COR"}). :func:run_design builds one AERMOD project per row with a function the caller supplies, runs every project in its own directory, and records each run in a manifest, so that an interrupted design picks up where it stopped when it is run again. :func:collect_plotfiles reads the PLOTFILEs of the finished runs into one table.

Each run is known by its run ID, the SHA-256 of the canonical JSON (:func:canonical_json) of::

{"binary_sha256": ..., "factors": {...},
 "input_files_sha256": {"HOUREMIS": ..., ...},
 "met_sha256": {"profile": ..., "surface": ...},
 "schema_version": SCHEMA_VERSION}

that is, of the row's factors, the SHA-256 of the AERMOD binary, the SHA-256 of the surface and profile met files and of every other file the deck has AERMOD read (HOUREMIS, an hourly BACKGRND file, OZONEFIL, NOX_FILE, INITFILE, the MULTYEAR initial file, INCLUDED; see :func:run_design), and the version of this scheme. The ID does not depend on file paths or on when the run was made. A new binary or an edited met or emission file makes a new run, in a new directory; the old one is kept, and root/design.json names the runs of the latest call, which :func:collect_plotfiles reads by default.

Layout under root::

root/
  manifest.json         one entry per run ID (EnsembleManifest)
  manifest.csv          the same, one row per run
  design.json           the run IDs of the latest run_design call
  runs/<run ID>/
    run.inp             the deck
    factors.json        what the run ID was computed from
    <surface>, <profile>, <other input files>
                        links to the files the deck reads (copies
                        where links cannot be made)
    run.out, run.err, run.sum, PLOTFILEs, ...

Why one directory per run: AERMOD reads aermod.inp and writes its output files relative to its working directory, and the runner locks that directory for the length of a run (:meth:pyaermod.runner.AERMODRunner.run), so decks sharing a directory run one after another whatever n_workers is, and decks naming the same output file overwrite each other's results. :func:run_design therefore rewrites every output file name the deck gives (PLOTFILE, POSTFILE, SUMMFILE, MAXIFILE, RANKFILE, ERRORFIL, DEBUGOPT, ..., also in the lines :mod:pyaermod.input_reader keeps verbatim) to its bare file name inside the run's directory.

EnsembleManifestEntry dataclass

Bases: RunManifestEntry

One run of a design, as :class:EnsembleManifest stores it.

Extends :class:~pyaermod.runner_utils.RunManifestEntry, whose input_file here is the deck's path relative to the design root, status is pending, success or failed, and runtime_seconds is the run's wall time.

EnsembleManifest dataclass

Bases: RunManifest

A :class:~pyaermod.runner_utils.RunManifest keyed by run ID.

put

put(entry: EnsembleManifestEntry, save: bool = True) -> None

Store entry under its run ID, replacing any earlier one.

to_dataframe

to_dataframe()

One row per run, indexed by run ID; factors that are not numbers, strings or booleans are written as canonical JSON.

write_csv

write_csv(path: Union[str, Path]) -> Path

Write :meth:to_dataframe as CSV and return the path.

DesignRun dataclass

One row of a design after :func:run_design.

DesignResult dataclass

Bases: Mapping

The runs of a design, keyed by run ID, in the order of its rows.

n_skipped property

n_skipped: int

Runs already done, taken from the manifest without running AERMOD.

n_run property

n_run: int

Runs AERMOD made in this call.

run_seconds property

run_seconds: float

Total wall time of the runs made in this call, as each run measured it.

concurrency property

concurrency: float

:attr:run_seconds over :attr:elapsed_seconds: how many runs were in progress on average.

It is not the speed-up over running one at a time: runs that share a machine slow each other down, so each run's own time is longer than it would be alone. Time the same design with n_workers=1 for the speed-up.

collect_plotfiles

collect_plotfiles(out_stem: Optional[Union[str, Path]] = 'plotfiles')

:func:collect_plotfiles for these runs only.

to_dataframe

to_dataframe()

One row per run, indexed by run ID: the factors, then the status.

canonical_json

canonical_json(value: Any) -> str

The canonical JSON text of value, from which run IDs are hashed.

Keys are sorted, there is no whitespace, and text is UTF-8 rather than \u escapes. A float is written as Python's shortest round-trip form, so 1.0 and 1 are different factors. An enum is written as its value, a path as its POSIX form, a dataclass as a dict of its fields with "_type" set to its class name, and a set as a sorted list. NaN, infinities, dicts with non-string keys and any other type raise, instead of being written in a form that could change between runs.

file_sha256

file_sha256(path: Union[str, Path], chunk_size: int = 1 << 20) -> str

The SHA-256 of a file's bytes, as 64 lower-case hex digits.

run_id_payload

run_id_payload(factors: Mapping[str, Any], binary_sha256: str, met_sha256: Mapping[str, str], input_files_sha256: Optional[Mapping[str, str]] = None, schema_version: int = SCHEMA_VERSION) -> Dict[str, Any]

What a run ID is the hash of (see :func:run_id).

run_id

run_id(factors: Mapping[str, Any], binary_sha256: str, met_sha256: Mapping[str, str], input_files_sha256: Optional[Mapping[str, str]] = None, schema_version: int = SCHEMA_VERSION) -> str

The run ID: SHA-256 of the canonical JSON of the factors and versions.

met_sha256 maps each met file's role ("surface", "profile") to the SHA-256 of its bytes, and input_files_sha256 does the same for the other files the deck reads, whose roles are their keywords ("HOUREMIS", and "HOUREMIS.2" for a second, different file).

rewrite_output_names

rewrite_output_names(project: Any, prefix: str = '') -> Dict[str, List[str]]

Point every output file project names into AERMOD's working directory.

Each name becomes prefix + its bare file name, so ../plotfiles/pit.plt becomes pit.plt and AERMOD writes it beside the deck. project is changed in place. Returns the new names by keyword, such as {"PLOTFILE": ["pit.plt"]}.

The per-period stems OutputPathway.period_plot_files and period_postfiles are renamed the same way, and the files they stand for (one per ControlPathway.averaging_periods entry, such as per_01H.plt) are listed under PLOTFILE and POSTFILE beside the others; the length and duplicate checks apply to those names.

The names in the lines :mod:pyaermod.input_reader keeps verbatim (:attr:~pyaermod.input_generator.AERMODProject.unparsed_lines) are renamed too: a PLOTFILE with a rank below FIRST or with a unit, a second POSTFILE, and the file fields of MAXIFILE, RANKFILE, TOXXFILE, SEASONHR, EVALFILE, SUMMFILE, MAXDAILY, MXDYBYYR, MAXDCONT, ERRORFIL, EVENTFIL, SAVEFILE, MULTYEAR and DEBUGOPT. The debug files of ControlPathway.debug_options are renamed under DEBUGOPT; a debug option given without a file name writes AERMOD's default name (MODEL.DBG, AREA.DBG, ...) in the working directory, which is the run's own directory already.

Raises ValueError when two outputs would end up with the same name (compared ignoring case, since the disk may ignore it), or when a new name is longer than AERMOD's :data:MAX_FILENAME_LENGTH characters.

Only files AERMOD writes are renamed. Files it reads (met data, INITFILE, HOUREMIS, background and ozone files) are left as they are here; :func:run_design links those into each run's directory itself.

run_design

run_design(rows: Iterable[Mapping[str, Any]], build_fn: Callable[[Dict[str, Any]], Any], root: Union[str, Path], n_workers: int = 4, *, executable: Optional[Union[str, Path]] = None, timeout: int = 3600, resume: bool = True, validate: bool = True, progress: Optional[ProgressReporter] = None) -> DesignResult

Run one AERMOD run per design row, each in its own directory.

For each row, build_fn(factors) returns an :class:~pyaermod.input_generator.AERMODProject. :func:run_design works on a deep copy of it:

  1. The files it has AERMOD read are hashed: the met files (SURFFILE, PROFFILE), INITFILE, the MULTYEAR initial file, OZONEFIL and NOX_FILE files, the HOUREMIS files of SourcePathway.hourly_emissions, and, in the lines kept verbatim, HOUREMIS, hourly BACKGRND files and INCLUDED files. A relative path is taken relative to the current directory. The run ID is computed from the factors and the SHA-256 of the binary and of these files (:func:run_id), so editing an emission file makes a new run.
  2. The run's directory is root/runs/<run ID>. The input files are linked into it and the deck names them by their bare names, and every output file name is rewritten to a bare name in the same directory (:func:rewrite_output_names), so no run can overwrite another's files. An INCLUDED file is linked as it is: the file names inside it are not rewritten.
  3. The deck is written there as run.inp and run with :class:~pyaermod.runner.AERMODRunner, n_workers at a time.

The manifest root/manifest.json gets an entry per run before any run starts, and each entry is updated (and the file saved) as its run finishes, so it always shows which runs have finished. manifest.csv beside it is written at the end. root/design.json lists this call's run IDs, in row order, before any run starts; the manifest keeps the runs of earlier calls too.

With resume=True (the default), a run is skipped when its manifest entry says it succeeded for the same deck text and input files, the deck on disk is that deck, its .out has AERMOD's success banner and a copy of that deck, and its PLOTFILEs, POSTFILEs and the debug files it wrote are all present. Any other run is made again: a run that failed or was cut off, one whose build_fn now writes a different deck, and one whose files were removed. Running the same design again after an interrupt therefore makes only the runs that had not finished.

Workers are processes. On macOS and Windows a script must call this function from under if __name__ == "__main__": (see :meth:~pyaermod.runner.AERMODRunner.run_batch). n_workers=1 runs every deck in this process, one after another.

Args: rows: the design: mappings of factor name to value, or a pandas DataFrame (one run per row). Factor values must be writable by :func:canonical_json; two rows with the same factors are an error. build_fn: called with a copy of each row's factors, returns the project for that run. root: directory for the design (created if needed). n_workers: number of runs at a time. executable: the AERMOD binary; by default, aermod on PATH. timeout: seconds allowed for each run. resume: skip runs the manifest shows as done (see above). With False every run is made again. validate: validate each project before writing its deck. progress: a :class:~pyaermod.runner_utils.ProgressReporter told about each finished run.

Returns: A :class:DesignResult: the runs keyed by run ID, in row order.

Raises: FileNotFoundError: a met file or other input file does not exist. ValueError: duplicate rows, an input file name longer than AERMOD's 200 characters, or input and output file names that collide in the run directory.

collect_plotfiles

collect_plotfiles(root: Union[str, Path], run_ids: Optional[Iterable[str]] = None, out_stem: Optional[Union[str, Path]] = 'plotfiles')

Read the PLOTFILEs of a design's successful runs into one tidy table.

One row per receptor of each PLOTFILE of each run whose manifest entry says success, among the runs of run_ids. By default those are the runs of the latest :func:run_design call on root (root/design.json), not every run the manifest holds: it keeps the runs of rows since dropped and of an earlier binary or met file too. Pass run_ids=manifest.entries for all of them. The columns are run_id, plotfile (its file name), receptor (the row's position in its file, from 0), then AERMOD's own columns in lower case with underscores: x, y, average_conc, total_depo, dry_depo, wet_depo, zelev, zhill, zflag, ave, grp, num_hrs, net_id, as the file has them. A column one file lacks is empty (NaN) in its rows. Factors are not repeated here; join on run_id with the manifest (:meth:EnsembleManifest.to_dataframe) or :class:DesignResult.

The files are read with :func:pyaermod.aermod_outputs.read_plotfile.

Unless out_stem is None, the table is also written as <out_stem>.csv and <out_stem>.npz (relative to root unless absolute). The .npz holds one array per column, strings as NumPy unicode arrays, so numpy.load(path) reads it without allow_pickle.

Raises: FileNotFoundError: a successful run's PLOTFILE is missing.