Skip to content

gui_v2

gui_v2

PyAERMOD GUI v2 — the NiceGUI app.

It replaced the Streamlit GUI, which was removed in v2.0. NiceGUI gives us:

  • No rerun-on-keystroke model — real reactive state binding
  • Real components: AG-Grid tables, Leaflet maps, Plotly plots
  • A Python-only dev model
  • Optional native desktop window via :mod:pyaermod.gui_v2.desktop (pywebview wrapper) — single codebase, two delivery modes
Entry points
  • pyaermod-app — :func:pyaermod.gui_v2.main: serves the app and opens it in a browser tab. --host, --port and --no-browser change where it listens and whether a tab opens (a container binds 0.0.0.0 and opens none). Needs the [gui] extra. pyaermod gui and python -m pyaermod.gui_v2 are the same command.
  • pyaermod-desktop — :func:pyaermod.gui_v2.desktop.main: the same app inside a pywebview window. Needs the [gui-desktop] extra.

Without the packages of its extra, either command stops with one line that names what to install (:func:_missing_dependency).

Both serve the app with :func:pyaermod.gui_v2.app.build_and_run.

Module layout::

gui_v2/
  __init__.py        -- entry point ``main()``
  __main__.py        -- ``python -m pyaermod.gui_v2``
  session.py         -- Session: the project, its runs and change events (no UI)
  state.py           -- _empty_project(), the blank project
  project_io.py      -- JSON save/load for AERMODProject
  app.py             -- top-level shell (tabs, header, one session per tab)
  _live.py           -- live(): page sections rebuilt from the session
  _form.py           -- dataclass field -> widget helper
  _native.py         -- the desktop window, for native dialogs
  run_results.py     -- what Results shows about a run, from its files (no UI)
  results_map.py     -- the Results step's concentration map (matplotlib Agg)
  desktop.py         -- pywebview wrapper (``pyaermod-desktop``)
  pages/
    project.py       -- file menu + project metadata
    sources.py       -- source editor
    receptors.py     -- receptor editor
    meteorology.py   -- AERMET / met-file pathway
    output.py        -- output pathway + chemistry
    run.py           -- AERMOD invocation and the last run's status
    results.py       -- a run's results, downloads and the run history

The shell resolves each browser tab's :class:~pyaermod.gui_v2.session.Session and passes it to every page; pages rebuild from it through :func:pyaermod.gui_v2._live.live.

main

main(argv: Optional[Sequence[str]] = None) -> None

Launch the NiceGUI application (the pyaermod-app command).

argv is the command line without the program name; None reads sys.argv. Run pyaermod-app --help for the options.

Importing :mod:nicegui is deferred to call-time so that import pyaermod doesn't pay the NiceGUI import cost when the GUI isn't being used.

Session

session

The GUI's session: the project under edit, its runs, and change events.

A :class:Session is everything one browser tab of the GUI works on: the :class:~pyaermod.input_generator.AERMODProject, the file it came from, the unsaved-changes flag, the latest validation result and the history of AERMOD runs. Every user operation is a method (:meth:Session.new, :meth:Session.open_json, :meth:Session.add_source, :meth:Session.start_run, ...), and each one tells its observers what changed by emitting a :class:Change.

The pages of the GUI never keep a reference to a part of the project across a :attr:SessionEvent.PROJECT_REPLACED event: they subscribe to the events that concern them and rebuild from the session (see :mod:pyaermod.gui_v2._live). This module imports nothing from NiceGUI, so every operation can be tested without a UI.

Session is a plain class compared by identity, never a dataclass: the NiceGUI refreshables and observer lists that hang off a session must not mistake two tabs whose sessions happen to hold equal values for one.

DeckImport dataclass

What :meth:Session.import_inp brought in, for the notice the GUI shows.

path is the deck's file on this computer, or None for an upload. unparsed holds the lines the reader kept as written (:attr:AERMODProject.unparsed_lines). met_found names the met file fields whose relative path was found beside the deck and is now a full path; met_needed lists (field, path as written) for each met file the user still has to point at. The deck's other input files (ozone and NOx files, INCLUDED, HOUREMIS ...; see :func:~pyaermod.input_reader.input_files) are listed as (keyword, path as written): inputs_found for those found beside the deck, now full paths, and inputs_missing for those that are not a file on this computer as the project names them.

DeckImportError

Bases: ValueError

:meth:Session.import_inp could not import the deck.

The message starts with the deck's name and says why, in words meant for the user; nothing in the session has changed.

SessionEvent

Bases: StrEnum

What changed in a :class:Session.

RunRecord dataclass

One AERMOD run started from the session.

work_dir is kept exactly as the user gave it (never resolved), so the GUI shows the directory the user typed.

