# fetch_wigos_metadata.R # Script to fetch WIGOS metadata from the WMO OSCAR/Surface API library(httr) library(jsonlite) library(dplyr) # Function to fetch and cache the OSCAR database locally get_oscar_database <- function(cache_file = "oscar_station_cache.json") { if (file.exists(cache_file)) { message("Loading OSCAR database from local cache...") parsed_data <- fromJSON(cache_file, flatten = TRUE) if ("stationSearchResults" %in% names(parsed_data)) { return(parsed_data$stationSearchResults) } return(parsed_data) } message("Downloading OSCAR database (this may take a few minutes)...") base_url <- "https://oscar.wmo.int/surface/rest/api/search/station" resp <- tryCatch({ GET(base_url, query = list(itemsPerPage = 100000), timeout(300)) }, error = function(e) { message(" -> Error: Request failed: ", e$message) return(NULL) }) if (is.null(resp) || status_code(resp) != 200) { message(" -> Error: Bad response or timeout.") return(NULL) } data_text <- content(resp, "text", encoding = "UTF-8") writeLines(data_text, cache_file) parsed_data <- fromJSON(data_text, flatten = TRUE) if ("stationSearchResults" %in% names(parsed_data)) { return(parsed_data$stationSearchResults) } return(parsed_data) } # Function to lookup WIGOS metadata for a single or multiple WMO IDs lookup_wigos_bulk <- function(oscar_db, wmo_ids) { wmo_id_strs <- as.character(wmo_ids) # Ensure the OSCAR DB has wmoIndex extracted clearly if (!"wmoIndex" %in% names(oscar_db)) { oscar_db <- oscar_db %>% mutate(wmoIndex = sub("^.*-", "", wigosId)) } # Create a tibble of target IDs with normalized match key targets <- tibble(WMO_ID = wmo_id_strs) %>% mutate(match_key = sub("^0+", "", trimws(WMO_ID))) # Clean and prepare OSCAR data for matching (strip leading zeros for robust matching) oscar_clean <- oscar_db %>% filter(!is.na(wmoIndex), wmoIndex != "") %>% mutate(match_key = sub("^0+", "", trimws(as.character(wmoIndex)))) %>% filter(nzchar(match_key)) %>% select(match_key, wigosId, name, latitude, longitude, elevation) %>% # In case of duplicates in OSCAR, take the first one group_by(match_key) %>% slice(1) %>% ungroup() # Perform left join res <- targets %>% left_join(oscar_clean, by = "match_key") %>% mutate( WIGOS_ID = as.character(wigosId), Station_Name_OSCAR = as.character(name), Latitude_OSCAR = as.numeric(latitude), Longitude_OSCAR = as.numeric(longitude), Elevation_OSCAR = as.numeric(elevation) ) %>% select(WMO_ID, WIGOS_ID, Station_Name_OSCAR, Latitude_OSCAR, Longitude_OSCAR, Elevation_OSCAR) return(res) } # Example usage (can be executed directly if this script is sourced) if (!interactive()) { args <- commandArgs(trailingOnly = TRUE) oscar_db <- get_oscar_database() if (!is.null(oscar_db)) { if (length(args) > 0) { if (tolower(args[1]) == "all") { message("Updating WIGOS metadata for all stations in data/ folder...") csv_files <- list.files("data", pattern = "^wmo_normals_.*\\.csv$", full.names = TRUE) all_ids <- c() for(f in csv_files) { try({ df <- read.csv(f, stringsAsFactors = FALSE) if("ID" %in% names(df)) all_ids <- c(all_ids, as.character(df$ID)) if("WMO_ID" %in% names(df)) all_ids <- c(all_ids, as.character(df$WMO_ID)) }, silent = TRUE) } unique_ids <- unique(all_ids[!is.na(all_ids) & nzchar(trimws(all_ids))]) message(sprintf("Found %d unique WMO IDs.", length(unique_ids))) if(length(unique_ids) > 0) { results <- lookup_wigos_bulk(oscar_db, unique_ids) write.csv(results, "wigos_metadata_all.csv", row.names = FALSE) message("Successfully saved metadata to wigos_metadata_all.csv") } } else { wmo_inputs <- args results <- lookup_wigos_bulk(oscar_db, wmo_inputs) print(results) } } else { message("No WMO IDs provided. Testing with 15420 (Bucharest/Baneasa).") message("Hint: Run with 'Rscript misc/fetch_wigos_metadata.R all' to run on all stations.") test_result <- lookup_wigos_bulk(oscar_db, c("15420")) print(test_result) } } }