Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions .Rbuildignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
^renv$
^renv\.lock$
^LICENSE\.md$
.vscode
46 changes: 46 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
# History files
.Rhistory
.Rapp.history

# Session Data files
.RData
.RDataTmp

# User-specific files
.Ruserdata

# Output files from R CMD build
/*.tar.gz

# Output files from R CMD check
/*.Rcheck/

# RStudio files
.Rproj.user/

# produced vignettes
vignettes/*.html
vignettes/*.pdf

# OAuth2 token, see https://github.com/hadley/httr/releases/tag/v0.3
.httr-oauth

# knitr and R markdown default cache directories
*_cache/
/cache/

# Temporary files created by R markdown
*.utf8.md
*.knit.md

# R Environment Variables
.Renviron

# Rcpp artifacts
*.o
*.so
*.dll

# ignore renv files; if people want to init renv from DESCRIPTION, they should be able to
renv*
.Rprofile
37 changes: 37 additions & 0 deletions .vscode/c_cpp_properties.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
{
// Setup derived from https://github.com/renkun-ken/vscode-rcpp-demo/
"configurations": [
{
"name": "Linux",
"includePath": [
"${workspaceFolder}/**",
"${userHome}/.cache/R/renv/library/${workspaceFolderBasename}*/**/include",
"${userHome}/R/x86_64-pc-linux-gnu-library/4.2/Rcpp/include",
"/usr/share/R/include"
],
"defines": [],
"compilerPath": "/usr/bin/gcc",
"cStandard": "c11",
"cppStandard": "c++17"
},
{
"name": "Mac",
"includePath": [
"${workspaceFolder}/**",
"${userHome}/Library/Caches/org.R-project.R/R/renv/library/${workspaceFolderBasename}*/**/include",
"/Library/Frameworks/R.framework/Resources/include",
"/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include",
"/opt/homebrew/include"
],
"defines": [],
"macFrameworkPath": [
"/System/Library/Frameworks",
"/Library/Frameworks"
],
"compilerPath": "/usr/bin/clang",
"cStandard": "c11",
"cppStandard": "c++17"
}
],
"version": 4
}
19 changes: 17 additions & 2 deletions DESCRIPTION
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,27 @@ Package: rsplash
Type: Package
Title: Simple Process-led Algorithms for Simulating Habitats v2.0
Version: 1.0
Encoding: UTF-8
Date: 2022-11-30
Author: David Sandoval
Maintainer: David Sandoval <[email protected]>
Description: Implementaion of the SPLASH v2.0 Algorithms for calibration-free calculations of water and energy fluxes.
License: AFL (>= 3)
Imports: Rcpp, raster, xts, parallel, topmodel
Imports:
doParallel,
fastmatch,
lubridate,
parallel,
raster,
Rcpp,
topmodel,
xts
Suggests:
spatial.tools,
splashTools
Remotes:
github::dsval/splashTools@d103f33
ByteCompile: TRUE
LinkingTo: Rcpp
RoxygenNote: 7.1.1
RoxygenNote: 7.3.2
Roxygen: list(markdown = TRUE)
13 changes: 6 additions & 7 deletions NAMESPACE
Original file line number Diff line number Diff line change
@@ -1,14 +1,13 @@
useDynLib(rsplash, .registration=TRUE)
exportPattern("^[[:alpha:]]+")
import(Rcpp)
export(splash.point)
# Generated by roxygen2: do not edit by hand

export(splash.grid)
export(splash.point)
export(unSWC)
export(unSWC.grid)
export(upslope_area)
import(Rcpp)
import(raster)
import(topmodel)
import(xts)



importFrom(Rcpp,sourceCpp)
useDynLib(rsplash, .registration = TRUE)
38 changes: 38 additions & 0 deletions R/data.R
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
#' Sample Data
#'
#' @format
#' A list containing
#' - `forcing` as an [xts::xts()] object, and
#' - `soil` as a named double vector.
"ATNeu_example"

#' Bourne SNOTEL station sample data
#'
#' @source <https://wcc.sc.egov.usda.gov/nwcc/site?sitenum=361>
#'
#' @format
#' A list containing
#' - `forcing` as an [xts::xts()] object, and
#' - `max_depth_sm` numeric vector length 1
#' - `soil` as a named double vector.
#' - `md` a metadata [data.frame()] with 1 row and 28 columns
"Bourne"

