├── .github ├── .gitignore └── workflows │ ├── R-CMD-check.yaml │ └── rhub.yaml ├── vignettes ├── .gitignore └── rlandfire.Rmd ├── tests ├── testthat │ ├── setup.R │ ├── testdata │ │ ├── vsiTest.zip │ │ ├── wildfire.zip │ │ └── editmask_noshp.zip │ ├── _mock │ │ ├── healthCheck-true │ │ │ └── lfps.usgs.gov │ │ │ │ └── api │ │ │ │ └── healthCheck.json │ │ ├── healthCheck-false │ │ │ └── lfps.usgs.gov │ │ │ │ └── api │ │ │ │ └── healthCheck.json │ │ ├── cancelJob │ │ │ └── lfps.usgs.gov │ │ │ │ └── api │ │ │ │ └── job │ │ │ │ └── cancel-1204b9.json │ │ ├── checkStatus-nojob │ │ │ └── lfps.usgs.gov │ │ │ │ └── api │ │ │ │ └── job │ │ │ │ └── status-1cad1e.R │ │ └── checkStatus │ │ │ └── lfps.usgs.gov │ │ │ └── api │ │ │ └── job │ │ │ └── status-24eb09.json │ ├── test-utils.R │ ├── test-checkStatus.R │ ├── test-getAOI.R │ └── test-landfireAPI.R └── testthat.R ├── R ├── sysdata.rda ├── rlandfire-package.R ├── zzz.R ├── getAOI.R ├── utils.R ├── checkStatus.R └── landfireAPI.R ├── man ├── figures │ ├── lfps.png │ ├── rlandfire.png │ ├── README-unnamed-chunk-11-1.png │ ├── README-unnamed-chunk-12-1.png │ ├── README-unnamed-chunk-14-1.png │ ├── README-unnamed-chunk-15-1.png │ ├── README-unnamed-chunk-17-1.png │ └── README-unnamed-chunk-2-1.png ├── viewProducts.Rd ├── healthCheck.Rd ├── cancelJob.Rd ├── rlandfire-package.Rd ├── getZone.Rd ├── landfireVSI.Rd ├── getAOI.Rd ├── checkStatus.Rd ├── landfireAPI.Rd └── landfireAPIv2.Rd ├── inst ├── extdata │ ├── wildfire.zip │ ├── LFPS_Return.zip │ └── LFPS_cat_Return.zip └── CITATION ├── CRAN-SUBMISSION ├── .gitignore ├── .Rbuildignore ├── NAMESPACE ├── rlandfire.Rproj ├── cran-comments.md ├── DESCRIPTION ├── NEWS.md ├── README.Rmd ├── README.md └── LICENSE.md /.github/.gitignore: -------------------------------------------------------------------------------- 1 | *.html 2 | -------------------------------------------------------------------------------- /vignettes/.gitignore: -------------------------------------------------------------------------------- 1 | *.html 2 | *.R 3 | -------------------------------------------------------------------------------- /tests/testthat/setup.R: -------------------------------------------------------------------------------- 1 | library(httptest2) 2 | -------------------------------------------------------------------------------- /R/sysdata.rda: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bcknr/rlandfire/HEAD/R/sysdata.rda -------------------------------------------------------------------------------- /man/figures/lfps.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bcknr/rlandfire/HEAD/man/figures/lfps.png -------------------------------------------------------------------------------- /inst/extdata/wildfire.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bcknr/rlandfire/HEAD/inst/extdata/wildfire.zip -------------------------------------------------------------------------------- /man/figures/rlandfire.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bcknr/rlandfire/HEAD/man/figures/rlandfire.png -------------------------------------------------------------------------------- /inst/extdata/LFPS_Return.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bcknr/rlandfire/HEAD/inst/extdata/LFPS_Return.zip -------------------------------------------------------------------------------- /CRAN-SUBMISSION: -------------------------------------------------------------------------------- 1 | Version: 2.0.1 2 | Date: 2025-07-30 22:51:29 UTC 3 | SHA: 0963da313ce2423afa8f2fa3ad98b425b08431d3 4 | -------------------------------------------------------------------------------- /inst/extdata/LFPS_cat_Return.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bcknr/rlandfire/HEAD/inst/extdata/LFPS_cat_Return.zip -------------------------------------------------------------------------------- /tests/testthat/testdata/vsiTest.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bcknr/rlandfire/HEAD/tests/testthat/testdata/vsiTest.zip -------------------------------------------------------------------------------- /tests/testthat/testdata/wildfire.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bcknr/rlandfire/HEAD/tests/testthat/testdata/wildfire.zip -------------------------------------------------------------------------------- /man/figures/README-unnamed-chunk-11-1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bcknr/rlandfire/HEAD/man/figures/README-unnamed-chunk-11-1.png -------------------------------------------------------------------------------- /man/figures/README-unnamed-chunk-12-1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bcknr/rlandfire/HEAD/man/figures/README-unnamed-chunk-12-1.png -------------------------------------------------------------------------------- /man/figures/README-unnamed-chunk-14-1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bcknr/rlandfire/HEAD/man/figures/README-unnamed-chunk-14-1.png -------------------------------------------------------------------------------- /man/figures/README-unnamed-chunk-15-1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bcknr/rlandfire/HEAD/man/figures/README-unnamed-chunk-15-1.png -------------------------------------------------------------------------------- /man/figures/README-unnamed-chunk-17-1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bcknr/rlandfire/HEAD/man/figures/README-unnamed-chunk-17-1.png -------------------------------------------------------------------------------- /man/figures/README-unnamed-chunk-2-1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bcknr/rlandfire/HEAD/man/figures/README-unnamed-chunk-2-1.png -------------------------------------------------------------------------------- /tests/testthat/testdata/editmask_noshp.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bcknr/rlandfire/HEAD/tests/testthat/testdata/editmask_noshp.zip -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .Rproj.user 2 | .Rhistory 3 | .RData 4 | .Ruserdata 5 | inst/doc 6 | CRAN-SUBMISSION 7 | /doc/ 8 | /Meta/ 9 | tests/testthat/misc.r -------------------------------------------------------------------------------- /tests/testthat/_mock/healthCheck-true/lfps.usgs.gov/api/healthCheck.json: -------------------------------------------------------------------------------- 1 | { 2 | "message": "The service is up", 3 | "success": true 4 | } -------------------------------------------------------------------------------- /tests/testthat/_mock/healthCheck-false/lfps.usgs.gov/api/healthCheck.json: -------------------------------------------------------------------------------- 1 | { 2 | "message": "The service is up", 3 | "success": true 4 | } 5 | -------------------------------------------------------------------------------- /.Rbuildignore: -------------------------------------------------------------------------------- 1 | ^.*\.Rproj$ 2 | ^\.Rproj\.user$ 3 | ^LICENSE\.md$ 4 | ^README\.Rmd$ 5 | ^CRAN-SUBMISSION$ 6 | ^cran-comments\.md$ 7 | ^\.github$ 8 | ^doc$ 9 | ^Meta$ 10 | -------------------------------------------------------------------------------- /tests/testthat/_mock/cancelJob/lfps.usgs.gov/api/job/cancel-1204b9.json: -------------------------------------------------------------------------------- 1 | { 2 | "message": "Job 6f5ba39c-09f7-4f6d-97fa-543af185eb1b has been canceled", 3 | "success": true 4 | } 5 | -------------------------------------------------------------------------------- /R/rlandfire-package.R: -------------------------------------------------------------------------------- 1 | #' @keywords internal 2 | "_PACKAGE" 3 | 4 | ## usethis namespace: start 5 | #' @importFrom utils browseURL 6 | #' @importFrom utils unzip 7 | ## usethis namespace: end 8 | NULL 9 | -------------------------------------------------------------------------------- /NAMESPACE: -------------------------------------------------------------------------------- 1 | # Generated by roxygen2: do not edit by hand 2 | 3 | export(cancelJob) 4 | export(checkStatus) 5 | export(getAOI) 6 | export(getZone) 7 | export(healthCheck) 8 | export(landfireAPI) 9 | export(landfireAPIv2) 10 | export(landfireVSI) 11 | export(viewProducts) 12 | importFrom(utils,browseURL) 13 | importFrom(utils,unzip) 14 | -------------------------------------------------------------------------------- /inst/CITATION: -------------------------------------------------------------------------------- 1 | citHeader("To cite rlandfire in publications use:") 2 | 3 | bibentry( 4 | bibtype = "Manual", 5 | title = "rlandfire: Interface to 'LANDFIRE Product Service' API", 6 | author = person("Mark A. Buckner", role = "aut"), 7 | year = 2025, 8 | note = "R Package version 2.0.1", 9 | url = "https://CRAN.R-project.org/package=rlandfire", 10 | doi = "10.6084/m9.figshare.22203250" 11 | ) 12 | -------------------------------------------------------------------------------- /tests/testthat.R: -------------------------------------------------------------------------------- 1 | # This file is part of the standard setup for testthat. 2 | # It is recommended that you do not modify it. 3 | # 4 | # Where should you do additional test configuration? 5 | # Learn more about the roles of various files in: 6 | # * https://r-pkgs.org/tests.html 7 | # * https://testthat.r-lib.org/reference/test_package.html#special-files 8 | 9 | library(testthat) 10 | library(rlandfire) 11 | 12 | test_check("rlandfire") 13 | -------------------------------------------------------------------------------- /rlandfire.Rproj: -------------------------------------------------------------------------------- 1 | Version: 1.0 2 | 3 | RestoreWorkspace: Default 4 | SaveWorkspace: Default 5 | AlwaysSaveHistory: Default 6 | 7 | EnableCodeIndexing: Yes 8 | UseSpacesForTab: Yes 9 | NumSpacesForTab: 2 10 | Encoding: UTF-8 11 | 12 | RnwWeave: knitr 13 | LaTeX: pdfLaTeX 14 | 15 | AutoAppendNewline: Yes 16 | StripTrailingWhitespace: Yes 17 | 18 | BuildType: Package 19 | PackageUseDevtools: Yes 20 | PackageInstallArgs: --no-multiarch --with-keep.source 21 | -------------------------------------------------------------------------------- /man/viewProducts.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/utils.R 3 | \name{viewProducts} 4 | \alias{viewProducts} 5 | \title{View LFPS products table} 6 | \usage{ 7 | viewProducts() 8 | } 9 | \value{ 10 | NULL. Opens the LF products table in your default browser. 11 | } 12 | \description{ 13 | \code{viewProducts()} opens the LFPS products table in your web browser 14 | } 15 | \examples{ 16 | \dontrun{ 17 | viewProducts() 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /man/healthCheck.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/checkStatus.R 3 | \name{healthCheck} 4 | \alias{healthCheck} 5 | \title{Check if the LFPS API is available} 6 | \usage{ 7 | healthCheck() 8 | } 9 | \value{ 10 | NULL. Prints a message to the console about the current LFPS status. 11 | } 12 | \description{ 13 | \code{healthCheck()} checks if the LPFS API is available 14 | } 15 | \examples{ 16 | \dontrun{ 17 | healthCheck() 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /R/zzz.R: -------------------------------------------------------------------------------- 1 | .onAttach <- function(libname, pkgname) { 2 | packageStartupMessage( 3 | paste0("\033[38;5;208m", 4 | r"( 5 | _ _ ___ _ 6 | ___| |___ ___ _| | _|_|___ ___ 7 | | _| | .'| | . | _| | _| -_| 8 | |_| |_|__,|_|_|___|_| |_|_| |___| 9 | 10 | )", "\033[0m"), "version:", utils::packageVersion("rlandfire"), 11 | "\033[38;5;160m\n\nNOTICE:\033[0m\n", 12 | "The LFPS API has been updated (LFPSv1 -> LFPSv2) and has new requirements.\n", 13 | "To review the required parameters and syntax for LFPSv2 view `?rlandfire::landfireAPIv2`\n", 14 | "Product names and availability may have changed, check `viewProducts()`\n\n", 15 | "\033[38;5;160mWorkflows built before May 2025 or with `rlandfire` versions < 2.0.0 will need to be updated.\033[0m") 16 | } -------------------------------------------------------------------------------- /tests/testthat/_mock/checkStatus-nojob/lfps.usgs.gov/api/job/status-1cad1e.R: -------------------------------------------------------------------------------- 1 | structure(list(method = "GET", url = "https://lfps.usgs.gov/api/job/status?JobId=123456", 2 | status_code = 500L, headers = structure(list(date = "Wed, 16 Apr 2025 20:35:38 GMT", 3 | server = "Apache", `x-frame-options` = "SAMEORIGIN", 4 | `strict-transport-security` = "max-age=31536000; includeSubDomains", 5 | `content-type` = "application/json", vary = "Accept-Encoding", 6 | `content-encoding` = "br", `access-control-allow-origin` = "*", 7 | `Set-Cookie` = "REDACTED", `Set-Cookie` = "REDACTED", 8 | `Content-Length` = "50"), redact = character(0), class = "httr2_headers"), 9 | body = charToRaw("{\"message\":\"JobId not found.\",\"success\":false}"), 10 | cache = new.env(parent = emptyenv())), class = "httr2_response") 11 | -------------------------------------------------------------------------------- /man/cancelJob.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/checkStatus.R 3 | \name{cancelJob} 4 | \alias{cancelJob} 5 | \title{Cancel an active LANDFIRE Product Service (LFPS) API job} 6 | \usage{ 7 | cancelJob(job_id) 8 | } 9 | \arguments{ 10 | \item{job_id}{The job ID of the LFPS API request as a character string} 11 | } 12 | \value{ 13 | NULL. Prints a message to the console about the job status. 14 | } 15 | \description{ 16 | \code{cancelJob()} sends a request to cancel a LFPS API request 17 | } 18 | \examples{ 19 | \dontrun{ 20 | products <- c("ASP2020", "ELEV2020", "230CC") 21 | aoi <- c("-123.7835", "41.7534", "-123.6352", "41.8042") 22 | email <- "email@example.com>" 23 | 24 | resp <- landfireAPIv2(products, aoi, email, background = TRUE) 25 | 26 | job_id <- resp$request$job_id #Get job_id from a previous request 27 | cancelJob("job_id") 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /cran-comments.md: -------------------------------------------------------------------------------- 1 | ## Update (v2.0.1) 2 | 3 | * This is a patch to the existing `rlandfire` package. To address issues resulting in failed checks on CRAN. 4 | 5 | * Changes include: 6 | 7 | - All tests that require API access are mocked when possible or conditionally skipped with `skip_on_cran()`. 8 | - Tests expected to fail prior to making an API call are now terminated early with `execute=FALSE` argument in `landfireAPIv2()`. 9 | - The old `landfireAPI` function has been fully deprecated. 10 | - Shapefile POST requests are repeated if they fail with status code 500, up to a maximum of 3 attempts. 11 | 12 | ## R CMD check results 13 | 14 | 0 errors | 0 warnings | 0 notes 15 | 16 | * Possibly mis-spelled words in DESCRIPTION: 17 | LANDFIRE (3:21) 18 | geospatial (12:44) 19 | 20 | Both of the flagged words are spelled correctly. 21 | 22 | * Tests requiring API access are conditionally skipped or mocked. -------------------------------------------------------------------------------- /man/rlandfire-package.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/rlandfire-package.R 3 | \docType{package} 4 | \name{rlandfire-package} 5 | \alias{rlandfire} 6 | \alias{rlandfire-package} 7 | \title{rlandfire: Interface to 'LANDFIRE Product Service' API} 8 | \description{ 9 | Provides access to a suite of geospatial data layers for wildfire management, fuel modeling, ecology, natural resource management, climate, conservation, etc., via the 'LANDFIRE' (\url{https://www.landfire.gov/}) Product Service ('LFPS') API. 10 | } 11 | \seealso{ 12 | Useful links: 13 | \itemize{ 14 | \item \url{https://github.com/bcknr/rlandfire} 15 | \item Report bugs at \url{https://github.com/bcknr/rlandfire/issues} 16 | } 17 | 18 | } 19 | \author{ 20 | \strong{Maintainer}: Mark Buckner \email{mab677@cornell.edu} (\href{https://orcid.org/0000-0002-9692-7454}{ORCID}) [copyright holder] 21 | 22 | } 23 | \keyword{internal} 24 | -------------------------------------------------------------------------------- /man/getZone.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/getAOI.R 3 | \name{getZone} 4 | \alias{getZone} 5 | \title{Find LANDFIRE map zone for use with \code{landfireAPI()}} 6 | \usage{ 7 | getZone(data) 8 | } 9 | \arguments{ 10 | \item{data}{An sf object or character string with the map zone name.} 11 | } 12 | \value{ 13 | Returns a numeric vector containing the map zone(s) 14 | } 15 | \description{ 16 | \code{getZone} returns the LANDFIRE Map Zone(s) a spatial object intersects or the 17 | zone number from the zone name. Currently, only map zones within CONUS are 18 | supported. 19 | } 20 | \examples{ 21 | \dontrun{ 22 | v <- sf::st_bbox(sf::st_as_sf(data.frame(x = c(-123.7835,-123.6352), 23 | y = c(41.7534,41.8042)), 24 | coords = c("x", "y"), 25 | crs = 4326)) |> 26 | sf::st_as_sfc() 27 | zone <- getZone(v) 28 | } 29 | 30 | } 31 | -------------------------------------------------------------------------------- /man/landfireVSI.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/utils.R 3 | \name{landfireVSI} 4 | \alias{landfireVSI} 5 | \title{Read in LANDFIRE products using the GDAL \verb{virtual file system}} 6 | \usage{ 7 | landfireVSI(landfire_api) 8 | } 9 | \arguments{ 10 | \item{landfire_api}{A \code{landfire_api} object created by \code{landfireAPIv2()}} 11 | } 12 | \value{ 13 | SpatRaster object of the requested LANDFIRE product/s 14 | } 15 | \description{ 16 | \code{landfire_vsi()} opens a request LANDFIRE GeoTIFF using the GDAL \verb{virtual file system} (VSI). 17 | } 18 | \details{ 19 | The GDAL virtual file system allows you to read in LANDFIRE products without 20 | having to download the file to your local machine within 60 minutes of the 21 | request or if the file already exists on your local machine without having 22 | to unzip it. 23 | } 24 | \examples{ 25 | \dontrun{ 26 | aoi <- c("-113.79", "42.148", "-113.56", "42.29") 27 | email <- "email@example" 28 | rast <- landfireAPIv2(products = "240EVC", 29 | aoi = aoi, email = email, 30 | method = "none") |> 31 | landfireVSI() 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /DESCRIPTION: -------------------------------------------------------------------------------- 1 | Package: rlandfire 2 | Type: Package 3 | Title: Interface to 'LANDFIRE Product Service' API 4 | Version: 2.0.1 5 | Authors@R: 6 | c(person(given = "Mark", 7 | family = "Buckner", 8 | role = c("aut", "cre", "cph"), 9 | email = "mab677@cornell.edu", 10 | comment = c(ORCID = "0000-0002-9692-7454"))) 11 | Maintainer: Mark Buckner 12 | Description: Provides access to a suite of geospatial data layers for wildfire management, fuel modeling, ecology, natural resource management, climate, conservation, etc., via the 'LANDFIRE' () Product Service ('LFPS') API. 13 | License: GPL (>= 3) 14 | Encoding: UTF-8 15 | LazyData: false 16 | URL: https://github.com/bcknr/rlandfire 17 | BugReports: https://github.com/bcknr/rlandfire/issues 18 | RoxygenNote: 7.3.2 19 | Imports: 20 | curl, 21 | httr2, 22 | sf, 23 | terra, 24 | utils 25 | Suggests: 26 | foreign, 27 | httptest2, 28 | httr, 29 | knitr, 30 | lifecycle, 31 | raster, 32 | rmarkdown, 33 | stars, 34 | testthat (>= 3.0.0) 35 | Config/testthat/edition: 3 36 | VignetteBuilder: knitr 37 | Depends: 38 | R (>= 4.1.0) 39 | -------------------------------------------------------------------------------- /tests/testthat/test-utils.R: -------------------------------------------------------------------------------- 1 | # Test for utils.R 2 | 3 | # `landfireVSI()` 4 | 5 | test_that("landfireVSI() works as expected", { 6 | expect_error( 7 | landfireVSI("not a landfire_api object"), 8 | "argument `landfire_api` must be a landfire_api object" 9 | ) 10 | expect_error( 11 | landfireVSI(.build_landfire_api(), 12 | "The provided `landfire_api` object does not contain a valid `path` or `dwl_url`") 13 | ) 14 | 15 | expect_error( 16 | landfireVSI(.build_landfire_api(path = test_path("testdata", "vsiTestdoesntexist.zip"))), 17 | "No file associated with the provide `landfire_api` object was found" 18 | ) 19 | 20 | expect_s4_class( 21 | landfireVSI(.build_landfire_api(path = test_path("testdata", "vsiTest.zip"))), 22 | "SpatRaster" 23 | ) 24 | }) 25 | 26 | test_that("landfireVSI() works with a valid url", { 27 | skip_on_cran() 28 | 29 | aoi <- c("-113.79", "42.148", "-113.56", "42.29") 30 | email <- "rlandfire@markabuckner.com" 31 | resp <- landfireAPIv2(products = "240EVC", 32 | aoi = aoi, email = email, 33 | method = "none", 34 | verbose = FALSE) 35 | 36 | expect_s4_class(landfireVSI(resp), "SpatRaster") 37 | 38 | }) -------------------------------------------------------------------------------- /man/getAOI.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/getAOI.R 3 | \name{getAOI} 4 | \alias{getAOI} 5 | \title{Create extent vector for \code{landfireAPI()}} 6 | \usage{ 7 | getAOI(data, extend = NULL, sf_order = FALSE) 8 | } 9 | \arguments{ 10 | \item{data}{A SpatRaster, SpatVector, sf, stars, or RasterLayer (raster) object} 11 | 12 | \item{extend}{Optional. A numeric vector of 1, 2, or 4 elements to 13 | increase the extent by.} 14 | 15 | \item{sf_order}{If \code{extend} != NULL, logical indicating that the order of the 16 | \code{extend} vector follows \code{\link[sf:st_bbox]{sf::st_bbox()}} (\code{xmin}, \code{ymin}, \code{xmax}, \code{ymax}) when TRUE or 17 | \code{\link[terra:extend]{terra::extend()}} (\code{xmin}, \code{xmax}, \code{ymin}, \code{ymax}) when FALSE. This 18 | is \code{FALSE} by default to ensure backwards compatibility with previous versions.} 19 | } 20 | \value{ 21 | Returns an extent vector ordered \code{xmin}, \code{ymin}, \code{xmax}, \code{ymax} 22 | with a lat/lon projection. 23 | } 24 | \description{ 25 | \code{getAOI} creates an extent vector in WGS84 from spatial data 26 | } 27 | \examples{ 28 | r <- terra::rast(nrows = 50, ncols = 50, 29 | xmin = -123.7835, xmax = -123.6352, 30 | ymin = 41.7534, ymax = 41.8042, 31 | crs = terra::crs("epsg:4326"), 32 | vals = rnorm(2500)) 33 | ext <- getAOI(r, c(10, 15)) 34 | 35 | } 36 | -------------------------------------------------------------------------------- /man/checkStatus.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/checkStatus.R 3 | \name{checkStatus} 4 | \alias{checkStatus} 5 | \title{Check the status of an existing LANDFIRE Product Service (LFPS) request} 6 | \usage{ 7 | checkStatus(landfire_api, verbose = TRUE, method = "curl") 8 | } 9 | \arguments{ 10 | \item{landfire_api}{\code{landfire_api} object returned from \code{landfireAPIv2()}} 11 | 12 | \item{verbose}{If FALSE suppress all status messages} 13 | 14 | \item{method}{Passed to \code{\link[utils:download.file]{utils::download.file()}}. See \code{?download.file} or 15 | use "none" to skip download and use \code{landfire_vsi()}} 16 | } 17 | \value{ 18 | Returns a \code{landfire_api} object with named elements: 19 | \itemize{ 20 | \item \code{request} - list with elements \code{query}, \code{date}, \code{url}, \code{job_id}, \code{request},\code{dwl_url} 21 | \item \code{content} - Informative messages passed from API 22 | \item \code{response} - Full response 23 | \item \code{status} - Final API status, one of "Failed", "Succeeded", or "Timed out" 24 | \item \code{time} - time of job completion 25 | \item \code{path} - path to save directory 26 | } 27 | } 28 | \description{ 29 | \code{checkStatus} checks if a previous request is complete and downloads available data 30 | } 31 | \examples{ 32 | \dontrun{ 33 | products <- c("ASP2020", "ELEV2020", "230CC") 34 | aoi <- c("-123.7835", "41.7534", "-123.6352", "41.8042") 35 | email <- "email@example.com" 36 | resp <- landfireAPIv2(products, aoi, email, background = TRUE) 37 | checkStatus(resp) 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /.github/workflows/R-CMD-check.yaml: -------------------------------------------------------------------------------- 1 | # Workflow derived from https://github.com/r-lib/actions/tree/v2/examples 2 | # Need help debugging build failures? Start at https://github.com/r-lib/actions#where-to-find-help 3 | on: 4 | push: 5 | branches: [main, master] 6 | pull_request: 7 | 8 | name: R-CMD-check.yaml 9 | 10 | permissions: read-all 11 | 12 | jobs: 13 | R-CMD-check: 14 | runs-on: ${{ matrix.config.os }} 15 | 16 | name: ${{ matrix.config.os }} (${{ matrix.config.r }}) 17 | 18 | strategy: 19 | fail-fast: false 20 | matrix: 21 | config: 22 | - {os: macos-latest, r: 'release'} 23 | - {os: windows-latest, r: 'release'} 24 | - {os: ubuntu-latest, r: 'devel', http-user-agent: 'release'} 25 | - {os: ubuntu-latest, r: 'release'} 26 | - {os: ubuntu-latest, r: 'oldrel-1'} 27 | 28 | env: 29 | GITHUB_PAT: ${{ secrets.GITHUB_TOKEN }} 30 | R_KEEP_PKG_SOURCE: yes 31 | NOT_CRAN: "false" 32 | 33 | steps: 34 | - uses: actions/checkout@v4 35 | 36 | - uses: r-lib/actions/setup-pandoc@v2 37 | 38 | - uses: r-lib/actions/setup-r@v2 39 | with: 40 | r-version: ${{ matrix.config.r }} 41 | http-user-agent: ${{ matrix.config.http-user-agent }} 42 | use-public-rspm: true 43 | 44 | - uses: r-lib/actions/setup-r-dependencies@v2 45 | with: 46 | extra-packages: any::rcmdcheck 47 | needs: check 48 | 49 | - uses: r-lib/actions/check-r-package@v2 50 | with: 51 | upload-snapshots: true 52 | build_args: 'c("--no-manual","--compact-vignettes=gs+qpdf")' 53 | -------------------------------------------------------------------------------- /man/landfireAPI.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/landfireAPI.R 3 | \name{landfireAPI} 4 | \alias{landfireAPI} 5 | \title{Depreciated: Call the LANDFIRE Product Service (LFPS) API} 6 | \usage{ 7 | landfireAPI( 8 | products, 9 | aoi, 10 | projection = NULL, 11 | resolution = NULL, 12 | edit_rule = NULL, 13 | edit_mask = NULL, 14 | path = NULL, 15 | max_time = 10000, 16 | method = "curl", 17 | verbose = TRUE 18 | ) 19 | } 20 | \arguments{ 21 | \item{products}{Product names as character vector 22 | (see: Products Table)} 23 | 24 | \item{aoi}{Area of interest as character or numeric vector defined by 25 | latitude and longitude in decimal degrees in WGS84 and ordered 26 | \code{xmin}, \code{ymin}, \code{xmax}, \code{ymax} or a LANDFIRE map zone.} 27 | 28 | \item{projection}{Optional. A numeric value of the WKID for the output projection 29 | Default is a localized Albers projection.} 30 | 31 | \item{resolution}{Optional. A numeric value between 30-9999 specifying the 32 | resample resolution in meters. Default is 30m.} 33 | 34 | \item{edit_rule}{Optional. A list of character vectors ordered "operator class" 35 | "product", "operator", "value". Limited to fuel theme products only. 36 | (see: LFPS Guide)} 37 | 38 | \item{edit_mask}{Optional. \strong{Not currently functional}} 39 | 40 | \item{path}{Path to \code{.zip} directory. Passed to \code{\link[utils:download.file]{utils::download.file()}}. 41 | If NULL, a temporary directory is created.} 42 | 43 | \item{max_time}{Maximum time, in seconds, to wait for job to be completed.} 44 | 45 | \item{method}{Passed to \code{\link[utils:download.file]{utils::download.file()}}. See \code{?download.file} or 46 | use "none" to skip download and use \code{landfire_vsi()}} 47 | 48 | \item{verbose}{If FALSE suppress all status messages} 49 | } 50 | \value{ 51 | Returns a \code{landfire_api} object with named elements: 52 | \itemize{ 53 | \item \code{request} - list with elements \code{query}, \code{date}, \code{url}, \code{job_id},\code{dwl_url} 54 | \item \code{content} - Informative messages passed from API 55 | \item \code{response} - Full response 56 | \item \code{status} - Final API status, one of "Failed", "Succeeded", or "Timed out" 57 | \item \code{path} - path to save directory 58 | } 59 | } 60 | \description{ 61 | Superseded: \code{landfireAPI()} is no longer supported due to updates to the 62 | LFPS API. Use \code{landfireAPIv2()} instead. 63 | 64 | \code{landfireAPI} downloads LANDFIRE data by calling the LFPS API 65 | } 66 | \examples{ 67 | \dontrun{ 68 | products <- c("ASP2020", "ELEV2020", "230CC") 69 | aoi <- c("-123.7835", "41.7534", "-123.6352", "41.8042") 70 | projection <- 6414 71 | resolution <- 90 72 | edit_rule <- list(c("condition","ELEV2020","lt",500), c("change", "230CC", "st", 181)) 73 | save_file <- tempfile(fileext = ".zip") 74 | resp <- landfireAPI(products, aoi, projection, resolution, edit_rule = edit_rule, path = save_file) 75 | } 76 | } 77 | -------------------------------------------------------------------------------- /.github/workflows/rhub.yaml: -------------------------------------------------------------------------------- 1 | # R-hub's generic GitHub Actions workflow file. It's canonical location is at 2 | # https://github.com/r-hub/actions/blob/v1/workflows/rhub.yaml 3 | # You can update this file to a newer version using the rhub2 package: 4 | # 5 | # rhub::rhub_setup() 6 | # 7 | # It is unlikely that you need to modify this file manually. 8 | 9 | name: R-hub 10 | run-name: "${{ github.event.inputs.id }}: ${{ github.event.inputs.name || format('Manually run by {0}', github.triggering_actor) }}" 11 | 12 | on: 13 | workflow_dispatch: 14 | inputs: 15 | config: 16 | description: 'A comma separated list of R-hub platforms to use.' 17 | type: string 18 | default: 'linux,windows,macos' 19 | name: 20 | description: 'Run name. You can leave this empty now.' 21 | type: string 22 | id: 23 | description: 'Unique ID. You can leave this empty now.' 24 | type: string 25 | 26 | jobs: 27 | 28 | setup: 29 | runs-on: ubuntu-latest 30 | outputs: 31 | containers: ${{ steps.rhub-setup.outputs.containers }} 32 | platforms: ${{ steps.rhub-setup.outputs.platforms }} 33 | 34 | steps: 35 | # NO NEED TO CHECKOUT HERE 36 | - uses: r-hub/actions/setup@v1 37 | with: 38 | config: ${{ github.event.inputs.config }} 39 | id: rhub-setup 40 | 41 | linux-containers: 42 | needs: setup 43 | if: ${{ needs.setup.outputs.containers != '[]' }} 44 | runs-on: ubuntu-latest 45 | name: ${{ matrix.config.label }} 46 | strategy: 47 | fail-fast: false 48 | matrix: 49 | config: ${{ fromJson(needs.setup.outputs.containers) }} 50 | container: 51 | image: ${{ matrix.config.container }} 52 | 53 | steps: 54 | - uses: r-hub/actions/checkout@v1 55 | - uses: r-hub/actions/platform-info@v1 56 | with: 57 | token: ${{ secrets.RHUB_TOKEN }} 58 | job-config: ${{ matrix.config.job-config }} 59 | - uses: r-hub/actions/setup-deps@v1 60 | with: 61 | token: ${{ secrets.RHUB_TOKEN }} 62 | job-config: ${{ matrix.config.job-config }} 63 | - uses: r-hub/actions/run-check@v1 64 | with: 65 | token: ${{ secrets.RHUB_TOKEN }} 66 | job-config: ${{ matrix.config.job-config }} 67 | 68 | other-platforms: 69 | needs: setup 70 | if: ${{ needs.setup.outputs.platforms != '[]' }} 71 | runs-on: ${{ matrix.config.os }} 72 | name: ${{ matrix.config.label }} 73 | strategy: 74 | fail-fast: false 75 | matrix: 76 | config: ${{ fromJson(needs.setup.outputs.platforms) }} 77 | 78 | steps: 79 | - uses: r-hub/actions/checkout@v1 80 | - uses: r-hub/actions/setup-r@v1 81 | with: 82 | job-config: ${{ matrix.config.job-config }} 83 | token: ${{ secrets.RHUB_TOKEN }} 84 | - uses: r-hub/actions/platform-info@v1 85 | with: 86 | token: ${{ secrets.RHUB_TOKEN }} 87 | job-config: ${{ matrix.config.job-config }} 88 | - uses: r-hub/actions/setup-deps@v1 89 | with: 90 | job-config: ${{ matrix.config.job-config }} 91 | token: ${{ secrets.RHUB_TOKEN }} 92 | - uses: r-hub/actions/run-check@v1 93 | with: 94 | job-config: ${{ matrix.config.job-config }} 95 | token: ${{ secrets.RHUB_TOKEN }} 96 | -------------------------------------------------------------------------------- /tests/testthat/test-checkStatus.R: -------------------------------------------------------------------------------- 1 | # Test for checkStatus.R 2 | 3 | # Tests for .checkStatus_internal() 4 | httptest2::with_mock_dir("_mock/checkStatus-nojob", { 5 | test_that("`.checkStatus_internal()` recognizes API errors", { 6 | noJob_landfire_api <- .build_landfire_api(job_id = "123456") 7 | expect_error( 8 | .checkStatus_internal(noJob_landfire_api, i = 1, max_time = 10), 9 | "\tAPI request failed with status code: 500\n\tLFPS Error message: JobId not found" 10 | ) 11 | }) 12 | }) 13 | 14 | httptest2::with_mock_dir("_mock/checkStatus", { 15 | test_that("`.checkStatus_internal()` returns expected", { 16 | landfire_api <- .build_landfire_api( 17 | job_id = "be7fab41-867e-41a5-b594-c469f118bc49", 18 | path = tempfile(fileext = ".zip") 19 | ) 20 | return <- .checkStatus_internal(landfire_api, i = 1, max_time = 10, method = "none") 21 | expect_s3_class(return, "landfire_api") 22 | expect_equal(return$request$job_id, "be7fab41-867e-41a5-b594-c469f118bc49") 23 | }) 24 | }) 25 | 26 | # Tests for checkStatus() 27 | test_that("`checkStatus()` recognizes argument errors", { 28 | without_internet({ 29 | expect_error(checkStatus(), 30 | "argument `landfire_api` is missing with no default", 31 | fixed = TRUE 32 | ) 33 | 34 | expect_error( 35 | checkStatus(landfire_api = list()), 36 | "argument `landfire_api` must be a landfire_api object" 37 | ) 38 | 39 | expect_error( 40 | checkStatus( 41 | landfire_api = .build_landfire_api(), 42 | verbose = "not logical" 43 | ), 44 | "argument `verbose` must be logical" 45 | ) 46 | 47 | expect_error( 48 | checkStatus( 49 | landfire_api = .build_landfire_api(), 50 | method = "not a method" 51 | ), 52 | "`method` is invalid. See `?download.file`", 53 | fixed = TRUE 54 | ) 55 | }) 56 | }) 57 | 58 | # Tests for cancelJob() 59 | test_that("`cancelJob()` recognizes arguement errors", { 60 | without_internet({ 61 | expect_error( 62 | cancelJob(), 63 | "argument `job_id` is missing with no default" 64 | ) 65 | 66 | expect_error( 67 | cancelJob(job_id = 123456), 68 | "argument `job_id` must be a character string" 69 | ) 70 | }) 71 | }) 72 | 73 | # Check functionality of `cancelJob()` 74 | httptest2::with_mock_dir("_mock/cancelJob", { 75 | test_that("cancelJob() returns expected response", { 76 | # Check class and values 77 | expect_null(cancelJob("6f5ba39c-09f7-4f6d-97fa-543af185eb1b")) 78 | 79 | # Check message 80 | expect_message( 81 | cancelJob("6f5ba39c-09f7-4f6d-97fa-543af185eb1b"), 82 | "Job 6f5ba39c-09f7-4f6d-97fa-543af185eb1b has been canceled" 83 | ) 84 | }) 85 | }) 86 | 87 | # Check functionality of `healthCheck()` 88 | httptest2::with_mock_dir("_mock/healthCheck-true", { 89 | test_that("healthCheck() returns correct message when up", { 90 | expect_message(healthCheck(), "The LFPS API is available") 91 | }) 92 | }) 93 | 94 | # httptest2::with_mock_dir("_mock/healthCheck-false", { 95 | # test_that("healthCheck() returns correct message when down", { 96 | # expect_warning(healthCheck(), "The LFPS API is currently down. 97 | # Please notify the LANDFIRE helpdesk at of the following error: 98 | # The service is down") 99 | # }) 100 | # }) 101 | -------------------------------------------------------------------------------- /NEWS.md: -------------------------------------------------------------------------------- 1 | # rlandfire 2.0.1 2 | - Fully deprecated the old `landfireAPI()` function in favor of `landfireAPIv2()` 3 | - Shapefile POST requests are repeated if they fail with status code 500, up to a maximum of 3 attempts. 4 | - Minor bug fixes and improvements to address CRAN check issues on Windows-release 5 | 6 | # rlandfire 2.0.0 7 | - Added support for the new "version 2" LANDFIRE Products Service (LFPS) API 8 | - Deprecated the old `landfireAPI()` function in favor of `landfireAPIv2()` 9 | - Added new features to `landfireAPIv2()` including: 10 | - `edit_mask` to restrict edit rules to a specific area using a shapefile 11 | - Support for more complex `edit_rule` requests 12 | - Option to run calls in the background with `background = TRUE` 13 | - Added new functions: 14 | - `cancelJob()`: cancels a previously submitted job 15 | - `checkStatus()`: checks the status of a background job manually and download files if complete 16 | - `healthCheck()`: checks the current status of the LFPS API 17 | - `landfireVSI()`: reads LANDFIRE GeoTIFFs as a Spatraster using GDAL's Virtual File System (VSI) 18 | - Improved error handling and reporting and minor bug fixes 19 | - Updated documentation, vignette, and examples to reflect the new API 20 | - License for v2.0.0 is now GPL-3.0 due to dependencies on `terra` 21 | 22 | # rlandfire 1.0.1 23 | - Created startup message with warning about potential/upcoming product name changes 24 | - Updated links to LFPS products table in documentation and `viewProducts()` 25 | - Updated documentation to reflect product name changes 26 | - Added documentation to `README.md` and the vignette on working with categorical data 27 | - Added `foreign` to suggests 28 | 29 | # rlandfire 1.0.0 30 | - CRAN submission 31 | - Modified `CITATION` and `DESCRIPTION` files 32 | - Minor edits to vignette and documentation 33 | - Improved error reporting in `landfireAPI()` if multiple map zones are supplied 34 | 35 | # rlandfire 0.4.1 36 | - Fixed issue with license badge in README 37 | 38 | # rlandfire 0.4.0 39 | - Added new function (`getZone()`) which returns the LANDFIRE map zone based on a spatial object or zone name 40 | - Removed dependencies on `terra` and `stringr` 41 | - Updated to MIT + file LICENSE 42 | - Added argument to specify order of values in the `extend` argument of `getAOI()` 43 | - Added additional tests for `getAOI()`, `getZone()`, and `landfireAPI()` 44 | - Improved portability of examples 45 | 46 | # rlandfire 0.3.0 47 | 48 | - Added new function (`viewProducts()`) to open the LFPS products table in your web browser 49 | - Fixed bug causing early timeout well before `max_time` was reached 50 | 51 | # rlandfire 0.2.2 52 | 53 | - Added a `NEWS.md` file to track changes to the package. 54 | - Improved getAOI() example 55 | - Added additional checks to landfireAPI 56 | - Created a vignette 57 | 58 | # rlandfire 0.2.1 59 | 60 | - Corrected issue with `getAOI()` returning values in wrong order 61 | - Added checks to prevent API error when resolution is set to 30 by user 62 | - Fixed documentation formatting 63 | - Updated package tests 64 | 65 | # rlandfire 0.2.0 66 | 67 | - Added edit rule functionality in `landfireAPI()` 68 | - Improved error/warning reporting 69 | - Return useful object w/ class `landfire_api` 70 | - Added tests for `landfireAPI()` and `.fmt_editrules` (internal) 71 | - Improved and updated documentation 72 | - Fixed minor errors and bugs 73 | -------------------------------------------------------------------------------- /tests/testthat/_mock/checkStatus/lfps.usgs.gov/api/job/status-24eb09.json: -------------------------------------------------------------------------------- 1 | { 2 | "jobId": "be7fab41-867e-41a5-b594-c469f118bc49", 3 | "queuePosition": -1, 4 | "status": "Succeeded", 5 | "messages": [ 6 | { 7 | "type": "esriJobMessageTypeInformative", 8 | "description": "Start Time: Monday, April 21, 2025 10:51:05 AM" 9 | }, 10 | { 11 | "type": "esriJobMessageTypeInformative", 12 | "description": "AOI: -105.402073426741 40.1122440067607 -105.235264686219 40.1961284789623" 13 | }, 14 | { 15 | "type": "esriJobMessageTypeInformative", 16 | "description": "Entering ValidateCoordinates()" 17 | }, 18 | { 19 | "type": "esriJobMessageTypeInformative", 20 | "description": "Entering DetermineRegion()" 21 | }, 22 | { 23 | "type": "esriJobMessageTypeInformative", 24 | "description": "region: US_" 25 | }, 26 | { 27 | "type": "esriJobMessageTypeInformative", 28 | "description": "Exiting DetermineRegion()" 29 | }, 30 | { 31 | "type": "esriJobMessageTypeInformative", 32 | "description": "US_SLPP2020" 33 | }, 34 | { 35 | "type": "esriJobMessageTypeInformative", 36 | "description": "US_ELEV2020" 37 | }, 38 | { 39 | "type": "esriJobMessageTypeInformative", 40 | "description": "US_240FBFM13" 41 | }, 42 | { 43 | "type": "esriJobMessageTypeInformative", 44 | "description": "No Output projection input provided." 45 | }, 46 | { 47 | "type": "esriJobMessageTypeInformative", 48 | "description": "Entering CreateLocalProjection()" 49 | }, 50 | { 51 | "type": "esriJobMessageTypeInformative", 52 | "description": "local projection string: PROJCS[\"Albers\",GEOGCS[\"GCS_North_American_1983\",DATUM[\"D_North_American_1983\",SPHEROID[\"GRS_1980\",6378137.0,298.257222101]],PRIMEM[\"Greenwich\",0.0],UNIT[\"Degree\",0.0174532925199433]],PROJECTION[\"Albers\"],PARAMETER[\"False_Easting\",0.0],PARAMETER[\"False_Northing\",0.0],PARAMETER[\"Central_Meridian\",-105.31866905647999],PARAMETER[\"Standard_Parallel_1\",40.1122440067607],PARAMETER[\"Standard_Parallel_2\",40.1961284789623],PARAMETER[\"Latitude_Of_Origin\",40.1541862428615],UNIT[\"Meter\",1.0]]" 53 | }, 54 | { 55 | "type": "esriJobMessageTypeInformative", 56 | "description": "Exiting CreateLocalProjection()" 57 | }, 58 | { 59 | "type": "esriJobMessageTypeInformative", 60 | "description": "Start creating geotif" 61 | }, 62 | { 63 | "type": "esriJobMessageTypeInformative", 64 | "description": "Finished creating geotif" 65 | }, 66 | { 67 | "type": "esriJobMessageTypeInformative", 68 | "description": "Start zipping of files" 69 | }, 70 | { 71 | "type": "esriJobMessageTypeInformative", 72 | "description": "All files zipped successfully." 73 | }, 74 | { 75 | "type": "esriJobMessageTypeInformative", 76 | "description": "Job Finished" 77 | }, 78 | { 79 | "type": "esriJobMessageTypeInformative", 80 | "description": "Succeeded at Monday, April 21, 2025 10:51:09 AM (Elapsed Time: 4.63 seconds)" 81 | } 82 | ], 83 | "outputFile": "https://lfps.usgs.gov/arcgis/rest/directories/arcgisjobs/landfireproductservice_gpserver/jd0285f8499c448f7b795044b0d16966a/scratch/jd0285f8499c448f7b795044b0d16966a.zip" 84 | } 85 | -------------------------------------------------------------------------------- /man/landfireAPIv2.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/landfireAPI.R 3 | \name{landfireAPIv2} 4 | \alias{landfireAPIv2} 5 | \title{Call the LANDFIRE Product Service (LFPS) API} 6 | \usage{ 7 | landfireAPIv2( 8 | products, 9 | aoi, 10 | email, 11 | projection = NULL, 12 | resolution = NULL, 13 | edit_rule = NULL, 14 | edit_mask = NULL, 15 | priority_code = NULL, 16 | path = NULL, 17 | max_time = 10000, 18 | method = "curl", 19 | verbose = TRUE, 20 | background = FALSE, 21 | execute = TRUE 22 | ) 23 | } 24 | \arguments{ 25 | \item{products}{Product names as character vector 26 | (see: \href{https://lfps.usgs.gov/products}{Products Table})} 27 | 28 | \item{aoi}{Area of interest as character or numeric vector defined by 29 | latitude and longitude in decimal degrees in WGS84 and ordered 30 | \code{xmin}, \code{ymin}, \code{xmax}, \code{ymax} or a LANDFIRE map zone.} 31 | 32 | \item{email}{Email address as character string. This is a required argument 33 | for the LFPS v2 API. See the \href{https://lfps.usgs.gov/LFProductsServiceUserGuide.pdf}{LFPS Guide} 34 | for more information. Outside of the LFPS API request, this email address 35 | is not used for any other purpose, stored, or shared by \code{rlandfire}.} 36 | 37 | \item{projection}{Optional. A numeric value of the WKID for the output projection 38 | Default is a localized Albers projection.} 39 | 40 | \item{resolution}{Optional. A numeric value between 30-9999 specifying the 41 | resample resolution in meters. Default is 30m.} 42 | 43 | \item{edit_rule}{Optional. A list of character vectors ordered "operator class" 44 | "product", "operator", "value" where "operator class" is one of "condition", 45 | "ORcondition", or "change". Edits are limited to fuel theme products only. 46 | (see: \href{https://lfps.usgs.gov/LFProductsServiceUserGuide.pdf}{LFPS Guide})} 47 | 48 | \item{edit_mask}{Optional. Path to a compressed shapefile (.zip) to be used 49 | as an edit mask. The shapefile must be less than 1MB in size and must 50 | comply with ESRI shapefile naming rules.} 51 | 52 | \item{priority_code}{Optional. Priority code for wildland fire systems/users. 53 | Contact the LANDFIRE help desk for information (\href{mailto:helpdesk@landfire.gov}{helpdesk@landfire.gov})} 54 | 55 | \item{path}{Path to \code{.zip} directory. Passed to \code{\link[utils:download.file]{utils::download.file()}}. 56 | If NULL, a temporary directory is created.} 57 | 58 | \item{max_time}{Maximum time, in seconds, to wait for job to be completed.} 59 | 60 | \item{method}{Passed to \code{\link[utils:download.file]{utils::download.file()}}. See \code{?download.file}} 61 | 62 | \item{verbose}{If FALSE suppress all status messages} 63 | 64 | \item{background}{If TRUE, the function will return immediately and the job 65 | will run in the background. User will need to check the status of the job 66 | manually with \code{checkStatus()}.} 67 | 68 | \item{execute}{If FALSE, the function will build a request without submitting 69 | it to the LFPS API.} 70 | } 71 | \value{ 72 | Returns a \code{landfire_api} object with named elements: 73 | \itemize{ 74 | \item \code{request} - list with elements \code{query}, \code{date}, \code{url}, \code{job_id}, \code{request},\code{dwl_url} 75 | \item \code{content} - Informative messages passed from API 76 | \item \code{response} - Full response 77 | \item \code{status} - Final API status, one of "Failed", "Succeeded", or "Timed out" 78 | \item \code{time} - time of job completion 79 | \item \code{path} - path to save directory 80 | } 81 | } 82 | \description{ 83 | \code{landfireAPIv2} downloads LANDFIRE data by calling the LFPS API 84 | } 85 | \examples{ 86 | \dontrun{ 87 | products <- c("ASP2020", "ELEV2020", "230CC") 88 | aoi <- c("-123.7835", "41.7534", "-123.6352", "41.8042") 89 | email <- "email@example.com" 90 | projection <- 6414 91 | resolution <- 90 92 | edit_rule <- list(c("condition","ELEV2020","lt",500), 93 | c("change", "230CC", "st", 181)) 94 | save_file <- tempfile(fileext = ".zip") 95 | resp <- landfireAPIv2(products, aoi, email, projection, 96 | resolution, edit_rule = edit_rule, 97 | path = save_file) 98 | } 99 | } 100 | -------------------------------------------------------------------------------- /R/getAOI.R: -------------------------------------------------------------------------------- 1 | #' Create extent vector for `landfireAPI()` 2 | #' 3 | #' @description 4 | #' `getAOI` creates an extent vector in WGS84 from spatial data 5 | #' 6 | #' @param data A SpatRaster, SpatVector, sf, stars, or RasterLayer (raster) object 7 | #' @param extend Optional. A numeric vector of 1, 2, or 4 elements to 8 | #' increase the extent by. 9 | #' @param sf_order If `extend` != NULL, logical indicating that the order of the 10 | #' `extend` vector follows [sf::st_bbox()] (`xmin`, `ymin`, `xmax`, `ymax`) when TRUE or 11 | #' [terra::extend()] (`xmin`, `xmax`, `ymin`, `ymax`) when FALSE. This 12 | #' is `FALSE` by default to ensure backwards compatibility with previous versions. 13 | #' 14 | #' @return Returns an extent vector ordered `xmin`, `ymin`, `xmax`, `ymax` 15 | #' with a lat/lon projection. 16 | #' 17 | #' @md 18 | #' @export 19 | #' 20 | #' @examples 21 | #' r <- terra::rast(nrows = 50, ncols = 50, 22 | #' xmin = -123.7835, xmax = -123.6352, 23 | #' ymin = 41.7534, ymax = 41.8042, 24 | #' crs = terra::crs("epsg:4326"), 25 | #' vals = rnorm(2500)) 26 | #' ext <- getAOI(r, c(10, 15)) 27 | #' 28 | getAOI <- function(data, extend = NULL, sf_order = FALSE) { 29 | # Check object class and extract extent as SpatExtent 30 | if(inherits(data, c("SpatRaster", "SpatVector", "sf", "RasterLayer", "stars"))) { 31 | ext <- sf::st_bbox(data) 32 | } else { 33 | stop("`data` must be SpatRaster, SpatVector, sf, stars, or RasterLayer (raster) object") 34 | } 35 | 36 | stopifnot("argument `sf_order` must be logical" = inherits(sf_order, c("logical"))) 37 | 38 | if(!is.null(extend)) { 39 | stopifnot("argument `extend` must be numeric vector" = inherits(extend, c("numeric"))) 40 | stopifnot("argument `extend` must be a numeric vector with a length of 1, 2, or 4 elements" = length(extend) %in% c(1,2,4)) 41 | } 42 | 43 | # if extend !null extend the SpatExtent Object 44 | if(!is.null(extend)){ 45 | 46 | # Change order, for back compatibility 47 | if(sf_order == FALSE & length(extend) == 4) { 48 | extend <- extend[c(1,3,2,4)] 49 | } 50 | 51 | if(length(extend) < 4) { 52 | extend <- rep_len(extend, 4) 53 | } 54 | # Extend 55 | ext <- ext + extend * c(-1,-1,1,1) 56 | } 57 | 58 | # Check object projection and project to lat/lon if need 59 | if(sf::st_crs(data) != sf::st_crs(4326)) { 60 | ext <- sf::st_bbox(sf::st_transform(sf::st_as_sfc(ext), 4326)) 61 | } 62 | as.vector(c(ext$xmin, ext$ymin, ext$xmax, ext$ymax)) 63 | } 64 | 65 | 66 | 67 | #' Find LANDFIRE map zone for use with `landfireAPI()` 68 | #' 69 | #' @description 70 | #' `getZone` returns the LANDFIRE Map Zone(s) a spatial object intersects or the 71 | #' zone number from the zone name. Currently, only map zones within CONUS are 72 | #' supported. 73 | #' 74 | #' @param data An sf object or character string with the map zone name. 75 | #' 76 | #' @return Returns a numeric vector containing the map zone(s) 77 | #' 78 | #' @md 79 | #' @export 80 | #' 81 | #' @examples 82 | #' \dontrun{ 83 | #'v <- sf::st_bbox(sf::st_as_sf(data.frame(x = c(-123.7835,-123.6352), 84 | #' y = c(41.7534,41.8042)), 85 | #' coords = c("x", "y"), 86 | #' crs = 4326)) |> 87 | #' sf::st_as_sfc() 88 | #' zone <- getZone(v) 89 | #'} 90 | #' 91 | getZone <- function(data) { 92 | 93 | if(inherits(data, c("sf", "sfc"))) { 94 | # Extract mz 95 | if(sf::st_crs(data) != sf::st_crs(mapzones)) { 96 | data <- sf::st_transform(data, sf::st_crs(mapzones)) 97 | } 98 | 99 | mz <- sf::st_intersects(data, mapzones) 100 | 101 | } else if(inherits(data, "character")) { 102 | mz <- which(sf::st_drop_geometry(mapzones[,"ZONE_NAME"]) == data) 103 | 104 | } else { 105 | stop("argument `data` must be sf object, or character string") 106 | } 107 | 108 | mz <- unique(unlist(mz)) 109 | 110 | stopifnot("argument `data` must be sf object or zone name within CONUS" = length(mz) != 0) 111 | if(length(mz) > 1) { 112 | warning("Spatial object intersects more than one map zone. `landfireAPI` only accepts one zone at a time!\nConsider using `getAOI()` instead") 113 | } 114 | 115 | mapzones$ZONE_NUM[mz] 116 | 117 | } 118 | -------------------------------------------------------------------------------- /R/utils.R: -------------------------------------------------------------------------------- 1 | #' View LFPS products table 2 | #' 3 | #' @description 4 | #' `viewProducts()` opens the LFPS products table in your web browser 5 | #' 6 | #' 7 | #' @return NULL. Opens the LF products table in your default browser. 8 | #' 9 | #' @md 10 | #' @export 11 | #' 12 | #' @examples 13 | #' \dontrun{ 14 | #' viewProducts() 15 | #' } 16 | 17 | viewProducts <- function() { 18 | utils::browseURL("https://lfps.usgs.gov/products") 19 | } 20 | 21 | #' Read in LANDFIRE products using the GDAL `virtual file system` 22 | #' 23 | #' @description 24 | #' `landfire_vsi()` opens a request LANDFIRE GeoTIFF using the GDAL `virtual 25 | #' file system` (VSI). 26 | #' 27 | #' @param landfire_api A `landfire_api` object created by `landfireAPIv2()` 28 | #' 29 | #' @details 30 | #' The GDAL virtual file system allows you to read in LANDFIRE products without 31 | #' having to download the file to your local machine within 60 minutes of the 32 | #' request or if the file already exists on your local machine without having 33 | #' to unzip it. 34 | #' 35 | #' 36 | #' @return SpatRaster object of the requested LANDFIRE product/s 37 | #' 38 | #' @md 39 | #' @export 40 | #' 41 | #' @examples 42 | #' \dontrun{ 43 | #' aoi <- c("-113.79", "42.148", "-113.56", "42.29") 44 | #' email <- "email@example" 45 | #' rast <- landfireAPIv2(products = "240EVC", 46 | #' aoi = aoi, email = email, 47 | #' method = "none") |> 48 | #' landfireVSI() 49 | #' } 50 | 51 | landfireVSI <- function(landfire_api) { 52 | # checks 53 | if (!inherits(landfire_api, "landfire_api")) { 54 | stop("argument `landfire_api` must be a landfire_api object") 55 | } 56 | if (is.null(landfire_api$path) && is.null(landfire_api$request$dwl_url)) { 57 | stop("The provided `landfire_api` object does not contain a valid `path` or `dwl_url`") 58 | } 59 | # end checks 60 | 61 | if (!is.null(landfire_api$path) && file.exists(landfire_api$path)) { 62 | r <- terra::rast( 63 | sprintf("/vsizip/%s/%s", 64 | landfire_api$path, 65 | grep("\\.tif$",unzip(landfire_api$path, list=T)$Name, 66 | value = TRUE)) 67 | ) 68 | } else if (!is.null(landfire_api$request$dwl_url)) { 69 | if (difftime(Sys.time(), landfire_api$time, units = "min") > 60) { 70 | stop("The requested file is no longer available for download") 71 | } 72 | 73 | r <- terra::rast( 74 | sprintf("/vsizip/vsicurl/%s/%s", 75 | landfire_api$request$dwl_url, 76 | gsub("\\.zip$",".tif", basename(landfire_api$request$dwl_url))) 77 | ) 78 | } else { 79 | stop("No file associated with the provide `landfire_api` object was found") 80 | } 81 | 82 | return(r) 83 | } 84 | 85 | 86 | #' Internal: Build Landfire API object 87 | #' 88 | #' @param params List of parameters to be passed to the API 89 | #' @param request httr2_request object 90 | #' @param init_resp httr2_response object for the initial request 91 | #' @param job_id Job ID 92 | #' @param dwl_url URL to download the file 93 | #' @param content Content of the response 94 | #' @param response httr2_response object for the final request 95 | #' @param status Status of the request 96 | #' @param path Path to the file 97 | #' 98 | #' @return Character vector (length = 1) with formated edit rules call 99 | #' 100 | #' @noRd 101 | #' 102 | #' @examples 103 | #' \dontrun{ 104 | #' 105 | #' } 106 | .build_landfire_api <- function(params = NULL, request = NULL, init_resp = NULL, 107 | job_id = NULL, dwl_url = NULL, content = NULL, 108 | response = NULL, status = NULL, time = NULL, 109 | path = NULL) { 110 | structure( 111 | list( 112 | request = list(query = params, # User input in rlandfire formats 113 | date = Sys.time(), 114 | url = if (!is.null(request)) request$url else NULL, 115 | job_id = job_id, 116 | request = init_resp, 117 | dwl_url = dwl_url), 118 | content = content, 119 | response = response, 120 | status = status, 121 | time = time, 122 | path = path 123 | ), 124 | class = "landfire_api" 125 | ) 126 | } -------------------------------------------------------------------------------- /tests/testthat/test-getAOI.R: -------------------------------------------------------------------------------- 1 | test_that("`getAOI` works with supported object classes", { 2 | r <- terra::rast(nrows = 50, ncols = 50, 3 | xmin = -123.7835, xmax = -123.6352, 4 | ymin = 41.7534, ymax = 41.8042, 5 | crs = terra::crs("epsg:4326"), 6 | vals = rnorm(2500)) 7 | v <- terra::as.polygons(r) 8 | ext <- c(-123.7835, 41.7534, -123.6352, 41.8042) 9 | 10 | expect_equal(getAOI(r), ext) 11 | expect_equal(getAOI(v), ext) 12 | expect_equal(getAOI(sf::st_as_sf(v)), ext) 13 | expect_equal(getAOI(raster::raster(r)), ext) 14 | expect_equal(getAOI(stars::st_as_stars(r)), ext) 15 | 16 | expect_error(getAOI(matrix()), 17 | "`data` must be SpatRaster, SpatVector, sf, stars, or RasterLayer (raster) object", 18 | fixed = TRUE) 19 | 20 | }) 21 | 22 | 23 | test_that("`getAOI()` recognizes arguement errors", { 24 | r <- terra::rast(nrows = 50, ncols = 50, 25 | xmin = -123.7835, xmax = -123.6352, 26 | ymin = 41.7534, ymax = 41.8042, 27 | crs = terra::crs("epsg:4326"), 28 | vals = rnorm(2500)) 29 | 30 | # Check for required arguments 31 | expect_error(getAOI(extend = c(10,15)), 32 | 'argument "data" is missing, with no default') 33 | 34 | expect_error(getAOI(data = r, extend = c(10,15), sf_order = 1), 35 | "argument `sf_order` must be logical") 36 | 37 | # Check class 38 | expect_error(getAOI(r, extend = "string"), 39 | "argument `extend` must be numeric vector") 40 | expect_error(getAOI(r, extend = c(1,2,3)), 41 | "argument `extend` must be a numeric vector with a length of 1, 2, or 4 elements") 42 | expect_error(getAOI(r, sf_order = 1), 43 | "argument `sf_order` must be logical") 44 | 45 | 46 | }) 47 | 48 | test_that("`getAOI` returns correct extended AOI", { 49 | r <- terra::rast(nrows = 50, ncols = 50, 50 | xmin = -123.7835, xmax = -123.6352, 51 | ymin = 41.7534, ymax = 41.8042, 52 | crs = terra::crs("epsg:4326"), 53 | vals = rnorm(2500)) 54 | 55 | ext <- c(-123.7835, 41.7534, -123.6352, 41.8042) 56 | 57 | expect_equal(getAOI(r, extend = c(10)), ext + c(-10, -10, 10, 10)) 58 | expect_equal(getAOI(r, extend = c(10, 15)), ext + c(-10, -15, 10, 15)) 59 | expect_equal(getAOI(r, extend = c(10, 15, 2, 4)), ext + c(-10, -2, 15, 4)) 60 | expect_equal(getAOI(r, extend = c(10, 15, 2, 4), sf_order = TRUE), ext + c(-10, -15, 2, 4)) 61 | }) 62 | 63 | 64 | test_that("`getAOI` returns correct CRS", { 65 | r <- terra::rast(nrows = 50, ncols = 50, 66 | xmin = -2261174.94, xmax = -2247816.36, 67 | ymin = 2412704.65, ymax = 2421673.98, 68 | crs = terra::crs("epsg:5070"), 69 | vals = rnorm(2500)) 70 | 71 | ext <- c(-123.80251, 41.72353, -123.61607, 41.83432) 72 | 73 | # Expect minor differences from transformation 74 | expect_equal(getAOI(r), ext, tolerance = 0.001) 75 | }) 76 | 77 | 78 | # Tests for `getZone` 79 | 80 | test_that("`getZone` works with supported object classes", { 81 | v <- sf::st_bbox(sf::st_as_sf(data.frame(x = c(-123.7835,-123.6352), 82 | y = c(41.7534,41.8042)), 83 | coords = c("x", "y"), 84 | crs = 4326)) |> 85 | sf::st_as_sfc() 86 | 87 | p <- sf::st_as_sf(data.frame(x = c(-123.7835,-123.6352), 88 | y = c(41.7534,41.8042)), 89 | coords = c("x", "y"), 90 | crs = 4326) 91 | 92 | zone <- 3 93 | 94 | # polygon 95 | expect_equal(getZone(v), zone) 96 | # points 97 | expect_equal(getZone(p), zone) 98 | # character string 99 | expect_equal(getZone("Northern California Coastal Range"), zone) 100 | }) 101 | 102 | 103 | test_that("`getZone` recognizes arguement errors", { 104 | v <- sf::st_bbox(sf::st_as_sf(data.frame(x = c(-6.2,-6), 105 | y = c(41.7534,41.8042)), 106 | coords = c("x", "y"), 107 | crs = 4326)) |> 108 | sf::st_as_sfc() 109 | 110 | v_mult <- sf::st_bbox(sf::st_as_sf(data.frame(x = c(-114.77,-114.57), 111 | y = c(33.26,33.37)), 112 | coords = c("x", "y"), 113 | crs = 4326)) |> 114 | sf::st_as_sfc() 115 | 116 | expect_error(getZone(v), 117 | "argument `data` must be sf object or zone name within CONUS") 118 | 119 | expect_error(getZone("Not a Zone"), 120 | "argument `data` must be sf object or zone name within CONUS") 121 | 122 | expect_error(getZone(terra::vect(v)), 123 | "argument `data` must be sf object, or character string") 124 | 125 | expect_warning(getZone(v_mult), 126 | "Spatial object intersects more than one map zone. `landfireAPI` only accepts one zone at a time! 127 | Consider using `getAOI()` instead", fixed = TRUE) 128 | }) 129 | -------------------------------------------------------------------------------- /R/checkStatus.R: -------------------------------------------------------------------------------- 1 | #' Internal: Check the status of an existing LANDFIRE Product Service (LFPS) request 2 | #' 3 | #' @param landfire_api `landfire_api` object returned from `landfireAPIv2()` 4 | #' @param verbose If FALSE suppress all status messages 5 | #' @param method Passed to [utils::download.file()]. See `?download.file` 6 | #' @param i Current iteration 7 | #' @param max_time Maximum time, in seconds, to wait for job to be completed. 8 | #' 9 | #' @return Character vector (length = 1) with formated edit rules call 10 | #' 11 | #' @noRd 12 | #' 13 | #' @examples 14 | #' \dontrun{ 15 | #' .checkStatus_internal(landfire_api, verbose = TRUE, 16 | #' method = "curl", i = 1, max_time = 10000) 17 | #' } 18 | 19 | .checkStatus_internal <- function(landfire_api, verbose = TRUE, method = "curl", 20 | i, max_time) { 21 | 22 | # Checks 23 | stopifnot("argument `landfire_api` must be a landfire_api object" 24 | = inherits(landfire_api, "landfire_api")) 25 | stopifnot("argument `verbose` must be logical" = inherits(verbose, "logical")) 26 | stopifnot("argument `i` must be an integer" = is.numeric(i)) 27 | stopifnot("argument `max_time` must be numeric" = is.numeric(max_time)) 28 | # End Checks 29 | 30 | 31 | # Check status 32 | purpose <- "status" 33 | 34 | job_id <- landfire_api$request$job_id 35 | 36 | # Construct request URL 37 | response <- httr2::request("https://lfps.usgs.gov/api/job/") |> 38 | httr2::req_url_path_append(purpose) |> 39 | httr2::req_url_query("JobId" = job_id) |> 40 | httr2::req_user_agent("rlandfire (https://CRAN.R-project.org/package=rlandfire)") |> 41 | httr2::req_headers("Accept" = "application/json") |> 42 | httr2::req_error(is_error = \(response) FALSE) |> 43 | httr2::req_perform() 44 | 45 | # resp_body <- jsonlite::fromJSON(httr2::resp_body_string(response)) 46 | resp_body <- httr2::resp_body_json(response) 47 | 48 | status <- httr2::resp_status(response) 49 | 50 | if(status != 200) { 51 | stop("\tAPI request failed with status code: ", status, 52 | "\n\tLFPS Error message: ", resp_body$message) 53 | } 54 | 55 | # Parse content for messaging and error reporting 56 | job_status <- resp_body$status 57 | inf_msg <- sapply(resp_body$messages, 58 | function(msg) paste(msg[[1]], msg[[2]], 59 | sep = ": ")) 60 | 61 | if (verbose == TRUE) { 62 | # There is a better way to do this but for now...clear console each loop: 63 | cat("\014") 64 | cat("Job Status: ", job_status, "\nJob ID: ", job_id, 65 | "\nQueue Position: ", resp_body$queuePosition, 66 | "\nJob Messages:\n", paste(inf_msg, collapse = "\n"), 67 | "\n-------------------", 68 | "\nElapsed time: ", sprintf("%.1f", round(i*0.1, 1)), "s", "(Max time:", max_time, "s)", 69 | "\n-------------------\n") 70 | } 71 | 72 | call_status <- "pending" 73 | 74 | # If failed exit and report 75 | if(grepl("Failed",job_status)) { 76 | call_status <- "Failed" 77 | 78 | warning("Job ", job_id, " has failed with:\n\t", 79 | inf_msg[grepl("ERROR", inf_msg)], 80 | "\nPlease check the LFPS API documentation for more information.") 81 | 82 | # If success report success and download file 83 | } else if (grepl("Succeeded",job_status)) { 84 | dwl_url <- resp_body$outputFile 85 | 86 | if (method != "none"){ 87 | utils::download.file(dwl_url, landfire_api$path, 88 | method = method, quiet = !verbose) 89 | call_status <- "Succeeded" 90 | } else { 91 | call_status <- "Succeeded (download skipped)" 92 | } 93 | landfire_api$request$dwl_url <- dwl_url 94 | } 95 | 96 | # Update landfire_api object 97 | landfire_api$request$job_id <- job_id 98 | landfire_api$content <- inf_msg 99 | landfire_api$response <- response 100 | landfire_api$status <- call_status 101 | landfire_api$time <- Sys.time() 102 | 103 | return(landfire_api) 104 | 105 | } 106 | 107 | #' Check the status of an existing LANDFIRE Product Service (LFPS) request 108 | #' 109 | #' @description 110 | #' `checkStatus` checks if a previous request is complete and downloads available data 111 | #' 112 | #' @param landfire_api `landfire_api` object returned from `landfireAPIv2()` 113 | #' @param verbose If FALSE suppress all status messages 114 | #' @param method Passed to [utils::download.file()]. See `?download.file` or 115 | #' use "none" to skip download and use `landfire_vsi()` 116 | #' 117 | #' @return 118 | #' Returns a `landfire_api` object with named elements: 119 | #' * `request` - list with elements `query`, `date`, `url`, `job_id`, `request`,`dwl_url` 120 | #' * `content` - Informative messages passed from API 121 | #' * `response` - Full response 122 | #' * `status` - Final API status, one of "Failed", "Succeeded", or "Timed out" 123 | #' * `time` - time of job completion 124 | #' * `path` - path to save directory 125 | #' 126 | #' @md 127 | #' @export 128 | #' 129 | #' @examples 130 | #' \dontrun{ 131 | #' products <- c("ASP2020", "ELEV2020", "230CC") 132 | #' aoi <- c("-123.7835", "41.7534", "-123.6352", "41.8042") 133 | #' email <- "email@@example.com" 134 | #' resp <- landfireAPIv2(products, aoi, email, background = TRUE) 135 | #' checkStatus(resp) 136 | #' } 137 | checkStatus <- function(landfire_api, verbose = TRUE, method = "curl") { 138 | # Checks 139 | # Missing 140 | stopifnot("argument `landfire_api` is missing with no default" 141 | = !missing(landfire_api)) 142 | # Classes 143 | stopifnot("argument `landfire_api` must be a landfire_api object" 144 | = inherits(landfire_api, "landfire_api")) 145 | stopifnot("argument `verbose` must be logical" = inherits(verbose, "logical")) 146 | stopifnot( 147 | "`method` is invalid. See `?download.file`" = 148 | method %in% c("internal", "libcurl", "wget", "curl", "wininet", "auto", "none") 149 | ) 150 | # End Checks 151 | .checkStatus_internal(landfire_api, verbose = verbose, method = method, 152 | i = 1, max_time = 0) 153 | } 154 | 155 | #' Cancel an active LANDFIRE Product Service (LFPS) API job 156 | #' 157 | #' @description 158 | #' `cancelJob()` sends a request to cancel a LFPS API request 159 | #' 160 | #' @param job_id The job ID of the LFPS API request as a character string 161 | #' 162 | #' @return NULL. Prints a message to the console about the job status. 163 | #' 164 | #' @md 165 | #' @export 166 | #' 167 | #' @examples 168 | #' \dontrun{ 169 | #' products <- c("ASP2020", "ELEV2020", "230CC") 170 | #' aoi <- c("-123.7835", "41.7534", "-123.6352", "41.8042") 171 | #' email <- "email@@example.com>" 172 | #' 173 | #' resp <- landfireAPIv2(products, aoi, email, background = TRUE) 174 | #' 175 | #' job_id <- resp$request$job_id #Get job_id from a previous request 176 | #' cancelJob("job_id") 177 | #' } 178 | 179 | cancelJob <- function(job_id) { 180 | 181 | #### Checks 182 | # Missing 183 | stopifnot("argument `job_id` is missing with no default" = !missing(job_id)) 184 | 185 | # Classes 186 | stopifnot("argument `job_id` must be a character string" 187 | = inherits(job_id, "character")) 188 | 189 | #### End Checks 190 | 191 | # Define Parameters 192 | params <- list( 193 | JobId = job_id 194 | ) 195 | 196 | purpose <- "cancel" 197 | 198 | # Construct request URL 199 | request <- httr2::request("https://lfps.usgs.gov/api/job/") |> 200 | httr2::req_url_path_append(purpose) |> 201 | httr2::req_url_query(!!!params) |> 202 | httr2::req_user_agent("rlandfire (https://CRAN.R-project.org/package=rlandfire)") 203 | 204 | # Submit job 205 | response <- httr2::req_perform(request) 206 | 207 | # Report status 208 | resp_body <- httr2::resp_body_json(response) 209 | message(resp_body$message) 210 | } 211 | 212 | #' Check if the LFPS API is available 213 | #' 214 | #' @description 215 | #' `healthCheck()` checks if the LPFS API is available 216 | #' 217 | #' @return NULL. Prints a message to the console about the current LFPS status. 218 | #' 219 | #' @md 220 | #' @export 221 | #' 222 | #' @examples 223 | #' \dontrun{ 224 | #' healthCheck() 225 | #' } 226 | 227 | healthCheck <- function() { 228 | 229 | # Construct request URL 230 | request <- httr2::request("https://lfps.usgs.gov/api/healthCheck") |> 231 | httr2::req_user_agent("rlandfire (https://CRAN.R-project.org/package=rlandfire)") |> 232 | httr2::req_headers("Accept" = "application/json") 233 | 234 | # Submit job 235 | response <- httr2::req_perform(request) 236 | 237 | # Parse content for messaging and error reporting 238 | resp_body <- httr2::resp_body_json(response) 239 | 240 | if (resp_body$success) { 241 | message("The LFPS API is available") 242 | } else { 243 | warning("The LFPS API is currently down.\n", 244 | "Please notify the LANDFIRE helpdesk at of the following error:\n", 245 | resp_body$message) 246 | } 247 | } 248 | -------------------------------------------------------------------------------- /vignettes/rlandfire.Rmd: -------------------------------------------------------------------------------- 1 | --- 2 | title: "Introduction to rlandfire" 3 | output: rmarkdown::html_vignette 4 | vignette: > 5 | %\VignetteIndexEntry{Introduction to rlandfire} 6 | %\VignetteEngine{knitr::rmarkdown} 7 | %\VignetteEncoding{UTF-8} 8 | --- 9 | 10 | ```{r, include = FALSE} 11 | knitr::opts_chunk$set( 12 | collapse = TRUE, 13 | comment = "#>" 14 | ) 15 | ``` 16 | 17 | 18 | 19 | ## rlandfire: Tools for Accessing and Working with LANDFIRE in R 20 | \ 21 | \ 22 | `rlandfire` provides access to a diverse suite of spatial data layers via the LANDFIRE Product Services ([LFPS](https://lfps.usgs.gov/arcgis/rest/services/LandfireProductService/GPServer)) API. [LANDFIRE](https://landfire.gov) is a joint program of the USFS, DOI, and other major partners, which provides data layers for wildfire management, fuel modeling, ecology, natural resource management, climate, conservation, etc. The complete list of available layers and additional resources can be found on the LANDFIRE webpage. 23 | 24 | ## Installation 25 | 26 | Install `rlandfire` from CRAN: 27 | 28 | ``` r 29 | install.packages("rlandfire") 30 | ``` 31 | 32 | The development version of `rlandfire` can be installed from GitHub with: 33 | 34 | ``` r 35 | # install.packages("devtools") 36 | devtools::install_github("bcknr/rlandfire") 37 | ``` 38 | 39 | Set `build_vignettes = TRUE` to access this vignette in R: 40 | 41 | ``` r 42 | devtools::install_github("bcknr/rlandfire", build_vignettes = TRUE) 43 | ``` 44 | 45 | This package is still in development, and users may encounter bugs or unexpected behavior. Please report any issues, feature requests, or suggestions in the package's [GitHub repo](https://github.com/bcknr/rlandfire/issues). 46 | 47 | ## Using `rlandfire` 48 | 49 | To demonstrate `rlandfire`, we will explore how ponderosa pine forest canopy cover changed after the 2020 Calwood fire near Boulder, Colorado. 50 | 51 | ```{r setup} 52 | library(rlandfire) 53 | library(sf) 54 | library(terra) 55 | library(foreign) 56 | ``` 57 | 58 | First, we will load the Calwood Fire perimeter data which was downloaded from Boulder County's [geospatial data hub](https://opendata-bouldercounty.hub.arcgis.com/). 59 | 60 | ```{r, fig.align = "center", fig.height = 5, fig.width = 7} 61 | boundary_file <- file.path(tempdir(), "wildfire") 62 | utils::unzip(system.file("extdata/wildfire.zip", package = "rlandfire"), 63 | exdir = tempdir()) 64 | 65 | boundary <- st_read(file.path(boundary_file, "wildfire.shp")) %>% 66 | sf::st_transform(crs = st_crs(32613)) 67 | 68 | plot(boundary$geometry, main = "Calwood Fire Boundary (2020)", 69 | border = "red", lwd = 1.5) 70 | ``` 71 | 72 | ### AOI 73 | 74 | We can use the function `rlandfire::getAOI()` to create an area of interest (AOI) vector with the correct format for `landfireAPIv2()`. `getAOI()` handles several steps for us, it ensures that the AOI is returned in the correct order (`xmin`, `ymin`, `xmax`, `ymax`) and converts the AOI to latitude and longitude coordinates (as required by the API) if needed. 75 | 76 | Using the `extend` argument, we will increase the AOI by 1 km in all directions to provide additional context surrounding the burned area. This argument takes an optional numeric vector of 1, 2, or 4 elements. 77 | 78 | ```{r} 79 | aoi <- getAOI(boundary, extend = 1000) 80 | aoi 81 | ``` 82 | 83 | Alternatively, you can supply a LANDFIRE map zone number in place of the AOI vector. The function `getZone()` returns the zone number containing an `sf` object or which corresponds to the supplied zone name. See `help("getZone")` for more information and an example. 84 | 85 | ### Products 86 | 87 | For this example, we are interested in canopy cover data for two years, 2019 (`200CC_19`) and 2022 (`220CC_22`), and existing vegetation type (`200EVT`). All available data products, and their abbreviated names, can be found in the [products table](https://lfps.usgs.gov/products) which can be opened by calling `viewProducts()`. 88 | 89 | ```{r} 90 | products <- c("200CC_19", "220CC_22", "200EVT") 91 | ``` 92 | 93 | ### Email 94 | 95 | ```{r} 96 | email <- "rlandfire@example.com" 97 | ``` 98 | 99 | ### Projection and resolution 100 | 101 | We can ask the API to project the data to the same CRS as our fire perimeter data by providing the `WKID` for our CRS of interest and a resolution of our choosing, in meters. 102 | 103 | ```{r} 104 | projection <- 32613 105 | resolution <- 90 106 | ``` 107 | 108 | ### Edit rule 109 | 110 | We will use the `edit_rule` argument to filter out canopy cover data that does not correspond to Ponderosa Pine Woodland. The `edit_rule` statement should tell the API that when existing vegetation cover is anything other than Ponderosa Pine Woodland (`7054`), the value of the canopy cover layers should be set to a specified value. 111 | 112 | To do so, we specify that when `220EVT` is not equal (`ne`) to `7054`, the "condition," the canopy cover layers should be set equal (`st`) to `1`, the "change." The edit rule syntax is explained in more depth in the [LFPS guide](https://lfps.usgs.gov/LFProductsServiceUserGuide.pdf). 113 | 114 | *(How the API applies edit rules can be unintuitive. For example, if we used 'clear value' [`cv`] or set the value outside of 0-100 the edits we want would not work. To work around this behavior, we set the values to `1` since it is not found in the original data set.*) 115 | 116 | ```{r} 117 | edit_rule <- list(c("condition","200EVT","ne",7054), 118 | c("change", "200CC_19", "st", 1), 119 | c("change", "220CC_22", "st", 1)) 120 | ``` 121 | 122 | Note: Edits are performed in the order that they are listed and are limited to fuel theme products (i.e., Fire Behavior Fuel Model 13, Fire Behavior Fuel Model 40, Forest Canopy Base Height, Forest Canopy Bulk Density, Forest Canopy Cover, and Forest Canopy Height). 123 | 124 | If we wanted to restrict these edits to a certain area we could pass the path to a zip archive (`.zip`) containing a shapefile to `edit_mask`: 125 | 126 | ```{r, eval=FALSE} 127 | edit_mask <- "path/to/wildfire.zip" 128 | ``` 129 | 130 | Note: The file must follow ESRI shapefile naming standards (e.g., no special characters) and be less than 1MB in size. 131 | 132 | ### Path 133 | 134 | Finally, we will provide a path to a temporary zip file. Setting the path as a temp file is not strictly necessary because if `path` is left blank `landfireAPIv2()` will save the data to a temporary folder by default. 135 | 136 | ```{r} 137 | path <- tempfile(fileext = ".zip") 138 | ``` 139 | 140 | ### Call `landfireAPIv2()` 141 | 142 | Now we are able to submit a request to the LANDFIRE Product Services API with the `landfireAPIv2()` function. 143 | 144 | ```{r,eval=FALSE} 145 | resp <- landfireAPIv2(products = products, 146 | aoi = aoi, 147 | email = email, 148 | projection = projection, 149 | resolution = resolution, 150 | edit_rule = edit_rule, 151 | path = path, 152 | verbose = FALSE) 153 | ``` 154 | 155 | `landfireAPIv2()` will download your requested data into the folder provided in the path argument. If you did not provide one, you can find the path to your data in the `$path` element of the `landfire_api` object. 156 | 157 | ```{r,eval=FALSE} 158 | resp$path 159 | ``` 160 | 161 | ### Load and process LF data 162 | 163 | ```{r,include=FALSE} 164 | path <- system.file("extdata/LFPS_Return.zip", package = "rlandfire") 165 | ``` 166 | 167 | 168 | The files returned by the LFPS API are compressed `.zip` files. We need to unzip the directory before reading the `.tif` file. Note: all additional metadata is included in this same directory. 169 | 170 | ```{r} 171 | lf_dir <- file.path(tempdir(), "lf") 172 | utils::unzip(path, exdir = lf_dir) 173 | 174 | lf <- terra::rast(list.files(lf_dir, pattern = ".tif$", 175 | full.names = TRUE, 176 | recursive = TRUE)) 177 | ``` 178 | 179 | Now we can reclassify the canopy cover layers to remove any values which are not classified as Ponderosa Pine, calculate the change, and plot our results. 180 | 181 | ```{r, fig.align = "center", fig.height = 5, fig.width = 7} 182 | lf$US_200CC_19[lf$US_200CC_19 == 1] <- NA 183 | lf$US_220CC_22[lf$US_220CC_22 == 1] <- NA 184 | 185 | change <- lf$US_220CC_22 - lf$US_200CC_19 186 | 187 | plot(change, col = rev(terrain.colors(250)), 188 | main = "Canopy Cover Loss - Calwood Fire (2020)", 189 | xlab = "Easting", 190 | ylab = "Northing") 191 | plot(boundary$geometry, add = TRUE, col = NA, 192 | border = "black", lwd = 2) 193 | ``` 194 | 195 | ### Working with Categorical Products 196 | 197 | The LFPS REST API now embeds attributes in the GeoTIFF files for some variables 198 | and returns a database file (`.dbf`) containing the full attribute table. 199 | 200 | To demonstrate, we will download the Existing Vegetation Cover product from LF 2.4.0 201 | (`240EVC`). Unlike in the example above we will submit a minimal request with 202 | the default projection and resolution. We will also allow `rlandfire` to 203 | save the files to a temporary directory automatically. As mentioned above, we 204 | can find the path to the temporary directory in the `$path` element of the 205 | `landfire_api` object returned by `landfireAPIv2()`. 206 | 207 | ```{r,eval=FALSE} 208 | resp <- landfireAPIv2(products = "240EVC", 209 | aoi = aoi, 210 | email = email, 211 | verbose = FALSE) 212 | ``` 213 | 214 | ```{r,include=FALSE} 215 | resp <- c() 216 | resp$path <- system.file("extdata/LFPS_cat_Return.zip", package = "rlandfire") 217 | ``` 218 | 219 | When we read in and plot the EVC layer the legend will now list the `classnames` 220 | for each vegetation type. 221 | 222 | ```{r} 223 | lf_cat <- file.path(tempdir(), "lf_cat") 224 | utils::unzip(resp$path, exdir = lf_cat) 225 | 226 | evc <- terra::rast(list.files(lf_cat, pattern = ".tif$", 227 | full.names = TRUE, 228 | recursive = TRUE)) 229 | 230 | plot(evc) 231 | ``` 232 | 233 | To access the values each `classname` is assigned to we can uses the `levels()` 234 | function. This returns a simple two column data frame containing both the index 235 | and active category, in our case the vegetation cover classes. 236 | 237 | ```{r} 238 | head(levels(evc)[[1]]) 239 | ``` 240 | 241 | Alternatively, we can access the full attribute table using two methods. 242 | We can use the function `cats()` which works similarly to `levels()` but 243 | returns the full attribute table as a data frame. Alternatively, we can read the 244 | database file using `foreign::read.dbf()`. Both methods return similar results, 245 | although in this case, we see that the `.dbf` file includes an additional `Count` 246 | column not included in the data frame returned from `cats()`. 247 | 248 | ```{r} 249 | # cats 250 | attr_tbl <- cats(evc) 251 | 252 | # Find path to database file 253 | dbf <- list.files(lf_cat, pattern = ".dbf$", 254 | full.names = TRUE, 255 | recursive = TRUE) 256 | 257 | # Read file 258 | dbf_tbl <- foreign::read.dbf(dbf) 259 | 260 | head(attr_tbl[[1]]) 261 | head(dbf_tbl) 262 | ``` 263 | 264 | ### Citation 265 | 266 | Visit the [LANDFIRE webpage](https://landfire.gov/data/citation) for information on citing LANDFIRE data layers. The package citation information can be viewed with `citation("rlandfire")`. 267 | -------------------------------------------------------------------------------- /README.Rmd: -------------------------------------------------------------------------------- 1 | --- 2 | output: github_document 3 | --- 4 | 5 | 6 | 7 | ```{r, include = FALSE} 8 | knitr::opts_chunk$set( 9 | collapse = TRUE, 10 | comment = "#>", 11 | fig.path = "man/figures/README-", 12 | out.width = "100%" 13 | ) 14 | ``` 15 | 16 | 17 | 18 |

