importNGWMN_wml2.R 8.35 KB
Newer Older
David Watkins's avatar
David Watkins committed
1
#' Function to return data from the National Ground Water Monitoring Network waterML2 format
2
3
4
#'
#' This function accepts a url parameter for a WaterML2 getObservation. This function is still under development,
#' but the general functionality is correct.
David Watkins's avatar
David Watkins committed
5
#' 
6
7
#' @param input character or raw, containing the url for the retrieval or a path to the data file, or raw XML.
#' @param asDateTime logical, if \code{TRUE} returns date and time as POSIXct, if \code{FALSE}, character
Laura A DeCicco's avatar
Laura A DeCicco committed
8
9
#' @param tz character to set timezone attribute of datetime. Default is UTC (properly accounting for daylight savings times based on the data's provided time zone offset).
#' Possible values include "America/New_York","America/Chicago", "America/Denver","America/Los_Angeles",
10
#' "America/Anchorage","America/Honolulu","America/Jamaica","America/Managua","America/Phoenix", and "America/Metlakatla"
David Watkins's avatar
David Watkins committed
11
#' @return mergedDF a data frame source, time, value, uom, uomTitle, comment, gmlID
12
13
14
15
16
#' @export
#' @importFrom xml2 read_xml
#' @importFrom xml2 xml_find_all
#' @importFrom xml2 xml_text
#' @importFrom xml2 xml_attr
17
#' @importFrom xml2 xml_find_first
18
19
#' @importFrom lubridate parse_date_time
#' @examples
David Watkins's avatar
David Watkins committed
20
#' \dontrun{
Laura A DeCicco's avatar
Laura A DeCicco committed
21
22
23
24
25
#' obs_url <- paste("http://cida.usgs.gov/ngwmn_cache/sos?request=GetObservation",
#' "service=SOS","version=2.0.0",
#' "observedProperty=urn:ogc:def:property:OGC:GroundWaterLevel",
#' "responseFormat=text/xml",
#' "featureOfInterest=VW_GWDP_GEOSERVER.USGS.403836085374401",sep="&")
Laura A DeCicco's avatar
Laura A DeCicco committed
26
#' data <- importNGWMN(obs_url)
David Watkins's avatar
David Watkins committed
27
#' 
Laura A DeCicco's avatar
Laura A DeCicco committed
28
29
30
31
32
#' obs_url <- paste("http://cida.usgs.gov/ngwmn_cache/sos?request=GetObservation",
#' "service=SOS","version=2.0.0",
#' "observedProperty=urn:ogc:def:property:OGC:GroundWaterLevel",
#' "responseFormat=text/xml",
#' "featureOfInterest=VW_GWDP_GEOSERVER.USGS.474011117072901",sep="&")
Laura A DeCicco's avatar
Laura A DeCicco committed
33
#' data <- importNGWMN(obs_url)
David Watkins's avatar
David Watkins committed
34
#' }
David Watkins's avatar
David Watkins committed
35
#' 
Laura A DeCicco's avatar
Laura A DeCicco committed
36
37
importNGWMN <- function(input, asDateTime=FALSE, tz="UTC"){
  
38
  if(tz != ""){
David Watkins's avatar
David Watkins committed
39
    tz <- match.arg(tz, OlsonNames())
40
41
42
43
44
45
46
47
48
49
50
51
  }else{tz = "UTC"}
  
  raw <- FALSE
  if(class(input) == "character" && file.exists(input)){
    returnedDoc <- read_xml(input)
  }else if(class(input) == 'raw'){
    returnedDoc <- read_xml(input)
    raw <- TRUE
  } else {
    returnedDoc <- xml_root(getWebServiceData(input, encoding='gzip'))
  }
  
David Watkins's avatar
David Watkins committed
52
53
54
55
56
57
58
59
60
61
62
  response <- xml_name(returnedDoc)
  if(response == "GetObservationResponse"){
    
    timeSeries <- xml_find_all(returnedDoc, "//wml2:MeasurementTimeseries") #each parameter/site combo
    
    if(0 == length(timeSeries)){
      df <- data.frame()
      if(!raw){
        attr(df, "url") <- input
      }
      return(df)
63
64
    }
    
David Watkins's avatar
David Watkins committed
65
    mergedDF <- NULL
66
    
David Watkins's avatar
David Watkins committed
67
    for(t in timeSeries){
Laura A DeCicco's avatar
Laura A DeCicco committed
68
      df <- importWaterML2(t, asDateTime, tz)
69
      
David Watkins's avatar
David Watkins committed
70
71
72
73
74
75
      if (is.null(mergedDF)){
        mergedDF <- df
      } else {
        similarNames <- intersect(colnames(mergedDF), colnames(df))
        mergedDF <- full_join(mergedDF, df, by=similarNames)
      }
76
    }
David Watkins's avatar
David Watkins committed
77
78
79
80
81
    
    if(!raw){
      url <- input
      attr(mergedDF, "url") <- url
    }
David Watkins's avatar
David Watkins committed
82
83
84
    if(asDateTime){
      mergedDF$date <- as.Date(mergedDF$date)
    }
85
86
87
    nonDateCols <- grep("date",names(mergedDF), value=TRUE, invert = TRUE)
    
    mergedDF[nonDateCols][mergedDF[nonDateCols] == "" | mergedDF[nonDateCols]== -999999.0] <- NA
David Watkins's avatar
David Watkins committed
88
89
    attr(mergedDF, "gml:identifier") <- xml_text(xml_find_all(returnedDoc, ".//gml:identifier")) 
    attr(mergedDF, "generationDate") <- xml_text(xml_find_all(returnedDoc, ".//wml2:generationDate")) 
90
91
92
93
    meta <- xml_find_all(returnedDoc, ".//gmd:contact")
    attr(mergedDF, "contact") <- xml_attr(meta, "href")
    attr(mergedDF, "responsibleParty") <- xml_text(xml_find_all(meta, ".//gco:CharacterString"))
    
David Watkins's avatar
David Watkins committed
94
95
    
  }else if(response == "GetFeatureOfInterestResponse"){
96
97
    featureMembers <- xml_find_all(returnedDoc, ".//sos:featureMember")
    site <- xml_text(xml_find_all(featureMembers,".//gml:identifier"))
David Watkins's avatar
David Watkins committed
98
99
    site <- substring(site, 8)
    
100
101
    #some sites don't have a description
    siteDesc <- xml_text(xml_find_first(featureMembers, ".//gml:description"))
David Watkins's avatar
David Watkins committed
102
    
103
104
105
    siteLocs <- strsplit(xml_text(xml_find_all(featureMembers, ".//gml:pos")), " ")
    siteLocs <- data.frame(matrix(unlist(siteLocs), nrow=length(siteLocs), byrow=TRUE), stringsAsFactors = FALSE)
    names(siteLocs) <- c("dec_lat_va", "dec_lon_va")
106
107
    dec_lat_va <- "dplyr var"
    dec_lon_va <- "dplyr var"
108
    siteLocs <- mutate(siteLocs, dec_lat_va=as.numeric(dec_lat_va), dec_lon_va=as.numeric(dec_lon_va))
David Watkins's avatar
David Watkins committed
109
110
    mergedDF <- cbind.data.frame(site, description = siteDesc, siteLocs, stringsAsFactors = FALSE) 
  }
David Watkins's avatar
David Watkins committed
111
112
  else{
    stop("Unrecognized response from the web service")
113
114
115
  }
  return(mergedDF)
}
116

