Metadata-Version: 2.4
Name: flowfreq
Version: 0.27.1
Summary: Python library for hydrologic analysis with Bulletin 17C flood frequency
Author: pinhead001
License-Expression: MIT
Project-URL: Homepage, https://github.com/pinhead001/flowfreq
Project-URL: Repository, https://github.com/pinhead001/flowfreq
Project-URL: Changelog, https://github.com/pinhead001/flowfreq/blob/main/CHANGELOG.md
Project-URL: Issues, https://github.com/pinhead001/flowfreq/issues
Keywords: hydrology,flood-frequency,bulletin-17c,usgs,streamflow
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Science/Research
Classifier: Topic :: Scientific/Engineering :: Hydrology
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Requires-Python: >=3.11
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: numpy>=1.23.2
Requires-Dist: pandas>=1.5.0
Requires-Dist: matplotlib>=3.6.1
Requires-Dist: scipy>=1.9.2
Requires-Dist: requests>=2.33.0
Requires-Dist: click>=8.0
Requires-Dist: pyarrow>=14.0.1
Requires-Dist: mpmath>=1.2
Provides-Extra: dev
Requires-Dist: pytest<10,>=9.0.3; extra == "dev"
Requires-Dist: pytest-cov<8,>=5.0; extra == "dev"
Requires-Dist: black<27,>=24.0; extra == "dev"
Requires-Dist: isort<10,>=5.12; extra == "dev"
Requires-Dist: mypy>=1.8; extra == "dev"
Requires-Dist: pandas-stubs; extra == "dev"
Requires-Dist: types-requests; extra == "dev"
Requires-Dist: filelock<5,>=3.13; extra == "dev"
Requires-Dist: python-docx<2,>=1.1; extra == "dev"
Requires-Dist: mcp<3,>=2.3; extra == "dev"
Provides-Extra: report
Requires-Dist: python-docx<2,>=1.1; extra == "report"
Provides-Extra: mcp
Requires-Dist: mcp<3,>=2.3; extra == "mcp"
Requires-Dist: python-docx<2,>=1.1; extra == "mcp"
Provides-Extra: study
Requires-Dist: rasterio<2,>=1.3; extra == "study"
Dynamic: license-file

# FlowFreq

A Python library for USGS streamflow data retrieval and Bulletin 17C flood frequency analysis.