#' South American sample gridded data
#'
#' Used to construct a [splash.grid()] call. The CRU in the name likely stands for the
#' [Climatic Research
#' Unit](https://research-portal.uea.ac.uk/en/organisations/climatic-research-unit) at
#' the University of East Anglia.
#'
#' @source <https://crudata.uea.ac.uk/cru/data/hrg/>
#'
#' @format
#' A list containing
#' - `tc` a [RasterBrick][raster::Raster-class] of monthly temperature data (mean deg C)
#' - `pn` a [RasterBrick][raster::Raster-class] of monthly precipitation data (mean mm/d or mm/month?)
#' - `sw_in` a [RasterBrick][raster::Raster-class] of monthly precipitation data (mean W m^-2)
#' - `elev` a [RasterLayer][raster::Raster-class] representing a DEM over South America (presumably in average meters above sealevel)
#' - `soil` a [RasterBrick][raster::Raster-class] representing the soil fractions
#' - ⚠️ sometimes adding up to less, sometimes to more than 100% ⚠️
"SA_cru"
27 changes: 22 additions & 5 deletions R/splash.grid.R
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,16 @@
#' R/C++ implementation of the SPLASH v.2.0 algorithm (Davis et al., 2017; Sandoval et al., in prep.).
#'
#' @param sw_in Incoming shortwave solar radiation (W m-2), Raster* object of monthly or daily averages with z time dimension.
#' @param tc Air temperature (C), same dimensions as sw_in
#' @param tc Air temperature (°C), same dimensions as sw_in
#' @param pn Precipitation (mm), same dimensions as sw_in
#' @param elev Elevation (m.a.s.l)
#' @param soil Raster* object with the layers organized as sand(perc),clay(perc),organic matter(perc),coarse-fragments-fraction(perc), bulk density(g cm-3) and depth(m)
#' @param outdir (optional) directory path where the results will be saved, the working directory by default
#' @param tmpdir (optional) directory path where the temporary files will be saved
#' @param sim.control (optional) list including options to control the output: output.mode="monthly" by default, "daily" also available, inmem=FALSE by default write all the results to the disk by chunks to save RAM, sacrificing speed.
#' @param sim.control (optional) list including options to control the output:
#' - monthly_out = TRUE by default; daily if FALSE.
#' - inmem = FALSE by default; writes all the results to the disk by chunks to save RAM,
#' sacrificing speed.
#' @return a list of rasterBricks objects with z time dimension, all of them saved to outdir as netcdf files:
#' \itemize{
#' \item \eqn{wn}: Soil water content (mm) within the first 2 m of depth.
Expand All @@ -24,7 +27,21 @@
#' @keywords splash, evapotranspiration, soil moisture
#' @export
#' @examples
#' splash.grid(sw_in=200, tc=15, pn=10, lat=44,elev=1800,slop=10,asp=270,soil_data=c(sand=44,clay=2,OM=6,fgravel=12))
#' \dontrun{data(SA_cru)
#' splash.grid(
#' sw_in = SA_cru$sw_in,
#' tc = SA_cru$tc,
#' pn = SA_cru$pn,
#' elev = SA_cru$elev,
#' soil = SA_cru$soil,
#' outdir = getwd(),
#' tmpdir = dirname(raster::rasterTmpFile()),
#' sim.control = list(
#' monthly_out = FALSE,
#' inmem = TRUE
#' )
#' )}

