Skip to content

grat.reports

Turns GRAT model results into report dataframes.

expand

expand(names)

Returns the requested reports plus any report they are built from.

Parameters:

Name Type Description Default
names

report names the caller asked for.

required

Returns: frozenset of report names to produce

Raises:

Type Description
KeyError

a name is not a known report.

Source code in src/grat/reports/catalog.py
def expand(names):
    """Returns the requested reports plus any report they are built from.

    Args:
        names: report names the caller asked for.

    Returns: frozenset of report names to produce

    Raises:
        KeyError: a name is not a known report.
    """
    requested = frozenset(names)

    unknown = requested - ALL_REPORTS
    if unknown:
        raise KeyError(f"unknown reports: {sorted(unknown)}")

    for name, implied in IMPLIES.items():
        if name in requested:
            requested |= implied
    return requested

post_process

post_process(names, output_folder, produced=None)

Builds the reports that can only run once every water year is done.

Parameters:

Name Type Description Default
names

report names that were selected.

required
output_folder

path to the output folder.

required
produced

report names that report_picker produced.

None

dict of report name to result, holding the frontend series as json-ready

Type Description

dicts and the post-run csv reports as dataframes

Raises:

Type Description
KeyError

a name is not a known report.

Source code in src/grat/reports/selector.py
def post_process(names, output_folder, produced=None):
    """Builds the reports that can only run once every water year is done.

    Args:
        names: report names that were selected.
        output_folder: path to the output folder.
        produced: report names that report_picker  produced.

    Returns: dict of report name to result, holding the frontend series as json-ready
        dicts and the post-run csv reports as dataframes

    Raises:
        KeyError: a name is not a known report.
    """
    wanted = catalog.expand(names)
    if produced is not None:
        # report can be dropped by a missing model input
        guarded = (catalog.NEEDS_TRANSFERS | catalog.NEEDS_BOTTLENECKS) & catalog.PER_YEAR
        missing = guarded - set(produced)
        wanted -= missing
        wanted -= {name for name, sources in catalog.IMPLIES.items() if sources & missing}
    results = {}

    if wanted & catalog.NEEDS_ANNUAL_GROUPING:
        try:
            grouping_df = read_report(output_folder, "annual_recharge_by_grouping")
        except (OSError, pd.errors.EmptyDataError, pd.errors.ParserError):
            logger.exception("unable to read the annual recharge by grouping intermediate")
        else:
            for name, build in (
                ("annual_recharge_by_sw_and_gw", annual_recharge_by_sw_and_gw),
                ("annual_recharge_by_district_and_gw", annual_recharge_by_district_and_gw),
                ("annual_recharge_by_district_and_wafr", annual_recharge_by_district_and_wafr),
            ):
                if name in wanted:
                    results[name] = build(grouping_df)
                    write_report(results[name], output_folder, name)

    if wanted & catalog.NEEDS_MONTHLY:
        pivot = monthly_recharge_by_site_report_post(
            read_report(output_folder, "monthly_recharge_by_site_temp", dtype=MONTHLY_DTYPES),
            read_report(output_folder, "site_info", dtype=SITE_INFO_DTYPES),
        )

        if "monthly_recharge_by_site_report" in wanted:
            results["monthly_recharge_by_site_report"] = monthly_recharge_by_site_summary(pivot)
            write_report(results["monthly_recharge_by_site_report"], output_folder, "monthly_recharge_by_site_report")

        if "monthly_recharge_by_site_report_detailed" in wanted:
            results["monthly_recharge_by_site_report_detailed"] = pivot
            write_report(pivot, output_folder, "monthly_recharge_by_site_report_detailed")

    if "fields_repurposed" in wanted:
        results["fields_repurposed"] = mlrp_report(read_report(output_folder, "site_info"))
        write_report(results["fields_repurposed"], output_folder, "fields_repurposed")

    if "yearly_water_transfer_by_sustain_zone_report" in wanted:
        name = "yearly_water_transfer_by_sustain_zone_report"
        results[name] = yearly_water_transfer_by_sustain_zone_report(
            read_report(output_folder, "daily_water_transfer_by_sustain_zone_report")
        )
        write_report(results[name], output_folder, name)

    # the frontend series
    for name, source, build in (
        ("yearly_recharge_volumes", "annual_summary_recharge", post_process_viz_recharge_by_type),
        ("unused_wafr", "unused_and_orig_wafr", post_process_unused_wafr),
        ("max_wafr_per_site", "yearly_wafr_applied_by_site", post_process_max_per_site),
        ("recharge_by_sustainability_zone", "total_by_sustainability_zone", post_process_recharge_by_sustain_zone),
    ):
        if name in wanted:
            results[name] = build(read_report(output_folder, source))

    _remove_intermediates(output_folder)
    return results

