findNLDI.R 13.1 KB
Newer Older
mike's avatar
mike committed
1
#' @title Trim and Cull NULLs
mike's avatar
mike committed
2
3
4
5
#' @description Remove NULL arguments from a named list
#' @param x a list
#' @keywords nldi internal
#' @return a list
mike's avatar
mike committed
6
#' @noRd
mike's avatar
mike committed
7
8
9
10
11

tc <- function(x) {
  Filter(Negate(is.null), x)
}

12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#' @title Find Good Names
#' @description minimize names of returned features
#' @param input data returned from NLDI
#' @param type type of return
#' @keywords nldi internal
#' @return a list
#' @noRd

find_good_names = function(input, type) {
  # The features names are different across features, navigation, and basin returns
  # This sets the environment for what to expect
  if (type == "nav") {
    grep("comid", names(input), value = TRUE)
  } else if (type == "feature") {
    c("sourceName", "identifier", "comid")
  } else {
    NULL
  }
}

mike's avatar
mike committed
32
33
34
35
36
37
38
39
#' @title Get current NLDI offerings
#' @description Used to query the current resources available through the NLDI
#' @return data.frame
#' @export
#' @keywords nldi
#' @importFrom httr RETRY content
#' @importFrom jsonlite fromJSON
#' @examples
40
#' \donttest{
mike's avatar
mike committed
41
#' get_nldi_sources()
42
#' }
mike's avatar
mike committed
43
get_nldi_sources <- function() {
mike's avatar
mike committed
44
45
46
47
48
  res <-
    httr::RETRY("GET",
                pkg.env$nldi_base,
                times = 3,
                pause_cap = 60)
49
  
mike's avatar
mike committed
50
  if (res$status_code == 200) {
51
52
53
54
    jsonlite::fromJSON(httr::content(res, "text",
                                     encoding = "UTF8"),
                       simplifyDataFrame = TRUE)
    
mike's avatar
mike committed
55
56
57
58
59
60
  } else {
    message("Error in: ",  url)
  }
}