splash.grid<-function(sw_in, tc, pn, elev, soil, outdir=getwd(),tmpdir=dirname(rasterTmpFile()),sim.control=list(monthly_out=TRUE,inmem=FALSE)){
###########################################################################
# 00. Check if parallel computation is required by the user and if the dimensions of the raster objects match
Expand Down Expand Up @@ -267,7 +284,7 @@ splash.grid<-function(sw_in, tc, pn, elev, soil, outdir=getwd(),tmpdir=dirname(r
bs <- blockSize(sw_in, minblocks=nodes*10)
}
########################### export the vaiables to the nodes
parallel:::clusterExport(cl, c("sw_in","tc","pn","elev","lat","terraines",'soil','resolution','Au','ztime','bs','splash.point','sim.control'),envir=environment())
parallel::clusterExport(cl, c("sw_in","tc","pn","elev","lat","terraines",'soil','resolution','Au','ztime','bs','splash.point','sim.control'),envir=environment())
pb <- pbCreate(bs$n)
pb <- txtProgressBar(min=1,max = max(bs$n,2), style = 3)
#cat("computing...","\n")
Expand Down Expand Up @@ -358,7 +375,7 @@ splash.grid<-function(sw_in, tc, pn, elev, soil, outdir=getwd(),tmpdir=dirname(r
###############################################################################################
for (i in 1:bs$n) {

d <- parallel:::recvOneData(cl)
d <- parallel::recvOneData(cl)
# error?
if (! d$value$success) {
stop('cluster error:',"\n",d$value$value)
Expand Down
27 changes: 20 additions & 7 deletions R/splash.point.R
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,11 @@
#' R/C++ implementation of the SPLASH v.2.0 algorithm (Davis et al., 2017; Sandoval et al., in prep.).
#'
#' @param sw_in Incoming shortwave solar radiation (W m-2), timeseries object of monthly or daily averages.
#' @param tc Air temperature (C), same timestep as sw_in
#' @param tc Air temperature (°C), same timestep as sw_in
#' @param pn Precipitation (mm), same timestep as sw_in
#' @param elev Elevation (m.a.s.l)
#' @param slop Terrain feature: slope inclination ()
#' @param asp Terrain feature: slope orientation (), standard clockwise from 0.0 North
#' @param slop Terrain feature: slope inclination (°)
#' @param asp Terrain feature: slope orientation (°), standard clockwise from 0.0° North
#' @param soil_data Soil data organized as a vector in the way: c(sand(perc),clay(perc),organic matter(perc),coarse-fragments-fraction(perc), bulk density(g cm-3))
#' @return a time series matrix including:
#' \itemize{
Expand All @@ -25,7 +25,20 @@
#' @keywords splash, evapotranspiration, soil moisture
#' @export
#' @examples
#' splash.point(sw_in=200, tc=15, pn=10, lat=44,elev=1800,slop=10,asp=270,soil_data=c(sand=44,clay=2,OM=6,fgravel=12))
#' data(Bourne)
#' splash.point(
#' sw_in = Bourne$forcing$sw_in,
#' tc = Bourne$forcing$Ta,
#' pn = Bourne$forcing$P,
#' lat = Bourne$md$latitude,
#' elev = Bourne$md$elev_m,
#' slop = Bourne$md$slop_250m,
#' asp = Bourne$md$asp_250m,
#' soil_data = Bourne$soil,
#' Au = Bourne$md$Aups_250m,
#' resolution = 250.0
#' )

splash.point<-function(sw_in, tc, pn, lat,elev,slop=0,asp=0,soil_data,Au=0,resolution=250,time_index=NULL,monthly_out=FALSE,ts_out=TRUE,verbose=TRUE){
###########################################################################
# 010. Check time info
Expand Down Expand Up @@ -252,7 +265,7 @@ soil_hydro<-function(sand, clay, OM, fgravel=0,bd=NA, ...) {
# by Texture and Organic Matter for Hydrologic Solutions.
# Soil Sci. Soc. Am. J. 70, 1569. doi:10.2136/sssaj2005.0117
# Balland, V., Pollacco, J.A.P., Arp, P.A., 2008. Modeling soil hydraulic properties for
# a wide range of soil conditions. Ecol. Modell. 219, 300316. doi:10.1016/j.ecolmodel.2008.07.009
# a wide range of soil conditions. Ecol. Modell. 219, 300-316. doi:10.1016/j.ecolmodel.2008.07.009
# ************************************************************************
results<-list()
########################################################################################
Expand Down Expand Up @@ -524,7 +537,7 @@ frain_func<-function(tc,Tt,Tr,time_index){
# Inputs:
# tc ..... double, air daily temperature C
# Tt... double, parameter threshold temperature,where 50% of precipitation falls as rain
# Tr... double, TR is range of temperatures where both rainfall and snowfall can occur, in C, typically around 13 C
# Tr... double, TR is range of temperatures where both rainfall and snowfall can occur, in °C, typically around 13 °C
# y ....... year
# Returns: fraction of the precipitaion falling as rain
# Features: calculates the fraction of the precipitaion falling as rain, accounting for monthly variations of the parameters
Expand Down Expand Up @@ -568,7 +581,7 @@ snowfall_prob<-function(tc,lat,elev){

# Features: calculates the snowfall occurrence probability
# Ref: Jennings, K.S., Winchell, T.S., Livneh, B., Molotch, N.P., 2018. Spatial variation of the
# rain-snow temperature threshold across the Northern Hemisphere. Nat. Commun. 9, 19. doi:10.1038/s41467-018-03629-7
# rain-snow temperature threshold across the Northern Hemisphere. Nat. Commun. 9, 1-9. doi:10.1038/s41467-018-03629-7
# ************************************************************************
# calibration set
#p_snow<-1/(1+exp(-0.5827+1.319*as.numeric(tc)-as.numeric(elev)*4.18E-4-abs(as.numeric(lat))*1.140E-2))
Expand Down
4 changes: 1 addition & 3 deletions R/unsSWC.R
Original file line number Diff line number Diff line change
@@ -1,15 +1,13 @@
#' unsSWC
#'
#' Estimates water content using an analytca integral of the profile described by Brooks and Corey 1964 and calculates depth to water table if there is any
#' @param soil_data, vector as retrieved from splashTools::getSoilNRCS() or splashTools::getSoilSite()
#' @param soil_data, vector as retrieved from [splashTools::getSoilNRCS()] or [splashTools::getSoilSite()]
#' @param uns_depth, maximum depth to calculate the accumulated water content in (m)
#' @param wn, xts object, total water content of the profile from surface to bedrock (m)
#' @param ouputdir, directory where to save the files
#' @import xts
#' @keywords splashTools
#' @export
#' @examples
#' unSWC()

unSWC<-function(soil_data,uns_depth,wn){
# test
Expand Down
2 changes: 0 additions & 2 deletions R/unsSWC.grid.R
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,6 @@
#' @import raster
#' @keywords splashTools
#' @export
#' @examples
#' unSWC()

unSWC.grid<-function(soil_data,uns_depth,wn,d_name ,outdir=getwd()){
#########################################################################
Expand Down
4 changes: 1 addition & 3 deletions R/upslope_area.R
Original file line number Diff line number Diff line change
@@ -1,14 +1,12 @@
#' upslope_area
#'
#' Computes n cells draining in/out and the contributing area per pixel in m2 using topmodel for small areas or Taudem for large, corrections acording to latitude done by raster::area
#' @param dem
#' @param dem a [RasterLayer][raster::Raster-class] Digital Elevation Model model passed to [topmodel::sinkfill()]
#' @return a RasterStack with the contributing area per pixel, number of cells draining in, and number of cells draining out
#' @import topmodel
#' @import raster
#' @keywords contributing area
#' @export
#' @examples
#' splash.grid()
upslope_area<-function(dem,resolution){

resolution<-cellStats(resolution, stat='mean', na.rm=TRUE)
Expand Down
25 changes: 9 additions & 16 deletions R/zzz.R
Original file line number Diff line number Diff line change
@@ -1,16 +1,9 @@

## Up until R 2.15.0, the require("methods") is needed but (now)
## triggers an warning from R CMD check
#.onLoad <- function(libname, pkgname){
# #require("methods") ## needed with R <= 2.15.0
# loadRcppModules()
#}


## For R 2.15.1 and later this also works. Note that calling loadModule() triggers
## a load action, so this does not have to be placed in .onLoad() or evalqOnLoad().
loadModule("NumEx", TRUE)
loadModule("yada", TRUE)
loadModule("stdVector", TRUE)


## usethis namespace: start
#' @importFrom Rcpp sourceCpp
## usethis namespace: end
NULL

## usethis namespace: start
#' @useDynLib rsplash, .registration = TRUE
## usethis namespace: end
NULL
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -65,3 +65,7 @@ addLegend(legend.loc = "topright", legend.names =c('SWC obs.','SWC sim.'),col=c(
Sandoval, D., Prentice, I. C. and Nóbrega R. (in progress). Simple process-led algorithms for simulating habitats (SPLASH v.2.0): calibration-free calculations of water and energy fluxes

Davis, T.W., Prentice, I.C., Stocker, B.D., Thomas, R.T., Whitley, R.J., Wang, H., Evans, B.J., Gallego-Sala, A. V., Sykes, M.T., Cramer, W., 2017. Simple process-led algorithms for simulating habitats (SPLASH v.1.0): robust indices of radiation, evapotranspiration and plant-available moisture. Geosci. Model Dev. 10, 689–708. doi:10.5194/gmd-10-689-2017

## Development Setup

If you want to work on this codebase using Visual Studio Code, some setup files are included. Assuming you install the extensions `REditorSupport.r` and `ms-vscode.cpptools-extension-pack`, you should get a functioning environment set up and running by executing `renv::init()` and choosing the "explicit" option, i.e., reading package dependencies from the package `DESCRIPTION`.
Loading