Skip to content

grat

GRAT - a groundwater recharge allocation model.

The model lives in grat.model; grat.model.engine.start_analysis runs it across a span of water years. grat.reports turns a run's results into report dataframes, and grat.reports.writers writes them to csv.

To run the model and produce reports in one call::

from grat import read_report, run_grat

result = run_grat(sites, wafr, bottlenecks, crop_calendar, precip,
                  reports=["annual_summary_recharge", "acres_available_and_used"])

result["zip_path"]    # the results archive
result["reports"]     # the report names that were produced

read_report(result["output_folder"], "annual_summary_recharge")

grat.reports.catalog.ALL_REPORTS lists everything that can be asked for.

Before running, check your own input data for problems with grat.validation::

from grat.validation import validate_grat_inputs

report = validate_grat_inputs(sites, wafr, crop_calendar=crop_calendar)
report  # prints a summary in a notebook cell

read_report

read_report(output_folder, key, year=None, dtype=None)

Reads a report back from the folder it was written into.

Parameters:

Name Type Description Default
output_folder

the run's output folder.

required
key

entry in REPORT_FILES.

required
year

water year, for the reports written into a per-year subfolder.

None
dtype

optional column types, passed through to pandas.read_csv. The reports that are read back and re-pivoted need the types the csv threw away.

None

Returns: the report as a dataframe

Raises:

Type Description
KeyError

key is not a known report.

FileNotFoundError

that report is not in output_folder.

Source code in src/grat/reports/writers.py
def read_report(output_folder, key, year=None, dtype=None):
    """Reads a report back from the folder it was written into.

    Args:
        output_folder: the run's output folder.
        key: entry in `REPORT_FILES`.
        year: water year, for the reports written into a per-year subfolder.
        dtype: optional column types, passed through to `pandas.read_csv`. The
            reports that are read back and re-pivoted need the types the csv threw away.

    Returns: the report as a dataframe

    Raises:
        KeyError: `key` is not a known report.
        FileNotFoundError: that report is not in `output_folder`.
    """
    folder = output_folder if year is None else os.path.join(output_folder, str(year))
    return pd.read_csv(os.path.join(folder, REPORT_FILES[key].filename), dtype=dtype)

run_grat

run_grat(
    raw_sites,
    raw_wafr,
    raw_bottlenecks,
    crop_calendar,
    precip,
    *,
    reports=ALL_REPORTS,
    output_parent=".",
    zip_output=True,
    zip_name=None,
    **model_kwargs,
)

Runs the model across every water year and produces the requested reports.

Parameters:

Name Type Description Default
raw_sites

every canal, basin and farm, in processing order.

required
raw_wafr

water available for recharge, indexed as [year][source][day].

required
raw_bottlenecks

the bottlenecks restricting delivery, or None.

required
crop_calendar

accepted application rate, indexed as [crop][soil_type][day].

required
precip

precipitation, indexed as [year][precip_grid][day].

required
reports

report names to produce. Defaults to everything in the catalog; pass a smaller list and only the intermediates those reports need are built.

ALL_REPORTS
output_parent

directory to create the timestamped results folder in.

'.'
zip_output

zip the results folder when the run finishes.

True
zip_name

name for the zip, defaulting to the results folder's name.

None
**model_kwargs

passed through to start_analysis - years, crop_calendar_in_lieu, use_in_lieu, use_ofr, rma_sort, transfer_goals.

{}

Returns:

Type Description

A dict with four keys:

  • "output_folder": where the csv files were written. Pass it to read_report to get any of them back as a dataframe.
  • "zip_path": the zip archive, or None when zip_output was False.
  • "reports": sorted names of the reports produced. A report whose model input was missing - no bottlenecks, no transfer list - is absent.
  • "series": the frontend visualisation data, keyed by series name.

Raises:

Type Description
KeyError

a report name is not in the catalog.

ValueError

on Windows, output_parent is too long for the report paths.