Laura A DeCicco's avatar
Laura A DeCicco committed
117
#' Parse the WaterML2 timeseries portion of a waterML2 file
118
#' 
David Watkins's avatar
David Watkins committed
119
120
121
122
#' Returns data frame columns of all information with each time series measurement;
#' Anything defined as a default, is returned as an attribute of that data frame.
#' 
#' @param input XML with only the wml2:MeasurementTimeseries node and children
Laura A DeCicco's avatar
Laura A DeCicco committed
123
124
125
126
127
#' @param asDateTime logical, if \code{TRUE} returns date and time as POSIXct, if \code{FALSE}, character
#' @param tz character to set timezone attribute of datetime. Default is an empty quote, which converts the 
#' datetimes to UTC (properly accounting for daylight savings times based on the data's provided time zone offset).
#' Possible values are "America/New_York","America/Chicago", "America/Denver","America/Los_Angeles",
#' "America/Anchorage","America/Honolulu","America/Jamaica","America/Managua","America/Phoenix", and "America/Metlakatla"
David Watkins's avatar
David Watkins committed
128
129
130
#' @importFrom xml2 xml_attr xml_find_all xml_text 
#' @importFrom dplyr mutate
#' @importFrom lubridate parse_date_time
131
#' @export
Laura A DeCicco's avatar
Laura A DeCicco committed
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
#' @examples 
#' baseURL <- "https://waterservices.usgs.gov/nwis/dv/?format=waterml,2.0"
#' URL <- paste(baseURL, "sites=01646500",
#'      "startDT=2014-09-01",
#'      "endDT=2014-09-08",
#'      "statCd=00003",
#'      "parameterCd=00060",sep="&")
#' \dontrun{
#' timesereies <- importWaterML2(URL, asDateTime=TRUE, tz="UTC")
#' } 
importWaterML2 <- function(input, asDateTime=FALSE, tz="UTC") {
  
  returnedDoc <- check_if_xml(input)
  raw <- class(input) == 'raw'
  
  gmlID <- xml_attr(returnedDoc,"id") #TODO: make this an attribute
  TVP <- xml_find_all(returnedDoc, ".//wml2:MeasurementTVP")#time-value pairs
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
  rawTime <- xml_text(xml_find_all(TVP,".//wml2:time"))
  
  valueNodes <- xml_find_all(TVP,".//wml2:value")
  values <- as.numeric(xml_text(valueNodes))
  nVals <- length(values)
  
  #df of date, time, dateTime
  oneCol <- rep(NA, nVals) 
  timeDF <- data.frame(date=oneCol, time=oneCol, dateTime=oneCol)
  splitTime <- data.frame(matrix(unlist(strsplit(rawTime, "T")), nrow=nVals, byrow = TRUE), stringsAsFactors=FALSE)
  if(ncol(splitTime) > 1){ #some sites only have a date
    names(splitTime) <- c("date", "time")
  }else{
    names(splitTime) <- "date"
    splitTime <- mutate(splitTime, time = NA)
  }
  
  timeDF <- mutate(splitTime, dateTime = NA)
  logicVec <- nchar(rawTime) > 19
David Watkins's avatar
David Watkins committed
168
169
170
  if(!all(!logicVec)) { #otherwise sets it to char <NA>
    timeDF$dateTime[logicVec] <- rawTime[logicVec]
  }
171
172
173
174
  if(asDateTime){
    timeDF$dateTime <- parse_date_time(timeDF$dateTime, c("%Y","%Y-%m-%d","%Y-%m-%dT%H:%M","%Y-%m-%dT%H:%M:%S",
                                                          "%Y-%m-%dT%H:%M:%OS","%Y-%m-%dT%H:%M:%OS%z"), exact = TRUE)
    #^^setting tz in as.POSIXct just sets the attribute, does not convert the time!
David Watkins's avatar
David Watkins committed
175
    attr(timeDF$dateTime, 'tzone') <- tz
176
177
178
  }
  
  uom <- xml_attr(valueNodes, "uom", default = NA)
David Watkins's avatar
David Watkins committed
179
  
180
181
  source <- xml_attr(xml_find_all(TVP, ".//wml2:source"), "title")
  comment <- xml_text(xml_find_all(TVP, ".//wml2:comment"))
David Watkins's avatar
David Watkins committed
182
  tvpQuals <- xml_text(xml_find_all(TVP, ".//swe:description"))
Laura A DeCicco's avatar
Laura A DeCicco committed
183
  defaultMeta <- xml_find_all(returnedDoc, ".//wml2:DefaultTVPMeasurementMetadata")
David Watkins's avatar
David Watkins committed
184
185
  defaultQuals <- xml_text(xml_find_all(defaultMeta, ".//swe:description"))
  defaultUOM <- xml_attr(xml_find_all(defaultMeta, ".//wml2:uom"), "title", default = NA)
David Watkins's avatar
David Watkins committed
186
187
188
 
  df_vars <- list(source = source, timeDF, value = values, 
                  uom = uom, comment = comment)
David Watkins's avatar
David Watkins committed
189
190
  df_use <- df_vars[sapply(df_vars, function(x){length(x) > 0 && !all(is.na(x))})]
  df <- data.frame(df_use, stringsAsFactors = FALSE)
David Watkins's avatar
David Watkins committed
191
192
193
  
  #from the default metadata section
  #append to existing attributes if they aren't empty
David Watkins's avatar
David Watkins committed
194
   mdAttribs <- list(defaultQualifier=defaultQuals, defaultUOM=defaultUOM, 
David Watkins's avatar
David Watkins committed
195
196
197
                    gmlID=gmlID) #all attributes must have names
  mdAttribs_use <- mdAttribs[sapply(mdAttribs, function(x){length(x) > 0})]
  attributes(df) <- append(attributes(df), mdAttribs_use)
198
199
  return(df)
}