status property

status: str

"Running", "Succeeded", "Cancelled" or "Failed".

fraction_done property

fraction_done: Optional[float]

Days processed over the days of met data, in [0, 1]; None if unknown.

Change dataclass

One change event: what happened, and to which part or run.

RunOptions dataclass

The Run step's inputs. Not part of the project, and not saved with it.

MetCoverage dataclass

The surface file a run would read, as :meth:Session.met_coverage finds it.

path is the file resolved as AERMOD will open it (None when none is set, or when AERMOD would not find it: a relative path with a blank working directory, or one starting with ~); period what it holds and problem why it could not be read (see :meth:Session.met_period); warnings the :func:~pyaermod.validator_advanced.check_annual_met_coverage finding (ANNUAL with less than a year of data, which AERMOD aborts with E480).

ProjectFileError

Bases: ValueError

:meth:Session.open_json could not read the project file.

DeckError

Bases: ValueError

The project could not be written as an AERMOD deck.

RunInProgressError

Bases: RuntimeError

:meth:Session.start_run was called while a run is in progress.

Session

Everything one GUI tab works on, and the operations on it.

Attributes:

Name Type Description
project AERMODProject

The project under edit.

project_path Optional[Path]

A file on the server's disk that :meth:save writes to. Set by :meth:open_json with a path and by :meth:save_as (desktop mode).

file_name Optional[str]

The file name the header shows. Every open or save that knows a name sets it, including a browser download.

dirty bool

True while the project has changes that were not saved.

validation Optional[ValidationResult]

The result of the latest :meth:validate, or None.

runs List[RunRecord]

Every finished run of this session, oldest first.

run_in_progress Optional[RunRecord]

The run :meth:start_run is executing, or None.

run_options

The Run step's inputs.

last_import Optional[DeckImport]

What the latest :meth:import_inp brought in, until the project is replaced again; the header names the deck while the project has no file of its own.

show_import_notice bool

Whether the Project step still shows the import notice (the user can dismiss it).

tab_id Optional[str]

Which browser tab owns this session. The GUI shell reads and writes it; the session never interprets it.

dispatch Callable[[Callable[[], object]], Any]

How a background run's events reach the session's owner: dispatch(callback) must arrange for callback() to run on the thread that owns the session. The GUI passes its event loop's call_soon_threadsafe; the default calls at once, on the run's own thread (fine for scripts and tests that only wait).

last_run property

last_run: Optional[RunRecord]

The newest finished run, including one whose runner raised.

last_completed_run property

last_completed_run: Optional[RunRecord]

The newest run AERMOD actually completed (it has a result and was not cancelled).

title property

title: str

The header text: the file name, and whether it has unsaved changes.

source_entries

source_entries() -> List[Tuple[str, Any]]

(key, source) for every source, in the project's order.

receptor_entries

receptor_entries() -> List[Tuple[str, str, Any]]

(key, kind, receptor) over Cartesian grids, polar grids, discrete.

subscribe

subscribe(events: Union[SessionEvent, Iterable[SessionEvent]], callback: Observer) -> Callable[[], None]

Call callback(change) for each of events; return an unsubscribe.

The returned function may be called any number of times.

new

new() -> None

Discard the project and start from the blank one.

open_json

open_json(source: Union[str, bytes, Path], *, name: Optional[str] = None) -> None

Replace the project with one read from a file or its text.

A :class:~pathlib.Path is read from the server's disk and becomes :attr:project_path; text or bytes (an upload) sets only :attr:file_name, to name. Nothing changes if the file cannot be read: :class:ProjectFileError says why.

import_inp

import_inp(source: Union[str, bytes, Path], *, name: Optional[str] = None) -> DeckImport

Replace the project with one read from an AERMOD .inp deck.

source is a :class:~pathlib.Path (a deck on this computer) or an upload's text or bytes, shown under name; see :func:~pyaermod.gui_v2.deck_import.read_deck for how each is read.

The project has no file of its own afterwards and counts as modified. Raises :class:DeckImportError, with nothing changed, when the deck cannot be imported. Returns what came in, which is also kept as :attr:last_import.

save

save() -> Path

Write the project to :attr:project_path and mark it saved.

Every save method raises :class:ValueError (nothing written, the project stays dirty) when the project holds a value the file could not be reopened with; see :func:~.project_io.project_to_json.

save_as

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

Write the project to path (desktop mode) and remember it.

save_as_download

save_as_download(file_name: Optional[str]) -> bytes

The project file's bytes, to deliver as a browser download.

Writes nothing to disk. The cleaned name (:func:clean_file_name) becomes :attr:file_name, and :attr:project_path is cleared: the browser decides where the file goes.

add_source

