imgw / misc /generate_metadata.R
alexdum's picture
Fix IMGW ingestion, status/sentinel handling, CBDH metadata, and Dockerfile
442ba7e
Raw History Blame Contribute Delete
33.9 kB
#!/usr/bin/env Rscript
# ============================================================================
# Generate IMGW Station Metadata
# ============================================================================
# This script fetches station metadata from IMGW JSON endpoints and probes
# the public data directories to determine robust start dates for each
# temporal resolution (hourly, daily, monthly).
#
# Output: data/stations_metadata.csv
#
# Usage: Rscript misc/generate_metadata.R
# ============================================================================
suppressPackageStartupMessages({
library(jsonlite)
library(dplyr)
library(curl)
library(data.table)
})
# --- Configuration ---
imgw_json_synop <- "https://klimat.imgw.pl/json/stacje.json"
imgw_json_klimat <- "https://klimat.imgw.pl/json/stacje_klimat.json"
output_dir <- "data"
if (!dir.exists(output_dir)) dir.create(output_dir, recursive = TRUE)
probe_zip_cache <- new.env(parent = emptyenv())
download_url_to_file <- function(url, dest) {
ok <- tryCatch({
curl::curl_download(url, dest, mode = "wb", quiet = TRUE)
TRUE
}, error = function(e) FALSE)
if (!ok) {
cli_out <- tryCatch(
suppressWarnings(system2("curl", c("-fsSL", "-o", dest, url), stdout = TRUE, stderr = TRUE)),
error = function(e) NULL
)
status <- attr(cli_out, "status")
ok <- is.null(status) || identical(status, 0L)
}
isTRUE(ok) && file.exists(dest) && !is.na(file.info(dest)$size) && file.info(dest)$size > 0
}
fetch_listing_lines <- function(url) {
lines <- suppressWarnings(tryCatch({
resp <- curl::curl_fetch_memory(
url,
handle = curl::new_handle(failonerror = TRUE)
)
strsplit(rawToChar(resp$content), "\n", fixed = TRUE)[[1]]
}, error = function(e) NULL))
if (is.null(lines)) {
lines <- tryCatch(
suppressWarnings(system2("curl", c("-fsSL", url), stdout = TRUE, stderr = TRUE)),
error = function(e) NULL
)
status <- attr(lines, "status")
if (!is.null(status) && status != 0) {
lines <- NULL
}
}
lines
}
read_utf8_text <- function(file_path) {
sz <- file.info(file_path)$size
if (is.na(sz) || sz <= 0) {
return("")
}
raw_bytes <- readBin(file_path, what = "raw", n = as.integer(sz))
if (length(raw_bytes) == 0) {
return("")
}
raw_bytes <- raw_bytes[raw_bytes != as.raw(0L)]
txt <- rawToChar(raw_bytes)
Encoding(txt) <- "UTF-8"
if (!validUTF8(txt)) {
txt <- iconv(txt, from = "CP1250", to = "UTF-8", sub = "")
if (is.na(txt)) {
Encoding(txt) <- "UTF-8"
txt <- iconv(rawToChar(raw_bytes), from = "latin1", to = "UTF-8", sub = "")
}
}
if (is.na(txt)) txt <- ""
if (nzchar(txt) && !grepl("\n", txt, fixed = TRUE)) {
txt <- paste0(txt, "\n")
}
txt
}
title_case_pl <- function(x) {
s <- trimws(enc2utf8(as.character(x)))
if (is.na(s) || !nzchar(s)) return(NA_character_)
# Preserve original casing unless ALL CAPS (as in api/data/meteo / wykaz_stacji)
if (identical(s, toupper(s)) && !identical(s, tolower(s))) {
parts <- strsplit(tolower(s), "(-|\\s+)")[[1]]
seps <- regmatches(tolower(s), gregexpr("(-|\\s+)", tolower(s)))[[1]]
parts <- vapply(parts, function(p) {
if (!nzchar(p)) return(p)
paste0(toupper(substr(p, 1, 1)), substr(p, 2, nchar(p)))
}, character(1))
out <- parts[1]
if (length(seps) > 0) {
for (k in seq_along(seps)) {
out <- paste0(out, seps[k], if (k + 1 <= length(parts)) parts[k + 1] else "")
}
}
return(out)
}
s
}
# ============================================================================
# 1. Fetch station lists from JSON endpoints
# ============================================================================
parse_imgw_json <- function(url, type) {
tryCatch(
{
json_data <- jsonlite::fromJSON(url, flatten = TRUE)
df <- json_data %>%
select(
id = `kod stacji`,
id_9 = `kod 9-znakowy`,
name = `nazwa stacji`,
lat_str = latitude,
lon_str = longitude,
date_start = data_od,
date_end = data_do,
elevation = `wysokość [m npm]`,
data_order = `rząd danych w CBDH`
) %>%
mutate(
lat = as.numeric(gsub(",", ".", lat_str)),
lon = as.numeric(gsub(",", ".", lon_str)),
# Normalise dates: IMGW uses mixing formats (DD.MM.YYYY, YYYY-MM-DD, YYYY)
date_start = as.Date(lubridate::parse_date_time(date_start, orders = c("Ymd", "dmY", "Y"), quiet = TRUE)),
date_end = as.Date(lubridate::parse_date_time(date_end, orders = c("Ymd", "dmY", "Y"), quiet = TRUE)),
station_type = type,
id = as.character(id),
id_9 = as.character(id_9),
elevation = as.character(elevation),
data_order = as.character(data_order)
) %>%
filter(!is.na(lat), !is.na(lon)) %>%
select(-lat_str, -lon_str)
return(df)
},
error = function(e) {
message("Error fetching ", url, ": ", e$message)
return(NULL)
}
)
}
message("Fetching synoptic stations...")
synop <- parse_imgw_json(imgw_json_synop, "Synoptic")
message(" -> ", if (!is.null(synop)) nrow(synop) else 0, " stations")
message("Fetching climatological stations...")
klimat <- parse_imgw_json(imgw_json_klimat, "Climatological")
message(" -> ", if (!is.null(klimat)) nrow(klimat) else 0, " stations")
all_stations <- bind_rows(synop, klimat)
if (nrow(all_stations) == 0) stop("No stations fetched. Check network connectivity.")
stations <- all_stations %>%
mutate(
id = trimws(as.character(id)),
id_9 = trimws(as.character(id_9)),
name = trimws(as.character(name))
) %>%
group_by(id, name) %>%
mutate(
earliest_start = if (all(is.na(date_start))) as.Date(NA) else min(date_start, na.rm = TRUE),
has_open_end = any(is.na(date_end)),
latest_end = if (all(is.na(date_end))) as.Date(NA) else max(date_end, na.rm = TRUE)
) %>%
arrange(!is.na(date_end), desc(date_end), desc(date_start), .by_group = TRUE) %>%
slice(1) %>%
ungroup() %>%
mutate(
date_start = earliest_start,
date_end = if_else(has_open_end, as.Date(NA), latest_end)
) %>%
select(-earliest_start, -has_open_end, -latest_end) %>%
mutate(row_id = row_number())
message("Total unique stations from JSON: ", nrow(stations))
# ============================================================================
# 2. Probe IMGW directories for robust start/end dates
# ============================================================================
parse_year_range <- function(dir_name) {
if (grepl("^[0-9]{4}_[0-9]{4}$", dir_name)) {
return(c(
start_year = as.numeric(substr(dir_name, 1, 4)),
end_year = as.numeric(substr(dir_name, 6, 9))
))
}
if (grepl("^[0-9]{4}$", dir_name)) {
yr <- as.numeric(dir_name)
return(c(start_year = yr, end_year = yr))
}
return(c(start_year = NA_real_, end_year = NA_real_))
}
normalize_station_code <- function(x) {
x <- trimws(as.character(x))
x <- gsub("[^0-9A-Za-z]", "", x)
x <- sub("^0+", "", x)
ifelse(x == "", "0", x)
}
build_station_code_map <- function(station_df) {
out <- vector("list", nrow(station_df))
for (i in seq_len(nrow(station_df))) {
raw_codes <- unique(c(station_df$id[i], station_df$id_9[i]))
raw_codes <- trimws(as.character(raw_codes))
raw_codes <- raw_codes[!is.na(raw_codes) & nzchar(raw_codes)]
if (length(raw_codes) == 0) next
out[[i]] <- data.frame(
row_id = station_df$row_id[i],
code_norm = unique(normalize_station_code(raw_codes)),
stringsAsFactors = FALSE
)
}
out <- out[!vapply(out, is.null, logical(1))]
if (length(out) == 0) {
return(data.frame(row_id = integer(), code_norm = character(), stringsAsFactors = FALSE))
}
bind_rows(out) %>% distinct(row_id, code_norm, .keep_all = TRUE)
}
map_probe_to_stations <- function(probe_df, code_map) {
if (nrow(probe_df) == 0 || nrow(code_map) == 0) {
return(data.frame(row_id = integer(), min_year = numeric(), max_year = numeric(), stringsAsFactors = FALSE))
}
probe_df <- probe_df %>%
mutate(code_norm = normalize_station_code(file_code)) %>%
filter(!is.na(min_year), !is.na(max_year)) %>%
distinct(code_norm, min_year, max_year)
if (nrow(probe_df) == 0) {
return(data.frame(row_id = integer(), min_year = numeric(), max_year = numeric(), stringsAsFactors = FALSE))
}
joined <- inner_join(code_map, probe_df, by = "code_norm", relationship = "many-to-many")
if (nrow(joined) == 0) {
return(data.frame(row_id = integer(), min_year = numeric(), max_year = numeric(), stringsAsFactors = FALSE))
}
joined %>%
group_by(row_id) %>%
summarise(
min_year = min(min_year, na.rm = TRUE),
max_year = max(max_year, na.rm = TRUE),
.groups = "drop"
)
}
infer_missing_end_dates <- function(df, start_col = "date_start", end_col = "date_end", group_col = "id") {
if (!all(c(start_col, end_col, group_col) %in% names(df))) {
return(df)
}
starts <- df[[start_col]]
ends <- df[[end_col]]
groups <- trimws(as.character(df[[group_col]]))
for (gid in unique(groups)) {
if (is.na(gid) || !nzchar(gid)) next
idx <- which(groups == gid & !is.na(starts))
if (length(idx) < 2) next
ord <- idx[order(starts[idx], na.last = TRUE)]
starts_ord <- starts[ord]
for (i in ord) {
if (!is.na(ends[i])) next
later <- starts_ord[starts_ord > starts[i]]
if (length(later) == 0) next
inferred <- min(later, na.rm = TRUE) - 1
if (!is.na(inferred)) ends[i] <- inferred
}
}
df[[end_col]] <- ends
df
}
combine_start_date <- function(metadata_start, probed_start) {
out <- metadata_start
only_probe <- is.na(out) & !is.na(probed_start)
out[only_probe] <- probed_start[only_probe]
both <- !is.na(out) & !is.na(probed_start)
out[both] <- pmax(out[both], probed_start[both])
out
}
combine_end_date <- function(metadata_end, probed_end, latest_archive_end = NULL) {
out <- metadata_end
only_probe <- is.na(out) & !is.na(probed_end)
if (!is.null(latest_archive_end) && !is.na(latest_archive_end)) {
# Active stations (NA metadata end) that continue through the latest archive year
# for this resolution stay NA ("Present"), avoiding artificial cutoff years.
ceased_earlier <- only_probe & (probed_end < latest_archive_end)
out[ceased_earlier] <- probed_end[ceased_earlier]
} else {
out[only_probe] <- probed_end[only_probe]
}
both <- !is.na(out) & !is.na(probed_end)
out[both] <- pmin(out[both], probed_end[both])
out
}
combine_resolution_window <- function(metadata_start, metadata_end, probed_start, probed_end, latest_archive_end = NULL) {
has_probe <- !is.na(probed_start) | !is.na(probed_end)
start_out <- as.Date(rep(NA_character_, length(metadata_start)))
end_out <- as.Date(rep(NA_character_, length(metadata_end)))
if (any(has_probe)) {
start_out[has_probe] <- combine_start_date(metadata_start[has_probe], probed_start[has_probe])
end_out[has_probe] <- combine_end_date(metadata_end[has_probe], probed_end[has_probe], latest_archive_end = latest_archive_end)
}
list(start = start_out, end = end_out)
}
year_to_date <- function(x, month_day) {
out <- as.Date(rep(NA_character_, length(x)))
valid <- !is.na(x)
if (any(valid)) {
out[valid] <- as.Date(sprintf("%04d-%s", as.integer(x[valid]), month_day))
}
out
}
extract_station_codes_from_zip_file <- function(zip_tmp) {
zip_list <- tryCatch(unzip(zip_tmp, list = TRUE), error = function(e) NULL)
if (is.null(zip_list) || nrow(zip_list) == 0) {
return(character())
}
targets <- zip_list$Name[grepl("\\.(txt|csv)$", zip_list$Name, ignore.case = TRUE)]
targets <- targets[!grepl("(format|opis|lista_zmian)\\.txt$", basename(targets), ignore.case = TRUE)]
if (length(targets) == 0) {
targets <- zip_list$Name[!grepl("/$", zip_list$Name) & !grepl("(format|opis|lista_zmian)\\.txt$", basename(zip_list$Name), ignore.case = TRUE)]
}
if (length(targets) == 0) {
return(character())
}
extract_dir <- tempfile()
dir.create(extract_dir)
on.exit(unlink(extract_dir, recursive = TRUE), add = TRUE)
unzip(zip_tmp, files = targets, exdir = extract_dir)
station_codes <- character()
for (cand in targets) {
file_path <- file.path(extract_dir, cand)
if (!file.exists(file_path)) next
txt <- read_utf8_text(file_path)
if (!nzchar(txt)) next
for (sep in c(",", ";", "\t")) {
found_for_file <- FALSE
for (use_header in c(FALSE, TRUE)) {
dt <- tryCatch(
data.table::fread(
text = txt,
sep = sep,
header = use_header,
fill = TRUE,
data.table = FALSE,
showProgress = FALSE
),
error = function(e) NULL
)
if (is.null(dt) || ncol(dt) == 0) next
first_col <- trimws(as.character(dt[[1]]))
first_col <- first_col[!is.na(first_col) & nzchar(first_col)]
if (length(first_col) == 0) next
station_codes <- union(station_codes, unique(first_col))
found_for_file <- TRUE
break
}
if (found_for_file) break
}
}
station_codes
}
extract_station_codes_from_zip <- function(zip_url) {
cache_key <- gsub("[^A-Za-z0-9]", "_", zip_url)
if (exists(cache_key, envir = probe_zip_cache, inherits = FALSE)) {
return(get(cache_key, envir = probe_zip_cache, inherits = FALSE))
}
zip_tmp <- tempfile(fileext = ".zip")
on.exit(unlink(zip_tmp), add = TRUE)
ok <- download_url_to_file(zip_url, zip_tmp)
if (!ok) {
return(character())
}
station_codes <- extract_station_codes_from_zip_file(zip_tmp)
assign(cache_key, station_codes, envir = probe_zip_cache)
station_codes
}
prefetch_aggregate_zip_codes <- function(agg_urls) {
if (length(agg_urls) == 0) return(invisible(NULL))
keys <- gsub("[^A-Za-z0-9]", "_", agg_urls)
uncached <- !vapply(keys, exists, logical(1), envir = probe_zip_cache, inherits = FALSE)
todo_urls <- agg_urls[uncached]
if (length(todo_urls) == 0) return(invisible(NULL))
batch_size <- 20L
n <- length(todo_urls)
for (start_idx in seq(1L, n, by = batch_size)) {
end_idx <- min(start_idx + batch_size - 1L, n)
chunk_urls <- todo_urls[start_idx:end_idx]
dest_files <- replicate(length(chunk_urls), tempfile(fileext = ".zip"))
res <- tryCatch(
curl::multi_download(chunk_urls, destfiles = dest_files, progress = FALSE, multiplex = TRUE),
error = function(e) NULL
)
for (k in seq_along(chunk_urls)) {
u <- chunk_urls[k]
df_path <- dest_files[k]
ck <- gsub("[^A-Za-z0-9]", "_", u)
ok_dl <- !is.null(res) && k <= nrow(res) && isTRUE(res$success[k]) &&
!is.na(res$status_code[k]) && res$status_code[k] >= 200 && res$status_code[k] < 300 &&
file.exists(df_path) && !is.na(file.info(df_path)$size) && file.info(df_path)$size > 0
if (!ok_dl) {
ok_dl <- download_url_to_file(u, df_path)
}
if (ok_dl) {
codes <- extract_station_codes_from_zip_file(df_path)
assign(ck, codes, envir = probe_zip_cache)
}
unlink(df_path)
}
}
invisible(NULL)
}
probe_dir <- function(base_url, pattern_suffix = "_s.zip", aggregate_type = c("none", "yearly_m", "monthly_ym")) {
aggregate_type <- match.arg(aggregate_type)
message(" Probing: ", base_url)
html <- fetch_listing_lines(base_url)
if (is.null(html)) {
message(" -> Failed to fetch directory listing")
return(data.frame(file_code = character(), min_year = numeric(), max_year = numeric(), stringsAsFactors = FALSE))
}
dirs <- grep('href="([0-9]{4}_[0-9]{4}|[0-9]{4})/"', html, value = TRUE)
dirs_clean <- unique(gsub('.*href="([0-9]{4}_[0-9]{4}|[0-9]{4})/".*', "\\1", dirs))
message(" -> Found ", length(dirs_clean), " year/range directories")
station_ranges <- list()
for (rng in dirs_clean) {
years <- parse_year_range(rng)
start_year <- years[["start_year"]]
end_year <- years[["end_year"]]
if (is.na(start_year) || is.na(end_year)) next
url <- paste0(base_url, rng, "/")
html2 <- fetch_listing_lines(url)
if (is.null(html2)) next
href_lines <- grep('href="[^"]+\\.zip"', html2, value = TRUE)
if (length(href_lines) == 0) next
hrefs <- unique(gsub('.*href="([^"]+)".*', "\\1", href_lines))
hrefs <- trimws(sub("\\?.*$", "", hrefs))
hrefs <- hrefs[nzchar(hrefs)]
suffix_regex <- gsub(".", "[.]", pattern_suffix, fixed = TRUE)
suffix_pattern <- paste0(suffix_regex, "$")
hrefs <- hrefs[grepl(suffix_pattern, hrefs, ignore.case = TRUE)]
if (length(hrefs) == 0) next
aggregate_pattern <- switch(aggregate_type,
yearly_m = paste0("^([0-9]{4}_[0-9]{4}|[0-9]{4})_m", suffix_regex, "$"),
monthly_ym = paste0("^((18|19|20)[0-9]{2}_[0-9]{2}|(18|19|20)[0-9]{2}_(18|19|20)[0-9]{2}|(18|19|20)[0-9]{2})", suffix_regex, "$"),
none = NA_character_
)
is_aggregate <- if (!is.na(aggregate_pattern)) grepl(aggregate_pattern, hrefs, ignore.case = TRUE) else rep(FALSE, length(hrefs))
aggregate_hrefs <- hrefs[is_aggregate]
station_hrefs <- hrefs[!is_aggregate]
id_pattern <- paste0("^.*_([A-Za-z0-9]+)", suffix_regex, "$")
has_id <- grepl(id_pattern, station_hrefs, ignore.case = TRUE)
station_hrefs <- station_hrefs[has_id]
file_codes <- character()
if (length(station_hrefs) > 0) {
file_codes <- unique(sub(id_pattern, "\\1", station_hrefs, ignore.case = TRUE))
}
if (length(aggregate_hrefs) > 0) {
agg_urls <- paste0(url, aggregate_hrefs)
prefetch_aggregate_zip_codes(agg_urls)
aggregate_codes <- character()
for (agg_url in agg_urls) {
aggregate_codes <- union(aggregate_codes, extract_station_codes_from_zip(agg_url))
}
if (length(aggregate_codes) > 0) {
file_codes <- unique(c(file_codes, aggregate_codes))
}
}
if (length(file_codes) > 0) {
station_ranges[[rng]] <- data.frame(
file_code = file_codes,
min_year = start_year,
max_year = end_year,
stringsAsFactors = FALSE
)
}
}
if (length(station_ranges) == 0) {
return(data.frame(file_code = character(), min_year = numeric(), max_year = numeric(), stringsAsFactors = FALSE))
}
all_res <- do.call(rbind, station_ranges)
final <- all_res %>%
group_by(file_code) %>%
summarise(
min_year = min(min_year),
max_year = max(max_year),
.groups = "drop"
) %>%
ungroup()
message(" -> Found data for ", nrow(final), " stations")
return(final)
}
message("\nProbing hourly data...")
hourly_synop_url <- "https://danepubliczne.imgw.pl/data/dane_pomiarowo_obserwacyjne/dane_meteorologiczne/terminowe/synop/"
hourly_klimat_url <- "https://danepubliczne.imgw.pl/data/dane_pomiarowo_obserwacyjne/dane_meteorologiczne/terminowe/klimat/"
hourly_synop <- probe_dir(hourly_synop_url, "_s.zip", aggregate_type = "monthly_ym")
hourly_klimat <- probe_dir(hourly_klimat_url, "_k.zip", aggregate_type = "monthly_ym")
message("\nProbing daily data...")
daily_synop_url <- "https://danepubliczne.imgw.pl/data/dane_pomiarowo_obserwacyjne/dane_meteorologiczne/dobowe/synop/"
daily_klimat_url <- "https://danepubliczne.imgw.pl/data/dane_pomiarowo_obserwacyjne/dane_meteorologiczne/dobowe/klimat/"
daily_opad_url <- "https://danepubliczne.imgw.pl/data/dane_pomiarowo_obserwacyjne/dane_meteorologiczne/dobowe/opad/"
daily_synop <- probe_dir(daily_synop_url, "_s.zip", aggregate_type = "monthly_ym")
daily_klimat <- probe_dir(daily_klimat_url, "_k.zip", aggregate_type = "monthly_ym")
daily_opad <- probe_dir(daily_opad_url, "_o.zip", aggregate_type = "monthly_ym")
message("\nProbing monthly data...")
monthly_synop_url <- "https://danepubliczne.imgw.pl/data/dane_pomiarowo_obserwacyjne/dane_meteorologiczne/miesieczne/synop/"
monthly_klimat_url <- "https://danepubliczne.imgw.pl/data/dane_pomiarowo_obserwacyjne/dane_meteorologiczne/miesieczne/klimat/"
monthly_opad_url <- "https://danepubliczne.imgw.pl/data/dane_pomiarowo_obserwacyjne/dane_meteorologiczne/miesieczne/opad/"
monthly_synop <- probe_dir(monthly_synop_url, "_s.zip", aggregate_type = "yearly_m")
monthly_klimat <- probe_dir(monthly_klimat_url, "_k.zip", aggregate_type = "yearly_m")
monthly_opad <- probe_dir(monthly_opad_url, "_o.zip", aggregate_type = "yearly_m")
# Supplement active Synoptic/Climatological stations missing from klimat.imgw.pl/json
# using wykaz_stacji.csv + danepubliczne.imgw.pl/api/data/meteo verified against synop/klimat probes.
supplement_missing_active_stations <- function(stations_df) {
wykaz_url <- "https://danepubliczne.imgw.pl/data/dane_pomiarowo_obserwacyjne/dane_meteorologiczne/wykaz_stacji.csv"
meteo_url <- "https://danepubliczne.imgw.pl/api/data/meteo"
synop_codes <- unique(normalize_station_code(c(hourly_synop$file_code, daily_synop$file_code, monthly_synop$file_code)))
klimat_codes <- unique(normalize_station_code(c(hourly_klimat$file_code, daily_klimat$file_code, monthly_klimat$file_code)))
known_norms <- unique(normalize_station_code(c(stations_df$id, stations_df$id_9)))
known_norms <- known_norms[!is.na(known_norms) & nzchar(known_norms) & known_norms != "0"]
wykaz_tmp <- tempfile(fileext = ".csv")
on.exit(unlink(wykaz_tmp), add = TRUE)
wykaz_map <- data.frame(id_9 = character(), short_id = character(), wykaz_name = character(), stringsAsFactors = FALSE)
if (download_url_to_file(wykaz_url, wykaz_tmp)) {
wtxt <- read_utf8_text(wykaz_tmp)
if (nzchar(wtxt)) {
wdf <- tryCatch(
data.table::fread(text = wtxt, sep = ",", header = FALSE, quote = "", fill = TRUE, data.table = FALSE, showProgress = FALSE),
error = function(e) NULL
)
if (!is.null(wdf) && ncol(wdf) >= 3) {
clean_q <- function(v) trimws(gsub('^"|"$', "", as.character(v)))
wdf_clean <- data.frame(
id_9 = clean_q(wdf[[1]]),
wykaz_name = clean_q(wdf[[2]]),
short_id = clean_q(wdf[[3]]),
stringsAsFactors = FALSE
) %>%
filter(nzchar(id_9), grepl("^[0-9]{6,9}$", id_9)) %>%
mutate(is_precip_alias = grepl("^9[0-9]{4}$", short_id)) %>%
arrange(id_9, is_precip_alias, nchar(short_id)) %>%
group_by(id_9) %>%
slice(1) %>%
ungroup() %>%
select(id_9, short_id, wykaz_name)
wykaz_map <- wdf_clean
}
}
}
meteo_df <- tryCatch(jsonlite::fromJSON(meteo_url, flatten = TRUE), error = function(e) NULL)
if (is.null(meteo_df) || nrow(meteo_df) == 0) {
return(stations_df)
}
meteo_df$lat_num <- suppressWarnings(as.numeric(gsub(",", ".", as.character(meteo_df$lat))))
meteo_df$lon_num <- suppressWarnings(as.numeric(gsub(",", ".", as.character(meteo_df$lon))))
meteo_df$id_9 <- trimws(as.character(meteo_df$kod_stacji))
meteo_df <- meteo_df %>% filter(!is.na(lat_num), !is.na(lon_num), nzchar(id_9))
if (nrow(wykaz_map) > 0) {
meteo_df <- meteo_df %>% left_join(wykaz_map, by = "id_9")
} else {
meteo_df$short_id <- NA_character_
meteo_df$wykaz_name <- NA_character_
}
extra_rows <- list()
for (i in seq_len(nrow(meteo_df))) {
c9 <- meteo_df$id_9[i]
c_short <- if (!is.na(meteo_df$short_id[i]) && nzchar(meteo_df$short_id[i])) meteo_df$short_id[i] else NA_character_
norms <- unique(normalize_station_code(c(c9, c_short)))
norms <- norms[!is.na(norms) & nzchar(norms) & norms != "0"]
if (any(norms %in% known_norms)) next
in_synop <- any(norms %in% synop_codes)
in_klimat <- any(norms %in% klimat_codes)
if (!in_synop && !in_klimat) next
# Avoid adding 3xxxx sub-station aliases if short id is absent from wykaz or matches precip network only
stype <- if (in_synop) "Synoptic" else "Climatological"
dorder <- if (in_synop) "synop" else "klimat"
yr_start <- suppressWarnings(as.integer(meteo_df$rok_zalozenia_stacji[i]))
dstart <- if (!is.na(yr_start) && yr_start >= 1800 && yr_start <= 2100) as.Date(sprintf("%04d-01-01", yr_start)) else as.Date(NA)
elev_val <- if ("wysokosc_npm" %in% names(meteo_df) && !is.na(meteo_df$wysokosc_npm[i])) as.character(meteo_df$wysokosc_npm[i]) else NA_character_
raw_name <- if (!is.na(meteo_df$nazwa_stacji[i]) && nzchar(trimws(meteo_df$nazwa_stacji[i]))) meteo_df$nazwa_stacji[i] else meteo_df$wykaz_name[i]
extra_rows[[length(extra_rows) + 1]] <- data.frame(
id = if (!is.na(c_short)) c_short else "",
id_9 = c9,
name = title_case_pl(raw_name),
date_start = dstart,
date_end = as.Date(NA),
elevation = elev_val,
data_order = dorder,
lat = meteo_df$lat_num[i],
lon = meteo_df$lon_num[i],
station_type = stype,
stringsAsFactors = FALSE
)
}
if (length(extra_rows) > 0) {
add_df <- bind_rows(extra_rows)
message(" -> Supplemented ", nrow(add_df), " missing active Synoptic/Climatological station(s): ", paste(add_df$name, collapse = ", "))
stations_df <- bind_rows(stations_df, add_df)
}
stations_df
}
message("\nChecking for active Synoptic/Climatological stations missing from JSON...")
stations <- supplement_missing_active_stations(stations) %>%
infer_missing_end_dates(start_col = "date_start", end_col = "date_end", group_col = "id") %>%
infer_missing_end_dates(start_col = "date_start", end_col = "date_end", group_col = "id_9") %>%
mutate(row_id = row_number())
station_code_map <- build_station_code_map(stations)
hourly <- map_probe_to_stations(bind_rows(hourly_synop, hourly_klimat), station_code_map)
daily <- map_probe_to_stations(bind_rows(daily_synop, daily_klimat, daily_opad), station_code_map)
monthly <- map_probe_to_stations(bind_rows(monthly_synop, monthly_klimat, monthly_opad), station_code_map)
latest_hourly_end <- if (nrow(hourly) > 0) year_to_date(max(hourly$max_year, na.rm = TRUE), "12-31") else as.Date(NA)
latest_daily_end <- if (nrow(daily) > 0) year_to_date(max(daily$max_year, na.rm = TRUE), "12-31") else as.Date(NA)
latest_monthly_end <- if (nrow(monthly) > 0) year_to_date(max(monthly$max_year, na.rm = TRUE), "12-31") else as.Date(NA)
message("Total stations in catalog: ", nrow(stations))
message(" -> Matched hourly availability for ", nrow(hourly), " station rows (latest year: ", format(latest_hourly_end, "%Y"), ")")
message(" -> Matched daily availability for ", nrow(daily), " station rows (latest year: ", format(latest_daily_end, "%Y"), ")")
message(" -> Matched monthly availability for ", nrow(monthly), " station rows (latest year: ", format(latest_monthly_end, "%Y"), ")")
# ============================================================================
# 3. Merge probed dates into station data
# ============================================================================
message("\nMerging probed dates into station metadata...")
stations <- stations %>%
left_join(hourly, by = "row_id") %>%
rename(
date_start_hourly_probe = min_year,
date_end_hourly_probe = max_year
) %>%
left_join(daily, by = "row_id") %>%
rename(
date_start_daily_probe = min_year,
date_end_daily_probe = max_year
) %>%
left_join(monthly, by = "row_id") %>%
rename(
date_start_monthly_probe = min_year,
date_end_monthly_probe = max_year
) %>%
mutate(
date_start_hourly_probe = year_to_date(date_start_hourly_probe, "01-01"),
date_end_hourly_probe = year_to_date(date_end_hourly_probe, "12-31"),
date_start_daily_probe = year_to_date(date_start_daily_probe, "01-01"),
date_end_daily_probe = year_to_date(date_end_daily_probe, "12-31"),
date_start_monthly_probe = year_to_date(date_start_monthly_probe, "01-01"),
date_end_monthly_probe = year_to_date(date_end_monthly_probe, "12-31")
) %>%
{
hourly_bounds <- combine_resolution_window(.$date_start, .$date_end, .$date_start_hourly_probe, .$date_end_hourly_probe, latest_archive_end = latest_hourly_end)
daily_bounds <- combine_resolution_window(.$date_start, .$date_end, .$date_start_daily_probe, .$date_end_daily_probe, latest_archive_end = latest_daily_end)
monthly_bounds <- combine_resolution_window(.$date_start, .$date_end, .$date_start_monthly_probe, .$date_end_monthly_probe, latest_archive_end = latest_monthly_end)
mutate(.,
date_start_hourly = hourly_bounds$start,
date_end_hourly = hourly_bounds$end,
date_start_daily = daily_bounds$start,
date_end_daily = daily_bounds$end,
date_start_monthly = monthly_bounds$start,
date_end_monthly = monthly_bounds$end
)
} %>%
mutate(
date_end_hourly = if_else(!is.na(date_start_hourly) & !is.na(date_end_hourly) & date_end_hourly < date_start_hourly,
as.Date(NA),
date_end_hourly
),
date_end_daily = if_else(!is.na(date_start_daily) & !is.na(date_end_daily) & date_end_daily < date_start_daily,
as.Date(NA),
date_end_daily
),
date_end_monthly = if_else(!is.na(date_start_monthly) & !is.na(date_end_monthly) & date_end_monthly < date_start_monthly,
as.Date(NA),
date_end_monthly
)
) %>%
select(
-row_id,
-date_start_hourly_probe, -date_end_hourly_probe,
-date_start_daily_probe, -date_end_daily_probe,
-date_start_monthly_probe, -date_end_monthly_probe
)
# Assign Polish Voivodeship (Wojewodztwo) from data/poland_voivodeships.geojson
geojson_file <- file.path(output_dir, "poland_voivodeships.geojson")
if (file.exists(geojson_file) && requireNamespace("sf", quietly = TRUE)) {
message("\nAssigning Voivodeships from ", geojson_file, "...")
old_s2 <- suppressMessages(sf::sf_use_s2())
suppressMessages(sf::sf_use_s2(FALSE))
poly_sf <- suppressWarnings(sf::st_read(geojson_file, quiet = TRUE))
pts <- sf::st_as_sf(stations, coords = c("lon", "lat"), crs = 4326, remove = FALSE)
within_list <- suppressMessages(sf::st_within(pts, poly_sf))
voiv <- vapply(
within_list,
function(x) if (length(x) > 0) as.character(poly_sf$voivodeship[x[1]]) else NA_character_,
character(1)
)
na_mask <- is.na(voiv)
if (any(na_mask)) {
nearest_idx <- suppressMessages(sf::st_nearest_feature(pts[na_mask, ], poly_sf))
voiv[na_mask] <- as.character(poly_sf$voivodeship[nearest_idx])
}
stations$voivodeship <- enc2utf8(voiv)
suppressMessages(sf::sf_use_s2(old_s2))
}
# ============================================================================
# 4. Save to CSV
# ============================================================================
output_file <- file.path(output_dir, "stations_metadata.csv")
write.csv(stations, output_file, row.names = FALSE, fileEncoding = "UTF-8")
message("\nSaved: ", output_file, " (", nrow(stations), " stations)")
# Summary
n_hourly <- sum(!is.na(stations$date_start_hourly))
n_daily <- sum(!is.na(stations$date_start_daily))
n_monthly <- sum(!is.na(stations$date_start_monthly))
n_hourly_end <- sum(!is.na(stations$date_end_hourly))
n_daily_end <- sum(!is.na(stations$date_end_daily))
n_monthly_end <- sum(!is.na(stations$date_end_monthly))
message("\nStations with resolution start dates (probed + metadata-bounded):")
message(" Hourly: ", n_hourly)
message(" Daily: ", n_daily)
message(" Monthly: ", n_monthly)
message("\nStations with resolution end dates (probed + metadata-bounded):")
message(" Hourly: ", n_hourly_end)
message(" Daily: ", n_daily_end)
message(" Monthly: ", n_monthly_end)
message("\nDone!")