#' @title Query NLDI
61
62
63
64
#' @description Queries the NLDI for a given URL. If local sf install is
#' available the function returns a sf data.frame.
#' If the object requested is a POINT object, the XY coordinates are added
#' as columns. Otherwise the columns returned are "sourceName" and
65
#' "identifier" for features, and "nhdplus_comid".
mike's avatar
mike committed
66
67
68
69
#' @param url the URL to retrieve
#' @param type the type of data being returned (nav or feature)
#' @param use_sf should a local sf install be usedto parse data
#' @keywords nldi internal
mike's avatar
mike committed
70
#' @noRd
mike's avatar
mike committed
71
72
73
74
#' @return a data.frame
#' @importFrom httr content RETRY
#' @importFrom jsonlite fromJSON
#' @examples
75
#' \donttest{
mike's avatar
mike committed
76
77
78
#'  base = "https://labs.waterdata.usgs.gov/api/nldi/linked-data/"
#'  get_nldi(paste0(base, "comid/101"), type = "feature", use_sf = FALSE)
#'  get_nldi(paste0(base, "comid/101"), type = "feature", use_sf = TRUE)
mike's avatar
mike committed
79
#'  get_nldi(url = paste0(base, "nwissite/USGS-11120000"), type = "feature", use_sf = TRUE)
mike's avatar
mike committed
80
81
#'  get_nldi(paste0(base, "nwissite/USGS-11120000"), type = "feature", use_sf = TRUE)
#'  }
82
get_nldi = function(url, type = "", use_sf = FALSE) {
mike's avatar
mike committed
83
84
  # Query
  res <- httr::RETRY("GET", url, times = 3, pause_cap = 60)
85
  
mike's avatar
mike committed
86
  # If successful ...
87
  if (res$status_code == 200) {
mike's avatar
mike committed
88
89
    # Interpret as text
    d <- httr::content(res, "text", encoding = "UTF8")
90
91
    
    if (d == "") {
mike's avatar
mike committed
92
93
      message("No data returned for: ", url, call. = FALSE)
      return(NULL)
mike's avatar
mike committed
94
    }
95
96
    
    if (use_sf) {
mike's avatar
mike committed
97
      #Parse with sf
98
99
100
      tmp <- sf::read_sf(d)
      good_name = find_good_names(tmp, type)
      
mike's avatar
mike committed
101
      # if of type POINT at the X,Y coordinates as columns
102
103
104
105
106
107
      if (sf::st_geometry_type(tmp)[1] == "POINT") {
        tmp$X <- sf::st_coordinates(tmp)[, 1]
        tmp$Y <- sf::st_coordinates(tmp)[, 2]
        
        tmp <- tmp[, c(good_name, "X", "Y")]
        
mike's avatar
mike committed
108
109
      } else {
        # If line/polygon then keep geometry but don't expand
110
111
        tmp <- tmp[, c(good_name, attr(tmp, "sf_column"))]
        
mike's avatar
mike committed
112
      }
113
114
115
      # Returning as data.frame drops the geometry column ...
      return(tmp)
      
mike's avatar
mike committed
116
117
118
    } else {
      # Parse as simplified JSON
      d <- jsonlite::fromJSON(d, simplifyDataFrame = TRUE)
119
      
mikejohnson51's avatar
mikejohnson51 committed
120
121
122
      input <-  d$features$properties
      
      good_name = find_good_names(input, type)
123
      
mike's avatar
mike committed
124
      # if of type POINT at the X,Y coordinates as columns
125
      if (d$features$geometry$type[1] == "Point") {
mike's avatar
mike committed
126
        geom = d$features$geometry$coordinates
127
        
mikejohnson51's avatar
mikejohnson51 committed
128
        tmp = cbind(input[, good_name], do.call(rbind, geom))
129
        
mike's avatar
mike committed
130
        names(tmp) <- c(good_name, "X", "Y")
131
        
mike's avatar
mike committed
132
        return(tmp)
133
        
mike's avatar
mike committed
134
135
      } else {
        # If line/polygon then keep geometry but don't expand
mikejohnson51's avatar
mikejohnson51 committed
136
        return(input[, good_name])
mike's avatar
mike committed
137
138
      }
    }
139
140
141
142
    
  } else {
    message("Error in: ",  url)
  }
mike's avatar
mike committed
143
144
145
}

#' Clean NWIS NLDI ids
146
147
#' @description The NWIS ids come as "USGS-XXXXXXXX". This is not suitable for 
#' passing to other package functions like readNWISdv.
mike's avatar
mike committed
148
#' This function strips the "USGS-" from these ids.
mike's avatar
mike committed
149
150
#' @param tmp a data.frame retrieved from get_nldi()
#' @return the input object with potentially modified identifiers
mike's avatar
mike committed
151
#' @keywords nldi internal
mike's avatar
mike committed
152
#' @noRd
mike's avatar
mike committed
153
clean_nwis_ids = function(tmp) {
mike's avatar
mike committed
154
  # If data.frame, and of type NWIS, then strip "USGS-" from identifiers
155
  if (is.data.frame(tmp)) {
156
    if ("sourceName" %in% names(tmp) &&
157
        tmp$sourceName[1] == "NWIS Sites") {
mike's avatar
mike committed
158
      tmp$identifier = gsub("USGS-", "", tmp$identifier)
159
      
mike's avatar
mike committed
160
161
162
163
164
165
    }
  }
  tmp
}