add_source(src: Any) -> str

Append src and return its key. Duplicate source_id is allowed.

update_source

update_source(key: str, src: Any) -> bool

Replace the source that has key; False if it no longer exists.

delete_source

delete_source(key: str) -> Optional[Any]

Remove and return the source that has key; None if it is gone.

add_receptor

add_receptor(rec: Any) -> str

Append rec to the list for its type and return its key.

update_receptor

update_receptor(key: str, rec: Any) -> bool

Replace the receptor that has key with one of the same type.

delete_receptor

delete_receptor(key: str) -> Optional[Any]

Remove and return the receptor that has key; None if it is gone.

set_control

set_control(**fields: Any) -> None

Set fields of the project's ControlPathway (titles, pollutant, ...).

mark_edited

mark_edited(part: str) -> None

Record an edit a widget made in place (Meteorology, Output).

validate

validate(check_files: bool = False) -> ValidationResult

Validate the project, keep the result and emit VALIDATION_CHANGED.

With check_files the result is the one the Review & Run step reviews (:func:~pyaermod.gui_v2.readiness.project_findings): the met files are looked for where AERMOD will open them (a relative path in :attr:run_options' working directory), and the surface file is read for the warning that ANNUAL needs a year of met data and for the station IDs and year in its header. So the header's readiness line, the step badges and the checklist agree.

changed_since

changed_since(record: RunRecord) -> bool

Whether the deck the project writes now differs from record's.

False when the record does not know its deck (made by hand); True when the project cannot be written as a deck at the moment. Emits nothing.

deck_text

deck_text() -> str

The AERMOD deck :meth:start_run would write for the project.

Written from the project as a file would reopen it: a value the loader refuses is refused here by name, and whole numbers the number boxes stored as floats are integers again. Raises :class:DeckError when the project cannot be written as a deck. Emits nothing, so a page section may call it.

met_period

met_period(base_dir: Union[str, Path, None] = None) -> Tuple[Optional[Path], Optional[SurfaceFilePeriod], Optional[str]]

The surface file, the period it covers, and why it could not be read.

(path, period, problem): path is the surface file resolved against base_dir (None when none is set), period the :class:~pyaermod.aermet.SurfaceFilePeriod it holds, and problem a sentence saying why it could not be read (then period is None). Reads are cached by the file's mtime. Emits nothing.

met_coverage

met_coverage() -> MetCoverage

The surface file the next run would read, what it holds, and the ANNUAL warning (see :class:MetCoverage). Emits nothing.

The file is resolved against :attr:run_options' working directory. With a blank one the run goes to a new, empty folder, so a relative surface file is not read from the server's own directory; nor is one starting with ~, which AERMOD does not expand. Review & Run blocks both (run.RELATIVE_MET, run.HOME_MET).

start_run

start_run(*, working_dir: Union[str, Path, None] = None, timeout: int = 600, runner: Optional[AERMODRunner] = None, background: bool = False) -> RunRecord

Write the deck, run AERMOD on it, and record the run.

Raises :class:RunInProgressError while another run is in progress (nothing written, nothing emitted), :class:DeckError (nothing recorded, nothing emitted) when the project cannot be written as a deck (see :meth:deck_text), and OSError when the deck cannot be written to the working directory. Anything the runner raises, including a missing binary, is kept on the record as error.

With background=False the run is synchronous: RUN_STARTED, then RUN_FINISHED, and the finished record is returned.

With background=True AERMOD runs through :meth:AERMODRunner.start <pyaermod.runner.AERMODRunner.start> and this returns the record in progress (:attr:run_in_progress) after RUN_STARTED. RUN_PROGRESS follows for each day AERMOD reports (a burst is coalesced into one event), then RUN_FINISHED, all delivered through :attr:dispatch. :meth:cancel_run stops it. A runner that cannot be built or started finishes the run at once, as a synchronous run would.

cancel_run

cancel_run() -> bool

Stop the background run in progress.

Returns True when a cancel was sent: RUN_FINISHED follows once AERMOD has exited, with a record whose status is "Cancelled". False when nothing is running, the run was already cancelled, or the run is synchronous (it cannot be interrupted).

fork

fork(tab_id: Optional[str]) -> Session

An independent copy for another tab: same content and runs, no observers.

A run in progress is shared: the fork shows its progress, can cancel it and records its end too (a desktop window's reload arrives as a fork while the old page lingers, and must not lose the run).

run_deck_name

run_deck_name(number: int, extra: int = 0) -> str

pyaermod_gui_run3.inp; pyaermod_gui_run3_2.inp for extra=2.

read_met_period

read_met_period(path: Path) -> SurfaceFilePeriod

:func:~pyaermod.aermet.read_surface_period, cached by path and mtime.

Raises what it raises (OSError, ValueError).

remove_temp_run_dirs

remove_temp_run_dirs() -> None

Remove every temporary run directory a session of this process made.

For when the app exits (after its runs have been stopped): a run with a blank working directory goes to a folder of its own under the system's temporary folder, which nothing else removes.

clean_file_name

clean_file_name(name: Optional[str]) -> str

The file name a download is offered under.

Any directory part is dropped (POSIX or Windows spelling), characters a browser would rewrite ("*:<>?| and control characters) become _ so the header names the file the browser saved, an empty name becomes project.json and a name without a .json suffix gets one.

Project I/O

project_io

JSON save/load for the project a GUI v2 :class:~pyaermod.gui_v2.session.Session edits.

UI-framework-agnostic and headless: it needs only the core package, so scripts can read and write the GUI's project files without the [gui] extra. It replaced ProjectSerializer of the Streamlit GUI (pyaermod.gui), which was removed in v2.0.

Format

Top-level JSON dict::

{
  "pyaermod_version": "1.9.0",
  "save_format_version": 1,
  "project": <AERMODProject as a tree of JSON objects>
}

Every dataclass is a JSON object of its fields plus a _type tag naming its class, so a list of sources (or a field holding a subclass) reads back as the right class. Enums are {"_enum": "EnumClass.MEMBER"}; tuples, ranges and anything with a tolist() (numpy arrays, pandas Series, Index and Categorical: a background profile may be any of them) are lists, numpy scalars plain numbers (a one-shot iterator, such as a map or a generator, is refused with a :class:TypeError asking for a list); and a dict whose keys are not all strings is {"_items": [[key, value], ...]}.

Reading is driven by the dataclass annotations, not by the file: each value is checked against the type of the field it fills and nested dataclasses are rebuilt, so a file that loads is one the GUI and the deck writer can use. A value of the wrong type, an unknown _type or enum member, a number that is NaN or infinite, a whole number beyond +-2**53 (the browser cannot carry it), a fraction in an integer field, or a missing required field refuses the file with a :class:ValueError that names the file and the field. An integer field written as a whole float (2020.0, as the GUI's number boxes store it) reads as the integer. Saving applies the same checks and repairs before anything is written, so pyaermod never writes a file it would refuse to open. Files written before the _type tags covered nested objects still load: an untagged object is built as the field's own class. Unknown keys are ignored.

type_hints

type_hints(cls: type) -> Dict[str, Any]

Resolved field types of dataclass cls (the forms read them too).

check_project

check_project(project: AERMODProject, *, origin: str = 'the project') -> AERMODProject

Return a copy of project as :func:project_from_json would read it.

The copy has every value checked against its field's type and repaired where the loader repairs it (2020.0 in an integer field becomes 2020). Raises :class:ValueError starting with origin and naming the field when the loader would refuse a value, and :class:TypeError for a value no project file can hold.

project_to_json

project_to_json(project: AERMODProject) -> str

Return project as the JSON text :func:save_project writes.

The project is written as :func:check_project reads it, so a file that cannot be opened again is never produced: :class:ValueError names the field holding a value :func:project_from_json would refuse (a missing number, text in a list of objects, NaN ...), and :class:TypeError means a value no project file can hold.

save_project

save_project(project: AERMODProject, path: Union[str, Path]) -> Path

Write project to path as JSON. Returns the path.

Nothing is created when :func:project_to_json refuses the project. The file is written beside path and then moved over it, so a failed write leaves any earlier file at path whole.

project_from_json

project_from_json(text: Union[str, bytes], *, origin: str = '<text>') -> AERMODProject

Read an AERMODProject from JSON text written by :func:project_to_json.

Tolerates older save formats by reading what's there and filling missing fields with dataclass defaults. Every problem with the text itself -- not UTF-8, invalid JSON, a document of the wrong shape, a value of the wrong type, a newer save format -- raises :class:ValueError whose message starts with origin (a file name, or "<text>").

load_project

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

Read an AERMODProject from a JSON file written by :func:save_project.

Desktop wrapper

desktop

pywebview wrapper for the NiceGUI app.

Runs the NiceGUI server on the loopback in a background thread, then opens a native OS window pointed at the local URL. Single codebase, two delivery modes:

  • pyaermod-app — browser tab (opens default browser)
  • pyaermod-desktop — native OS window (this module)

Requires the [gui-desktop] extra (pywebview). Linux also needs one of pywebview's backends (GTK or Qt); see docs/desktop.md.

main

main(*, title: str = 'PyAERMOD', width: int = 1280, height: int = 800, port: Optional[int] = None) -> None

Launch NiceGUI in a background thread and open a pywebview window.