19 | 20 | ## rlandfire: Interface to 'LANDFIRE Product Service' API 21 | 22 | 23 | ![](https://img.shields.io/github/r-package/v/bcknr/rlandfire) [![R-CMD-check](https://github.com/bcknr/rlandfire/actions/workflows/R-CMD-check.yaml/badge.svg)](https://github.com/bcknr/rlandfire/actions/workflows/R-CMD-check.yaml) 24 | 25 | 26 | `rlandfire` provides access to a diverse suite of spatial data layers via the LANDFIRE Product Services ([LFPS](https://lfps.usgs.gov/arcgis/rest/services/LandfireProductService/GPServer)) API. [LANDFIRE](https://landfire.gov) is a joint program of the USFS, DOI, and other major partners, which provides data layers for wildfire management, fuel modeling, ecology, natural resource management, climate, conservation, etc. The complete list of available layers and additional resources can be found on the LANDFIRE webpage. 27 | 28 | ## Installation 29 | 30 | Install `rlandfire` from CRAN: 31 | 32 | ``` r 33 | install.packages("rlandfire") 34 | ``` 35 | 36 | The development version of `rlandfire` can be installed from GitHub with: 37 | 38 | ``` r 39 | # install.packages("devtools") 40 | devtools::install_github("bcknr/rlandfire") 41 | ``` 42 | 43 | Set `build_vignettes = TRUE` to access this vignette in R: 44 | 45 | ``` r 46 | devtools::install_github("bcknr/rlandfire", build_vignettes = TRUE) 47 | ``` 48 | 49 | This package is still in development, and users may encounter bugs or unexpected behavior. Please report any issues, feature requests, or suggestions in the package's [GitHub repo](https://github.com/bcknr/rlandfire/issues). 50 | 51 | ## Using `rlandfire` 52 | 53 | To demonstrate `rlandfire`, we will explore how ponderosa pine forest canopy cover changed after the 2020 Calwood fire near Boulder, Colorado. 54 | 55 | ```{r setup, message = FALSE, warning = FALSE} 56 | library(rlandfire) 57 | library(sf) 58 | library(terra) 59 | library(foreign) 60 | ``` 61 | 62 | First, we will load the Calwood Fire perimeter data which was downloaded from Boulder County's [geospatial data hub](https://opendata-bouldercounty.hub.arcgis.com/). 63 | 64 | ```{r, fig.align = "center", fig.height = 5, fig.width = 7} 65 | boundary_file <- file.path(tempdir(), "wildfire") 66 | utils::unzip(system.file("extdata/wildfire.zip", package = "rlandfire"), 67 | exdir = tempdir()) 68 | 69 | boundary <- st_read(file.path(boundary_file, "wildfire.shp")) %>% 70 | sf::st_transform(crs = st_crs(32613)) 71 | 72 | plot(boundary$geometry, main = "Calwood Fire Boundary (2020)", 73 | border = "red", lwd = 1.5) 74 | ``` 75 | 76 | ### AOI 77 | 78 | We can use the function `rlandfire::getAOI()` to create an area of interest (AOI) vector with the correct format for `landfireAPIv2()`. `getAOI()` handles several steps for us, it ensures that the AOI is returned in the correct order (`xmin`, `ymin`, `xmax`, `ymax`) and converts the AOI to latitude and longitude coordinates (as required by the API) if needed. 79 | 80 | Using the `extend` argument, we will increase the AOI by 1 km in all directions to provide additional context surrounding the burned area. This argument takes an optional numeric vector of 1, 2, or 4 elements. 81 | 82 | ```{r} 83 | aoi <- getAOI(boundary, extend = 1000) 84 | aoi 85 | ``` 86 | 87 | Alternatively, you can supply a LANDFIRE map zone number in place of the AOI vector. The function `getZone()` returns the zone number containing an `sf` object or which corresponds to the supplied zone name. See `help("getZone")` for more information and an example. 88 | 89 | ### Products 90 | 91 | For this example, we are interested in canopy cover data for two years, 2019 (`200CC_19`) and 2022 (`220CC_22`), and existing vegetation type (`200EVT`). All available data products, and their abbreviated names, can be found in the [products table](https://lfps.usgs.gov/products) which can be opened by calling `viewProducts()`. 92 | 93 | ```{r} 94 | products <- c("200CC_19", "220CC_22", "200EVT") 95 | ``` 96 | 97 | ### Email 98 | 99 | ```{r} 100 | email <- "rlandfire@example.com" 101 | ``` 102 | 103 | ### Projection and resolution 104 | 105 | We can ask the API to project the data to the same CRS as our fire perimeter data by providing the `WKID` for our CRS of interest and a resolution of our choosing, in meters. 106 | 107 | ```{r} 108 | projection <- 32613 109 | resolution <- 90 110 | ``` 111 | 112 | ### Edit rule 113 | 114 | We will use the `edit_rule` argument to filter out canopy cover data that does not correspond to Ponderosa Pine Woodland. The `edit_rule` statement should tell the API that when existing vegetation cover is anything other than Ponderosa Pine Woodland (`7054`), the value of the canopy cover layers should be set to a specified value. 115 | 116 | To do so, we specify that when `220EVT` is not equal (`ne`) to `7054`, the "condition," the canopy cover layers should be set equal (`st`) to `1`, the "change." The edit rule syntax is explained in more depth in the [LFPS guide](https://lfps.usgs.gov/LFProductsServiceUserGuide.pdf). 117 | 118 | *(How the API applies edit rules can be unintuitive. For example, if we used 'clear value' [`cv`] or set the value outside of 0-100 the edits we want would not work. To work around this behavior, we set the values to `1` since it is not found in the original data set.*) 119 | 120 | ```{r} 121 | edit_rule <- list(c("condition","200EVT","ne",7054), 122 | c("change", "200CC_19", "st", 1), 123 | c("change", "220CC_22", "st", 1)) 124 | ``` 125 | 126 | Note: Edits are performed in the order that they are listed and are limited to fuel theme products (i.e., Fire Behavior Fuel Model 13, Fire Behavior Fuel Model 40, Forest Canopy Base Height, Forest Canopy Bulk Density, Forest Canopy Cover, and Forest Canopy Height). 127 | 128 | If we wanted to restrict these edits to a certain area we could pass the path to a zip archive (`.zip`) containing a shapefile to `edit_mask`: 129 | 130 | ```{r, eval=FALSE} 131 | edit_mask <- "path/to/wildfire.zip" 132 | ``` 133 | 134 | Note: The file must follow ESRI shapefile naming standards (e.g., no special characters) and be less than 1MB in size. 135 | 136 | ### Path 137 | 138 | Finally, we will provide a path to a temporary zip file. Setting the path as a temp file is not strictly necessary because if `path` is left blank `landfireAPIv2()` will save the data to a temporary folder by default. 139 | 140 | ```{r} 141 | path <- tempfile(fileext = ".zip") 142 | ``` 143 | 144 | ### Call `landfireAPIv2()` 145 | 146 | Now we are able to submit a request to the LANDFIRE Product Services API with the `landfireAPIv2()` function. 147 | 148 | ```{r,eval=FALSE} 149 | resp <- landfireAPIv2(products = products, 150 | aoi = aoi, 151 | email = email, 152 | projection = projection, 153 | resolution = resolution, 154 | edit_rule = edit_rule, 155 | path = path, 156 | verbose = FALSE) 157 | ``` 158 | 159 | `landfireAPIv2()` will download your requested data into the folder provided in the path argument. If you did not provide one, you can find the path to your data in the `$path` element of the `landfire_api` object. 160 | 161 | ```{r,eval=FALSE} 162 | resp$path 163 | ``` 164 | 165 | ### Load and process LF data 166 | 167 | ```{r,include=FALSE} 168 | path <- system.file("extdata/LFPS_Return.zip", package = "rlandfire") 169 | ``` 170 | 171 | 172 | The files returned by the LFPS API are compressed `.zip` files. We need to unzip the directory before reading the `.tif` file. Note: all additional metadata is included in this same directory. 173 | 174 | ```{r} 175 | lf_dir <- file.path(tempdir(), "lf") 176 | utils::unzip(path, exdir = lf_dir) 177 | 178 | lf <- terra::rast(list.files(lf_dir, pattern = ".tif$", 179 | full.names = TRUE, 180 | recursive = TRUE)) 181 | ``` 182 | 183 | Now we can reclassify the canopy cover layers to remove any values which are not classified as Ponderosa Pine, calculate the change, and plot our results. 184 | 185 | ```{r, fig.align = "center", fig.height = 5, fig.width = 7} 186 | lf$US_200CC_19[lf$US_200CC_19 == 1] <- NA 187 | lf$US_220CC_22[lf$US_220CC_22 == 1] <- NA 188 | 189 | change <- lf$US_220CC_22 - lf$US_200CC_19 190 | 191 | plot(change, col = rev(terrain.colors(250)), 192 | main = "Canopy Cover Loss - Calwood Fire (2020)", 193 | xlab = "Easting", 194 | ylab = "Northing") 195 | plot(boundary$geometry, add = TRUE, col = NA, 196 | border = "black", lwd = 2) 197 | ``` 198 | 199 | ### Working with Categorical Products 200 | 201 | The LFPS REST API now embeds attributes in the GeoTIFF files for some variables 202 | and returns a database file (`.dbf`) containing the full attribute table. 203 | 204 | To demonstrate, we will download the Existing Vegetation Cover product from LF 2.4.0 205 | (`240EVC`). Unlike in the example above we will submit a minimal request with 206 | the default projection and resolution. We will also allow `rlandfire` to 207 | save the files to a temporary directory automatically. As mentioned above, we 208 | can find the path to the temporary directory in the `$path` element of the 209 | `landfire_api` object returned by `landfireAPIv2()`. 210 | 211 | ```{r,eval=FALSE} 212 | resp <- landfireAPIv2(products = "240EVC", 213 | aoi = aoi, 214 | email = email, 215 | verbose = FALSE) 216 | ``` 217 | 218 | ```{r,include=FALSE} 219 | resp <- c() 220 | resp$path <- system.file("extdata/LFPS_cat_Return.zip", package = "rlandfire") 221 | ``` 222 | 223 | When we read in and plot the EVC layer the legend will now list the `classnames` 224 | for each vegetation type. 225 | 226 | ```{r} 227 | lf_cat <- file.path(tempdir(), "lf_cat") 228 | utils::unzip(resp$path, exdir = lf_cat) 229 | 230 | evc <- terra::rast(list.files(lf_cat, pattern = ".tif$", 231 | full.names = TRUE, 232 | recursive = TRUE)) 233 | 234 | plot(evc) 235 | ``` 236 | 237 | To access the values each `classname` is assigned to we can uses the `levels()` 238 | function. This returns a simple two column data frame containing both the index 239 | and active category, in our case the vegetation cover classes. 240 | 241 | ```{r} 242 | head(levels(evc)[[1]]) 243 | ``` 244 | 245 | Alternatively, we can access the full attribute table using two methods. 246 | We can use the function `cats()` which works similarly to `levels()` but 247 | returns the full attribute table as a data frame. Alternatively, we can read the 248 | database file using `foreign::read.dbf()`. Both methods return similar results, 249 | although in this case, we see that the `.dbf` file includes an additional `Count` 250 | column not included in the data frame returned from `cats()`. 251 | 252 | ```{r} 253 | # cats 254 | attr_tbl <- cats(evc) 255 | 256 | # Find path to database file 257 | dbf <- list.files(lf_cat, pattern = ".dbf$", 258 | full.names = TRUE, 259 | recursive = TRUE) 260 | 261 | # Read file 262 | dbf_tbl <- foreign::read.dbf(dbf) 263 | 264 | head(attr_tbl[[1]]) 265 | head(dbf_tbl) 266 | ``` 267 | 268 | ### Citation 269 | 270 | Visit the [LANDFIRE webpage](https://landfire.gov/data/citation) for information on citing LANDFIRE data layers. The package citation information can be viewed with `citation("rlandfire")`. 271 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 |