#' @title NLDI Validity Check
mike's avatar
mike committed
166
167
168
#' @description tests if NLDI feature is available. Is vectorized and works with partial string matching.
#' @param all a data.frame of available features (see get_nldi_sources)
#' @param type type(s) to check (character)
mike's avatar
mike committed
169
170
#' @return a list with good and bad entries
#' @keywords nldi internal
mike's avatar
mike committed
171
#' @noRd
mike's avatar
mike committed
172
#' @examples
173
#' \donttest{
174
#' valid_ask(all = get_nldi_sources(), "nwis")
mike's avatar
mike committed
175
#' }
176
valid_ask = function(all, type) {
mike's avatar
mike committed
177
  # those where the requested pattern is included in a nldi_source ...
178
179
180
  # means we will catch nwis - not just nwissite ...
  # means we will catch both wqp and WQP ...
  
181
  ### WOW! This is hacky and will hopefully be unneeded latter on....
182
183
184
185
186
187
188
189
190
191
192
  type = ifelse(type == "nwis", "nwissite", type)
  all = rbind(all, c("flowlines", "NHDPlus comid", NA))
  
  good  <-
    grepl(paste0(tolower(type), collapse = "|"), tolower(c(all$source)))
  
  bad <-
    grepl(paste0(tolower(all$source), collapse = "|"), tolower(c(all$source)))
  
  list(good = all[good, ], bad = type[!bad])
  
mike's avatar
mike committed
193
194
}

