--- title: "Reproducible and auditable analyses with tidyhydat" author: "Sam Albers" date: "2026-12-03" output: html_vignette: keep_md: true vignette: > %\VignetteIndexEntry{Reproducible and auditable analyses with tidyhydat} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ``` r library(tidyhydat) library(dplyr) library(ggplot2) ``` # Why the same code can return different numbers Run a `tidyhydat` analysis today and again in six months and you may get different numbers. Nothing is broken: the data underneath has changed, and it changes in two distinct ways. - **HYDAT is released periodically.** Each release adds new records, and can revise or fill in past values. Environment and Climate Change Canada (ECCC) only hosts the current release, so once a new one is published, the previous one cannot be downloaded again. - **Real-time data is a moving window of provisional values.** `realtime_dd()` returns the last 30 days and `realtime_ws()` reaches back roughly 18 months. Values in that window are provisional: they are revised as hydrometric staff review them, and they eventually reappear in HYDAT as approved data, sometimes with noticeably different values. Once a value has been revised or has left the window, no `tidyhydat` call will return exactly what you originally saw. `available_flows()` and `available_levels()` combine both sources, so the boundary between approved and provisional records also moves with every HYDAT release. This vignette has two different aims: - **Auditable**: you cannot necessarily get the same numbers back, but you can explain why they differ, because you recorded which data you used. This requires no extra storage and is enough for most work. - **Reproducible**: you can rerun the analysis and get identical numbers. Because neither source keeps its history, this requires keeping a copy of the data you used. # Auditable: recording what you used ## Which HYDAT release? `hy_version()` reports the release of a HYDAT database, and `hy_remote()` reports the release ECCC currently serves. Comparing them tells you whether your local copy is out of date: ``` r hy_version() ``` ``` ## # A tibble: 1 × 2 ## Version Date ## ## 1 1.0 2022-07-21 08:22:43 ``` ``` r hy_remote() ``` So that its output stays stable between HYDAT releases, most of this vignette uses the small test database bundled with `tidyhydat`, which is why the release shown above dates from 2022. Your own output will show the release you have downloaded. You rarely need to call `hy_version()` yourself, because every `hy_*` function records the release it was queried from in a `hydat_version` attribute. It is shown in the printed summary: ``` r flows <- hy_daily_flows(station_number = "08MF005") flows ``` ``` ## Queried from version of HYDAT released on 2022-07-21 ## Observations: 32,448 ## Measurement flags: 1,697 ## Parameter(s): Flow ## Date range: 1912-03-01 to 2000-12-31 ## Station(s) returned: 1 ## Stations requested but not returned: ## All stations returned. ## # A tibble: 32,448 × 5 ## STATION_NUMBER Date Parameter Value Symbol ## ## 1 08MF005 1912-03-01 Flow 538 ## 2 08MF005 1912-03-02 Flow 538 ## 3 08MF005 1912-03-03 Flow 538 ## 4 08MF005 1912-03-04 Flow 538 ## 5 08MF005 1912-03-05 Flow 538 ## 6 08MF005 1912-03-06 Flow 538 ## 7 08MF005 1912-03-07 Flow 479 ## 8 08MF005 1912-03-08 Flow 479 ## 9 08MF005 1912-03-09 Flow 459 ## 10 08MF005 1912-03-10 Flow 459 ## # ℹ 32,438 more rows ``` and can be retrieved directly: ``` r attr(flows, "hydat_version") ``` ``` ## [1] "2022-07-21" ``` The attribute reflects the database that was actually queried. If you pass a different database through `hydat_path`, the attribute records that database's release, not the release of your default copy. ## When was real-time data retrieved? Real-time results record the time of the query, in UTC, in a `query_time` attribute: ``` r rt <- realtime_ws( station_number = "08MF005", parameters = 47, ## Discharge start_date = Sys.Date() - 7, end_date = Sys.Date() ) attr(rt, "query_time") ``` ``` ## [1] "2026-12-03 21:14:53 UTC" ``` For provisional data this timestamp is the only meaningful identifier: the same request made a week later may return revised values. ## Combined data needs both The output of `available_flows()` and `available_levels()` is defined by two things: the HYDAT release that supplied the approved records and the time the provisional records were retrieved. Both are recorded, along with whether the approved records came from HYDAT or from the web service: ``` r combined <- available_flows( station_number = "08MH056", start_date = "2026-01-01", end_date = "2026-11-30" ) attr(combined, "hydat_version") ``` ``` ## [1] "2026-10-19" ``` ``` r attr(combined, "historical_source") ``` ``` ## [1] "HYDAT" ``` ``` r attr(combined, "query_time") ``` ``` ## [1] "2026-12-03 21:14:55 UTC" ``` When the approved records come from the web service rather than HYDAT, `hydat_version` is `NA`, because there is no release to report. Note that both functions default to `end_date = Sys.Date()`. That default is convenient for exploratory work, but it guarantees that the same script returns a different date range each time it runs. For anything you intend to report, pass a fixed `end_date`, as above. The `Approval` column records which rows are provisional, so you can report them separately or exclude them from analyses that should only use approved data: ``` r table(combined$Approval) ``` ``` ## ## final provisional ## 181 139 ``` ## Approved data from the web service HYDAT is not the only source of approved data. `hy_daily_flows()` and `hy_daily_levels()` can query ECCC's historical web service instead, by setting `hydat_path = FALSE`, and `available_flows()` and `available_levels()` fall back to the same service when a HYDAT query fails and no `hydat_path` was given. Where the two sources cover the same days they agree, but they do not necessarily cover the same days. Here is one station queried from both: ``` r from_hydat <- hy_daily_flows( station_number = "08MF005", start_date = "2024-01-01" ) from_ws <- hy_daily_flows( station_number = "08MF005", hydat_path = FALSE, start_date = "2024-01-01", end_date = "2026-11-30" ) range(from_hydat$Date) ``` ``` ## [1] "2024-01-01" "2025-02-28" ``` ``` r range(from_ws$Date) ``` ``` ## [1] "2024-01-01" "2026-08-17" ``` The web service is updated independently of HYDAT releases, so it can run well ahead of the current release, as it does here, and at other stations it trails it by a few weeks. It also has no release identifier: the only record of what it returned is the `query_time` attribute. Two consequences follow: - The same `available_flows()` call can return a different split between approved and provisional records depending on which source supplied the approved data. Check `attr(x, "historical_source")` when the distinction matters. - If you need to know exactly which approved data an analysis used, pass `hydat_path` explicitly. A query against a named HYDAT file fails rather than switching sources. # How much does provisional data change? The distinction between provisional and approved data is easy to dismiss in the abstract. The comparison below makes it concrete. It uses a station where the window covered by `realtime_ws()` overlaps with approved data in HYDAT, so the same days are available in both forms: as provisional values from the web service and as approved values from HYDAT. The station was selected automatically when this vignette was built, as the unregulated real-time station with the most days of overlap. This time it is **03NE011** (REID BROOK BELOW TRIBUTARY). ``` r final <- hy_daily_flows( station_number = comparison_stn, hydat_path = full_db, start_date = as.character(window_start) ) provisional_raw <- realtime_ws( station_number = comparison_stn, parameters = 47, ## Discharge start_date = window_start, end_date = Sys.Date() ) ## Averaging to daily values summarises the data, which drops the query_time ## attribute, so it is read from the unaggregated result. retrieved <- attr(provisional_raw, "query_time") provisional <- realtime_daily_mean(provisional_raw, na.rm = TRUE) paired <- inner_join( final |> select(Date, final = Value), provisional |> select(Date, provisional = Value), by = "Date" ) |> filter(!is.na(final), !is.na(provisional), final > 0) |> mutate(pct_diff = (provisional - final) / final * 100) paired |> summarise( days_compared = n(), median_abs_pct_diff = median(abs(pct_diff)), max_abs_pct_diff = max(abs(pct_diff)) ) ``` ``` ## # A tibble: 1 × 3 ## days_compared median_abs_pct_diff max_abs_pct_diff ## ## 1 382 0.668 18.3 ``` ``` r paired |> tidyr::pivot_longer(c(final, provisional), names_to = "Status", values_to = "Value") |> ggplot(aes(x = Date, y = Value, colour = Status)) + geom_line() + scale_colour_manual(values = c(final = "black", provisional = "#D55E00")) + labs( y = "Mean daily discharge (m^3/s)", x = NULL, title = paste("Provisional and approved discharge at", comparison_stn), caption = paste( "Approved data from HYDAT released on", attr(final, "hydat_version"), "| Provisional data retrieved", format(retrieved, "%Y-%m-%d") ) ) + theme_minimal() + theme(legend.position = "bottom") ``` ![plot of chunk compare-plot](vignette-fig-repro-compare-plot-1.png) Most of the time the two agree closely, but individual days can differ substantially. An analysis run on the provisional values and the same analysis rerun after the next HYDAT release can therefore disagree, and both results are correct for the data available at the time. # Reproducible: keeping the data you used If you need to reproduce numbers exactly, for example to support a published result, recording provenance is not enough. You need to keep the data itself. ## Saving query results `saveRDS()` stores a result together with its attributes, so the `hydat_version` and `query_time` come back with it: ``` r path <- tempfile(fileext = ".rds") saveRDS(combined, path) restored <- readRDS(path) attr(restored, "hydat_version") ``` ``` ## [1] "2026-10-19" ``` ``` r attr(restored, "query_time") ``` ``` ## [1] "2026-12-03 21:14:55 UTC" ``` Downstream code then reads the saved file instead of querying again. ## Keeping a copy of HYDAT Because ECCC only hosts the current release, the only way to rerun an analysis against an earlier release is to have kept a copy. HYDAT is a single SQLite file, so archiving it is a matter of copying that file somewhere safe before downloading a new release: ``` r file.copy(hy_downloaded_db(), "archive/Hydat_2026-10-19.sqlite3") ``` Any `hy_*` function can then be pointed at the archived copy: ``` r hy_daily_flows( station_number = "08MF005", hydat_path = "archive/Hydat_2026-10-19.sqlite3" ) ``` To use an archived copy for an entire script, set it as the default instead of passing `hydat_path` to every call: ``` r hy_set_default_db("archive/Hydat_2026-10-19.sqlite3") ``` HYDAT is large, roughly 1 GB uncompressed, so you will probably want to archive only the releases your published work depends on. # Scheduled jobs Scripts that run on a schedule, such as dashboards or alerting, are often working with provisional data. A few habits make their output easier to interpret later: - Log `query_time` and `hydat_version` with every run, so a surprising value can be traced back to the data that produced it. - Request a fixed window relative to the run time, and record it, rather than relying on function defaults that may change. - Check `hy_version()` against `hy_remote()` periodically and download new releases deliberately, rather than discovering mid-season that the approved record has moved. # Testing pipelines without HYDAT Code that depends on `tidyhydat` can be tested without downloading the full database. `hy_test_db()` returns the path to a small database bundled with the package, and `hy_set_default_db()` makes every `hy_*` function use it: ``` r hy_set_default_db(hy_test_db()) ``` The test database contains only a handful of stations, but it has the same tables as HYDAT, which is usually enough to check that a pipeline runs end to end. # Checklist For any result you may need to explain or reproduce, record: - the HYDAT release (`attr(x, "hydat_version")` or `hy_version()`) - the real-time query time (`attr(x, "query_time")`) - the exact `start_date` and `end_date` used, never `Sys.Date()` implicitly - whether provisional data was included (the `Approval` column) - the `tidyhydat` version (`packageVersion("tidyhydat")`) And if exact reproduction matters, keep the query results with `saveRDS()` and archive the HYDAT release they came from.