7 | 8 | ## rlandfire: Interface to ‘LANDFIRE Product Service’ API 9 | 10 | 11 | 12 | ![](https://img.shields.io/github/r-package/v/bcknr/rlandfire) 13 | [![R-CMD-check](https://github.com/bcknr/rlandfire/actions/workflows/R-CMD-check.yaml/badge.svg)](https://github.com/bcknr/rlandfire/actions/workflows/R-CMD-check.yaml) 14 | 15 | 16 | `rlandfire` provides access to a diverse suite of spatial data layers 17 | via the LANDFIRE Product Services 18 | ([LFPS](https://lfps.usgs.gov/arcgis/rest/services/LandfireProductService/GPServer)) 19 | API. [LANDFIRE](https://landfire.gov) is a joint program of the USFS, 20 | DOI, and other major partners, which provides data layers for wildfire 21 | management, fuel modeling, ecology, natural resource management, 22 | climate, conservation, etc. The complete list of available layers and 23 | additional resources can be found on the LANDFIRE webpage. 24 | 25 | ## Installation 26 | 27 | Install `rlandfire` from CRAN: 28 | 29 | ``` r 30 | install.packages("rlandfire") 31 | ``` 32 | 33 | The development version of `rlandfire` can be installed from GitHub 34 | with: 35 | 36 | ``` r 37 | # install.packages("devtools") 38 | devtools::install_github("bcknr/rlandfire") 39 | ``` 40 | 41 | Set `build_vignettes = TRUE` to access this vignette in R: 42 | 43 | ``` r 44 | devtools::install_github("bcknr/rlandfire", build_vignettes = TRUE) 45 | ``` 46 | 47 | This package is still in development, and users may encounter bugs or 48 | unexpected behavior. Please report any issues, feature requests, or 49 | suggestions in the package’s [GitHub 50 | repo](https://github.com/bcknr/rlandfire/issues). 51 | 52 | ## Using `rlandfire` 53 | 54 | To demonstrate `rlandfire`, we will explore how ponderosa pine forest 55 | canopy cover changed after the 2020 Calwood fire near Boulder, Colorado. 56 | 57 | ``` r 58 | library(rlandfire) 59 | library(sf) 60 | library(terra) 61 | library(foreign) 62 | ``` 63 | 64 | First, we will load the Calwood Fire perimeter data which was downloaded 65 | from Boulder County’s [geospatial data 66 | hub](https://opendata-bouldercounty.hub.arcgis.com/). 67 | 68 | ``` r 69 | boundary_file <- file.path(tempdir(), "wildfire") 70 | utils::unzip(system.file("extdata/wildfire.zip", package = "rlandfire"), 71 | exdir = tempdir()) 72 | 73 | boundary <- st_read(file.path(boundary_file, "wildfire.shp")) %>% 74 | sf::st_transform(crs = st_crs(32613)) 75 | #> Reading layer `wildfire' from data source `/tmp/RtmpV4trFT/wildfire/wildfire.shp' using driver `ESRI Shapefile' 76 | #> Simple feature collection with 1 feature and 7 fields 77 | #> Geometry type: MULTIPOLYGON 78 | #> Dimension: XY 79 | #> Bounding box: xmin: -105.3901 ymin: 40.12149 xmax: -105.2471 ymax: 40.18701 80 | #> Geodetic CRS: WGS 84 81 | 82 | plot(boundary$geometry, main = "Calwood Fire Boundary (2020)", 83 | border = "red", lwd = 1.5) 84 | ``` 85 | 86 | 87 | 88 | ### AOI 89 | 90 | We can use the function `rlandfire::getAOI()` to create an area of 91 | interest (AOI) vector with the correct format for `landfireAPIv2()`. 92 | `getAOI()` handles several steps for us, it ensures that the AOI is 93 | returned in the correct order (`xmin`, `ymin`, `xmax`, `ymax`) and 94 | converts the AOI to latitude and longitude coordinates (as required by 95 | the API) if needed. 96 | 97 | Using the `extend` argument, we will increase the AOI by 1 km in all 98 | directions to provide additional context surrounding the burned area. 99 | This argument takes an optional numeric vector of 1, 2, or 4 elements. 100 | 101 | ``` r 102 | aoi <- getAOI(boundary, extend = 1000) 103 | aoi 104 | #> [1] -105.40207 40.11224 -105.23526 40.19613 105 | ``` 106 | 107 | Alternatively, you can supply a LANDFIRE map zone number in place of the 108 | AOI vector. The function `getZone()` returns the zone number containing 109 | an `sf` object or which corresponds to the supplied zone name. See 110 | `help("getZone")` for more information and an example. 111 | 112 | ### Products 113 | 114 | For this example, we are interested in canopy cover data for two years, 115 | 2019 (`200CC_19`) and 2022 (`220CC_22`), and existing vegetation type 116 | (`200EVT`). All available data products, and their abbreviated names, 117 | can be found in the [products table](https://lfps.usgs.gov/products) 118 | which can be opened by calling `viewProducts()`. 119 | 120 | ``` r 121 | products <- c("200CC_19", "220CC_22", "200EVT") 122 | ``` 123 | 124 | ### Email 125 | 126 | ``` r 127 | email <- "rlandfire@example.com" 128 | ``` 129 | 130 | ### Projection and resolution 131 | 132 | We can ask the API to project the data to the same CRS as our fire 133 | perimeter data by providing the `WKID` for our CRS of interest and a 134 | resolution of our choosing, in meters. 135 | 136 | ``` r 137 | projection <- 32613 138 | resolution <- 90 139 | ``` 140 | 141 | ### Edit rule 142 | 143 | We will use the `edit_rule` argument to filter out canopy cover data 144 | that does not correspond to Ponderosa Pine Woodland. The `edit_rule` 145 | statement should tell the API that when existing vegetation cover is 146 | anything other than Ponderosa Pine Woodland (`7054`), the value of the 147 | canopy cover layers should be set to a specified value. 148 | 149 | To do so, we specify that when `220EVT` is not equal (`ne`) to `7054`, 150 | the “condition,” the canopy cover layers should be set equal (`st`) to 151 | `1`, the “change.” The edit rule syntax is explained in more depth in 152 | the [LFPS guide](https://lfps.usgs.gov/LFProductsServiceUserGuide.pdf). 153 | 154 | *(How the API applies edit rules can be unintuitive. For example, if we 155 | used ‘clear value’ \[`cv`\] or set the value outside of 0-100 the edits 156 | we want would not work. To work around this behavior, we set the values 157 | to `1` since it is not found in the original data set.*) 158 | 159 | ``` r 160 | edit_rule <- list(c("condition","200EVT","ne",7054), 161 | c("change", "200CC_19", "st", 1), 162 | c("change", "220CC_22", "st", 1)) 163 | ``` 164 | 165 | Note: Edits are performed in the order that they are listed and are 166 | limited to fuel theme products (i.e., Fire Behavior Fuel Model 13, Fire 167 | Behavior Fuel Model 40, Forest Canopy Base Height, Forest Canopy Bulk 168 | Density, Forest Canopy Cover, and Forest Canopy Height). 169 | 170 | If we wanted to restrict these edits to a certain area we could pass the 171 | path to a zip archive (`.zip`) containing a shapefile to `edit_mask`: 172 | 173 | ``` r 174 | edit_mask <- "path/to/wildfire.zip" 175 | ``` 176 | 177 | Note: The file must follow ESRI shapefile naming standards (e.g., no 178 | special characters) and be less than 1MB in size. 179 | 180 | ### Path 181 | 182 | Finally, we will provide a path to a temporary zip file. Setting the 183 | path as a temp file is not strictly necessary because if `path` is left 184 | blank `landfireAPIv2()` will save the data to a temporary folder by 185 | default. 186 | 187 | ``` r 188 | path <- tempfile(fileext = ".zip") 189 | ``` 190 | 191 | ### Call `landfireAPIv2()` 192 | 193 | Now we are able to submit a request to the LANDFIRE Product Services API 194 | with the `landfireAPIv2()` function. 195 | 196 | ``` r 197 | resp <- landfireAPIv2(products = products, 198 | aoi = aoi, 199 | email = email, 200 | projection = projection, 201 | resolution = resolution, 202 | edit_rule = edit_rule, 203 | path = path, 204 | verbose = FALSE) 205 | ``` 206 | 207 | `landfireAPIv2()` will download your requested data into the folder 208 | provided in the path argument. If you did not provide one, you can find 209 | the path to your data in the `$path` element of the `landfire_api` 210 | object. 211 | 212 | ``` r 213 | resp$path 214 | ``` 215 | 216 | ### Load and process LF data 217 | 218 | The files returned by the LFPS API are compressed `.zip` files. We need 219 | to unzip the directory before reading the `.tif` file. Note: all 220 | additional metadata is included in this same directory. 221 | 222 | ``` r 223 | lf_dir <- file.path(tempdir(), "lf") 224 | utils::unzip(path, exdir = lf_dir) 225 | 226 | lf <- terra::rast(list.files(lf_dir, pattern = ".tif$", 227 | full.names = TRUE, 228 | recursive = TRUE)) 229 | ``` 230 | 231 | Now we can reclassify the canopy cover layers to remove any values which 232 | are not classified as Ponderosa Pine, calculate the change, and plot our 233 | results. 234 | 235 | ``` r 236 | lf$US_200CC_19[lf$US_200CC_19 == 1] <- NA 237 | lf$US_220CC_22[lf$US_220CC_22 == 1] <- NA 238 | 239 | change <- lf$US_220CC_22 - lf$US_200CC_19 240 | 241 | plot(change, col = rev(terrain.colors(250)), 242 | main = "Canopy Cover Loss - Calwood Fire (2020)", 243 | xlab = "Easting", 244 | ylab = "Northing") 245 | plot(boundary$geometry, add = TRUE, col = NA, 246 | border = "black", lwd = 2) 247 | ``` 248 | 249 | 250 | 251 | ### Working with Categorical Products 252 | 253 | The LFPS REST API now embeds attributes in the GeoTIFF files for some 254 | variables and returns a database file (`.dbf`) containing the full 255 | attribute table. 256 | 257 | To demonstrate, we will download the Existing Vegetation Cover product 258 | from LF 2.4.0 (`240EVC`). Unlike in the example above we will submit a 259 | minimal request with the default projection and resolution. We will also 260 | allow `rlandfire` to save the files to a temporary directory 261 | automatically. As mentioned above, we can find the path to the temporary 262 | directory in the `$path` element of the `landfire_api` object returned 263 | by `landfireAPIv2()`. 264 | 265 | ``` r 266 | resp <- landfireAPIv2(products = "240EVC", 267 | aoi = aoi, 268 | email = email, 269 | verbose = FALSE) 270 | ``` 271 | 272 | When we read in and plot the EVC layer the legend will now list the 273 | `classnames` for each vegetation type. 274 | 275 | ``` r 276 | lf_cat <- file.path(tempdir(), "lf_cat") 277 | utils::unzip(resp$path, exdir = lf_cat) 278 | 279 | evc <- terra::rast(list.files(lf_cat, pattern = ".tif$", 280 | full.names = TRUE, 281 | recursive = TRUE)) 282 | 283 | plot(evc) 284 | ``` 285 | 286 | 287 | 288 | To access the values each `classname` is assigned to we can uses the 289 | `levels()` function. This returns a simple two column data frame 290 | containing both the index and active category, in our case the 291 | vegetation cover classes. 292 | 293 | ``` r 294 | head(levels(evc)[[1]]) 295 | #> Value CLASSNAMES 296 | #> 1 11 Open Water 297 | #> 2 13 Developed-Upland Deciduous Forest 298 | #> 3 14 Developed-Upland Evergreen Forest 299 | #> 4 15 Developed-Upland Mixed Forest 300 | #> 5 16 Developed-Upland Herbaceous 301 | #> 6 17 Developed-Upland Shrubland 302 | ``` 303 | 304 | Alternatively, we can access the full attribute table using two methods. 305 | We can use the function `cats()` which works similarly to `levels()` but 306 | returns the full attribute table as a data frame. Alternatively, we can 307 | read the database file using `foreign::read.dbf()`. Both methods return 308 | similar results, although in this case, we see that the `.dbf` file 309 | includes an additional `Count` column not included in the data frame 310 | returned from `cats()`. 311 | 312 | ``` r 313 | # cats 314 | attr_tbl <- cats(evc) 315 | 316 | # Find path to database file 317 | dbf <- list.files(lf_cat, pattern = ".dbf$", 318 | full.names = TRUE, 319 | recursive = TRUE) 320 | 321 | # Read file 322 | dbf_tbl <- foreign::read.dbf(dbf) 323 | 324 | head(attr_tbl[[1]]) 325 | #> Value CLASSNAMES Count R G B RED GREEN BLUE 326 | #> 1 11 Open Water 229 0 0 255 0 0 255 327 | #> 2 13 Developed-Upland Deciduous Forest 119 64 61 168 64 61 168 328 | #> 3 14 Developed-Upland Evergreen Forest 337 68 79 137 68 79 137 329 | #> 4 15 Developed-Upland Mixed Forest 198 102 119 205 102 119 205 330 | #> 5 16 Developed-Upland Herbaceous 365 122 142 245 122 142 245 331 | #> 6 17 Developed-Upland Shrubland 181 158 170 215 158 170 215 332 | head(dbf_tbl) 333 | #> Value Count CLASSNAMES R G B RED GREEN 334 | #> 1 11 229 Open Water 0 0 255 0.000000 0.000000 335 | #> 2 13 119 Developed-Upland Deciduous Forest 64 61 168 0.250980 0.239216 336 | #> 3 14 337 Developed-Upland Evergreen Forest 68 79 137 0.266667 0.309804 337 | #> 4 15 198 Developed-Upland Mixed Forest 102 119 205 0.400000 0.466667 338 | #> 5 16 365 Developed-Upland Herbaceous 122 142 245 0.478431 0.556863 339 | #> 6 17 181 Developed-Upland Shrubland 158 170 215 0.619608 0.666667 340 | #> BLUE 341 | #> 1 1.000000 342 | #> 2 0.658824 343 | #> 3 0.537255 344 | #> 4 0.803922 345 | #> 5 0.960784 346 | #> 6 0.843137 347 | ``` 348 | 349 | ### Citation 350 | 351 | Visit the [LANDFIRE webpage](https://landfire.gov/data/citation) for 352 | information on citing LANDFIRE data layers. The package citation 353 | information can be viewed with `citation("rlandfire")`. 354 | -------------------------------------------------------------------------------- /tests/testthat/test-landfireAPI.R: -------------------------------------------------------------------------------- 1 | # Tests for landfireAPIv2.R 2 | 3 | test_that("`landfireAPIv2()` recognizes argument errors", { 4 | products <- c("ASP2020", "ELEV2020", "230CC") 5 | aoi <- c("-123.7835", "41.7534", "-123.6352", "41.8042") 6 | email <- "rlandfire@markabuckner.com" 7 | projection <- 6414 8 | resolution <- 90 9 | edit_rule <- list( 10 | c("condition", "ELEV2020", "lt", 500), 11 | c("change", "230CC", "st", 181) 12 | ) 13 | path <- tempfile(fileext = ".zip") 14 | 15 | # Check for required arguments 16 | expect_error( 17 | landfireAPIv2(aoi = aoi, email = email, execute = FALSE), 18 | "argument `products` is missing with no default" 19 | ) 20 | 21 | expect_error( 22 | landfireAPIv2(products, email = email, execute = FALSE), 23 | "argument `aoi` is missing with no default" 24 | ) 25 | 26 | expect_error( 27 | landfireAPIv2(products, aoi, execute = FALSE), 28 | 'argument "email" is missing, with no default' 29 | ) 30 | 31 | # Check class 32 | expect_error( 33 | landfireAPIv2( 34 | products = c(1, 2, 3), aoi, 35 | email = email, path = path, 36 | execute = FALSE 37 | ), 38 | "argument `products` must be a character vector" 39 | ) 40 | 41 | expect_error( 42 | landfireAPIv2(products, 43 | aoi = list(1, 2, 3), 44 | email = email, path = path, execute = FALSE 45 | ), 46 | "argument `aoi` must be a character or numeric vector" 47 | ) 48 | 49 | expect_error( 50 | landfireAPIv2(products, aoi, email = "notanemail", execute = FALSE), 51 | "A valid `email` address is required.*" 52 | ) 53 | 54 | expect_error( 55 | landfireAPIv2(products, aoi, 56 | email = email, 57 | max_time = TRUE, path = path, execute = FALSE 58 | ), 59 | "argument `max_time` must be numeric" 60 | ) 61 | 62 | expect_error( 63 | landfireAPIv2(products, aoi, 64 | email = email, 65 | verbose = "yes", path = path, execute = FALSE 66 | ), 67 | "argument `verbose` must be logical" 68 | ) 69 | 70 | expect_error( 71 | landfireAPIv2(products, aoi, 72 | email = email, 73 | edit_rule = "edit_rule", execute = FALSE 74 | ), 75 | "argument `edit_rule` must be a list" 76 | ) 77 | 78 | # Check `aoi` errors 79 | expect_error( 80 | landfireAPIv2(products, 81 | aoi = 100, email = email, 82 | path = path, execute = FALSE 83 | ), 84 | "argument `aoi` must be between 1 and 79.*" 85 | ) 86 | 87 | expect_error( 88 | landfireAPIv2(products, 89 | aoi = c(-200, 43, -179, 44), 90 | email = email, path = path, execute = FALSE 91 | ), 92 | "argument `aoi` must be latitude and longitude.*" 93 | ) 94 | 95 | expect_error( 96 | landfireAPIv2(products, 97 | aoi = c(-123, 43, -124, 44), 98 | email = email, path = path, execute = FALSE 99 | ), 100 | "argument `aoi` must be ordered `xmin`, `ymin`, `xmax`, `ymax`" 101 | ) 102 | 103 | expect_error( 104 | landfireAPIv2(products, 105 | aoi = c(65, 66), 106 | email = email, path = path, execute = FALSE 107 | ), 108 | "argument `aoi` must be vector of coordinates.*" 109 | ) 110 | 111 | # Check `resolution` 112 | expect_error( 113 | landfireAPIv2(products, aoi, 114 | email = email, 115 | resolution = 20, path = path, execute = FALSE 116 | ), 117 | "argument `resolution` must be between 30 and 9999 or `NULL`" 118 | ) 119 | expect_error( 120 | landfireAPIv2(products, aoi, 121 | email = email, 122 | resolution = 10000, path = path, execute = FALSE 123 | ), 124 | "argument `resolution` must be between 30 and 9999 or `NULL`" 125 | ) 126 | 127 | # Check edit_rule arguments 128 | expect_error( 129 | landfireAPIv2(products, aoi, 130 | email = email, 131 | edit_rule = list( 132 | c("wrong", "ELEV2020", "lt", 500), 133 | c("change", "230CC", "st", 181) 134 | ), execute = FALSE 135 | ), 136 | "`edit_rule` operator classes must only be .*" 137 | ) 138 | expect_error( 139 | landfireAPIv2(products, aoi, 140 | email = email, 141 | edit_rule = list( 142 | c("condition", "ELEV2020", "xx", 500), 143 | c("change", "230CC", "st", 181) 144 | ), execute = FALSE 145 | ), 146 | "`edit_rule` conditional operators must be one of .*" 147 | ) 148 | 149 | # Returns error if `edit_mask` but no edit_rule 150 | expect_error( 151 | landfireAPIv2(products, aoi, 152 | email = email, 153 | edit_mask = testthat::test_path("testdata", "wildfire.zip"), 154 | path = path, execute = FALSE 155 | ), 156 | "`edit_mask` requires `edit_rule` to be specified." 157 | ) 158 | }) 159 | 160 | test_that("`landfireAPIv2()` returns errors with email/priority_code", { 161 | products <- c("ASP2020") 162 | aoi <- c("-123.7835", "41.7534", "-123.6352", "41.8042") 163 | projection <- 6414 164 | path <- tempfile(fileext = ".zip") 165 | 166 | # ID errors with LFPSv1 requests with positional arguments 167 | expect_error( 168 | landfireAPIv2(products, aoi, projection, 169 | path = path, 170 | execute = FALSE 171 | ), 172 | "A valid `email` address is required.*" 173 | ) 174 | 175 | # Check class 176 | expect_error( 177 | landfireAPIv2(products, aoi, 178 | email = "test@email.com", 179 | priority_code = 1, path = path, execute = FALSE 180 | ), 181 | "argument `priority_code` must be a character string" 182 | ) 183 | }) 184 | 185 | 186 | 187 | test_that("`landfireAPIv2()` formats priority requests correctly", { 188 | products <- c( 189 | "ELEV2020", "SLPD2020", "ASP2020", "230FBFM40", 190 | "230CC", "230CH", "230CBH", "230CBD" 191 | ) 192 | aoi <- c("-113.79", "42.148", "-113.56", "42.29") 193 | email <- "example@domain.com" 194 | priority_code <- "K3LS9F" 195 | path <- tempfile(fileext = ".zip") 196 | 197 | output <- landfireAPIv2(products, aoi, email, 198 | priority_code = priority_code, 199 | path = path, method = "none", 200 | execute = FALSE 201 | ) 202 | expect_identical(output$request$url, "https://lfps.usgs.gov/api/job/submit?Email=example%40domain.com&Layer_List=ELEV2020%3BSLPD2020%3BASP2020%3B230FBFM40%3B230CC%3B230CH%3B230CBH%3B230CBD&Area_of_Interest=-113.79%2042.148%20-113.56%2042.29&Priority_Code=K3LS9F") 203 | }) 204 | 205 | 206 | test_that("`landfireAPIv2()` returns expected messages", { 207 | products <- c("ELEV2020") 208 | aoi <- c("-113.79", "42.148", "-113.56", "42.29") 209 | email <- "rlandfire@markabuckner.com" 210 | path <- "path.zip" 211 | 212 | expect_message( 213 | landfireAPIv2(products, aoi, email, background = TRUE, execute = FALSE), 214 | "`path` is missing. Files will be saved in temporary directory: .*" 215 | ) 216 | }) 217 | 218 | 219 | test_that("`landfireAPIv2()` returns expected background messages", { 220 | skip_on_cran() 221 | 222 | products <- c("ELEV2020") 223 | aoi <- c("-113.79", "42.148", "-113.56", "42.29") 224 | email <- "rlandfire@markabuckner.com" 225 | path <- "path.zip" 226 | # Return correct message with background jobs 227 | expect_message( 228 | output <- landfireAPIv2(products, aoi, email, 229 | background = TRUE, path = path, 230 | method = "none", verbose = FALSE 231 | ), 232 | "Job submitted in background.*" 233 | ) 234 | 235 | cancelJob(output$request$job_id) 236 | 237 | expect_message( 238 | output <- landfireAPIv2(products, aoi, email, 239 | max_time = 0, path = path, 240 | method = "none", verbose = FALSE 241 | ), 242 | "Job submitted in background.*" 243 | ) 244 | 245 | cancelJob(output$request$job_id) 246 | }) 247 | 248 | 249 | 250 | test_that("`landfireAPIv2()` recognizes failed call", { 251 | skip_on_cran() 252 | products <- "NotAProduct" 253 | aoi <- c("-123.7835", "41.7534", "-123.6352", "41.8042") 254 | email <- "rlandfire@markabuckner.com" 255 | projection <- 123456 256 | path <- tempfile(fileext = ".zip") 257 | 258 | expect_warning( 259 | landfireAPIv2(products, aoi, email, projection, path = path), 260 | paste( 261 | "Job .* has failed with:\n\t.*\nPlease check the LFPS", 262 | "API documentation for more information." 263 | ) 264 | ) 265 | }) 266 | 267 | 268 | 269 | 270 | test_that("`landfireAPIv2()` edge cases", { 271 | products <- c("ASP2020") 272 | aoi <- c("-123.65", "41.75", "-123.63", "41.83") 273 | email <- "rlandfire@markabuckner.com" 274 | path <- tempfile(fileext = ".zip") 275 | 276 | # Resets resolution to NULL when user sets resolution = 30 277 | result <- landfireAPIv2(products, aoi, email, 278 | resolution = 30, path = path, 279 | method = "none", execute = FALSE 280 | ) 281 | expect_null(result$request$query$resolution) 282 | }) 283 | 284 | 285 | 286 | test_that("`landfireAPIv2()` works with `getAOI()`", { 287 | products <- c("ASP2020") 288 | email <- "rlandfire@markabuckner.com" 289 | path <- tempfile(fileext = ".zip") 290 | 291 | r <- terra::rast( 292 | nrows = 50, ncols = 50, 293 | xmin = -2261174.94, xmax = -2247816.36, 294 | ymin = 2412704.65, ymax = 2421673.98, 295 | crs = terra::crs("epsg:5070"), 296 | vals = rnorm(2500) 297 | ) 298 | 299 | aoi <- round(getAOI(r), 3) 300 | 301 | aoi_result <- landfireAPIv2( 302 | products = products, aoi = aoi, 303 | email = email, path = path, 304 | method = "none", execute = FALSE 305 | ) 306 | 307 | 308 | expect_identical( 309 | aoi_result$request$query$Area_of_Interest, 310 | "-123.803 41.723 -123.616 41.834" 311 | ) 312 | }) 313 | 314 | 315 | 316 | test_that("`landfireAPIv2()` works with `getZone()`", { 317 | products <- c("ASP2020") 318 | email <- "rlandfire@markabuckner.com" 319 | resolution <- 90 320 | path <- tempfile(fileext = ".zip") 321 | 322 | zone <- getZone("Northern California Coastal Range") 323 | 324 | zone_result <- landfireAPIv2( 325 | products = products, aoi = zone, 326 | email = email, resolution = resolution, 327 | path = path, method = "none", execute = FALSE 328 | ) 329 | expect_identical( 330 | zone_result$request$query$Area_of_Interest, 331 | "3" 332 | ) 333 | }) 334 | 335 | 336 | # Tests for .post_request (internal) 337 | test_that("`.post_request` catches file issues", { 338 | without_internet({ 339 | expect_error( 340 | .post_editmask("notafile.zip"), 341 | "`edit_mask` file not found" 342 | ) 343 | 344 | # Check for file extension 345 | tmp_file <- tempfile(fileext = ".txt") 346 | writeBin(raw(32 * 32), tmp_file) 347 | expect_error(.post_editmask(tmp_file), 348 | "`edit_mask` file must be a zipped shapefile (.zip)", 349 | fixed = TRUE 350 | ) 351 | 352 | # Check for file size 353 | writeBin(raw(1024 * 1024 + 1), tmp_file) 354 | expect_error(.post_editmask(tmp_file), 355 | "`edit_mask` file exceeds maximum allowable size (1MB)", 356 | fixed = TRUE 357 | ) 358 | unlink(tmp_file) 359 | 360 | # Check for shapefile 361 | expect_error( 362 | .post_editmask(testthat::test_path("testdata", "editmask_noshp.zip")), 363 | "`edit_mask` file does not contain a shapefile" 364 | ) 365 | 366 | # Returns NULL if no file is provided 367 | expect_null(.post_editmask(NULL)$item_id) 368 | expect_null(.post_editmask(NULL)$item_name) 369 | }) 370 | }) 371 | 372 | # Tests for .post_editmask (internal) 373 | test_that("`.post_editmask` returns expected response", { 374 | skip_on_cran() 375 | 376 | shapefile <- testthat::test_path("testdata", "wildfire.zip") 377 | result <- rlandfire:::.post_editmask(shapefile) 378 | 379 | expect_match(result$item_id, "[{\"itemID\":\".*\"}]") 380 | expect_match(result$item_name, "wildfire.shp$") 381 | }) 382 | 383 | 384 | # Tests for .fmt_editrules (internal) 385 | test_that("`.fmt_editrules` correctly formats requests", { 386 | # One condition, one change 387 | single_rule <- list( 388 | c("condition", "ELEV2020", "lt", 500), 389 | c("change", "230CC", "st", 181) 390 | ) 391 | expect_identical( 392 | .fmt_editrules(single_rule), 393 | "{\"edit\":[{\"condition\":[{\"product\":\"ELEV2020\",\"operator\":\"lt\",\"value\":500}],\"change\":[{\"product\":\"230CC\",\"operator\":\"st\",\"value\":181}]}]}" 394 | ) 395 | 396 | # Multiple conditions 397 | multi_rule <- list( 398 | c("condition", "ELEV2020", "lt", 500), 399 | c("change", "230CC", "st", 181), 400 | c("condition", "ELEV2020", "ge", 600), 401 | c("change", "230CC", "db", 20), 402 | c("condition", "ELEV2020", "eq", 550), 403 | c("change", "230CC", "st", 0) 404 | ) 405 | expect_identical( 406 | .fmt_editrules(multi_rule), 407 | "{\"edit\":[{\"condition\":[{\"product\":\"ELEV2020\",\"operator\":\"lt\",\"value\":500}],\"change\":[{\"product\":\"230CC\",\"operator\":\"st\",\"value\":181}],\"condition\":[{\"product\":\"ELEV2020\",\"operator\":\"ge\",\"value\":600}],\"change\":[{\"product\":\"230CC\",\"operator\":\"db\",\"value\":20}],\"condition\":[{\"product\":\"ELEV2020\",\"operator\":\"eq\",\"value\":550}],\"change\":[{\"product\":\"230CC\",\"operator\":\"st\",\"value\":0}]}]}" 408 | ) 409 | 410 | 411 | # Single condition with multiple changes (Pulled from documentation) 412 | multi_change <- list( 413 | c("condition", "ELEV2020", "lt", 500), 414 | c("change", "140FBFM", "st", 181), 415 | c("change", "140CBH", "ib", 5) 416 | ) 417 | expect_identical( 418 | .fmt_editrules(multi_change), 419 | "{\"edit\":[{\"condition\":[{\"product\":\"ELEV2020\",\"operator\":\"lt\",\"value\":500}],\"change\":[{\"product\":\"140FBFM\",\"operator\":\"st\",\"value\":181},{\"product\":\"140CBH\",\"operator\":\"ib\",\"value\":5}]}]}" 420 | ) 421 | 422 | # Multiple conditions with OR (Pulled from documentation) 423 | or_rule <- list( 424 | c("condition", "ELEV2020", "", 0), 425 | c("change", "140FBFM", "st", 181), 426 | c("change", "140CBH", "ib", 5), 427 | c("ORcondition", "ELEV2020", "gt", 500), 428 | c("condition", "ELEV2020", "lt", 600), 429 | c("change", "140FBFM", "st", 181), 430 | c("change", "140CBH", "ib", 5) 431 | ) 432 | expect_identical( 433 | .fmt_editrules(or_rule), 434 | "{\"edit\":[{\"condition\":[{\"product\":\"ELEV2020\",\"operator\":\"\",\"value\":0}],\"change\":[{\"product\":\"140FBFM\",\"operator\":\"st\",\"value\":181},{\"product\":\"140CBH\",\"operator\":\"ib\",\"value\":5}]}],\"edit\":[{\"condition\":[{\"product\":\"ELEV2020\",\"operator\":\"gt\",\"value\":500},{\"product\":\"ELEV2020\",\"operator\":\"lt\",\"value\":600}],\"change\":[{\"product\":\"140FBFM\",\"operator\":\"st\",\"value\":181},{\"product\":\"140CBH\",\"operator\":\"ib\",\"value\":5}]}]}" 435 | ) 436 | 437 | # Single `edit_mask` with simple edit rules 438 | single_mask <- list( 439 | c("condition", "ELEV2020", "eq", 593), 440 | c("change", "140CC", "st", 500), 441 | c("change", "140CH", "ib", 50) 442 | ) 443 | mask <- list( 444 | item_id = "{\"itemID\":\"i5ce09134-4e57-41fe-bcaa-0c38879bc3fc\"}]", 445 | item_name = "wildfire.shp" 446 | ) 447 | expect_identical( 448 | .fmt_editrules(single_mask, mask), 449 | "{\"edit\":[{\"mask\":\"wildfire.shp\",\"condition\":[{\"product\":\"ELEV2020\",\"operator\":\"eq\",\"value\":593}],\"change\":[{\"product\":\"140CC\",\"operator\":\"st\",\"value\":500},{\"product\":\"140CH\",\"operator\":\"ib\",\"value\":50}]}]}" 450 | ) 451 | 452 | # Returns NULL if no file is provided 453 | expect_null(.fmt_editrules(NULL)) 454 | }) 455 | -------------------------------------------------------------------------------- /R/landfireAPI.R: -------------------------------------------------------------------------------- 1 | #' Call the LANDFIRE Product Service (LFPS) API 2 | #' 3 | #' @description 4 | #' `landfireAPIv2` downloads LANDFIRE data by calling the LFPS API 5 | #' 6 | #' @param products Product names as character vector 7 | #' (see: \href{https://lfps.usgs.gov/products}{Products Table}) 8 | #' @param aoi Area of interest as character or numeric vector defined by 9 | #' latitude and longitude in decimal degrees in WGS84 and ordered 10 | #' `xmin`, `ymin`, `xmax`, `ymax` or a LANDFIRE map zone. 11 | #' @param email Email address as character string. This is a required argument 12 | #' for the LFPS v2 API. See the \href{https://lfps.usgs.gov/LFProductsServiceUserGuide.pdf}{LFPS Guide} 13 | #' for more information. Outside of the LFPS API request, this email address 14 | #' is not used for any other purpose, stored, or shared by `rlandfire`. 15 | #' @param projection Optional. A numeric value of the WKID for the output projection 16 | #' Default is a localized Albers projection. 17 | #' @param resolution Optional. A numeric value between 30-9999 specifying the 18 | #' resample resolution in meters. Default is 30m. 19 | #' @param edit_rule Optional. A list of character vectors ordered "operator class" 20 | #' "product", "operator", "value" where "operator class" is one of "condition", 21 | #' "ORcondition", or "change". Edits are limited to fuel theme products only. 22 | #' (see: \href{https://lfps.usgs.gov/LFProductsServiceUserGuide.pdf}{LFPS Guide}) 23 | #' @param edit_mask Optional. Path to a compressed shapefile (.zip) to be used 24 | #' as an edit mask. The shapefile must be less than 1MB in size and must 25 | #' comply with ESRI shapefile naming rules. 26 | #' @param priority_code Optional. Priority code for wildland fire systems/users. 27 | #' Contact the LANDFIRE help desk for information () 28 | #' @param path Path to `.zip` directory. Passed to [utils::download.file()]. 29 | #' If NULL, a temporary directory is created. 30 | #' @param max_time Maximum time, in seconds, to wait for job to be completed. 31 | #' @param method Passed to [utils::download.file()]. See `?download.file` 32 | #' @param verbose If FALSE suppress all status messages 33 | #' @param background If TRUE, the function will return immediately and the job 34 | #' will run in the background. User will need to check the status of the job 35 | #' manually with `checkStatus()`. 36 | #' @param execute If FALSE, the function will build a request without submitting 37 | #' it to the LFPS API. 38 | #' 39 | #' @return 40 | #' Returns a `landfire_api` object with named elements: 41 | #' * `request` - list with elements `query`, `date`, `url`, `job_id`, `request`,`dwl_url` 42 | #' * `content` - Informative messages passed from API 43 | #' * `response` - Full response 44 | #' * `status` - Final API status, one of "Failed", "Succeeded", or "Timed out" 45 | #' * `time` - time of job completion 46 | #' * `path` - path to save directory 47 | #' 48 | #' @md 49 | #' @export 50 | #' 51 | #' @examples 52 | #' \dontrun{ 53 | #' products <- c("ASP2020", "ELEV2020", "230CC") 54 | #' aoi <- c("-123.7835", "41.7534", "-123.6352", "41.8042") 55 | #' email <- "email@@example.com" 56 | #' projection <- 6414 57 | #' resolution <- 90 58 | #' edit_rule <- list(c("condition","ELEV2020","lt",500), 59 | #' c("change", "230CC", "st", 181)) 60 | #' save_file <- tempfile(fileext = ".zip") 61 | #' resp <- landfireAPIv2(products, aoi, email, projection, 62 | #' resolution, edit_rule = edit_rule, 63 | #' path = save_file) 64 | #' } 65 | 66 | landfireAPIv2 <- function(products, aoi, email, projection = NULL, 67 | resolution = NULL, edit_rule = NULL, edit_mask = NULL, 68 | priority_code = NULL, path = NULL, max_time = 10000, 69 | method = "curl", verbose = TRUE, background = FALSE, 70 | execute = TRUE) { 71 | 72 | #### Checks 73 | # Missing 74 | stopifnot("argument `products` is missing with no default" = !missing(products)) 75 | stopifnot("argument `aoi` is missing with no default" = !missing(aoi)) 76 | stopifnot("A valid `email` address is required. (See `?rlandfire::landfireAPIv2` for more information)" 77 | = grepl("@", email) && !missing(email)) 78 | stopifnot("argument `email` is missing with no default" = !missing(aoi)) 79 | 80 | if(!is.null(edit_rule)){ 81 | stopifnot("argument `edit_rule` must be a list" 82 | = inherits(edit_rule, "list")) 83 | 84 | class <- sapply(edit_rule, `[`, 1) 85 | 86 | stopifnot( 87 | '`edit_rule` operator classes must only be "condition" or "change"' = 88 | all(class %in% c("condition", "change", "ORcondition")) 89 | ) 90 | 91 | stopifnot( 92 | '`edit_rule` conditional operators must be one of "eq","ge","gt","le","lt","ne"' 93 | = all(sapply(edit_rule, `[`, 3)[class %in% c("condition","ORcondition")] %in% c("eq","ge","gt","le","lt","ne")) 94 | ) 95 | 96 | stopifnot( 97 | '`edit_rule` change operators must be one of "cm","cv","cx","bd","ib","mb","st"' 98 | = all(sapply(edit_rule, `[`, 3)[class == "change"] %in% c("cm","cv","cx","db","ib","mb","st")) 99 | ) 100 | 101 | stopifnot( 102 | "all products used in argument `edit_rule` must be included in argument `products`" 103 | = all(sapply(edit_rule, `[`, 2) %in% products) 104 | ) 105 | } 106 | 107 | if(is.null(path) && method != "none") { 108 | path = tempfile(fileext = ".zip") 109 | message("`path` is missing. Files will be saved in temporary directory: ", 110 | path) 111 | } 112 | 113 | if (!is.null(edit_mask) && is.null(edit_rule)) { 114 | stop("`edit_mask` requires `edit_rule` to be specified.") 115 | } 116 | 117 | # Classes 118 | stopifnot("argument `products` must be a character vector" 119 | = inherits(products, "character")) 120 | stopifnot("argument `aoi` must be a character or numeric vector" 121 | = inherits(aoi, c("character", "numeric"))) 122 | stopifnot("argument `aoi` must be vector of coordinates with length == 4 or a single map zone" 123 | = length(aoi) == 1 | length(aoi) == 4) 124 | stopifnot("argument `max_time` must be numeric" 125 | = inherits(max_time, c("numeric"))) 126 | stopifnot("argument `priority_code` must be a character string" 127 | = inherits(priority_code, c("character", "NULL"))) 128 | stopifnot("argument `edit_mask` must be a character string" 129 | = inherits(edit_mask, c("character", "NULL"))) 130 | stopifnot("argument `background` must be a logical" 131 | = inherits(background, "logical")) 132 | 133 | stopifnot( 134 | "`method` is invalid. See `?download.file` or use \"none\" to skip download" 135 | = method %in% c("internal", "libcurl", "wget", 136 | "curl", "wininet", "auto", "none") 137 | ) 138 | 139 | stopifnot("argument `verbose` must be logical" = inherits(verbose, "logical")) 140 | 141 | # stopifnot("argument `max_time` must be >= 5" = max_time >= 5) 142 | 143 | # Values in range 144 | if(is.numeric(resolution) && resolution == 30) { 145 | resolution <- NULL 146 | } 147 | 148 | if(!is.null(resolution) && !all(resolution >= 30 & resolution <= 9999)) { 149 | stop("argument `resolution` must be between 30 and 9999 or `NULL`") 150 | } 151 | 152 | aoi <- as.numeric(aoi) 153 | 154 | if(length(aoi) == 4) { 155 | # Likely lat/lon? 156 | if(!all(aoi[c(1,3)] >=-180 & aoi[c(1,3)] <=180 & 157 | aoi[c(2,4)] >=-90 & aoi[c(2,4)] <=90)){ 158 | stop("argument `aoi` must be latitude and longitude in decimal degrees (WGS84) or a LANDFIRE map zone") 159 | } 160 | # Correct order? 161 | if(!all(aoi[[1]] < aoi[[3]] & aoi[[2]] < aoi[[4]])) { 162 | stop("argument `aoi` must be ordered `xmin`, `ymin`, `xmax`, `ymax`") 163 | } 164 | # Valid map zone? 165 | } else if(length(aoi) == 1 && !all(aoi >= 1 & aoi <= 79)){ 166 | stop("argument `aoi` must be between 1 and 79 if using LANDFIRE map zones") 167 | } 168 | 169 | #### End Checks 170 | 171 | # Edit mask 172 | mask <- .post_editmask(edit_mask) 173 | 174 | # Define Parameters 175 | params <- list( 176 | Email = email, 177 | Layer_List = paste(products, collapse = ";"), 178 | Area_of_Interest = paste(aoi, collapse = " "), 179 | Output_Projection = projection, 180 | Resample_Resolution = resolution, 181 | Edit_Rule = .fmt_editrules(edit_rule, mask = mask), 182 | Edit_Mask = mask$item_id, 183 | Priority_Code = priority_code 184 | ) 185 | 186 | purpose <- "submit" 187 | 188 | # Construct request URL 189 | request <- httr2::request("https://lfps.usgs.gov/api/job/") |> 190 | httr2::req_url_path_append(purpose) |> 191 | httr2::req_url_query(!!!params) |> 192 | httr2::req_user_agent("rlandfire (https://CRAN.R-project.org/package=rlandfire)") |> 193 | httr2::req_headers("Accept" = "application/json") 194 | 195 | if (!execute) { 196 | lfps <- .build_landfire_api(params = params, request = request) 197 | return(lfps) 198 | } 199 | 200 | # Submit job and get initial response 201 | req <- httr2::req_error(request, is_error = \(req) FALSE) |> 202 | httr2::req_perform() 203 | 204 | req_response <- httr2::resp_body_json(req, simplifyVector = TRUE) 205 | 206 | if(req$status != 200) { 207 | stop("\tAPI request failed with status code: ", req$status, 208 | "\n\tLFPS Error message: ", req_response$message) 209 | } 210 | 211 | lfps <- .build_landfire_api(params = params, request = request, 212 | job_id = req_response$jobId, 213 | init_resp = req, path = path) 214 | 215 | mt <- max_time*10 216 | 217 | for (i in 1:mt) { 218 | # Check status 219 | lfps_return <- .checkStatus_internal(landfire_api = lfps, verbose = verbose, 220 | method = method, i = i, max_time = max_time) 221 | 222 | # Set early exit if background is TRUE or status is "Failed" or "Succeeded" 223 | if (background == TRUE || max_time == 0) { 224 | message("Job submitted in background.\n", 225 | "Call `checkStatus()` to check the current status and download", 226 | " if completed.\n", 227 | "Or visit URL to check status and download manually:\n ", 228 | lfps_return$response$url) 229 | break 230 | } else if (lfps_return$status %in% c("Failed", 231 | "Succeeded", 232 | "Succeeded (download skipped)")) { 233 | break 234 | } 235 | 236 | # Max time error 237 | if(i == mt) { 238 | cat("\n") 239 | warning("Job status: Incomplete and `max_time` reached\n", 240 | "Call: `checkStatus()` to check the current status\n", 241 | " `cancelJob()` to cancel.\n", 242 | "Or visit URL to check status and download manually:\n ", 243 | lfps_return$response$url) 244 | lfps_return$status <- "Timed out" 245 | break 246 | } else { 247 | Sys.sleep(0.1) 248 | } 249 | } 250 | 251 | return(lfps_return) 252 | 253 | } 254 | 255 | #' Internal: Submit edit_mask POST request 256 | #' 257 | #' @param file Path to the zipped shape file to be uploaded 258 | #' 259 | #' @return JSON array returned by POST request 260 | #' 261 | #' @noRd 262 | #' 263 | #' @examples 264 | #' \dontrun{ 265 | #' edit_mask <- system.file("extdata", "wildfire.zip", package = "rlandfire") 266 | #' .post_editmask(edit_mask) 267 | #' } 268 | .post_editmask <- function(file) { 269 | 270 | if(is.null(file)) { 271 | return(list(item_id = NULL, 272 | item_name = NULL)) 273 | } 274 | 275 | # Checks 276 | stopifnot("`edit_mask` file not found" = file.exists(file)) 277 | stopifnot("`edit_mask` file exceeds maximum allowable size (1MB)" 278 | = file.info(file)$size < 1000000) 279 | stopifnot("`edit_mask` file must be a zipped shapefile (.zip)" 280 | = grepl("\\.zip$", file)) 281 | stopifnot("`edit_mask` file does not contain a shapefile" 282 | = any(grepl("\\.shp$", unzip(file, list=T)$Name))) 283 | 284 | stopifnot("`edit_mask` file name must not contain special characters" 285 | = !grepl("[^[:alnum:].]", basename(file))) 286 | # End Checks 287 | 288 | req <- httr2::request("https://lfps.usgs.gov/api/upload/shapefile") |> 289 | httr2::req_method("POST") |> 290 | httr2::req_user_agent("rlandfire (https://CRAN.R-project.org/package=rlandfire)") |> 291 | httr2::req_headers("Accept" = "application/json") |> 292 | httr2::req_body_multipart( 293 | file = curl::form_file(file, type = "application/zip"), 294 | description = "string" 295 | ) |> 296 | httr2::req_error(is_error = function(resp) FALSE) 297 | 298 | # Perform the request 299 | tries <- 0 300 | repeat { 301 | tries <- tries + 1 302 | upload_resp <- httr2::req_perform(req) 303 | if (upload_resp$status != 500 || tries >= 3) break 304 | Sys.sleep(1) 305 | } 306 | 307 | upload_body <- tryCatch( 308 | httr2::resp_body_json(upload_resp), 309 | error = function(e) list(message = "Could not parse response body") 310 | ) 311 | 312 | # Check for errors 313 | if (upload_resp$status != 200) { 314 | stop("\t`edit_mask` upload failed with status code: ", upload_resp$status, 315 | "\n\tLFPS Error message: ", upload_body$message) 316 | } 317 | 318 | return(list(item_id = sprintf('[{"itemID":"%s"}]', upload_body$itemId), 319 | item_name = grep("\\.shp$", 320 | unzip(file, list=T)$Name, 321 | value = TRUE))) 322 | 323 | } 324 | 325 | 326 | #' Internal: Format edit_rule for API call 327 | #' 328 | #' @param rules A list of character vectors ordered "operator class" 329 | #' "product", "operator", "value". Limited to fuel theme products only. 330 | #' 331 | #' @return Character vector (length = 1) with formated edit rules call 332 | #' 333 | #' @noRd 334 | #' 335 | #' @examples 336 | #' \dontrun{ 337 | #' edit_rule <- list(c("condition","ELEV2020","lt",500), 338 | #' c("change", "230CC", "st", 181)) 339 | #' .fmt_editrules(edit_rule) 340 | #' } 341 | .fmt_editrules <- function(rules, mask = NULL) { 342 | 343 | # Check for NULL 344 | if (is.null(rules)) { 345 | return(NULL) 346 | } 347 | 348 | class <- sapply(rules, `[`, 1) 349 | 350 | params <- lapply(rules, function(x) { 351 | paste0('"product":"', x[2], 352 | '","operator":"', x[3], 353 | '","value":', x[4]) 354 | }) 355 | 356 | # Condition - ID groups with same class and build request 357 | cnd <- grep(".*condition", class) 358 | breaks <- c(0, which(diff(cnd) != 1), length(cnd)) 359 | cnd_grp <- lapply(seq(length(breaks) - 1), 360 | function(i) cnd[(breaks[i] + 1):breaks[i+1]]) 361 | 362 | cnd <- lapply(cnd_grp, function(i) paste0('"condition":[{', 363 | paste0(params[i], 364 | collapse = '},{'),'}]')) 365 | 366 | # Check for OR condition 367 | or_cnd <- grep("OR.*", class) 368 | stopifnot("`edit_rule` contains a `condition` without an associated `change`." 369 | = or_cnd %in% sapply(cnd_grp, `[`, 1)) 370 | 371 | # Add edit mask if provided 372 | if(!is.null(mask)) { 373 | 374 | mask_file <- sprintf('"mask":"%s"', mask$item_name) 375 | 376 | # mask groups 377 | mask_grp <- c(1, which(do.call("c", cnd_grp) %in% or_cnd)) 378 | 379 | if (length(mask$item_name) == 1 || 380 | length(mask$item_name) == length(cnd_grp)) { 381 | cnd[mask_grp] <- paste(mask_file, cnd[mask_grp], sep = ",") 382 | } else { 383 | stop("The number of `edit_mask` count should match the number of", 384 | "`edit_rules` condition groups when using multiple shapefiles.") 385 | } 386 | } 387 | 388 | # Change - ID groups with same class and build request 389 | chng <- which(class == "change") 390 | breaks <- c(0, which(diff(chng) != 1), length(chng)) 391 | chng_grp <- lapply(seq(length(breaks) - 1), 392 | function(i) chng[(breaks[i] + 1):breaks[i+1]]) 393 | 394 | chng <- lapply(chng_grp, function(i) paste0('"change":[{', 395 | paste0(params[i], 396 | collapse = '},{'),'}]')) 397 | 398 | # Retain original order 399 | order_cnd <- sapply(cnd_grp, `[`, 1) 400 | order_chng <- sapply(chng_grp, `[`, 1) 401 | 402 | edit_rule <- c() 403 | edit_rule[order_cnd] <- unlist(cnd) 404 | edit_rule[order_chng] <- unlist(chng) 405 | 406 | # Check if multiple "Edit" groups needed 407 | ed_grp <- edit_rule[c(1, or_cnd)] 408 | out_rules <- edit_rule[!is.na(edit_rule)] 409 | 410 | # If OR condition 411 | if (length(ed_grp) > 1) { 412 | out_rules <- lapply(which(out_rules %in% ed_grp), function(i) { 413 | sprintf('"edit":[{%s,%s}]', out_rules[i], out_rules[i + 1]) 414 | }) 415 | } else { 416 | out_rules <- paste0('"edit":[{', 417 | paste(out_rules, collapse = ','), 418 | '}]') 419 | } 420 | 421 | # Assemble final string 422 | sprintf("{%s}", 423 | paste0(out_rules[!is.na(out_rules)], collapse = ",") 424 | ) 425 | } 426 | 427 | # Depreciated ----------------------------------------------------------- 428 | 429 | 430 | #' Depreciated: Call the LANDFIRE Product Service (LFPS) API 431 | #' 432 | #' @description 433 | #' Superseded: `landfireAPI()` is no longer supported due to updates to the 434 | #' LFPS API. Use `landfireAPIv2()` instead. 435 | #' 436 | #' `landfireAPI` downloads LANDFIRE data by calling the LFPS API 437 | #' 438 | #' @param products Product names as character vector 439 | #' (see: Products Table) 440 | #' @param aoi Area of interest as character or numeric vector defined by 441 | #' latitude and longitude in decimal degrees in WGS84 and ordered 442 | #' `xmin`, `ymin`, `xmax`, `ymax` or a LANDFIRE map zone. 443 | #' @param projection Optional. A numeric value of the WKID for the output projection 444 | #' Default is a localized Albers projection. 445 | #' @param resolution Optional. A numeric value between 30-9999 specifying the 446 | #' resample resolution in meters. Default is 30m. 447 | #' @param edit_rule Optional. A list of character vectors ordered "operator class" 448 | #' "product", "operator", "value". Limited to fuel theme products only. 449 | #' (see: LFPS Guide) 450 | #' @param edit_mask Optional. **Not currently functional** 451 | #' @param path Path to `.zip` directory. Passed to [utils::download.file()]. 452 | #' If NULL, a temporary directory is created. 453 | #' @param max_time Maximum time, in seconds, to wait for job to be completed. 454 | #' @param method Passed to [utils::download.file()]. See `?download.file` or 455 | #' use "none" to skip download and use `landfire_vsi()` 456 | #' @param verbose If FALSE suppress all status messages 457 | #' 458 | #' @return 459 | #' Returns a `landfire_api` object with named elements: 460 | #' * `request` - list with elements `query`, `date`, `url`, `job_id`,`dwl_url` 461 | #' * `content` - Informative messages passed from API 462 | #' * `response` - Full response 463 | #' * `status` - Final API status, one of "Failed", "Succeeded", or "Timed out" 464 | #' * `path` - path to save directory 465 | #' 466 | #' @md 467 | #' @export 468 | #' 469 | #' @examples 470 | #' \dontrun{ 471 | #' products <- c("ASP2020", "ELEV2020", "230CC") 472 | #' aoi <- c("-123.7835", "41.7534", "-123.6352", "41.8042") 473 | #' projection <- 6414 474 | #' resolution <- 90 475 | #' edit_rule <- list(c("condition","ELEV2020","lt",500), c("change", "230CC", "st", 181)) 476 | #' save_file <- tempfile(fileext = ".zip") 477 | #' resp <- landfireAPI(products, aoi, projection, resolution, edit_rule = edit_rule, path = save_file) 478 | #' } 479 | 480 | landfireAPI <- function(products, aoi, projection = NULL, resolution = NULL, 481 | edit_rule = NULL, edit_mask = NULL, path = NULL, 482 | max_time = 10000, method = "curl", verbose = TRUE) { 483 | requireNamespace("lifecycle", quietly = TRUE) 484 | lifecycle::deprecate_stop( 485 | when = "1.0.0", 486 | what = "landfireAPI()", 487 | with = "landfireAPIv2()", 488 | details = c("The LANDFIRE Products Services API has been updated to v2 as of May 2025.", 489 | "New parameters and syntax are required.", 490 | "See `?rlandfire::landfireAPIv2` for more information.") 491 | ) 492 | 493 | #### Checks 494 | # Missing 495 | stopifnot("argument `products` is missing with no default" = !missing(products)) 496 | stopifnot("argument `aoi` is missing with no default" = !missing(aoi)) 497 | 498 | if(!is.null(edit_rule)){ 499 | stopifnot("`edit_rule` must be a list" = inherits(edit_rule, "list")) 500 | 501 | class <- sapply(edit_rule, `[`, 1) 502 | 503 | stopifnot( 504 | '`edit_rule` operator classes must only be "condition" or "change"' = 505 | all(class %in% c("condition", "change")) 506 | ) 507 | 508 | stopifnot( 509 | '`edit_rule` conditional operators must be one of "eq","ge","gt","le","lt","ne"' = 510 | all(sapply(edit_rule, `[`, 3)[class == "condition"] %in% c("eq","ge","gt","le","lt","ne"))) 511 | 512 | stopifnot( 513 | '`edit_rule` change operators must be one of "cm","cv","cx","bd","ib","mb","st"' = 514 | all(sapply(edit_rule, `[`, 3)[class == "change"] %in% c("cm","cv","cx","db","ib","mb","st"))) 515 | } 516 | 517 | if(is.null(path)){ 518 | path = tempfile(fileext = ".zip") 519 | warning("`path` is missing. Files will be saved in temp directory: ", path) 520 | } 521 | 522 | if (method == "none") { 523 | path <- NULL 524 | } 525 | 526 | # Classes 527 | stopifnot("argument `products` must be a character vector" = inherits(products, "character")) 528 | stopifnot("argument `aoi` must be a character or numeric vector" = inherits(aoi, c("character", "numeric"))) 529 | stopifnot("argument `aoi` must be vector of coordinates with length == 4 or a single map zone" = length(aoi) == 1 | length(aoi) == 4) 530 | stopifnot("argument `max_time` must be numeric" = inherits(max_time, c("numeric"))) 531 | 532 | stopifnot( 533 | "`method` is invalid. See `?download.file`" = 534 | method %in% c("internal", "libcurl", "wget", "curl", "wininet", "auto") 535 | ) 536 | 537 | stopifnot("argument `verbose` must be logical" = inherits(verbose, "logical")) 538 | 539 | stopifnot("argument `max_time` must be >= 5" = max_time >= 5) 540 | 541 | #check for special characters in edit mask 542 | # grepl('[^[:alnum:]]', val) 543 | # Check it is sf or spatvector 544 | 545 | # Values in range 546 | if(is.numeric(resolution) && resolution == 30) { 547 | resolution <- NULL 548 | } 549 | 550 | if(!is.null(resolution) && !all(resolution >= 30 & resolution <= 9999)) { 551 | stop("argument `resolution` must be between 30 and 9999 or `NULL`") 552 | } 553 | 554 | aoi <- as.numeric(aoi) 555 | 556 | if(length(aoi) == 4) { 557 | # Likely lat/lon? 558 | if(!all(aoi[c(1,3)] >=-180 & aoi[c(1,3)] <=180 & 559 | aoi[c(2,4)] >=-90 & aoi[c(2,4)] <=90)){ 560 | stop("argument `aoi` must be latitude and longitude in decimal degrees (WGS84) or a LANDFIRE map zone") 561 | } 562 | # Correct order? 563 | if(!all(aoi[[1]] < aoi[[3]] & aoi[[2]] < aoi[[4]])) { 564 | stop("argument `aoi` must be ordered `xmin`, `ymin`, `xmax`, `ymax`") 565 | } 566 | # Valid map zone? 567 | } else if(length(aoi) == 1 & !all(aoi >= 1 & aoi <= 79)){ 568 | stop("argument `aoi` must be between 1 and 79 when using LANDFIRE map zones") 569 | } 570 | 571 | #### End Checks 572 | 573 | if(!is.null(edit_rule)) { 574 | edit_rule <- .fmt_editrules(edit_rule) 575 | } 576 | 577 | base_url <- httr::parse_url("https://lfps.usgs.gov/arcgis/rest/services/LandfireProductService/GPServer/LandfireProductService/submitJob?") 578 | base_url$query <- list(Layer_List = paste(products, collapse = ";"), 579 | Area_of_Interest = paste(aoi, collapse = " "), 580 | Output_Projection = projection, 581 | Resample_Resolution = resolution, 582 | Edit_Rule = edit_rule #, 583 | #Edit_Mask = edit_mask 584 | ) 585 | 586 | url <- httr::build_url(base_url) 587 | r <- httr::GET(url) 588 | job_id <- sub(".*jobs/(.*)$", "\\1", r$url) 589 | dwl_url <- paste0("https://lfps.usgs.gov/arcgis/rest/directories/arcgisjobs/landfireproductservice_gpserver/", 590 | job_id, "/scratch/", job_id, ".zip") 591 | 592 | # Loop through up to max time 593 | mt <- max_time*10 594 | 595 | for (i in 1:mt) { 596 | # Check status 597 | r <- httr::GET(r$url) 598 | status <- httr::status_code(r) #API always returns a successful status code (200) 599 | content <- strsplit(httr::content(r, "text"), "\r\n")[[1]] 600 | 601 | # Parse content for messaging and error reporting 602 | message <- gsub("\\<.*?\\>", "", content, perl = TRUE) 603 | job_status <- message[grep("Job Status", message)] 604 | inf_msg <- message[grep("esriJobMessageType", message)] 605 | 606 | if(verbose == TRUE) { 607 | # There is a better way to do this but for now...clear console each loop: 608 | cat("\014") 609 | 610 | cat(job_status,"\nJob Messages:\n",paste(inf_msg, collapse = "\n"), 611 | "\n-------------------", 612 | "\nElapsed time: ", sprintf("%.1f", round(i*0.1, 1)), "s", "(Max time:", max_time, "s)", 613 | "\n-------------------\n") 614 | } 615 | 616 | # If failed exit and report 617 | if(status != 200 | grepl("Failed",job_status)) { 618 | warning(job_status) 619 | status <- "Failed" 620 | break 621 | 622 | # If success report success and download file 623 | } else if(grepl("Succeeded",job_status)) { 624 | utils::download.file(dwl_url, path, method = method, quiet = !verbose) 625 | status <- "Succeeded" 626 | break 627 | 628 | # Print current status, wait, and check again 629 | } else { 630 | Sys.sleep(0.1) 631 | } 632 | 633 | # Max time error 634 | if(i == mt) { 635 | cat("\n") 636 | warning("Job status: Incomplete and max_time reached\nVisit URL to check status and download manually:\n ", r$url) 637 | status <- "Timed out" 638 | break 639 | } 640 | 641 | } 642 | 643 | # construct landfire_api object 644 | structure( 645 | list( 646 | request = list(query = base_url$query, 647 | date = Sys.time(), 648 | url = url, 649 | job_id = job_id, 650 | dwl_url = dwl_url), 651 | content = inf_msg, # currently just returns a vector 652 | response = r, 653 | status = status, 654 | path = path 655 | ), 656 | class = "landfire_api" 657 | ) 658 | 659 | } -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | GNU General Public License 2 | ========================== 3 | 4 | _Version 3, 29 June 2007_ 5 | _Copyright © 2007 Free Software Foundation, Inc. <>_ 6 | 7 | Everyone is permitted to copy and distribute verbatim copies of this license 8 | document, but changing it is not allowed. 9 | 10 | ## Preamble 11 | 12 | The GNU General Public License is a free, copyleft license for software and other 13 | kinds of works. 14 | 15 | The licenses for most software and other practical works are designed to take away 16 | your freedom to share and change the works. By contrast, the GNU General Public 17 | License is intended to guarantee your freedom to share and change all versions of a 18 | program--to make sure it remains free software for all its users. We, the Free 19 | Software Foundation, use the GNU General Public License for most of our software; it 20 | applies also to any other work released this way by its authors. You can apply it to 21 | your programs, too. 22 | 23 | When we speak of free software, we are referring to freedom, not price. Our General 24 | Public Licenses are designed to make sure that you have the freedom to distribute 25 | copies of free software (and charge for them if you wish), that you receive source 26 | code or can get it if you want it, that you can change the software or use pieces of 27 | it in new free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you these rights or 30 | asking you to surrender the rights. Therefore, you have certain responsibilities if 31 | you distribute copies of the software, or if you modify it: responsibilities to 32 | respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether gratis or for a fee, 35 | you must pass on to the recipients the same freedoms that you received. You must make 36 | sure that they, too, receive or can get the source code. And you must show them these 37 | terms so they know their rights. 38 | 39 | Developers that use the GNU GPL protect your rights with two steps: **(1)** assert 40 | copyright on the software, and **(2)** offer you this License giving you legal permission 41 | to copy, distribute and/or modify it. 42 | 43 | For the developers' and authors' protection, the GPL clearly explains that there is 44 | no warranty for this free software. For both users' and authors' sake, the GPL 45 | requires that modified versions be marked as changed, so that their problems will not 46 | be attributed erroneously to authors of previous versions. 47 | 48 | Some devices are designed to deny users access to install or run modified versions of 49 | the software inside them, although the manufacturer can do so. This is fundamentally 50 | incompatible with the aim of protecting users' freedom to change the software. The 51 | systematic pattern of such abuse occurs in the area of products for individuals to 52 | use, which is precisely where it is most unacceptable. Therefore, we have designed 53 | this version of the GPL to prohibit the practice for those products. If such problems 54 | arise substantially in other domains, we stand ready to extend this provision to 55 | those domains in future versions of the GPL, as needed to protect the freedom of 56 | users. 57 | 58 | Finally, every program is threatened constantly by software patents. States should 59 | not allow patents to restrict development and use of software on general-purpose 60 | computers, but in those that do, we wish to avoid the special danger that patents 61 | applied to a free program could make it effectively proprietary. To prevent this, the 62 | GPL assures that patents cannot be used to render the program non-free. 63 | 64 | The precise terms and conditions for copying, distribution and modification follow. 65 | 66 | ## TERMS AND CONDITIONS 67 | 68 | ### 0. Definitions 69 | 70 | “This License” refers to version 3 of the GNU General Public License. 71 | 72 | “Copyright” also means copyright-like laws that apply to other kinds of 73 | works, such as semiconductor masks. 74 | 75 | “The Program” refers to any copyrightable work licensed under this 76 | License. Each licensee is addressed as “you”. “Licensees” and 77 | “recipients” may be individuals or organizations. 78 | 79 | To “modify” a work means to copy from or adapt all or part of the work in 80 | a fashion requiring copyright permission, other than the making of an exact copy. The 81 | resulting work is called a “modified version” of the earlier work or a 82 | work “based on” the earlier work. 83 | 84 | A “covered work” means either the unmodified Program or a work based on 85 | the Program. 86 | 87 | To “propagate” a work means to do anything with it that, without 88 | permission, would make you directly or secondarily liable for infringement under 89 | applicable copyright law, except executing it on a computer or modifying a private 90 | copy. Propagation includes copying, distribution (with or without modification), 91 | making available to the public, and in some countries other activities as well. 92 | 93 | To “convey” a work means any kind of propagation that enables other 94 | parties to make or receive copies. Mere interaction with a user through a computer 95 | network, with no transfer of a copy, is not conveying. 96 | 97 | An interactive user interface displays “Appropriate Legal Notices” to the 98 | extent that it includes a convenient and prominently visible feature that **(1)** 99 | displays an appropriate copyright notice, and **(2)** tells the user that there is no 100 | warranty for the work (except to the extent that warranties are provided), that 101 | licensees may convey the work under this License, and how to view a copy of this 102 | License. If the interface presents a list of user commands or options, such as a 103 | menu, a prominent item in the list meets this criterion. 104 | 105 | ### 1. Source Code 106 | 107 | The “source code” for a work means the preferred form of the work for 108 | making modifications to it. “Object code” means any non-source form of a 109 | work. 110 | 111 | A “Standard Interface” means an interface that either is an official 112 | standard defined by a recognized standards body, or, in the case of interfaces 113 | specified for a particular programming language, one that is widely used among 114 | developers working in that language. 115 | 116 | The “System Libraries” of an executable work include anything, other than 117 | the work as a whole, that **(a)** is included in the normal form of packaging a Major 118 | Component, but which is not part of that Major Component, and **(b)** serves only to 119 | enable use of the work with that Major Component, or to implement a Standard 120 | Interface for which an implementation is available to the public in source code form. 121 | A “Major Component”, in this context, means a major essential component 122 | (kernel, window system, and so on) of the specific operating system (if any) on which 123 | the executable work runs, or a compiler used to produce the work, or an object code 124 | interpreter used to run it. 125 | 126 | The “Corresponding Source” for a work in object code form means all the 127 | source code needed to generate, install, and (for an executable work) run the object 128 | code and to modify the work, including scripts to control those activities. However, 129 | it does not include the work's System Libraries, or general-purpose tools or 130 | generally available free programs which are used unmodified in performing those 131 | activities but which are not part of the work. For example, Corresponding Source 132 | includes interface definition files associated with source files for the work, and 133 | the source code for shared libraries and dynamically linked subprograms that the work 134 | is specifically designed to require, such as by intimate data communication or 135 | control flow between those subprograms and other parts of the work. 136 | 137 | The Corresponding Source need not include anything that users can regenerate 138 | automatically from other parts of the Corresponding Source. 139 | 140 | The Corresponding Source for a work in source code form is that same work. 141 | 142 | ### 2. Basic Permissions 143 | 144 | All rights granted under this License are granted for the term of copyright on the 145 | Program, and are irrevocable provided the stated conditions are met. This License 146 | explicitly affirms your unlimited permission to run the unmodified Program. The 147 | output from running a covered work is covered by this License only if the output, 148 | given its content, constitutes a covered work. This License acknowledges your rights 149 | of fair use or other equivalent, as provided by copyright law. 150 | 151 | You may make, run and propagate covered works that you do not convey, without 152 | conditions so long as your license otherwise remains in force. You may convey covered 153 | works to others for the sole purpose of having them make modifications exclusively 154 | for you, or provide you with facilities for running those works, provided that you 155 | comply with the terms of this License in conveying all material for which you do not 156 | control copyright. Those thus making or running the covered works for you must do so 157 | exclusively on your behalf, under your direction and control, on terms that prohibit 158 | them from making any copies of your copyrighted material outside their relationship 159 | with you. 160 | 161 | Conveying under any other circumstances is permitted solely under the conditions 162 | stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 163 | 164 | ### 3. Protecting Users' Legal Rights From Anti-Circumvention Law 165 | 166 | No covered work shall be deemed part of an effective technological measure under any 167 | applicable law fulfilling obligations under article 11 of the WIPO copyright treaty 168 | adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention 169 | of such measures. 170 | 171 | When you convey a covered work, you waive any legal power to forbid circumvention of 172 | technological measures to the extent such circumvention is effected by exercising 173 | rights under this License with respect to the covered work, and you disclaim any 174 | intention to limit operation or modification of the work as a means of enforcing, 175 | against the work's users, your or third parties' legal rights to forbid circumvention 176 | of technological measures. 177 | 178 | ### 4. Conveying Verbatim Copies 179 | 180 | You may convey verbatim copies of the Program's source code as you receive it, in any 181 | medium, provided that you conspicuously and appropriately publish on each copy an 182 | appropriate copyright notice; keep intact all notices stating that this License and 183 | any non-permissive terms added in accord with section 7 apply to the code; keep 184 | intact all notices of the absence of any warranty; and give all recipients a copy of 185 | this License along with the Program. 186 | 187 | You may charge any price or no price for each copy that you convey, and you may offer 188 | support or warranty protection for a fee. 189 | 190 | ### 5. Conveying Modified Source Versions 191 | 192 | You may convey a work based on the Program, or the modifications to produce it from 193 | the Program, in the form of source code under the terms of section 4, provided that 194 | you also meet all of these conditions: 195 | 196 | * **a)** The work must carry prominent notices stating that you modified it, and giving a 197 | relevant date. 198 | * **b)** The work must carry prominent notices stating that it is released under this 199 | License and any conditions added under section 7. This requirement modifies the 200 | requirement in section 4 to “keep intact all notices”. 201 | * **c)** You must license the entire work, as a whole, under this License to anyone who 202 | comes into possession of a copy. This License will therefore apply, along with any 203 | applicable section 7 additional terms, to the whole of the work, and all its parts, 204 | regardless of how they are packaged. This License gives no permission to license the 205 | work in any other way, but it does not invalidate such permission if you have 206 | separately received it. 207 | * **d)** If the work has interactive user interfaces, each must display Appropriate Legal 208 | Notices; however, if the Program has interactive interfaces that do not display 209 | Appropriate Legal Notices, your work need not make them do so. 210 | 211 | A compilation of a covered work with other separate and independent works, which are 212 | not by their nature extensions of the covered work, and which are not combined with 213 | it such as to form a larger program, in or on a volume of a storage or distribution 214 | medium, is called an “aggregate” if the compilation and its resulting 215 | copyright are not used to limit the access or legal rights of the compilation's users 216 | beyond what the individual works permit. Inclusion of a covered work in an aggregate 217 | does not cause this License to apply to the other parts of the aggregate. 218 | 219 | ### 6. Conveying Non-Source Forms 220 | 221 | You may convey a covered work in object code form under the terms of sections 4 and 222 | 5, provided that you also convey the machine-readable Corresponding Source under the 223 | terms of this License, in one of these ways: 224 | 225 | * **a)** Convey the object code in, or embodied in, a physical product (including a 226 | physical distribution medium), accompanied by the Corresponding Source fixed on a 227 | durable physical medium customarily used for software interchange. 228 | * **b)** Convey the object code in, or embodied in, a physical product (including a 229 | physical distribution medium), accompanied by a written offer, valid for at least 230 | three years and valid for as long as you offer spare parts or customer support for 231 | that product model, to give anyone who possesses the object code either **(1)** a copy of 232 | the Corresponding Source for all the software in the product that is covered by this 233 | License, on a durable physical medium customarily used for software interchange, for 234 | a price no more than your reasonable cost of physically performing this conveying of 235 | source, or **(2)** access to copy the Corresponding Source from a network server at no 236 | charge. 237 | * **c)** Convey individual copies of the object code with a copy of the written offer to 238 | provide the Corresponding Source. This alternative is allowed only occasionally and 239 | noncommercially, and only if you received the object code with such an offer, in 240 | accord with subsection 6b. 241 | * **d)** Convey the object code by offering access from a designated place (gratis or for 242 | a charge), and offer equivalent access to the Corresponding Source in the same way 243 | through the same place at no further charge. You need not require recipients to copy 244 | the Corresponding Source along with the object code. If the place to copy the object 245 | code is a network server, the Corresponding Source may be on a different server 246 | (operated by you or a third party) that supports equivalent copying facilities, 247 | provided you maintain clear directions next to the object code saying where to find 248 | the Corresponding Source. Regardless of what server hosts the Corresponding Source, 249 | you remain obligated to ensure that it is available for as long as needed to satisfy 250 | these requirements. 251 | * **e)** Convey the object code using peer-to-peer transmission, provided you inform 252 | other peers where the object code and Corresponding Source of the work are being 253 | offered to the general public at no charge under subsection 6d. 254 | 255 | A separable portion of the object code, whose source code is excluded from the 256 | Corresponding Source as a System Library, need not be included in conveying the 257 | object code work. 258 | 259 | A “User Product” is either **(1)** a “consumer product”, which 260 | means any tangible personal property which is normally used for personal, family, or 261 | household purposes, or **(2)** anything designed or sold for incorporation into a 262 | dwelling. In determining whether a product is a consumer product, doubtful cases 263 | shall be resolved in favor of coverage. For a particular product received by a 264 | particular user, “normally used” refers to a typical or common use of 265 | that class of product, regardless of the status of the particular user or of the way 266 | in which the particular user actually uses, or expects or is expected to use, the 267 | product. A product is a consumer product regardless of whether the product has 268 | substantial commercial, industrial or non-consumer uses, unless such uses represent 269 | the only significant mode of use of the product. 270 | 271 | “Installation Information” for a User Product means any methods, 272 | procedures, authorization keys, or other information required to install and execute 273 | modified versions of a covered work in that User Product from a modified version of 274 | its Corresponding Source. The information must suffice to ensure that the continued 275 | functioning of the modified object code is in no case prevented or interfered with 276 | solely because modification has been made. 277 | 278 | If you convey an object code work under this section in, or with, or specifically for 279 | use in, a User Product, and the conveying occurs as part of a transaction in which 280 | the right of possession and use of the User Product is transferred to the recipient 281 | in perpetuity or for a fixed term (regardless of how the transaction is 282 | characterized), the Corresponding Source conveyed under this section must be 283 | accompanied by the Installation Information. But this requirement does not apply if 284 | neither you nor any third party retains the ability to install modified object code 285 | on the User Product (for example, the work has been installed in ROM). 286 | 287 | The requirement to provide Installation Information does not include a requirement to 288 | continue to provide support service, warranty, or updates for a work that has been 289 | modified or installed by the recipient, or for the User Product in which it has been 290 | modified or installed. Access to a network may be denied when the modification itself 291 | materially and adversely affects the operation of the network or violates the rules 292 | and protocols for communication across the network. 293 | 294 | Corresponding Source conveyed, and Installation Information provided, in accord with 295 | this section must be in a format that is publicly documented (and with an 296 | implementation available to the public in source code form), and must require no 297 | special password or key for unpacking, reading or copying. 298 | 299 | ### 7. Additional Terms 300 | 301 | “Additional permissions” are terms that supplement the terms of this 302 | License by making exceptions from one or more of its conditions. Additional 303 | permissions that are applicable to the entire Program shall be treated as though they 304 | were included in this License, to the extent that they are valid under applicable 305 | law. If additional permissions apply only to part of the Program, that part may be 306 | used separately under those permissions, but the entire Program remains governed by 307 | this License without regard to the additional permissions. 308 | 309 | When you convey a copy of a covered work, you may at your option remove any 310 | additional permissions from that copy, or from any part of it. (Additional 311 | permissions may be written to require their own removal in certain cases when you 312 | modify the work.) You may place additional permissions on material, added by you to a 313 | covered work, for which you have or can give appropriate copyright permission. 314 | 315 | Notwithstanding any other provision of this License, for material you add to a 316 | covered work, you may (if authorized by the copyright holders of that material) 317 | supplement the terms of this License with terms: 318 | 319 | * **a)** Disclaiming warranty or limiting liability differently from the terms of 320 | sections 15 and 16 of this License; or 321 | * **b)** Requiring preservation of specified reasonable legal notices or author 322 | attributions in that material or in the Appropriate Legal Notices displayed by works 323 | containing it; or 324 | * **c)** Prohibiting misrepresentation of the origin of that material, or requiring that 325 | modified versions of such material be marked in reasonable ways as different from the 326 | original version; or 327 | * **d)** Limiting the use for publicity purposes of names of licensors or authors of the 328 | material; or 329 | * **e)** Declining to grant rights under trademark law for use of some trade names, 330 | trademarks, or service marks; or 331 | * **f)** Requiring indemnification of licensors and authors of that material by anyone 332 | who conveys the material (or modified versions of it) with contractual assumptions of 333 | liability to the recipient, for any liability that these contractual assumptions 334 | directly impose on those licensors and authors. 335 | 336 | All other non-permissive additional terms are considered “further 337 | restrictions” within the meaning of section 10. If the Program as you received 338 | it, or any part of it, contains a notice stating that it is governed by this License 339 | along with a term that is a further restriction, you may remove that term. If a 340 | license document contains a further restriction but permits relicensing or conveying 341 | under this License, you may add to a covered work material governed by the terms of 342 | that license document, provided that the further restriction does not survive such 343 | relicensing or conveying. 344 | 345 | If you add terms to a covered work in accord with this section, you must place, in 346 | the relevant source files, a statement of the additional terms that apply to those 347 | files, or a notice indicating where to find the applicable terms. 348 | 349 | Additional terms, permissive or non-permissive, may be stated in the form of a 350 | separately written license, or stated as exceptions; the above requirements apply 351 | either way. 352 | 353 | ### 8. Termination 354 | 355 | You may not propagate or modify a covered work except as expressly provided under 356 | this License. Any attempt otherwise to propagate or modify it is void, and will 357 | automatically terminate your rights under this License (including any patent licenses 358 | granted under the third paragraph of section 11). 359 | 360 | However, if you cease all violation of this License, then your license from a 361 | particular copyright holder is reinstated **(a)** provisionally, unless and until the 362 | copyright holder explicitly and finally terminates your license, and **(b)** permanently, 363 | if the copyright holder fails to notify you of the violation by some reasonable means 364 | prior to 60 days after the cessation. 365 | 366 | Moreover, your license from a particular copyright holder is reinstated permanently 367 | if the copyright holder notifies you of the violation by some reasonable means, this 368 | is the first time you have received notice of violation of this License (for any 369 | work) from that copyright holder, and you cure the violation prior to 30 days after 370 | your receipt of the notice. 371 | 372 | Termination of your rights under this section does not terminate the licenses of 373 | parties who have received copies or rights from you under this License. If your 374 | rights have been terminated and not permanently reinstated, you do not qualify to 375 | receive new licenses for the same material under section 10. 376 | 377 | ### 9. Acceptance Not Required for Having Copies 378 | 379 | You are not required to accept this License in order to receive or run a copy of the 380 | Program. Ancillary propagation of a covered work occurring solely as a consequence of 381 | using peer-to-peer transmission to receive a copy likewise does not require 382 | acceptance. However, nothing other than this License grants you permission to 383 | propagate or modify any covered work. These actions infringe copyright if you do not 384 | accept this License. Therefore, by modifying or propagating a covered work, you 385 | indicate your acceptance of this License to do so. 386 | 387 | ### 10. Automatic Licensing of Downstream Recipients 388 | 389 | Each time you convey a covered work, the recipient automatically receives a license 390 | from the original licensors, to run, modify and propagate that work, subject to this 391 | License. You are not responsible for enforcing compliance by third parties with this 392 | License. 393 | 394 | An “entity transaction” is a transaction transferring control of an 395 | organization, or substantially all assets of one, or subdividing an organization, or 396 | merging organizations. If propagation of a covered work results from an entity 397 | transaction, each party to that transaction who receives a copy of the work also 398 | receives whatever licenses to the work the party's predecessor in interest had or 399 | could give under the previous paragraph, plus a right to possession of the 400 | Corresponding Source of the work from the predecessor in interest, if the predecessor 401 | has it or can get it with reasonable efforts. 402 | 403 | You may not impose any further restrictions on the exercise of the rights granted or 404 | affirmed under this License. For example, you may not impose a license fee, royalty, 405 | or other charge for exercise of rights granted under this License, and you may not 406 | initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging 407 | that any patent claim is infringed by making, using, selling, offering for sale, or 408 | importing the Program or any portion of it. 409 | 410 | ### 11. Patents 411 | 412 | A “contributor” is a copyright holder who authorizes use under this 413 | License of the Program or a work on which the Program is based. The work thus 414 | licensed is called the contributor's “contributor version”. 415 | 416 | A contributor's “essential patent claims” are all patent claims owned or 417 | controlled by the contributor, whether already acquired or hereafter acquired, that 418 | would be infringed by some manner, permitted by this License, of making, using, or 419 | selling its contributor version, but do not include claims that would be infringed 420 | only as a consequence of further modification of the contributor version. For 421 | purposes of this definition, “control” includes the right to grant patent 422 | sublicenses in a manner consistent with the requirements of this License. 423 | 424 | Each contributor grants you a non-exclusive, worldwide, royalty-free patent license 425 | under the contributor's essential patent claims, to make, use, sell, offer for sale, 426 | import and otherwise run, modify and propagate the contents of its contributor 427 | version. 428 | 429 | In the following three paragraphs, a “patent license” is any express 430 | agreement or commitment, however denominated, not to enforce a patent (such as an 431 | express permission to practice a patent or covenant not to sue for patent 432 | infringement). To “grant” such a patent license to a party means to make 433 | such an agreement or commitment not to enforce a patent against the party. 434 | 435 | If you convey a covered work, knowingly relying on a patent license, and the 436 | Corresponding Source of the work is not available for anyone to copy, free of charge 437 | and under the terms of this License, through a publicly available network server or 438 | other readily accessible means, then you must either **(1)** cause the Corresponding 439 | Source to be so available, or **(2)** arrange to deprive yourself of the benefit of the 440 | patent license for this particular work, or **(3)** arrange, in a manner consistent with 441 | the requirements of this License, to extend the patent license to downstream 442 | recipients. “Knowingly relying” means you have actual knowledge that, but 443 | for the patent license, your conveying the covered work in a country, or your 444 | recipient's use of the covered work in a country, would infringe one or more 445 | identifiable patents in that country that you have reason to believe are valid. 446 | 447 | If, pursuant to or in connection with a single transaction or arrangement, you 448 | convey, or propagate by procuring conveyance of, a covered work, and grant a patent 449 | license to some of the parties receiving the covered work authorizing them to use, 450 | propagate, modify or convey a specific copy of the covered work, then the patent 451 | license you grant is automatically extended to all recipients of the covered work and 452 | works based on it. 453 | 454 | A patent license is “discriminatory” if it does not include within the 455 | scope of its coverage, prohibits the exercise of, or is conditioned on the 456 | non-exercise of one or more of the rights that are specifically granted under this 457 | License. You may not convey a covered work if you are a party to an arrangement with 458 | a third party that is in the business of distributing software, under which you make 459 | payment to the third party based on the extent of your activity of conveying the 460 | work, and under which the third party grants, to any of the parties who would receive 461 | the covered work from you, a discriminatory patent license **(a)** in connection with 462 | copies of the covered work conveyed by you (or copies made from those copies), or **(b)** 463 | primarily for and in connection with specific products or compilations that contain 464 | the covered work, unless you entered into that arrangement, or that patent license 465 | was granted, prior to 28 March 2007. 466 | 467 | Nothing in this License shall be construed as excluding or limiting any implied 468 | license or other defenses to infringement that may otherwise be available to you 469 | under applicable patent law. 470 | 471 | ### 12. No Surrender of Others' Freedom 472 | 473 | If conditions are imposed on you (whether by court order, agreement or otherwise) 474 | that contradict the conditions of this License, they do not excuse you from the 475 | conditions of this License. If you cannot convey a covered work so as to satisfy 476 | simultaneously your obligations under this License and any other pertinent 477 | obligations, then as a consequence you may not convey it at all. For example, if you 478 | agree to terms that obligate you to collect a royalty for further conveying from 479 | those to whom you convey the Program, the only way you could satisfy both those terms 480 | and this License would be to refrain entirely from conveying the Program. 481 | 482 | ### 13. Use with the GNU Affero General Public License 483 | 484 | Notwithstanding any other provision of this License, you have permission to link or 485 | combine any covered work with a work licensed under version 3 of the GNU Affero 486 | General Public License into a single combined work, and to convey the resulting work. 487 | The terms of this License will continue to apply to the part which is the covered 488 | work, but the special requirements of the GNU Affero General Public License, section 489 | 13, concerning interaction through a network will apply to the combination as such. 490 | 491 | ### 14. Revised Versions of this License 492 | 493 | The Free Software Foundation may publish revised and/or new versions of the GNU 494 | General Public License from time to time. Such new versions will be similar in spirit 495 | to the present version, but may differ in detail to address new problems or concerns. 496 | 497 | Each version is given a distinguishing version number. If the Program specifies that 498 | a certain numbered version of the GNU General Public License “or any later 499 | version” applies to it, you have the option of following the terms and 500 | conditions either of that numbered version or of any later version published by the 501 | Free Software Foundation. If the Program does not specify a version number of the GNU 502 | General Public License, you may choose any version ever published by the Free 503 | Software Foundation. 504 | 505 | If the Program specifies that a proxy can decide which future versions of the GNU 506 | General Public License can be used, that proxy's public statement of acceptance of a 507 | version permanently authorizes you to choose that version for the Program. 508 | 509 | Later license versions may give you additional or different permissions. However, no 510 | additional obligations are imposed on any author or copyright holder as a result of 511 | your choosing to follow a later version. 512 | 513 | ### 15. Disclaimer of Warranty 514 | 515 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. 516 | EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES 517 | PROVIDE THE PROGRAM “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER 518 | EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 519 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE 520 | QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE 521 | DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 522 | 523 | ### 16. Limitation of Liability 524 | 525 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY 526 | COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS 527 | PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, 528 | INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE 529 | PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE 530 | OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE 531 | WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE 532 | POSSIBILITY OF SUCH DAMAGES. 533 | 534 | ### 17. Interpretation of Sections 15 and 16 535 | 536 | If the disclaimer of warranty and limitation of liability provided above cannot be 537 | given local legal effect according to their terms, reviewing courts shall apply local 538 | law that most closely approximates an absolute waiver of all civil liability in 539 | connection with the Program, unless a warranty or assumption of liability accompanies 540 | a copy of the Program in return for a fee. 541 | 542 | _END OF TERMS AND CONDITIONS_ 543 | 544 | ## How to Apply These Terms to Your New Programs 545 | 546 | If you develop a new program, and you want it to be of the greatest possible use to 547 | the public, the best way to achieve this is to make it free software which everyone 548 | can redistribute and change under these terms. 549 | 550 | To do so, attach the following notices to the program. It is safest to attach them 551 | to the start of each source file to most effectively state the exclusion of warranty; 552 | and each file should have at least the “copyright” line and a pointer to 553 | where the full notice is found. 554 | 555 | 556 | Copyright (C) 557 | 558 | This program is free software: you can redistribute it and/or modify 559 | it under the terms of the GNU General Public License as published by 560 | the Free Software Foundation, either version 3 of the License, or 561 | (at your option) any later version. 562 | 563 | This program is distributed in the hope that it will be useful, 564 | but WITHOUT ANY WARRANTY; without even the implied warranty of 565 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 566 | GNU General Public License for more details. 567 | 568 | You should have received a copy of the GNU General Public License 569 | along with this program. If not, see . 570 | 571 | Also add information on how to contact you by electronic and paper mail. 572 | 573 | If the program does terminal interaction, make it output a short notice like this 574 | when it starts in an interactive mode: 575 | 576 | Copyright (C) 577 | This program comes with ABSOLUTELY NO WARRANTY; for details type 'show w'. 578 | This is free software, and you are welcome to redistribute it 579 | under certain conditions; type 'show c' for details. 580 | 581 | The hypothetical commands `show w` and `show c` should show the appropriate parts of 582 | the General Public License. Of course, your program's commands might be different; 583 | for a GUI interface, you would use an “about box”. 584 | 585 | You should also get your employer (if you work as a programmer) or school, if any, to 586 | sign a “copyright disclaimer” for the program, if necessary. For more 587 | information on this, and how to apply and follow the GNU GPL, see 588 | <>. 589 | 590 | The GNU General Public License does not permit incorporating your program into 591 | proprietary programs. If your program is a subroutine library, you may consider it 592 | more useful to permit linking proprietary applications with the library. If this is 593 | what you want to do, use the GNU Lesser General Public License instead of this 594 | License. But first, please read 595 | <>. 596 | --------------------------------------------------------------------------------