-
Notifications
You must be signed in to change notification settings - Fork 3
/
ala_occurrences.R
234 lines (206 loc) · 8.11 KB
/
ala_occurrences.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
#' Occurrence records
#'
#' The most common form of data stored by ALA are observations of
#' individual life forms, known as 'occurrences'. This function allows the
#' user to search for occurrence records that match their specific criteria,
#' and return them as a \code{data.frame} for analysis. Optionally,
#' the user can also request a DOI for a given download to facilitate citation and
#' re-use of specific data resources.
#'
#' @param taxa \code{data.frame}: generated by a call to \code{\link{select_taxa}()}. This
#' argument also accepts a vector of unique species identifiers.
#' @param filters \code{data.frame}: generated by a call to \code{\link{select_filters}()}
#' @param locations \code{string}: generated by a call to \code{\link{select_locations}()}
#' @param columns \code{data.frame}: generated by a call to \code{\link{select_columns}()}
#' @param mint_doi \code{logical}: by default no DOI will be generated. Set to
#' true if you intend to use the data in a publication or similar
#' @param doi \code{string}: this argument enables retrieval of occurrence
#' records previously downloaded from the ALA, using the DOI generated by the data.
#' Specifying this argument means all other arguments will be ignored.
#' @details
#' Note that unless care is taken, some queries can be particularly large.
#' While most cases this will simply take a long time to process, if the number
#' of requested records is >50 million the call will not return any data. Users
#' can test whether this threshold will be reached by first calling
#' \code{\link{ala_counts}()} using the same arguments that they intend to pass to
#' \code{ala_occurrences}(). It may also be beneficial when requesting a large
#' number of records to show a progress bar by setting \code{verbose = TRUE} in
#' \code{\link{ala_config}()}.
#' @return A \code{data.frame} of occurrences, columns as specified
#' by \code{\link{select_columns}()}.
#' @examples \dontrun{
#' # Search for occurrences matching a taxon identifier
#' occ <- ala_occurrences(taxa = select_taxa("Reptilia"))
#'
#' # Search for occurrences in a year range
#' occ <- ala_occurrences(filters = select_filters(year = seq(2010, 2020)))
#'
#' # Search for occurrences in a WKT-specified area
#' polygon <- "POLYGON((146.24960 -34.05930,146.37045 -34.05930,146.37045 \
#' -34.152549,146.24960 -34.15254,146.24960 -34.05930))"
#' occ <- ala_occurrences(locations = select_locations(polygon))
#' }
#' @export ala_occurrences
ala_occurrences <- function(taxa = NULL, filters = NULL, locations = NULL,
columns = select_columns(group = "basic"),
mint_doi = FALSE, doi) {
verbose <- getOption("galah_config")$verbose
assert_that(is.logical(mint_doi))
if (!missing(doi)) {
# search for data using DOI
return(doi_download(doi))
}
profile <- extract_profile(filters)
query <- build_query(taxa, filters, locations, columns, profile)
# handle caching
caching <- getOption("galah_config")$caching
# Check record count
count <- record_count(query)
check_count(count)
# Add columns to query
assertion_cols <- columns[columns$type == "assertions", ]
query$fields <- build_columns(columns[columns$type != "assertions", ])
query$qa <- build_columns(assertion_cols)
if (mint_doi) {
query$mintDoi <- "true"
}
if (caching) {
cache_file <- cache_filename("occurrences", unlist(query))
if (file.exists(cache_file)) {
return(read_cache_file(cache_file))
}
}
if (getOption("galah_config")$atlas == "Australia") {
query$emailNotify <- email_notify()
query$sourceTypeId <- 2004
query$reasonTypeId <- getOption("galah_config")$download_reason_id
}
# Get data
tmp <- tempfile()
url <- server_config("records_base_url")
query <- c(query, email = user_email(), dwcHeaders = "true")
download_resp <- wait_for_download(url, query)
download_path <- download_resp$download_path
data_path <- ala_download(url = server_config("records_download_base_url"),
path = download_path,
cache_file = tmp, ext = ".zip")
tryCatch(
df <- read.csv(unz(data_path, "data.csv"), stringsAsFactors = FALSE),
error = function(e) {
message("There was an error reading the occurrence data; possibly no data was returned. This may be because
no valid column names have been provided. To check whether column names are valid, use `search_fields()`")
}
)
# rename cols so they match requested cols
names(df) <- rename_columns(names(df), type = "occurrence")
# replace 'true' and 'false' with boolean
if (nrow(assertion_cols) > 0) {
df <- fix_assertion_cols(df, assertion_cols$name)
}
# add DOI as attribute
attr(df, "doi") <- get_doi(mint_doi, data_path)
attr(df, "search_url") <- download_resp$search_url
attr(df, "data_type") <- "occurrences"
if (caching) {
write_cache_file(object = df, data_type = "occurrences", query = list(),
cache_file = cache_file)
}
return(df)
}
get_doi <- function(mint_doi, data_path) {
doi <- NA
if (as.logical(mint_doi)) {
tryCatch(
doi <- as.character(
read.table(unz(data_path, "doi.txt"))$V1),
warning = function(e) {
e$message <- "No DOI was generated for this download. The DOI server may
be down or, if this is a cached result, may not have been generated for
the original download."
})
}
return(doi)
}
wait_for_download <- function(url, query) {
status <- ala_GET(url, "occurrences/offline/download",
params = query, on_error = occ_error_handler)
search_url <- status$searchUrl
status_url <- parse_url(status$statusUrl)
status <- ala_GET(url, path = status_url$path)
verbose <- getOption("galah_config")$verbose
# create a progress bar
if (verbose) {
pb <- txtProgressBar(max = 1, style = 3)
}
while(status$status == "inQueue") {
status <- ala_GET(url, path = status_url$path)
}
while (tolower(status$status) == "running") {
val <- (status$records / status$totalRecords)
if (verbose) {
setTxtProgressBar(pb, val)
}
status <- ala_GET(url, path = status_url$path)
Sys.sleep(2)
}
if (verbose) {
setTxtProgressBar(pb, value = 1)
close(pb)
}
resp <- list(download_path = parse_url(status$downloadUrl)$path,
search_url = search_url)
return(resp)
}
check_count <- function(count) {
if (count == 0) {
stop("This query does not match any records.")
} else if (count > 50000000) {
stop("A maximum of 50 million records can be retrieved at once.",
" Please narrow the query and try again.")
} else {
if (getOption("galah_config")$verbose) {
message("This query will return ", count, " records")
}
}
}
doi_download <- function(doi) {
# strip useful part of DOI
doi_str <- str_split(doi, "ala.")[[1]][2]
if (is.na(doi_str)) {
stop("DOI has not been generated by the ALA. ALA DOIs created by the ALA
have a prefix of 10.26197/ala.")
}
path <- ala_download(server_config("doi_base_url"),
path = paste0("/doi/", doi_str, "/download"),
ext = ".zip", cache_file = tempfile(pattern = "data"))
record_file <- grep('^records', unzip(path, list=TRUE)$Name,
ignore.case=TRUE, value=TRUE)
df <- read.csv(unz(path, record_file), stringsAsFactors = FALSE)
attr(df, "doi") <- doi
return(df)
}
email_notify <- function() {
notify <- as.logical(getOption("galah_config")$send_email)
if (is.na(notify)) {
notify <- FALSE
}
# ala api requires lowercase
ifelse(notify, "true", "false")
}
user_email <- function() {
email <- getOption("galah_config")$email
if (email == "") {
email <- Sys.getenv("email")
}
if (email == "") {
stop("To download occurrence records you must provide a valid email ",
"address registered with the ALA using `ala_config(email = )`")
}
email
}
occ_error_handler <- function(code) {
if (code == 403) {
stop("Status code 403 was returned for this occurrence download request. This may be because
the email you provided is not registered with the ALA. Please check and try again.")
}
}