Source code in src/grat/run.py
def run_grat(
    raw_sites,
    raw_wafr,
    raw_bottlenecks,
    crop_calendar,
    precip,
    *,
    reports=catalog.ALL_REPORTS,
    output_parent=".",
    zip_output=True,
    zip_name=None,
    **model_kwargs,
):
    """Runs the model across every water year and produces the requested reports.

    Args:
        raw_sites: every canal, basin and farm, in processing order.
        raw_wafr: water available for recharge, indexed as `[year][source][day]`.
        raw_bottlenecks: the bottlenecks restricting delivery, or None.
        crop_calendar: accepted application rate, indexed as `[crop][soil_type][day]`.
        precip: precipitation, indexed as `[year][precip_grid][day]`.
        reports: report names to produce. Defaults to everything in the catalog; pass a
            smaller list and only the intermediates those reports need are built.
        output_parent: directory to create the timestamped results folder in.
        zip_output: zip the results folder when the run finishes.
        zip_name: name for the zip, defaulting to the results folder's name.
        **model_kwargs: passed through to `start_analysis` - `years`,
            `crop_calendar_in_lieu`, `use_in_lieu`, `use_ofr`, `rma_sort`,
            `transfer_goals`.

    Returns:
        A dict with four keys:

        - `"output_folder"`: where the csv files were written. Pass it to `read_report`
            to get any of them back as a dataframe.
        - `"zip_path"`: the zip archive, or None when `zip_output` was False.
        - `"reports"`: sorted names of the reports produced. A report whose model input
            was missing - no bottlenecks, no transfer list - is absent.
        - `"series"`: the frontend visualisation data, keyed by series name.

    Raises:
        KeyError: a report name is not in the catalog.
        ValueError: on Windows, `output_parent` is too long for the report paths.
    """
    names = catalog.expand(reports)

    # report_picker skips these every year; say so once here
    skipped = names & catalog.NEEDS_BOTTLENECKS if raw_bottlenecks is None else set()
    if skipped:
        logger.info("No bottlenecks provided, skipping %s", ", ".join(sorted(skipped)))
    skipped = names & catalog.NEEDS_TRANSFERS if not model_kwargs.get("transfer_goals") else set()
    if skipped:
        logger.warning("No transfer list provided, skipping %s", ", ".join(sorted(skipped)))

    if os.name == "nt":
        check_output_path_length(output_parent)
    output_folder = construct_output_folder_name(output_parent)
    logger.info("Writing reports to %s", output_folder)

    produced = set()

    def build_this_years_reports(year, sites, raw_wafr, wafr, bottlenecks, transfer_limits):
        """Builds one water year's reports, called as the model finishes each year."""
        built = report_picker(
            names,
            output_folder,
            year,
            sites,
            raw_wafr,
            wafr,
            bottlenecks,
            transfer_list=_transfer_zones(transfer_limits),
        )
        produced.update(built)

    start_analysis(
        raw_sites,
        raw_wafr,
        raw_bottlenecks,
        crop_calendar,
        precip,
        on_year=build_this_years_reports,
        **model_kwargs,
    )

    results = post_process(names, output_folder, produced)
    produced.update(name for name in results if name in catalog.CSV_REPORTS)

    return {
        "output_folder": output_folder,
        "zip_path": zip_output_folder(output_folder, zip_name) if zip_output else None,
        "reports": sorted(produced),
        "series": {name: value for name, value in results.items() if name in catalog.FRONTEND_SERIES},
    }

validate_grat_inputs

validate_grat_inputs(
    sites,
    wafr,
    *,
    bottleneck_rows=None,
    crop_calendar=None,
    crop_calendar_in_lieu=None,
    precip=None,
)

Runs every check that applies to the inputs provided, and returns the combined report.

Call this with whatever you've already loaded - only sites and wafr are required, matching what build_sites and run_grat need at a minimum. Nothing passed in is modified.

Parameters:

