alexdum commited on
Commit
82f495c
·
1 Parent(s): f873a98

feat: integrate WIGOS metadata, enhance station dashboard UI, and improve map navigation logic

Browse files
docs/architecture.md ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # WMO Normals Explorer Architecture
2
+
3
+ This document briefly outlines the core functionalities, technical implementation, and primary data workflows powering the **WMO Normals Explorer** application.
4
+
5
+ ## 1. Overview
6
+ The WMO Normals Explorer is an R/Shiny interactive web application designed to visualize and investigate the WMO Climatological Standard Normals (1991-2020). It allows users to quickly cross-filter by country, station, weather parameter, and time period, and seamlessly switch between map-based overviews and deep-dive dashboard analytics.
7
+
8
+ ## 2. Interface Layer (UI)
9
+ The application leverages the `bslib` framework alongside Bootstrap 5 for modern, responsive layouts and unified UI styling.
10
+
11
+ - **Map View:** The primary interface focuses on an interactive MapLibre map rendering thousands of stations as dynamic points coloured automatically by ECMWF and standard palettes based on weather parameter intensity. It features layer controls (switching between Positron, Bright, and Sentinel-2 satellite formats).
12
+ - **Dashboard Panel:** The deep-dive view features a responsive `bslib::card()` metadata header that mimics top-tier portals (such as MeteoGate). It displays WMO and local identifying strings, exact coordinates, and allows bulk CSV/Excel exports of the matrices. Below the metadata are modular parameter tables (using `DT`) and flexible `plotly` graphical windows (Walter-Lieth climate diagrams, time series).
13
+
14
+ ## 3. Server Logic (Back-end)
15
+ The core logic resides in `server.R` handling map reactive filtering across potentially large datasets without bogging down the main thread.
16
+
17
+ - **Reactive Filtering Architecture:** Instead of processing all data, the server holds robust pre-loaded `sf` (Simple Features) spatial vectors mapping variables (e.g. `tavg_sf`, `prcp_sf`). Filters systematically cascade down `active_dataset()` -> `filtered_stations_by_country()` -> `final_filtered_stations()`.
18
+ - **Dynamic Selection Management:** Whenever a station is clicked via `input$station_map_feature_click`, the application zooms smoothly, draws a highlight halo over the station, transitions immediately to the Dashboard panel, and cross-references its exact `WMO_ID` to populate matrix arrays over the diverse variables present.
19
+ - **Cross-Dataset Extraction:** A unified helper iterates across independent parameter DataFrames, plucking exact monthly arrays for the active WMO ID and securely binding them to construct the final wide-format table presented strictly to the user.
20
+
21
+ ## 4. Metadata Utility Workflows
22
+ Because WMO Normals files often only contain legacy WMO IDs, the explorer requires supplementary utilities to ingest modern identification semantics (like WIGOS identifiers and standardized coordinate precision from the ultimate authority).
23
+
24
+ ### WIGOS Metadata Lookup (`misc/fetch_wigos_metadata.R`)
25
+ This CLI script enriches our local datasets with WMO OSCAR/Surface parameters.
26
+ - **Bulk Extraction Optimization:** Point querying individual stations against the OSCAR `<api/search/station>` endpoint triggers long API timeouts due to the massive payloads (30MB+ JSON). The script solves this by immediately triggering a bulk-download of the entire database on first run, saving it into `oscar_station_cache.json`.
27
+ - **Dplyr Matrix Filtering:** When queried, the script performs near-instant local indexing against the cached payload.
28
+ - **`all` Strategy Mode:** Running `Rscript misc/fetch_wigos_metadata.R all` from the terminal traverses the local `data/` directory, extracts every distinct `WMO_ID` (or `ID`) from the `.csv` normals datasets, looks them up in the cached OSCAR matrix for `wigosId`, `name`, `elevation`, and exact GPS decimal combinations, and dumps a unified reference table locally (`wigos_metadata_all.csv`).
29
+
30
+ ## 5. Technology Stack
31
+ - **R / Shiny**: Main orchestration engine.
32
+ - **bslib / htmltools**: Rapid, responsive grid layouts.
33
+ - **sf / maplibre**: Accelerated point rendering for geospatial logic without slowing R.
34
+ - **plotly / DT**: High-density interactive widgets.
35
+ - **httr / jsonlite**: High-performance HTTP request tooling for metadata APIs.
misc/fetch_wigos_metadata.R ADDED
@@ -0,0 +1,121 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # fetch_wigos_metadata.R
2
+ # Script to fetch WIGOS metadata from the WMO OSCAR/Surface API
3
+
4
+ library(httr)
5
+ library(jsonlite)
6
+ library(dplyr)
7
+
8
+ # Function to fetch and cache the OSCAR database locally
9
+ get_oscar_database <- function(cache_file = "oscar_station_cache.json") {
10
+ if (file.exists(cache_file)) {
11
+ message("Loading OSCAR database from local cache...")
12
+ parsed_data <- fromJSON(cache_file, flatten = TRUE)
13
+ if ("stationSearchResults" %in% names(parsed_data)) {
14
+ return(parsed_data$stationSearchResults)
15
+ }
16
+ return(parsed_data)
17
+ }
18
+
19
+ message("Downloading OSCAR database (this may take a few minutes)...")
20
+ base_url <- "https://oscar.wmo.int/surface/rest/api/search/station"
21
+
22
+ resp <- tryCatch({
23
+ GET(base_url, query = list(itemsPerPage = 100000), timeout(300))
24
+ }, error = function(e) {
25
+ message(" -> Error: Request failed: ", e$message)
26
+ return(NULL)
27
+ })
28
+
29
+ if (is.null(resp) || status_code(resp) != 200) {
30
+ message(" -> Error: Bad response or timeout.")
31
+ return(NULL)
32
+ }
33
+
34
+ data_text <- content(resp, "text", encoding = "UTF-8")
35
+ writeLines(data_text, cache_file)
36
+
37
+ parsed_data <- fromJSON(data_text, flatten = TRUE)
38
+ if ("stationSearchResults" %in% names(parsed_data)) {
39
+ return(parsed_data$stationSearchResults)
40
+ }
41
+ return(parsed_data)
42
+ }
43
+
44
+ # Function to lookup WIGOS metadata for a single or multiple WMO IDs
45
+ lookup_wigos_bulk <- function(oscar_db, wmo_ids) {
46
+ wmo_id_strs <- as.character(wmo_ids)
47
+
48
+ # Ensure the OSCAR DB has wmoIndex extracted clearly
49
+ if (!"wmoIndex" %in% names(oscar_db)) {
50
+ # Attempt to extract from wigosId if wmoIndex is missing
51
+ oscar_db <- oscar_db %>%
52
+ mutate(wmoIndex = sub("^.*-", "", wigosId))
53
+ }
54
+
55
+ # Create a tibble of target IDs
56
+ targets <- tibble(WMO_ID = wmo_id_strs)
57
+
58
+ # Clean and prepare OSCAR data for matching
59
+ oscar_clean <- oscar_db %>%
60
+ filter(!is.na(wmoIndex), wmoIndex != "") %>%
61
+ select(wmoIndex, wigosId, name, latitude, longitude, elevation) %>%
62
+ # In case of duplicates in OSCAR, take the first one
63
+ group_by(wmoIndex) %>%
64
+ slice(1) %>%
65
+ ungroup()
66
+
67
+ # Perform left join
68
+ res <- targets %>%
69
+ left_join(oscar_clean, by = c("WMO_ID" = "wmoIndex")) %>%
70
+ mutate(
71
+ WIGOS_ID = as.character(wigosId),
72
+ Station_Name_OSCAR = as.character(name),
73
+ Latitude_OSCAR = as.numeric(latitude),
74
+ Longitude_OSCAR = as.numeric(longitude),
75
+ Elevation_OSCAR = as.numeric(elevation)
76
+ ) %>%
77
+ select(WMO_ID, WIGOS_ID, Station_Name_OSCAR, Latitude_OSCAR, Longitude_OSCAR, Elevation_OSCAR)
78
+
79
+ return(res)
80
+ }
81
+
82
+ # Example usage (can be executed directly if this script is sourced)
83
+ if (!interactive()) {
84
+ args <- commandArgs(trailingOnly = TRUE)
85
+
86
+ oscar_db <- get_oscar_database()
87
+
88
+ if (!is.null(oscar_db)) {
89
+ if (length(args) > 0) {
90
+ if (tolower(args[1]) == "all") {
91
+ message("Updating WIGOS metadata for all stations in data/ folder...")
92
+ csv_files <- list.files("data", pattern="\\.csv$", full.names=TRUE)
93
+ all_ids <- c()
94
+ for(f in csv_files) {
95
+ try({
96
+ df <- read.csv(f, stringsAsFactors=FALSE)
97
+ if("ID" %in% names(df)) all_ids <- c(all_ids, as.character(df$ID))
98
+ if("WMO_ID" %in% names(df)) all_ids <- c(all_ids, as.character(df$WMO_ID))
99
+ }, silent=TRUE)
100
+ }
101
+ unique_ids <- unique(all_ids)
102
+ message(sprintf("Found %d unique WMO IDs.", length(unique_ids)))
103
+ if(length(unique_ids) > 0) {
104
+ results <- lookup_wigos_bulk(oscar_db, unique_ids)
105
+ write.csv(results, "wigos_metadata_all.csv", row.names=FALSE)
106
+ message("Successfully saved metadata to wigos_metadata_all.csv")
107
+ }
108
+ } else {
109
+ wmo_inputs <- args
110
+ results <- lookup_wigos_bulk(oscar_db, wmo_inputs)
111
+ print(results)
112
+ }
113
+ } else {
114
+ message("No WMO IDs provided. Testing with 15420 (Bucharest/Baneasa).")
115
+ message("Hint: Run with 'Rscript misc/fetch_wigos_metadata.R all' to run on all stations.")
116
+ test_result <- lookup_wigos_bulk(oscar_db, c("15420"))
117
+ print(test_result)
118
+ }
119
+ }
120
+ }
121
+
oscar_station_cache.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:47b831c1d2ce7eade26899091a619cac6a210209f3db25dde111b4c34b6eb3f3
3
+ size 39751999
server.R CHANGED
@@ -46,14 +46,8 @@ server <- function(input, output, session) {
46
 
47
  # Final reactive dataset based on both filters a user selects
48
  final_filtered_stations <- reactive({
49
- req(input$station)
50
  data <- filtered_stations_by_country()
51
-
52
  req(!is.null(data))
53
- if (input$station != "All") {
54
- data <- data %>% filter(Station_Name == input$station)
55
- }
56
-
57
  data
58
  })
59
 
@@ -325,11 +319,40 @@ server <- function(input, output, session) {
325
 
326
  # Navigation lock bounds logic
327
  if (input$station != "All") {
328
- map %>% fit_bounds(data, max_zoom = 8, animate = TRUE)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
329
  } else if (input$country != "All") {
330
- # Added padding=100 and animate=TRUE to fly smoothly out a bit loosely around bounds
331
  map %>% fit_bounds(data, padding = 100, animate = TRUE)
332
  } else {
 
333
  map %>% fly_to(center = c(initial_lng, initial_lat), zoom = initial_zoom)
334
  }
335
  } else {
@@ -390,7 +413,7 @@ server <- function(input, output, session) {
390
  circle_stroke_width = 2,
391
  circle_opacity = 0.4
392
  ) %>%
393
- fly_to(center = c(sta_lon, sta_lat), zoom = 9)
394
 
395
  # Automatically transition to Dashboard Tab immediately
396
  nav_select("main_nav", "Dashboard")
@@ -415,15 +438,45 @@ server <- function(input, output, session) {
415
  station_name <- meta_df$Station_Name[1]
416
  country <- meta_df$Country[1]
417
  elev <- meta_df$Elevation[1]
 
 
418
 
419
- tagList(
420
- div(
421
- class = "data-info-box",
422
- style = "max-width: 600px; margin-top: 0;",
423
- div(class = "data-info-title", style = "font-size: 1.2rem; color: #007bff;", station_name),
424
- div(class = "data-info-item", span(class = "fw-bold", "Country:"), paste(" ", country)),
425
- div(class = "data-info-item", span(class = "fw-bold", "WMO ID:"), paste(" ", wmo)),
426
- div(class = "data-info-item", span(class = "fw-bold", "Elevation:"), paste(" ", elev, "m"))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
427
  )
428
  )
429
  } else {
 
46
 
47
  # Final reactive dataset based on both filters a user selects
48
  final_filtered_stations <- reactive({
 
49
  data <- filtered_stations_by_country()
 
50
  req(!is.null(data))
 
 
 
 
51
  data
52
  })
53
 
 
319
 
320
  # Navigation lock bounds logic
321
  if (input$station != "All") {
322
+ target_station <- data %>% filter(Station_Name == input$station)
323
+ if (nrow(target_station) > 0) {
324
+ sta_lon <- target_station$Longitude[1]
325
+ sta_lat <- target_station$Latitude[1]
326
+ click_id <- target_station$WMO_ID[1]
327
+
328
+ clicked_wmo_id(click_id)
329
+
330
+ hl_pt <- sf::st_as_sf(
331
+ data.frame(x = sta_lon, y = sta_lat),
332
+ coords = c("x", "y"),
333
+ crs = 4326
334
+ )
335
+
336
+ map %>%
337
+ clear_layer("selected_highlight") %>%
338
+ add_circle_layer(
339
+ id = "selected_highlight",
340
+ source = hl_pt,
341
+ circle_color = "red",
342
+ circle_radius = 12,
343
+ circle_stroke_color = "white",
344
+ circle_stroke_width = 2,
345
+ circle_opacity = 0.4
346
+ ) %>%
347
+ fly_to(center = c(sta_lon, sta_lat), zoom = 8)
348
+
349
+ nav_select("main_nav", "Dashboard")
350
+ }
351
  } else if (input$country != "All") {
352
+ map %>% clear_layer("selected_highlight")
353
  map %>% fit_bounds(data, padding = 100, animate = TRUE)
354
  } else {
355
+ map %>% clear_layer("selected_highlight")
356
  map %>% fly_to(center = c(initial_lng, initial_lat), zoom = initial_zoom)
357
  }
358
  } else {
 
413
  circle_stroke_width = 2,
414
  circle_opacity = 0.4
415
  ) %>%
416
+ fly_to(center = c(sta_lon, sta_lat), zoom = 8)
417
 
418
  # Automatically transition to Dashboard Tab immediately
419
  nav_select("main_nav", "Dashboard")
 
438
  station_name <- meta_df$Station_Name[1]
439
  country <- meta_df$Country[1]
440
  elev <- meta_df$Elevation[1]
441
+ lat <- meta_df$Latitude[1]
442
+ lon <- meta_df$Longitude[1]
443
 
444
+ card(
445
+ style = "margin-bottom: 20px; border-left: 5px solid #007bff;",
446
+ card_body(
447
+ padding = 15,
448
+ layout_columns(
449
+ fill = FALSE,
450
+ col_widths = breakpoints(sm = c(6, 6, 6, 12), lg = c(4, 3, 3, 2)),
451
+ # Col 1: Station
452
+ div(
453
+ strong("Station"), br(),
454
+ span(paste0(station_name, " (", country, ")"), style = "font-size: 1.1rem;"), br(),
455
+ tags$small(class = "text-muted", paste("WMO ID:", wmo))
456
+ ),
457
+ # Col 2: Location
458
+ div(
459
+ strong("Location"), br(),
460
+ span(country), br(),
461
+ tags$small(class = "text-muted", paste0(lat, "°N, ", lon, "°E"))
462
+ ),
463
+ # Col 3: Elevation
464
+ div(
465
+ strong("Technical"), br(),
466
+ span(paste0("Elevation: ", elev, " m")), br(),
467
+ span(class = "badge bg-primary", "WMO Normals 1991-2020")
468
+ ),
469
+ # Col 4: Actions
470
+ div(
471
+ class = "d-flex align-items-center justify-content-end",
472
+ downloadButton(
473
+ "download_normals",
474
+ label = "Export CSV",
475
+ class = "btn-sm btn-success",
476
+ icon = icon("file-excel")
477
+ )
478
+ )
479
+ )
480
  )
481
  )
482
  } else {
ui.R CHANGED
@@ -120,10 +120,6 @@ ui <- page_navbar(
120
  style = "padding: 20px;",
121
  uiOutput("dashboard_header"),
122
  hr(),
123
- div(
124
- style = "text-align: right; margin-bottom: 10px;",
125
- downloadButton("download_normals", "Export CSV", class = "btn-success", icon = icon("file-excel"))
126
- ),
127
  DT::DTOutput("dashboard_data"),
128
  div(
129
  style = "margin-top: 20px; margin-bottom: 20px;",
 
120
  style = "padding: 20px;",
121
  uiOutput("dashboard_header"),
122
  hr(),
 
 
 
 
123
  DT::DTOutput("dashboard_data"),
124
  div(
125
  style = "margin-top: 20px; margin-bottom: 20px;",
wigos_metadata_all.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:fd657c6c3ba68a6c8c909d04a27dd0c95261a99e80dedba9a47fd8020c5e7a7e
3
+ size 324606