-
Notifications
You must be signed in to change notification settings - Fork 3
/
get_NOAA.R
236 lines (211 loc) · 6.74 KB
/
get_NOAA.R
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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
#' Obtain NOAA World Ocean Atlas dataset
#'
#' Retrieves data from the NOAA World Ocean Atlas.
#'
#' Functions to retrieve data from the
#' [NOAA World Ocean Atlas](https://www.ncei.noaa.gov/products/world-ocean-atlas)
#' . Data is an 3D array (longitude, latitude, and depth) and is loaded as a
#' [`stars`][stars::st_as_stars()] object. Check [`NOAA_data`] for available
#' variables, respective units and their citations. The function can automatically
#' cache the extracted files (default: `cache = FALSE`). The cached file will
#' then reside in the package's `extdata` directory.
#'
#' @seealso [Introduction to the stars package](https://r-spatial.github.io/stars/articles/stars1.html)
#'
#' @param var The chemical or physical variable of interest (possible choices:
#' `"temperature"`, `"phosphate"`, `"nitrate"`, `"silicate"`, `"oxygen"`,
#' `"salinity"`, `"density"`).
#' @param spat_res Spatial resolution, either 1 or 5 degree grid-cells (numeric)
#' .
#' @param av_period Temporal resolution, either `"annual"`, specific seasons
#' (e.g. `"winter"`), or month (e.g. `"August"`).
#' @param cache Caching the extracted NOAA file in the package's `extdata`
#' directory (default = `FALSE`). Size of individual files is around 12 Mb. Use
#' [list_NOAA()] to list cached data resources.
#'
#' @return [`stars`][stars::st_as_stars()] object or path.
#' @export
#'
#' @examples
#'
#' # path to NOAA server or local data source
#' url_parser("oxygen", 1, "annual")
#'
#' if (interactive()) {
#'
#' # retrieve NOAA data
#' get_NOAA("oxygen", 1, "annual")
#'
#' }
get_NOAA <- function(var, spat_res, av_period, cache = FALSE) {
# abbreviate variable
if (var == "silicate") {
v <- strsplit(var, "")[[1]][2]
} else if (var == "density") {
v <- "I"
} else {
v <- strsplit(var, "")[[1]][1]
}
# stat to extract
if (spat_res < 5) {
# standard set to objectively analyzed climatology for variable of interest
stat <- paste(v, "an", sep = "_")
} else {
# standard set to Statistical mean for variable of interest
stat <- paste(v, "mn", sep = "_")
}
# where is package
pkg_path <- fs::path_package("oceanexplorer")
# path
NOAA_path <- url_parser(var, spat_res, av_period, cache = cache)
if (!"external" %in% names(NOAA_path)) {
# get data and make stars
NOAA <- readRDS(fs::path(pkg_path, NOAA_path$local)) |> stars::st_as_stars()
} else {
# get netcdf
NOAA <- read_NOAA(NOAA_path$external, stat)
if (isTRUE(cache)) {
# write stars object if extracted from NOAA server
# create dir
fs::dir_create(pkg_path, fs::path_dir(NOAA_path$local))
# create file
saveRDS(NOAA, fs::path(pkg_path, NOAA_path$local))
}
}
# return object
NOAA
}
#' @rdname get_NOAA
#'
#' @export
url_parser <- function(var, spat_res, av_period, cache = FALSE) {
# temporal resolution
averaging_periods <- c("annual", month.name, "winter", "spring", "summer",
"autumn")
stopifnot(av_period %in% averaging_periods)
# base path to NCEI server
base_path <- "https://data.nodc.noaa.gov/thredds/dodsC/ncei/woa"
# grouped variables
chem <- c("phosphate", "nitrate", "silicate", "oxygen")
misc <- c("temperature", "salinity", "density")
# see https://www.ncei.noaa.gov/data/oceans/woa/WOA18/DOC/woa18documentation.pdf
# for metadata names
# recording range
if (var %in% chem) {
deca <- "all"
} else if (var %in% misc) {
deca <- "decav"
}
# abbreviate variable
if (var == "silicate") {
v <- strsplit(var, "")[[1]][2]
} else if (var == "density") {
v <- "I"
} else {
v <- strsplit(var, "")[[1]][1]
}
# averaging period
tp <- grep(av_period, averaging_periods, ignore.case = TRUE) - 1
tp <- sprintf(fmt = "%02.0f", tp)
# grid-cell size
gr <- if(spat_res > 1) "5d" else "01"
# complete file name
file <- paste0(paste("woa18", deca, paste0(v, tp), gr, sep = "_"), ".nc")
# complete file path
file_path <- paste(var, deca, if(spat_res > 1) "5deg" else "1.00", file,
sep = "/")
if (isTRUE(cache)) {
# where is package
pkg_path <- fs::path_package("oceanexplorer")
# create extdata if not already existing
if (!fs::dir_exists(fs::path(pkg_path, "extdata"))) {
fs::dir_create(fs::path(pkg_path, "extdata"))
}
}
# check whether exist locally (respesting conventions for paths of the OS)
local_path <- fs::path("extdata", fs::path_ext_remove(file_path), ext = "rds")
# if not exist make external path to server
noaa_path <- try(fs::path_package("oceanexplorer", local_path), silent = TRUE)
if (!inherits(noaa_path, "fs_path")) {
external_path <- paste(base_path, file_path, sep = "/")
pt <- list(external = external_path)
# caching also add local_path
if (isTRUE(cache)) {
pt <- append(pt, list(local = local_path))
}
pt
} else {
list(local = local_path)
}
}
#' List cached NOAA data files
#'
#' List all cached NOAA data files from package's `extdata` directory.
#'
#' @return A character vector containing the names of the files in the specified
#' directories (empty if there were no files). If a path does not exist or is
#' not a directory or is unreadable it is skipped.
#' @export
#'
#' @examples
#'
#' # show cached NOAA files
#' list_NOAA()
#'
list_NOAA <- function() {
# directory
cache_pkg <- try(
fs::path_package(package = "oceanexplorer", "extdata"),
silent = TRUE
)
if (inherits(cache_pkg, "try-error")) {
character(0)
} else {
# list files and delete them
list.files(cache_pkg, full.names = TRUE)
}
}
#-------------------------------------------------------------------------------
# not exportet
#-------------------------------------------------------------------------------
clean_cache <- function(...) {
list_NOAA() |> fs::file_delete()
}
# read the NOAA netcdf
read_NOAA <- function(conn, var) {
# make connection
nc <- RNetCDF::open.nc(conn)
# variable
lat <- RNetCDF::var.get.nc(nc, "lat")
lon <- RNetCDF::var.get.nc(nc, "lon")
depth <- RNetCDF::var.get.nc(nc, "depth")
lat_bnds <- RNetCDF::var.get.nc(nc, "lat_bnds")
lon_bnds <- RNetCDF::var.get.nc(nc, "lon_bnds")
depth_bnds <- RNetCDF::var.get.nc(nc, "depth_bnds")
attr <- RNetCDF::var.get.nc(nc, var)
# close connection
RNetCDF::close.nc(nc)
st <- stars::st_as_stars(attr) |>
stars::st_set_dimensions(
which = 1,
offset = min(lon_bnds),
delta = unique(diff(lon)),
refsys = sf::st_crs(4326),
names = "lon"
) |>
stars::st_set_dimensions(
which = 2,
offset = min(lat_bnds),
delta = unique(diff(lat)),
refsys = sf::st_crs(4326),
names = "lat"
) |>
stars::st_set_dimensions(
which = 3,
values = depth_bnds[1, ],
names = "depth"
)
# variable name
names(st) <- var
st
}