File size: 4,220 Bytes
4093a3b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ea4c284
 
 
 
 
 
 
 
 
846ccf2
 
 
 
 
 
 
4093a3b
 
 
 
 
ea4c284
46e39d6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ea4c284
46e39d6
ea4c284
 
46e39d6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ea4c284
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
wmo_translit_prep <- function(x) {
  if (is.null(x) || length(x) == 0) return(character(0))
  s <- ifelse(is.na(x), "", as.character(x))
  # Sanitize mixed-encoding CSV bytes without locale wide-char conversion
  s <- iconv(s, from = "UTF-8", to = "UTF-8", sub = "")
  s[is.na(s)] <- ""
  repl <- list(
    c("\xd0\xa2", "t"), c("\xd1\x82", "t"),
    c("\xc5\x82", "l"), c("\xc5\x81", "l"),
    c("\xc3\xb8", "o"), c("\xc3\x98", "o"),
    c("\xc3\xa6", "ae"), c("\xc3\x86", "ae"),
    c("\xc3\x9f", "ss")
  )
  for (pair in repl) {
    s <- gsub(pair[1], pair[2], s, fixed = TRUE, useBytes = TRUE)
  }
  enc <- suppressWarnings(iconv(s, from = "UTF-8", to = "ASCII//TRANSLIT", sub = ""))
  s <- tolower(ifelse(is.na(enc), s, enc))
  gsub("_+", " ", s, useBytes = TRUE)
}

wmo_slugify <- function(x) {
  s <- wmo_translit_prep(x)
  if (length(s) == 0) return(s)
  s <- gsub("[^a-z0-9]+", "-", s, useBytes = TRUE)
  gsub("^-+|-+$", "", s, useBytes = TRUE)
}

normalize_wmo_key <- function(x) {
  s <- wmo_translit_prep(x)
  if (length(s) == 0) return(s)
  trimws(gsub("\\s+", " ", s, useBytes = TRUE))
}

# Reusable robust parser for WMO CSV files
load_wmo_data <- function(filename) {
  filepath <- paste0("data/", filename)
  if(!file.exists(filepath)) return(st_sfc())
  
  df <- tryCatch(read.csv(filepath, stringsAsFactors = FALSE), error = function(e) data.frame())
  
  if(nrow(df) > 0) {
    df <- df %>% 
      mutate(Country = trimws(as.character(Country)), 
             Station_Name = trimws(as.character(Station)), 
             WMO_ID = as.character(ID)) %>% 
      filter(!is.na(Latitude), !is.na(Longitude),
             Latitude >= -90, Latitude <= 90,
             Longitude >= -180, Longitude <= 180,
             nzchar(Station_Name), nzchar(Country))

    if ("WIGOS_ID" %in% colnames(df)) {
      df$WIGOS_ID <- trimws(as.character(df$WIGOS_ID))
    }
    df$Station_Slug <- wmo_slugify(df$Station_Name)
      
    # Clean invalid Elevation sentinels (-9999, -999, -876.5, -99.9)
    if ("Elevation" %in% colnames(df)) {
      elev <- suppressWarnings(as.numeric(df$Elevation))
      elev[!is.na(elev) & (elev < -450 | elev > 9000 | abs(elev - (-99.9)) < 1e-4)] <- NA_real_
      df$Elevation <- elev
    }

    # Resolve parameter code from filename (fallback to Elem column)
    param_code <- sub("^wmo_normals_\\d+_([A-Z0-9]+)_.*$", "\\1", basename(filename))
    if (identical(param_code, basename(filename)) && "Elem" %in% colnames(df)) {
      param_code <- trimws(as.character(df$Elem[1]))
    }

    dp01_limits <- c(
      Jan = 31, Feb = 29.25, Mar = 31, Apr = 30, May = 31, Jun = 30,
      Jul = 31, Aug = 31, Sep = 30, Oct = 31, Nov = 30, Dec = 31, Annual = 366
    )
    tsun_limits <- c(
      Jan = 744, Feb = 696, Mar = 744, Apr = 720, May = 744, Jun = 720,
      Jul = 744, Aug = 744, Sep = 720, Oct = 744, Nov = 720, Dec = 744, Annual = 4500
    )

    # Convert months and Annual to numeric and enforce sentinel + physical bounds QC
    time_cols <- c("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", "Annual")

    for (col in time_cols) {
      if (col %in% colnames(df)) {
        v <- suppressWarnings(as.numeric(df[[col]]))
        v[!is.na(v) & (v <= -99.0 | v >= 32760)] <- NA_real_

        if (param_code %in% c("TAVG", "TMAX", "TMIN")) {
          v[!is.na(v) & (v < -90 | v > 60)] <- NA_real_
        } else if (identical(param_code, "PRCP")) {
          max_prcp <- if (identical(col, "Annual")) 15000 else 5000
          v[!is.na(v) & (v < 0 | v > max_prcp)] <- NA_real_
        } else if (identical(param_code, "MSLP")) {
          v[!is.na(v) & (v < 870 | v > 1085)] <- NA_real_
        } else if (identical(param_code, "MNVP")) {
          v[!is.na(v) & (v < 0 | v > 100)] <- NA_real_
        } else if (identical(param_code, "DP01")) {
          v[!is.na(v) & (v < 0 | v > dp01_limits[[col]])] <- NA_real_
        } else if (identical(param_code, "TSUN")) {
          v[!is.na(v) & (v < 0 | v > tsun_limits[[col]])] <- NA_real_
        }

        df[[col]] <- v
      }
    }
      
    if(nrow(df) > 0) {
      return(st_as_sf(df, coords = c("Longitude", "Latitude"), crs = 4326, remove = FALSE))
    }
  }
  return(st_sfc())
}