Name Type Description Default
sites

list of site attribute dictionaries, as returned by load_sites.

required
wafr

dictionary of {year: {source: [daily values]}}, as returned by load_wafr.

required
bottleneck_rows

raw bottleneck rows (before load_bottlenecks builds objects), e.g. pandas.read_csv(path).to_dict("records").

None
crop_calendar

on-farm crop compatibility calendar, as returned by get_crop_calendar.

None
crop_calendar_in_lieu

in-lieu crop compatibility calendar, as returned by get_il_crop_calendar.

None
precip

dictionary of {year: {grid: [daily values]}}, as returned by get_precip.

None

Returns:

Type Description

ValidationReport. Prints as a readable summary in a notebook cell; report.ok

is True when no errors were found, and report.errors / report.warnings give

the issues found at each level.

Source code in src/grat/validation.py
def validate_grat_inputs(
    sites,
    wafr,
    *,
    bottleneck_rows=None,
    crop_calendar=None,
    crop_calendar_in_lieu=None,
    precip=None,
):
    """Runs every check that applies to the inputs provided, and returns the combined report.

    Call this with whatever you've already loaded - only `sites` and `wafr` are
    required, matching what `build_sites` and `run_grat` need at a minimum. Nothing
    passed in is modified.

    Args:
        sites: list of site attribute dictionaries, as returned by `load_sites`.
        wafr: dictionary of `{year: {source: [daily values]}}`, as returned by `load_wafr`.
        bottleneck_rows: raw bottleneck rows (before `load_bottlenecks` builds objects),
            e.g. `pandas.read_csv(path).to_dict("records")`.
        crop_calendar: on-farm crop compatibility calendar, as returned by `get_crop_calendar`.
        crop_calendar_in_lieu: in-lieu crop compatibility calendar, as returned by `get_il_crop_calendar`.
        precip: dictionary of `{year: {grid: [daily values]}}`, as returned by `get_precip`.

    Returns:
        `ValidationReport`. Prints as a readable summary in a notebook cell; `report.ok`
        is True when no errors were found, and `report.errors` / `report.warnings` give
        the issues found at each level.
    """
    report = ValidationReport()

    # materialize once - an iterator/generator would otherwise be exhausted building
    # known_bottleneck_ids below, leaving nothing for check_bottlenecks to see.
    if bottleneck_rows is not None:
        bottleneck_rows = list(bottleneck_rows)

    valid_crops = ccc_valid_crops(crop_calendar) if crop_calendar else None
    valid_soil_types = ccc_valid_soil_types(crop_calendar) if crop_calendar else None
    valid_il_crops = ccc_valid_crops(crop_calendar_in_lieu) if crop_calendar_in_lieu else None

    known_wafr_sources = {src for by_source in wafr.values() for src in by_source} if wafr else None
    known_precip_grids = {grid for by_grid in precip.values() for grid in by_grid} if precip else None
    known_bottleneck_ids = {row["bid"] for row in bottleneck_rows if "bid" in row} if bottleneck_rows else None

    check_sites(
        report,
        sites,
        known_wafr_sources=known_wafr_sources,
        known_bottleneck_ids=known_bottleneck_ids,
        known_precip_grids=known_precip_grids,
        valid_crops=valid_crops,
        valid_il_crops=valid_il_crops,
        valid_soil_types=valid_soil_types,
        crop_calendar=crop_calendar,
        crop_calendar_in_lieu=crop_calendar_in_lieu,
    )
    check_wafr(report, wafr)

    if precip is not None:
        check_precip(report, precip)
    if bottleneck_rows is not None:
        check_bottlenecks(report, bottleneck_rows)
    if crop_calendar is not None:
        check_crop_calendar(report, crop_calendar, source="on-farm crop calendar")
    if crop_calendar_in_lieu is not None:
        check_crop_calendar(report, crop_calendar_in_lieu, source="in-lieu crop calendar")

    return report