195
196
#' @title R Client for the Network Linked Data Index
#' @description Provides a formal client to the USGS
mike's avatar
mike committed
197
#' \href{https://labs.waterdata.usgs.gov/about-nldi/index.html}{Network Linked Data Index}.
198
199
200
201
202
203
#' @details The function is useful for topology and location based
#' feature discovery. A user must specify an origin feature, optional navigation
#' direction(s) along the network, as well as features to identify along the
#' navigated paths. Valid starting options can be given by one of the following
#' arguments: comid, nwis, huc12, wqp, location, and start.
#' @param comid numeric or character. An NHDPlusV2 COMID
204
#' @param nwis  numeric or character. A USGS NWIS surface water siteID
205
206
207
208
209
210
211
212
213
214
215
216
217
#' @param wqp   numeric or character. A water quality point ID
#' @param huc12 numeric or character. A WBD HUC12 unit ID
#' @param location numeric vector. Coordinate pair in WGS84
#' SRS ordered lng/lat (X,Y)
#' @param origin named list. Specifying a feature type and ID
#' (e.g. list("comid" = 101))
#' @param nav character vector. where to navigate from the starting point.
#' Options include along the upper mainsteam (UM), upstream tributary (UT),
#' downstream mainstem (DM) and downstream divergences (DD). You may select
#' one or more of the abbreviations ("UM", "UT", DM", "DD").
#' @param find character vector. Define what resources to find along the
#' navigation path(s) (see get_nldi_sources()$source). Can also include 'basin'
#' or 'flowline', which will return the upstream basin of the starting feature
218
219
220
#' or flowlines along the navigation respectively. The default is "flowlines". 
#' If you provide any other resource, AND want flowlines, then flowlines must 
#' be explicitly requested.
221
222
223
224
225
#' @param distance_km numeric. Define how far to look along the navigation path in
#' kilometers (default = 100)
#' @param no_sf if available, should `sf` be used for parsing,
#' defaults to `TRUE` if `sf` is locally installed
#' @return a list of data.frames if sf is not installed, a list of sf objects if it is
mike's avatar
mike committed
226
227
228
#' @export
#' @keywords nldi
#' @examples
229
#' \donttest{
mike's avatar
mike committed
230
231
232
233
#' # Find Features / Define origin features
#'
#' ## Find feature by COMID
#'  findNLDI(comid = 101)
Laura A DeCicco's avatar
Laura A DeCicco committed
234
#'  
mike's avatar
mike committed
235
#' ## Find feature by NWIS ID
Laura A DeCicco's avatar
Laura A DeCicco committed
236
237
238
#'   findNLDI(nwis = '11120000')
#' 
#' ## Find feature by WQP ID 
mike's avatar
mike committed
239
240
241
242
243
244
245
246
247
248
249
#'  findNLDI(wqp = 'USGS-04024315')
#'
#' ## Find feature by LOCATION
#'  findNLDI(location = c(-115,40))
#'
#' ## GENERAL ORIGIN: COMID
#'  findNLDI(origin = list("comid" = 101))
#'
#' ## GENERAL ORIGIN: WaDE
#'  findNLDI(origin = list("wade" = 'CA_45206'))
#'
250
#' # Navigation (flowlines will be returned if find is unspecified)
mike's avatar
mike committed
251
#' # UPPER MAINSTEM of USGS-11120000
252
#'  findNLDI(nwis = '11120000', nav = "UM")
mike's avatar
mike committed
253
254
255
#'
#' # MULTI-REQUEST
#' # UPPER MAINSTEM and TRIBUTARY of USGS-11120000
256
#'  findNLDI(nwis = '11120000', nav = c("UT", "UM"))
mike's avatar
mike committed
257
#'
258
#' # Discover Features(flowlines will not be returned unless included in find)
mike's avatar
mike committed
259
260
#'
#' ## Find feature(s) on the upper tributary of USGS-11120000
mike's avatar
mike committed
261
#'  findNLDI(nwis = '11120000', nav = "UT", find = c("nwis", "wqp"))
mike's avatar
mike committed
262
#'
263
264
#' ## Find upstream basin boundary and  of USGS-11120000
#'  findNLDI(nwis = '11120000',  find = "basin")
mike's avatar
mike committed
265
266
#'
#' # Control Distance
267
268
#' ## Limit search to 50 km
#'  findNLDI(comid = 101, nav = "DM", find = c("nwis", "wqp", "flowlines"), distance_km = 50)
269
#'}
mike's avatar
mike committed
270
findNLDI <- function(comid = NULL,
271
272
273
274
275
276
277
278
279
                     nwis = NULL,
                     wqp = NULL,
                     huc12 = NULL,
                     location = NULL,
                     origin = NULL,
                     nav = NULL,
                     find = c("flowlines"),
                     distance_km = 100,
                     no_sf = FALSE) {
mike's avatar
mike committed
280
281
  # Should sf be used? Both no_sf and pkg.env must agree
  use_sf = all(pkg.env$local_sf, !no_sf)
282
  
mike's avatar
mike committed
283
  # Should the basin be identified?
mike's avatar
mike committed
284
  getBasin = ("basin" %in% find)
285
  
286
  # From the collection of possible origins, pick 1 and remove NULLS
mike's avatar
mike committed
287
288
289
290
291
292
293
294
295
296
  starter <- tc(c(
    list(
      comid = comid,
      nwis = nwis,
      wqp = wqp,
      huc12 = huc12,
      location = location
    ),
    origin
  ))
297
  
mike's avatar
mike committed
298
299
300
301
  # a single starting location must be given ...
  if (is.null(starter) | length(starter) > 1) {
    stop("Define a single starting point. Use `find` to identify other resources.")
  }
302
  
mike's avatar
mike committed
303
  # Ensure nav types are valid
304
  bad_nav <- !nav %in% c("UM", "UT", "DD", "DM")
305
  
mike's avatar
mike committed
306
  if (any(bad_nav)) {
307
    stop(nav[bad_nav], " not a valid navigation. Chose from: UM, UT, DD, DM")
mike's avatar
mike committed
308
  }
309
  
mike's avatar
mike committed
310
311
  # name of starter
  start_type = names(starter)
312
  
mike's avatar
mike committed
313
  # If location, ensure lng is first argument (hack for USA features)
mike's avatar
mike committed
314
  if (start_type == 'location') {
315
316
    if (any(grepl("sfc$|sf$", class(location))) & use_sf) {
      if (sf::st_geometry_type(location) != "POINT") {
317
318
        stop("Only POINT objects can be passed to location")
      }
319
      
320
321
      location  = sf::st_coordinates(location)
    } else {
322
323
324
      if (location[1] > 0) {
        stop("Provide location in the form c(lng,lat)")
      }
325
    }
326
327
    
    # Must convert location to COMID for tracing and discovery ...
328
    tmp_url <- paste0(
mike's avatar
mike committed
329
330
      pkg.env$nldi_base,
      "comid/position?coords=POINT%28",
331
332
333
334
      location[1] ,
      "%20",
      location[2] ,
      "%29"
mike's avatar
mike committed
335
    )
336
    
337
    tmp_return <- get_nldi(tmp_url, "feature", use_sf = use_sf)
338
    
mike's avatar
mike committed
339
    # Override starter with location based COMID
340
    starter <- list("comid" = tmp_return$identifier)
mike's avatar
mike committed
341
  }
342
  
mike's avatar
mike committed
343
  # Reset (if needed)
344
  start_type <- names(starter)
345
346
  
  if (is.null(pkg.env$current_nldi)) {
347
348
    pkg.env$current_nldi <- get_nldi_sources()
  }
349
  
mike's avatar
mike committed
350
  # Defining the origin URL.
351
352
  #  Align request with formal name from sources
  #  If NWIS, add "USGS-" prefix
mike's avatar
mike committed
353
  start_url = paste0(
354
355
356
357
    valid_ask(all = pkg.env$current_nldi, type = start_type)$good$features,
    "/",
    ifelse(start_type == "nwis", paste0("USGS-", starter), starter),
    "/"
mike's avatar
mike committed
358
  )
359
  
mike's avatar
mike committed
360
  # Makes sure that all requested features to `find` are valid and name-aligned
mike's avatar
mike committed
361
362
363
  if (!is.null(find)) {
    find = valid_ask(pkg.env$current_nldi, type = find)$good$source
  }
364
  
mike's avatar
mike committed
365
  # Set empty lists to store origin, navigation, features, and basin requests ...
366
  navigate <- features  <- list()
367
  
mike's avatar
mike committed
368
  # Build navigation URLs
mike's avatar
mike committed
369
  for (i in seq_along(nav)) {
370
    navigate[[nav[i]]] = paste0(start_url, "navigation/", nav[i])
mike's avatar
mike committed
371
  }
372
  
mike's avatar
mike committed
373
374
  # Build find URLs
  if (length(find) > 0) {
375
376
377
378
    features = lapply(navigate,
                      paste0,
                      paste0("/", find),
                      paste0("?distance=", distance_km))
mike's avatar
mike committed
379
  }
380
  
381
  names  <- unlist(lapply(nav, paste0, paste0("_", find)))
382
  
383
384
  search <- data.frame(
    url = unlist(c(start_url,
385
386
387
                   if (getBasin) {
                     paste0(start_url, "basin")
                   },
388
                   features)),
389
    
390
    type = c("feature",
391
392
393
394
395
396
397
             if (getBasin) {
               'basin'
             },
             ifelse(
               rep(find, length(nav)) == "flowlines", "nav", "feature"
             )),
    
398
    name = c("origin",
399
400
401
             if (getBasin) {
               'basin'
             },
402
403
             names[!names %in%  c("UM_", "UT_", "DD_", "DM_")])
  )
404
  
mike's avatar
mike committed
405
  # Send NLDI queries ...
406
  shp <- lapply(1:nrow(search), function(x) {
407
408
409
    get_nldi(url = search$url[x],
             type = search$type[x],
             use_sf = use_sf)
mike's avatar
mike committed
410
  })
411
  
mike's avatar
mike committed
412
  # Set the names of the parsed URL list
413
  names(shp) <- search$name
414
  
mike's avatar
mike committed
415
  # Clean up NWIS ids, trim NULLs, and return ...
416
  shp = tc(lapply(shp, clean_nwis_ids))
417
418
419
  
  # dont return list for one length elements
  if (length(shp) == 1) {
420
421
    shp = shp[[1]]
  }
422
  
423
  return(shp)
mike's avatar
mike committed
424
}