| Title: | NASA's Ice, Cloud, and Elevation Satellite (ICESat-2) Data Analysis for Land and Vegetation Applications |
|---|---|
| Description: | Set of tools for downloading, reading, visualizing, processing and exporting NASA's ICESat-2 ATL03 (Global Geolocated Photon Data) and ATL08 (Land and Vegetation Height) products for Land and Vegetation Applications. |
| Authors: | Carlos Alberto Silva [aut, cph, cre], Caio Hamamura [aut, cph], Cesar Alvites [aut, ctb], Alexander J. Gaskins [aut, ctb] |
| Maintainer: | Carlos Alberto Silva <[email protected]> |
| License: | GPL (>= 3) |
| Version: | 0.0.5 |
| Built: | 2026-06-06 21:03:17 UTC |
| Source: | https://github.com/carlos-alberto-silva/ICESat2VegR |
Tools to download, read, process, model, and visualize ICESat-2 ATL03/ATL08 for land and vegetation applications.
Maintainer: Caio Hamamura [email protected] [copyright holder]
Authors:
Caio Hamamura [email protected] [copyright holder]
Carlos Alberto Silva [email protected] [copyright holder]
Useful links:
Report bugs at https://github.com/carlos-alberto-silva/ICESat2VegR/issues
.as_ee_geom() converts a variety of R geometry representations
(including sf, sfc, terra objects, bounding boxes, WKT/GeoJSON,
and even existing Earth Engine python objects) into a Python
ee$Geometry suitable for use in Earth Engine workflows.
This helper is designed to be flexible and permissive: it accepts most common spatial formats used in R and normalizes them into a standard Earth Engine geometry. When a buffer distance is supplied, the geometry is optionally buffered in meters on the Earth Engine side.
.as_ee_geom(geom, xcol = "lon", ycol = "lat", crs = 4326, buffer_m = NULL).as_ee_geom(geom, xcol = "lon", ycol = "lat", crs = 4326, buffer_m = NULL)
geom |
Geometry input. Supported types include:
|
xcol |
Character. Name of the longitude column when |
ycol |
Character. Name of the latitude column when |
crs |
Coordinate reference system of the input geometry when |
buffer_m |
Optional numeric. Buffer distance in meters applied to
the resulting Earth Engine geometry. If |
For sf/sfc and data.frame inputs, geometries are first transformed
to EPSG:4326 and written to a temporary GeoJSON file, which is then read
and wrapped into an ee$FeatureCollection(... )$geometry(). For
terra::SpatVector and terra::SpatExtent inputs, conversion proceeds
via terra::writeVector() / terra::as.polygons() and an EE rectangle
geometry, respectively.
Existing Earth Engine python objects are returned as-is, except that
ee$Feature and ee$FeatureCollection objects are coerced to their
underlying geometry via $geometry().
A Python ee$Geometry object (or compatible geometry-like EE object)
suitable for use in Earth Engine operations.
## Not run: ee <- reticulate::import("ee", delay_load = FALSE) # 1) From sf polygon library(sf) poly <- st_as_sfc(st_bbox(c( xmin = -82.4, xmax = -82.2, ymin = 29.6, ymax = 29.8 ), crs = 4326)) ee_geom1 <- .as_ee_geom(poly) # 2) From terra::SpatVector library(terra) v <- vect(system.file("extdata", "all_boundary.shp", package = "ICESat2VegR")) ee_geom2 <- .as_ee_geom(v, buffer_m = 30) # 3) From numeric extent (xmin, ymin, xmax, ymax) bbox_vec <- c(-82.4, 29.6, -82.2, 29.8) ee_geom3 <- .as_ee_geom(bbox_vec) # 4) From data.frame of points df <- data.frame( lon = c(-82.3, -82.25), lat = c(29.65, 29.7) ) ee_geom4 <- .as_ee_geom(df, buffer_m = 1000) ## End(Not run)## Not run: ee <- reticulate::import("ee", delay_load = FALSE) # 1) From sf polygon library(sf) poly <- st_as_sfc(st_bbox(c( xmin = -82.4, xmax = -82.2, ymin = 29.6, ymax = 29.8 ), crs = 4326)) ee_geom1 <- .as_ee_geom(poly) # 2) From terra::SpatVector library(terra) v <- vect(system.file("extdata", "all_boundary.shp", package = "ICESat2VegR")) ee_geom2 <- .as_ee_geom(v, buffer_m = 30) # 3) From numeric extent (xmin, ymin, xmax, ymax) bbox_vec <- c(-82.4, 29.6, -82.2, 29.8) ee_geom3 <- .as_ee_geom(bbox_vec) # 4) From data.frame of points df <- data.frame( lon = c(-82.3, -82.25), lat = c(29.65, 29.7) ) ee_geom4 <- .as_ee_geom(df, buffer_m = 1000) ## End(Not run)
.ee_ping() verifies that the Earth Engine Python API is initialized and
responsive. It attempts to evaluate a trivial Earth Engine expression
(ee$Image$constant(1)$getInfo()) and returns invisibly if successful.
If the call fails, an error is raised with a hint to authenticate and
initialize Earth Engine.
.ee_ping(ee).ee_ping(ee)
ee |
The Earth Engine Python module as returned by
|
Invisibly returns TRUE if Earth Engine is initialized and responsive.
Otherwise, an error is thrown indicating that Earth Engine must be
authenticated and initialized.
## Not run: library(reticulate) ee <- import("ee", delay_load = FALSE) # Will error if EE is not authenticated/initialized .ee_ping(ee) ## End(Not run)## Not run: library(reticulate) ee <- import("ee", delay_load = FALSE) # Will error if EE is not authenticated/initialized .ee_ping(ee) ## End(Not run)
This method subsets the granules slot of an
icesat2.granules_cloud object.
## S4 method for signature 'icesat2.granules_cloud,ANY,ANY,ANY' x[i, j, ..., drop = TRUE]## S4 method for signature 'icesat2.granules_cloud,ANY,ANY,ANY' x[i, j, ..., drop = TRUE]
x |
An object of class |
i |
Subset index. |
j |
Unused, just to match the generic signature. |
... |
Additional arguments (not used). |
drop |
Unused, just to match the generic signature. |
An object of class icesat2.granule_cloud.
This method extracts a single element from the granules
slot of an icesat2.granules_cloud object.
## S4 method for signature 'icesat2.granules_cloud,ANY,ANY' x[[i, j, ...]]## S4 method for signature 'icesat2.granules_cloud,ANY,ANY' x[[i, j, ...]]
x |
An object of class |
i |
Extraction index. |
j |
Unused, just to match the generic signature. |
... |
Additional arguments (not used). |
An object of class icesat2.granule_cloud.
## Not run: lower_left_lon <- -83.26 lower_left_lat <- 31.95 upper_right_lon <- -83.11 upper_right_lat <- 32.46 daterange <- c("2019-04-12", "2019-05-03") ATL08_granules_cloud <- ATLAS_dataFinder( short_name = "ATL08", lower_left_lon, lower_left_lat, upper_right_lon, upper_right_lat, version = "007", daterange = daterange, persist = TRUE, cloud_computing = TRUE ) ATL08_h5_cloud <- ATL08_read(ATL08_granules_cloud[1]) ATL08_h5_cloud[['gt1l']] close(ATL08_h5_cloud) ## End(Not run)## Not run: lower_left_lon <- -83.26 lower_left_lat <- 31.95 upper_right_lon <- -83.11 upper_right_lat <- 32.46 daterange <- c("2019-04-12", "2019-05-03") ATL08_granules_cloud <- ATLAS_dataFinder( short_name = "ATL08", lower_left_lon, lower_left_lat, upper_right_lon, upper_right_lat, version = "007", daterange = daterange, persist = TRUE, cloud_computing = TRUE ) ATL08_h5_cloud <- ATL08_read(ATL08_granules_cloud[1]) ATL08_h5_cloud[['gt1l']] close(ATL08_h5_cloud) ## End(Not run)
This function gives access to the GDALRasterBand using [[i]], where i is the band index to return.
## S3 method for class 'GDALDataset' x[[slice]]## S3 method for class 'GDALDataset' x[[slice]]
x |
GDALDatset. Automatically obtained from GDALDataset[[]] call. |
slice |
Integer. The index for the band to access. |
An object of GDALRasterBand R6 class.
This function gives access to the GDALRasterBand using [[i]], where i is the band index to return.
## S3 method for class 'GDALRasterBand' x[[blockX, blockY]]## S3 method for class 'GDALRasterBand' x[[blockX, blockY]]
x |
GDALRasterBand. Automatically obtained from GDALDataset[[]] call. |
blockX |
Integer. The x index for block to access. |
blockY |
Integer. The y index for block to access. |
Nothing, this is a setter
This function gives access to the GDALRasterBand using [[i]], where i is the band index to return.
## S3 replacement method for class 'GDALRasterBand' x[[blockX, blockY]] <- value## S3 replacement method for class 'GDALRasterBand' x[[blockX, blockY]] <- value
x |
GDALRasterBand. Automatically obtained from GDALDataset[[]] call. |
blockX |
Integer. The x index for block to access. |
blockY |
Integer. The y index for block to access. |
value |
Integer. The value buffer to write |
Nothing, this is a setter
Add an Earth Engine Image to a leaflet map
addEEImage( map, img, bands = NULL, min_value = 0, max_value = 1, palette = c("#d55e00", "#cc79a7", "#f0e442", "#0072b2", "#009e73"), group = NULL, aoi = NULL, ... )addEEImage( map, img, bands = NULL, min_value = 0, max_value = 1, palette = c("#d55e00", "#cc79a7", "#f0e442", "#0072b2", "#009e73"), group = NULL, aoi = NULL, ... )
map |
A |
img |
An Earth Engine image (reticulate |
bands |
Character or numeric vector (length 1 or 3). If |
min_value |
Numeric. Minimum visualization range. |
max_value |
Numeric. Maximum visualization range. |
palette |
Character vector of colors for single-band rendering. |
group |
Optional overlay group name. |
aoi |
Optional EE geometry to clip before rendering. |
... |
Passed to |
The input leaflet map with the EE image layer added.
## Not run: # Initialize Earth Engine (use your own project id) Sys.setenv(EE_PROJECT = "your-ee-project-id") ee_initialize() # Harmonized Landsat-Sentinel (HLS) surface reflectance collection collection_id <- "NASA/HLS/HLSL30/v002" ee_collection <- ee$ImageCollection(collection_id) # Mask cloud, cloud-shadow and adjacent-cloud pixels (Fmask bits 1-3) cloudMask <- 2^1 + 2^2 + 2^3 hlsMask <- function(image) { image$updateMask(!(image[["Fmask"]] & cloudMask)) } # Cloud-free median composite over two summer seasons image <- c( ee_collection$filterDate("2020-04-01", "2020-07-31")$map(hlsMask), ee_collection$filterDate("2021-04-01", "2021-07-31")$map(hlsMask) )$filter("CLOUD_COVERAGE < 30")$median() # Show the RGB composite (bands 3-2-1) on an interactive map if (require("leaflet")) { leaflet() %>% addEEImage( image, bands = c(3, 2, 1), min_value = 0.001, max_value = 0.2 ) %>% setView(lng = -82.2345, lat = 29.6552, zoom = 10) } ## End(Not run)## Not run: # Initialize Earth Engine (use your own project id) Sys.setenv(EE_PROJECT = "your-ee-project-id") ee_initialize() # Harmonized Landsat-Sentinel (HLS) surface reflectance collection collection_id <- "NASA/HLS/HLSL30/v002" ee_collection <- ee$ImageCollection(collection_id) # Mask cloud, cloud-shadow and adjacent-cloud pixels (Fmask bits 1-3) cloudMask <- 2^1 + 2^2 + 2^3 hlsMask <- function(image) { image$updateMask(!(image[["Fmask"]] & cloudMask)) } # Cloud-free median composite over two summer seasons image <- c( ee_collection$filterDate("2020-04-01", "2020-07-31")$map(hlsMask), ee_collection$filterDate("2021-04-01", "2021-07-31")$map(hlsMask) )$filter("CLOUD_COVERAGE < 30")$median() # Show the RGB composite (bands 3-2-1) on an interactive map if (require("leaflet")) { leaflet() %>% addEEImage( image, bands = c(3, 2, 1), min_value = 0.001, max_value = 0.2 ) %>% setView(lng = -82.2345, lat = 29.6552, zoom = 10) } ## End(Not run)
This class uses Approximate Neareast Neighbor Index for finding points that are within a specified range.
treeThe C++ pointer for the built tree ANNIndex constructor
ANNIndex$new()Creates a new instance of the ANNIndex class.
ANNIndex$new(x, y)
xNumericVector of x/longitude
yNumericVector of y/latitude
searchFixedRadius method
ANNIndex$searchFixedRadius()Given a x, y point get the indexes that are within a specified radius.
ANNIndex$searchFixedRadius(x, y, radius)
xNumericVector of x/longitude
yNumericVector of y/latitude
radiusthe minimum radius between the points
Mount, D. M.; Arya, S. ANN: A Library for Approximate Nearest Neighbor Searching, available in https://www.cs.umd.edu/~mount/ANN/
Computes the terrain aspect in degrees for each pixel of an Earth Engine
ee$Image representing a digital elevation model (DEM).
Aspect describes the downslope direction of the steepest gradient and is
expressed in degrees clockwise from north. The computation is performed
using Earth Engine's built-in ee$Terrain$aspect() function. As with slope,
Earth Engine uses the 4-connected neighborhood, so missing values may occur
near image edges.
aspect(x)aspect(x)
x |
An |
An ee$Image with one band named aspect containing aspect
values in degrees clockwise from north.
## Not run: ee <- reticulate::import("ee") dem <- ee$Image("NASA/NASADEM_HGT/001") asp <- aspect(dem) ## End(Not run)## Not run: ee <- reticulate::import("ee") dem <- ee$Image("NASA/NASADEM_HGT/001") asp <- aspect(dem) ## End(Not run)
Calculates the angle formed by the 2D vector [x, y]
atan2.ee.ee_number.Number(x, e2)atan2.ee.ee_number.Number(x, e2)
x |
An |
e2 |
An |
An ee$Number representing the angle in radians
https://developers.google.com/earth-engine/apidocs/ee-number-atan2
Computes a series of statistics from ATL03 and ATL08 labeled photons within a given segment length.
ATL03_ATL08_compute_seg_attributes_dt_segStat( atl03_atl08_seg_dt, list_expr, ph_class = c(0, 1, 2, 3), beam = c("gt1l", "gt1r", "gt2l", "gt2r", "gt3l", "gt3r"), quality_ph = NULL, night_flag = NULL )ATL03_ATL08_compute_seg_attributes_dt_segStat( atl03_atl08_seg_dt, list_expr, ph_class = c(0, 1, 2, 3), beam = c("gt1l", "gt1r", "gt2l", "gt2r", "gt3l", "gt3r"), quality_ph = NULL, night_flag = NULL )
atl03_atl08_seg_dt |
An S4 object of class |
list_expr |
The function to be applied for computing the defined statistics |
ph_class |
Character vector indicating photons to process based on the classification (1=ground, 2=canopy, 3=top canopy), Default is c(2,3) |
beam |
Character vector indicating beams to process. Default is c("gt1l", "gt1r", "gt2l", "gt2r", "gt3l", "gt3r") |
quality_ph |
Indicates the quality of the associated photon. 0 = nominal, 1 = possible_afterpulse, 2 = possible_impulse_response_ effect, 3=possible_tep. Default is 0 |
night_flag |
Flag indicating the data were acquired in night conditions: 0=day, 1=night. Default is 1 |
Returns an S4 object of class icesat2.atl08_dt
Containing Statistics of ATL03 and ATL08 labeled photons
# Specifying ATL03 and ATL08 file path atl03_path <- system.file("extdata", "atl03_clip.h5", package = "ICESat2VegR" ) atl08_path <- system.file("extdata", "atl08_clip.h5", package = "ICESat2VegR" ) # Reading ATL03 data (h5 file) atl03_h5 <- ATL03_read(atl03_path = atl03_path) # Reading ATL08 data (h5 file) atl08_h5 <- ATL08_read(atl08_path = atl08_path) # Extracting ATL03 and ATL08 labeled photons atl03_atl08_dt <- ATL03_ATL08_photons_attributes_dt_join(atl03_h5, atl08_h5) # Computing the max canopy height at 30 m segments atl03_atl08_dt_seg <- ATL03_ATL08_segment_create(atl03_atl08_dt, segment_length = 30) max_canopy <- ATL03_ATL08_compute_seg_attributes_dt_segStat(atl03_atl08_dt_seg, list_expr = max(ph_h), ph_class = c(2, 3), beam = c("gt1l", "gt1r", "gt2l", "gt2r", "gt3l", "gt3r"), quality_ph = 0, night_flag = 0 ) head(max_canopy) # Computing a series of canopy height statistics from customized list expressions canopy_metrics <- ATL03_ATL08_compute_seg_attributes_dt_segStat(atl03_atl08_dt_seg, list_expr = list( max_ph_elevation = max(h_ph), h_canopy = quantile(ph_h, 0.98), n_canopy = sum(classed_pc_flag == 2), n_top_canopy = sum(classed_pc_flag == 3) ), ph_class = c(2, 3), beam = c("gt1l", "gt1r", "gt2l", "gt2r", "gt3l", "gt3r"), quality_ph = 0, night_flag = 0 # there are no night photons in this dataset ) head(canopy_metrics) close(atl03_h5) close(atl08_h5)# Specifying ATL03 and ATL08 file path atl03_path <- system.file("extdata", "atl03_clip.h5", package = "ICESat2VegR" ) atl08_path <- system.file("extdata", "atl08_clip.h5", package = "ICESat2VegR" ) # Reading ATL03 data (h5 file) atl03_h5 <- ATL03_read(atl03_path = atl03_path) # Reading ATL08 data (h5 file) atl08_h5 <- ATL08_read(atl08_path = atl08_path) # Extracting ATL03 and ATL08 labeled photons atl03_atl08_dt <- ATL03_ATL08_photons_attributes_dt_join(atl03_h5, atl08_h5) # Computing the max canopy height at 30 m segments atl03_atl08_dt_seg <- ATL03_ATL08_segment_create(atl03_atl08_dt, segment_length = 30) max_canopy <- ATL03_ATL08_compute_seg_attributes_dt_segStat(atl03_atl08_dt_seg, list_expr = max(ph_h), ph_class = c(2, 3), beam = c("gt1l", "gt1r", "gt2l", "gt2r", "gt3l", "gt3r"), quality_ph = 0, night_flag = 0 ) head(max_canopy) # Computing a series of canopy height statistics from customized list expressions canopy_metrics <- ATL03_ATL08_compute_seg_attributes_dt_segStat(atl03_atl08_dt_seg, list_expr = list( max_ph_elevation = max(h_ph), h_canopy = quantile(ph_h, 0.98), n_canopy = sum(classed_pc_flag == 2), n_top_canopy = sum(classed_pc_flag == 3) ), ph_class = c(2, 3), beam = c("gt1l", "gt1r", "gt2l", "gt2r", "gt3l", "gt3r"), quality_ph = 0, night_flag = 0 # there are no night photons in this dataset ) head(canopy_metrics) close(atl03_h5) close(atl08_h5)
Clips joined ATL03 and ATL08 photon attributes within a given bounding
extent, defined by a single clip_obj argument. The clipping extent can
be provided as:
(i) a numeric bounding box, or
(ii) a spatial extent object.
ATL03_ATL08_photons_attributes_dt_clipBox(atl03_atl08_dt, clip_obj)ATL03_ATL08_photons_attributes_dt_clipBox(atl03_atl08_dt, clip_obj)
atl03_atl08_dt |
An S4 object of class
|
clip_obj |
Bounding extent used to perform the clipping. Supported inputs:
|
When clip_obj is a SpatExtent, the package terra must be
installed. If not found, the function stops with an informative message.
Returns an S4 object of class
icesat2.atl03atl08_dt containing a subset of the
joined ATL03 and ATL08 photon attributes restricted to the clipping extent.
https://icesat-2.gsfc.nasa.gov/sites/default/files/page_files/ICESat2_ATL03_ATBD_r006.pdf
https://icesat-2.gsfc.nasa.gov/sites/default/files/page_files/ICESat2_ATL08_ATBD_r006.pdf
# Specifying the path to ATL03 and ATL08 files atl03_path <- system.file("extdata", "atl03_clip.h5", package = "ICESat2VegR") atl08_path <- system.file("extdata", "atl08_clip.h5", package = "ICESat2VegR") # Reading ATL03 and ATL08 data (h5 files) atl03_h5 <- ATL03_read(atl03_path = atl03_path) atl08_h5 <- ATL08_read(atl08_path = atl08_path) # Joining ATL03 and ATL08 photons and heights atl03_atl08_dt <- ATL03_ATL08_photons_attributes_dt_join(atl03_h5, atl08_h5) head(atl03_atl08_dt) # 1) Using a numeric bounding box: xmin ymin xmax ymax bbox <- c(-106.571, 41.531, -106.569, 41.540) atl03_atl08_dt_clip <- ATL03_ATL08_photons_attributes_dt_clipBox( atl03_atl08_dt = atl03_atl08_dt, clip_obj = bbox ) head(atl03_atl08_dt_clip) # 2) Using a SpatExtent (example) # library(terra) # ext <- terra::ext(-106.57, -106.569, 41.531, 41.540) # atl03_atl08_dt_clip_ext <- ATL03_ATL08_photons_attributes_dt_clipBox( # atl03_atl08_dt = atl03_atl08_dt, # clip_obj = ext # ) close(atl03_h5) close(atl08_h5)# Specifying the path to ATL03 and ATL08 files atl03_path <- system.file("extdata", "atl03_clip.h5", package = "ICESat2VegR") atl08_path <- system.file("extdata", "atl08_clip.h5", package = "ICESat2VegR") # Reading ATL03 and ATL08 data (h5 files) atl03_h5 <- ATL03_read(atl03_path = atl03_path) atl08_h5 <- ATL08_read(atl08_path = atl08_path) # Joining ATL03 and ATL08 photons and heights atl03_atl08_dt <- ATL03_ATL08_photons_attributes_dt_join(atl03_h5, atl08_h5) head(atl03_atl08_dt) # 1) Using a numeric bounding box: xmin ymin xmax ymax bbox <- c(-106.571, 41.531, -106.569, 41.540) atl03_atl08_dt_clip <- ATL03_ATL08_photons_attributes_dt_clipBox( atl03_atl08_dt = atl03_atl08_dt, clip_obj = bbox ) head(atl03_atl08_dt_clip) # 2) Using a SpatExtent (example) # library(terra) # ext <- terra::ext(-106.57, -106.569, 41.531, 41.540) # atl03_atl08_dt_clip_ext <- ATL03_ATL08_photons_attributes_dt_clipBox( # atl03_atl08_dt = atl03_atl08_dt, # clip_obj = ext # ) close(atl03_h5) close(atl08_h5)
This function clips joined ATL03 and ATL08 photon attributes within a given geometry.
ATL03_ATL08_photons_attributes_dt_clipGeometry( atl03_atl08_dt, clip_obj, split_by = NULL )ATL03_ATL08_photons_attributes_dt_clipGeometry( atl03_atl08_dt, clip_obj, split_by = NULL )
atl03_atl08_dt |
An S4 object of class |
clip_obj |
An object of class |
split_by |
Optional. clip_obj ID. If defined, the data will be clipped by each clip_obj using the clip_obj ID from the attribute table. |
Returns an S4 object of class icesat2.atl03atl08_dt
containing the clipped ATL08 attributes.
# Specifying the path to ATL03 and ATL08 files atl03_path <- system.file("extdata", "atl03_clip.h5", package = "ICESat2VegR") atl08_path <- system.file("extdata", "atl08_clip.h5", package = "ICESat2VegR") # Reading ATL03 and ATL08 data (h5 files) atl03_h5 <- ATL03_read(atl03_path) atl08_h5 <- ATL08_read(atl08_path) # Joining ATL03 and ATL08 photon attributes atl03_atl08_dt <- ATL03_ATL08_photons_attributes_dt_join(atl03_h5, atl08_h5) head(atl03_atl08_dt) # Specifying the path to the shapefile clip_obj_filepath <- system.file("extdata", "clip_geom.shp", package = "ICESat2VegR") # Reading shapefile as a SpatVector object clip_obj <- terra::vect(clip_obj_filepath) # Clipping ATL08 terrain attributes by geometry atl03_atl08_dt_clip <- ATL03_ATL08_photons_attributes_dt_clipGeometry( atl03_atl08_dt, clip_obj, split_by = "id" ) head(atl03_atl08_dt_clip) close(atl03_h5) close(atl08_h5)# Specifying the path to ATL03 and ATL08 files atl03_path <- system.file("extdata", "atl03_clip.h5", package = "ICESat2VegR") atl08_path <- system.file("extdata", "atl08_clip.h5", package = "ICESat2VegR") # Reading ATL03 and ATL08 data (h5 files) atl03_h5 <- ATL03_read(atl03_path) atl08_h5 <- ATL08_read(atl08_path) # Joining ATL03 and ATL08 photon attributes atl03_atl08_dt <- ATL03_ATL08_photons_attributes_dt_join(atl03_h5, atl08_h5) head(atl03_atl08_dt) # Specifying the path to the shapefile clip_obj_filepath <- system.file("extdata", "clip_geom.shp", package = "ICESat2VegR") # Reading shapefile as a SpatVector object clip_obj <- terra::vect(clip_obj_filepath) # Clipping ATL08 terrain attributes by geometry atl03_atl08_dt_clip <- ATL03_ATL08_photons_attributes_dt_clipGeometry( atl03_atl08_dt, clip_obj, split_by = "id" ) head(atl03_atl08_dt_clip) close(atl03_h5) close(atl08_h5)
This function computes a series of user defined descriptive statistics within each given grid cell for ATL03 and ATL08 photon attributes
ATL03_ATL08_photons_attributes_dt_gridStat( atl03_atl08_dt, func, res = 0.5, ph_class = c(2, 3), beam = c("gt1l", "gt1r", "gt2l", "gt2r", "gt3l", "gt3r"), quality_ph = 0, night_flag = 1 )ATL03_ATL08_photons_attributes_dt_gridStat( atl03_atl08_dt, func, res = 0.5, ph_class = c(2, 3), beam = c("gt1l", "gt1r", "gt2l", "gt2r", "gt3l", "gt3r"), quality_ph = 0, night_flag = 1 )
atl03_atl08_dt |
An S4 object of class |
func |
The function to be applied for computing the defined statistics |
res |
Spatial resolution in decimal degrees for the output SpatRast raster layer. Default is 0.5. |
ph_class |
Character vector indicating photons to process based on the classification (1=ground, 2=canopy, 3=top canopy), Default is c(2,3) |
beam |
Character vector indicating beams to process. Default is c("gt1l", "gt1r", "gt2l", "gt2r", "gt3l", "gt3r") |
quality_ph |
Indicates the quality of the associated photon. 0=nominal, 1=possible_afterpulse, 2=possible_impulse_response_effect, 3=possible_tep. Default is 0 |
night_flag |
Flag indicating the data were acquired in night conditions: 0=day, 1=night. Default is 1 |
Return a SpatRast raster layer(s) of selected ATL03 and ATL08 photon attribute(s)
# ATL03 file path atl03_path <- system.file("extdata", "atl03_clip.h5", package = "ICESat2VegR" ) # ATL08 file path atl08_path <- system.file("extdata", "atl08_clip.h5", package = "ICESat2VegR" ) # Reading ATL03 data (h5 file) atl03_h5 <- ATL03_read(atl03_path = atl03_path) # Reading ATL08 data (h5 file) atl08_h5 <- ATL08_read(atl08_path = atl08_path) # # Extracting ATL03 and ATL08 photons and heights atl03_atl08_dt <- ATL03_ATL08_photons_attributes_dt_join(atl03_h5, atl08_h5) # Computing the mean of ph_h attribute at 0.0002 degree grid cell mean_ph_h <- ATL03_ATL08_photons_attributes_dt_gridStat(atl03_atl08_dt, func = mean(ph_h), res = 0.0002 ) plot(mean_ph_h) # Define your own function mySetOfMetrics <- function(x) { metrics <- list( min = min(x), # Min of x max = max(x), # Max of x mean = mean(x), # Mean of x sd = sd(x) # Sd of x ) return(metrics) } # Computing a series of ph_h stats at 0.0002 degree grid cell from customized function ph_h_metrics <- ATL03_ATL08_photons_attributes_dt_gridStat(atl03_atl08_dt, func = mySetOfMetrics(ph_h), res = 0.0002 ) plot(ph_h_metrics) close(atl03_h5) close(atl08_h5)# ATL03 file path atl03_path <- system.file("extdata", "atl03_clip.h5", package = "ICESat2VegR" ) # ATL08 file path atl08_path <- system.file("extdata", "atl08_clip.h5", package = "ICESat2VegR" ) # Reading ATL03 data (h5 file) atl03_h5 <- ATL03_read(atl03_path = atl03_path) # Reading ATL08 data (h5 file) atl08_h5 <- ATL08_read(atl08_path = atl08_path) # # Extracting ATL03 and ATL08 photons and heights atl03_atl08_dt <- ATL03_ATL08_photons_attributes_dt_join(atl03_h5, atl08_h5) # Computing the mean of ph_h attribute at 0.0002 degree grid cell mean_ph_h <- ATL03_ATL08_photons_attributes_dt_gridStat(atl03_atl08_dt, func = mean(ph_h), res = 0.0002 ) plot(mean_ph_h) # Define your own function mySetOfMetrics <- function(x) { metrics <- list( min = min(x), # Min of x max = max(x), # Max of x mean = mean(x), # Mean of x sd = sd(x) # Sd of x ) return(metrics) } # Computing a series of ph_h stats at 0.0002 degree grid cell from customized function ph_h_metrics <- ATL03_ATL08_photons_attributes_dt_gridStat(atl03_atl08_dt, func = mySetOfMetrics(ph_h), res = 0.0002 ) plot(ph_h_metrics) close(atl03_h5) close(atl08_h5)
This function joins ATL03 and ATL08 computed photons attributes
ATL03_ATL08_photons_attributes_dt_join( atl03_h5, atl08_h5, beam = c("gt1l", "gt1r", "gt2l", "gt2r", "gt3l", "gt3r") )ATL03_ATL08_photons_attributes_dt_join( atl03_h5, atl08_h5, beam = c("gt1l", "gt1r", "gt2l", "gt2r", "gt3l", "gt3r") )
atl03_h5 |
A ICESat-2 ATL03 object (output of |
atl08_h5 |
A ICESat-2 ATL08 object (output of |
beam |
Character vector indicating beams to process (e.g. "gt1l", "gt1r", "gt2l", "gt2r", "gt3l", "gt3r") |
These are the photons attributes extracted by default:
ph_segment_id: Georeferenced segment id (20-m) associated with each photon.
lon_ph: Longitude of each received photon. Computed from the ECEF Cartesian coordinates
of the bounce point.
lat_ph: Latitude of each received photon. Computed from the ECEF Cartesian coordinates
of the bounce point.
h_ph: Height of each received photon, relative to the WGS-84 ellipsoid including the
geophysical corrections noted in section 6.0. Please note that neither the geoid,
ocean tide nor the dynamic atmospheric corrections (DAC) are applied to the
ellipsoidal heights.
quality_ph: Indicates the quality of the associated photon. 0=nominal,
1=possible_afterpulse, 2=possible_impulse_response_effect, 3=possible_tep.
Use this flag in conjunction with signal_conf_ph to identify those photons
that are likely noise or likely signal.
solar_elevation: Elevation of the sun above the horizon at the photon bounce point.
dist_ph_along: Along-track distance of the photon from the beginning of the segment.
dist_ph_across: Across-track distance of the photon from the center of the segment.
night_flag: Flag indicating the data were acquired in night conditions: 0=day, 1=night.
Night flag is set when solar elevation is below 0.0 degrees.
classed_pc_indx: Indices of photons tracking back to ATL03 that surface finding software
identified and used within the creation of the data products.
classed_pc_flag: The L2B algorithm is run if this flag is set to 1 indicating data have
sufficient waveform fidelity for L2B to run.
ph_h: Height of photon above interpolated ground surface.
d_flag: Flag indicating whether DRAGANN labeled the photon as noise or signal.
delta_time: Mid-segment GPS time in seconds past an epoch. The epoch is provided in
the metadata at the file level.
orbit_number: Orbit number identifier to identify data from different orbits.
beam: Beam identifier.
strong_beam: Logical indicating if the beam is a strong beam.
Returns an S4 object of class icesat2.atl03atl08_dt
containing the ATL08 computed photons attributes.
https://icesat-2.gsfc.nasa.gov/sites/default/files/page_files/ICESat2_ATL08_ATBD_r006.pdf
# Specifying the path to ATL03 file atl03_path <- system.file("extdata", "atl03_clip.h5", package = "ICESat2VegR" ) # Specifying the path to ATL08 file atl08_path <- system.file("extdata", "atl08_clip.h5", package = "ICESat2VegR" ) # Reading ATL03 data (h5 file) atl03_h5 <- ATL03_read(atl03_path = atl03_path) # Reading ATL08 data (h5 file) atl08_h5 <- ATL08_read(atl08_path = atl08_path) # # Extracting ATL03 and ATL08 photons and heights atl03_atl08_dt <- ATL03_ATL08_photons_attributes_dt_join(atl03_h5, atl08_h5) head(atl03_atl08_dt) close(atl03_h5) close(atl08_h5)# Specifying the path to ATL03 file atl03_path <- system.file("extdata", "atl03_clip.h5", package = "ICESat2VegR" ) # Specifying the path to ATL08 file atl08_path <- system.file("extdata", "atl08_clip.h5", package = "ICESat2VegR" ) # Reading ATL03 data (h5 file) atl03_h5 <- ATL03_read(atl03_path = atl03_path) # Reading ATL08 data (h5 file) atl08_h5 <- ATL08_read(atl08_path = atl08_path) # # Extracting ATL03 and ATL08 photons and heights atl03_atl08_dt <- ATL03_ATL08_photons_attributes_dt_join(atl03_h5, atl08_h5) head(atl03_atl08_dt) close(atl03_h5) close(atl08_h5)
Converts ATL03/ATL08 classified photon cloud to LAS
ATL03_ATL08_photons_attributes_dt_LAS( atl03_atl08_dt, output, normalized = TRUE )ATL03_ATL08_photons_attributes_dt_LAS( atl03_atl08_dt, output, normalized = TRUE )
atl03_atl08_dt |
An S4 object of class |
output |
character. The output path of for the LAS(Z) file(s). The function will create one LAS file per UTM Zone in WGS84 datum. |
normalized |
logical, default TRUE. Whether the output should be normalized LAS or raw altitude. |
Nothing, it just saves outputs as LAS file in disk
outdir <- tempdir() # ATL03 file path atl03_path <- system.file("extdata", "atl03_clip.h5", package = "ICESat2VegR" ) # ATL08 file path atl08_path <- system.file("extdata", "atl08_clip.h5", package = "ICESat2VegR" ) # Reading ATL03 data (h5 file) atl03_h5 <- ATL03_read(atl03_path = atl03_path) # Reading ATL08 data (h5 file) atl08_h5 <- ATL08_read(atl08_path = atl08_path) # Extracting ATL03 and ATL08 photons and heights atl03_atl08_dt <- ATL03_ATL08_photons_attributes_dt_join(atl03_h5, atl08_h5) if (require("lidR")) { ATL03_ATL08_photons_attributes_dt_LAS( atl03_atl08_dt, output = file.path(outdir, "output.laz"), normalized = TRUE ) } close(atl03_h5) close(atl08_h5)outdir <- tempdir() # ATL03 file path atl03_path <- system.file("extdata", "atl03_clip.h5", package = "ICESat2VegR" ) # ATL08 file path atl08_path <- system.file("extdata", "atl08_clip.h5", package = "ICESat2VegR" ) # Reading ATL03 data (h5 file) atl03_h5 <- ATL03_read(atl03_path = atl03_path) # Reading ATL08 data (h5 file) atl08_h5 <- ATL08_read(atl08_path = atl08_path) # Extracting ATL03 and ATL08 photons and heights atl03_atl08_dt <- ATL03_ATL08_photons_attributes_dt_join(atl03_h5, atl08_h5) if (require("lidR")) { ATL03_ATL08_photons_attributes_dt_LAS( atl03_atl08_dt, output = file.path(outdir, "output.laz"), normalized = TRUE ) } close(atl03_h5) close(atl08_h5)
Computes a series of statistics ATL03 and ATL08 joined photons attributes within area defined by a polygon
ATL03_ATL08_photons_attributes_dt_polyStat( atl03_atl08_dt, func, poly_id = NULL )ATL03_ATL08_photons_attributes_dt_polyStat( atl03_atl08_dt, func, poly_id = NULL )
atl03_atl08_dt |
An S4 object of class |
func |
The function to be applied for computing the defined statistics |
poly_id |
Polygon id. If defined, statistics will be computed for each polygon |
Returns an S4 object of class icesat2.atl08_dt
Containing Statistics of ATL08 classified canopy photons
# Specifying the path to ATL03 and ATL08 files # ATL03 file path atl03_path <- system.file("extdata", "atl03_clip.h5", package = "ICESat2VegR" ) # ATL08 file path atl08_path <- system.file("extdata", "atl08_clip.h5", package = "ICESat2VegR" ) # Reading ATL03 data (h5 file) atl03_h5 <- ATL03_read(atl03_path = atl03_path) # Reading ATL08 data (h5 file) atl08_h5 <- ATL08_read(atl08_path = atl08_path) # Extracting ATL03 and ATL08 photons and heights atl03_atl08_dt <- ATL03_ATL08_photons_attributes_dt_join(atl03_h5, atl08_h5) head(atl03_atl08_dt) # Specifying the path to shapefile polygon_filepath <- system.file("extdata", "clip_geom.shp", package = "ICESat2VegR") # Reading shapefile as sf object polygon <- terra::vect(polygon_filepath) # Clipping ATL08 terrain attributes by Geometry atl03_atl08_dt_clip <- ATL03_ATL08_photons_attributes_dt_clipGeometry(atl03_atl08_dt, polygon, split_by = "id") # Computing the maximum ph_h by polygon id max_ph_h <- ATL03_ATL08_photons_attributes_dt_polyStat(atl03_atl08_dt_clip, func = max(ph_h), poly_id = "poly_id") head(max_ph_h) # Define your own function mySetOfMetrics <- function(x) { metrics <- list( min = min(x), # Min of x max = max(x), # Max of x mean = mean(x), # Mean of x sd = sd(x) # Sd of x ) return(metrics) } # Computing a series of ph_h statistics from customized function ph_h_metrics <- ATL03_ATL08_photons_attributes_dt_polyStat( atl03_atl08_dt_clip, func = mySetOfMetrics(ph_h), poly_id = "poly_id" ) head(ph_h_metrics) close(atl03_h5) close(atl08_h5)# Specifying the path to ATL03 and ATL08 files # ATL03 file path atl03_path <- system.file("extdata", "atl03_clip.h5", package = "ICESat2VegR" ) # ATL08 file path atl08_path <- system.file("extdata", "atl08_clip.h5", package = "ICESat2VegR" ) # Reading ATL03 data (h5 file) atl03_h5 <- ATL03_read(atl03_path = atl03_path) # Reading ATL08 data (h5 file) atl08_h5 <- ATL08_read(atl08_path = atl08_path) # Extracting ATL03 and ATL08 photons and heights atl03_atl08_dt <- ATL03_ATL08_photons_attributes_dt_join(atl03_h5, atl08_h5) head(atl03_atl08_dt) # Specifying the path to shapefile polygon_filepath <- system.file("extdata", "clip_geom.shp", package = "ICESat2VegR") # Reading shapefile as sf object polygon <- terra::vect(polygon_filepath) # Clipping ATL08 terrain attributes by Geometry atl03_atl08_dt_clip <- ATL03_ATL08_photons_attributes_dt_clipGeometry(atl03_atl08_dt, polygon, split_by = "id") # Computing the maximum ph_h by polygon id max_ph_h <- ATL03_ATL08_photons_attributes_dt_polyStat(atl03_atl08_dt_clip, func = max(ph_h), poly_id = "poly_id") head(max_ph_h) # Define your own function mySetOfMetrics <- function(x) { metrics <- list( min = min(x), # Min of x max = max(x), # Max of x mean = mean(x), # Mean of x sd = sd(x) # Sd of x ) return(metrics) } # Computing a series of ph_h statistics from customized function ph_h_metrics <- ATL03_ATL08_photons_attributes_dt_polyStat( atl03_atl08_dt_clip, func = mySetOfMetrics(ph_h), poly_id = "poly_id" ) head(ph_h_metrics) close(atl03_h5) close(atl08_h5)
Function to estimate ground elevation using smoothing and interpolation functions. Ground photons (classed_pc_flag == 1) are first aggregated within a smoothing window, then an interpolation function is applied to estimate the ground elevation at each photon location or at arbitrary distances along the track.
ATL03_ATL08_photons_seg_dt_fitground( atl03_atl08_seg_dt, smoothing_window = NA, smoothing_func = median, interpolation_func = NA, xout_parameter_name = "xout", ... )ATL03_ATL08_photons_seg_dt_fitground( atl03_atl08_seg_dt, smoothing_window = NA, smoothing_func = median, interpolation_func = NA, xout_parameter_name = "xout", ... )
atl03_atl08_seg_dt |
An S4 object of class
|
smoothing_window |
numeric. The smoothing window size in meters
for aggregating ground photons before interpolation.
Default is |
smoothing_func |
function. The aggregation function applied to
ground photon elevations within each smoothing window.
Default is |
interpolation_func |
function. The interpolation function used
to estimate ground elevation from the smoothed ground photons.
Default is |
xout_parameter_name |
character. The name of the parameter used
by |
... |
Optional additional parameters passed to
|
The function for calculating the ground will first pass a smoothing
window with smoothing_window size, applying the
smoothing_func to aggregate the ground photons
(classed_pc_flag == 1).
Then it will use an interpolation function between those aggregated photons to estimate a smooth ground surface.
The smoothing_func signature will depend on the function used.
It is assumed that the first two arguments are vectors of x
(independent variable) and y (the values to be aggregated).
The remaining arguments are passed through ....
The interpolation functions need a third parameter which is the
x vector to predict at. Functions from the stats base
package such as stats::approx() and stats::spline()
name this argument xout, so you can use:
ATL03_ATL08_photons_seg_dt_fitground( atl03_atl08_seg_dt, interpolation_func = approx, xout_parameter_name = "xout" )
to predict at every photon location along the track. Other functions
may name the prediction parameter differently — for example,
signal::pchip() uses xi instead of xout.
The pchip algorithm (as implemented in the
signal package) is the algorithm used by the ATL08 ATBD.
The smoothing_window can be left NA, which will use
the ATBD adaptive algorithm for calculating the window size:
,
where length is the number of photons within the segment.
This is not the same algorithm as used in ATL08 but is an adapted version that uses the ATL08 pre-classification.
When xout_parameter_name is not NA, returns a
named list with two numeric vectors:
Distance along track (dist_ph_along) for each
photon, in meters.
Interpolated ground elevation (h_ph) at each
photon location, in meters. Values are NA for photons
outside the smoothed ground range (controlled by the
rule argument of the interpolation function).
When xout_parameter_name = NA, returns the raw output of
interpolation_func directly — for example, a callable
function when interpolation_func = approxfun, which
can then be evaluated at arbitrary distances along the track.
# Specifying the path to ATL03 and ATL08 files atl03_path <- system.file("extdata", "atl03_clip.h5", package = "ICESat2VegR") atl08_path <- system.file("extdata", "atl08_clip.h5", package = "ICESat2VegR") # Reading ATL03 and ATL08 data (h5 files) atl03_h5 <- ATL03_read(atl03_path = atl03_path) atl08_h5 <- ATL08_read(atl08_path = atl08_path) # Extracting ATL03 and ATL08 photons and heights atl03_atl08_dt <- ATL03_ATL08_photons_attributes_dt_join(atl03_h5, atl08_h5) # Converting to seg_dt class (required input for fitground) atl03_atl08_seg_dt <- ATL03_ATL08_segment_create( atl03_atl08_dt, segment_length = 30 ) # Example 1: ATBD adaptive smoothing window + linear interpolation # at each photon location along the track. # Returns a list with $x (dist_ph_along) and $y (ground elevation in meters). # NAs appear at photon locations outside the smoothed ground range. ground_approx <- ATL03_ATL08_photons_seg_dt_fitground( atl03_atl08_seg_dt, interpolation_func = approx, xout_parameter_name = "xout" ) head(ground_approx$x) # photon distances along track (meters) head(ground_approx$y) # interpolated ground elevations (meters) # Example 2: Return an interpolation function (approxfun) for # querying ground elevation at arbitrary distances along the track. # xout_parameter_name = NA skips prediction at photon locations # and returns the interpolation function directly. ground_fun <- ATL03_ATL08_photons_seg_dt_fitground( atl03_atl08_seg_dt, interpolation_func = approxfun, xout_parameter_name = NA ) # Query ground elevation at custom distances along track (meters) ground_fun(c(100, 200, 300)) # Example 3: Fixed 5 m smoothing window using mean instead of median ground_mean <- ATL03_ATL08_photons_seg_dt_fitground( atl03_atl08_seg_dt, smoothing_window = 5, smoothing_func = mean, interpolation_func = approx, xout_parameter_name = "xout" ) head(ground_mean$y) close(atl03_h5) close(atl08_h5)# Specifying the path to ATL03 and ATL08 files atl03_path <- system.file("extdata", "atl03_clip.h5", package = "ICESat2VegR") atl08_path <- system.file("extdata", "atl08_clip.h5", package = "ICESat2VegR") # Reading ATL03 and ATL08 data (h5 files) atl03_h5 <- ATL03_read(atl03_path = atl03_path) atl08_h5 <- ATL08_read(atl08_path = atl08_path) # Extracting ATL03 and ATL08 photons and heights atl03_atl08_dt <- ATL03_ATL08_photons_attributes_dt_join(atl03_h5, atl08_h5) # Converting to seg_dt class (required input for fitground) atl03_atl08_seg_dt <- ATL03_ATL08_segment_create( atl03_atl08_dt, segment_length = 30 ) # Example 1: ATBD adaptive smoothing window + linear interpolation # at each photon location along the track. # Returns a list with $x (dist_ph_along) and $y (ground elevation in meters). # NAs appear at photon locations outside the smoothed ground range. ground_approx <- ATL03_ATL08_photons_seg_dt_fitground( atl03_atl08_seg_dt, interpolation_func = approx, xout_parameter_name = "xout" ) head(ground_approx$x) # photon distances along track (meters) head(ground_approx$y) # interpolated ground elevations (meters) # Example 2: Return an interpolation function (approxfun) for # querying ground elevation at arbitrary distances along the track. # xout_parameter_name = NA skips prediction at photon locations # and returns the interpolation function directly. ground_fun <- ATL03_ATL08_photons_seg_dt_fitground( atl03_atl08_seg_dt, interpolation_func = approxfun, xout_parameter_name = NA ) # Query ground elevation at custom distances along track (meters) ground_fun(c(100, 200, 300)) # Example 3: Fixed 5 m smoothing window using mean instead of median ground_mean <- ATL03_ATL08_photons_seg_dt_fitground( atl03_atl08_seg_dt, smoothing_window = 5, smoothing_func = mean, interpolation_func = approx, xout_parameter_name = "xout" ) head(ground_mean$y) close(atl03_h5) close(atl08_h5)
Normalizes ATL03 and ATL08 photon heights (ph_h) by subtracting
the estimated ground elevation at each photon location. Ground elevation
is estimated internally using ATL03_ATL08_photons_seg_dt_fitground.
The function updates the ph_h column in place and returns the
modified atl03_atl08_seg_dt object.
ATL03_ATL08_photons_seg_dt_height_normalize( atl03_atl08_seg_dt, smoothing_window = NA, smoothing_func = median, interpolation_func = NA, xout_parameter_name = "xout", ... )ATL03_ATL08_photons_seg_dt_height_normalize( atl03_atl08_seg_dt, smoothing_window = NA, smoothing_func = median, interpolation_func = NA, xout_parameter_name = "xout", ... )
atl03_atl08_seg_dt |
An S4 object of class
|
smoothing_window |
numeric. The smoothing window size in meters
for aggregating ground photons before interpolation.
Default is |
smoothing_func |
function. The aggregation function applied to
ground photon elevations within each smoothing window.
Default is |
interpolation_func |
function. The interpolation function used
to estimate ground elevation from the smoothed ground photons.
Default is |
xout_parameter_name |
character. The name of the parameter used
by |
... |
Additional parameters passed forward to
|
This function is a wrapper around
ATL03_ATL08_photons_seg_dt_fitground. It first estimates
the ground elevation at every photon location using the smoothing and
interpolation approach described in that function, then subtracts the
estimated ground elevation from the raw photon height (h_ph)
to produce height above ground level.
For full details on the smoothing window, smoothing function, and
interpolation function behaviour, see
ATL03_ATL08_photons_seg_dt_fitground.
Returns the input atl03_atl08_seg_dt object with the
ph_h column updated in place to contain height above
ground level (AGL) in meters, computed as h_ph - ground_elevation.
Values are NA for photons outside the interpolated ground range.
Note: as this function uses data.table assignment by reference,
the original input object is also modified.
# Specifying the path to ATL03 and ATL08 files atl03_path <- system.file("extdata", "atl03_clip.h5", package = "ICESat2VegR") atl08_path <- system.file("extdata", "atl08_clip.h5", package = "ICESat2VegR") # Reading ATL03 and ATL08 data (h5 files) atl03_h5 <- ATL03_read(atl03_path = atl03_path) atl08_h5 <- ATL08_read(atl08_path = atl08_path) # Extracting ATL03 and ATL08 photons and heights atl03_atl08_dt <- ATL03_ATL08_photons_attributes_dt_join(atl03_h5, atl08_h5) # Converting to seg_dt class (required input) atl03_atl08_seg_dt <- ATL03_ATL08_segment_create( atl03_atl08_dt, segment_length = 30 ) # Example 1: Normalize photon heights using default ATBD smoothing window atl03_atl08_seg_dt_norm <- ATL03_ATL08_photons_seg_dt_height_normalize( atl03_atl08_seg_dt, interpolation_func = approx, xout_parameter_name = "xout" ) head(atl03_atl08_seg_dt_norm) # Example 2: Fixed 5 m smoothing window using mean aggregation # Recreate seg_dt since ph_h was modified in place by the previous call atl03_atl08_seg_dt <- ATL03_ATL08_segment_create( atl03_atl08_dt, segment_length = 30 ) atl03_atl08_seg_dt_norm2 <- ATL03_ATL08_photons_seg_dt_height_normalize( atl03_atl08_seg_dt, smoothing_window = 5, smoothing_func = mean, interpolation_func = approx, xout_parameter_name = "xout" ) head(atl03_atl08_seg_dt_norm2) close(atl03_h5) close(atl08_h5)# Specifying the path to ATL03 and ATL08 files atl03_path <- system.file("extdata", "atl03_clip.h5", package = "ICESat2VegR") atl08_path <- system.file("extdata", "atl08_clip.h5", package = "ICESat2VegR") # Reading ATL03 and ATL08 data (h5 files) atl03_h5 <- ATL03_read(atl03_path = atl03_path) atl08_h5 <- ATL08_read(atl08_path = atl08_path) # Extracting ATL03 and ATL08 photons and heights atl03_atl08_dt <- ATL03_ATL08_photons_attributes_dt_join(atl03_h5, atl08_h5) # Converting to seg_dt class (required input) atl03_atl08_seg_dt <- ATL03_ATL08_segment_create( atl03_atl08_dt, segment_length = 30 ) # Example 1: Normalize photon heights using default ATBD smoothing window atl03_atl08_seg_dt_norm <- ATL03_ATL08_photons_seg_dt_height_normalize( atl03_atl08_seg_dt, interpolation_func = approx, xout_parameter_name = "xout" ) head(atl03_atl08_seg_dt_norm) # Example 2: Fixed 5 m smoothing window using mean aggregation # Recreate seg_dt since ph_h was modified in place by the previous call atl03_atl08_seg_dt <- ATL03_ATL08_segment_create( atl03_atl08_dt, segment_length = 30 ) atl03_atl08_seg_dt_norm2 <- ATL03_ATL08_photons_seg_dt_height_normalize( atl03_atl08_seg_dt, smoothing_window = 5, smoothing_func = mean, interpolation_func = approx, xout_parameter_name = "xout" ) head(atl03_atl08_seg_dt_norm2) close(atl03_h5) close(atl08_h5)
Clips an icesat2.atl08_dt object to a given spatial extent. Only
rows whose longitude and latitude fall inside the specified
bounding extent are retained. This is the bounding-box counterpart to
geometry-based clipping via
ATL03_ATL08_seg_attributes_dt_clipGeometry.
ATL03_ATL08_seg_attributes_dt_clipBox(atl03_atl08_dt, clip_obj)ATL03_ATL08_seg_attributes_dt_clipBox(atl03_atl08_dt, clip_obj)
atl03_atl08_dt |
An object of class
|
clip_obj |
Bounding extent used for clipping. Supported inputs:
|
The function:
Validates that the input has longitude and latitude
columns.
Converts clip_obj to numeric bounds xmin,
ymin, xmax, ymax.
Drops rows with missing coordinates.
Returns a subset of atl03_atl08_dt where
longitude and latitude fall inside the bounding box.
An object of the same class as atl03_atl08_dt, containing
only segments whose longitude and latitude fall inside
the bounding extent.
# Specifying the path to ATL08 file atl08_path <- system.file("extdata", "atl08_clip.h5", package = "ICESat2VegR" ) # Reading ATL08 data (h5 file) atl08_h5 <- ATL08_read(atl08_path = atl08_path) # Extracting ATL08 segment attributes atl08_seg_dt <- ATL08_seg_attributes_dt(atl08_h5) head(atl08_seg_dt) # Example 1: Clip using a numeric bounding box (xmin, ymin, xmax, ymax) bbox <- c(-106.571, 41.532, -106.570, 41.537) atl08_seg_clip <- ATL03_ATL08_seg_attributes_dt_clipBox( atl08_seg_dt, clip_obj = bbox ) head(atl08_seg_clip) nrow(atl08_seg_clip) # Example 2: Clip using a terra SpatExtent object library(terra) ext_obj <- terra::ext(bbox) atl08_seg_clip2 <- ATL03_ATL08_seg_attributes_dt_clipBox( atl08_seg_dt, clip_obj = ext_obj ) head(atl08_seg_clip2) nrow(atl08_seg_clip2) close(atl08_h5)# Specifying the path to ATL08 file atl08_path <- system.file("extdata", "atl08_clip.h5", package = "ICESat2VegR" ) # Reading ATL08 data (h5 file) atl08_h5 <- ATL08_read(atl08_path = atl08_path) # Extracting ATL08 segment attributes atl08_seg_dt <- ATL08_seg_attributes_dt(atl08_h5) head(atl08_seg_dt) # Example 1: Clip using a numeric bounding box (xmin, ymin, xmax, ymax) bbox <- c(-106.571, 41.532, -106.570, 41.537) atl08_seg_clip <- ATL03_ATL08_seg_attributes_dt_clipBox( atl08_seg_dt, clip_obj = bbox ) head(atl08_seg_clip) nrow(atl08_seg_clip) # Example 2: Clip using a terra SpatExtent object library(terra) ext_obj <- terra::ext(bbox) atl08_seg_clip2 <- ATL03_ATL08_seg_attributes_dt_clipBox( atl08_seg_dt, clip_obj = ext_obj ) head(atl08_seg_clip2) nrow(atl08_seg_clip2) close(atl08_h5)
Clips an icesat2.atl08_dt or icesat2.atl03_atl08_seg_dt
object to the features inside a polygon. Accepts terra::SpatVector
or sf/sfc polygons. Performs a fast bounding box pre-clip,
then a precise intersection in the polygon CRS.
ATL03_ATL08_seg_attributes_dt_clipGeometry( atl03_atl08_dt, clip_obj, split_by = NULL )ATL03_ATL08_seg_attributes_dt_clipGeometry( atl03_atl08_dt, clip_obj, split_by = NULL )
atl03_atl08_dt |
An object of class
|
clip_obj |
A polygon as |
split_by |
character. Optional name of a polygon attribute to copy
into the output as column |
The function performs clipping in two steps for efficiency:
A fast bounding box pre-clip using
ATL03_ATL08_seg_attributes_dt_clipBox to reduce
the number of points before the precise intersection.
A precise point-in-polygon intersection using
terra::intersect(), reprojecting the points to the
polygon CRS if needed.
An object of the same class as atl03_atl08_dt containing
only segments that fall inside the polygon. If split_by is
provided, an additional poly_id column is added identifying
which polygon feature each segment belongs to.
# Specifying the path to ATL08 file atl08_path <- system.file("extdata", "atl08_clip.h5", package = "ICESat2VegR" ) # Reading ATL08 data (h5 file) atl08_h5 <- ATL08_read(atl08_path = atl08_path) # Extracting ATL08 segment attributes atl08_seg_dt <- ATL08_seg_attributes_dt(atl08_h5) head(atl08_seg_dt) # Reading polygon from shapefile polygon_filepath <- system.file("extdata", "clip_geom.shp", package = "ICESat2VegR" ) polygon <- terra::vect(polygon_filepath) # Example 1: Clip by polygon geometry atl08_seg_clip_geom <- ATL03_ATL08_seg_attributes_dt_clipGeometry( atl08_seg_dt, clip_obj = polygon ) head(atl08_seg_clip_geom) nrow(atl08_seg_clip_geom) # Example 2: Clip by polygon geometry and add polygon id column atl08_seg_clip_geom2 <- ATL03_ATL08_seg_attributes_dt_clipGeometry( atl08_seg_dt, clip_obj = polygon, split_by = "id" ) head(atl08_seg_clip_geom2) nrow(atl08_seg_clip_geom2) close(atl08_h5)# Specifying the path to ATL08 file atl08_path <- system.file("extdata", "atl08_clip.h5", package = "ICESat2VegR" ) # Reading ATL08 data (h5 file) atl08_h5 <- ATL08_read(atl08_path = atl08_path) # Extracting ATL08 segment attributes atl08_seg_dt <- ATL08_seg_attributes_dt(atl08_h5) head(atl08_seg_dt) # Reading polygon from shapefile polygon_filepath <- system.file("extdata", "clip_geom.shp", package = "ICESat2VegR" ) polygon <- terra::vect(polygon_filepath) # Example 1: Clip by polygon geometry atl08_seg_clip_geom <- ATL03_ATL08_seg_attributes_dt_clipGeometry( atl08_seg_dt, clip_obj = polygon ) head(atl08_seg_clip_geom) nrow(atl08_seg_clip_geom) # Example 2: Clip by polygon geometry and add polygon id column atl08_seg_clip_geom2 <- ATL03_ATL08_seg_attributes_dt_clipGeometry( atl08_seg_dt, clip_obj = polygon, split_by = "id" ) head(atl08_seg_clip_geom2) nrow(atl08_seg_clip_geom2) close(atl08_h5)
Computes canopy cover metrics from ATL03 and ATL08 classified photons
within each segment. Cover is calculated using the ratio of ground
to vegetation photons, optionally weighted by a reflectance ratio.
The function adds three new columns (cover, n_g,
n_v) to the input object and returns it.
ATL03_ATL08_seg_cover_dt_compute(atl03_atl08_dt, reflectance_ratio = 1)ATL03_ATL08_seg_cover_dt_compute(atl03_atl08_dt, reflectance_ratio = 1)
atl03_atl08_dt |
An object of class
|
reflectance_ratio |
numeric. The reflectance ratio
|
Cover is calculated with the formula:
where is the number of ground photons
(classed_pc_flag == 1) and is the number of
vegetation photons (classed_pc_flag > 1) within each segment.
Returns the input object with three additional columns:
Numeric. Canopy cover fraction per segment (0-1).
Integer. Number of ground photons per segment
(classed_pc_flag == 1).
Integer. Number of vegetation photons per segment
(classed_pc_flag > 1).
https://icesat-2.gsfc.nasa.gov/sites/default/files/page_files/ICESat2_ATL08_ATBD_r006.pdf
# Specifying the path to ATL03 and ATL08 files atl03_path <- system.file("extdata", "atl03_clip.h5", package = "ICESat2VegR") atl08_path <- system.file("extdata", "atl08_clip.h5", package = "ICESat2VegR") # Reading ATL03 and ATL08 data (h5 files) atl03_h5 <- ATL03_read(atl03_path = atl03_path) atl08_h5 <- ATL08_read(atl08_path = atl08_path) # Extracting ATL03 and ATL08 photons and heights atl03_atl08_dt <- ATL03_ATL08_photons_attributes_dt_join(atl03_h5, atl08_h5) # Converting to seg_dt class (required input) atl03_atl08_seg_dt <- ATL03_ATL08_segment_create( atl03_atl08_dt, segment_length = 30 ) # Computing canopy cover metrics per segment cover <- ATL03_ATL08_seg_cover_dt_compute(atl03_atl08_seg_dt) head(cover[, c("segment_id", "cover", "n_g", "n_v")]) # Computing cover with a custom reflectance ratio (rho_v/rho_g = 1.5) cover2 <- ATL03_ATL08_seg_cover_dt_compute( atl03_atl08_seg_dt, reflectance_ratio = 1.5 ) head(cover2[, c("segment_id", "cover", "n_g", "n_v")]) close(atl03_h5) close(atl08_h5)# Specifying the path to ATL03 and ATL08 files atl03_path <- system.file("extdata", "atl03_clip.h5", package = "ICESat2VegR") atl08_path <- system.file("extdata", "atl08_clip.h5", package = "ICESat2VegR") # Reading ATL03 and ATL08 data (h5 files) atl03_h5 <- ATL03_read(atl03_path = atl03_path) atl08_h5 <- ATL08_read(atl08_path = atl08_path) # Extracting ATL03 and ATL08 photons and heights atl03_atl08_dt <- ATL03_ATL08_photons_attributes_dt_join(atl03_h5, atl08_h5) # Converting to seg_dt class (required input) atl03_atl08_seg_dt <- ATL03_ATL08_segment_create( atl03_atl08_dt, segment_length = 30 ) # Computing canopy cover metrics per segment cover <- ATL03_ATL08_seg_cover_dt_compute(atl03_atl08_seg_dt) head(cover[, c("segment_id", "cover", "n_g", "n_v")]) # Computing cover with a custom reflectance ratio (rho_v/rho_g = 1.5) cover2 <- ATL03_ATL08_seg_cover_dt_compute( atl03_atl08_seg_dt, reflectance_ratio = 1.5 ) head(cover2[, c("segment_id", "cover", "n_g", "n_v")]) close(atl03_h5) close(atl08_h5)
This function reads the ICESat-2 Land and Vegetation Along-Track Products (ATL08) as h5 file.
ATL03_ATL08_segment_create( atl03_atl08_dt, segment_length, centroid = "mean", output = NA, overwrite = FALSE )ATL03_ATL08_segment_create( atl03_atl08_dt, segment_length, centroid = "mean", output = NA, overwrite = FALSE )
atl03_atl08_dt |
|
segment_length |
|
centroid |
character. Method used to calculate the segment centroid, either "mean" or "midpoint", see details. Default 'mean'. |
output |
Character vector. The output vector file. The GDAL vector format
will be inferred by the file extension using |
overwrite |
logical input to control if the output vector file should be overwritten. Default FALSE. |
The centroid will be computed using either the photons centroid or the approximate segment centroid.
"mean": calculated using the average coordinates from all photons within the segment. This approach will better represent the mean statistics location.
"mid-point": the minimum and maximum coordinates will be averaged to calculate a midpoint within the segment. This will give a better representation of the segment true mid-point
Returns an S4 object of class icesat2.atl03atl08_dt containing ICESat-2 ATL08 data.
https://icesat-2.gsfc.nasa.gov/sites/default/files/page_files/ICESat2_ATL08_ATBD_r006.pdf
# Specifying the path to ICESat-2 ATL03 and ATL08 data atl03_path <- system.file("extdata", "atl03_clip.h5", package = "ICESat2VegR" ) atl08_path <- system.file("extdata", "atl08_clip.h5", package = "ICESat2VegR" ) # Reading ICESat-2 ATL08 data (h5 file) atl03_h5 <- ATL03_read(atl03_path = atl03_path) atl08_h5 <- ATL08_read(atl08_path = atl08_path) atl03_atl08_dt <- ATL03_ATL08_photons_attributes_dt_join(atl03_h5, atl08_h5) atl03_atl08_dt_seg <- ATL03_ATL08_segment_create(atl03_atl08_dt, segment_length = 30, centroid = "mean", output = NA, overwrite = FALSE ) head(atl03_atl08_dt_seg) close(atl03_h5) close(atl08_h5)# Specifying the path to ICESat-2 ATL03 and ATL08 data atl03_path <- system.file("extdata", "atl03_clip.h5", package = "ICESat2VegR" ) atl08_path <- system.file("extdata", "atl08_clip.h5", package = "ICESat2VegR" ) # Reading ICESat-2 ATL08 data (h5 file) atl03_h5 <- ATL03_read(atl03_path = atl03_path) atl08_h5 <- ATL08_read(atl08_path = atl08_path) atl03_atl08_dt <- ATL03_ATL08_photons_attributes_dt_join(atl03_h5, atl08_h5) atl03_atl08_dt_seg <- ATL03_ATL08_segment_create(atl03_atl08_dt, segment_length = 30, centroid = "mean", output = NA, overwrite = FALSE ) head(atl03_atl08_dt_seg) close(atl03_h5) close(atl08_h5)
Clips an ICESat-2 ATL03 HDF5 file to a specified spatial extent. Only geolocated photon and segment datasets within the ATL03 beam groups are clipped; all metadata, orbit information, and ancillary groups are preserved unchanged. This function provides bounding-box-based clipping, complementing geometry-based clipping workflows.
ATL03_h5_clipBox( atl03, output, clip_obj, beam = c("gt1r", "gt2r", "gt3r", "gt1l", "gt2l", "gt3l"), additional_groups = c("orbit_info") )ATL03_h5_clipBox( atl03, output, clip_obj, beam = c("gt1r", "gt2r", "gt3r", "gt1l", "gt2l", "gt3l"), additional_groups = c("orbit_info") )
atl03 |
An |
output |
Character. Path to the output HDF5 file that will store the clipped ATL03 dataset. |
clip_obj |
Bounding extent used for clipping. Supported inputs:
|
beam |
Character vector specifying which ATL03 beams to include.
Defaults to:
|
additional_groups |
Character vector of additional non-beam HDF5 groups
to copy unchanged into the output file. Defaults to:
|
The function performs spatial subsetting at the photon and segment level. Internally, it:
Copies file- and group-level attributes.
Extracts beam-level datasets and evaluates segment-level and photon-level masks using the supplied bounding box.
Applies these masks to all datasets whose dimensions correspond to segments or photons.
Recomputes dependent indexing datasets (e.g., ph_index_beg)
to maintain ATL03 structural integrity.
Writes the clipped data into a new, valid ATL03 HDF5 file.
This function preserves the full ATL03 metadata, ancillary information, and file structure while trimming the spatial domain to the user-specified bounding extent.
An S4 object of class icesat2.atl03_h5 representing
the clipped ATL03 HDF5 file saved at the output location.
# ATL03 file path atl03_path <- system.file("extdata", "atl03_clip.h5", package = "ICESat2VegR" ) # Read ATL03 data (HDF5) atl03_h5 <- ATL03_read(atl03_path) # Bounding rectangle coordinates (ul_lat, ul_lon, lr_lat, lr_lon) xmin <- -106.5723 xmax <- -106.5693 ymin <- 41.533 ymax <- 41.537 bbox <- c(ymax, xmin, ymin, xmax) # Clip ATL03 using the bounding extent output <- tempfile(fileext = ".h5") atl03_clip <- ATL03_h5_clipBox( atl03_h5, output = output, clip_obj = bbox ) close(atl03_h5)# ATL03 file path atl03_path <- system.file("extdata", "atl03_clip.h5", package = "ICESat2VegR" ) # Read ATL03 data (HDF5) atl03_h5 <- ATL03_read(atl03_path) # Bounding rectangle coordinates (ul_lat, ul_lon, lr_lat, lr_lon) xmin <- -106.5723 xmax <- -106.5693 ymin <- 41.533 ymax <- 41.537 bbox <- c(ymax, xmin, ymin, xmax) # Clip ATL03 using the bounding extent output <- tempfile(fileext = ".h5") atl03_clip <- ATL03_h5_clipBox( atl03_h5, output = output, clip_obj = bbox ) close(atl03_h5)
Clips an ICESat-2 ATL03 HDF5 file using one or more geometry-based clipping
objects provided as a terra::SpatVector. Each geometry in vect
defines an individual clipping region. The function iteratively clips the
ATL03 data for each region and writes a separate output HDF5 file for every
geometry. The name of each output file is automatically appended with the
value of the attribute specified in split_by.
Only datasets within the ATL03 beam groups are spatially clipped; metadata and ancillary non-beam groups remain unchanged in the resulting files.
ATL03_h5_clipGeometry( atl03, output, clip_obj, split_by = NULL, beam = c("gt1r", "gt2r", "gt3r", "gt1l", "gt2l", "gt3l"), additional_groups = c("orbit_info") )ATL03_h5_clipGeometry( atl03, output, clip_obj, split_by = NULL, beam = c("gt1r", "gt2r", "gt3r", "gt1l", "gt2l", "gt3l"), additional_groups = c("orbit_info") )
atl03 |
An |
output |
Character. Path to the output filename. The final written files
will append the unique value of |
clip_obj |
A |
split_by |
Character. The SpatVector attribute whose values are used to
identify and name each clipping geometry. Defaults to |
beam |
Character vector specifying which ATL03 beams to include. The
default includes all six beams:
|
additional_groups |
Character vector of non-beam HDF5 groups that should
be copied unchanged into each clipped file. Defaults to:
|
Returns a list of clipped S4 objects of class
icesat2.atl03_h5, one for each clipping geometry
contained in vect.
# ATL03 file path atl03_path <- system.file("extdata", "atl03_clip.h5", package = "ICESat2VegR" ) # Read ATL03 file atl03_h5 <- ATL03_read(atl03_path) # Output base filename output <- tempfile(fileext = ".h5") # Load clipping geometries vect_path <- system.file("extdata", "clip_geom.shp", package = "ICESat2VegR" ) vect <- terra::vect(vect_path) # Clip ATL03 data using polygon geometries atl03_clipped_list <- ATL03_h5_clipGeometry( atl03_h5, output, vect, split_by = "id" ) close(atl03_h5)# ATL03 file path atl03_path <- system.file("extdata", "atl03_clip.h5", package = "ICESat2VegR" ) # Read ATL03 file atl03_h5 <- ATL03_read(atl03_path) # Output base filename output <- tempfile(fileext = ".h5") # Load clipping geometries vect_path <- system.file("extdata", "clip_geom.shp", package = "ICESat2VegR" ) vect <- terra::vect(vect_path) # Clip ATL03 data using polygon geometries atl03_clipped_list <- ATL03_h5_clipGeometry( atl03_h5, output, vect, split_by = "id" ) close(atl03_h5)
Extract photon-level attributes from ICESat-2 ATL03 data.
ATL03_photons_attributes_dt( atl03_h5, beam = c("gt1l", "gt1r", "gt2l", "gt2r", "gt3l", "gt3r"), attributes = c("quality_ph", "dist_ph_along") )ATL03_photons_attributes_dt( atl03_h5, beam = c("gt1l", "gt1r", "gt2l", "gt2r", "gt3l", "gt3r"), attributes = c("quality_ph", "dist_ph_along") )
atl03_h5 |
An ICESat-2 ATL03 object (output of |
beam |
Character vector indicating beams to process (e.g. "gt1l", "gt1r", "gt2l", "gt2r", "gt3l", "gt3r"). |
attributes |
Character vector of additional photon-level attributes to extract.
See details below for available options. Default is
|
The returned data.table always includes the following columns:
beam: Beam ID (e.g., "gt2l").
strong_beam: Logical indicating whether the beam is classified as
strong for that orbit.
lon_ph: Longitude of each received photon, computed from ECEF
Cartesian coordinates of the bounce point (degrees_east).
lat_ph: Latitude of each received photon, computed from ECEF
Cartesian coordinates of the bounce point (degrees_north).
h_ph: Height of each received photon, relative to the WGS-84
ellipsoid, including the geophysical corrections described in the
ATL03 ATBD. (Geoid, ocean tide, and dynamic atmosphere corrections
are not applied.)
solar_elevation: Solar elevation interpolated from segment-level
geolocation/solar_elevation to photon level.
Additional photon-level attributes can be requested using the
attributes argument. These must correspond to names defined in
ATL03.photon.map. Available optional attributes currently include:
delta_time: Photon transmit time in seconds since
2018-01-01 (ATLAS SDP epoch).
dist_ph_across: Across-track distance of the photon projected
to the reference ellipsoid (meters).
pce_mframe_cnt: Major frame counter (part of photon ID).
ph_id_channel: Channel number assigned to the photon event.
ph_id_count: Photon event counter (part of photon ID).
ph_id_pulse: Laser pulse counter (part of photon ID).
quality_ph: Photon quality flag indicating nominal, saturation,
or noise conditions.
signal_class_ph: Experimental photon classification flag based
on photon weights.
signal_conf_ph: Signal confidence level per surface type
(5 x N array in original product).
weight_ph: Relative photon weight (0-65535), proportional to
photon density.
If a requested attribute is not present in a given beam, the
corresponding column is filled with NA.
An S4 object of class data.table::data.table (with class
icesat2.atl03_dt prepended) containing photon-level ATL03
attributes.
https://nsidc.org/sites/default/files/documents/technical-reference/icesat2_atl03_data_dict_v007.pdf
atl03_path <- system.file( "extdata", "atl03_clip.h5", package = "ICESat2VegR" ) atl03_h5 <- ATL03_read(atl03_path) atl03_photons_dt <- ATL03_photons_attributes_dt( atl03_h5, beam = c("gt1r"), attributes = c("quality_ph", "dist_ph_along", "ph_id_count") ) head(atl03_photons_dt) close(atl03_h5)atl03_path <- system.file( "extdata", "atl03_clip.h5", package = "ICESat2VegR" ) atl03_h5 <- ATL03_read(atl03_path) atl03_photons_dt <- ATL03_photons_attributes_dt( atl03_h5, beam = c("gt1r"), attributes = c("quality_ph", "dist_ph_along", "ph_id_count") ) head(atl03_photons_dt) close(atl03_h5)
Clips ATL03 photon attributes within a given bounding extent, defined by a
single clip_obj argument. The clipping extent can be provided as:
(i) a numeric bounding box, or
(ii) a spatial extent object.
ATL03_photons_attributes_dt_clipBox(atl03_photons_dt, clip_obj)ATL03_photons_attributes_dt_clipBox(atl03_photons_dt, clip_obj)
atl03_photons_dt |
An |
clip_obj |
Bounding extent used to perform the clipping. Supported inputs:
|
When clip_obj is a SpatExtent, the package terra must be
installed. If not found, the function stops with an informative message.
Returns a subset of the original icesat2.atl03_dt object containing
only photons within the bounding box.
https://icesat-2.gsfc.nasa.gov/sites/default/files/page_files/ICESat2_ATL03_ATBD_r006.pdf
atl03_path <- system.file("extdata", "atl03_clip.h5", package = "ICESat2VegR") atl03_h5 <- ATL03_read(atl03_path = atl03_path) atl03_photons_dt <- ATL03_photons_attributes_dt(atl03_h5 = atl03_h5) # 1) Using a numeric bbox: xmin ymin xmax ymax bbox <- c(-106.57, 41.53, -106.5698, 41.54) atl03_clip_bbox <- ATL03_photons_attributes_dt_clipBox( atl03_photons_dt = atl03_photons_dt, clip_obj = bbox ) # 2) Using a SpatExtent # library(terra) # ext <- terra::ext(-106.57, -106.5698, 41.53, 41.54) # atl03_clip_ext <- ATL03_photons_attributes_dt_clipBox( # atl03_photons_dt = atl03_photons_dt, # clip_obj = ext # ) close(atl03_h5)atl03_path <- system.file("extdata", "atl03_clip.h5", package = "ICESat2VegR") atl03_h5 <- ATL03_read(atl03_path = atl03_path) atl03_photons_dt <- ATL03_photons_attributes_dt(atl03_h5 = atl03_h5) # 1) Using a numeric bbox: xmin ymin xmax ymax bbox <- c(-106.57, 41.53, -106.5698, 41.54) atl03_clip_bbox <- ATL03_photons_attributes_dt_clipBox( atl03_photons_dt = atl03_photons_dt, clip_obj = bbox ) # 2) Using a SpatExtent # library(terra) # ext <- terra::ext(-106.57, -106.5698, 41.53, 41.54) # atl03_clip_ext <- ATL03_photons_attributes_dt_clipBox( # atl03_photons_dt = atl03_photons_dt, # clip_obj = ext # ) close(atl03_h5)
This function clips ATL03 photon attributes within given bounding coordinates.
ATL03_photons_attributes_dt_clipGeometry( atl03_photons_dt, clip_obj, split_by = "id" )ATL03_photons_attributes_dt_clipGeometry( atl03_photons_dt, clip_obj, split_by = "id" )
atl03_photons_dt |
An ATL03 photon data table. An S4 object of class |
clip_obj |
Spatial clip_obj. An object of class |
split_by |
clip_obj id. If defined, GEDI data will be clipped by each clip_obj using the clip_obj id from the attribute table defined by the user. |
Returns an S4 object of class icesat2.atl03_dt
containing the ATL03 photon attributes.
https://icesat-2.gsfc.nasa.gov/sites/default/files/page_files/ICESat2_ATL03_ATBD_r006.pdf
# ATL03 file path atl03_path <- system.file("extdata", "atl03_clip.h5", package = "ICESat2VegR" ) # Reading ATL03 data (h5 file) atl03_h5 <- ATL03_read(atl03_path = atl03_path) # Extracting ATL03 photon attributes atl03_photons_dt <- ATL03_photons_attributes_dt(atl03_h5 = atl03_h5) # Specifying the path to shapefile clip_obj_filepath <- system.file( "extdata", "clip_geom.shp", package = "ICESat2VegR" ) # Reading shapefile as sf object clip_obj <- terra::vect(clip_obj_filepath) # Clipping ATL03 photon attributes by Geometry atl03_photons_dt_clip <- ATL03_photons_attributes_dt_clipGeometry(atl03_photons_dt, clip_obj, split_by = "id") head(atl03_photons_dt_clip) close(atl03_h5)# ATL03 file path atl03_path <- system.file("extdata", "atl03_clip.h5", package = "ICESat2VegR" ) # Reading ATL03 data (h5 file) atl03_h5 <- ATL03_read(atl03_path = atl03_path) # Extracting ATL03 photon attributes atl03_photons_dt <- ATL03_photons_attributes_dt(atl03_h5 = atl03_h5) # Specifying the path to shapefile clip_obj_filepath <- system.file( "extdata", "clip_geom.shp", package = "ICESat2VegR" ) # Reading shapefile as sf object clip_obj <- terra::vect(clip_obj_filepath) # Clipping ATL03 photon attributes by Geometry atl03_photons_dt_clip <- ATL03_photons_attributes_dt_clipGeometry(atl03_photons_dt, clip_obj, split_by = "id") head(atl03_photons_dt_clip) close(atl03_h5)
Converts ATL03 photon cloud to LAS
ATL03_photons_attributes_dt_LAS(atl03_dt, output)ATL03_photons_attributes_dt_LAS(atl03_dt, output)
atl03_dt |
An S4 object of class |
output |
character. The output path of for the LAS(Z) file(s) The function will create one LAS file per UTM Zone in WGS84 datum. |
As the las format expects a metric coordinate reference system (CRS) we use helper functions to define UTM zones to which the original ICESat-2 data will be converted.
Writing LAS/LAZ files requires the lidR package; if it is not installed
the function stops with an informative message.
The function credits go to Chuck Gantz- [email protected].
Nothing, it just saves outputs as LAS file in disk
https://oceancolor.gsfc.nasa.gov/docs/ocssw/LatLong-UTMconversion_8cpp_source.html
# ATL03 file path atl03_path <- system.file("extdata", "atl03_clip.h5", package = "ICESat2VegR" ) # Reading ATL03 data (h5 file) atl03_h5 <- ATL03_read(atl03_path = atl03_path) # Extracting ATL03 photons and heights atl03_dt <- ATL03_photons_attributes_dt(atl03_h5, beam = "gt1r") # Writing to LAS/LAZ requires the 'lidR' package if (requireNamespace("lidR", quietly = TRUE)) { outdir <- tempdir() ATL03_photons_attributes_dt_LAS( atl03_dt, file.path(outdir, "output.laz") ) } close(atl03_h5)# ATL03 file path atl03_path <- system.file("extdata", "atl03_clip.h5", package = "ICESat2VegR" ) # Reading ATL03 data (h5 file) atl03_h5 <- ATL03_read(atl03_path = atl03_path) # Extracting ATL03 photons and heights atl03_dt <- ATL03_photons_attributes_dt(atl03_h5, beam = "gt1r") # Writing to LAS/LAZ requires the 'lidR' package if (requireNamespace("lidR", quietly = TRUE)) { outdir <- tempdir() ATL03_photons_attributes_dt_LAS( atl03_dt, file.path(outdir, "output.laz") ) } close(atl03_h5)
This function reads the ICESat-2 Global Geolocated Photons Product (ATL03) from an HDF5 (.h5) file.
ATL03_read(atl03_path)ATL03_read(atl03_path)
atl03_path |
Either a file path pointing to ICESat-2 ATL03 HDF5 data, or a granule
returned by |
An S4 object of class icesat2.atl03_dt containing ICESat-2
ATL03 data.
https://icesat-2.gsfc.nasa.gov/sites/default/files/page_files/ICESat2_ATL03_ATBD_r007.pdf
# Specify the path to an ATL03 file atl03_path <- system.file( "extdata", "atl03_clip.h5", package = "ICESat2VegR" ) # Read ICESat-2 ATL03 data (HDF5 file) ATL03 <- ATL03_read(atl03_path = atl03_path) close(ATL03)# Specify the path to an ATL03 file atl03_path <- system.file( "extdata", "atl03_clip.h5", package = "ICESat2VegR" ) # Read ICESat-2 ATL03 data (HDF5 file) ATL03 <- ATL03_read(atl03_path = atl03_path) close(ATL03)
Method for reading ICESat-2 ATL03 data from a local HDF5 (.h5) file.
## S4 method for signature 'character' ATL03_read(atl03_path)## S4 method for signature 'character' ATL03_read(atl03_path)
atl03_path |
A character string specifying the path to the ICESat-2 ATL03 HDF5 file. |
An S4 object of class icesat2.atl03_h5 containing ICESat-2 ATL03 data.
Method for reading ICESat-2 ATL03 data from a cloud-based granule.
## S4 method for signature 'icesat2.granule_cloud' ATL03_read(atl03_path)## S4 method for signature 'icesat2.granule_cloud' ATL03_read(atl03_path)
atl03_path |
An object of class |
An S4 object of class icesat2.atl03_h5 containing ICESat-2 ATL03 data.
Extract geolocation segment-level metadata from ICESat-2 ATL03 data. Each row in the output corresponds to a single 20m geolocation segment along track, not to individual photons.
In addition to variables from the ATL03 geolocation group, this
function derives a segment-level reference photon height (h_ph) using
the reference photon index and the photon-height array in the
heights group.
ATL03_seg_metadata_dt( atl03_h5, beam = c("gt1l", "gt1r", "gt2l", "gt2r", "gt3l", "gt3r"), attributes = c("h_ph", "altitude_sc", "bounce_time_offset", "delta_time", "full_sat_fract", "near_sat_fract", "neutat_delay_derivative", "neutat_delay_total", "neutat_ht", "ph_index_beg", "pitch", "podppd_flag", "range_bias_corr", "ref_azimuth", "ref_elev", "reference_photon_index", "roll", "segment_dist_x", "segment_id", "segment_length", "segment_ph_cnt", "sigma_across", "sigma_along", "sigma_h", "sigma_lat", "sigma_lon", "solar_azimuth", "solar_elevation", "surf_type", "tx_pulse_energy", "tx_pulse_skew_est", "tx_pulse_width_lower", "tx_pulse_width_upper", "yaw") )ATL03_seg_metadata_dt( atl03_h5, beam = c("gt1l", "gt1r", "gt2l", "gt2r", "gt3l", "gt3r"), attributes = c("h_ph", "altitude_sc", "bounce_time_offset", "delta_time", "full_sat_fract", "near_sat_fract", "neutat_delay_derivative", "neutat_delay_total", "neutat_ht", "ph_index_beg", "pitch", "podppd_flag", "range_bias_corr", "ref_azimuth", "ref_elev", "reference_photon_index", "roll", "segment_dist_x", "segment_id", "segment_length", "segment_ph_cnt", "sigma_across", "sigma_along", "sigma_h", "sigma_lat", "sigma_lon", "solar_azimuth", "solar_elevation", "surf_type", "tx_pulse_energy", "tx_pulse_skew_est", "tx_pulse_width_lower", "tx_pulse_width_upper", "yaw") )
atl03_h5 |
An ICESat-2 ATL03 object (output of |
beam |
Character vector indicating beams to process
(e.g. |
attributes |
Character vector naming the segment-level variables to extract.
By default, a broad set of geolocation and quality variables is used,
including a derived reference-photon height ( |
The following variables may be requested via 'attributes“:
h_ph: Height of the reference photon above the WGS84 ellipsoid
for each geolocation segment. This is derived from
geolocation/ph_index_beg, geolocation/reference_photon_index,
and heights/h_ph.
altitude_sc: Height of the spacecraft above the WGS84 ellipsoid.
beta_angle: Acute angle between Sun vector and orbit
plane
bounce_time_offset: Difference between the transmit time and the
ground-bounce time of the reference photon.
delta_time: Transmit time of the reference photon, measured in
seconds from 'atlas_sdp_gps_epoch“.
full_sat_fract: Fraction of pulses within the segment that are
fully saturated.
near_sat_fract: Fraction of pulses within the segment that are
nearly saturated.
neutat_delay_derivative: Change in neutral atmospheric delay per
unit height change.
neutat_delay_total: Total neutral atmosphere delay correction
(wet + dry).
neutat_ht: Reference height of the neutral atmosphere range
correction.
ph_index_beg: 1-based index of the first photon in this segment
within the photon-rate data.
pitch: Spacecraft pitch (degrees), 3-2-1 Euler sequence.
podppd_flag: Composite flag describing the quality of input
geolocation products for the segment.
range_bias_corr: Estimated range bias from geolocation analysis.
ref_azimuth: Azimuth (radians) of the unit pointing vector for the
reference photon in the local ENU frame.
ref_elev: Elevation (radians) of the unit pointing vector for the
reference photon in the local ENU frame.
reference_photon_index: Index of the reference photon within the
photon set for a segment.
reference_photon_lat: Latitude of the reference photon.
reference_photon_lon: Longitude of the reference photon.
roll: Spacecraft roll (degrees), 3-2-1 Euler sequence.
segment_dist_x: Along-track distance from the equator crossing to
the start of the 20 m geolocation segment.
segment_id: 7-digit along-track geolocation segment identifier.
segment_length: Along-track length of the geolocation segment
(typically 20 m).
segment_ph_cnt: Number of photons in the segment.
sigma_across: Estimated Cartesian across-track uncertainty
(1-sigma) for the reference photon.
sigma_along: Estimated Cartesian along-track uncertainty (1-sigma)
for the reference photon.
sigma_h: Estimated height uncertainty (1-sigma) for the reference
photon bounce point.
sigma_lat: Estimated geodetic latitude uncertainty (1-sigma) for
the reference photon.
sigma_lon: Estimated geodetic longitude uncertainty (1-sigma) for
the reference photon.
solar_azimuth: Azimuth (degrees east) of the sun position vector
from the reference photon bounce point in the local ENU frame.
solar_elevation: Elevation (degrees) of the sun position vector
from the reference photon bounce point in the local ENU frame.
surf_type: Flags describing which surface types the segment is
associated with (land, ocean, sea ice, land ice, inland water).
tx_pulse_energy: Average transmit pulse energy per beam.
tx_pulse_skew_est: Difference between the averages of the lower and
upper threshold crossing times, estimating transmit pulse skew.
tx_pulse_width_lower: Average distance between lower threshold
crossing times measured by the Start Pulse Detector.
tx_pulse_width_upper: Average distance between upper threshold
crossing times measured by the Start Pulse Detector.
velocity_sc: Spacecraft velocity components (east
component, north component, up component)
an observer on the ground would measure.
While values are common to all beams, this
parameter is naturally produced as part of
geolocation.
yaw: Spacecraft yaw (degrees), 3-2-1 Euler sequence.
A data.table::data.table with one row per ATL03 geolocation segment,
with class icesat2.atl03_seg_dt prepended. Columns include:
beam - beam ID (e.g., gt2l).
strong_beam - logical flag indicating whether the beam is
classified as strong for the orbit.
selected geolocation fields (see below).
a derived h_ph column: height of the reference photon
for each segment (one value per segment).
https://icesat-2.gsfc.nasa.gov/sites/default/files/page_files/ICESat2_ATL03_ATBD_r006.pdf
atl03_path <- system.file( "extdata", "atl03_clip.h5", package = "ICESat2VegR" ) atl03_h5 <- ATL03_read(atl03_path) # Extract ATL03 geolocation segment metadata atl03_segment_dt <- ATL03_seg_metadata_dt(atl03_h5) head(atl03_segment_dt) close(atl03_h5)atl03_path <- system.file( "extdata", "atl03_clip.h5", package = "ICESat2VegR" ) atl03_h5 <- ATL03_read(atl03_path) # Extract ATL03 geolocation segment metadata atl03_segment_dt <- ATL03_seg_metadata_dt(atl03_h5) head(atl03_segment_dt) close(atl03_h5)
Clips an ICESat-2 ATL08 HDF5 file to a specified spatial extent. Only segment-level datasets within the ATL08 beam groups are clipped; all metadata, orbit information, and ancillary groups are preserved unchanged. This function is the bounding-box-based counterpart to geometry-based clipping functions.
ATL08_h5_clipBox( atl08, output, clip_obj, beam = c("gt1r", "gt2r", "gt3r", "gt1l", "gt2l", "gt3l"), additional_groups = c("orbit_info") )ATL08_h5_clipBox( atl08, output, clip_obj, beam = c("gt1r", "gt2r", "gt3r", "gt1l", "gt2l", "gt3l"), additional_groups = c("orbit_info") )
atl08 |
An |
output |
Character path specifying where the clipped HDF5 file should be written. |
clip_obj |
Bounding extent used for clipping. Supported inputs:
|
beam |
Character vector specifying which ATL08 beams to include.
Defaults to:
|
additional_groups |
Character vector specifying additional non-beam
HDF5 groups to copy unchanged into the output file. Defaults to:
|
The function performs the following steps:
Copies file-level attributes and all requested non-beam groups.
Clips beam-level datasets based on latitude/longitude coordinates and the supplied spatial extent.
Reconstructs dependent indexing datasets (e.g., photon index ranges) when necessary to maintain valid ATL08 structure.
The resulting HDF5 file remains fully compliant with the ATL08 product structure, but contains only data within the specified bounding extent.
An S4 object of class icesat2.atl08_h5 representing
the clipped ATL08 HDF5 file.
# ATL08 file path atl08_path <- system.file("extdata", "atl08_clip.h5", package = "ICESat2VegR" ) # Read ATL08 data atl08_h5 <- ATL08_read(atl08_path) # Bounding rectangle coordinates (ul_lat, ul_lon, lr_lat, lr_lon) ul_lon <- -106.5723 lr_lon <- -106.5693 lr_lat <- 41.533 ul_lat <- 41.537 # Clip ATL08 data using the bounding extent atl08_clip <- ATL08_h5_clipBox( atl08_h5, output = tempfile(fileext = ".h5"), clip_obj = c(ul_lat, ul_lon, lr_lat, lr_lon) ) close(atl08_h5) close(atl08_clip)# ATL08 file path atl08_path <- system.file("extdata", "atl08_clip.h5", package = "ICESat2VegR" ) # Read ATL08 data atl08_h5 <- ATL08_read(atl08_path) # Bounding rectangle coordinates (ul_lat, ul_lon, lr_lat, lr_lon) ul_lon <- -106.5723 lr_lon <- -106.5693 lr_lat <- 41.533 ul_lat <- 41.537 # Clip ATL08 data using the bounding extent atl08_clip <- ATL08_h5_clipBox( atl08_h5, output = tempfile(fileext = ".h5"), clip_obj = c(ul_lat, ul_lon, lr_lat, lr_lon) ) close(atl08_h5) close(atl08_clip)
This function clips ATL08 HDF5 file within beam groups, but keeps metada and ancillary data the same.
ATL08_h5_clipGeometry( atl08, output, clip_obj, split_by = "id", beam = c("gt1r", "gt2r", "gt3r", "gt1l", "gt2l", "gt3l"), additional_groups = c("orbit_info") )ATL08_h5_clipGeometry( atl08, output, clip_obj, split_by = "id", beam = c("gt1r", "gt2r", "gt3r", "gt1l", "gt2l", "gt3l"), additional_groups = c("orbit_info") )
atl08 |
|
output |
character. Path to the output h5 file. |
clip_obj |
|
split_by |
|
beam |
|
additional_groups |
|
Returns a list of clipped S4 object of class icesat2.atl08_h5
# ATL08 file path atl08_path <- system.file("extdata", "atl08_clip.h5", package = "ICESat2VegR" ) # Reading ATL08 data (h5 file) atl08_h5 <- ATL08_read(atl08_path = atl08_path) output <- tempfile(fileext = ".h5") vect_path <- system.file("extdata", "clip_geom.shp", package = "ICESat2VegR" ) vect <- terra::vect(vect_path) # Clipping ATL08 photons by boundary box extent atl08_photons_dt_clip <- ATL08_h5_clipGeometry( atl08_h5, output, vect, split_by = "id" ) close(atl08_h5)# ATL08 file path atl08_path <- system.file("extdata", "atl08_clip.h5", package = "ICESat2VegR" ) # Reading ATL08 data (h5 file) atl08_h5 <- ATL08_read(atl08_path = atl08_path) output <- tempfile(fileext = ".h5") vect_path <- system.file("extdata", "clip_geom.shp", package = "ICESat2VegR" ) vect <- terra::vect(vect_path) # Clipping ATL08 photons by boundary box extent atl08_photons_dt_clip <- ATL08_h5_clipGeometry( atl08_h5, output, vect, split_by = "id" ) close(atl08_h5)
This function extracts computed photons attributes from ICESat-2 ATL08 data
ATL08_photons_attributes_dt( atl08_h5, beam = c("gt1l", "gt1r", "gt2l", "gt2r", "gt3l", "gt3r"), photon_attributes = c("ph_segment_id", "classed_pc_indx", "classed_pc_flag", "ph_h", "d_flag", "delta_time") )ATL08_photons_attributes_dt( atl08_h5, beam = c("gt1l", "gt1r", "gt2l", "gt2r", "gt3l", "gt3r"), photon_attributes = c("ph_segment_id", "classed_pc_indx", "classed_pc_flag", "ph_h", "d_flag", "delta_time") )
atl08_h5 |
A ICESat-2 ATL08 object (output of |
beam |
Character vector indicating beams to process (e.g. "gt1l", "gt1r", "gt2l", "gt2r", "gt3l", "gt3r") |
photon_attributes |
character vector indicating the attributes to extract from the ATL08 photons.
Default all |
These are the photons attributes extracted by default:
ph_segment_id: Georeferenced bin number (20-m) associated with each photon
classed_pc_indx: Indices of photons tracking back to ATL03 that surface finding software identified and used within the creation of the data products.
classed_pc_flag: The L2B algorithm is run if this flag is set to 1 indicating data have sufficient waveform fidelity for L2B to run
ph_h: Height of photon above interpolated ground surface
d_flag: Flag indicating whether DRAGANN labeled the photon as noise or signal
delta_time: Mid-segment GPS time in seconds past an epoch. The epoch is provided in the metadata at the file level
Returns an S4 object of class data.table::data.table containing the ATL08 computed photons attributes.
https://icesat-2.gsfc.nasa.gov/sites/default/files/page_files/ICESat2_ATL08_ATBD_r006.pdf
# Specifying the path to ATL08 file atl08_path <- system.file("extdata", "atl08_clip.h5", package = "ICESat2VegR" ) # Reading ATL08 data (h5 file) atl08_h5 <- ATL08_read(atl08_path) # Extracting ATL08 classified photons and heights atl08_photons <- ATL08_photons_attributes_dt(atl08_h5 = atl08_h5) head(atl08_photons) close(atl08_h5)# Specifying the path to ATL08 file atl08_path <- system.file("extdata", "atl08_clip.h5", package = "ICESat2VegR" ) # Reading ATL08 data (h5 file) atl08_h5 <- ATL08_read(atl08_path) # Extracting ATL08 classified photons and heights atl08_photons <- ATL08_photons_attributes_dt(atl08_h5 = atl08_h5) head(atl08_photons) close(atl08_h5)
This function reads the ICESat-2 Land and Vegetation Along-Track Products (ATL08) as h5 file.
ATL08_photons_attributes_dt_LAS(atl08_path)ATL08_photons_attributes_dt_LAS(atl08_path)
atl08_path |
File path pointing to ICESat-2 ATL08 data. Data in HDF5 Hierarchical Data Format (.h5). |
Returns an S4 object of class icesat2.atl08_dt containing ICESat-2 ATL08 data.
https://icesat-2.gsfc.nasa.gov/sites/default/files/page_files/ICESat2_ATL08_ATBD_r006.pdf
# ATL08 file path atl08_path <- system.file("extdata", "atl08_clip.h5", package = "ICESat2VegR" ) # Reading ICESat-2 ATL08 data (h5 file) atl08 <- ATL08_read(atl08_path = atl08_path) close(atl08)# ATL08 file path atl08_path <- system.file("extdata", "atl08_clip.h5", package = "ICESat2VegR" ) # Reading ICESat-2 ATL08 data (h5 file) atl08 <- ATL08_read(atl08_path = atl08_path) close(atl08)
Read the ICESat-2 Land and Vegetation Along-Track Product (ATL08) from an HDF5 (.h5) file.
ATL08_read(atl08_path)ATL08_read(atl08_path)
atl08_path |
File path to an ICESat-2 ATL08 dataset in HDF5 format (.h5). |
An S4 object of class icesat2.atl08_h5 containing ICESat-2
ATL08 data.
https://icesat-2.gsfc.nasa.gov/sites/default/files/page_files/ICESat2_ATL08_ATBD_r007.pdf
# Specify the path to an example ATL08 file atl08_path <- system.file( "extdata", "atl08_clip.h5", package = "ICESat2VegR" ) # Read ICESat-2 ATL08 data (HDF5 file) atl08 <- ATL08_read(atl08_path = atl08_path) close(atl08)# Specify the path to an example ATL08 file atl08_path <- system.file( "extdata", "atl08_clip.h5", package = "ICESat2VegR" ) # Read ICESat-2 ATL08 data (HDF5 file) atl08 <- ATL08_read(atl08_path = atl08_path) close(atl08)
Read the ICESat-2 Land and Vegetation Along-Track Product (ATL08) from a local HDF5 (.h5) file.
## S4 method for signature 'character' ATL08_read(atl08_path)## S4 method for signature 'character' ATL08_read(atl08_path)
atl08_path |
Character. File path to ICESat-2 ATL08 data in HDF5 format (.h5). |
An S4 object of class icesat2.atl08_h5 containing ICESat-2
ATL08 data.
# Specify the path to an example ATL08 file atl08_path <- system.file( "extdata", "atl08_clip.h5", package = "ICESat2VegR" ) # Read ICESat-2 ATL08 data (HDF5 file) atl08 <- ATL08_read(atl08_path = atl08_path) close(atl08)# Specify the path to an example ATL08 file atl08_path <- system.file( "extdata", "atl08_clip.h5", package = "ICESat2VegR" ) # Read ICESat-2 ATL08 data (HDF5 file) atl08 <- ATL08_read(atl08_path = atl08_path) close(atl08)
Read the ICESat-2 Land and Vegetation Along-Track Product (ATL08) from a single granule accessible in the cloud.
## S4 method for signature 'icesat2.granule_cloud' ATL08_read(atl08_path)## S4 method for signature 'icesat2.granule_cloud' ATL08_read(atl08_path)
atl08_path |
Object of class |
An S4 object of class icesat2.atl08_h5 containing ICESat-2
ATL08 data.
This method stops execution when multiple granules are provided, because the package currently supports only one granule at a time.
## S4 method for signature 'icesat2.granules_cloud' ATL08_read(atl08_path)## S4 method for signature 'icesat2.granules_cloud' ATL08_read(atl08_path)
atl08_path |
Object of class |
This method always stops with an error indicating that only one granule at a time is supported.
This function extracts terrain and canopy attributes by segments from ICESat-2 ATL08 data
ATL08_seg_attributes_dt( atl08_h5, beam = c("gt1l", "gt1r", "gt2l", "gt2r", "gt3l", "gt3r"), attributes = c("delta_time", "h_canopy", "canopy_openness", "h_te_mean", "terrain_slope") )ATL08_seg_attributes_dt( atl08_h5, beam = c("gt1l", "gt1r", "gt2l", "gt2r", "gt3l", "gt3r"), attributes = c("delta_time", "h_canopy", "canopy_openness", "h_te_mean", "terrain_slope") )
atl08_h5 |
A ICESat-2 ATL08 object (output of |
beam |
Character vector indicating beams to process (e.g. "gt1l", "gt1r", "gt2l", "gt2r", "gt3l", "gt3r") |
attributes |
A character vector containing the list of terrain and canopy attributes to be extracted. Default is attribute = c("h_canopy","canopy_h_metrics","canopy_openness","h_te_mean","h_te_median","terrain_slope") |
segment_id_beg
segment_id_end
delta_time
delta_time_beg
delta_time_end
latitude_20m
longitude_20m
rgt
n_seg_ph
ph_ndx_beg
segment_landcover
segment_snowcover
segment_watermask
surf_type
urban_flag
night_flag
permafrost_alt
permafrost_prob
cloud_flag_atm
cloud_fold_flag
column_od_asr
brightness_flag
layer_flag
msw_flag
psf_flag
sat_flag
asr
atlas_pa
beam_azimuth
beam_coelev
solar_azimuth
solar_elevation
snr
dem_flag
dem_removal_flag
dem_h
h_dif_ref
last_seg_extend
sigma_h
sigma_along
sigma_across
sigma_topo
sigma_atlas_land
can_noise
can_quality_score
canopy_h_metrics_abs
canopy_openness
h_canopy
canopy_rh_conf
h_median_canopy_abs
h_min_canopy
h_mean_canopy_abs
h_median_canopy
h_canopy_abs
toc_roughness
h_min_canopy_abs
h_dif_canopy
h_canopy_quad
h_canopy_20m
n_ca_photons
photon_rate_can
'photon_rate_can_nr“
centroid_height
canopy_h_metrics_abs
h_mean_canopy
subset_can_flag
canopy_h_metrics
n_toc_photons
h_max_canopy_abs
h_canopy_uncertainty
canopy_openness
h_max_canopy
segment_cover
h_te_best_fit
h_te_best_fit_20m
h_te_interp
h_te_max
h_te_mean
h_te_median
h_te_mode
h_te_rh25
h_te_skew
h_te_std
h_te_uncertainty
n_te_photons
photon_rate_te
subset_te_flag
terrain_slope
te_quality
Returns an S4 object of class icesat2.atl08_dt
containing the ATL08-derived terrain and canopy attributes by segments.
https://nsidc.org/sites/default/files/documents/technical-reference/icesat2_atl08_atbd_v007.pdf
# Specifying the path to ATL08 file atl08_path <- system.file("extdata", "atl08_clip.h5", package = "ICESat2VegR" ) # Reading ATL08 data (h5 file) atl08_h5 <- ATL08_read(atl08_path = atl08_path) # Extracting ATL08-derived terrain and canopy attributes atl08_seg_att_dt <- ATL08_seg_attributes_dt(atl08_h5 = atl08_h5) head(atl08_seg_att_dt) close(atl08_h5)# Specifying the path to ATL08 file atl08_path <- system.file("extdata", "atl08_clip.h5", package = "ICESat2VegR" ) # Reading ATL08 data (h5 file) atl08_h5 <- ATL08_read(atl08_path = atl08_path) # Extracting ATL08-derived terrain and canopy attributes atl08_seg_att_dt <- ATL08_seg_attributes_dt(atl08_h5 = atl08_h5) head(atl08_seg_att_dt) close(atl08_h5)
Clips ATL08 terrain and canopy segment attributes within a given bounding
extent, defined by a single clip_obj argument. The clipping extent can
be provided as:
(i) a numeric bounding box, or
(ii) a spatial extent object.
ATL08_seg_attributes_dt_clipBox(atl08_seg_att_dt, clip_obj)ATL08_seg_attributes_dt_clipBox(atl08_seg_att_dt, clip_obj)
atl08_seg_att_dt |
An |
clip_obj |
Bounding extent used to perform the clipping. Supported inputs:
|
When clip_obj is a SpatExtent, the package terra must be
installed. If not found, the function stops with an informative message.
Returns an S4 object of class
icesat2.atl08_dt
containing the clipped ATL08 terrain and canopy attributes.
# Specifying the path to the ATL08 file atl08_path <- system.file("extdata", "atl08_clip.h5", package = "ICESat2VegR" ) # Reading ATL08 data (h5 file) atl08_h5 <- ATL08_read(atl08_path) # Extracting ATL08-derived segment attributes atl08_seg_att_dt <- ATL08_seg_attributes_dt(atl08_h5 = atl08_h5) # 1) Using a numeric bounding box: xmin ymin xmax ymax bbox <- c(-103.7604, 59.4672, -103.7600, 59.4680) atl08_seg_att_dt_clip <- ATL08_seg_attributes_dt_clipBox( atl08_seg_att_dt = atl08_seg_att_dt, clip_obj = bbox ) # 2) Using a SpatExtent # library(terra) # ext <- terra::ext(-103.7604, -103.7600, 59.4672, 59.4680) # atl08_seg_att_dt_clip_ext <- ATL08_seg_attributes_dt_clipBox( # atl08_seg_att_dt = atl08_seg_att_dt, # clip_obj = ext # ) close(atl08_h5)# Specifying the path to the ATL08 file atl08_path <- system.file("extdata", "atl08_clip.h5", package = "ICESat2VegR" ) # Reading ATL08 data (h5 file) atl08_h5 <- ATL08_read(atl08_path) # Extracting ATL08-derived segment attributes atl08_seg_att_dt <- ATL08_seg_attributes_dt(atl08_h5 = atl08_h5) # 1) Using a numeric bounding box: xmin ymin xmax ymax bbox <- c(-103.7604, 59.4672, -103.7600, 59.4680) atl08_seg_att_dt_clip <- ATL08_seg_attributes_dt_clipBox( atl08_seg_att_dt = atl08_seg_att_dt, clip_obj = bbox ) # 2) Using a SpatExtent # library(terra) # ext <- terra::ext(-103.7604, -103.7600, 59.4672, 59.4680) # atl08_seg_att_dt_clip_ext <- ATL08_seg_attributes_dt_clipBox( # atl08_seg_att_dt = atl08_seg_att_dt, # clip_obj = ext # ) close(atl08_h5)
This function clips ATL08 Terrain and Canopy Attributes within a given geometry
ATL08_seg_attributes_dt_clipGeometry( atl08_seg_att_dt, clip_obj, split_by = NULL )ATL08_seg_attributes_dt_clipGeometry( atl08_seg_att_dt, clip_obj, split_by = NULL )
atl08_seg_att_dt |
A atl08_seg_att_dt object (output of
|
clip_obj |
clip_obj. An object of class |
split_by |
clip_obj id. If defined, ATL08 data will be clipped by each clip_obj using the clip_obj id from table of attribute defined by the user |
Returns an S4 object of class icesat2.atl08_dt
containing the clipped ATL08 Terrain and Canopy Attributes.
# Specifying the path to ATL08 file atl08_path <- system.file("extdata", "atl08_clip.h5", package = "ICESat2VegR" ) # Reading ATL08 data (h5 file) atl08_h5 <- ATL08_read(atl08_path = atl08_path) # Extracting ATL08-derived terrain and canopy attributes atl08_seg_att_dt <- ATL08_seg_attributes_dt(atl08_h5 = atl08_h5) clip_obj_path <- system.file("extdata", "clip_geom.shp", package = "ICESat2VegR" ) if (require(terra)) { polygon <- terra::vect(clip_obj_path) head(atl08_seg_att_dt) # Clipping ATL08 Terrain and Canopy Attributes by Geometry atl08_seg_att_dt_clip <- ATL08_seg_attributes_dt_clipGeometry( atl08_seg_att_dt, polygon, split_by = "id" ) hasLeaflet <- require(leaflet) if (hasLeaflet) { leaflet() %>% addCircleMarkers(atl08_seg_att_dt_clip$longitude, atl08_seg_att_dt_clip$latitude, radius = 1, opacity = 1, color = "red" ) %>% addScaleBar(options = list(imperial = FALSE)) %>% addPolygons( data = polygon, weight = 1, col = "white", opacity = 1, fillOpacity = 0 ) %>% addProviderTiles(providers$Esri.WorldImagery, options = providerTileOptions(minZoom = 3, maxZoom = 17) ) } } close(atl08_h5)# Specifying the path to ATL08 file atl08_path <- system.file("extdata", "atl08_clip.h5", package = "ICESat2VegR" ) # Reading ATL08 data (h5 file) atl08_h5 <- ATL08_read(atl08_path = atl08_path) # Extracting ATL08-derived terrain and canopy attributes atl08_seg_att_dt <- ATL08_seg_attributes_dt(atl08_h5 = atl08_h5) clip_obj_path <- system.file("extdata", "clip_geom.shp", package = "ICESat2VegR" ) if (require(terra)) { polygon <- terra::vect(clip_obj_path) head(atl08_seg_att_dt) # Clipping ATL08 Terrain and Canopy Attributes by Geometry atl08_seg_att_dt_clip <- ATL08_seg_attributes_dt_clipGeometry( atl08_seg_att_dt, polygon, split_by = "id" ) hasLeaflet <- require(leaflet) if (hasLeaflet) { leaflet() %>% addCircleMarkers(atl08_seg_att_dt_clip$longitude, atl08_seg_att_dt_clip$latitude, radius = 1, opacity = 1, color = "red" ) %>% addScaleBar(options = list(imperial = FALSE)) %>% addPolygons( data = polygon, weight = 1, col = "white", opacity = 1, fillOpacity = 0 ) %>% addProviderTiles(providers$Esri.WorldImagery, options = providerTileOptions(minZoom = 3, maxZoom = 17) ) } } close(atl08_h5)
Computes a series of user-defined descriptive statistics within each grid cell for ATL08 terrain and canopy attributes.
ATL08_seg_attributes_dt_gridStat(atl08_seg_att_dt, func, res = 0.5)ATL08_seg_attributes_dt_gridStat(atl08_seg_att_dt, func, res = 0.5)
atl08_seg_att_dt |
An object of class
|
func |
The function to be applied for computing the defined
statistics. Can be a single function (e.g. |
res |
numeric. Spatial resolution in decimal degrees for the
output |
Returns a SpatRaster object containing one layer per
computed statistic of the selected ATL08 terrain and canopy
attribute(s).
# Specifying the path to ATL08 file atl08_path <- system.file("extdata", "atl08_clip.h5", package = "ICESat2VegR" ) # Reading ATL08 data (h5 file) atl08_h5 <- ATL08_read(atl08_path = atl08_path) # Extracting ATL08-derived terrain and canopy attributes atl08_seg_att_dt <- ATL08_seg_attributes_dt(atl08_h5 = atl08_h5) # Computing mean h_canopy at 0.0001 degree grid cell library(terra) mean_h_canopy <- ATL08_seg_attributes_dt_gridStat( atl08_seg_att_dt, func = mean(h_canopy), res = 0.0001 ) terra::plot(mean_h_canopy) # Define a custom set of metrics mySetOfMetrics <- function(x) { metrics <- list( min = min(x, na.rm = TRUE), max = max(x, na.rm = TRUE), mean = mean(x, na.rm = TRUE), sd = sd(x, na.rm = TRUE) ) return(metrics) } # Computing h_canopy statistics at 0.05 degree grid cell h_canopy_metrics <- ATL08_seg_attributes_dt_gridStat( atl08_seg_att_dt, func = mySetOfMetrics(h_canopy), res = 0.05 ) terra::plot(h_canopy_metrics) close(atl08_h5)# Specifying the path to ATL08 file atl08_path <- system.file("extdata", "atl08_clip.h5", package = "ICESat2VegR" ) # Reading ATL08 data (h5 file) atl08_h5 <- ATL08_read(atl08_path = atl08_path) # Extracting ATL08-derived terrain and canopy attributes atl08_seg_att_dt <- ATL08_seg_attributes_dt(atl08_h5 = atl08_h5) # Computing mean h_canopy at 0.0001 degree grid cell library(terra) mean_h_canopy <- ATL08_seg_attributes_dt_gridStat( atl08_seg_att_dt, func = mean(h_canopy), res = 0.0001 ) terra::plot(mean_h_canopy) # Define a custom set of metrics mySetOfMetrics <- function(x) { metrics <- list( min = min(x, na.rm = TRUE), max = max(x, na.rm = TRUE), mean = mean(x, na.rm = TRUE), sd = sd(x, na.rm = TRUE) ) return(metrics) } # Computing h_canopy statistics at 0.05 degree grid cell h_canopy_metrics <- ATL08_seg_attributes_dt_gridStat( atl08_seg_att_dt, func = mySetOfMetrics(h_canopy), res = 0.05 ) terra::plot(h_canopy_metrics) close(atl08_h5)
Converts ATL08 segments to LAS
ATL08_seg_attributes_dt_LAS(atl08_dt, output)ATL08_seg_attributes_dt_LAS(atl08_dt, output)
atl08_dt |
An S4 object of class |
output |
character. The output path of for the LAS(Z) file(s) The function will create one LAS file per UTM Zone in WGS84 datum. |
As the las format expects a metric coordinate reference system (CRS) we use helper functions to define UTM zones to which the original ICESat-2 data will be converted.
The function credits go to Chuck Gantz- [email protected].
Nothing, it just saves outputs as LAS file in disk
https://oceancolor.gsfc.nasa.gov/docs/ocssw/LatLong-UTMconversion_8cpp_source.html
# Specifying the path to ATL08 file atl08_path <- system.file("extdata", "atl08_clip.h5", package = "ICESat2VegR" ) # Reading ATL08 data (h5 file) atl08_h5 <- ATL08_read(atl08_path = atl08_path) # # Extracting ATL03 and ATL08 photons and heights atl08_dt <- ATL08_seg_attributes_dt(atl08_h5) outputLaz <- tempfile(fileext = ".laz") ATL08_seg_attributes_dt_LAS( atl08_dt, outputLaz ) close(atl08_h5)# Specifying the path to ATL08 file atl08_path <- system.file("extdata", "atl08_clip.h5", package = "ICESat2VegR" ) # Reading ATL08 data (h5 file) atl08_h5 <- ATL08_read(atl08_path = atl08_path) # # Extracting ATL03 and ATL08 photons and heights atl08_dt <- ATL08_seg_attributes_dt(atl08_h5) outputLaz <- tempfile(fileext = ".laz") ATL08_seg_attributes_dt_LAS( atl08_dt, outputLaz ) close(atl08_h5)
Computes a series of statistics of ATL08 terrain and canopy attributes within area defined by a polygon
ATL08_seg_attributes_dt_polyStat(atl08_seg_att_dt, func, poly_id = NULL)ATL08_seg_attributes_dt_polyStat(atl08_seg_att_dt, func, poly_id = NULL)
atl08_seg_att_dt |
An S4 object of class
|
func |
The function to be applied for computing the defined statistics |
poly_id |
Polygon id. If defined, statistics will be computed for each polygon |
Returns an S4 object of class icesat2.atl08_dt
Containing Statistics of ATL08 terrain and canopy attributes
# Specifying the path to ATL08 file atl08_path <- system.file( "extdata", "atl08_clip.h5", package = "ICESat2VegR" ) # Reading ATL08 data (h5 file) atl08_h5 <- ATL08_read(atl08_path = atl08_path) # Extracting ATL08 terrain and canopy attributes atl08_seg_att_dt <- ATL08_seg_attributes_dt(atl08_h5 = atl08_h5) # Specifying the path to shapefile polygon_filepath <- system.file( "extdata", "clip_geom.shp", package = "ICESat2VegR" ) # Reading shapefile as sf object polygon <- terra::vect(polygon_filepath) # Clipping ATL08 terrain and canopy attributes by Geometry atl08_seg_att_dt_clip <- ATL08_seg_attributes_dt_clipGeometry( atl08_seg_att_dt, polygon, split_by = "id" ) # Computing the max h_canopy by polygon id max_h_canopy <- ATL08_seg_attributes_dt_polyStat( atl08_seg_att_dt_clip, func = max(h_canopy), poly_id = "poly_id" ) head(max_h_canopy) # Define your own function mySetOfMetrics <- function(x) { metrics <- list( min = min(x), # Min of x max = max(x), # Max of x mean = mean(x), # Mean of x sd = sd(x) # Sd of x ) return(metrics) } # Computing a series of canopy statistics from customized function h_canopy_metrics <- ATL08_seg_attributes_dt_polyStat( atl08_seg_att_dt_clip, func = mySetOfMetrics(h_canopy), poly_id = "poly_id" ) head(h_canopy_metrics) close(atl08_h5)# Specifying the path to ATL08 file atl08_path <- system.file( "extdata", "atl08_clip.h5", package = "ICESat2VegR" ) # Reading ATL08 data (h5 file) atl08_h5 <- ATL08_read(atl08_path = atl08_path) # Extracting ATL08 terrain and canopy attributes atl08_seg_att_dt <- ATL08_seg_attributes_dt(atl08_h5 = atl08_h5) # Specifying the path to shapefile polygon_filepath <- system.file( "extdata", "clip_geom.shp", package = "ICESat2VegR" ) # Reading shapefile as sf object polygon <- terra::vect(polygon_filepath) # Clipping ATL08 terrain and canopy attributes by Geometry atl08_seg_att_dt_clip <- ATL08_seg_attributes_dt_clipGeometry( atl08_seg_att_dt, polygon, split_by = "id" ) # Computing the max h_canopy by polygon id max_h_canopy <- ATL08_seg_attributes_dt_polyStat( atl08_seg_att_dt_clip, func = max(h_canopy), poly_id = "poly_id" ) head(max_h_canopy) # Define your own function mySetOfMetrics <- function(x) { metrics <- list( min = min(x), # Min of x max = max(x), # Max of x mean = mean(x), # Mean of x sd = sd(x) # Sd of x ) return(metrics) } # Computing a series of canopy statistics from customized function h_canopy_metrics <- ATL08_seg_attributes_dt_polyStat( atl08_seg_att_dt_clip, func = mySetOfMetrics(h_canopy), poly_id = "poly_id" ) head(h_canopy_metrics) close(atl08_h5)
This function will read multiple ATL08 H5 files and create a stack of raster layers: count, and 1st, 2nd, 3rd and 4th moments (count, m1, m2, m3 and m4) for each metric selected, from which we can calculate statistics such as Mean, SD, Skewness and Kurtosis.
ATL08_seg_attributes_h5_gridStat( atl08_dir, metrics = c("h_canopy", "canopy_rh_conf", "h_median_canopy_abs", "h_min_canopy", "h_mean_canopy_abs", "h_median_canopy", "h_canopy_abs", "toc_roughness", "h_min_canopy_abs", "h_dif_canopy", "h_canopy_quad", "h_canopy_20m", "n_ca_photons", "photon_rate_can", "centroid_height", "canopy_h_metrics_abs", "h_mean_canopy", "subset_can_flag", "canopy_h_metrics", "n_toc_photons", "h_max_canopy_abs", "h_canopy_uncertainty", "canopy_openness", "h_max_canopy", "segment_cover"), beam = c("gt1l", "gt1r", "gt2l", "gt2r", "gt3l", "gt3r"), out_root, clip_obj, res, creation_options = def_co, agg_function = default_agg_function, agg_join = default_agg_join, finalizer = default_finalizer )ATL08_seg_attributes_h5_gridStat( atl08_dir, metrics = c("h_canopy", "canopy_rh_conf", "h_median_canopy_abs", "h_min_canopy", "h_mean_canopy_abs", "h_median_canopy", "h_canopy_abs", "toc_roughness", "h_min_canopy_abs", "h_dif_canopy", "h_canopy_quad", "h_canopy_20m", "n_ca_photons", "photon_rate_can", "centroid_height", "canopy_h_metrics_abs", "h_mean_canopy", "subset_can_flag", "canopy_h_metrics", "n_toc_photons", "h_max_canopy_abs", "h_canopy_uncertainty", "canopy_openness", "h_max_canopy", "segment_cover"), beam = c("gt1l", "gt1r", "gt2l", "gt2r", "gt3l", "gt3r"), out_root, clip_obj, res, creation_options = def_co, agg_function = default_agg_function, agg_join = default_agg_join, finalizer = default_finalizer )
atl08_dir |
CharacterVector. The directory paths where the ATL08 H5 files are stored; |
metrics |
CharacterVector. A vector of canopy attributes available from ATL08 product (e.g. "h_canopy") |
beam |
Character vector indicating beams to process (e.g. "gt1l", "gt1r", "gt2l", "gt2r", "gt3l", "gt3r") |
out_root |
Character. The root name for the raster output files, the pattern is {out_root}{metric}{count/m1/m2}.tif. This should include the full path for the file. |
clip_obj |
Bounding extent or spatial object used to define the clipping area. Supported inputs:
When a polygon object is provided ( |
res |
NumericVector. Resolution lon lat for the output raster in coordinates decimal degrees |
creation_options |
CharacterVector. The GDAL creation options for the tif file. Default c("COMPRESS=PACKBITS", "BIGTIFF=IF_SAFER", "TILED=YES", "BLOCKXSIZE=512", "BLOCKYSIZE=512") will create BIGTIFF if needed, with DEFLATE compression and tiled by 512x512 pixels. |
agg_function |
Formula function-like. An aggregate function which should return a data.table with the aggregate statistics |
agg_join |
Function. A function to merge two different agg objects. |
finalizer |
List<name, formula>. A list with the final raster names and the formula which uses the base statistics. |
This function will create five different aggregate statistics (n, mean, variance, min, max). One can calculate mean and standard deviation with the following formulas according to Terriberry (2007).
The agg_function is a formula which return a data.table with the
aggregate function to perform over the data.
The default is:
~data.table(
n = length(x),
mean = mean(x,na.rm = TRUE),
var = var(x) * (length(x) - 1),
min = min(x, na.rm=T),
max = max(x, na.rm=T)
)
The agg_join is a function to merge two data.table aggregates
from the agg_function. Since the h5 files will be aggregated
one by one, the statistics from the different h5 files should
have a function to merge them. The default function is:
function(x1, x2) {
combined = data.table()
x1$n[is.na(x1$n)] = 0
x1$mean[is.na(x1$mean)] = 0
x1$variance[is.na(x1$variance)] = 0
x1$max[is.na(x1$max)] = -Inf
x1$min[is.na(x1$min)] = Inf
combined$n = x1$n + x2$n
delta = x2$mean - x1$mean
delta2 = delta * delta
combined$mean = (x1$n * x1$mean + x2$n * x2$mean) / combined$n
combined$variance = x1$variance + x2$variance +
delta2 * x1$n * x2$n / combined$n
combined$min = pmin(x1$min, x2$min, na.rm=F)
combined$max = pmax(x1$max, x2$max, na.rm=F)
return(combined)
}
The finalizer is a list of formulas to generate the final
rasters based on the intermediate statistics from the previous
functions. The default finalizer will calculate the sd,
skewness and kurtosis based on the variance, M3, M4 and n
values. It is defined as:
list( sd = ~sqrt(variance/(n - 1)), )
Nothing. It outputs multiple raster tif files to the out_root specified path.
Terriberry, Timothy B. (2007), Computing Higher-Order Moments Online, archived from the original on 23 April 2014, retrieved 5 May 2008
library(data.table) # Specifying the path to ATL08 file atl08_path <- system.file("extdata", "atl08_clip.h5", package = "ICESat2VegR" ) # Reading ATL08 data (h5 file) atl08_h5 <- ATL08_read(atl08_path = atl08_path) # Bounding rectangle as numeric bbox: c(xmin, ymin, xmax, ymax) clip_obj <- c( xmin = -106.5708541870117188, ymin = 41.5314979553222656, xmax = -106.5699081420898438, ymax = 41.5386848449707031 ) res <- 100 # meters lat_to_met_factor <- 1 / 110540 lon_to_met_factor <- 1 / 111320 xres <- lon_to_met_factor * res yres <- lat_to_met_factor * res agg_function <- ~ data.table( min = min(x), max = max(x), sum = sum(x), n = length(x) ) agg_join <- function(agg1, agg2) { agg1[is.na(agg1)] <- 0 data.table( min = pmin(agg1$min, agg2$min), max = pmax(agg1$max, agg2$max), sum = agg1$sum + agg2$sum, n = agg1$n + agg2$n ) } finalizer <- list( mean = "sum/n", range = "max-min" ) outdir <- tempdir() # ATL08_seg_attributes_h5_gridStat( # atl08_dir = dirname(atl08_path), # metrics = c("h_canopy"), # out_root = outdir, # beam = c("gt1l","gt1r","gt2l","gt2r","gt3l","gt3r"), # clip_obj = clip_obj, # res = c(xres, -yres), # creation_options = c( # "COMPRESS=DEFLATE", # "BIGTIFF=IF_SAFER", # "TILED=YES", # "BLOCKXSIZE=512", # "BLOCKYSIZE=512" # ), # agg_function = agg_function, # agg_join = agg_join, # finalizer = finalizer # ) gc() file.remove(list.files(outdir, "*.tif")) close(atl08_h5)library(data.table) # Specifying the path to ATL08 file atl08_path <- system.file("extdata", "atl08_clip.h5", package = "ICESat2VegR" ) # Reading ATL08 data (h5 file) atl08_h5 <- ATL08_read(atl08_path = atl08_path) # Bounding rectangle as numeric bbox: c(xmin, ymin, xmax, ymax) clip_obj <- c( xmin = -106.5708541870117188, ymin = 41.5314979553222656, xmax = -106.5699081420898438, ymax = 41.5386848449707031 ) res <- 100 # meters lat_to_met_factor <- 1 / 110540 lon_to_met_factor <- 1 / 111320 xres <- lon_to_met_factor * res yres <- lat_to_met_factor * res agg_function <- ~ data.table( min = min(x), max = max(x), sum = sum(x), n = length(x) ) agg_join <- function(agg1, agg2) { agg1[is.na(agg1)] <- 0 data.table( min = pmin(agg1$min, agg2$min), max = pmax(agg1$max, agg2$max), sum = agg1$sum + agg2$sum, n = agg1$n + agg2$n ) } finalizer <- list( mean = "sum/n", range = "max-min" ) outdir <- tempdir() # ATL08_seg_attributes_h5_gridStat( # atl08_dir = dirname(atl08_path), # metrics = c("h_canopy"), # out_root = outdir, # beam = c("gt1l","gt1r","gt2l","gt2r","gt3l","gt3r"), # clip_obj = clip_obj, # res = c(xres, -yres), # creation_options = c( # "COMPRESS=DEFLATE", # "BIGTIFF=IF_SAFER", # "TILED=YES", # "BLOCKXSIZE=512", # "BLOCKYSIZE=512" # ), # agg_function = agg_function, # agg_join = agg_join, # finalizer = finalizer # ) gc() file.remove(list.files(outdir, "*.tif")) close(atl08_h5)
Download ICESat-2 ATL03 and ATL08 data from the LP DAAC / NSIDC endpoints.
Handles connection drops by resuming partial files and retrying with
exponential backoff. Authentication is handled via a .netrc file:
if it does not exist, the user is prompted for Earthdata Login credentials.
If authentication fails (e.g., wrong username/password), the user is
informed and can choose to re-enter credentials or cancel.
ATLAS_dataDownload( url, outdir = NULL, overwrite = FALSE, buffer_size = 512, timeout = 10, retries = 3, backoff = 2, quiet = FALSE )ATLAS_dataDownload( url, outdir = NULL, overwrite = FALSE, buffer_size = 512, timeout = 10, retries = 3, backoff = 2, quiet = FALSE )
url |
Character vector; URLs to ATL03/ATL08 files
(e.g., returned by |
outdir |
Character; output directory (default: |
overwrite |
Logical; overwrite existing files? Default |
buffer_size |
Integer; chunk size in KB per |
timeout |
Numeric; connection timeout (seconds) for establishing the connection (default 10). |
retries |
Integer; maximum attempts per file (default 3). |
backoff |
Numeric; exponential backoff base used as
|
quiet |
Logical; suppress per-file messages (default |
(invisibly) a data.frame with columns:
file: file name
dest: full destination path
status: one of ok, failed, skipped
attempts: number of attempts used
error: error message (if any)
Credits to Cole Krehbiel. Code adapted from: https://git.earthdata.nasa.gov/projects/LPDUR/repos/daac_data_download_r/browse/DAACDataDownload.R
## Not run: urls <- c( "https://example.com/path/to/ATL03_001.h5", "https://example.com/path/to/ATL08_001.h5" ) status <- ATLAS_dataDownload(urls, outdir = "data", retries = 5, backoff = 2) subset(status, status == "failed") ## End(Not run)## Not run: urls <- c( "https://example.com/path/to/ATL03_001.h5", "https://example.com/path/to/ATL08_001.h5" ) status <- ATLAS_dataDownload(urls, outdir = "data", retries = 5, backoff = 2) subset(status, status == "failed") ## End(Not run)
This function finds the exact granule(s) that contain ICESat-2 ATLAS data for a given region of interest and date range
ATLAS_dataFinder( short_name, lower_left_lon, lower_left_lat, upper_right_lon, upper_right_lat, version = "006", daterange = NULL, persist = TRUE, cloud_hosted = TRUE, cloud_computing = FALSE )ATLAS_dataFinder( short_name, lower_left_lon, lower_left_lat, upper_right_lon, upper_right_lat, version = "006", daterange = NULL, persist = TRUE, cloud_hosted = TRUE, cloud_computing = FALSE )
short_name |
ICESat-2 ATLAS data level short_name; Options: "ATL03", "ATL08", |
lower_left_lon |
Numeric. Minimum longitude in (decimal degrees) for the bounding box of the area of interest. |
lower_left_lat |
Numeric. Minimum latitude in (decimal degrees) for the bounding box of the area of interest. |
upper_right_lon |
Numeric. Maximum longitude in lon (decimal degrees) for the bounding box of the area of interest. |
upper_right_lat |
Numeric. Maximum latitude in (decimal degrees) for the bounding box of the area of interest. |
version |
Character. The version of the ICESat-2 ATLAS product files to be returned (only V005 or V006). Default "006". |
daterange |
Vector. Date range. Specify your start and end dates using ISO 8601 [YYYY]-[MM]-[DD]T[hh]:[mm]:[ss]Z. Ex.: c("2019-07-01T00:00:00Z","2020-05-22T23:59:59Z"). If NULL (default), the date range filter will be not applied. |
persist |
Logical. If TRUE, it will create the .netrc |
cloud_hosted |
Logical. Flag to indicate use of cloud hosted collections.To be used when the cloud computing parameter is FALSE. |
cloud_computing |
Logical. If TRUE, it will return granules for cloud computing directly, otherwise it will return links to be passed in the function ATLAS_dataDownload for data download. |
Return either a vector object pointing out the path to ICESat-2 ATLAS data found within the boundary box coordinates provided for data download or a vector object containing the granules hosted on the cloud for cloud computing directly.
bbox: Defined by the upper left and lower right corner coordinates, in lat,lon ordering, for the bounding box of the area of interest (e.g. lower_left_lon,lower_left_lat,upper_right_lon,upper_right_lat)
This function relies on the existing CMR tool: https://cmr.earthdata.nasa.gov/search/site/docs/search/api.html
# ICESat-2 data finder is a web service provided by NASA # usually the request takes more than 5 seconds # Specifying bounding box coordinates lower_left_lon <- -96.0 lower_left_lat <- 40.0 upper_right_lon <- -96.5 upper_right_lat <- 40.5 # Specifying the date range daterange <- c("2022-05-01", "2022-05-02") # Extracting the path to ICESat-2 ATLAS data for the specified boundary box coordinates # for data download # Shouldn't be tested because it relies on a web service which might be down ## Not run: ATLAS02b_list <- ATLAS_dataFinder( short_name = "ATL08", lower_left_lon, lower_left_lat, upper_right_lon, upper_right_lat, version = "007", daterange = daterange ) ## End(Not run)# ICESat-2 data finder is a web service provided by NASA # usually the request takes more than 5 seconds # Specifying bounding box coordinates lower_left_lon <- -96.0 lower_left_lat <- 40.0 upper_right_lon <- -96.5 upper_right_lat <- 40.5 # Specifying the date range daterange <- c("2022-05-01", "2022-05-02") # Extracting the path to ICESat-2 ATLAS data for the specified boundary box coordinates # for data download # Shouldn't be tested because it relies on a web service which might be down ## Not run: ATLAS02b_list <- ATLAS_dataFinder( short_name = "ATL08", lower_left_lon, lower_left_lat, upper_right_lon, upper_right_lat, version = "007", daterange = daterange ) ## End(Not run)
Given a fitted randomForest::randomForest object, this function
serializes the forest using the internal Rcpp module icesat2_module
and constructs a corresponding Google Earth Engine random forest
classifier via
ee$Classifier$decisionTreeEnsemble(rf_strings).
This implementation always returns an ee$Classifier and does not use
ee$Regressor.
build_ee_forest(rf)build_ee_forest(rf)
rf |
A fitted randomForest::randomForest model object. |
An Earth Engine ee$Classifier object created with
ee$Classifier$decisionTreeEnsemble() that can be used with
ee$Image$classify().
Unified clipping interface for ICESat-2 ATL03/ATL08 data. The generic
clip() dispatches on the class of x and internally calls appropriate
_clipBox() or _clipGeometry() helpers.
Depending on the product you are working with you can access its specific clipping methods:
clip(x, clip_obj, ...)clip(x, clip_obj, ...)
x |
ICESat-2 object (ATL03/ATL08 h5, attributes, or joined table) Can be either: |
clip_obj |
Clipping object. Supported for box-based clipping:
For geometry-based clipping:
To clip by a spatial object's extent, extract its bbox first. |
... |
Additional arguments passed to For hdf5 based clip, the additional arguments are:
|
This function clips ATL03 photon attributes within given bounding coordinates.
## S4 method for signature 'icesat2.atl03_dt,ANY' clip(x, clip_obj, ...)## S4 method for signature 'icesat2.atl03_dt,ANY' clip(x, clip_obj, ...)
x |
An ATL03 photon data table. An S4 object of class |
clip_obj |
Spatial clip_obj. An object of class |
... |
. The |
Returns an S4 object of class icesat2.atl03_dt
containing the ATL03 photon attributes.
https://icesat-2.gsfc.nasa.gov/sites/default/files/page_files/ICESat2_ATL03_ATBD_r006.pdf
# ATL03 file path atl03_path <- system.file("extdata", "atl03_clip.h5", package = "ICESat2VegR" ) # Reading ATL03 data (h5 file) atl03_h5 <- ATL03_read(atl03_path = atl03_path) # Extracting ATL03 photon attributes atl03_photons_dt <- ATL03_photons_attributes_dt(atl03_h5 = atl03_h5) # Specifying the path to shapefile clip_obj_filepath <- system.file( "extdata", "clip_geom.shp", package = "ICESat2VegR" ) # Reading shapefile as sf object clip_obj <- terra::vect(clip_obj_filepath) # Clipping ATL03 photon attributes by Geometry atl03_photons_dt_clip <- ATL03_photons_attributes_dt_clipGeometry(atl03_photons_dt, clip_obj, split_by = "id") head(atl03_photons_dt_clip) close(atl03_h5)# ATL03 file path atl03_path <- system.file("extdata", "atl03_clip.h5", package = "ICESat2VegR" ) # Reading ATL03 data (h5 file) atl03_h5 <- ATL03_read(atl03_path = atl03_path) # Extracting ATL03 photon attributes atl03_photons_dt <- ATL03_photons_attributes_dt(atl03_h5 = atl03_h5) # Specifying the path to shapefile clip_obj_filepath <- system.file( "extdata", "clip_geom.shp", package = "ICESat2VegR" ) # Reading shapefile as sf object clip_obj <- terra::vect(clip_obj_filepath) # Clipping ATL03 photon attributes by Geometry atl03_photons_dt_clip <- ATL03_photons_attributes_dt_clipGeometry(atl03_photons_dt, clip_obj, split_by = "id") head(atl03_photons_dt_clip) close(atl03_h5)
Clips ATL03 photon attributes within a given bounding extent, defined by a
single clip_obj argument. The clipping extent can be provided as:
(i) a numeric bounding box, or
(ii) a spatial extent object.
## S4 method for signature 'icesat2.atl03_dt,numeric' clip(x, clip_obj, ...)## S4 method for signature 'icesat2.atl03_dt,numeric' clip(x, clip_obj, ...)
x |
An |
clip_obj |
Bounding extent used to perform the clipping. Supported inputs:
|
... |
not used |
When clip_obj is a SpatExtent, the package terra must be
installed. If not found, the function stops with an informative message.
Returns a subset of the original icesat2.atl03_dt object containing
only photons within the bounding box.
https://icesat-2.gsfc.nasa.gov/sites/default/files/page_files/ICESat2_ATL03_ATBD_r006.pdf
atl03_path <- system.file("extdata", "atl03_clip.h5", package = "ICESat2VegR" ) atl03_h5 <- ATL03_read(atl03_path = atl03_path) atl03_photons_dt <- ATL03_photons_attributes_dt(atl03_h5 = atl03_h5) # 1) Using a numeric bbox: xmin ymin xmax ymax bbox <- c(-106.57, 41.53, -106.5698, 41.54) atl03_clip_bbox <- ATL03_photons_attributes_dt_clipBox( atl03_photons_dt = atl03_photons_dt, clip_obj = bbox ) # 2) Using a SpatExtent # library(terra) # ext <- terra::ext(-106.57, -106.5698, 41.53, 41.54) # atl03_clip_ext <- ATL03_photons_attributes_dt_clipBox( # atl03_photons_dt = atl03_photons_dt, # clip_obj = ext # ) close(atl03_h5)atl03_path <- system.file("extdata", "atl03_clip.h5", package = "ICESat2VegR" ) atl03_h5 <- ATL03_read(atl03_path = atl03_path) atl03_photons_dt <- ATL03_photons_attributes_dt(atl03_h5 = atl03_h5) # 1) Using a numeric bbox: xmin ymin xmax ymax bbox <- c(-106.57, 41.53, -106.5698, 41.54) atl03_clip_bbox <- ATL03_photons_attributes_dt_clipBox( atl03_photons_dt = atl03_photons_dt, clip_obj = bbox ) # 2) Using a SpatExtent # library(terra) # ext <- terra::ext(-106.57, -106.5698, 41.53, 41.54) # atl03_clip_ext <- ATL03_photons_attributes_dt_clipBox( # atl03_photons_dt = atl03_photons_dt, # clip_obj = ext # ) close(atl03_h5)
Clips ATL03 photon attributes within a given bounding extent, defined by a
single clip_obj argument. The clipping extent can be provided as:
(i) a numeric bounding box, or
(ii) a spatial extent object.
## S4 method for signature 'icesat2.atl03_dt,SpatExtent' clip(x, clip_obj, ...)## S4 method for signature 'icesat2.atl03_dt,SpatExtent' clip(x, clip_obj, ...)
x |
An |
clip_obj |
Bounding extent used to perform the clipping. Supported inputs:
|
... |
not used |
When clip_obj is a SpatExtent, the package terra must be
installed. If not found, the function stops with an informative message.
Returns a subset of the original icesat2.atl03_dt object containing
only photons within the bounding box.
https://icesat-2.gsfc.nasa.gov/sites/default/files/page_files/ICESat2_ATL03_ATBD_r006.pdf
atl03_path <- system.file("extdata", "atl03_clip.h5", package = "ICESat2VegR" ) atl03_h5 <- ATL03_read(atl03_path = atl03_path) atl03_photons_dt <- ATL03_photons_attributes_dt(atl03_h5 = atl03_h5) # 1) Using a numeric bbox: xmin ymin xmax ymax bbox <- c(-106.57, 41.53, -106.5698, 41.54) atl03_clip_bbox <- ATL03_photons_attributes_dt_clipBox( atl03_photons_dt = atl03_photons_dt, clip_obj = bbox ) # 2) Using a SpatExtent # library(terra) # ext <- terra::ext(-106.57, -106.5698, 41.53, 41.54) # atl03_clip_ext <- ATL03_photons_attributes_dt_clipBox( # atl03_photons_dt = atl03_photons_dt, # clip_obj = ext # ) close(atl03_h5)atl03_path <- system.file("extdata", "atl03_clip.h5", package = "ICESat2VegR" ) atl03_h5 <- ATL03_read(atl03_path = atl03_path) atl03_photons_dt <- ATL03_photons_attributes_dt(atl03_h5 = atl03_h5) # 1) Using a numeric bbox: xmin ymin xmax ymax bbox <- c(-106.57, 41.53, -106.5698, 41.54) atl03_clip_bbox <- ATL03_photons_attributes_dt_clipBox( atl03_photons_dt = atl03_photons_dt, clip_obj = bbox ) # 2) Using a SpatExtent # library(terra) # ext <- terra::ext(-106.57, -106.5698, 41.53, 41.54) # atl03_clip_ext <- ATL03_photons_attributes_dt_clipBox( # atl03_photons_dt = atl03_photons_dt, # clip_obj = ext # ) close(atl03_h5)
Clips an ICESat-2 ATL03 HDF5 file using one or more geometry-based clipping
objects provided as a terra::SpatVector. Each geometry in vect
defines an individual clipping region. The function iteratively clips the
ATL03 data for each region and writes a separate output HDF5 file for every
geometry. The name of each output file is automatically appended with the
value of the attribute specified in split_by.
Only datasets within the ATL03 beam groups are spatially clipped; metadata and ancillary non-beam groups remain unchanged in the resulting files.
## S4 method for signature 'icesat2.atl03_h5,ANY' clip(x, clip_obj, ...)## S4 method for signature 'icesat2.atl03_h5,ANY' clip(x, clip_obj, ...)
x |
An |
clip_obj |
A |
... |
Additional arguments:
|
Returns a list of clipped S4 objects of class
icesat2.atl03_h5, one for each clipping geometry
contained in vect.
# ATL03 file path atl03_path <- system.file("extdata", "atl03_clip.h5", package = "ICESat2VegR" ) # Read ATL03 file atl03_h5 <- ATL03_read(atl03_path) # Output base filename output <- tempfile(fileext = ".h5") # Load clipping geometries vect_path <- system.file("extdata", "clip_geom.shp", package = "ICESat2VegR" ) vect <- terra::vect(vect_path) # Clip ATL03 data using polygon geometries atl03_clipped_list <- ATL03_h5_clipGeometry( atl03_h5, output, vect, split_by = "id" ) close(atl03_h5)# ATL03 file path atl03_path <- system.file("extdata", "atl03_clip.h5", package = "ICESat2VegR" ) # Read ATL03 file atl03_h5 <- ATL03_read(atl03_path) # Output base filename output <- tempfile(fileext = ".h5") # Load clipping geometries vect_path <- system.file("extdata", "clip_geom.shp", package = "ICESat2VegR" ) vect <- terra::vect(vect_path) # Clip ATL03 data using polygon geometries atl03_clipped_list <- ATL03_h5_clipGeometry( atl03_h5, output, vect, split_by = "id" ) close(atl03_h5)
Clips an ICESat-2 ATL03 HDF5 file to a specified spatial extent. Only geolocated photon and segment datasets within the ATL03 beam groups are clipped; all metadata, orbit information, and ancillary groups are preserved unchanged. This function provides bounding-box-based clipping, complementing geometry-based clipping workflows.
## S4 method for signature 'icesat2.atl03_h5,numeric' clip(x, clip_obj, ...)## S4 method for signature 'icesat2.atl03_h5,numeric' clip(x, clip_obj, ...)
x |
An |
clip_obj |
Bounding extent used for clipping. Supported inputs:
|
... |
Additional arguments:
|
The function performs spatial subsetting at the photon and segment level. Internally, it:
Copies file- and group-level attributes.
Extracts beam-level datasets and evaluates segment-level and photon-level masks using the supplied bounding box.
Applies these masks to all datasets whose dimensions correspond to segments or photons.
Recomputes dependent indexing datasets (e.g., ph_index_beg)
to maintain ATL03 structural integrity.
Writes the clipped data into a new, valid ATL03 HDF5 file.
This function preserves the full ATL03 metadata, ancillary information, and file structure while trimming the spatial domain to the user-specified bounding extent.
An S4 object of class icesat2.atl03_h5 representing
the clipped ATL03 HDF5 file saved at the output location.
# ATL03 file path atl03_path <- system.file("extdata", "atl03_clip.h5", package = "ICESat2VegR" ) # Read ATL03 data (HDF5) atl03_h5 <- ATL03_read(atl03_path) # Bounding rectangle coordinates (ul_lat, ul_lon, lr_lat, lr_lon) xmin <- -106.5723 xmax <- -106.5693 ymin <- 41.533 ymax <- 41.537 bbox <- c(ymax, xmin, ymin, xmax) # Clip ATL03 using the bounding extent output <- tempfile(fileext = ".h5") atl03_clip <- ATL03_h5_clipBox( atl03_h5, output = output, clip_obj = bbox ) close(atl03_h5)# ATL03 file path atl03_path <- system.file("extdata", "atl03_clip.h5", package = "ICESat2VegR" ) # Read ATL03 data (HDF5) atl03_h5 <- ATL03_read(atl03_path) # Bounding rectangle coordinates (ul_lat, ul_lon, lr_lat, lr_lon) xmin <- -106.5723 xmax <- -106.5693 ymin <- 41.533 ymax <- 41.537 bbox <- c(ymax, xmin, ymin, xmax) # Clip ATL03 using the bounding extent output <- tempfile(fileext = ".h5") atl03_clip <- ATL03_h5_clipBox( atl03_h5, output = output, clip_obj = bbox ) close(atl03_h5)
Clips an ICESat-2 ATL03 HDF5 file to a specified spatial extent. Only geolocated photon and segment datasets within the ATL03 beam groups are clipped; all metadata, orbit information, and ancillary groups are preserved unchanged. This function provides bounding-box-based clipping, complementing geometry-based clipping workflows.
## S4 method for signature 'icesat2.atl03_h5,SpatExtent' clip(x, clip_obj, ...)## S4 method for signature 'icesat2.atl03_h5,SpatExtent' clip(x, clip_obj, ...)
x |
An |
clip_obj |
Bounding extent used for clipping. Supported inputs:
|
... |
Additional arguments:
|
The function performs spatial subsetting at the photon and segment level. Internally, it:
Copies file- and group-level attributes.
Extracts beam-level datasets and evaluates segment-level and photon-level masks using the supplied bounding box.
Applies these masks to all datasets whose dimensions correspond to segments or photons.
Recomputes dependent indexing datasets (e.g., ph_index_beg)
to maintain ATL03 structural integrity.
Writes the clipped data into a new, valid ATL03 HDF5 file.
This function preserves the full ATL03 metadata, ancillary information, and file structure while trimming the spatial domain to the user-specified bounding extent.
An S4 object of class icesat2.atl03_h5 representing
the clipped ATL03 HDF5 file saved at the output location.
# ATL03 file path atl03_path <- system.file("extdata", "atl03_clip.h5", package = "ICESat2VegR" ) # Read ATL03 data (HDF5) atl03_h5 <- ATL03_read(atl03_path) # Bounding rectangle coordinates (ul_lat, ul_lon, lr_lat, lr_lon) xmin <- -106.5723 xmax <- -106.5693 ymin <- 41.533 ymax <- 41.537 bbox <- c(ymax, xmin, ymin, xmax) # Clip ATL03 using the bounding extent output <- tempfile(fileext = ".h5") atl03_clip <- ATL03_h5_clipBox( atl03_h5, output = output, clip_obj = bbox ) close(atl03_h5)# ATL03 file path atl03_path <- system.file("extdata", "atl03_clip.h5", package = "ICESat2VegR" ) # Read ATL03 data (HDF5) atl03_h5 <- ATL03_read(atl03_path) # Bounding rectangle coordinates (ul_lat, ul_lon, lr_lat, lr_lon) xmin <- -106.5723 xmax <- -106.5693 ymin <- 41.533 ymax <- 41.537 bbox <- c(ymax, xmin, ymin, xmax) # Clip ATL03 using the bounding extent output <- tempfile(fileext = ".h5") atl03_clip <- ATL03_h5_clipBox( atl03_h5, output = output, clip_obj = bbox ) close(atl03_h5)
This function clips joined ATL03 and ATL08 photon attributes within a given geometry.
## S4 method for signature 'icesat2.atl03atl08_dt,ANY' clip(x, clip_obj, ...)## S4 method for signature 'icesat2.atl03atl08_dt,ANY' clip(x, clip_obj, ...)
x |
An S4 object of class |
clip_obj |
An object of class |
... |
|
Returns an S4 object of class icesat2.atl03atl08_dt
containing the clipped ATL08 attributes.
# Specifying the path to ATL03 and ATL08 files atl03_path <- system.file("extdata", "atl03_clip.h5", package = "ICESat2VegR") atl08_path <- system.file("extdata", "atl08_clip.h5", package = "ICESat2VegR") # Reading ATL03 and ATL08 data (h5 files) atl03_h5 <- ATL03_read(atl03_path) atl08_h5 <- ATL08_read(atl08_path) # Joining ATL03 and ATL08 photon attributes atl03_atl08_dt <- ATL03_ATL08_photons_attributes_dt_join(atl03_h5, atl08_h5) head(atl03_atl08_dt) # Specifying the path to the shapefile clip_obj_filepath <- system.file("extdata", "clip_geom.shp", package = "ICESat2VegR") # Reading shapefile as a SpatVector object clip_obj <- terra::vect(clip_obj_filepath) # Clipping ATL08 terrain attributes by geometry atl03_atl08_dt_clip <- ATL03_ATL08_photons_attributes_dt_clipGeometry( atl03_atl08_dt, clip_obj, split_by = "id" ) head(atl03_atl08_dt_clip) close(atl03_h5) close(atl08_h5)# Specifying the path to ATL03 and ATL08 files atl03_path <- system.file("extdata", "atl03_clip.h5", package = "ICESat2VegR") atl08_path <- system.file("extdata", "atl08_clip.h5", package = "ICESat2VegR") # Reading ATL03 and ATL08 data (h5 files) atl03_h5 <- ATL03_read(atl03_path) atl08_h5 <- ATL08_read(atl08_path) # Joining ATL03 and ATL08 photon attributes atl03_atl08_dt <- ATL03_ATL08_photons_attributes_dt_join(atl03_h5, atl08_h5) head(atl03_atl08_dt) # Specifying the path to the shapefile clip_obj_filepath <- system.file("extdata", "clip_geom.shp", package = "ICESat2VegR") # Reading shapefile as a SpatVector object clip_obj <- terra::vect(clip_obj_filepath) # Clipping ATL08 terrain attributes by geometry atl03_atl08_dt_clip <- ATL03_ATL08_photons_attributes_dt_clipGeometry( atl03_atl08_dt, clip_obj, split_by = "id" ) head(atl03_atl08_dt_clip) close(atl03_h5) close(atl08_h5)
Clips joined ATL03 and ATL08 photon attributes within a given bounding
extent, defined by a single clip_obj argument. The clipping extent can
be provided as:
(i) a numeric bounding box, or
(ii) a spatial extent object.
## S4 method for signature 'icesat2.atl03atl08_dt,numeric' clip(x, clip_obj, ...)## S4 method for signature 'icesat2.atl03atl08_dt,numeric' clip(x, clip_obj, ...)
x |
An S4 object of class
|
clip_obj |
Bounding extent used to perform the clipping. Supported inputs:
|
... |
not used. |
When clip_obj is a SpatExtent, the package terra must be
installed. If not found, the function stops with an informative message.
Returns an S4 object of class
icesat2.atl03atl08_dt containing a subset of the
joined ATL03 and ATL08 photon attributes restricted to the clipping extent.
https://icesat-2.gsfc.nasa.gov/sites/default/files/page_files/ICESat2_ATL03_ATBD_r006.pdf
https://icesat-2.gsfc.nasa.gov/sites/default/files/page_files/ICESat2_ATL08_ATBD_r006.pdf
# Specifying the path to ATL03 and ATL08 files atl03_path <- system.file("extdata", "atl03_clip.h5", package = "ICESat2VegR" ) atl08_path <- system.file("extdata", "atl08_clip.h5", package = "ICESat2VegR" ) # Reading ATL03 and ATL08 data (h5 files) atl03_h5 <- ATL03_read(atl03_path = atl03_path) atl08_h5 <- ATL08_read(atl08_path = atl08_path) # Joining ATL03 and ATL08 photons and heights atl03_atl08_dt <- ATL03_ATL08_photons_attributes_dt_join(atl03_h5, atl08_h5) head(atl03_atl08_dt) # 1) Using a numeric bounding box: xmin ymin xmax ymax bbox <- c(-103.7604, 59.4672, -103.7600, 59.4680) atl03_atl08_dt_clip <- ATL03_ATL08_photons_attributes_dt_clipBox( atl03_atl08_dt = atl03_atl08_dt, clip_obj = bbox ) head(atl03_atl08_dt_clip) # 2) Using a SpatExtent (example) # library(terra) # ext <- terra::ext(-103.7604, -103.7600, 59.4672, 59.4680) # atl03_atl08_dt_clip_ext <- ATL03_ATL08_photons_attributes_dt_clipBox( # atl03_atl08_dt = atl03_atl08_dt, # clip_obj = ext # ) close(atl03_h5) close(atl08_h5)# Specifying the path to ATL03 and ATL08 files atl03_path <- system.file("extdata", "atl03_clip.h5", package = "ICESat2VegR" ) atl08_path <- system.file("extdata", "atl08_clip.h5", package = "ICESat2VegR" ) # Reading ATL03 and ATL08 data (h5 files) atl03_h5 <- ATL03_read(atl03_path = atl03_path) atl08_h5 <- ATL08_read(atl08_path = atl08_path) # Joining ATL03 and ATL08 photons and heights atl03_atl08_dt <- ATL03_ATL08_photons_attributes_dt_join(atl03_h5, atl08_h5) head(atl03_atl08_dt) # 1) Using a numeric bounding box: xmin ymin xmax ymax bbox <- c(-103.7604, 59.4672, -103.7600, 59.4680) atl03_atl08_dt_clip <- ATL03_ATL08_photons_attributes_dt_clipBox( atl03_atl08_dt = atl03_atl08_dt, clip_obj = bbox ) head(atl03_atl08_dt_clip) # 2) Using a SpatExtent (example) # library(terra) # ext <- terra::ext(-103.7604, -103.7600, 59.4672, 59.4680) # atl03_atl08_dt_clip_ext <- ATL03_ATL08_photons_attributes_dt_clipBox( # atl03_atl08_dt = atl03_atl08_dt, # clip_obj = ext # ) close(atl03_h5) close(atl08_h5)
Clips joined ATL03 and ATL08 photon attributes within a given bounding
extent, defined by a single clip_obj argument. The clipping extent can
be provided as:
(i) a numeric bounding box, or
(ii) a spatial extent object.
## S4 method for signature 'icesat2.atl03atl08_dt,SpatExtent' clip(x, clip_obj, ...)## S4 method for signature 'icesat2.atl03atl08_dt,SpatExtent' clip(x, clip_obj, ...)
x |
An S4 object of class
|
clip_obj |
Bounding extent used to perform the clipping. Supported inputs:
|
... |
not used. |
When clip_obj is a SpatExtent, the package terra must be
installed. If not found, the function stops with an informative message.
Returns an S4 object of class
icesat2.atl03atl08_dt containing a subset of the
joined ATL03 and ATL08 photon attributes restricted to the clipping extent.
https://icesat-2.gsfc.nasa.gov/sites/default/files/page_files/ICESat2_ATL03_ATBD_r006.pdf
https://icesat-2.gsfc.nasa.gov/sites/default/files/page_files/ICESat2_ATL08_ATBD_r006.pdf
# Specifying the path to ATL03 and ATL08 files atl03_path <- system.file("extdata", "atl03_clip.h5", package = "ICESat2VegR" ) atl08_path <- system.file("extdata", "atl08_clip.h5", package = "ICESat2VegR" ) # Reading ATL03 and ATL08 data (h5 files) atl03_h5 <- ATL03_read(atl03_path = atl03_path) atl08_h5 <- ATL08_read(atl08_path = atl08_path) # Joining ATL03 and ATL08 photons and heights atl03_atl08_dt <- ATL03_ATL08_photons_attributes_dt_join(atl03_h5, atl08_h5) head(atl03_atl08_dt) # 1) Using a numeric bounding box: xmin ymin xmax ymax bbox <- c(-103.7604, 59.4672, -103.7600, 59.4680) atl03_atl08_dt_clip <- ATL03_ATL08_photons_attributes_dt_clipBox( atl03_atl08_dt = atl03_atl08_dt, clip_obj = bbox ) head(atl03_atl08_dt_clip) # 2) Using a SpatExtent (example) # library(terra) # ext <- terra::ext(-103.7604, -103.7600, 59.4672, 59.4680) # atl03_atl08_dt_clip_ext <- ATL03_ATL08_photons_attributes_dt_clipBox( # atl03_atl08_dt = atl03_atl08_dt, # clip_obj = ext # ) close(atl03_h5) close(atl08_h5)# Specifying the path to ATL03 and ATL08 files atl03_path <- system.file("extdata", "atl03_clip.h5", package = "ICESat2VegR" ) atl08_path <- system.file("extdata", "atl08_clip.h5", package = "ICESat2VegR" ) # Reading ATL03 and ATL08 data (h5 files) atl03_h5 <- ATL03_read(atl03_path = atl03_path) atl08_h5 <- ATL08_read(atl08_path = atl08_path) # Joining ATL03 and ATL08 photons and heights atl03_atl08_dt <- ATL03_ATL08_photons_attributes_dt_join(atl03_h5, atl08_h5) head(atl03_atl08_dt) # 1) Using a numeric bounding box: xmin ymin xmax ymax bbox <- c(-103.7604, 59.4672, -103.7600, 59.4680) atl03_atl08_dt_clip <- ATL03_ATL08_photons_attributes_dt_clipBox( atl03_atl08_dt = atl03_atl08_dt, clip_obj = bbox ) head(atl03_atl08_dt_clip) # 2) Using a SpatExtent (example) # library(terra) # ext <- terra::ext(-103.7604, -103.7600, 59.4672, 59.4680) # atl03_atl08_dt_clip_ext <- ATL03_ATL08_photons_attributes_dt_clipBox( # atl03_atl08_dt = atl03_atl08_dt, # clip_obj = ext # ) close(atl03_h5) close(atl08_h5)
This function clips ATL08 Terrain and Canopy Attributes within a given geometry
## S4 method for signature 'icesat2.atl08_dt,ANY' clip(x, clip_obj, ...)## S4 method for signature 'icesat2.atl08_dt,ANY' clip(x, clip_obj, ...)
x |
An icesat2.atl08_dt object (output of
|
clip_obj |
clip_obj. An object of class |
... |
The |
Returns an S4 object of class icesat2.atl08_dt
containing the clipped ATL08 Terrain and Canopy Attributes.
# Specifying the path to ATL08 file atl08_path <- system.file("extdata", "atl08_clip.h5", package = "ICESat2VegR" ) # Reading ATL08 data (h5 file) atl08_h5 <- ATL08_read(atl08_path = atl08_path) # Extracting ATL08-derived terrain and canopy attributes atl08_seg_att_dt <- ATL08_seg_attributes_dt(atl08_h5 = atl08_h5) clip_obj_path <- system.file("extdata", "clip_geom.shp", package = "ICESat2VegR" ) if (require(terra)) { polygon <- terra::vect(clip_obj_path) head(atl08_seg_att_dt) # Clipping ATL08 Terrain and Canopy Attributes by Geometry atl08_seg_att_dt_clip <- ATL08_seg_attributes_dt_clipGeometry(atl08_seg_att_dt, polygon, split_by = "id" ) hasLeaflet <- require(leaflet) if (hasLeaflet) { leaflet() %>% addCircleMarkers(atl08_seg_att_dt_clip$longitude, atl08_seg_att_dt_clip$latitude, radius = 1, opacity = 1, color = "red" ) %>% addScaleBar(options = list(imperial = FALSE)) %>% addPolygons( data = polygon, weight = 1, col = "white", opacity = 1, fillOpacity = 0 ) %>% addProviderTiles(providers$Esri.WorldImagery, options = providerTileOptions(minZoom = 3, maxZoom = 17) ) } } close(atl08_h5)# Specifying the path to ATL08 file atl08_path <- system.file("extdata", "atl08_clip.h5", package = "ICESat2VegR" ) # Reading ATL08 data (h5 file) atl08_h5 <- ATL08_read(atl08_path = atl08_path) # Extracting ATL08-derived terrain and canopy attributes atl08_seg_att_dt <- ATL08_seg_attributes_dt(atl08_h5 = atl08_h5) clip_obj_path <- system.file("extdata", "clip_geom.shp", package = "ICESat2VegR" ) if (require(terra)) { polygon <- terra::vect(clip_obj_path) head(atl08_seg_att_dt) # Clipping ATL08 Terrain and Canopy Attributes by Geometry atl08_seg_att_dt_clip <- ATL08_seg_attributes_dt_clipGeometry(atl08_seg_att_dt, polygon, split_by = "id" ) hasLeaflet <- require(leaflet) if (hasLeaflet) { leaflet() %>% addCircleMarkers(atl08_seg_att_dt_clip$longitude, atl08_seg_att_dt_clip$latitude, radius = 1, opacity = 1, color = "red" ) %>% addScaleBar(options = list(imperial = FALSE)) %>% addPolygons( data = polygon, weight = 1, col = "white", opacity = 1, fillOpacity = 0 ) %>% addProviderTiles(providers$Esri.WorldImagery, options = providerTileOptions(minZoom = 3, maxZoom = 17) ) } } close(atl08_h5)
Clips ATL08 terrain and canopy segment attributes within a given bounding
extent, defined by a single clip_obj argument. The clipping extent can
be provided as:
(i) a numeric bounding box, or
(ii) a spatial extent object.
## S4 method for signature 'icesat2.atl08_dt,numeric' clip(x, clip_obj, ...)## S4 method for signature 'icesat2.atl08_dt,numeric' clip(x, clip_obj, ...)
x |
An |
clip_obj |
Bounding extent used to perform the clipping. Supported inputs:
|
... |
not used. |
When clip_obj is a SpatExtent, the package terra must be
installed. If not found, the function stops with an informative message.
Returns an S4 object of class
icesat2.atl08_dt
containing the clipped ATL08 terrain and canopy attributes.
# Specifying the path to the ATL08 file atl08_path <- system.file("extdata", "atl08_clip.h5", package = "ICESat2VegR" ) # Reading ATL08 data (h5 file) atl08_h5 <- ATL08_read(atl08_path) # Extracting ATL08-derived segment attributes atl08_seg_att_dt <- ATL08_seg_attributes_dt(atl08_h5 = atl08_h5) # 1) Using a numeric bounding box: xmin ymin xmax ymax bbox <- c(-103.7604, 59.4672, -103.7600, 59.4680) atl08_seg_att_dt_clip <- ATL08_seg_attributes_dt_clipBox( atl08_seg_att_dt = atl08_seg_att_dt, clip_obj = bbox ) # 2) Using a SpatExtent # library(terra) # ext <- terra::ext(-103.7604, -103.7600, 59.4672, 59.4680) # atl08_seg_att_dt_clip_ext <- ATL08_seg_attributes_dt_clipBox( # atl08_seg_att_dt = atl08_seg_att_dt, # clip_obj = ext # ) close(atl08_h5)# Specifying the path to the ATL08 file atl08_path <- system.file("extdata", "atl08_clip.h5", package = "ICESat2VegR" ) # Reading ATL08 data (h5 file) atl08_h5 <- ATL08_read(atl08_path) # Extracting ATL08-derived segment attributes atl08_seg_att_dt <- ATL08_seg_attributes_dt(atl08_h5 = atl08_h5) # 1) Using a numeric bounding box: xmin ymin xmax ymax bbox <- c(-103.7604, 59.4672, -103.7600, 59.4680) atl08_seg_att_dt_clip <- ATL08_seg_attributes_dt_clipBox( atl08_seg_att_dt = atl08_seg_att_dt, clip_obj = bbox ) # 2) Using a SpatExtent # library(terra) # ext <- terra::ext(-103.7604, -103.7600, 59.4672, 59.4680) # atl08_seg_att_dt_clip_ext <- ATL08_seg_attributes_dt_clipBox( # atl08_seg_att_dt = atl08_seg_att_dt, # clip_obj = ext # ) close(atl08_h5)
Clips ATL08 terrain and canopy segment attributes within a given bounding
extent, defined by a single clip_obj argument. The clipping extent can
be provided as:
(i) a numeric bounding box, or
(ii) a spatial extent object.
## S4 method for signature 'icesat2.atl08_dt,SpatExtent' clip(x, clip_obj, ...)## S4 method for signature 'icesat2.atl08_dt,SpatExtent' clip(x, clip_obj, ...)
x |
An |
clip_obj |
Bounding extent used to perform the clipping. Supported inputs:
|
... |
not used. |
When clip_obj is a SpatExtent, the package terra must be
installed. If not found, the function stops with an informative message.
Returns an S4 object of class
icesat2.atl08_dt
containing the clipped ATL08 terrain and canopy attributes.
This function clips ATL08 HDF5 file within beam groups, but keeps metada and ancillary data the same.
## S4 method for signature 'icesat2.atl08_h5,ANY' clip(x, clip_obj, ...)## S4 method for signature 'icesat2.atl08_h5,ANY' clip(x, clip_obj, ...)
x |
|
clip_obj |
|
... |
Additional arguments:
|
Returns a list of clipped S4 object of class icesat2.atl08_h5
# ATL08 file path atl08_path <- system.file("extdata", "atl08_clip.h5", package = "ICESat2VegR" ) # Reading ATL08 data (h5 file) atl08_h5 <- ATL08_read(atl08_path = atl08_path) output <- tempfile(fileext = ".h5") vect_path <- system.file("extdata", "clip_geom.shp", package = "ICESat2VegR" ) vect <- terra::vect(vect_path) # Clipping ATL08 photons by boundary box extent atl08_photons_dt_clip <- ATL08_h5_clipGeometry( atl08_h5, output, vect, split_by = "id" ) close(atl08_h5)# ATL08 file path atl08_path <- system.file("extdata", "atl08_clip.h5", package = "ICESat2VegR" ) # Reading ATL08 data (h5 file) atl08_h5 <- ATL08_read(atl08_path = atl08_path) output <- tempfile(fileext = ".h5") vect_path <- system.file("extdata", "clip_geom.shp", package = "ICESat2VegR" ) vect <- terra::vect(vect_path) # Clipping ATL08 photons by boundary box extent atl08_photons_dt_clip <- ATL08_h5_clipGeometry( atl08_h5, output, vect, split_by = "id" ) close(atl08_h5)
Clips an ICESat-2 ATL08 HDF5 file to a specified spatial extent. Only segment-level datasets within the ATL08 beam groups are clipped; all metadata, orbit information, and ancillary groups are preserved unchanged. This function is the bounding-box-based counterpart to geometry-based clipping functions.
## S4 method for signature 'icesat2.atl08_h5,numeric' clip(x, clip_obj, ...)## S4 method for signature 'icesat2.atl08_h5,numeric' clip(x, clip_obj, ...)
x |
An |
clip_obj |
Bounding extent used for clipping. Supported inputs:
|
... |
Additional arguments:
|
The function performs the following steps:
Copies file-level attributes and all requested non-beam groups.
Clips beam-level datasets based on latitude/longitude coordinates and the supplied spatial extent.
Reconstructs dependent indexing datasets (e.g., photon index ranges) when necessary to maintain valid ATL08 structure.
The resulting HDF5 file remains fully compliant with the ATL08 product structure, but contains only data within the specified bounding extent.
An S4 object of class icesat2.atl08_h5 representing
the clipped ATL08 HDF5 file.
# ATL08 file path atl08_path <- system.file("extdata", "atl08_clip.h5", package = "ICESat2VegR" ) # Read ATL08 data atl08_h5 <- ATL08_read(atl08_path) # Bounding rectangle coordinates (ul_lat, ul_lon, lr_lat, lr_lon) ul_lon <- -106.5723 lr_lon <- -106.5693 lr_lat <- 41.533 ul_lat <- 41.537 # Clip ATL08 data using the bounding extent atl08_clip <- ATL08_h5_clipBox( atl08_h5, output = tempfile(fileext = ".h5"), clip_obj = c(ul_lat, ul_lon, lr_lat, lr_lon) ) close(atl08_h5) close(atl08_clip)# ATL08 file path atl08_path <- system.file("extdata", "atl08_clip.h5", package = "ICESat2VegR" ) # Read ATL08 data atl08_h5 <- ATL08_read(atl08_path) # Bounding rectangle coordinates (ul_lat, ul_lon, lr_lat, lr_lon) ul_lon <- -106.5723 lr_lon <- -106.5693 lr_lat <- 41.533 ul_lat <- 41.537 # Clip ATL08 data using the bounding extent atl08_clip <- ATL08_h5_clipBox( atl08_h5, output = tempfile(fileext = ".h5"), clip_obj = c(ul_lat, ul_lon, lr_lat, lr_lon) ) close(atl08_h5) close(atl08_clip)
Clips an ICESat-2 ATL08 HDF5 file to a specified spatial extent. Only segment-level datasets within the ATL08 beam groups are clipped; all metadata, orbit information, and ancillary groups are preserved unchanged. This function is the bounding-box-based counterpart to geometry-based clipping functions.
## S4 method for signature 'icesat2.atl08_h5,SpatExtent' clip(x, clip_obj, ...)## S4 method for signature 'icesat2.atl08_h5,SpatExtent' clip(x, clip_obj, ...)
x |
An |
clip_obj |
Bounding extent used for clipping. Supported inputs:
|
... |
Additional arguments:
|
The function performs the following steps:
Copies file-level attributes and all requested non-beam groups.
Clips beam-level datasets based on latitude/longitude coordinates and the supplied spatial extent.
Reconstructs dependent indexing datasets (e.g., photon index ranges) when necessary to maintain valid ATL08 structure.
The resulting HDF5 file remains fully compliant with the ATL08 product structure, but contains only data within the specified bounding extent.
An S4 object of class icesat2.atl08_h5 representing
the clipped ATL08 HDF5 file.
# ATL08 file path atl08_path <- system.file("extdata", "atl08_clip.h5", package = "ICESat2VegR" ) # Read ATL08 data atl08_h5 <- ATL08_read(atl08_path) # Bounding rectangle coordinates (ul_lat, ul_lon, lr_lat, lr_lon) ul_lon <- -106.5723 lr_lon <- -106.5693 lr_lat <- 41.533 ul_lat <- 41.537 # Clip ATL08 data using the bounding extent atl08_clip <- ATL08_h5_clipBox( atl08_h5, output = tempfile(fileext = ".h5"), clip_obj = c(ul_lat, ul_lon, lr_lat, lr_lon) ) close(atl08_h5) close(atl08_clip)# ATL08 file path atl08_path <- system.file("extdata", "atl08_clip.h5", package = "ICESat2VegR" ) # Read ATL08 data atl08_h5 <- ATL08_read(atl08_path) # Bounding rectangle coordinates (ul_lat, ul_lon, lr_lat, lr_lon) ul_lon <- -106.5723 lr_lon <- -106.5693 lr_lat <- 41.533 ul_lat <- 41.537 # Clip ATL08 data using the bounding extent atl08_clip <- ATL08_h5_clipBox( atl08_h5, output = tempfile(fileext = ".h5"), clip_obj = c(ul_lat, ul_lon, lr_lat, lr_lon) ) close(atl08_h5) close(atl08_clip)
Closing files will avoid locking HDF5 ATL03 files.
Closing files will avoid locking HDF5 files.
## S4 method for signature 'icesat2.h5' close(con, ...) ## S4 method for signature 'icesat2.predict_h5' close(con, ...)## S4 method for signature 'icesat2.h5' close(con, ...) ## S4 method for signature 'icesat2.predict_h5' close(con, ...)
con |
An object of class icesat2.predict_h5 |
... |
Inherited from base, not used |
Closing ensures the data is actually flushed (saved) to the dataset also it releases the lock from the file.
## S3 method for class 'GDALDataset' close(con, ...)## S3 method for class 'GDALDataset' close(con, ...)
con |
GDALDataset to be closed. |
... |
not used, inherited from generic close function. |
Closes the HDF5 file pointer to release resources
## S3 method for class 'icesat2.predict_h5' close(con, ...)## S3 method for class 'icesat2.predict_h5' close(con, ...)
con |
The HDF5 file pointer of class |
... |
Additional parameters inherited from generic |
Nothing, just closes the HDF5 file pointer
Create a new raster file based on specified data. It will output a *.tif file.
createDataset( raster_path, nbands, datatype, projstring, lr_lat, ul_lat, ul_lon, lr_lon, res, nodata, co = c("TILED=YES", "BLOCKXSIZE=512", "BLOCKYSIZE=512", "COMPRESSION=LZW") )createDataset( raster_path, nbands, datatype, projstring, lr_lat, ul_lat, ul_lon, lr_lon, res, nodata, co = c("TILED=YES", "BLOCKXSIZE=512", "BLOCKYSIZE=512", "COMPRESSION=LZW") )
raster_path |
Character. The output path for the raster data |
nbands |
Integer. Number of bands. Default 1. |
datatype |
GDALDataType. The GDALDataType to use for the raster, use (GDALDataType$) to find the options. Default GDALDataType$GDT_Float64 |
projstring |
The projection string, either proj or WKT is accepted. |
lr_lat |
Numeric. The lower right latitude. |
ul_lat |
Numeric. The upper left latitude. |
ul_lon |
Numeric. The upper left longitude. |
lr_lon |
Numeric. The lower right longitude. |
res |
Numeric. The resolution of the output raster |
nodata |
Numeric. The no data value for the raster. Default 0. |
co |
CharacterVector. A CharacterVector of creation options for GDAL. Default NULL |
An object from GDALDataset R6 class.
# Parameters raster_path <- tempfile(fileext = ".tif") ul_lat <- -15 ul_lon <- -45 lr_lat <- -25 lr_lon <- -35 res <- c(0.01, -0.01) datatype <- GDALDataType$GDT_Int32 nbands <- 1 projstring <- "EPSG:4326" nodata <- -1 co <- c("TILED=YES", "BLOCKXSIZE=512", "BLOCKYSIZE=512", "COMPRESSION=LZW") # Create a new raster dataset ds <- createDataset( raster_path = raster_path, nbands = nbands, datatype = datatype, projstring = projstring, lr_lat = lr_lat, ul_lat = ul_lat, ul_lon = ul_lon, lr_lon = lr_lon, res = res, nodata = nodata, co = co ) # Get the GDALRasterBand for ds band <- ds[[1]] # Set some dummy values band[[0, 0]] <- 1:(512 * 512) ds$Close()# Parameters raster_path <- tempfile(fileext = ".tif") ul_lat <- -15 ul_lon <- -45 lr_lat <- -25 lr_lon <- -35 res <- c(0.01, -0.01) datatype <- GDALDataType$GDT_Int32 nbands <- 1 projstring <- "EPSG:4326" nodata <- -1 co <- c("TILED=YES", "BLOCKXSIZE=512", "BLOCKYSIZE=512", "COMPRESSION=LZW") # Create a new raster dataset ds <- createDataset( raster_path = raster_path, nbands = nbands, datatype = datatype, projstring = projstring, lr_lat = lr_lat, ul_lat = ul_lat, ul_lon = ul_lon, lr_lon = lr_lon, res = res, nodata = nodata, co = co ) # Get the GDALRasterBand for ds band <- ds[[1]] # Set some dummy values band[[0, 0]] <- 1:(512 * 512) ds$Close()
.netrc File for NASA Earthdata LoginCreates (if necessary) and configures a .netrc file containing
credentials for NASA Earthdata Login (<urs.earthdata.nasa.gov>).
This file is required for authenticated downloads from Earthdata
services (e.g., via earthaccess, curl, wget, or other clients).
earthdata_login(output_dir = "~")earthdata_login(output_dir = "~")
output_dir |
Character. Directory where the |
The function will:
Use an existing .netrc file if valid credentials are already present
Otherwise prompt the user securely for credentials
Or read credentials from environment variables:
EARTHDATA_USERNAME
EARTHDATA_PASSWORD
Set the NETRC environment variable for the active Python session
Credentials are written in standard .netrc format:
machine urs.earthdata.nasa.gov login <username> password <password>
If credentials are not found in environment variables and the package getPass is available, the user is prompted securely. Otherwise, an error is thrown.
The function also updates the NETRC environment variable inside
the active Python session via reticulate, ensuring compatibility
with Python libraries such as earthaccess.
Character string. The normalized path to the .netrc file
being used.
earth-engine-api python reticulate moduleThe pointer to the earth-engine-api python reticulate module
eeee
https://developers.google.com/earth-engine/apidocs
Creates a Google Earth Engine image stack that combines:
Annual satellite embeddings from
GOOGLE/SATELLITE_EMBEDDING/V1/ANNUAL (AlphaEarth).
Terrain derivatives (elevation, slope, aspect) from USGS 3DEP or NASADEM as fallbacks.
Optional longitude/latitude bands from ee$Image$pixelLonLat().
The embedding collection is filtered to the specified year range and AOI,
reduced using a pixel-wise median, and clipped to the AOI. Terrain data
are reprojected to a target scale (default 30 m).
Geographic coverage limitation: The primary terrain sources (USGS 3DEP 1 m and 10 m) cover only the contiguous United States, Alaska, and Hawaii. For areas outside the US, the function falls back to NASADEM, which provides global coverage but at coarser resolution (~30 m). For best terrain accuracy, this function is recommended for use within the United States.
Authentication: This function requires an active Google Earth
Engine session. Authenticate using ICESat2VegR::ee_initialize()
before calling this function.
ee_build_AlphaEarth_embedding_terrain_stack( geom, start_year, end_year, mask_outside = TRUE, terrain_scale = 30, multiply_slope_aspect_by10 = TRUE, add_lonlat = TRUE )ee_build_AlphaEarth_embedding_terrain_stack( geom, start_year, end_year, mask_outside = TRUE, terrain_scale = 30, multiply_slope_aspect_by10 = TRUE, add_lonlat = TRUE )
geom |
AOI geometry. Can be:
The geometry is internally converted to an Earth Engine geometry via an internal helper. |
start_year, end_year
|
Integer (or coercible to integer). Inclusive year range used to filter the AlphaEarth annual embedding collection. |
mask_outside |
Logical. If |
terrain_scale |
Numeric. Target scale in meters used to reproject
the terrain data. Default is |
multiply_slope_aspect_by10 |
Logical. If |
add_lonlat |
Logical. If |
The terrain source is chosen in the following order:
USGS 3DEP 1 m (USGS/3DEP/1m), if available for the AOI.
USGS 3DEP 10 m (USGS/3DEP/10m).
NASADEM (NASA/NASADEM_HGT/001) as a global fallback.
All terrain layers are clipped to the AOI and reprojected to
EPSG:4326 with the requested terrain_scale.
A Python ee$Image object containing:
The median annual AlphaEarth embedding bands.
elevation, slope, and aspect bands.
Optional lon and lat bands.
## Not run: # Requires Google Earth Engine authentication # Note: USGS 3DEP terrain data covers the United States only. # Outside the US, NASADEM is used as a global fallback. Sys.setenv(EE_PROJECT = "your-ee-project-id") ICESat2VegR::ee_initialize() library(sf) aoi <- st_as_sfc(st_bbox(c( xmin = -82.4, xmax = -82.2, ymin = 29.6, ymax = 29.8 ), crs = 4326)) ee_geom <- ICESat2VegR:::.as_ee_geom(aoi) # Build the embedding + terrain stack for 2025 predictors <- ee_build_AlphaEarth_embedding_terrain_stack( geom = ee_geom, start_year = 2025, end_year = 2025 ) # Visualize RGB embedding bands using leaflet predictors_rgb <- predictors$select(c("A00", "A20", "A40")) centroid_lon <- mean(terra::ext(terra::vect(aoi))[c(1, 2)]) centroid_lat <- mean(terra::ext(terra::vect(aoi))[c(3, 4)]) leaflet::leaflet() |> ICESat2VegR::addEEImage( predictors_rgb, bands = c("A00", "A20", "A40"), group = "RGB Embedding", min = -0.2, max = 0.2 ) |> leaflet::setView( lng = centroid_lon, lat = centroid_lat, zoom = 15 ) |> leaflet::addLayersControl( overlayGroups = "RGB Embedding", options = leaflet::layersControlOptions(collapsed = FALSE) ) ## End(Not run)## Not run: # Requires Google Earth Engine authentication # Note: USGS 3DEP terrain data covers the United States only. # Outside the US, NASADEM is used as a global fallback. Sys.setenv(EE_PROJECT = "your-ee-project-id") ICESat2VegR::ee_initialize() library(sf) aoi <- st_as_sfc(st_bbox(c( xmin = -82.4, xmax = -82.2, ymin = 29.6, ymax = 29.8 ), crs = 4326)) ee_geom <- ICESat2VegR:::.as_ee_geom(aoi) # Build the embedding + terrain stack for 2025 predictors <- ee_build_AlphaEarth_embedding_terrain_stack( geom = ee_geom, start_year = 2025, end_year = 2025 ) # Visualize RGB embedding bands using leaflet predictors_rgb <- predictors$select(c("A00", "A20", "A40")) centroid_lon <- mean(terra::ext(terra::vect(aoi))[c(1, 2)]) centroid_lat <- mean(terra::ext(terra::vect(aoi))[c(3, 4)]) leaflet::leaflet() |> ICESat2VegR::addEEImage( predictors_rgb, bands = c("A00", "A20", "A40"), group = "RGB Embedding", min = -0.2, max = 0.2 ) |> leaflet::setView( lng = centroid_lon, lat = centroid_lat, zoom = 15 ) |> leaflet::addLayersControl( overlayGroups = "RGB Embedding", options = leaflet::layersControlOptions(collapsed = FALSE) ) ## End(Not run)
Constructs a multi-source ancillary stack in Google Earth Engine composed of:
Optical features from the Harmonized Landsat and Sentinel-2 (HLS) product, including spectral bands, vegetation indices, and spectral unmixing fractions.
C-band SAR backscatter and radar-based indices from Sentinel-1C GRD.
Terrain variables (elevation, slope, aspect) from a NASA DEM.
Neighborhood statistics (mean, min, max, stdDev) computed over a 3x3 kernel for HLS and terrain bands.
GLCM texture metrics computed from scaled HLS reflectance bands.
The final stack contains 244 bands covering spectral, radar, terrain, neighborhood, and texture features.
Authentication: This function requires an active Google Earth
Engine session. Authenticate using ICESat2VegR::ee_initialize()
before calling this function.
ee_build_hls_s1c_terrain_stack( x, start_date, end_date, cloud_max = 10, buffer_m = 30, hls_collection_id = c("NASA/HLS/HLSS30/v002", "NASA/HLS/HLSL30/v002") )ee_build_hls_s1c_terrain_stack( x, start_date, end_date, cloud_max = 10, buffer_m = 30, hls_collection_id = c("NASA/HLS/HLSS30/v002", "NASA/HLS/HLSL30/v002") )
x |
Spatial input defining the area of interest. Can be:
|
start_date |
character. Start date of the temporal filter
in |
end_date |
character. End date of the temporal filter
in |
cloud_max |
numeric. Maximum allowed cloud coverage percentage
for HLS scenes. Default is |
buffer_m |
numeric. Buffer distance in meters applied to the AOI
bounding box before filtering and clipping. Default is |
hls_collection_id |
character vector. HLS collection IDs to try
in order until one has data for the AOI and date range. Default tries
Sentinel-2 HLS first, then Landsat HLS as fallback:
|
The HLS collection is selected automatically from hls_collection_id
by trying each ID in order and using the first one that contains scenes
for the specified AOI and date range. By default, Sentinel-2 HLS
(NASA/HLS/HLSS30/v002) is tried first, followed by Landsat HLS
(NASA/HLS/HLSL30/v002).
Cloud masks are applied using the Fmask band before computing
the median mosaic. Sentinel-1C is filtered by VV/VH polarization and
IW instrument mode, sorted by acquisition time, and reduced using
ee$Reducer$firstNonNull().
Neighborhood statistics (mean, min, max, stdDev) are computed over a fixed 3x3 kernel for HLS and terrain bands. GLCM texture metrics are computed from scaled (x10000) HLS reflectance bands using a window size of 3.
Returns an ee$Image object containing 244 bands:
HLS reflectance bands and vegetation indices (blue, green, red, nir, swir1, swir2, ndvi, kndvi, evi, savi, msavi, f_soil, f_veg, f_water, sri, ndwi, gci, wdrvi, gvmi, cvi, cmr).
Sentinel-1C SAR bands and radar indices (vv, vh, rvi, copol, copol2, copol3).
Terrain bands (elevation, slope, aspect).
Neighborhood statistics (mean, min, max, stdDev) for HLS and terrain bands.
GLCM texture metrics for HLS reflectance bands.
## Not run: # Requires Google Earth Engine authentication Sys.setenv(EE_PROJECT = "your-ee-project-id") ICESat2VegR::ee_initialize() library(sf) library(terra) # AOI in Ocala National Forest, Florida aoi <- st_as_sfc(st_bbox(c( xmin = -81.8, xmax = -81.6, ymin = 29.1, ymax = 29.3 ), crs = 4326)) # Build the full ancillary stack (244 bands) stack <- ee_build_hls_s1c_terrain_stack( x = aoi, start_date = "2024-03-01", end_date = "2024-06-01", cloud_max = 10 ) # Check available bands names(stack) # Compute AOI centroid for map view centroid_lon <- mean(terra::ext(terra::vect(aoi))[c(1, 2)]) centroid_lat <- mean(terra::ext(terra::vect(aoi))[c(3, 4)]) # Visualize true color RGB leaflet::leaflet() |> leaflet::addProviderTiles("Esri.WorldImagery") |> ICESat2VegR::addEEImage( stack$select(c("red", "green", "blue")), bands = c("red", "green", "blue"), group = "True Color", min = 0, max = 0.3 ) |> leaflet::addControl( html = "<b>True Color</b><br>red / green / blue", position = "bottomleft" ) |> leaflet::setView(lng = centroid_lon, lat = centroid_lat, zoom = 11) |> leaflet::addLayersControl( overlayGroups = "True Color", options = leaflet::layersControlOptions(collapsed = FALSE) ) # Visualize false color (nir, red, green) leaflet::leaflet() |> leaflet::addProviderTiles("Esri.WorldImagery") |> ICESat2VegR::addEEImage( stack$select(c("nir", "red", "green")), bands = c("nir", "red", "green"), group = "False Color", min = 0, max = 0.3 ) |> leaflet::addControl( html = "<b>False Color</b><br>nir / red / green", position = "bottomleft" ) |> leaflet::setView(lng = centroid_lon, lat = centroid_lat, zoom = 11) |> leaflet::addLayersControl( overlayGroups = "False Color", options = leaflet::layersControlOptions(collapsed = FALSE) ) # Visualize NDVI leaflet::leaflet() |> leaflet::addProviderTiles("Esri.WorldImagery") |> ICESat2VegR::addEEImage( stack$select("ndvi"), bands = "ndvi", group = "NDVI", min = 0, max = 0.8 ) |> leaflet::addControl( html = "<b>NDVI</b>", position = "bottomleft" ) |> leaflet::setView(lng = centroid_lon, lat = centroid_lat, zoom = 11) |> leaflet::addLayersControl( overlayGroups = "NDVI", options = leaflet::layersControlOptions(collapsed = FALSE) ) # Force Landsat HLS only stack_landsat <- ee_build_hls_s1c_terrain_stack( x = aoi, start_date = "2024-03-01", end_date = "2024-06-01", hls_collection_id = "NASA/HLS/HLSL30/v002" ) names(stack_landsat) ## End(Not run)## Not run: # Requires Google Earth Engine authentication Sys.setenv(EE_PROJECT = "your-ee-project-id") ICESat2VegR::ee_initialize() library(sf) library(terra) # AOI in Ocala National Forest, Florida aoi <- st_as_sfc(st_bbox(c( xmin = -81.8, xmax = -81.6, ymin = 29.1, ymax = 29.3 ), crs = 4326)) # Build the full ancillary stack (244 bands) stack <- ee_build_hls_s1c_terrain_stack( x = aoi, start_date = "2024-03-01", end_date = "2024-06-01", cloud_max = 10 ) # Check available bands names(stack) # Compute AOI centroid for map view centroid_lon <- mean(terra::ext(terra::vect(aoi))[c(1, 2)]) centroid_lat <- mean(terra::ext(terra::vect(aoi))[c(3, 4)]) # Visualize true color RGB leaflet::leaflet() |> leaflet::addProviderTiles("Esri.WorldImagery") |> ICESat2VegR::addEEImage( stack$select(c("red", "green", "blue")), bands = c("red", "green", "blue"), group = "True Color", min = 0, max = 0.3 ) |> leaflet::addControl( html = "<b>True Color</b><br>red / green / blue", position = "bottomleft" ) |> leaflet::setView(lng = centroid_lon, lat = centroid_lat, zoom = 11) |> leaflet::addLayersControl( overlayGroups = "True Color", options = leaflet::layersControlOptions(collapsed = FALSE) ) # Visualize false color (nir, red, green) leaflet::leaflet() |> leaflet::addProviderTiles("Esri.WorldImagery") |> ICESat2VegR::addEEImage( stack$select(c("nir", "red", "green")), bands = c("nir", "red", "green"), group = "False Color", min = 0, max = 0.3 ) |> leaflet::addControl( html = "<b>False Color</b><br>nir / red / green", position = "bottomleft" ) |> leaflet::setView(lng = centroid_lon, lat = centroid_lat, zoom = 11) |> leaflet::addLayersControl( overlayGroups = "False Color", options = leaflet::layersControlOptions(collapsed = FALSE) ) # Visualize NDVI leaflet::leaflet() |> leaflet::addProviderTiles("Esri.WorldImagery") |> ICESat2VegR::addEEImage( stack$select("ndvi"), bands = "ndvi", group = "NDVI", min = 0, max = 0.8 ) |> leaflet::addControl( html = "<b>NDVI</b>", position = "bottomleft" ) |> leaflet::setView(lng = centroid_lon, lat = centroid_lat, zoom = 11) |> leaflet::addLayersControl( overlayGroups = "NDVI", options = leaflet::layersControlOptions(collapsed = FALSE) ) # Force Landsat HLS only stack_landsat <- ee_build_hls_s1c_terrain_stack( x = aoi, start_date = "2024-03-01", end_date = "2024-06-01", hls_collection_id = "NASA/HLS/HLSL30/v002" ) names(stack_landsat) ## End(Not run)
One-shot task status check
ee_check_task_status(task, quiet = TRUE)ee_check_task_status(task, quiet = TRUE)
task |
EE |
quiet |
Logical; if |
The task status (list).
Initializes the Google Earth Engine API Initialize Earth Engine for this R session
ee_initialize( project = Sys.getenv("EE_PROJECT", unset = NA), service_account = NULL, keyfile = NULL, quiet = FALSE, force_auth = FALSE )ee_initialize( project = Sys.getenv("EE_PROJECT", unset = NA), service_account = NULL, keyfile = NULL, quiet = FALSE, force_auth = FALSE )
project |
Character. GCP Project ID (e.g., "ice-map-2025") or a numeric project number. If NULL/NA, falls back to Sys.getenv("EE_PROJECT"). |
service_account |
Optional service account email (use with |
keyfile |
Path to service-account JSON key (required if |
quiet |
Logical. Suppress messages. |
force_auth |
Logical. If TRUE, perform OAuth before Initialize(). |
TRUE on success; FALSE otherwise (invisibly).
Earth Engine server numberCreates an Earth Engine server number
ee_number(x)ee_number(x)
x |
the number to convert to Earth Engine's number. |
The Earth Engine number
https://developers.google.com/earth-engine/apidocs/ee-number
Convert an EE Rectangle to an sf polygon (EPSG:4326)
ee_rect_to_sf(aoi)ee_rect_to_sf(aoi)
aoi |
An |
An sf polygon with CRS EPSG:4326.
Converts a terra::ext, terra::SpatVector, or terra::SpatRaster
into a Google Earth Engine geometry of type ee$Geometry$Rectangle.
The resulting rectangle is always expressed in geographic coordinates
(EPSG:4326), regardless of the input object's projection.
This function is mainly used internally to standardize spatial inputs before Earth Engine requests (e.g., filtering, clipping, or exporting data).
ext_to_ee(x)ext_to_ee(x)
x |
A spatial object of class terra::ext, terra::SpatVector, or terra::SpatRaster. Its extent is extracted and converted into an Earth Engine bounding box. |
A Python object representing ee$Geometry$Rectangle, suitable for use
with Earth Engine Python API functions accessed via reticulate.
## Not run: library(terra) # Create an extent over Gainesville, FL bb <- ext(c(-82.4, -82.2, 29.6, 29.8)) # Convert to EE geometry aoi <- ext_to_ee(bb) ## End(Not run)## Not run: library(terra) # Create an extent over Gainesville, FL bb <- ext(c(-82.4, -82.2, 29.6, 29.8)) # Convert to EE geometry aoi <- ext_to_ee(bb) ## End(Not run)
Given a geometry with point samples and images from Earth Engine retrieve the point geometry with values for the images
extract(stack, geom, scale)extract(stack, geom, scale)
stack |
A single image or a vector/list of images from Earth Engine. |
geom |
A geometry from |
scale |
The scale in meters for the extraction (image resolution). |
An ee.FeatureCollection with the properties extracted from the stack of images from ee.
Computes RMSE (absolute and relative), MAE (absolute and relative),
bias (absolute and relative), Pearson correlation (r), and adjusted from a
linear fit between predicted and observed values. Optionally draws a 1:1 plot
with the regression line.
fit_metrics( observed, predicted, plotstat = FALSE, legend = "topleft", unit = "", ... )fit_metrics( observed, predicted, plotstat = FALSE, legend = "topleft", unit = "", ... )
observed |
Numeric vector of observed values. |
predicted |
Numeric vector of predicted values (same length/order as |
plotstat |
Logical; if TRUE, draws a 1:1 plot with the regression line. Default: FALSE. |
legend |
Character position for the plot legend (e.g., "topleft"). Default: "topleft". |
unit |
Character indicating the unit for RMSE/MAE/Bias (e.g., "Mg/ha"). Default: "". |
... |
Additional arguments passed to |
A data.frame with rows for rmse, rmseR (%), mae, maeR (%),
bias, biasR (%), r, and adj_r2.
observed <- c(178, 33, 60, 80, 104, 204, 146) predicted <- c(184, 28.5, 55, 85, 105, 210, 155) fit_metrics(observed, predicted, plotstat = TRUE, legend = "topleft", unit = "Mg/ha", xlab = "Observed AGBD (Mg/ha)", ylab = "Predicted AGBD (Mg/ha)", pch = 16)observed <- c(178, 33, 60, 80, 104, 204, 146) predicted <- c(184, 28.5, 55, 85, 105, 210, 155) fit_metrics(observed, predicted, plotstat = TRUE, legend = "topleft", unit = "Mg/ha", xlab = "Observed AGBD (Mg/ha)", ylab = "Predicted AGBD (Mg/ha)", pch = 16)
fit_model() trains a Random Forest regression model and optionally
evaluates it via LOOCV, K-fold CV, a train/test split, or bootstrap OOB
estimation. It can also tune core RF hyperparameters and shows progress
bars for long-running loops.
fit_model( x, y, rf_args = list(ntree = 500, mtry = NULL, nodesize = 5, sampsize = NULL), test = list(method = "none", k = 5, test_size = 0.3, seed = NULL, folds = NULL, iterations = 200, correction = FALSE), tune = list(enable = FALSE, search = "grid", grid = NULL, n_random = 20, seed = NULL), verbose = TRUE, list_test_models = TRUE )fit_model( x, y, rf_args = list(ntree = 500, mtry = NULL, nodesize = 5, sampsize = NULL), test = list(method = "none", k = 5, test_size = 0.3, seed = NULL, folds = NULL, iterations = 200, correction = FALSE), tune = list(enable = FALSE, search = "grid", grid = NULL, n_random = 20, seed = NULL), verbose = TRUE, list_test_models = TRUE )
x |
A data.frame of predictors (rows = samples, cols = features). |
y |
A numeric vector of responses, |
rf_args |
A named list of base Random Forest arguments used for all fits (full-data fit and each resample). Elements:
|
test |
A named list configuring evaluation:
|
tune |
A named list configuring hyperparameter search on the training subset for each fit:
|
verbose |
Logical (default |
list_test_models |
Logical (default |
Tuning minimizes OOB MSE for each candidate configuration on the current
training subset and then refits the model using the best settings.
When test$method = "bootstrap" and correction = TRUE, the .632 corrected
RMSE is reported while keeping other OOB statistics unchanged.
A list with:
rf
Final RF arguments used for the full-data fit (after tuning).
(data.frame or NULL) tuning results sorted by OOB MSE.
Echo of test configuration (with resolved values).
randomForest object fit on the full dataset (or train subset for split).
Numeric vector of in-sample predictions from the full-data fit.
data.frame of training statistics (RMSE, Bias, %RMSE, %Bias, r, r2).
(data.frame or NULL) test-set or OOF statistics depending on method.
(numeric) LOOCV predictions (for method = "loocv").
(numeric) K-fold OOF predictions (for method = "k-fold").
(integer) indices for method = "split".
(numeric) predictions for train/test in split.
(numeric) OOB mean prediction per observation in bootstrap.
(list or NULL) models fitted per resample/fold/iteration when list_test_models=TRUE.
Optionally tune RF hyperparameters on the current training subset
(or on full data when test$method = "none").
Always fit a model on the full dataset (model and fitted_full).
If a testing method is requested, refit on resampled training folds and compute out-of-fold predictions to summarize generalization performance.
Uses utils::txtProgressBar(); disable with verbose = FALSE. The internal
helper is lightweight and has no external dependencies.
randomForest::randomForest(), stats::lm(), stats::cor()
set.seed(42) n <- 200 x <- data.frame(NDVI = runif(n, 0.2, 0.9), EVI = runif(n, 0.1, 0.8), NBR = runif(n, -0.5, 0.9), SLP = runif(n, 0, 30)) y <- with(x, 5 + 20*NDVI + 10*EVI^1.5 - 0.05*SLP + rnorm(n, 0, 2)) # Full-data fit (no resampling) fit_none <- fit_model(x, y, rf_args = list(ntree = 400, mtry = 2)) fit_none$stats_train # LOOCV fit_loocv <- fit_model(x, y, test = list(method = "loocv")) fit_loocv$stats_test # 5-fold CV fit_k_fold <- fit_model(x, y, test = list(method = "k-fold", k = 5, seed = 42)) fit_k_fold$stats_test # Train/Test split fit_split <- fit_model(x, y, test = list(method = "split", test_size = 0.25, seed = 42)) fit_split$stats_test # Bootstrap (with tuning and .632 correction) ntree <- 400 iterations <- 300 fit_boot <- fit_model( x, y, rf_args = list(ntree = ntree), test = list(method = "bootstrap", iterations = iterations, correction = TRUE), tune = list(enable = TRUE, search = "random", n_random = 12) ) # K-fold CV with saved models fit_k <- fit_model(x, y, test = list(method = "k-fold", k = 5, seed = 42), list_test_models = TRUE) length(fit_k$models_test) # one model per foldset.seed(42) n <- 200 x <- data.frame(NDVI = runif(n, 0.2, 0.9), EVI = runif(n, 0.1, 0.8), NBR = runif(n, -0.5, 0.9), SLP = runif(n, 0, 30)) y <- with(x, 5 + 20*NDVI + 10*EVI^1.5 - 0.05*SLP + rnorm(n, 0, 2)) # Full-data fit (no resampling) fit_none <- fit_model(x, y, rf_args = list(ntree = 400, mtry = 2)) fit_none$stats_train # LOOCV fit_loocv <- fit_model(x, y, test = list(method = "loocv")) fit_loocv$stats_test # 5-fold CV fit_k_fold <- fit_model(x, y, test = list(method = "k-fold", k = 5, seed = 42)) fit_k_fold$stats_test # Train/Test split fit_split <- fit_model(x, y, test = list(method = "split", test_size = 0.25, seed = 42)) fit_split$stats_test # Bootstrap (with tuning and .632 correction) ntree <- 400 iterations <- 300 fit_boot <- fit_model( x, y, rf_args = list(ntree = ntree), test = list(method = "bootstrap", iterations = iterations, correction = TRUE), tune = list(enable = TRUE, search = "random", n_random = 12) ) # K-fold CV with saved models fit_k <- fit_model(x, y, test = list(method = "k-fold", k = 5, seed = 42), list_test_models = TRUE) length(fit_k$models_test) # one model per fold
Calculate raster values based on a formula
formulaCalculate(formula, data, updateBand)formulaCalculate(formula, data, updateBand)
formula |
Formula. A formula to apply to the RasterBands from |
data |
List. A named list with the used variables in the textual formula |
updateBand |
GDALRasterBand. The GDALRasterBand which will be updated with the calculated values. |
Nothing, it just updates the band of interest.
# Parameters raster_path <- file.path(tempdir(), "output.tif") ul_lat <- -15 ul_lon <- -45 lr_lat <- -25 lr_lon <- -35 res <- c(0.01, -0.01) datatype <- GDALDataType$GDT_Int32 nbands <- 2 projstring <- "EPSG:4326" nodata <- -1 co <- c("TILED=YES", "BLOCKXSIZE=512", "BLOCKYSIZE=512", "COMPRESSION=LZW") # Create a new raster dataset ds <- createDataset( raster_path = raster_path, nbands = nbands, datatype = datatype, projstring = projstring, lr_lat = lr_lat, ul_lat = ul_lat, ul_lon = ul_lon, lr_lon = lr_lon, res = res, nodata = nodata, co = co ) # Get the GDALRasterBand for ds band <- ds[[1]] # The updateBand can be the same # using a different one just for testing updateBand <- ds[[2]] # Set some dummy values band[[0, 0]] <- 1:(512 * 512) # Calculate the double - 10 formulaCalculate( formula = ~ x * 2 - 10, data = list(x = band), updateBand = updateBand ) ds$Close()# Parameters raster_path <- file.path(tempdir(), "output.tif") ul_lat <- -15 ul_lon <- -45 lr_lat <- -25 lr_lon <- -35 res <- c(0.01, -0.01) datatype <- GDALDataType$GDT_Int32 nbands <- 2 projstring <- "EPSG:4326" nodata <- -1 co <- c("TILED=YES", "BLOCKXSIZE=512", "BLOCKYSIZE=512", "COMPRESSION=LZW") # Create a new raster dataset ds <- createDataset( raster_path = raster_path, nbands = nbands, datatype = datatype, projstring = projstring, lr_lat = lr_lat, ul_lat = ul_lat, ul_lon = ul_lon, lr_lon = lr_lon, res = res, nodata = nodata, co = co ) # Get the GDALRasterBand for ds band <- ds[[1]] # The updateBand can be the same # using a different one just for testing updateBand <- ds[[2]] # Set some dummy values band[[0, 0]] <- 1:(512 * 512) # Calculate the double - 10 formulaCalculate( formula = ~ x * 2 - 10, data = list(x = band), updateBand = updateBand ) ds$Close()
Wrapping class for GDALDataset C++ API exporting GetRasterBand, GetRasterXSize, GetRasterYSize
GDALDataset$new()Create a new raster file based on specified data. It will output a *.tif file.
GDALDataset$new(ds)
dsGDALDatasetR pointer. Should not be used
datatypeGDALDataType. The GDALDataType to use for the raster, use (GDALDataType$) to find the options. Default GDALDataType$GDT_Float64
An object from GDALDataset R6 class.
GDALDataset$GetRasterBand()Function to retrieve the GDALRasterBand R6 Object.
GDALDataset$GetRasterBand(x)
xInteger. The band index, starting from 1 to number of bands.
An object of GDALRasterBand R6 class.
GDALDataset$GetRasterXSize()Get the width for the raster
GDALDataset$GetRasterXSize()
An integer indicating the raster width
GDALDataset$GetRasterYSize()Get the height for the raster
GDALDataset$GetRasterYSize()
An integer indicating the raster height
GDALDataset$Close()Closes the GDALDataset
GDALDataset$Close()
An integer indicating the raster width
GDALDataset$clone()The objects of this class are cloneable with this method.
GDALDataset$clone(deep = FALSE)
deepWhether to make a deep clone.
List of datatypes supported by the GDALDataset R6 class
GDALDataTypeGDALDataType
Function to open GDAL Dataset
GDALOpen(filename, readonly = TRUE)GDALOpen(filename, readonly = TRUE)
filename |
Character. The path to a GDAL dataset. |
readonly |
Logical. Flag to open a read only GDALDataset with GA_ReadOnly or GA_Update. Default TRUE. |
An R6 object of GDALDataset class.
ds_path <- system.file("extdata", "example.tif", package = "ICESat2VegR") ds <- GDALOpen(ds_path) ds$Close()ds_path <- system.file("extdata", "example.tif", package = "ICESat2VegR") ds <- GDALOpen(ds_path) ds$Close()
Wrapping class for GDALRasterBand C++ API exporting GetBlockXSize, GetBlockYSize, ReadBlock, WriteBlock for better IO speed.
GDALRasterBand$new()Creates a new GDALRasterBand
GDALRasterBand$new(band)
bandThe C++ pointer to the GDALRasterBandR object.
datatypeThe GDALDataType for this band
An object of GDALRasterBand R6 class
GDALRasterBand$ReadBlock()Efficiently reads a raster block
GDALRasterBand$ReadBlock(iXBlock, iYBlock)
iXBlockInteger. The i-th column block to access. The iXBlock will be offset
from the origin.
iYBlockInteger. The i-th row block to access. The iYBlock will be offset
from the origin.
The returned Vector will be single dimensional with the length
. If you use matrix(, ncol=BLOCKXSIZE)
the matrix returned will actually be transposed. You should either transpose it or you can
calculate the indices using
RawVector for GDALDataType$GDT_Byte, IntegerVector for int types and NumericVector for floating point types.
GDALRasterBand$WriteBlock()Efficiently writes a raster block
GDALRasterBand$WriteBlock(iXBlock, iYBlock, buffer)
iXBlockInteger. The i-th column block to write. The iXBlock will be
offset from the origin.
iYBlockInteger. The i-th row block to write. The iYBlock will be offset
from the origin.
bufferRawVector/IntegerVector/NumericVector depending on the GDALDataType.
This should be a 1D vector with size equal to raster
.
The returned Vector will be single dimensional with the length
.
If you use matrix(, ncol=BLOCKXSIZE) the matrix returned will actually be transposed.
You should either transpose it or you can calculate the indices using
.
Nothing
GDALRasterBand$GetBlockXSize()Get the block width
GDALRasterBand$GetBlockXSize()
An integer indicating block width
GDALRasterBand$GetBlockYSize()Get the block height
GDALRasterBand$GetBlockYSize()
An integer indicating block height
GDALRasterBand$GetXSize()Get the band width
GDALRasterBand$GetXSize()
An integer indicating band width
GDALRasterBand$CalculateStatistics()Calculate statistics for the GDALRasterBand
GDALRasterBand$CalculateStatistics()
nothing
GDALRasterBand$GetYSize()Get the band height
GDALRasterBand$GetYSize()
An integer indicating band height
GDALRasterBand$GetNoDataValue()Get band no data value
GDALRasterBand$GetNoDataValue()
Numeric indicating no data value
GDALRasterBand$GetRasterDataType()Get band datatype
GDALRasterBand$GetRasterDataType()
Numeric indicating the datatype
GDALRasterBand$clone()The objects of this class are cloneable with this method.
GDALRasterBand$clone(deep = FALSE)
deepWhether to make a deep clone.
This constructor must not be called at all, this is automatically called from GDALDataset$GetRasterBand function.
Get observations sampled within polygon features
geomSampling(size, geom, split_id = NULL, chainSampling = NULL)geomSampling(size, geom, split_id = NULL, chainSampling = NULL)
size |
numeric. The sample size per polygon feature. Either an integer
or a value between |
geom |
A |
split_id |
character. The attribute name in |
chainSampling |
optional. Chain with another sampling method. |
A icesat2_sampling_method-class object for use in
sample.
atl08_path <- system.file("extdata", "atl08_clip.h5", package = "ICESat2VegR") atl08_h5 <- ATL08_read(atl08_path = atl08_path) atl08_dt <- ATL08_seg_attributes_dt(atl08_h5) # Load polygon shapefile polygon_filepath <- system.file("extdata", "clip_geom.shp", package = "ICESat2VegR" ) polygon <- terra::vect(polygon_filepath) # Sample 2 observations per polygon feature set.seed(1) sampled <- ICESat2VegR::sample( atl08_dt, method = geomSampling(size = 2, geom = polygon, split_id = "id") ) head(sampled) close(atl08_h5)atl08_path <- system.file("extdata", "atl08_clip.h5", package = "ICESat2VegR") atl08_h5 <- ATL08_read(atl08_path = atl08_path) atl08_dt <- ATL08_seg_attributes_dt(atl08_h5) # Load polygon shapefile polygon_filepath <- system.file("extdata", "clip_geom.shp", package = "ICESat2VegR" ) polygon <- terra::vect(polygon_filepath) # Sample 2 observations per polygon feature set.seed(1) sampled <- ICESat2VegR::sample( atl08_dt, method = geomSampling(size = 2, geom = polygon, split_id = "id") ) head(sampled) close(atl08_h5)
Retrieve the Google Earth Engine image catalog id
get_catalog_id(id)get_catalog_id(id)
id |
character. The id retrieved from the data.table resulting from |
The catalog id to open within Google Earth Engine.
Retrieve Google Earth Engine's tile url for an Image or ImageCollection
getTileUrl(img)getTileUrl(img)
img |
The |
The url for the tile service.
ee.Image.glcmTexture
Computes texture metrics from the Gray Level Co-occurrence Matrix around each pixel of every band. The GLCM is a tabulation of how often different combinations of pixel brightness values (grey levels) occur in an image. It counts the number of times a pixel of value X lies next to a pixel of value Y, in a particular direction and distance. and then derives statistics from this tabulation.
glcmTexture(x, size = 1, kernel = NULL, average = TRUE)glcmTexture(x, size = 1, kernel = NULL, average = TRUE)
x |
The input image to calculate the texture on. |
size |
integer, default 1. The size of the neighborhood to include in each GLCM. |
kernel |
default NULL. A kernel specifying the x and y offsets over which to compute the GLCMs. A GLCM is computed for each pixel in the kernel that is non-zero, except the center pixel and as long as a GLCM hasn't already been computed for the same direction and distance. For example, if either or both of the east and west pixels are set, only 1 (horizontal) GLCM is computed. Kernels are scanned from left to right and top to bottom. The default is a 3x3 square, resulting in 4 GLCMs with the offsets (-1, -1), (0, -1), (1, -1) and (-1, 0). |
average |
logical, default TRUE. If true, the directional bands for each metric are averaged. |
This implementation computes the 14 GLCM metrics proposed by Haralick, and 4 additional metrics from Conners. Inputs are required to be integer valued.
The output consists of 18 bands per input band if directional averaging is on and 18 bands per directional pair in the kernel, if not:
ASM: f1, Angular Second Moment; measures the number of repeated pairs
CONTRAST: f2, Contrast; measures the local contrast of an image
CORR: f3, Correlation; measures the correlation between pairs of pixels
VAR: f4, Variance; measures how spread out the distribution of gray-levels is
IDM: f5, Inverse Difference Moment; measures the homogeneity
SAVG: f6, Sum Average
SVAR: f7, Sum Variance
SENT: f8, Sum Entropy
ENT: f9, Entropy. Measures the randomness of a gray-level distribution
DVAR: f10, Difference variance
DENT: f11, Difference entropy
IMCORR1: f12, Information Measure of Corr. 1
IMCORR2: f13, Information Measure of Corr. 2
MAXCORR: f14, Max Corr. Coefficient. (not computed)
DISS: Dissimilarity
INERTIA: Inertia
SHADE: Cluster Shade
PROM: Cluster prominence
Another Earth Engine image with bands described on details section.
More information can be found in the two papers: Haralick et. al, 'Textural Features for Image Classification', http://doi.org/10.1109/TSMC.1973.4309314 and Conners, et al, Segmentation of a high-resolution urban scene using texture operators', http://doi.org/10.1016/0734-189X(84)90197-X.
https://developers.google.com/earth-engine/apidocs/ee-image-glcmtexture
Get samples stratified by grid cells of specified size
gridSampling(size, grid_size, chainSampling = NULL)gridSampling(size, grid_size, chainSampling = NULL)
size |
numeric. The sample size per grid cell. Either an integer or
a value between |
grid_size |
numeric. The grid cell size in decimal degrees. |
chainSampling |
optional. Chain with another sampling method such as
|
A icesat2_sampling_method-class object for use in
sample.
atl08_path <- system.file("extdata", "atl08_clip.h5", package = "ICESat2VegR") atl08_h5 <- ATL08_read(atl08_path = atl08_path) atl08_dt <- ATL08_seg_attributes_dt(atl08_h5) # Sample 2 observations per 0.01 degree grid cell set.seed(1) sampled <- ICESat2VegR::sample( atl08_dt, method = gridSampling(size = 2, grid_size = 0.01) ) head(sampled) # Chain grid sampling with random sampling within each cell set.seed(1) sampled_chain <- ICESat2VegR::sample( atl08_dt, method = gridSampling( size = 2, grid_size = 0.01, chainSampling = randomSampling(2) ) ) head(sampled_chain) close(atl08_h5)atl08_path <- system.file("extdata", "atl08_clip.h5", package = "ICESat2VegR") atl08_h5 <- ATL08_read(atl08_path = atl08_path) atl08_dt <- ATL08_seg_attributes_dt(atl08_h5) # Sample 2 observations per 0.01 degree grid cell set.seed(1) sampled <- ICESat2VegR::sample( atl08_dt, method = gridSampling(size = 2, grid_size = 0.01) ) head(sampled) # Chain grid sampling with random sampling within each cell set.seed(1) sampled_chain <- ICESat2VegR::sample( atl08_dt, method = gridSampling( size = 2, grid_size = 0.01, chainSampling = randomSampling(2) ) ) head(sampled_chain) close(atl08_h5)
Class that represent custom segments created from ATL03 and ATL08 joined data
This class is actually just a wrap around the data.table, but it indicates
the output from ATL03_ATL08_segment_create(), which means the dataset will contain
the needed structure for computing value for the computing the stats with
ATL03_ATL08_compute_seg_attributes_dt_segStat()
Class for ATL03 attributes
data.table in the data.table package and
https://icesat-2.gsfc.nasa.gov/sites/default/files/page_files/ICESat2_ATL03_ATBD_r006.pdf
Class for ICESat-2 ATL03
h5Object of class H5File from
hdf5r package containing the ICESat-2 Global Geolocated
Photon Data (ATL03)
H5File in the hdf5r package and
https://icesat-2.gsfc.nasa.gov/sites/default/files/page_files/ICESat2_ATL03_ATBD_r006.pdf
Class for ATL03 segment attributes
data.table in the data.table package and
https://icesat-2.gsfc.nasa.gov/sites/default/files/page_files/ICESat2_ATL03_ATBD_r006.pdf
Class for joined ATL03 and ATL08 attributes
data.table in the data.table package and
https://icesat-2.gsfc.nasa.gov/sites/default/files/page_files/ICESat2_ATL03_ATBD_r006.pdf
Class for ATL08 attributes
data.table in the data.table package and
https://icesat-2.gsfc.nasa.gov/sites/default/files/page_files/ICESat2_ATL08_ATBD_r006.pdf
Class for ICESat-2 ATL08
h5Object of class H5File from
hdf5r package containing the
ICESat-2 Land and Vegetation Along-Track Products (ATL08)
H5File in the hdf5r package and
https://icesat-2.gsfc.nasa.gov/sites/default/files/page_files/ICESat2_ATL08_ATBD_r006.pdf
Besides representing h5 files, it is also used to represent groups
opened with [[]].
The variants _cloud and _local allows all the other functions
to use generic calls using the same interface, with each class
implementation is provided accordingly.
The regular usage does not require the user to work with those classes as most other provided functions will actually give access to the most common necessities for working with ICESat-2 data.
ICESat2.h5_cloud$new()Direct initialization should not be used, it is handled by ATL0X_read()
ICESat2.h5_cloud$new(h5)
h5the result of the ATLAS_dataFinder() with cloud_computing = TRUE
The class object
ICESat2.h5_cloud$ls()Lists the groups and datasets that are within current group
ICESat2.h5_cloud$ls()
List the groups and datasets within the current path
ICESat2.h5_cloud$ls_groups()Lists all grouops recursively
ICESat2.h5_cloud$ls_groups(recursive = FALSE)
recursivelogical, default FALSE. If TRUE it will list
groups recursively and return the full path.
The character representing
ICESat2.h5_cloud$ls_attrs()Lists the available attributes
ICESat2.h5_cloud$ls_attrs()
character vector of attributes available
ICESat2.h5_cloud$dt_datasets()Get datasets as data.table with columns (name, dataset.dims, rank)
ICESat2.h5_cloud$dt_datasets(recursive = FALSE)
recursivelogical, default FALSE. If TRUE recursively searches
and returns the full path.
A data.table::data.table with the columns (name, dataset.dims, rank)
ICESat2.h5_cloud$exists()Checks if a supplied group/dataset exist within the H5
ICESat2.h5_cloud$exists(path)
pathcharacter with the path to test
logical TRUE or FALSE if it exists or not
ICESat2.h5_cloud$attr()Read an attribute from h5
ICESat2.h5_cloud$attr(attribute)
attributecharacter the address of the attribute to open
ICESat2.h5_cloud$close_all()Safely closes the h5 file pointer
ICESat2.h5_cloud$close_all()
Nothing, just closes the file
ICESat2.h5_cloud$print()Prints the data in a friendly manner
ICESat2.h5_cloud$print(...)
...Added for compatibility purposes with generic signature
Outputs information about object
ICESat2.h5_cloud$clone()The objects of this class are cloneable with this method.
ICESat2.h5_cloud$clone(deep = FALSE)
deepWhether to make a deep clone.
The variants _cloud and _local allows all the other functions
to use generic calls using the same interface, with each class
implementation is provided accordingly.
The regular usage does not require the user to work with those classes as most other provided functions will actually give access to the most common necessities for working with ICESat-2 data.
h5A pointer to hdf5r::H5File in case
the user wants to access features not implemented yet
beamsThe character vector of beams available for the granule.
strong_beamsThe character vector of strong beams calculated using orbit_info
weak_beamsThe character vector of weak beams calculated using orbit_info
isOpenA flag to indicate if the file pointer has already been closed
ICESat2.h5_local$new()Direct initialization should not be used, it is handled by ATL0X_read()
ICESat2.h5_local$new(h5)
h5the result of the ATLAS_dataFinder()
The class object
ICESat2.h5_local$ls()Lists the groups and datasets that are within current group
ICESat2.h5_local$ls()
List the groups and datasets within the current path
ICESat2.h5_local$ls_groups()Lists all grouops recursively
ICESat2.h5_local$ls_groups(recursive = FALSE)
recursivelogical, default FALSE. If TRUE it will list
groups recursively and return the full path.
The character representing
ICESat2.h5_local$ls_attrs()Lists the available attributes
ICESat2.h5_local$ls_attrs()
character vector of attributes available
ICESat2.h5_local$dt_datasets()Get datasets as data.table with columns (name, dataset.dims, rank)
ICESat2.h5_local$dt_datasets(recursive = FALSE)
recursivelogical, default FALSE. If TRUE recursively searches
and returns the full path.
A data.table::data.table with the columns (name, dataset.dims, rank)
ICESat2.h5_local$exists()Checks if a supplied group/dataset exist within the H5
ICESat2.h5_local$exists(path)
pathcharacter with the path to test
logical TRUE or FALSE if it exists or not
ICESat2.h5_local$attr()Read an attribute from h5
ICESat2.h5_local$attr(attribute)
attributecharacter the address of the attribute to open
ICESat2.h5_local$close_all()Safely closes the h5 file pointer
ICESat2.h5_local$close_all(silent = TRUE)
silentlogical, default TRUE. Will cast warning messages if silent = FALSE.
Nothing, just closes the file
ICESat2.h5_local$print()Prints the data in a friendly manner
ICESat2.h5_local$print(...)
...Added for compatibility purposes with generic signature
Outputs information about object
ICESat2.h5_local$clone()The objects of this class are cloneable with this method.
ICESat2.h5_local$clone(deep = FALSE)
deepWhether to make a deep clone.
Base class for all ICESat2VegR package's H5 files for generic functions that can be run on any H5
This class should not be instanced by the user, instead it is
automatically handled when the user opens a dataset using [[]]
operator from a h5 file.
dsDataset pointer
dimsDimensions of the dataset
chunk_dimsChunk dimensions for the dataset
ICESat2.h5ds_cloud$new()Constructor using a dataset pointer
ICESat2.h5ds_cloud$new(ds)
dsDataset pointer
ICESat2.h5ds_cloud$get_type()Get the type of data for this dataset
ICESat2.h5ds_cloud$get_type()
ICESat2.h5ds_cloud$get_fill_value()Get the fill_value used by the dataset
ICESat2.h5ds_cloud$get_fill_value()
ICESat2.h5ds_cloud$get_creation_property_list()Get creation property list for the dataset (plist)
ICESat2.h5ds_cloud$get_creation_property_list()
ICESat2.h5ds_cloud$clone()The objects of this class are cloneable with this method.
ICESat2.h5ds_cloud$clone(deep = FALSE)
deepWhether to make a deep clone.
This class should not be instanced by the user, instead it is
automatically handled when the user opens a dataset using [[]]
operator from a h5 file.
dsDataset pointer
dimsDimensions of the dataset
chunk_dimsChunk dimensions for the dataset
ICESat2.h5ds_local$new()Constructor using a dataset pointer
ICESat2.h5ds_local$new(ds)
dsDataset pointer
ICESat2.h5ds_local$get_type()Get the type of data for this dataset
ICESat2.h5ds_local$get_type()
ICESat2.h5ds_local$get_fill_value()Get the fill_value used by the dataset
ICESat2.h5ds_local$get_fill_value()
ICESat2.h5ds_local$get_creation_property_list()Get creation property list for the dataset (plist)
ICESat2.h5ds_local$get_creation_property_list()
ICESat2.h5ds_local$clone()The objects of this class are cloneable with this method.
ICESat2.h5ds_local$clone(deep = FALSE)
deepWhether to make a deep clone.
This function sets up a robust, persistent Python environment for the cloud-related features of ICESat2VegR, including:
ICESat2VegR_configure( envname = "icesat2-env", py_ver = "3.10", prefer_conda = TRUE, force_conda_forge = TRUE, allow_session_installs = TRUE, manage_aiobotocore = TRUE, auto_restart = TRUE, verbose = TRUE, quick_probe = c("h5py", "earthaccess", "ee") )ICESat2VegR_configure( envname = "icesat2-env", py_ver = "3.10", prefer_conda = TRUE, force_conda_forge = TRUE, allow_session_installs = TRUE, manage_aiobotocore = TRUE, auto_restart = TRUE, verbose = TRUE, quick_probe = c("h5py", "earthaccess", "ee") )
envname |
Character. Name of the conda/virtualenv environment to use or
create. Default is |
py_ver |
Character. Python version to request when creating a new env
(default |
prefer_conda |
Logical. If |
force_conda_forge |
Logical. If |
allow_session_installs |
Logical. If |
manage_aiobotocore |
Logical. If |
auto_restart |
Logical. If |
verbose |
Logical. If |
quick_probe |
Character vector of Python import names to test for a
fast early exit (default: |
Downloading ICESat-2 data via earthaccess
Interfacing with Google Earth Engine via earthengine-api
Handling S3 access via boto3/botocore
The function:
Detects whether Python is already initialized in the R session.
Performs a fast "quick probe" to see if required modules are present
(h5py, earthaccess, ee by default).
If everything is already available, it returns immediately.
Otherwise, it:
Ensures Miniconda is installed (if prefer_conda = TRUE).
Creates or reuses a conda environment (default: "icesat2-env").
Installs required Python modules using conda-forge (and pip fallback).
Optionally tries in-session installs if Python is already initialized.
Optionally resolves common aiobotocore/botocore conflicts.
Optionally restarts the R session in RStudio to bind the new env.
Typical usage is simply:
ICESat2VegR_configure()
You usually only need to run this:
Once per machine, or
After major Python / Miniconda changes, or
If the package reports missing Python modules.
Logical TRUE on success, FALSE otherwise.
The function checks for the following import names and installs the corresponding packages when missing:
| Import name | Install name |
numpy |
numpy |
h5py |
h5py |
packaging |
packaging |
ee |
earthengine-api |
earthaccess |
earthaccess |
googleapiclient |
google-api-python-client |
boto3 |
boto3 |
botocore |
botocore |
s3transfer |
s3transfer
|
## Not run: # Basic configuration using defaults ICESat2VegR_configure() # Use existing conda env named "icesat2" ICESat2VegR_configure(envname = "icesat2") ## End(Not run)## Not run: # Basic configuration using defaults ICESat2VegR_configure() # Use existing conda env named "icesat2" ICESat2VegR_configure(envname = "icesat2") ## End(Not run)
Returns the number of images in an ImageCollection
## S4 method for signature 'ee.imagecollection.ImageCollection' length(x)## S4 method for signature 'ee.imagecollection.ImageCollection' length(x)
x |
The |
The number of images in the ImageCollection
Applies a fitted Random Forest model (from R's randomForest package)
to a Google Earth Engine image stack and returns an ee$Image
containing the predicted values. The model is converted to a GEE
Classifier via build_ee_forest, which serializes
the R forest through the ICESat2VegR C++ module and constructs an EE
estimator using ee$Classifier$decisionTreeEnsemble().
Authentication: This function requires an active Google Earth
Engine session. Authenticate using ICESat2VegR::ee_initialize()
before calling this function.
map_create( model, stack, aoi = NULL, reducer = c("mosaic", "median"), mode = c("auto", "classifier"), to_float = TRUE )map_create( model, stack, aoi = NULL, reducer = c("mosaic", "median"), mode = c("auto", "classifier"), to_float = TRUE )
model |
A fitted |
stack |
An |
aoi |
Optional. An EE geometry ( |
reducer |
character. Aggregation method when |
mode |
character. Controls how the estimator is applied. One of:
|
to_float |
logical. If |
The function works for both:
ee$Image: predictors already merged into one raster.
ee$ImageCollection: predictions computed for each image
and reduced using mosaic or median.
The output band is always named prediction_layer. Properties
from a zero-pixel placeholder image are copied to preserve band metadata.
The predictor variable names used to train the model must exactly
match the band names in stack. Use names(stack) to verify
the available bands before training the model.
An ee$Image containing one band named
"prediction_layer" with the model predictions at each pixel.
build_ee_forest,
ee_build_AlphaEarth_embedding_terrain_stack,
seg_ancillary_extract
## Not run: Sys.setenv(EE_PROJECT = "your-ee-project-id") ICESat2VegR::ee_initialize() library(sf) library(randomForest) # ── AOI as simple bounding box ─────────────────────────────── aoi <- sf::st_as_sfc(sf::st_bbox(c( xmin = -82.4, xmax = -82.2, ymin = 29.6, ymax = 29.8 ), crs = 4326)) ee_geom <- ICESat2VegR:::.as_ee_geom(aoi) # ── Build embedding + terrain stack ───────────────────────── stack <- ee_build_AlphaEarth_embedding_terrain_stack( geom = ee_geom, start_year = 2025, end_year = 2025 ) # ── Synthetic training data using stack band names ─────────── # In practice, use real ICESat-2 extracted values set.seed(42) n <- 200 predictor_cols <- head(names(stack), 10) X <- as.data.frame(matrix( rnorm(n * length(predictor_cols)), nrow = n, ncol = length(predictor_cols), dimnames = list(NULL, predictor_cols) )) # Synthetic canopy height response y <- 5 + 2 * X[[1]] + 3 * X[[2]] + rnorm(n, sd = 1) # ── Fit Random Forest model ────────────────────────────────── rf_model <- randomForest(x = X, y = y, ntree = 100) rf_model # ── Create prediction map in GEE ──────────────────────────── pred <- map_create( model = rf_model, stack = stack, aoi = ee_geom, mode = "auto" ) # pred is an ee$Image with one band: "prediction_layer" class(pred) names(pred) pred ## End(Not run)## Not run: Sys.setenv(EE_PROJECT = "your-ee-project-id") ICESat2VegR::ee_initialize() library(sf) library(randomForest) # ── AOI as simple bounding box ─────────────────────────────── aoi <- sf::st_as_sfc(sf::st_bbox(c( xmin = -82.4, xmax = -82.2, ymin = 29.6, ymax = 29.8 ), crs = 4326)) ee_geom <- ICESat2VegR:::.as_ee_geom(aoi) # ── Build embedding + terrain stack ───────────────────────── stack <- ee_build_AlphaEarth_embedding_terrain_stack( geom = ee_geom, start_year = 2025, end_year = 2025 ) # ── Synthetic training data using stack band names ─────────── # In practice, use real ICESat-2 extracted values set.seed(42) n <- 200 predictor_cols <- head(names(stack), 10) X <- as.data.frame(matrix( rnorm(n * length(predictor_cols)), nrow = n, ncol = length(predictor_cols), dimnames = list(NULL, predictor_cols) )) # Synthetic canopy height response y <- 5 + 2 * X[[1]] + 3 * X[[2]] + rnorm(n, sd = 1) # ── Fit Random Forest model ────────────────────────────────── rf_model <- randomForest(x = X, y = y, ntree = 100) rf_model # ── Create prediction map in GEE ──────────────────────────── pred <- map_create( model = rf_model, stack = stack, aoi = ee_geom, mode = "auto" ) # pred is an ee$Image with one band: "prediction_layer" class(pred) names(pred) pred ## End(Not run)
One function to export an EE image to Drive, Cloud Storage, or
Asset; optionally monitor the task; and, for Drive/GCS, download the result
locally. Returns a local file (or SpatRaster if terra is available) for
Drive/GCS, or the asset_id (invisible) for Asset exports.
map_download( ee_image, method = c("drive", "gcs", "asset"), region, scale = NULL, file_name_prefix, dsn = NULL, drive_folder = NULL, gcs_bucket = NULL, asset_id = NULL, monitor = TRUE, task_time = 5, ... )map_download( ee_image, method = c("drive", "gcs", "asset"), region, scale = NULL, file_name_prefix, dsn = NULL, drive_folder = NULL, gcs_bucket = NULL, asset_id = NULL, monitor = TRUE, task_time = 5, ... )
ee_image |
An |
method |
One of |
region |
EE geometry/feature collection defining the export region. |
scale |
Numeric pixel size in meters. |
file_name_prefix |
Export file prefix (used to search/download). |
dsn |
Destination path on disk (Drive/GCS methods). |
drive_folder |
Drive folder name for Drive exports. |
gcs_bucket |
Cloud Storage bucket name for GCS exports. |
asset_id |
Destination asset id for Asset exports. |
monitor |
Logical; if |
task_time |
Seconds between polls when monitoring. |
... |
Additional arguments forwarded to the corresponding export helper
( |
For drive/gcs, a local path or a SpatRaster if terra is installed.
For asset, returns invisible(asset_id).
## Not run: out <- map_download( ee_image = img, method = "drive", region = aoi, scale = 10, file_name_prefix = "my_pred", dsn = "pred.tif", drive_folder = "EE_Exports", monitor = TRUE ) ## End(Not run)## Not run: out <- map_download( ee_image = img, method = "drive", region = aoi, scale = 10, file_name_prefix = "my_pred", dsn = "pred.tif", drive_folder = "EE_Exports", monitor = TRUE ) ## End(Not run)
High-level map composer capable of adding Earth Engine raster
tiles (optionally tiled by AOI grid) and vector overlays (sf/SpatVector),
with layer control, legends, and per-group opacity sliders.
map_view( layers, base_tiles = c("OSM", "Carto.Light", "Carto.Dark"), add_layers_control = TRUE, add_opacity_controls = TRUE, fit_to = NULL )map_view( layers, base_tiles = c("OSM", "Carto.Light", "Carto.Dark"), add_layers_control = TRUE, add_opacity_controls = TRUE, fit_to = NULL )
layers |
A list of layer specs. For rasters: |
base_tiles |
One of |
add_layers_control |
Logical; add layers control panel. |
add_opacity_controls |
Logical; add per-group opacity sliders. |
fit_to |
Optional EE Rectangle to fit the initial view. |
A leaflet htmlwidget.
## Not run: m <- map_view(list( list(type="ee_image", x=img, bands="prediction_layer", aoi=aoi, group="Prediction", min_value=0, max_value=30, legend=list(title="Height (m)", auto="quantile")), list(type="vector", vect=polys_sf, group="Sites", color_field="site") )) ## End(Not run)## Not run: m <- map_view(list( list(type="ee_image", x=img, bands="prediction_layer", aoi=aoi, group="Prediction", min_value=0, max_value=30, legend=list(title="Height (m)", auto="quantile")), list(type="vector", vect=polys_sf, group="Sites", color_field="site") )) ## End(Not run)
Creates an interactive HTML animation of ICESat-2 orbital tracks from one or more KML files.
plot_icesat2_orbit_animation( kml_files = NULL, output_dir = tempdir(), output_file = "ICESat2_orbit_animation.html", track_speed = 2, earth_rotation_speed = 2, launch = TRUE )plot_icesat2_orbit_animation( kml_files = NULL, output_dir = tempdir(), output_file = "ICESat2_orbit_animation.html", track_speed = 2, earth_rotation_speed = 2, launch = TRUE )
kml_files |
Character vector. Path to one or more KML files. If |
output_dir |
Character. Folder where the HTML animation and required
assets will be written. Default is |
output_file |
Character. Name of the output HTML file. |
track_speed |
Numeric. Initial animation speed. Default is |
earth_rotation_speed |
Numeric. Initial Earth rotation speed. Default is |
launch |
Logical. If |
Invisibly returns the path to the generated HTML file.
## Not run: # Use example KML files from inst/extdata plot_icesat2_orbit_animation() # Use user-supplied KML files kmls <- c( "C:/data/IS2_RGT_1315_cycle33_07-Dec-2026.kml", "C:/data/IS2_RGT_1316_cycle33_08-Dec-2026.kml" ) plot_icesat2_orbit_animation( kml_files = kmls, output_dir = "C:/temp/icesat2_animation", launch = TRUE ) ## End(Not run)## Not run: # Use example KML files from inst/extdata plot_icesat2_orbit_animation() # Use user-supplied KML files kmls <- c( "C:/data/IS2_RGT_1315_cycle33_07-Dec-2026.kml", "C:/data/IS2_RGT_1316_cycle33_08-Dec-2026.kml" ) plot_icesat2_orbit_animation( kml_files = kmls, output_dir = "C:/temp/icesat2_animation", launch = TRUE ) ## End(Not run)
This function plots ATL03 and ATL08 joined data along track
This function plots ATL08 attributes along track
This function plots ATL03 photons along track
## S4 method for signature 'icesat2.atl03atl08_dt,missing' plot(x, y, ...) ## S4 method for signature 'icesat2.atl03atl08_dt,character' plot( x, y, beam = NULL, col = c("gray", "#bd8421", "forestgreen", "green"), ... ) ## S4 method for signature 'icesat2.atl03_seg_dt,missing' plot(x, col = "gray", ...)## S4 method for signature 'icesat2.atl03atl08_dt,missing' plot(x, y, ...) ## S4 method for signature 'icesat2.atl03atl08_dt,character' plot( x, y, beam = NULL, col = c("gray", "#bd8421", "forestgreen", "green"), ... ) ## S4 method for signature 'icesat2.atl03_seg_dt,missing' plot(x, col = "gray", ...)
x |
An object of class |
y |
The attribute name for y axis |
... |
will be passed to the main plot |
beam |
Character vector indicating only one beam to process ("gt1l", "gt1r", "gt2l", "gt2r", "gt3l", "gt3r"). Default is "gt1r" |
col |
Color for plotting the photons. Default is "gray" |
No return value
No return value
No return value
# Specifying the path to ATL03 file atl03_path <- system.file("extdata", "atl03_clip.h5", package = "ICESat2VegR" ) # Specifying the path to ATL08 file atl08_path <- system.file("extdata", "atl08_clip.h5", package = "ICESat2VegR" ) # Reading ATL03 data (h5 file) atl03_h5 <- ATL03_read(atl03_path = atl03_path) # Reading ATL08 data (h5 file) atl08_h5 <- ATL08_read(atl08_path = atl08_path) # Extracting ATL03 and ATL08 photons and heights atl03_atl08_dt <- ATL03_ATL08_photons_attributes_dt_join(atl03_h5, atl08_h5) plot( atl03_atl08_dt, "ph_h", pch = 16, cex = 0.5, beam = "gt1r", colors = c("gray", "#bd8421", "forestgreen", "green") ) close(atl03_h5) close(atl08_h5) # Specifying the path to ATL03 file atl03_path <- system.file("extdata", "atl03_clip.h5", package = "ICESat2VegR" ) # Specifying the path to ATL08 file atl08_path <- system.file("extdata", "atl08_clip.h5", package = "ICESat2VegR" ) # Reading ATL03 data (h5 file) atl03_h5 <- ATL03_read(atl03_path = atl03_path) # Reading ATL08 data (h5 file) atl08_h5 <- ATL08_read(atl08_path = atl08_path) # Extracting ATL03 and ATL08 photons and heights atl03_atl08_dt <- ATL03_ATL08_photons_attributes_dt_join(atl03_h5, atl08_h5) plot( atl03_atl08_dt, "h_ph", colors = c("gray", "#bd8421", "forestgreen", "green"), pch = 16, cex = 0.5 ) close(atl03_h5) close(atl08_h5) # Specifying the path to ATL03 file atl03_path <- system.file("extdata", "atl03_clip.h5", package = "ICESat2VegR" ) # Reading ATL03 data (h5 file) atl03_h5 <- ATL03_read(atl03_path = atl03_path) # Extracting atl03 and atl03 photons and heights atl03_photons_dt <- ATL03_seg_metadata_dt( atl03_h5 = atl03_h5, attributes = c( "reference_photon_lon", "reference_photon_lat", "segment_dist_x", "h_ph" ) ) plot( atl03_photons_dt, col = "gray", pch = 16, cex = 0.5 ) close(atl03_h5)# Specifying the path to ATL03 file atl03_path <- system.file("extdata", "atl03_clip.h5", package = "ICESat2VegR" ) # Specifying the path to ATL08 file atl08_path <- system.file("extdata", "atl08_clip.h5", package = "ICESat2VegR" ) # Reading ATL03 data (h5 file) atl03_h5 <- ATL03_read(atl03_path = atl03_path) # Reading ATL08 data (h5 file) atl08_h5 <- ATL08_read(atl08_path = atl08_path) # Extracting ATL03 and ATL08 photons and heights atl03_atl08_dt <- ATL03_ATL08_photons_attributes_dt_join(atl03_h5, atl08_h5) plot( atl03_atl08_dt, "ph_h", pch = 16, cex = 0.5, beam = "gt1r", colors = c("gray", "#bd8421", "forestgreen", "green") ) close(atl03_h5) close(atl08_h5) # Specifying the path to ATL03 file atl03_path <- system.file("extdata", "atl03_clip.h5", package = "ICESat2VegR" ) # Specifying the path to ATL08 file atl08_path <- system.file("extdata", "atl08_clip.h5", package = "ICESat2VegR" ) # Reading ATL03 data (h5 file) atl03_h5 <- ATL03_read(atl03_path = atl03_path) # Reading ATL08 data (h5 file) atl08_h5 <- ATL08_read(atl08_path = atl08_path) # Extracting ATL03 and ATL08 photons and heights atl03_atl08_dt <- ATL03_ATL08_photons_attributes_dt_join(atl03_h5, atl08_h5) plot( atl03_atl08_dt, "h_ph", colors = c("gray", "#bd8421", "forestgreen", "green"), pch = 16, cex = 0.5 ) close(atl03_h5) close(atl08_h5) # Specifying the path to ATL03 file atl03_path <- system.file("extdata", "atl03_clip.h5", package = "ICESat2VegR" ) # Reading ATL03 data (h5 file) atl03_h5 <- ATL03_read(atl03_path = atl03_path) # Extracting atl03 and atl03 photons and heights atl03_photons_dt <- ATL03_seg_metadata_dt( atl03_h5 = atl03_h5, attributes = c( "reference_photon_lon", "reference_photon_lat", "segment_dist_x", "h_ph" ) ) plot( atl03_photons_dt, col = "gray", pch = 16, cex = 0.5 ) close(atl03_h5)
varSel objectsPlot scaled variable importance for a varSel object using a horizontal
barplot. Variables are ordered so that the most important metrics appear at
the top (largest bars).
When which = "importance" all variables are shown, and those selected
by varSel() are highlighted in a different color. An optional
color palette (e.g., viridis::inferno) can be supplied to color the
bars by importance.
## S3 method for class 'varSel' plot( x, which = c("sel.importance", "importance"), main = "Random Forest variable importance", xlab = "Scaled importance", col.selected = "steelblue", col.other = "grey80", palette = NULL, legend.loc = "bottomright", ... )## S3 method for class 'varSel' plot( x, which = c("sel.importance", "importance"), main = "Random Forest variable importance", xlab = "Scaled importance", col.selected = "steelblue", col.other = "grey80", palette = NULL, legend.loc = "bottomright", ... )
x |
An object of class |
which |
Character; either |
main |
Plot title. |
xlab |
Label for the x-axis (importance scale). |
col.selected |
Base color for selected variables when no palette is given. |
col.other |
Base color for non-selected variables when no palette is given. |
palette |
Optional color palette. Can be:
- a function The palette is applied to all bars and then the color of selected variables
is overridden by |
legend.loc |
Legend location, e.g. "bottomright" |
... |
Additional graphical arguments passed to graphics::barplot. |
require(randomForest) data(airquality) airquality <- na.omit(airquality) xdata <- airquality[, 2:6] ydata <- airquality[, 1] ntree = 200 vs <- varSel(xdata, ydata, ntree = ntree, min.imp = 0.2) ## Selected variables only plot(vs, which = "sel.importance") ## All variables, highlighting selected ones, with inferno palette if (requireNamespace("viridis", quietly = TRUE)) { plot(vs, which = "importance", palette = viridis::inferno) }require(randomForest) data(airquality) airquality <- na.omit(airquality) xdata <- airquality[, 2:6] ydata <- airquality[, 1] ntree = 200 vs <- varSel(xdata, ydata, ntree = ntree, min.imp = 0.2) ## Selected variables only plot(vs, which = "sel.importance") ## All variables, highlighting selected ones, with inferno palette if (requireNamespace("viridis", quietly = TRUE)) { plot(vs, which = "importance", palette = viridis::inferno) }
Model prediction over a data.table from ATL03 or ATL08 data containing geolocation data. It can both append results to an existing HDF5 file or create a new file, allowing to incrementally add predictions to the file to avoid memory issues.
predict_h5(model, dt, output)predict_h5(model, dt, output)
model |
The trained model object |
dt |
The input data.table to run the model |
output |
The output HDF5 file path |
An icesat2.predict_h5, which is an
h5 file with latitude, longitude and prediction datasets.
atl03_path <- system.file( "extdata", "atl03_clip.h5", package = "ICESat2VegR" ) atl03_h5 <- ATL03_read(atl03_path = atl03_path) atl03_seg_dt <- ATL03_seg_metadata_dt(atl03_h5) linear_model <- stats::lm(h_ph ~ segment_ph_cnt, data = atl03_seg_dt) output_h5 <- tempfile(fileext = ".h5") predicted_h5 <- predict_h5(linear_model, atl03_seg_dt, output_h5) # List datasets predicted_h5$ls()$name # See predicted values head(predicted_h5[["prediction"]][]) # Close the file close(predicted_h5)atl03_path <- system.file( "extdata", "atl03_clip.h5", package = "ICESat2VegR" ) atl03_h5 <- ATL03_read(atl03_path = atl03_path) atl03_seg_dt <- ATL03_seg_metadata_dt(atl03_h5) linear_model <- stats::lm(h_ph ~ segment_ph_cnt, data = atl03_seg_dt) output_h5 <- tempfile(fileext = ".h5") predicted_h5 <- predict_h5(linear_model, atl03_seg_dt, output_h5) # List datasets predicted_h5$ls()$name # See predicted values head(predicted_h5[["prediction"]][]) # Close the file close(predicted_h5)
This method is used to predict using a trained model and save the results in HDF5 file.
## S4 method for signature 'ANY,icesat2.atl03_seg_dt,character' predict_h5(model, dt, output)## S4 method for signature 'ANY,icesat2.atl03_seg_dt,character' predict_h5(model, dt, output)
model |
The trained model object |
dt |
The input data.table to run the model |
output |
The output file path |
An icesat2.predict_h5, which is an
h5 file with latitude, longitude and prediction
atl03_path <- system.file( "extdata", "atl03_clip.h5", package = "ICESat2VegR" ) atl03_h5 <- ATL03_read(atl03_path = atl03_path) atl03_seg_dt <- ATL03_seg_metadata_dt(atl03_h5) linear_model <- stats::lm(h_ph ~ segment_ph_cnt, data = atl03_seg_dt) output_h5 <- tempfile(fileext = ".h5") predicted_h5 <- predict_h5(linear_model, atl03_seg_dt, output_h5) # List datasets predicted_h5$ls()$name # See predicted values head(predicted_h5[["prediction"]][]) # Close the file close(predicted_h5)atl03_path <- system.file( "extdata", "atl03_clip.h5", package = "ICESat2VegR" ) atl03_h5 <- ATL03_read(atl03_path = atl03_path) atl03_seg_dt <- ATL03_seg_metadata_dt(atl03_h5) linear_model <- stats::lm(h_ph ~ segment_ph_cnt, data = atl03_seg_dt) output_h5 <- tempfile(fileext = ".h5") predicted_h5 <- predict_h5(linear_model, atl03_seg_dt, output_h5) # List datasets predicted_h5$ls()$name # See predicted values head(predicted_h5[["prediction"]][]) # Close the file close(predicted_h5)
This method is used to predict using a trained model and save the results in HDF5 file.
## S4 method for signature 'ANY,icesat2.atl08_dt,character' predict_h5(model, dt, output)## S4 method for signature 'ANY,icesat2.atl08_dt,character' predict_h5(model, dt, output)
model |
The trained model object |
dt |
The input data.table to run the model |
output |
The output file path |
This method is used to predict using a trained model and save the results in an HDF5 file.
An icesat2.predict_h5, which is an
h5 file with latitude, longitude and prediction datasets.
atl08_path <- system.file( "extdata", "atl08_clip.h5", package = "ICESat2VegR" ) atl08_h5 <- ATL08_read(atl08_path = atl08_path) atl08_dt <- ATL08_seg_attributes_dt(atl08_h5) linear_model <- stats::lm(h_canopy ~ canopy_openness, data = atl08_dt) output_h5 <- tempfile(fileext = ".h5") predicted_h5 <- predict_h5(linear_model, atl08_dt, output_h5) # List datasets predicted_h5$ls()$name # See predicted values head(predicted_h5[["prediction"]][]) # Close the file close(predicted_h5)atl08_path <- system.file( "extdata", "atl08_clip.h5", package = "ICESat2VegR" ) atl08_h5 <- ATL08_read(atl08_path = atl08_path) atl08_dt <- ATL08_seg_attributes_dt(atl08_h5) linear_model <- stats::lm(h_canopy ~ canopy_openness, data = atl08_dt) output_h5 <- tempfile(fileext = ".h5") predicted_h5 <- predict_h5(linear_model, atl08_dt, output_h5) # List datasets predicted_h5$ls()$name # See predicted values head(predicted_h5[["prediction"]][]) # Close the file close(predicted_h5)
Prepend a class to an object's list of classes
prepend_class(obj, className)prepend_class(obj, className)
obj |
The object to which prepend the class. |
className |
|
Nothing, it replaces the class attribute in place
Pure random sampling method
randomSampling(size)randomSampling(size)
size |
numeric. The sample size. Either an integer for absolute number
of samples, or a value between |
A icesat2_sampling_method-class object for use in
sample.
sample, gridSampling,
stratifiedSampling, spacedSampling,
geomSampling, rasterSampling
atl08_path <- system.file("extdata", "atl08_clip.h5", package = "ICESat2VegR") atl08_h5 <- ATL08_read(atl08_path = atl08_path) atl08_dt <- ATL08_seg_attributes_dt(atl08_h5) # Sample 5 random observations set.seed(1) sampled <- ICESat2VegR::sample(atl08_dt, method = randomSampling(5)) head(sampled) # Sample 50% of observations set.seed(1) sampled_pct <- ICESat2VegR::sample(atl08_dt, method = randomSampling(0.5)) nrow(sampled_pct) close(atl08_h5)atl08_path <- system.file("extdata", "atl08_clip.h5", package = "ICESat2VegR") atl08_h5 <- ATL08_read(atl08_path = atl08_path) atl08_dt <- ATL08_seg_attributes_dt(atl08_h5) # Sample 5 random observations set.seed(1) sampled <- ICESat2VegR::sample(atl08_dt, method = randomSampling(5)) head(sampled) # Sample 50% of observations set.seed(1) sampled_pct <- ICESat2VegR::sample(atl08_dt, method = randomSampling(0.5)) nrow(sampled_pct) close(atl08_h5)
This is used after running the prediction using predict_h5()
function to rasterize and aggregate the prediction within raster cells.
By default it will calculate (n, mean, variance * (n - 1), min, max, sd)
in a single raster file with those 6 bands in that order.
You can modify this behavior by changing the agg_function, agg_join
and finalizer parameters, see details section.
rasterize_h5(h5_input, output, bbox, res, ...)rasterize_h5(h5_input, output, bbox, res, ...)
h5_input |
The input HDF5 file path |
output |
The output raster file path |
bbox |
The bounding box of the raster |
res |
The resolution of the raster |
... |
Additional parameters (see details section) |
This function will create five different aggregate statistics (n, mean, variance, min, max).
Within ... additional parameters we can use:
agg_function: is a formula which return a data.table with the
aggregate function to perform over the data.
The default is:
~data.table(
n = length(x),
mean = mean(x,na.rm = TRUE),
variance = var(x) * (length(x) - 1),
min = min(x, na.rm=T),
max = max(x, na.rm=T)
)
agg_join: is a function to merge two data.table aggregates
from the agg_function. Since the h5 files will be aggregated
in chunks to avoid memory overflow, the statistics from the
different chunks should have a function to merge them.
The default function is:
function(x1, x2) {
combined = data.table()
x1$n[is.na(x1$n)] = 0
x1$mean[is.na(x1$mean)] = 0
x1$variance[is.na(x1$variance)] = 0
x1$max[is.na(x1$max)] = -Inf
x1$min[is.na(x1$min)] = Inf
combined$n = x1$n + x2$n
delta = x2$mean - x1$mean
delta2 = delta * delta
combined$mean = (x1$n * x1$mean + x2$n * x2$mean) / combined$n
combined$variance = x1$variance + x2$variance +
delta2 * x1$n * x2$n / combined$n
combined$min = pmin(x1$min, x2$min, na.rm=F)
combined$max = pmax(x1$max, x2$max, na.rm=F)
return(combined)
}
finalizer: is a list of formulas to generate the final
rasters based on the intermediate statistics from the previous
functions. The default finalizer will calculate the sd,
based on the variance and n values. It is defined as:
list( sd = ~sqrt(variance/(n - 1)), )
atl08_path <- system.file( "extdata", "atl08_clip.h5", package = "ICESat2VegR" ) atl08_h5 <- ATL08_read(atl08_path = atl08_path) atl08_dt <- ATL08_seg_attributes_dt(atl08_h5) xmin <- min(atl08_dt$longitude) xmax <- max(atl08_dt$longitude) ymin <- min(atl08_dt$latitude) ymax <- max(atl08_dt$latitude) linear_model <- stats::lm(h_canopy ~ canopy_openness, data = atl08_dt) output_h5 <- tempfile(fileext = ".h5") predicted_h5 <- predict_h5(linear_model, atl08_dt, output_h5) output_raster <- tempfile(fileext = ".tif") rasterize_h5( predicted_h5, output = output_raster, bbox = terra::ext(xmin, xmax, ymin, ymax), res = 0.003 ) # Load and plot the raster r <- terra::rast(output_raster) terra::plot(r[[1]]) close(atl08_h5)atl08_path <- system.file( "extdata", "atl08_clip.h5", package = "ICESat2VegR" ) atl08_h5 <- ATL08_read(atl08_path = atl08_path) atl08_dt <- ATL08_seg_attributes_dt(atl08_h5) xmin <- min(atl08_dt$longitude) xmax <- max(atl08_dt$longitude) ymin <- min(atl08_dt$latitude) ymax <- max(atl08_dt$latitude) linear_model <- stats::lm(h_canopy ~ canopy_openness, data = atl08_dt) output_h5 <- tempfile(fileext = ".h5") predicted_h5 <- predict_h5(linear_model, atl08_dt, output_h5) output_raster <- tempfile(fileext = ".tif") rasterize_h5( predicted_h5, output = output_raster, bbox = terra::ext(xmin, xmax, ymin, ymax), res = 0.003 ) # Load and plot the raster r <- terra::rast(output_raster) terra::plot(r[[1]]) close(atl08_h5)
Rasterizes the model prediction saved in the HDF5 file
## S4 method for signature 'icesat2.predict_h5,character,SpatExtent,numeric' rasterize_h5( h5_input, output, bbox, res, chunk_size = 512 * 512, agg_function = agg_function_default, agg_join = agg_join_default, finalizer = finalizer_default )## S4 method for signature 'icesat2.predict_h5,character,SpatExtent,numeric' rasterize_h5( h5_input, output, bbox, res, chunk_size = 512 * 512, agg_function = agg_function_default, agg_join = agg_join_default, finalizer = finalizer_default )
h5_input |
The input HDF5 file path |
output |
The output raster file path |
bbox |
The bounding box of the raster |
res |
The resolution of the raster |
chunk_size |
The chunk size to read the HDF5 file |
agg_function |
The function to aggregate the data |
agg_join |
The function to join the aggregated data |
finalizer |
The function to finalize the raster |
Get observations sampled by raster class
rasterSampling(size, raster, chainSampling = NULL)rasterSampling(size, raster, chainSampling = NULL)
size |
numeric. The sample size per raster class. Either an integer
or a value between |
raster |
A |
chainSampling |
optional. Chain with another sampling method. |
A icesat2_sampling_method-class object for use in
sample.
atl08_path <- system.file("extdata", "atl08_clip.h5", package = "ICESat2VegR") atl08_h5 <- ATL08_read(atl08_path = atl08_path) atl08_dt <- ATL08_seg_attributes_dt(atl08_h5) # Create a raster over the data extent r <- terra::rast( xmin = min(atl08_dt$longitude), xmax = max(atl08_dt$longitude), ymin = min(atl08_dt$latitude), ymax = max(atl08_dt$latitude), resolution = 0.005, crs = "EPSG:4326" ) terra::values(r) <- sample(1:3, terra::ncell(r), replace = TRUE) # Sample 2 observations per raster class set.seed(1) sampled <- ICESat2VegR::sample( atl08_dt, method = rasterSampling(size = 2, raster = r) ) head(sampled) close(atl08_h5)atl08_path <- system.file("extdata", "atl08_clip.h5", package = "ICESat2VegR") atl08_h5 <- ATL08_read(atl08_path = atl08_path) atl08_dt <- ATL08_seg_attributes_dt(atl08_h5) # Create a raster over the data extent r <- terra::rast( xmin = min(atl08_dt$longitude), xmax = max(atl08_dt$longitude), ymin = min(atl08_dt$latitude), ymax = max(atl08_dt$latitude), resolution = 0.005, crs = "EPSG:4326" ) terra::values(r) <- sample(1:3, terra::ncell(r), replace = TRUE) # Sample 2 observations per raster class set.seed(1) sampled <- ICESat2VegR::sample( atl08_dt, method = rasterSampling(size = 2, raster = r) ) head(sampled) close(atl08_h5)
Convenience wrapper around data.table::rbindlist() that
row-binds a list of homogeneous objects and then restores their class.
This is especially useful for custom S3/S4-like classes used in ICESat2VegR
(e.g. icesat2.atl03_dt, icesat2.atl08_dt), where a plain
data.table::rbindlist() call would drop the original class attribute.
rbindlist2(l, ...)rbindlist2(l, ...)
l |
A list whose elements are all of the same class, typically
|
... |
Additional arguments passed directly to
|
A single data.table (the result of data.table::rbindlist()), with its
class attribute reset to match the class of the input elements.
This function extracts reference ground track from ICESat-2 ATL03 data and writes it as a GDAL vector format.
rgt_extract(h5, line = TRUE)rgt_extract(h5, line = TRUE)
h5 |
A ICESat-2 ATL03 object (output of |
line |
Logical; if |
This function will use the reference photons from the segments as reference for deriving the ground tracks. The begining and end of the lines are interpolated from the information regarding the position of the reference photon within the segment and the segment length.
Returns the ground track boundaries as terra::SpatVector extracted from "orbit_info",
along with other orbit information.
https://icesat-2.gsfc.nasa.gov/sites/default/files/page_files/ICESat2_ATL03_ATBD_r006.pdf
# Specifying the path to ATL03 H5 file atl03_path <- system.file("extdata", "atl03_clip.h5", package = "ICESat2VegR" ) # Reading ATL03 data (h5 file) atl03_h5 <- ATL03_read(atl03_path = atl03_path) # Extracting ATL03 RGT track as polygons rgt_polygon <- rgt_extract(h5 = atl03_h5, line = FALSE) head(rgt_polygon) terra::plet(rgt_polygon) # Extracting ATL03 RGT track as lines rgt_line <- rgt_extract(h5 = atl03_h5) head(rgt_line) terra::plet(rgt_line) close(atl03_h5)# Specifying the path to ATL03 H5 file atl03_path <- system.file("extdata", "atl03_clip.h5", package = "ICESat2VegR" ) # Reading ATL03 data (h5 file) atl03_h5 <- ATL03_read(atl03_path = atl03_path) # Extracting ATL03 RGT track as polygons rgt_polygon <- rgt_extract(h5 = atl03_h5, line = FALSE) head(rgt_polygon) terra::plet(rgt_polygon) # Extracting ATL03 RGT track as lines rgt_line <- rgt_extract(h5 = atl03_h5) head(rgt_line) terra::plet(rgt_line) close(atl03_h5)
Sample method for applying multiple sampling methods
sample(x, ..., method)sample(x, ..., method)
x |
the generic input data to be sampled |
... |
generic params to pass ahead to the specific sampling function |
method |
the sampling method to use. |
It is expected that the user pass a method parameter within ...
randomSampling(), spacedSampling(), gridSampling(),
stratifiedSampling(), geomSampling(), rasterSampling()
Given a vector (or first column of a matrix/data frame) of ICESat-2 ATL03/ATL08 granule URLs or file paths, this function:
Attempts to parse the acquisition year from each URL/path.
Groups granules by year.
Samples up to n_per_year unique URLs per year.
This is useful for creating manageable subsets of ATL granules for testing, model fitting, or cross-validation.
sample_ATL_granules_by_year(urls, n_per_year = 5, seed = NULL)sample_ATL_granules_by_year(urls, n_per_year = 5, seed = NULL)
urls |
Character vector, matrix, or data frame containing granule URLs or file paths. If a matrix or data frame is provided, the first column is used. |
n_per_year |
Integer. Maximum number of URLs to sample per year
(default |
seed |
Optional integer seed passed to |
The year is extracted using the following heuristics:
A path component of the form /YYYY/ (e.g., .../2020/...).
A filename pattern of the form ATL0[38]_YYYYMMDD....
URLs for which no year can be detected are dropped with a warning.
A data frame with columns:
year: integer acquisition year.
url: the sampled URL or file path.
Rows are ordered by year and then url.
## Not run: urls <- c( "https://example.org/ATL03_20200101000000_001.h5", "https://example.org/ATL03_20200102000000_002.h5", "https://example.org/ATL03_20210101000000_003.h5" ) sample_df <- ee_sample_atl_granules_by_year(urls, n_per_year = 1, seed = 42) sample_df ## End(Not run)## Not run: urls <- c( "https://example.org/ATL03_20200101000000_001.h5", "https://example.org/ATL03_20200102000000_002.h5", "https://example.org/ATL03_20210101000000_003.h5" ) sample_df <- ee_sample_atl_granules_by_year(urls, n_per_year = 1, seed = 42) sample_df ## End(Not run)
Search for Google Earth Engine datasets
search_datasets( ..., title = TRUE, description = TRUE, operator = "and", refresh_cache = FALSE )search_datasets( ..., title = TRUE, description = TRUE, operator = "and", refresh_cache = FALSE )
... |
character arguments to search for within title and/or description |
title |
logical. Whether should search within the title, default TRUE. |
description |
logical. Whether should search within the description of the dataset, default TRUE. |
operator |
character. Should be either "OR" or "AND" to tell if the search needs to include all the queries "AND" or any of the queries "OR". Default "AND". |
refresh_cache |
flag indicating if the results cache should be refreshed, default FALSE. |
A data.table containing the id, title and description of the datasets that matched
the supplied query ordered by relevance.
Given a stack image raster from GEE retrieve the point geometry with values for the images
seg_ancillary_extract(stack, geom, scale = 10, chunk_size = 1000)seg_ancillary_extract(stack, geom, scale = 10, chunk_size = 1000)
stack |
A single image or a vector/list of images from Earth Engine. |
geom |
A geometry from |
scale |
The scale in meters for the extraction (image resolution). |
chunk_size |
If the number of observations is greater than 1000, it is recommended to chunk the results for not running out of memory within GEE server, default is chunk by 1000. |
A data.table::data.table with the properties extracted from the ee images.
Computes the terrain slope in degrees for each pixel of an Earth Engine
ee$Image representing a digital elevation model (DEM).
This method is a thin wrapper around ee$Terrain$slope() and returns the
same output structure. Slope is computed using Earth Engine's internal
gradient operator, which relies on the 4-connected neighborhood around each
pixel. As a result, edge pixels may contain missing values depending on the
input DEM.
slope(x)slope(x)
x |
An |
An ee$Image with one band named slope containing terrain
slope values in degrees.
## Not run: ee <- reticulate::import("ee") dem <- ee$Image("NASA/NASADEM_HGT/001") slp <- slope(dem) ## End(Not run)## Not run: ee <- reticulate::import("ee") dem <- ee$Image("NASA/NASADEM_HGT/001") slp <- slope(dem) ## End(Not run)
Get observations with a minimum radius distance between samples
spacedSampling(size, radius, spatialIndex = NULL, chainSampling = NULL)spacedSampling(size, radius, spatialIndex = NULL, chainSampling = NULL)
size |
numeric. The sample size. Either an integer or a value between
|
radius |
numeric. The minimum radius in decimal degrees between samples. |
spatialIndex |
optional. A pre-built |
chainSampling |
optional. Chain with another sampling method. |
A icesat2_sampling_method-class object for use in
sample.
atl08_path <- system.file("extdata", "atl08_clip.h5", package = "ICESat2VegR") atl08_h5 <- ATL08_read(atl08_path = atl08_path) atl08_dt <- ATL08_seg_attributes_dt(atl08_h5) # Sample up to 5 observations with minimum 0.01 degree spacing set.seed(1) sampled <- ICESat2VegR::sample( atl08_dt, method = spacedSampling(size = 5, radius = 0.01) ) head(sampled) close(atl08_h5)atl08_path <- system.file("extdata", "atl08_clip.h5", package = "ICESat2VegR") atl08_h5 <- ATL08_read(atl08_path = atl08_path) atl08_dt <- ATL08_seg_attributes_dt(atl08_h5) # Sample up to 5 observations with minimum 0.01 degree spacing set.seed(1) sampled <- ICESat2VegR::sample( atl08_dt, method = spacedSampling(size = 5, radius = 0.01) ) head(sampled) close(atl08_h5)
Get samples stratified by a variable binning histogram
stratifiedSampling(size, variable, chainSampling = NULL, ...)stratifiedSampling(size, variable, chainSampling = NULL, ...)
size |
numeric. The sample size per stratum. Either an integer or
a value between |
variable |
character. Variable name used for the stratification. |
chainSampling |
optional. Chain with another sampling method. |
... |
Additional arguments forwarded to |
A icesat2_sampling_method-class object for use in
sample.
atl08_path <- system.file("extdata", "atl08_clip.h5", package = "ICESat2VegR") atl08_h5 <- ATL08_read(atl08_path = atl08_path) atl08_dt <- ATL08_seg_attributes_dt(atl08_h5) # Sample 2 observations per h_canopy stratum set.seed(1) sampled <- ICESat2VegR::sample( atl08_dt, method = stratifiedSampling(size = 2, variable = "h_canopy") ) head(sampled) close(atl08_h5)atl08_path <- system.file("extdata", "atl08_clip.h5", package = "ICESat2VegR") atl08_h5 <- ATL08_read(atl08_path = atl08_path) atl08_dt <- ATL08_seg_attributes_dt(atl08_h5) # Sample 2 observations per h_canopy stratum set.seed(1) sampled <- ICESat2VegR::sample( atl08_dt, method = stratifiedSampling(size = 2, variable = "h_canopy") ) head(sampled) close(atl08_h5)
Generic function to convert ICESat-2 objects, plain tables (data.frame / data.table),
and sf objects to a terra::SpatVector.
to_vect(x, ...) ## S4 method for signature 'data.frame' to_vect(x, lon = NULL, lat = NULL, crs = "EPSG:4326", ...) ## S4 method for signature 'data.table' to_vect(x, lon = NULL, lat = NULL, crs = "EPSG:4326", ...) ## S4 method for signature 'icesat2.atl03_seg_dt' to_vect(x, ...) ## S4 method for signature 'icesat2.atl08_dt' to_vect(x, ...) ## S4 method for signature 'icesat2.atl03atl08_dt' to_vect(x, ...) ## S4 method for signature 'icesat2.atl03_dt' to_vect(x, ...) ## S4 method for signature 'icesat2.atl03_atl08_seg_dt' to_vect(x, ...) ## S4 method for signature 'sf' to_vect(x, target_crs = NULL, ...)to_vect(x, ...) ## S4 method for signature 'data.frame' to_vect(x, lon = NULL, lat = NULL, crs = "EPSG:4326", ...) ## S4 method for signature 'data.table' to_vect(x, lon = NULL, lat = NULL, crs = "EPSG:4326", ...) ## S4 method for signature 'icesat2.atl03_seg_dt' to_vect(x, ...) ## S4 method for signature 'icesat2.atl08_dt' to_vect(x, ...) ## S4 method for signature 'icesat2.atl03atl08_dt' to_vect(x, ...) ## S4 method for signature 'icesat2.atl03_dt' to_vect(x, ...) ## S4 method for signature 'icesat2.atl03_atl08_seg_dt' to_vect(x, ...) ## S4 method for signature 'sf' to_vect(x, target_crs = NULL, ...)
x |
An |
... |
Ignored. |
lon, lat
|
For |
crs |
CRS string for the resulting SpatVector. Default is "EPSG:4326". |
target_crs |
Optional CRS string (e.g., "EPSG:4326") to reproject the output. |
For plain tables, you can either:
Provide lon= and lat= column names, or
Rely on defaults (longitude / latitude), or
Use common ICESat-2 column names (lon_ph/lat_ph, reference_photon_lon/reference_photon_lat).
A terra::SpatVector object.
A terra::SpatVector
# ICESat2VegR examples (package objects keep their classes): atl03_path <- system.file("extdata", "atl03_clip.h5", package = "ICESat2VegR") atl03_h5 <- ATL03_read(atl03_path = atl03_path) atl03_segment_dt <- ATL03_seg_metadata_dt(atl03_h5 = atl03_h5) atl03_segment_vect <- to_vect(atl03_segment_dt) terra::plot(atl03_segment_vect, col = atl03_segment_vect$segment_ph_cnt) close(atl03_h5) # Plain data.frame / data.table usage: # df <- data.frame(longitude = c(-84, -84.1), latitude = c(29.6, 29.7), z = 1:2) # v <- to_vect(df) # v2 <- to_vect(df, lon = "longitude", lat = "latitude", crs = "EPSG:4326")# ICESat2VegR examples (package objects keep their classes): atl03_path <- system.file("extdata", "atl03_clip.h5", package = "ICESat2VegR") atl03_h5 <- ATL03_read(atl03_path = atl03_path) atl03_segment_dt <- ATL03_seg_metadata_dt(atl03_h5 = atl03_h5) atl03_segment_vect <- to_vect(atl03_segment_dt) terra::plot(atl03_segment_vect, col = atl03_segment_vect$segment_ph_cnt) close(atl03_h5) # Plain data.frame / data.table usage: # df <- data.frame(longitude = c(-84, -84.1), latitude = c(29.6, 29.7), z = 1:2) # v <- to_vect(df) # v2 <- to_vect(df, lon = "longitude", lat = "latitude", crs = "EPSG:4326")
Implements the Random Forest model selection approach of Murphy et al. (2010),
using Breiman's original randomForest implementation. This is a simplified
adaptation of rfUtilities::rf.modelSel, restricted to the Breiman
implementation and modified for the ICESat2VegR package.
It returns the selected variables and importance metrics, but does not fit a final model.
varSel( xdata, ydata, imp.scale = c("mir", "se"), r = c(0.25, 0.5, 0.75), min.imp = NULL, seed = NULL, parsimony = NULL, kappa = FALSE, ... )varSel( xdata, ydata, imp.scale = c("mir", "se"), r = c(0.25, 0.5, 0.75), min.imp = NULL, seed = NULL, parsimony = NULL, kappa = FALSE, ... )
xdata |
Matrix or data.frame of predictor variables (columns = predictors). |
ydata |
Response vector. For classification, |
imp.scale |
Character; type of scaling for importance values, either
|
r |
Numeric vector of importance percentiles to test, e.g.,
|
min.imp |
Optional numeric in |
seed |
Optional integer; sets the random seed in the global R environment. This is strongly recommended for reproducibility. |
parsimony |
Numeric in (0,1); threshold for selecting among competing
models. If specified, models whose errors are within |
kappa |
Logical; use the chance-corrected |
... |
Additional arguments passed to |
For classification, ensure that ydata is a factor; otherwise the model
is fit in regression mode.
Selection strategy:
For classification, candidate models are compared using OOB PCC (or
, if kappa = TRUE) and maximum within-class error,
with preference for more parsimonious models.
For regression, candidate models are compared using percent variance explained and MSE, with preference for more parsimonious models.
After the best model is chosen, the optional min.imp cutoff is
applied to the scaled importance (MIR/SE) from the full model to remove
weak predictors from the final set selvars.
Typical choices for min.imp:
MIR: min.imp in (e.g., keep variables with
at least 20\
SE: min.imp in , remembering that SE-scaled
importance values sum to 1.
An object of class varSel (a list) with components:
selvars Character vector of selected variable names (after
applying min.imp, if provided).
test Data.frame of model-selection diagnostics, containing
error metrics, threshold, number of parameters, and the variables used
in each candidate model (for inspection only).
importance Data.frame of scaled importance values for all
variables in the full model (columns parameter, importance).
sel.importance Data.frame of scaled importance values for the
selected variables.
parameters List of variables used in each candidate model.
scaling Character; the importance scaling used (mir
or se).
randomForest::randomForest() and plot.varSel().
require(randomForest) data(airquality) airquality <- na.omit(airquality) xdata <- airquality[, 2:6] ydata <- airquality[, 1] ntree <- 500 ## Regression example with MIR scaling and importance cutoff vs.regress <- varSel( xdata = xdata, ydata = ydata, imp.scale = "mir", ntree = ntree, min.imp = 0.2 ) vs.regress$selvars ## Plot all variables, highlighting selected ones plot(vs.regress, which = "importance")require(randomForest) data(airquality) airquality <- na.omit(airquality) xdata <- airquality[, 2:6] ydata <- airquality[, 1] ntree <- 500 ## Regression example with MIR scaling and importance cutoff vs.regress <- varSel( xdata = xdata, ydata = ydata, imp.scale = "mir", ntree = ntree, min.imp = 0.2 ) vs.regress$selvars ## Plot all variables, highlighting selected ones plot(vs.regress, which = "importance")
vect_as_ee() converts vector data to a Google Earth Engine
ee$FeatureCollection using reticulate to call the official Python
Earth Engine API-without relying on rgee. It accepts sf/sfc/sfg
objects or terra::SpatVector, validates and reprojects geometries, and
either returns an in-memory FeatureCollection or exports to an EE Asset.
vect_as_ee( x, via = c("getInfo", "getInfo_to_asset"), assetId = NULL, overwrite = TRUE, proj = "EPSG:4326", make_valid = TRUE, quiet = FALSE, monitoring = TRUE, poll_interval_sec = 5, poll_timeout_sec = 3600 )vect_as_ee( x, via = c("getInfo", "getInfo_to_asset"), assetId = NULL, overwrite = TRUE, proj = "EPSG:4326", make_valid = TRUE, quiet = FALSE, monitoring = TRUE, poll_interval_sec = 5, poll_timeout_sec = 3600 )
x |
An input vector object: an |
via |
Character; one of
|
assetId |
Character; EE asset id (e.g., |
overwrite |
Logical; if |
proj |
Character CRS string (e.g., |
make_valid |
Logical; if |
quiet |
Logical; if |
monitoring |
Logical; when exporting to asset, if |
poll_interval_sec |
Numeric; seconds to wait between task status checks
when |
poll_timeout_sec |
Numeric; maximum seconds to keep polling before
timing out. Default |
The function converts x to sf, enforces a defined CRS, optionally fixes
invalid geometries, and transforms to proj (default WGS84).
Properties are carried alongside geometry; however, Earth Engine does not
accept POSIX* timestamp columns or property names containing '.'. The
function stops with a clear error if such columns are found-convert them to
character or rename before calling.
GeoJSON is built in-memory (via geojsonsf when available) or via a
temporary .geojson file as a fallback, then parsed to a list for
ee$FeatureCollection.
Requires a properly initialized EE Python environment (ee.Initialize()
in the active Python session used by reticulate).
If via = "getInfo", returns an in-memory ee$FeatureCollection object
(reticulate Python object). If via = "getInfo_to_asset", returns an
ee$FeatureCollection referencing assetId (after successful export),
or returns immediately if monitoring = FALSE.
Undefined CRS: the function stops if x has no CRS set.
Unsupported columns: the function stops if any property is POSIX* or if
names contain dots (.).
Export failures: if via = "getInfo_to_asset" and the EE task fails or is
cancelled, an error is thrown when monitoring = TRUE.
Earth Engine Python API docs: ee$FeatureCollection
Geometry repair: sf::st_make_valid(), terra::makeValid()
GeoJSON helpers: geojsonsf, sf::st_write()
## Not run: # -- Prerequisites (Python side): # import ee; ee.Initialize() # # Example with sf POINTS library(sf) pts <- st_as_sf(data.frame( id = 1:3, x = c(-84.02171, -84.02025, -84.02026), y = c(31.29891, 31.31945, 31.31938) ), coords = c("x","y"), crs = "EPSG:4326") # In-memory FeatureCollection: fc <- vect_as_ee(pts, via = "getInfo") # Export to an EE asset (monitor until done): # fc_asset <- vect_as_ee( # pts, # via = "getInfo_to_asset", # assetId = "users/you/demo_points", # overwrite = TRUE, # monitoring = TRUE # ) ## End(Not run)## Not run: # -- Prerequisites (Python side): # import ee; ee.Initialize() # # Example with sf POINTS library(sf) pts <- st_as_sf(data.frame( id = 1:3, x = c(-84.02171, -84.02025, -84.02026), y = c(31.29891, 31.31945, 31.31938) ), coords = c("x","y"), crs = "EPSG:4326") # In-memory FeatureCollection: fc <- vect_as_ee(pts, via = "getInfo") # Export to an EE asset (monitor until done): # fc_asset <- vect_as_ee( # pts, # via = "getInfo_to_asset", # assetId = "users/you/demo_points", # overwrite = TRUE, # monitoring = TRUE # ) ## End(Not run)
Converts a data frame or similar tabular object with longitude/latitude
columns into a point layer and writes it to disk as a GeoJSON file.
The function first attempts to use terra via
ICESat2VegR::to_vect(), and falls back to sf if available.
write_geojson( dt, path, xcol = "lon", ycol = "lat", crs = "EPSG:4326", overwrite = TRUE )write_geojson( dt, path, xcol = "lon", ycol = "lat", crs = "EPSG:4326", overwrite = TRUE )
dt |
A data frame, |
path |
Character. Path to the output GeoJSON file. |
xcol, ycol
|
Character. Names of the longitude and latitude columns in
|
crs |
Character. Coordinate reference system of the input coordinates.
Default is |
overwrite |
Logical. If |
Invisibly returns TRUE on success. An error is thrown if both the
terra-based and sf-based write attempts fail.
## Not run: pts <- data.frame( id = 1:3, lon = c(-82.35, -82.34, -82.33), lat = c( 29.65, 29.66, 29.67) ) write_geojson_safe(pts, "points.geojson") ## End(Not run)## Not run: pts <- data.frame( id = 1:3, lon = c(-82.35, -82.34, -82.33), lat = c( 29.65, 29.66, 29.67) ) write_geojson_safe(pts, "points.geojson") ## End(Not run)