Spaces:
Running

imgw / global.R
alexdum's picture
Fix IMGW ingestion, status/sentinel handling, CBDH metadata, and Dockerfile
442ba7e
Raw History Blame Contribute Delete
20.9 kB
# global.R for IMGW App
library(shiny)
library(bslib)
library(bsicons)
library(mapgl)
library(sf)
library(jsonlite)
library(dplyr)
library(readr)
library(DT)
library(plotly)
library(lubridate)
library(shinycssloaders)
library(curl)
library(stringr)
library(purrr)
library(shinyjs)
library(tibble)
library(data.table)
library(writexl)
library(shinyWidgets)
# Load helper functions
if (file.exists("funs/utils.R")) source("funs/utils.R")
if (file.exists("funs/wmo.R")) source("funs/wmo.R")
if (file.exists("funs/plot_weather_imgw.R")) source("funs/plot_weather_imgw.R")
# No Mapbox Token needed for open styles
# OpenFreeMap Style URLs
ofm_positron_style <- "https://tiles.openfreemap.org/styles/positron"
ofm_bright_style <- "https://tiles.openfreemap.org/styles/bright"
# EOX Sentinel-2 Cloudless (Free for commercial use with attribution)
sentinel_url <- "https://tiles.maps.eox.at/wmts/1.0.0/s2cloudless-2023_3857/default/GoogleMapsCompatible/{z}/{y}/{x}.jpg"
sentinel_attribution <- '<a href="https://s2maps.eu" target="_blank">Sentinel-2 cloudless - by EOX IT Services GmbH</a> (Contains modified Copernicus Sentinel data 2023)'
# --- Configuration ---
imgw_json_synop <- "https://klimat.imgw.pl/json/stacje.json"
imgw_json_klimat <- "https://klimat.imgw.pl/json/stacje_klimat.json"
# Pre-generated metadata CSV (created by misc/generate_metadata.R)
stations_metadata_file <- file.path("data", "stations_metadata.csv")
poland_voivodeships_geojson <- file.path("data", "poland_voivodeships.geojson")
is_valid_str <- function(x) {
!is.null(x) && length(x) > 0 && !is.na(x[1]) && nzchar(trimws(as.character(x[1])))
}
# Canonical catalog of Poland's 16 Voivodeships (Wojewodztwa)
imgw_voivodeship_catalog <- data.frame(
iso = c(
"PL-DS", "PL-KP", "PL-LU", "PL-LB", "PL-LD", "PL-MA", "PL-MZ", "PL-OP",
"PL-PK", "PL-PD", "PL-PM", "PL-SL", "PL-SK", "PL-WN", "PL-WP", "PL-ZP"
),
voivodeship = c(
"Dolno\u015bl\u0105skie", "Kujawsko-Pomorskie", "Lubelskie", "Lubuskie",
"\u0141\u00f3dzkie", "Ma\u0142opolskie", "Mazowieckie", "Opolskie",
"Podkarpackie", "Podlaskie", "Pomorskie", "\u015al\u0105skie",
"\u015awi\u0119tokrzyskie", "Warmi\u0144sko-Mazurskie", "Wielkopolskie", "Zachodniopomorskie"
),
name_en = c(
"Lower Silesian", "Kuyavian-Pomeranian", "Lublin", "Lubusz",
"Lodz", "Lesser Poland", "Masovian", "Opole",
"Subcarpathian", "Podlaskie", "Pomeranian", "Silesian",
"Swietokrzyskie", "Warmian-Masurian", "Greater Poland", "West Pomeranian"
),
lat_c = c(
51.10, 53.05, 51.22, 52.20, 51.60, 49.85, 52.35, 50.65,
49.95, 53.25, 54.20, 50.30, 50.75, 53.85, 52.35, 53.60
),
lon_c = c(
16.30, 18.50, 22.90, 15.25, 19.45, 20.05, 21.10, 17.90,
22.15, 22.95, 18.15, 19.00, 20.75, 20.80, 17.25, 15.55
),
stringsAsFactors = FALSE
)
imgw_slugify <- function(x) {
if (is.null(x) || length(x) == 0) return(character(0))
s <- enc2utf8(as.character(x))
s[is.na(s)] <- ""
# Explicit transliteration for Polish diacritics (robust across locales)
pl_from <- c(
"\u0105", "\u0107", "\u0119", "\u0142", "\u0144", "\u00f3", "\u015b", "\u017a", "\u017c",
"\u0104", "\u0106", "\u0118", "\u0141", "\u0143", "\u00d3", "\u015a", "\u0179", "\u017b"
)
pl_to <- c(
"a", "c", "e", "l", "n", "o", "s", "z", "z",
"a", "c", "e", "l", "n", "o", "s", "z", "z"
)
for (i in seq_along(pl_from)) {
s <- gsub(pl_from[i], pl_to[i], s, fixed = TRUE)
}
s_ascii <- suppressWarnings(iconv(s, from = "UTF-8", to = "ASCII//TRANSLIT", sub = ""))
use_ascii <- !is.na(s_ascii) & nzchar(s_ascii)
s[use_ascii] <- s_ascii[use_ascii]
s <- tolower(trimws(s))
s <- gsub("^wojewodztwo\\s+", "", s)
s <- gsub("[^a-z0-9]+", "-", s)
s <- gsub("(^-+|-+$)", "", s)
s
}
resolve_imgw_voivodeship <- function(value, available = NULL) {
if (!is_valid_str(value)) return(NULL)
raw <- trimws(enc2utf8(as.character(value[1])))
if (tolower(raw) == "all") return("All")
candidates <- if (!is.null(available) && length(available) > 0) {
unique(na.omit(enc2utf8(as.character(available))))
} else {
imgw_voivodeship_catalog$voivodeship
}
candidates <- candidates[nzchar(trimws(candidates))]
if (length(candidates) == 0) candidates <- imgw_voivodeship_catalog$voivodeship
# 1. Exact or case-insensitive match against available voivodeships
exact_idx <- which(tolower(candidates) == tolower(raw))
if (length(exact_idx) > 0) return(candidates[exact_idx[1]])
# 2. Match by slug against available voivodeships
raw_slug <- imgw_slugify(raw)
if (!nzchar(raw_slug)) return(NULL)
cand_slugs <- imgw_slugify(candidates)
slug_idx <- which(cand_slugs == raw_slug)
if (length(slug_idx) > 0) return(candidates[slug_idx[1]])
# 3. Match against catalog (ISO code, English name, or English name + "voivodeship")
cat_df <- imgw_voivodeship_catalog
iso_idx <- which(tolower(cat_df$iso) == tolower(raw) | imgw_slugify(cat_df$iso) == raw_slug)
if (length(iso_idx) > 0 && cat_df$voivodeship[iso_idx[1]] %in% candidates) {
return(cat_df$voivodeship[iso_idx[1]])
}
raw_slug_clean <- gsub("-voivodeship$", "", raw_slug)
en_idx <- which(imgw_slugify(cat_df$name_en) == raw_slug_clean)
if (length(en_idx) > 0 && cat_df$voivodeship[en_idx[1]] %in% candidates) {
return(cat_df$voivodeship[en_idx[1]])
}
NULL
}
# On-disk timestamp-verified cache for Poland Voivodeship polygons
.imgw_voiv_cache <- new.env(parent = emptyenv())
get_poland_voivodeships_sf <- function(geojson_path = poland_voivodeships_geojson) {
if (!file.exists(geojson_path)) return(NULL)
file_mtime <- file.info(geojson_path)$mtime
if (exists("poly_sf", envir = .imgw_voiv_cache, inherits = FALSE) &&
exists("mtime", envir = .imgw_voiv_cache, inherits = FALSE)) {
if (identical(get("mtime", envir = .imgw_voiv_cache, inherits = FALSE), file_mtime)) {
return(get("poly_sf", envir = .imgw_voiv_cache, inherits = FALSE))
}
}
poly_sf <- tryCatch(
suppressWarnings(sf::st_read(geojson_path, quiet = TRUE)),
error = function(e) NULL
)
if (!is.null(poly_sf) && nrow(poly_sf) > 0) {
poly_sf$voivodeship <- enc2utf8(as.character(poly_sf$voivodeship))
assign("poly_sf", poly_sf, envir = .imgw_voiv_cache)
assign("mtime", file_mtime, envir = .imgw_voiv_cache)
}
poly_sf
}
imgw_assign_voivodeship <- function(stations, geojson_path = poland_voivodeships_geojson) {
if (is.null(stations) || nrow(stations) == 0) return(stations)
if (!"voivodeship" %in% names(stations)) {
stations$voivodeship <- NA_character_
} else {
stations$voivodeship <- enc2utf8(as.character(stations$voivodeship))
stations$voivodeship[!nzchar(trimws(stations$voivodeship)) | stations$voivodeship == "NA"] <- NA_character_
}
missing_idx <- which(is.na(stations$voivodeship) & !is.na(stations$lat) & !is.na(stations$lon))
if (length(missing_idx) > 0) {
poly_sf <- get_poland_voivodeships_sf(geojson_path)
if (!is.null(poly_sf) && nrow(poly_sf) > 0) {
old_s2 <- suppressMessages(sf::sf_use_s2())
suppressMessages(sf::sf_use_s2(FALSE))
on.exit(suppressMessages(sf::sf_use_s2(old_s2)), add = TRUE)
sub_df <- data.frame(
lon = as.numeric(stations$lon[missing_idx]),
lat = as.numeric(stations$lat[missing_idx])
)
pts <- sf::st_as_sf(sub_df, coords = c("lon", "lat"), crs = 4326)
within_list <- suppressMessages(sf::st_within(pts, poly_sf))
assigned <- vapply(
within_list,
function(x) if (length(x) > 0) poly_sf$voivodeship[x[1]] else NA_character_,
character(1)
)
still_na <- is.na(assigned)
if (any(still_na)) {
nearest <- suppressMessages(sf::st_nearest_feature(pts[still_na, ], poly_sf))
assigned[still_na] <- poly_sf$voivodeship[nearest]
}
stations$voivodeship[missing_idx] <- enc2utf8(assigned)
}
# Final centroid fallback if GeoJSON was unavailable
still_missing <- which(is.na(stations$voivodeship) & !is.na(stations$lat) & !is.na(stations$lon))
if (length(still_missing) > 0) {
cat_df <- imgw_voivodeship_catalog
for (idx in still_missing) {
d2 <- (as.numeric(stations$lat[idx]) - cat_df$lat_c)^2 +
((as.numeric(stations$lon[idx]) - cat_df$lon_c) * cos(52 * pi / 180))^2
stations$voivodeship[idx] <- cat_df$voivodeship[which.min(d2)[1]]
}
}
}
stations$voivodeship <- enc2utf8(as.character(stations$voivodeship))
stations$county <- stations$voivodeship
stations
}
imgw_safe_parse_date <- function(x) {
as.Date(lubridate::parse_date_time(x, orders = c("Ymd", "dmY", "Y"), quiet = TRUE))
}
imgw_safe_chr <- function(x) {
out <- as.character(x)
out <- iconv(out, from = "", to = "UTF-8", sub = "")
out[is.na(out)] <- ""
out
}
imgw_safe_trim <- function(x) {
trimws(imgw_safe_chr(x))
}
# Infer missing end dates for legacy metadata where station relocations reused IDs.
# If a station row has no end date but there is a later row with the same ID,
# set end date to one day before the next row start.
imgw_infer_missing_end_dates <- function(stations, start_col = "date_start", end_col = "date_end", group_col = "id") {
if (!all(c(start_col, end_col, group_col) %in% names(stations))) {
return(stations)
}
starts <- stations[[start_col]]
ends <- stations[[end_col]]
groups <- as.character(stations[[group_col]])
for (gid in unique(groups)) {
if (is.na(gid) || 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 (j in seq_along(ord)) {
i <- ord[j]
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
}
}
stations[[end_col]] <- ends
stations
}
imgw_try_regenerate_metadata <- function(script_path = file.path("misc", "generate_metadata.R")) {
if (!file.exists(script_path)) {
message("Metadata regeneration script not found at: ", script_path)
return(FALSE)
}
rscript_bin <- file.path(R.home("bin"), "Rscript")
regen_ok <- tryCatch(
{
out <- suppressWarnings(system2(rscript_bin, script_path, stdout = TRUE, stderr = TRUE))
status <- attr(out, "status")
if (!is.null(status) && status != 0) {
message("Metadata regeneration failed (exit ", status, ").")
return(FALSE)
}
TRUE
},
error = function(e) {
message("Metadata regeneration failed: ", e$message)
FALSE
}
)
regen_ok && file.exists(stations_metadata_file)
}
#' Fetch IMGW Stations
#' Reads pre-generated metadata CSV from data/stations_metadata.csv.
#' Falls back to live JSON fetch if CSV is missing (without probing).
get_imgw_stations <- function() {
required_cols <- c(
"id", "id_9", "name", "lat", "lon", "date_start", "date_end",
"elevation", "station_type", "data_order",
"date_start_hourly", "date_start_daily", "date_start_monthly",
"date_end_hourly", "date_end_daily", "date_end_monthly"
)
end_cols <- c("date_end_hourly", "date_end_daily", "date_end_monthly")
start_cols <- c("date_start_hourly", "date_start_daily", "date_start_monthly")
read_metadata_csv <- function() {
readr::read_csv(
stations_metadata_file,
show_col_types = FALSE,
col_types = readr::cols(.default = "c")
)
}
# --- Primary: read pre-generated CSV ---
if (file.exists(stations_metadata_file)) {
stations <- read_metadata_csv()
original_cols <- names(stations)
missing_cols <- setdiff(required_cols, names(stations))
if (length(missing_cols) > 0) {
message("Metadata CSV is outdated (missing: ", paste(missing_cols, collapse = ", "), "). Attempting regeneration...")
if (imgw_try_regenerate_metadata()) {
stations <- read_metadata_csv()
original_cols <- names(stations)
}
}
# Ensure missing legacy columns exist, even if regeneration could not run.
for (col in setdiff(required_cols, names(stations))) {
stations[[col]] <- NA_character_
}
stations <- stations %>%
mutate(
lat = as.numeric(lat),
lon = as.numeric(lon),
date_start = imgw_safe_parse_date(date_start),
date_end = imgw_safe_parse_date(date_end),
date_start_hourly = imgw_safe_parse_date(date_start_hourly),
date_start_daily = imgw_safe_parse_date(date_start_daily),
date_start_monthly = imgw_safe_parse_date(date_start_monthly),
date_end_hourly = imgw_safe_parse_date(date_end_hourly),
date_end_daily = imgw_safe_parse_date(date_end_daily),
date_end_monthly = imgw_safe_parse_date(date_end_monthly)
) %>%
filter(!is.na(lat), !is.na(lon))
stations <- imgw_infer_missing_end_dates(stations, start_col = "date_start", end_col = "date_end", group_col = "id")
stations <- imgw_infer_missing_end_dates(stations, start_col = "date_start", end_col = "date_end", group_col = "id_9")
# Backfill resolution-specific columns only when the source CSV lacked them entirely.
missing_end_cols <- setdiff(end_cols, original_cols)
missing_start_cols <- setdiff(start_cols, original_cols)
for (col in missing_end_cols) {
stations[[col]] <- stations$date_end
}
for (col in missing_start_cols) {
stations[[col]] <- stations$date_start
}
# Drop impossible ranges introduced by stale metadata combinations.
for (k in seq_along(start_cols)) {
s_col <- start_cols[[k]]
e_col <- end_cols[[k]]
invalid <- !is.na(stations[[s_col]]) & !is.na(stations[[e_col]]) & stations[[e_col]] < stations[[s_col]]
stations[[e_col]][invalid] <- NA
}
stations <- imgw_assign_voivodeship(stations)
if (all(required_cols %in% names(stations))) {
return(stations)
}
message("CSV exists but missing required columns. Falling back to JSON fetch.")
} else {
message("No pre-generated metadata CSV found. Run: Rscript misc/generate_metadata.R")
message("Falling back to live JSON fetch (without probed start dates).")
}
# --- Fallback: live JSON fetch (no probing, fast) ---
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)),
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)
}
)
}
synop <- parse_imgw_json(imgw_json_synop, "Synoptic")
klimat <- parse_imgw_json(imgw_json_klimat, "Climatological")
all_stations <- bind_rows(synop, klimat)
if (nrow(all_stations) == 0) {
message("Failed to download JSONs, using minimal fallback.")
fallback_df <- data.frame(
id = c("12375", "12566"),
id_9 = NA_character_,
name = c("WARSZAWA-OK\u0118CIE", "KRAK\u00d3W-BALICE"),
date_start = NA_character_,
date_end = NA_character_,
elevation = NA_character_,
lat = c(52.1658, 50.0778),
lon = c(20.9672, 19.7847),
station_type = "Fallback",
data_order = NA_character_,
date_start_hourly = NA_character_,
date_start_daily = NA_character_,
date_start_monthly = NA_character_,
date_end_hourly = NA_character_,
date_end_daily = NA_character_,
date_end_monthly = NA_character_,
voivodeship = c("Mazowieckie", "Ma\u0142opolskie"),
county = c("Mazowieckie", "Ma\u0142opolskie"),
stringsAsFactors = FALSE
)
return(fallback_df)
}
unique_stations <- all_stations %>%
mutate(
id = trimws(as.character(id)),
id_9 = trimws(as.character(id_9)),
name = trimws(as.character(name)),
date_start_parsed = imgw_safe_parse_date(date_start),
date_end_parsed = imgw_safe_parse_date(date_end)
) %>%
group_by(id, name) %>%
mutate(
earliest_start = if (all(is.na(date_start_parsed))) as.Date(NA) else min(date_start_parsed, na.rm = TRUE),
has_open_end = any(is.na(date_end_parsed)),
latest_end = if (all(is.na(date_end_parsed))) as.Date(NA) else max(date_end_parsed, na.rm = TRUE)
) %>%
arrange(!is.na(date_end_parsed), desc(date_end_parsed), desc(date_start_parsed), .by_group = TRUE) %>%
slice(1) %>%
ungroup() %>%
mutate(
date_start = earliest_start,
date_end = if_else(has_open_end, as.Date(NA), latest_end),
date_start_hourly = as.Date(NA),
date_start_daily = date_start,
date_start_monthly = date_start,
date_end_hourly = date_end,
date_end_daily = date_end,
date_end_monthly = date_end
) %>%
select(-date_start_parsed, -date_end_parsed, -earliest_start, -has_open_end, -latest_end)
unique_stations <- imgw_infer_missing_end_dates(unique_stations, start_col = "date_start", end_col = "date_end", group_col = "id")
unique_stations <- imgw_infer_missing_end_dates(unique_stations, start_col = "date_start", end_col = "date_end", group_col = "id_9")
unique_stations$date_end_daily[is.na(unique_stations$date_end_daily)] <- unique_stations$date_end[is.na(unique_stations$date_end_daily)]
unique_stations$date_end_monthly[is.na(unique_stations$date_end_monthly)] <- unique_stations$date_end[is.na(unique_stations$date_end_monthly)]
unique_stations$date_end_hourly[is.na(unique_stations$date_end_hourly)] <- unique_stations$date_end[is.na(unique_stations$date_end_hourly)]
unique_stations <- imgw_assign_voivodeship(unique_stations)
return(unique_stations)
}
# Load raw IMGW download/parsing helpers after core metadata utilities
if (file.exists("funs/imgw_raw_data_helpers.R")) source("funs/imgw_raw_data_helpers.R")
create_empty_imgw_plot <- function(message = "No data available") {
plotly::plot_ly() %>%
plotly::add_trace(type = "scatter", mode = "markers", marker = list(opacity = 0), showlegend = FALSE) %>%
plotly::add_annotations(
text = message,
showarrow = FALSE,
xref = "paper", yref = "paper",
x = 0.5, y = 0.5,
font = list(size = 14, color = "#777")
) %>%
plotly::layout(
xaxis = list(visible = FALSE),
yaxis = list(visible = FALSE),
margin = list(t = 40, b = 40, l = 40, r = 40)
) %>%
plotly::config(displaylogo = FALSE)
}
# Default window: today − 366 days through today (computed once at startup;
# the server-side midnight-rollover observer auto-advances these when the
# calendar day changes while the app is still running).
default_end_date <- Sys.Date()
default_start_date <- default_end_date - lubridate::days(366)
create_imgw_group_plot <- function(df, patterns, title, y_title = "Value", max_series = 4) {
if (is.null(df) || nrow(df) == 0) {
return(create_empty_imgw_plot("No data loaded"))
}
if (!"datetime" %in% names(df)) {
if ("date" %in% names(df)) {
df$datetime <- as.POSIXct(df$date, tz = "UTC")
} else {
return(create_empty_imgw_plot("No datetime column available"))
}
}
numeric_cols <- names(df)[vapply(df, is.numeric, logical(1))]
numeric_cols <- setdiff(numeric_cols, c("year", "month", "day", "hour", "minute", "source_rank"))
if (length(numeric_cols) == 0) {
return(create_empty_imgw_plot("No numeric variables found"))
}
hits <- numeric_cols[grepl(patterns, numeric_cols, ignore.case = TRUE)]
if (length(hits) == 0) {
return(create_empty_imgw_plot(paste0("No matching variables for: ", title)))
}
cols <- unique(hits)[seq_len(min(length(unique(hits)), max_series))]
p <- plotly::plot_ly(type = "scatter", mode = "none")
for (col in cols) {
p <- p %>%
plotly::add_lines(
x = df$datetime,
y = df[[col]],
name = col,
connectgaps = FALSE,
hovertemplate = paste0(col, ": %{y}<extra></extra>")
)
}
p %>%
plotly::layout(
title = list(text = title),
xaxis = list(title = "Time"),
yaxis = list(title = y_title),
legend = list(orientation = "h")
) %>%
plotly::config(displaylogo = FALSE)
}