report_picker

report_picker(
    names,
    output_folder,
    year,
    sites,
    year_raw_wafr,
    wafr,
    bottlenecks=None,
    transfer_list=None,
)

Generates the reports for a single year of results.

Parameters:

Name Type Description Default
names

report names to generate. Post-run names are accepted and used only to decide which intermediates this year must contribute to.

required
output_folder

folder to write into, or None to build the dataframes

required
year

the current year

required
sites

list of the sites objects

required
year_raw_wafr

the unmodified WAFR for this year

required
wafr

the end wafr after water has been applied to the sites

required
bottlenecks

list of bottlenecks, or None if the run has none

None
transfer_list

list of zones that can receive water from transfers

None

Returns: dict of report name to dataframe, for the reports produced this year

Raises:

Type Description
KeyError

a name is not a known report.

Source code in src/grat/reports/selector.py
def report_picker(
    names,
    output_folder,
    year,
    sites,
    year_raw_wafr,
    wafr,
    bottlenecks=None,
    transfer_list=None,
):
    """Generates the reports for a single year of results.

    Args:
        names: report names to generate. Post-run names are accepted and used only to
            decide which intermediates this year must contribute to.
        output_folder: folder to write into, or None to build the dataframes
        year: the current year
        sites: list of the sites objects
        year_raw_wafr: the unmodified WAFR for this year
        wafr: the end wafr after water has been applied to the sites
        bottlenecks: list of bottlenecks, or None if the run has none
        transfer_list: list of zones that can receive water from transfers

    Returns: dict of report name to dataframe, for the reports produced this year

    Raises:
        KeyError: a name is not a known report.
    """
    logger.info("Generating reports")
    wanted = catalog.expand(names)

    # run_grat logs these skips once per run
    if bottlenecks is None:
        wanted -= catalog.NEEDS_BOTTLENECKS

    if transfer_list is None:
        wanted -= catalog.NEEDS_TRANSFERS

    def publish(df, key, folder=output_folder):
        """Writes a report and records its frame."""
        if folder is not None:
            write_report(df, folder, key)
        if key in wanted:
            produced[key] = df

    produced = {}

    # Site attribution
    if wanted & catalog.NEEDS_SITE_INFO:
        site_info_df = get_site_info(sites)
        if output_folder is not None:
            write_report(site_info_df, output_folder, "site_info")

    if wanted & catalog.NEEDS_DAILY_SUMMARY:
        daily_summary_df = daily_summary_recharge(year, sites, year_raw_wafr, wafr)

        if "annual_summary_recharge" in wanted:
            publish(annual_summary_recharge(daily_summary_df), "annual_summary_recharge")

        if "daily_summary_recharge" in wanted:
            publish(daily_summary_recharge_report(daily_summary_df), "daily_summary_recharge")

    if wanted & catalog.NEEDS_SITE_VOLUME:
        site_volume_report_df = site_volume_report(year, sites)
        year_folder = None if output_folder is None else os.path.join(output_folder, f"{year}")
        if year_folder is not None and wanted & catalog.YEAR_SUBFOLDER:
            os.makedirs(year_folder, exist_ok=True)

        if "daily_wafr_applied_by_site" in wanted:
            publish(
                daily_wafr_applied_by_site(site_volume_report_df, site_info_df),
                "daily_wafr_applied_by_site",
                year_folder,
            )

        if "daily_recharge_by_site" in wanted:
            publish(
                daily_recharge_by_site(site_volume_report_df, site_info_df),
                "daily_recharge_by_site",
                year_folder,
            )

        if wanted & catalog.NEEDS_MONTHLY:
            # accumulated per year and pivoted after the run
            monthly_df = monthly_recharge_by_site_report(site_volume_report_df)
            if output_folder is not None:
                write_report(monthly_df, output_folder, "monthly_recharge_by_site_temp")

        if "daily_farm_recharge_report" in wanted:
            publish(daily_farm_recharge_report(site_volume_report_df, site_info_df), "daily_farm_recharge_report")

        if "yearly_aggregate_farm_recharge_report" in wanted:
            publish(
                yearly_aggregate_farm_recharge_report(site_volume_report_df, site_info_df),
                "yearly_aggregate_farm_recharge_report",
            )

        if "daily_recharge_by_gw_basin" in wanted:
            publish(daily_recharge_by_gw_basin(site_volume_report_df, site_info_df), "daily_recharge_by_gw_basin")

    if "daily_wafr_report" in wanted:
        publish(daily_wafr_report(year, wafr), "daily_wafr_report")

    if "bottlenecks_capacity_limitations_report" in wanted:
        publish(bottlenecks_capacity_limitations_report(year, bottlenecks), "bottlenecks_capacity_limitations_report")

    if "bottlenecks_daily_conveyance_limits_by_volume" in wanted:
        publish(
            bottlenecks_daily_conveyance_limits_by_volume(year, bottlenecks),
            "bottlenecks_daily_conveyance_limits_by_volume",
        )

    if "yearly_bottleneck_capacity_logger" in wanted:
        publish(yearly_bottleneck_capacity_logger(year, bottlenecks), "yearly_bottleneck_capacity_logger")

    if wanted & catalog.NEEDS_ANNUAL_GROUPING:
        # reports 15, 16 and 17 have a complicated header, so they are built after the run
        grouping_df = annual_recharge_by_grouping(year, sites)
        if grouping_df is not None and output_folder is not None:
            write_report(grouping_df, output_folder, "annual_recharge_by_grouping")

    if "acres_available_and_used" in wanted:
        publish(acres_available_and_used(year, sites), "acres_available_and_used")

    if "daily_water_transfer_by_sustain_zone_report" in wanted:
        publish(
            daily_water_transfer_by_sustain_zone_report(year, sites, transfer_list),
            "daily_water_transfer_by_sustain_zone_report",
        )

    # Intermediates for the frontend series.
    if wanted & catalog.NEEDS_UNUSED_WAFR and output_folder is not None:
        write_report(yearly_wafr_report(year, wafr, year_raw_wafr), output_folder, "unused_and_orig_wafr")

    if wanted & catalog.NEEDS_WAFR_BY_SITE and output_folder is not None:
        write_report(yearly_wafr_applied_by_site(year, sites), output_folder, "yearly_wafr_applied_by_site")

    if wanted & catalog.NEEDS_TOTAL_BY_ZONE and output_folder is not None:
        write_report(
            total_recharge_by_sustainability_zone_report(year, sites),
            output_folder,
            "total_by_sustainability_zone",
        )

    return produced

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)

write_report

write_report(df, output_folder, key)

Writes a dataframe to the file that REPORT_FILES gives for key.

Parameters:

Name Type Description Default
df

dataframe to write.

required
output_folder

folder the file is written into.

required
key

entry in REPORT_FILES, which supplies the filename and whether the report appends across water years.

required

Returns: path to the csv file that was written

Raises:

Type Description
KeyError

key is not a known report.

Source code in src/grat/reports/writers.py
def write_report(df, output_folder, key):
    """Writes a dataframe to the file that `REPORT_FILES` gives for `key`.

    Args:
        df: dataframe to write.
        output_folder: folder the file is written into.
        key: entry in `REPORT_FILES`, which supplies the filename and whether the
            report appends across water years.

    Returns: path to the csv file that was written

    Raises:
        KeyError: `key` is not a known report.
    """
    report_file = REPORT_FILES[key]
    return write_csv(df, output_folder, report_file.filename, append=report_file.append)