importNGWMN_wml2.R 8.88 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
10
11
12
13
#' @param tz character to set timezone attribute of dateTime. Default is "UTC", and converts the 
#' date times to UTC, properly accounting for daylight savings times based on the data's provided time zone offset.
#' Possible values to provide are "America/New_York","America/Chicago", "America/Denver","America/Los_Angeles",
#' "America/Anchorage", as well as the following which do not use daylight savings time: "America/Honolulu",
#' "America/Jamaica","America/Managua","America/Phoenix", and "America/Metlakatla". See also  \code{OlsonNames()} 
#' for more information on time zones.
David Watkins's avatar
David Watkins committed
14
#' @return mergedDF a data frame source, time, value, uom, uomTitle, comment, gmlID
15
16
17
18
19
#' @export
#' @importFrom xml2 read_xml
#' @importFrom xml2 xml_find_all
#' @importFrom xml2 xml_text
#' @importFrom xml2 xml_attr
20
#' @importFrom xml2 xml_find_first
21
22
#' @importFrom lubridate parse_date_time
#' @examples
David Watkins's avatar
David Watkins committed
23
#' \dontrun{
Laura A DeCicco's avatar
Laura A DeCicco committed
24
25
26
27
28
#' 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
29
#' data <- importNGWMN(obs_url)
David Watkins's avatar
David Watkins committed
30
#' 
Laura A DeCicco's avatar
Laura A DeCicco committed
31
32
33
34
35
#' 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
36
#' data <- importNGWMN(obs_url)
David Watkins's avatar
David Watkins committed
37
#' }
David Watkins's avatar
David Watkins committed
38
#' 
Laura A DeCicco's avatar
Laura A DeCicco committed
39
40
importNGWMN <- function(input, asDateTime=FALSE, tz="UTC"){
  
41
  if(tz != ""){
David Watkins's avatar
David Watkins committed
42
    tz <- match.arg(tz, OlsonNames())
43
44
45
46
47
48
49
50
51
52
53
54
  }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
55
56
57
58
59
60
61
62
63
64
65
  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)
66
67
    }
    
David Watkins's avatar
David Watkins committed
68
    mergedDF <- NULL
69
    
David Watkins's avatar
David Watkins committed
70
    for(t in timeSeries){
Laura A DeCicco's avatar
Laura A DeCicco committed
71
      df <- importWaterML2(t, asDateTime, tz)
72
      
David Watkins's avatar
David Watkins committed
73
74
75
76
77
78
      if (is.null(mergedDF)){
        mergedDF <- df
      } else {
        similarNames <- intersect(colnames(mergedDF), colnames(df))
        mergedDF <- full_join(mergedDF, df, by=similarNames)
      }
79
    }
David Watkins's avatar
David Watkins committed
80
81
82
83
84
    
    if(!raw){
      url <- input
      attr(mergedDF, "url") <- url
    }
David Watkins's avatar
David Watkins committed
85
86
87
    if(asDateTime){
      mergedDF$date <- as.Date(mergedDF$date)
    }
88
89
    nonDateCols <- grep("date",names(mergedDF), value=TRUE, invert = TRUE)
    
David Watkins's avatar
David Watkins committed
90
    if(nrow(mergedDF) > 0){
91
92
      mergedDF[nonDateCols][mergedDF[nonDateCols] == "" | mergedDF[nonDateCols]== -999999.0] <- NA
    }
David Watkins's avatar
David Watkins committed
93
94
    attr(mergedDF, "gml:identifier") <- xml_text(xml_find_all(returnedDoc, ".//gml:identifier")) 
    attr(mergedDF, "generationDate") <- xml_text(xml_find_all(returnedDoc, ".//wml2:generationDate")) 
95
96
97
98
    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
99
  }else if(response == "GetFeatureOfInterestResponse"){
100
101
    featureMembers <- xml_find_all(returnedDoc, ".//sos:featureMember")
    site <- xml_text(xml_find_all(featureMembers,".//gml:identifier"))
David Watkins's avatar
David Watkins committed
102
103
    site <- substring(site, 8)
    
104
105
    #some sites don't have a description
    siteDesc <- xml_text(xml_find_first(featureMembers, ".//gml:description"))
David Watkins's avatar
David Watkins committed
106
    
107
108
109
    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")
110
111
    dec_lat_va <- "dplyr var"
    dec_lon_va <- "dplyr var"
112
    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
113
114
    mergedDF <- cbind.data.frame(site, description = siteDesc, siteLocs, stringsAsFactors = FALSE) 
  }
David Watkins's avatar
David Watkins committed
115
116
  else{
    stop("Unrecognized response from the web service")
117
118
119
  }
  return(mergedDF)
}
120

Laura A DeCicco's avatar
Laura A DeCicco committed
121
#' Parse the WaterML2 timeseries portion of a waterML2 file
122
#' 
David Watkins's avatar
David Watkins committed
123
124
125
126
#' 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
127
128
129
130
131
#' @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
132
133
134
#' @importFrom xml2 xml_attr xml_find_all xml_text 
#' @importFrom dplyr mutate
#' @importFrom lubridate parse_date_time
135
#' @export
Laura A DeCicco's avatar
Laura A DeCicco committed
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
#' @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
153
  if(length(TVP) == 0) { #empty nodes on some sites
David Watkins's avatar
David Watkins committed
154
155
    return(data.frame(site = character(0), source = character(0), date = character(0),
                      time = character(0), dateTime = character(0), value = numeric(0),
David Watkins's avatar
David Watkins committed
156
                      uom = character(0), comment = character(0), stringsAsFactors = FALSE))
157
  }
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
  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
177
178
179
  if(!all(!logicVec)) { #otherwise sets it to char <NA>
    timeDF$dateTime[logicVec] <- rawTime[logicVec]
  }
180
181
182
183
  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
184
    attr(timeDF$dateTime, 'tzone') <- tz
185
186
187
  }
  
  uom <- xml_attr(valueNodes, "uom", default = NA)
David Watkins's avatar
David Watkins committed
188
  
189
190
  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
191
  tvpQuals <- xml_text(xml_find_all(TVP, ".//swe:description"))
Laura A DeCicco's avatar
Laura A DeCicco committed
192
  defaultMeta <- xml_find_all(returnedDoc, ".//wml2:DefaultTVPMeasurementMetadata")
David Watkins's avatar
David Watkins committed
193
194
  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
195
196
197
 
  df_vars <- list(source = source, timeDF, value = values, 
                  uom = uom, comment = comment)
David Watkins's avatar
David Watkins committed
198
199
  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
200
201
202
  
  #from the default metadata section
  #append to existing attributes if they aren't empty
David Watkins's avatar
David Watkins committed
203
   mdAttribs <- list(defaultQualifier=defaultQuals, defaultUOM=defaultUOM, 
David Watkins's avatar
David Watkins committed
204
205
206
                    gmlID=gmlID) #all attributes must have names
  mdAttribs_use <- mdAttribs[sapply(mdAttribs, function(x){length(x) > 0})]
  attributes(df) <- append(attributes(df), mdAttribs_use)
207
208
  return(df)
}