The Streamlit web application that used to live here is now a separate project:
[pinhead001/flowfreq-app](https://github.com/pinhead001/flowfreq-app), which depends
on this library.

## Features

- **USGS Data Retrieval** — Download mean daily flow, annual peak flow, and
  instantaneous (unit-value, sub-daily) flow and stage for any gage, from the USGS Water
  Data OGC API by default (`backend="nwis-legacy"` for the legacy NWIS services). NWIS peak
  qualification codes are applied as peakfq 8.1.0 applies them
- **PeakFQ inputs** — Read PeakFQ `.psf` specification files and WATSTORE peak files, and
  run them as Bulletin 17C analyses
- **Bulletin 17C Analysis**
  - Expected Moments Algorithm (EMA) — the current USGS standard method
  - Method of Moments (MOM) fallback
  - Weighted regional skew (MSE weighting per B17C Appendix 6)
  - Multiple Grubbs-Beck test (MGBT) for low outlier detection
  - 90% confidence intervals (5%/95% limits)
  - Station / weighted / regional skew comparison
  - Regional skew lookup by site or location (`flowfreq.regional_skew`): a row for all 56
    jurisdictions, 34 verified against the cited USGS report, with a state-level fallback
    where a state has one usable row (see Coverage below)
  - Native engine, or the vendored USGS peakfq 8.1.0 Fortran as a selectable engine
- **Regional regression** — Offline USGS peak-flow regression equations with prediction
  intervals (`flowfreq.regression`) for 51 of the 56 jurisdictions in three tiers (see
  Coverage below). Also StreamStats delineation, basin characteristics and NSS estimates
  (`flowfreq.streamstats`)
- **Ungaged-site estimates** — `estimate_at_site` / `flowfreq ungaged`: delineate the basin,
  locate the NSS regression regions, evaluate the offline equations and report the
  estimate with its provenance (see Ungaged sites below). Where StreamStats can't delineate
  (Florida, Michigan, Nebraska), `estimate_from_characteristics` / `flowfreq ungaged-chars`
  take the region and basin characteristics from the caller
- **Transposition** — Drainage-area-ratio transfer to ungaged sites, QPPQ daily-series
  transfer, and donor screening by basin similarity
- **Low-Flow Frequency Analysis** — Annual minimum *n*-day mean flow (7Q10-style
  statistics), climatic/water/calendar year definitions, LP3 or lognormal
  fit, zero-flow-year handling, analytic and bootstrap confidence intervals
- **Flow Regime Metrics** — Richards-Baker flashiness index, TQmean, baseflow
  separation (UKIH, Lyne-Hollick, and three HYSEP variants), monthly/seasonal
  flow summaries
- **Diel (Sub-Daily) Variation** — Within-day flow range/CV from instantaneous
  data, with timezone-correct local-day grouping
- **Flow Series I/O** — Parquet-backed save/load for daily or instantaneous
  flow series (`flowfreq.flowio`)
- **Hydrograph Plotting** — Daily time series, summary hydrograph, flow duration curve
- **Frequency Curve** — Log-probability axis, LP3 fitted curve, CI band, multi-skew overlay
- **CLI** — `flowfreq validate` and `flowfreq benchmark` for numerical validation;
  `flowfreq compare` to run both engines on a peak CSV
- **Reports** — `flowfreq.reporting` / `flowfreq report`: a Word or Markdown report built from
  a JSON specification, every table and figure computed from the inputs it records (see
  Reports below)

## Installation

```bash
# Clone or download
git clone https://github.com/pinhead001/flowfreq.git
cd flowfreq

# Create and activate virtual environment (recommended)
python -m venv .venv
# Windows:
.venv\Scripts\activate
# macOS/Linux:
source .venv/bin/activate

# Install library + dev tools
pip install -e ".[dev]"
```

Or install a released version straight from GitHub:

```bash
pip install git+https://github.com/pinhead001/flowfreq@v0.27.1
```

**Dependencies:** `numpy`, `pandas`, `matplotlib`, `scipy`, `requests`, `click`, `pyarrow`.
Word reports need the `report` extra: `pip install "flowfreq[report]"` (python-docx).
The chat server needs the `mcp` extra: `pip install "flowfreq[mcp]"` (mcp 2.x and python-docx).

### USGS Water Data API key (optional)

Peaks, daily and instantaneous values, and site information come from the USGS Water Data
API (`api.waterdata.usgs.gov`). Without a key it allows about **1000 requests per hour per IP
address**; past that it answers HTTP 429. flowfreq retries 429s with backoff, so occasional
use needs nothing, but bulk work -- batch analyses, the gage catalog build, regional-skew
studies -- can hit the limit. A key raises it.

1. **Get a key:** https://api.waterdata.usgs.gov/signup/
2. **Set it** (pick one):

   ```powershell
   # PowerShell -- current session only
   $env:USGS_API_KEY = "your-key-here"

   # PowerShell or cmd -- persistent for your user (open a new terminal afterwards)
   setx USGS_API_KEY "your-key-here"
   ```

   ```bash
   # bash / Git Bash -- current session; add to ~/.bashrc to persist
   export USGS_API_KEY="your-key-here"
   ```

   ```python
   # or in code, overriding the environment variable for this process
   from flowfreq import waterdata
   waterdata.set_api_key("your-key-here")
   ```

3. **Check it is picked up:** `python -c "import os; print(bool(os.environ.get('USGS_API_KEY')))"`.
   flowfreq sends it as the `X-Api-Key` header on every Water Data API request; a rejected key
   raises an error that says so rather than being retried.

Never commit a key. In GitHub Actions, add it as the repository secret `USGS_API_KEY`
(Settings → Secrets and variables → Actions); the weekly live-service workflow reads it.

## Quick Start

### One-liner analysis

```python
from flowfreq import analyze_gage
from flowfreq.regional_skew import regional_skew_for_site

site = "12449500"                         # Methow River at Twisp, WA
skew = regional_skew_for_site(site)       # Pacific Northwest study: G = -0.07, MSE 0.18
# Raises RegionalSkewUnavailable where no verified study applies. B17C has no
# national default, so there you supply a published skew and its MSE yourself.

result = analyze_gage(
    site_no=site,
    regional_skew=skew.skew,
    regional_skew_mse=skew.skew_mse,
    output_dir="./output",
)
# Saves frequency_curve.png, flood_frequency_report.md, etc.
# A gage the regulation screen classes as regulated is refused unless
# allow_regulated=True.
```

### Step-by-step analysis

```python
import numpy as np
from flowfreq import USGSgage, Bulletin17C

# 1. Download data
gage = USGSgage("12449500")
peak_df = gage.download_peak_flow()

# 2. Run EMA. This fits every peak as an exact systematic value. To apply NWIS
# peak codes (historic, less-/greater-than, regulated), use flowfreq.workflow.run_ffa
# or analyze_gage, which apply them by default.
b17c = Bulletin17C(
    peak_flows=peak_df["peak_flow_cfs"].values,
    water_years=peak_df["water_year"].values.astype(int),
    regional_skew=-0.07,          # Pacific Northwest regional skew (SIR 2016-5083 app. B)
    regional_skew_mse=0.18,       # its MSE (SE 0.42)
)
results = b17c.run_analysis(method="ema")

# 3. Quantile table
aep = np.array([0.50, 0.20, 0.10, 0.04, 0.02, 0.01, 0.005, 0.002])
q_df = b17c.compute_quantiles(aep=aep)
ci_df = b17c.compute_confidence_limits(aep=aep)
print(q_df)

# 4. Frequency curve
fig = b17c.plot_frequency_curve(site_name=gage.site_name, site_no=gage.site_no)
fig.savefig("frequency_curve.png", dpi=300, bbox_inches="tight")
```

## Coverage

Coverage is stated per jurisdiction in [`docs/REGRESSION_COVERAGE.md`](docs/REGRESSION_COVERAGE.md)
(generated; do not edit by hand).

**Regression equations** (the offline library, `flowfreq.regression`):

| Tier | Jurisdictions | What it is | How to use it |
|------|---------------|------------|---------------|
| Published (`verified`) | 51: every state, and PR | Transcribed from the cited reports and checked against worked examples, per-gage estimates and NSS; `docs/VERIFICATION_PLAN.md` says what that rests on. Oregon also has a provisional set and Colorado a newer USGS set not yet in NSS | The default: `load_state("WA")` |
| `nss_snapshot` | None in use; 41 files kept as evidence | Harvested from the USGS NSS web service and parsed by machine, 2026-10-25. Unreviewed, so never "verified" | Opt in: `load_state(code, allow_nss_snapshot=True)`, `estimate_at_site(..., allow_nss_snapshot=True)`, `flowfreq ungaged --allow-nss-snapshot` |
| None | 5: DC, VI, GU, MP, AS | NSS serves no peak-flow regions | Not available; the error says so |

A published set always wins over a snapshot. A snapshot is a starting point, not a
supported jurisdiction: check the equations against the cited report before relying on
them.

**Regional skew** (`flowfreq.regional_skew`): `data/regional_skew.csv` has 77 rows covering
all 56 jurisdictions. 34 are `verified` (the value and MSE transcribed from the cited
report and confirmed by a second check), 41 are `pending` (the report prints only the
Bulletin 17B map, or readings disagree, or no study exists) and 2 are `provisional`
(flowfreq-developed, opt-in with `allow_provisional=True`). Where no HUC membership is
encoded for a unit and the state has exactly one usable row, that row is returned with a
`STATE-LEVEL FALLBACK` advisory (`allow_state_fallback=False` turns it off). Where nothing
applies, `RegionalSkewUnavailable` is raised: Bulletin 17C has no national default, so
supply a published skew and its MSE yourself. The nationwide smoke run over every
jurisdiction is in [`docs/NATIONWIDE_SMOKE.md`](docs/NATIONWIDE_SMOKE.md).

## Ungaged sites

```python
from flowfreq import estimate_at_site

est = estimate_at_site(48.3465, -120.1180, state="WA", aeps=[0.1, 0.01])
print(est.to_markdown())      # regions, citations, quantiles, intervals, provenance
est.quantiles                 # DataFrame: aep, flow_cfs, lower, upper, regions, ...
est.provenance                # snap, delineation, library, regions, options, timestamp
```

```bash
flowfreq ungaged --lat 48.3465 --lon -120.1180 --state WA --aep 0.01
# Sycamore Creek, TN: three overlapping NSS sets, so a choice is required
flowfreq ungaged --lat 36.320022 --lon -87.051194 --state TN --allow-nss-snapshot --region GC2016
```

`estimate_at_site` delineates the basin with StreamStats, asks NSS which regression regions
the basin falls in, matches them to the offline library and evaluates the equations on the
basin characteristics. A basin in several regions that partition it is area-weighted by
NSS's `percent_weight`; one region gives its own prediction interval. Pass an at-site
`FrequencyResults` as `at_site=` to weight it with the regression by Bulletin 17C
Appendix 9 (single region only).

- **Overlapping regions.** NSS serves superseded and current equation sets for the same
  area side by side, each at its full weight. They are alternatives, never blended, so
  flowfreq raises `OverlappingRegionsError` (exported from `flowfreq`) listing the candidates
  with their citation year until `region=` (`--region` on the CLI) chooses one, by NSS code
  or library region code, case-insensitively. The others are reported as alternatives. A
  choice that covers only part of a boundary basin, a code that more than one located region
  reaches, or a region not in use is refused with the reason. Some overlaps resolve without
  `region=`: a set drops out where its stated limits exclude the basin (a 1 mi2 small-basin set at a
  131 mi2 site, or an urban set at a basin under its urban threshold), and CT, ME, VT, TN, IA, IL, AL, AR,
  GA, NC and SC have a stored order of preference. `region=` overrides these, and a truly urban or
  NRCS-regulated basin still needs it. The reason is in
  `provenance["region_choice_source"]`.
- **What is refused, and why.** `EquationsUnavailable` when the library has no equations for
  the located regions (the snapshot tier needs its opt-in; DC and the territories have no
  library); a region whose equations need a basin characteristic StreamStats could not
  supply is skipped for the requested AEPs and recorded, not guessed; an input outside an
  equation's calibrated range raises `OutOfRangeError` unless `allow_extrapolation=True`
  (then it is flagged); an empty `aeps` is a `ValueError`. Every failure on the CLI is a
  one-line message and exit 1.
- **Not done yet.** A basin with overlapping sets on a region boundary (each side with its
  own alternatives) cannot take a single `region=`; transposition from a nearby gage is a
  separate step (`flowfreq.transpose`), not yet part of `estimate_at_site`.

## Reports

```python
from flowfreq.reporting import ReportSpec, SectionSpec, build_report

spec = ReportSpec(
    title="Big Sandy River flood frequency",
    author="A. Analyst",
    sections=[
        SectionSpec("text", title="Purpose", narrative="Design flows for the Route 70 bridge."),
        SectionSpec("gaged_ffa", options={"site_no": "03606500", "regional_skew_from_site": True}),
        SectionSpec("ungaged", options={
            "state": "FL", "region": "1", "lat": 30.4, "lon": -84.3,
            "characteristics": {"DRNAREA": 105.0, "LC92STOR": 43.3},
        }),
    ],
)
report = build_report(spec)           # downloads the peaks, looks up the skew, fits, draws
report.save("big_sandy.docx")         # or .md, with its figures in big_sandy_files/
report.spec.save("big_sandy.json")    # the spec as built: rebuilds the same report offline
```

```bash
flowfreq report big_sandy.json -o big_sandy.docx --save-spec big_sandy.built.json
```

A report is a specification of inputs, never of results. `build_report` runs each section's
analysis and lays out what it returns, so a quantile in a report is the one `run_ffa` or
`estimate_from_characteristics` computed.

- **Section kinds** are in `flowfreq.reporting.SECTION_KINDS`, each with its required and
  optional inputs. `gaged_ffa` is Bulletin 17C at a gage: the record, the method as applied
  (skew source with its citation, low-outlier screening, perception thresholds, peak codes),
  fitted parameters, quantiles with 90-percent confidence limits, the frequency curve, the
  stationarity screen and the peaks. `ungaged` is the regional regression at a point: give
  `characteristics` and `region`, or neither and StreamStats delineates the basin.
  `weighted` takes a `gage` (the `gaged_ffa` inputs) and a `regression` (the `ungaged`
  inputs, at the gage) and weights the two by inverse variance (Bulletin 17C Appendix 9):
  the weighted table, then both analyses unless `detail` is false. It refuses a basin in
  more than one region, whose area-weighted flow has no variance of prediction.
  `transposed` takes a `donor` (the `gaged_ffa` inputs), a `target_area_sqmi` and
  `exponents` (a `citation`, and either one `exponent` or `aeps` with `exponents`), and
  carries the gage's quantiles to an ungaged site on the same stream by the drainage-area
  ratio (`flowfreq.transpose.transpose_frequency`): per AEP the gage's flow, the exponent
  and whether it was published, interpolated or extrapolated, the factor and the transposed
  flow with the donor's limits scaled, then the caveats and, unless `detail` is false, the
  analysis at the gage. `engine_check` takes a `gage` and compares its fit with a reference
  computation of the same record: USGS peakfq 8.1.0 run by flowfreq's Fortran extension, or
  the numbers of another program's run given as `reference`. It states whether the two
  agree within the tolerances and tabulates the parameters, quantiles and confidence
  limits side by side. `low_flow` and `flow_duration` take a gage's daily mean flows
  (`site_no` to download them, or `daily` inline: a `start` date and one `flow_cfs` value
  per day, `null` where there is none). `low_flow` fits the annual minimum `n_day`-day mean
  flow (`flowfreq.lowflow.LowFlowFrequency`; 7Q10, 7Q2) and gives the quantiles with
  90-percent confidence limits, the fitted curve and the annual minima; `flow_duration`
  gives the flow equaled or exceeded on a given percent of days (q10, q50, q90) and the
  curve. `future_flow` takes a `gage` or a `regression` and a `factor_set` (name, AEPs,
  factors, scenario, horizon and citation, all the analyst's) and multiplies the flood
  quantiles by the change factors (`flowfreq.future_flow.apply_change_factors`), marking
  each factor as published, interpolated or held. `text` is a titled section of prose.
- **The spec as built is the record.** Give a `site_no` and the peaks are downloaded; give
  `regional_skew_state` or `regional_skew_from_site` and the skew is looked up. Both are
  written into `report.spec` as values, with the retrieval date and the citation, and the
  saved file builds the same tables and figures with no network. An `ungaged` section
  without `characteristics` is stored the same way: every characteristic StreamStats
  returned, the regions with their percent of the basin, and a `streamstats` record (date,
  snapped point, delineated area, what it warned of or set aside). The section is computed
  from those stored values, and is refused if they don't reproduce the StreamStats
  estimate. Its table lists the characteristics the equations use; `all_characteristics`
  lists every one.
- **Narrative.** A section's `narrative` is prose placed after its computed content:
  paragraphs and bullet lists only, so a table in a report always comes from flowfreq. It
  prints under "Draft narrative (written by a language model; not reviewed)" until
  `narrative_status` is `"reviewed"`.
- **What is refused.** An unknown section kind, option or spec key is a `ReportError` naming
  the section. The analyses' own refusals pass through: a regulated record without
  `allow_regulated`, no regional skew choice, a characteristic outside an equation's range.
- **Output.** `.docx` (the `report` extra) or `.md`. There is no PDF writer; export one from
  Word.

`flowfreq.report.HydroReport`, the older single-gage Markdown report, is unchanged.

### Reports through a chat

`flowfreq-mcp` serves the same report tools to a chat client over the Model Context
Protocol, so a report can be built by asking for it:

```bash
pip install "flowfreq[mcp]"
claude mcp add flowfreq -- /path/to/venv/bin/flowfreq-mcp --dir ~/reports
```

The model calls `find_gage`, `run_ffa`, `estimate_from_characteristics`,
`weight_gage_with_regression`, `edit_narrative` and `render_report`; flowfreq computes
every table and figure, and what the model writes is narrative that prints as a draft
until you mark it reviewed. `flowfreq.reporting.ReportSession` is the same thing from
Python. Client configuration, the twenty-one tools and the rules the server holds the model
to are in [docs/CHAT_REPORTS.md](docs/CHAT_REPORTS.md).

## Module Overview

| Module | Purpose |
|--------|---------|
| `flowfreq.usgs` | `USGSgage` — daily/peak/instantaneous flow and stage download |
| `flowfreq.waterdata` / `flowfreq.peak_sources` | Water Data OGC API client (default) and peak-data backends |
| `flowfreq.peak_codes` | NWIS peak qualification codes → Bulletin 17C treatment |
| `flowfreq.psf` / `flowfreq.psf_convert` / `flowfreq.watstore` | PeakFQ `.psf` and WATSTORE readers; `.psf` → `Bulletin17C` |
| `flowfreq.fortran_engine` | The vendored peakfq 8.1.0 Fortran as a selectable engine |
| `flowfreq.regional_skew` / `flowfreq.skew_study` | Regional skew lookup; B-WLS/B-GLS regional skew development |
| `flowfreq.regulation` / `flowfreq.catalog` | Regulation/urbanization screen; national gage catalog |
| `flowfreq.regression` | Offline regional regression equations and evaluator |
| `flowfreq.ungaged` | `estimate_at_site` — basin delineation, NSS region matching, regression estimate with provenance |
| `flowfreq.streamstats` | StreamStats delineation, basin characteristics, NSS estimates |
| `flowfreq.reporting` | `ReportSpec` / `build_report` — DOCX or Markdown reports from a JSON specification; `ReportSession` builds one a section at a time |
| `flowfreq.mcp_server` | `flowfreq-mcp` — the report tools as a Model Context Protocol server for a chat client |
| `flowfreq.transpose` / `flowfreq.qppq` / `flowfreq.donor_similarity` | Transposition to ungaged sites, QPPQ, donor screening |
| `flowfreq.transfer_variance` | Variance-based weighting of gage transfers: dissimilarity variance, GLS blend with the regression, area-ratio band, leave-one-out |
| `flowfreq.monthly_transfer` / `flowfreq.duration_transfer` | The same transfer variance for monthly mean/median flows and median annual duration quantiles (q10, q50, q90) |
| `flowfreq.gage_weighting` / `flowfreq.nesting` | Bulletin 17C Appendix 9 weighting of at-site and regression estimates; flow-connected gage pairs |
| `flowfreq.naturalize` | Naturalization add-back of upstream diversions (caller-supplied rates and return fractions) |
| `flowfreq.stationarity` | Trend and change-point screening (Mann-Kendall with Hamed-Rao, Sen, Spearman, Pettitt, CUSUM, Lombard), field significance (FDR, Walker, block bootstrap), change-point attribution (peak codes, NID, NLCD), peaks-over-threshold count trends, one-page `stationarity_report`, mixed-population screen |
| `flowfreq.future_flow` | Future-condition change-factor framework |
| `flowfreq.subdaily` | Sub-daily metrics: extreme timing, ramping rates |
| `flowfreq.bulletin17c` | `Bulletin17C` — EMA/MOM analysis, quantiles, CI, plots |
| `flowfreq.core` | `FrequencyResults`, `LowFlowResults`, `kfactor`, `grubbs_beck_critical_value` |
| `flowfreq.lowflow` | `LowFlowFrequency` — annual *n*-day low-flow frequency analysis |
| `flowfreq.regime` | `FlowRegime` — flashiness, baseflow separation, diel variation, seasonal summaries |
| `flowfreq.flowio` | `save_flow_frame` / `load_flow_frame` — parquet flow-series I/O |
| `flowfreq.hydrograph` | `Hydrograph` — daily timeseries, summary hydrograph, FDC |
| `flowfreq.freq_plot` | `plot_frequency_curve` — frequency curve as a matplotlib `Figure` |
| `flowfreq.report` | `HydroReport` — automated Markdown report |
| `flowfreq.validation` | Benchmark framework, comparison engine |
| `flowfreq.workflow` | `run_ffa` — one call from annual peaks to a fitted frequency curve |

## Key APIs

### `USGSgage`

```python
gage = USGSgage("03606500")          # Big Sandy River at Bruceton, TN
gage.fetch_site_info()              # Populates site_name, drainage_area, POR dates
                                    # (still the legacy NWIS site service)

daily_df = gage.download_daily_flow(start_date="2000-01-01")
# → DataFrame indexed by date, column: flow_cfs

peak_df = gage.download_peak_flow()
# → DataFrame: water_year, peak_date, peak_flow_cfs, qualification_code
# peak_date is a UTC date on the default Water Data API backend.
# backend="nwis-legacy" on any download_* method uses the legacy NWIS services.
```

### `Bulletin17C`

```python
b17c = Bulletin17C(
    peak_flows,          # np.ndarray of annual peaks (cfs)
    water_years,         # np.ndarray of water years
    regional_skew,       # float or None (station-only if None)
    regional_skew_mse,   # float or None (SE²)
)

results = b17c.run_analysis(method="ema")   # or "mom"

# Results attributes
results.mean_log          # μ (log10)
results.std_log           # σ (log10)
results.skew_station      # station skew
results.skew_weighted     # weighted skew (None if no regional)
results.skew_used         # skew used in quantile calculation
results.ema_converged     # bool
results.n_low_outliers    # rows censored as low outliers (peakfq's gbnlow)
results.n_mgbt_outliers   # of which, peaks the MGBT (or fixed threshold) flagged
results.low_outlier_threshold  # MGBT threshold (cfs)

# Quantile table
q_df = b17c.compute_quantiles(aep=np.array([0.10, 0.02, 0.01]))
# columns: aep, return_period, flow_cfs, log_flow, K_factor

# Confidence limits
ci_df = b17c.compute_confidence_limits(aep=..., confidence=0.90)
# columns: aep, return_period, flow_cfs, lower_5pct, upper_5pct
```

### Standard AEPs (return intervals 1.5–500 yr)

```python
aep = np.array([0.667, 0.50, 0.20, 0.10, 0.04, 0.02, 0.01, 0.005, 0.002])
# RI =              1.5,  2,   5,   10,   25,   50,  100,  200,   500
```

### `LowFlowFrequency`

```python
from flowfreq import LowFlowFrequency

lff = LowFlowFrequency(
    daily_df,             # from USGSgage.download_daily_flow()
    n_day=7,               # averaging window, e.g. 7 for 7Q10
    year_type="climatic",  # "climatic" (Apr-Mar, default), "water", or "calendar"
    distribution="lp3",    # or "lognormal"
)
results = lff.run_analysis()

q_df = lff.compute_quantiles(non_exceedance=np.array([0.5, 0.2, 0.1, 0.02]))
# columns: non_exceedance_prob, return_period, flow_cfs, log_flow, K_factor, conditional_prob

ci_df = lff.compute_confidence_limits(non_exceedance=np.array([0.5, 0.1]))
boot_df = lff.compute_bootstrap_confidence_limits(non_exceedance=np.array([0.5, 0.1]))
```

### `FlowRegime`

```python
from flowfreq import FlowRegime

regime = FlowRegime(
    daily_df,
    year_type="water",                   # default; independent of LowFlowFrequency's
    baseflow_method="ih_smoothed_minima",  # or hysep_*/lyne_hollick — see BASEFLOW_METHODS
)

regime.annual     # per-year: flashiness_index, tqmean, baseflow_index, completeness
regime.monthly    # per year/month means, gated on true calendar-day completeness
regime.seasonal   # per year/season means
regime.summary()  # period-of-record pooled summary
```

### Diel Variation

```python
from flowfreq import diel_variation, diel_variation_summary

iv_df = gage.download_instantaneous_flow(tz="America/Los_Angeles")
diel_df = diel_variation(iv_df, tz="America/Los_Angeles")   # tz required, no default
diel_variation_summary(diel_df)
```

See [`docs/vignette_lowflow_regime.md`](docs/vignette_lowflow_regime.md) for a
full walkthrough of all three, with a worked example and method-choice notes.

## CLI

```bash
# Validate EMA against reference fixtures
flowfreq validate

# Benchmark report (text)
flowfreq benchmark

# Benchmark report (JSON)
flowfreq benchmark --format json

# Native vs Fortran engine on a peak CSV (needs the built Fortran extension)
flowfreq compare --peaks peaks.csv --regional-skew -0.07 --regional-skew-se 0.4243

# Regional-regression estimate at an ungaged site (see Ungaged sites)
flowfreq ungaged --lat 48.3465 --lon -120.1180 --state WA

# A report from a JSON specification (see Reports); .docx needs the report extra
flowfreq report spec.json -o report.docx
```

## Web Application

The interactive Streamlit app lives in its own repository,
[pinhead001/flowfreq-app](https://github.com/pinhead001/flowfreq-app). It installs
this library as a pinned dependency; see that repo's README to run or deploy it.

**App features:**
- Single or multi-gage mode
- Daily time series, summary hydrograph, flow duration curve
- Flood Frequency Analysis (enable in sidebar):
  - EMA with MOM fallback
  - Regional skew inputs
  - Skew option checkboxes: Station / Weighted / Regional
  - Frequency curve with multi-skew overlay
  - Per-skew frequency tables (RI 1.5–500 yr, 90% CI)
- ZIP export: plots (PNG), daily flow CSV, frequency table, LP3 parameters
- Multi-gage comparison table
- Ungaged-site estimates with the overlapping-region choice (`estimate_at_site`; flowfreq-app
  PR #7, pinned to flowfreq v0.16.0, adds the page once it is merged)

## Vignettes

| Guide | Description |
|-------|-------------|
| [CLI Usage](docs/vignette_cli.md) | Command-line validation and benchmarking |
| [Jupyter Notebook](docs/vignette_jupyter.md) | Interactive Bulletin 17C analysis walkthrough |
| [Low-Flow & Flow Regime](docs/vignette_lowflow_regime.md) | Low-flow frequency, flashiness, baseflow separation, diel variation |

## Bulletin 17C Technical Notes

**Weighted skew:** the station and regional skews are weighted by inverse MSE.
```
w_regional  = MSE_station / (MSE_station + MSE_regional)
G_weighted  = (1 − w_regional) × G_station + w_regional × G_regional
```
`MSE_station` depends on the method:
- **EMA** (the default) follows peakfq 8.1.0's HWN weighting. The at-site MSE is ADJE, the
  censoring-aware adjustment of Bulletin 17B's `10^(A − B·log10(n/10))`, and the weight also
  carries the Halloween determinant ratio `Wd`. When MGBT finds low outliers, the at-site
  MSE switches to the unadjusted Bulletin 17B formula, as `emafit.f` does.
- **MOM** uses B17C Appendix 4 eq. A4-2:
  `[6n(n−1) / ((n−2)(n+1)(n+3))] × (1 + (6/n)G² + (15/n²)G⁴)`.

**90% confidence intervals:**
- **EMA** uses Cohn and others' EMA variance with peakfq's asymmetric bounds
  (`flowfreq._var_emab`), matching peakfq 8.1.0.
- **MOM** uses the classical approximation:
```
Var(log Q_p) = S² × (1/n) × [1 + K·G + (K²/2)(1 + 0.75G²)] + S² × (∂K/∂G)² × MSE_G
CI = log Q̂_p ± z × √Var
```

**Skew options** — Any combination of station, weighted, and regional skew can be selected to overlay multiple LP3 curves on the frequency plot and produce separate frequency tables for comparison.

## References

England, J.F., Jr., et al., 2019, Guidelines for determining flood flow frequency — Bulletin 17C: U.S. Geological Survey Techniques and Methods, book 4, chap. B5, 148 p. https://doi.org/10.3133/tm4B5

## Version History

| Version | Changes |
|---------|---------|
| **v0.27.1** | A StreamStats delineation or basin-characteristics request waits 200 s and is not retried after a timeout |
| **v0.27.0** | Reports from a JSON specification as DOCX or Markdown (`flowfreq.reporting`, `flowfreq report`; sections for a gage, a regression estimate, weighting, transposition, a peakfq check, low flow, flow duration and future-condition factors); `flowfreq-mcp` for building a report through a chat client; NSS `bylocation` calls serial and never retried on timeout (#365); flow averaging in twelve more states; Montana Northwest/Foothills caution (`weighting_cautions`); `peak_summary`; `regression.border` |
| **v0.26.0** | `estimate_from_characteristics` / `flowfreq ungaged-chars` (FL, MI, NE); flow averaging for SD, WY, KY (`weighting_space`); NH/NY drainage-area-only sets (`companion_regions`); IL degrees of freedom (`Variable.fitted`); leap-year `day_of_water_year` |
| **v0.25.0** | Texas regional sets first; Louisiana's southern gap (`fallback_region`); Maryland caution (`region_cautions`); Iowa CCM limit; AL/TN intervals from the SEP; `tools/border_qa.py` |
| **v0.24.0** | Indiana selects its region at the point (`RegionSelector`); known-miss cautions near three gages (`KnownMiss`); the report names extrapolated inputs |
| **v0.23.0** | Delaware verified (51 of 56); Arkansas's Mississippi Alluvial Plain slope corrected to `CSLBlue`; AL, AR, GA, NC and SC overlaps resolve without `region=` |
| **v0.22.0** | Regression equations verified in 37 more jurisdictions (50 of 56; DE `partial`); more overlapping sets resolve without `region=` (`RegionLimit`, more preferences); StreamStats' karst warning is a caveat. See `docs/VERIFICATION_PLAN.md` for what verified rests on |
| **v0.21.0** | Alaska, California and Hawaii equations verified (13 jurisdictions); region gates for Arizona and Oregon; Iowa prefers its full equation sets; a verified set beats its NSS snapshot under `allow_nss_snapshot`; Montana channel widths of 0 read as not measured; mypy over every module. See CHANGELOG.md. |
| **v0.20.0** | `run_ffa` attaches the stationarity screen by default (figure opt-in); provisional WA set with Peak Region 2 refit with mean basin elevation (`load_state("WA", allow_provisional=True)`); `flowfreq.stationarity`: Lombard tests, bootstrap field significance, NID/NLCD change-point attribution, peaks-over-threshold count trends, `stationarity_report` (methow item 8 complete); `RegionNotDelineatedError` (FL/MI/NE) and `RegulatedDelineationError`; smoke failures pinned as tests with new MT/ND/AK points; overlapping drainage-area classes chosen by DRNAREA (AK); mypy exemptions 14 to 6. See CHANGELOG.md. |
| **v0.19.0** | WA Peak Region 2 at the Methow: mean basin elevation explains about half the bias (`docs/WA_REGION2_METHOW.md`); monthly leave-one-out/blend and duration-quantile transfer variance (`flowfreq.duration_transfer`); `flowfreq.stationarity` (Mann-Kendall/Hamed-Rao, Sen, Pettitt, CUSUM, field significance, mixed populations); `flowfreq.naturalize`; `fit_gls` robust to an indefinite Σ. See CHANGELOG.md. |
| **v0.18.0** | Regional skew HUC rows for every report-defined study, overlapping studies chosen by state, Alaska's skew areas with drainage-area ranges (#204); `LAT_OUT`/`LONG_OUT` from the pour point (#253); Minnesota's Rainy River Basin equations (#246); `SiteEstimate.basin_geojson` (#256). See CHANGELOG.md. |
| **v0.17.0** | GA/NC/SC region-indicator equations parse (`Variable.times`, interaction terms; #211); `sep_log` for 32 LA/AR/MS equations (#213); multi-code `region=` for boundary basins (#203) and `region=` where NSS locates no peak-flow region (#207); NY urban regions out of scope (#212); nationwide smoke rerun 56/56 gaged, 42/56 ungaged. See CHANGELOG.md. |
| **v0.16.0** | Nationwide rollout: `nss_snapshot` equation tier (41 jurisdictions, 1817 equations); `estimate_at_site` and `flowfreq ungaged` with `OverlappingRegionsError`/`region=`; 77 regional skew rows (34 verified) with a state-level fallback (#194, #195, #196, #197). See CHANGELOG.md. |
| **v0.15.0** | Regulation guardrail on every transfer (`donor_regulation`/`target_regulation`, `RegulationMismatchError`, `classify_site(known_diversions=)`); non-squared dissimilarity terms (`powers=`) and `profile_power` in `flowfreq.transfer_variance` (#181). See CHANGELOG.md. |
| **v0.14.1** | `transfer_variance.leave_one_out` no longer aborts on a negative fold donor correlation: fold estimates floored at 0, unscorable gages recorded with a `note` (#177). See CHANGELOG.md. |
| **v0.14.0** | Quantile-estimate variance (`confidence_limits["variance_log"]`, peakfq's `var_est`) and B17C Appendix 9 weighting (`flowfreq.gage_weighting`); nested-gage pairs from StreamStats polygons and NLDI (`flowfreq.nesting`); SIR 2016-5118 regression-weighted area-ratio transfer (`transpose.regression_weighted_transfer`). See CHANGELOG.md. |
| **v0.13.0** | Variance-based gage-transfer weighting (`flowfreq.transfer_variance`): pair-fitted dissimilarity variance, GLS blend of donors and regression, derived area-ratio band with a gage-resampled bootstrap, leave-one-out coverage. See CHANGELOG.md. |
| **v0.12.0** | Record extension by MOVE.1 (`flowfreq.record_extension`); regression-equation applicability limits; `awaiting_nss` status (CO SIR 2025-5047); NV `verified` with constant equations, equivalent years and gaged-site weighting; catalog regions for WY/NV/NM; provisional Oregon equations; `ramping_rates(window_hours=)`; NID GeoPackage; map-service retries. See CHANGELOG.md. |
| **v0.11.0** | Countrywide groundwork: provisional equation sets (`load_state(..., allow_provisional=True)`); GLS regression (`flowfreq.regression.gls`); WA and UT `verified`; regional skew for AZ, provisional MT east-of-Divide and Oregon 1712 rows, pending rows citing what USGS uses in CO/UT/WY/NV/NM; peak codes keep their case (#135). See CHANGELOG.md. |
| **v0.10.4** | StreamStats cache hits log at DEBUG, not INFO: a cached batch re-run no longer prints one line per point. See CHANGELOG.md. |
| **v0.10.3** | `StreamStatsCache` thread-safe and written atomically: concurrent batch delineation no longer reports cached successes as failures. See CHANGELOG.md. |
| **v0.10.2** | Water Data peaks reduced to one annual peak per water year (duplicate time series, secondary peaks); clear error when peak codes remove every peak; `download_peak_flow` sets every site attribute; Wave 1/2 cross-border QA; AZ region 5 (AZ verified); Wave 2 catalog regions (CO/UT/AZ); opt-in NID/NLCD regulation screen; NCHRP 15-61 future-flow procedures; weekly live-service CI. See CHANGELOG.md. |
| **v0.10.1** | `fetch_site_info` on the Water Data API (discharge-only period of record); `pd.NA` peak codes accepted; native EMA 5-10x faster with bit-identical results. See CHANGELOG.md. |
| **v0.10.0** | Water Data OGC API default for instantaneous and daily values, API key and 429 backoff; regulation screen (refuses regulated gages unless overridden); national gage catalog; `n_low_outliers` = peakfq `gbnlow`; native EMA reproduces peakfq 8.1.0 on all 24 WY/MT stations; Wave 2 regression equations (CO/UT/WY/NM/AZ/NV); `regional_skew_at`; B-WLS/B-GLS skew tooling; StreamStats polygon and region selection; paired stage/discharge. See CHANGELOG.md. |
| **v0.9.0** | Water Data OGC API as the default peak backend; NWIS peak codes applied by default; no silent regional skew default (pass a published skew, `station_skew_only=True` or `use_default_skew=True`); `.psf` input; native-EMA fixes toward peakfq 8.1.0 (zero-flow years, per-year perception thresholds, interval peaks, exact LP3 quantiles, B17B skew-MSE switch, near-zero-skew bounds); WA/OR/ID/MT regression equations; Pacific Northwest regional skew. See CHANGELOG.md. |
| **v0.8.0** | `flowfreq.streamstats`: StreamStats delineation and basin characteristics (Phase 1) and NSS flow-statistic estimates (Phase 2); `download_daily_flow` timeout and date-range fixes |
| **v0.7.0** | Transposition of computed flows to ungaged sites (`flowfreq.transpose`: flood, flow-duration and low-flow, each with mandatory exponent provenance); QPPQ daily-series transfer with melt-timing tools (`flowfreq.qppq`); standalone `regime.flow_duration_curve` |
| **v0.6.1** | `plot_peak_flows_with_thresholds` gains a `yscale` toggle, closing the last app/library plot-dedupe gap (verified numerically equivalent to the app's old values) |
| **v0.6.0** | `plot_peak_flows_with_thresholds` gains PILF/MGBT hollow-bar censoring, closing the app/library plot dedupe; mypy fix in `fortran_engine.py`; `make clean` now also wipes `.mypy_cache` |
| **v0.5.0** | Fortran engine as a selectable analysis engine (`engine=`, `compare_engines`, `flowfreq compare` CLI); tests for `hydrograph.py`/`plots.py`/`batch.py`/`cli.py`; return-period lines and max-peak annotation on `plot_peak_flows_with_thresholds` |
| **v0.4.0** | `B17CEngine.fit` station skew corrected to the Bulletin 17C Eq. 7-2 unbiased estimator (numbers move); `plot_frequency_curve_streamlit` renamed to `plot_frequency_curve`; mypy in CI; `make clean-verify` |
| **v0.3.0** | Split into `flowfreq` (library) and `flowfreq-app` (Streamlit app); renamed from `hydrolib`; native `var_mom` port complete (EMA confidence intervals, censored-interval moment iteration, ADJE/`detrat` regional skew weighting); MOM PILF conditional-probability adjustment |
| **v0.2.0** | Instantaneous (unit-value) flow retrieval; low-flow frequency analysis (`flowfreq.lowflow`); flow regime metrics — flashiness, baseflow separation, monthly/seasonal summaries, diel variation (`flowfreq.regime`); parquet flow-series I/O (`flowfreq.flowio`); LP3 negative-skew quantile fix; EMA historical perception-threshold fix |
| **v0.1.0** | Streamlit app with FFA, skew comparison, ZIP export; freq_plot module; ffa_runner/ffa_export app modules; validation framework |
| **v0.0.3** | EMA algorithm, historical flood handling, CLI, validation benchmarks |
| **v0.0.1** | Initial release: MOM, USGS download, hydrograph plots |

## License

MIT License
