Skip to content

grat.reports.writers

Writes report dataframes to csv files, and manages the output folder.

ReportFile

Bases: NamedTuple

Where one report is written.

Attributes:

Name Type Description
filename str

basename written inside the run's output folder.

append bool

True when each water year appends to a single file, in which case the header is written only for the first year.

check_output_path_length

check_output_path_length(
    output_parent, max_length=WINDOWS_MAX_PATH
)

Fails early if the longest report path under output_parent would be too long.

Without this, the run gets as far as writing the first per-year report and then raises a FileNotFoundError that doesn't say why.

Parameters:

Name Type Description Default
output_parent

directory the timestamped results folder will be created in.

required
max_length

longest path allowed. Defaults to Windows' limit.

WINDOWS_MAX_PATH

Raises:

Type Description
ValueError

the longest report path would be over max_length.

Source code in src/grat/reports/writers.py
def check_output_path_length(output_parent, max_length=WINDOWS_MAX_PATH):
    """Fails early if the longest report path under `output_parent` would be too long.

    Without this, the run gets as far as writing the first per-year report and then
    raises a `FileNotFoundError` that doesn't say why.

    Args:
        output_parent: directory the timestamped results folder will be created in.
        max_length: longest path allowed. Defaults to Windows' limit.

    Raises:
        ValueError: the longest report path would be over `max_length`.
    """
    # same length as a real results folder and year subfolder
    results_folder = os.path.join(os.path.abspath(output_parent), "results_00000000000000")
    year_folder = os.path.join(results_folder, "0000")
    longest = max(
        (
            os.path.join(year_folder if key in YEAR_SUBFOLDER else results_folder, f.filename)
            for key, f in REPORT_FILES.items()
        ),
        key=len,
    )

    if len(longest) > max_length:
        raise ValueError(
            f"Report paths would be up to {len(longest)} characters, over the {max_length}-character limit "
            f"(e.g. {longest}). Use an output_parent at least {len(longest) - max_length} characters shorter."
        )

construct_output_folder_name

construct_output_folder_name(path_to_folder: str)

Creates a new unique folder using the current datetime to store the exported csv results.

Parameters:

Name Type Description Default
path_to_folder str

path to the output parent directory where the results folder will be created

required

Returns: path to the result folder that was just created

Source code in src/grat/reports/writers.py
def construct_output_folder_name(path_to_folder: str):
    """Creates a new unique folder using the current datetime to store the exported csv results.

    Args:
        path_to_folder: path to the output parent directory where the results folder will be created

    Returns: path to the result folder that was just created
    """
    timestamp = datetime.datetime.now().strftime("%Y%m%d%H%M%S")
    suffix = 0
    while True:
        name = f"results_{timestamp}" if suffix == 0 else f"results_{timestamp}_{suffix}"
        folder_name = os.path.join(path_to_folder, name)
        try:
            os.mkdir(folder_name)
        except FileExistsError:
            suffix += 1
        else:
            return folder_name

zip_output_folder

zip_output_folder(result_folder_path, custom_name=None)

Zips up the output folder as a zipfile.

Parameters:

Name Type Description Default
result_folder_path

path to zip up

required
custom_name

optional custom name for the zip file

None

Returns: path to the output zip file

Source code in src/grat/reports/writers.py
def zip_output_folder(result_folder_path, custom_name=None):
    """Zips up the output folder as a zipfile.

    Args:
        result_folder_path: path to zip up
        custom_name: optional custom name for the zip file

    Returns: path to the output zip file
    """
    parent_dir = os.path.dirname(result_folder_path)
    basename = os.path.basename(result_folder_path)

    if custom_name:
        basename = custom_name
    output_zip = os.path.join(parent_dir, basename)
    shutil.make_archive(output_zip, "zip", result_folder_path)
    return output_zip + ".zip"

write_csv

write_csv(df, output_folder, filename, *, append=False)

Writes a dataframe to a csv file inside the output folder.

Parameters:

Name Type Description Default
df

dataframe to write.

required
output_folder

folder the file is written into.

required
filename

basename of the output file.

required
append

when True, append to any existing file and write the header only if the file is not already there. Used by the reports that build up a row per water year.

False

Returns: path to the csv file that was written

Source code in src/grat/reports/writers.py
def write_csv(df, output_folder, filename, *, append=False):
    """Writes a dataframe to a csv file inside the output folder.

    Args:
        df: dataframe to write.
        output_folder: folder the file is written into.
        filename: basename of the output file.
        append: when True, append to any existing file and write the header only if
            the file is not already there. Used by the reports that build up a row
            per water year.

    Returns: path to the csv file that was written
    """
    out_file = os.path.join(output_folder, filename)

    if append:
        df.to_csv(out_file, index=False, mode="a", header=not os.path.exists(out_file))
    else:
        df.to_csv(out_file, index=False)

    return out_file

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)

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)