Title: | Snow Profile Analysis for Snowpack and Avalanche Research |
---|---|
Description: | Analysis and plotting tools for snow profile data produced from manual snowpack observations and physical snowpack models. The functions in this package support snowpack and avalanche research by reading various formats of data (including CAAML, SMET, generic csv, and outputs from the snow cover model SNOWPACK), manipulate the data, and produce graphics such as stratigraphy and time series profiles. Package developed by the Simon Fraser University Avalanche Research Program <http://www.avalancheresearch.ca>. Graphics apply visualization concepts from Horton, Nowak, and Haegeli (2020, <doi:10.5194/nhess-20-1557-2020>). |
Authors: | Pascal Haegeli [aut, cre], Simon Horton [aut], Florian Herla [aut], SFU Avalanche Research Program [fnd] |
Maintainer: | Pascal Haegeli <[email protected]> |
License: | CC BY-SA 4.0 |
Version: | 1.3.2 |
Built: | 2024-11-06 03:11:14 UTC |
Source: | https://github.com/cran/sarp.snowprofile |
Extract method
## S3 method for class 'snowprofileSet' x[i]
## S3 method for class 'snowprofileSet' x[i]
x |
object from which to extract element(s) or in which to replace element(s). |
i |
indices specifying elements to extract or replace |
snowprofileSet object
Convert character aspects (of snow profile locations) to numeric values. For example, Aspect "N" (north) becomes 0 degrees azimuth.
char2numAspect(charAspect)
char2numAspect(charAspect)
charAspect |
Character string of aspect location, i.e., one of
|
Float value of numeric aspect location, North = 0 degree, S = 180 degree
fherla
char2numAspect("W") char2numAspect("WNW") char2numAspect(c("N", NA, "NA", "NE"))
char2numAspect("W") char2numAspect("WNW") char2numAspect(c("N", NA, "NA", "NE"))
Convert character hand hardness index (HHI) of snow layers to numeric values. For example, hand hardness Fist becomes 1, Ice becomes 6.
char2numHHI(charHHI)
char2numHHI(charHHI)
charHHI |
Character string of hand hardness level, i.e., one of
|
Float value of numeric hand hardness level between 1 and 6.
fherla
char2numHHI('F+') char2numHHI('F-') char2numHHI('F-4F') ## not meaningful: this_throws_error <- TRUE if (!this_throws_error) { char2numHHI('F-P') }
char2numHHI('F+') char2numHHI('F-') char2numHHI('F-4F') ## not meaningful: this_throws_error <- TRUE if (!this_throws_error) { char2numHHI('F-P') }
The function can compute the RTA index for layers and for interfaces. The calculation follows the example in Monti (2013), referenced below. The six individual relative lemons are computed as follows. To compute the RTA index for layers, the layer properties are combined with the interface properties of the weakest interface below or above the layer. To compute the RTA index for interfaces, the interface properties are combined with the weakest layer properties below or above the interface. The six properties considered in the index are
grain size, hardness, grain type (layer properties)
difference of grain sizes and hardness (at the interface)
depth (at the top interface of the layer)
Instead of implementing a static threshold for the depth weighting, the depth is scaled with a weibull function that is corrected for potential crusts and their stabilizing effects (Monti and Mitterer, personal communication).
Note that due to the crust correction, the results from this function will only be correct if applied to profiles
that have not yet been resampled (such as by functions from sarp.snowprofile.alignment: resampleSP
, resampleSPpairs
,
dtw
, averageSP
).
The RTA index ranges between [0, 1]
, with the weakest layer/interface euqal to 1. Values > 0.8 indicate layers/interfaces with a poor structural stability.
computeRTA(x, target = c("interface", "layer")) ## S3 method for class 'snowprofileSet' computeRTA(x, target = c("interface", "layer")) ## S3 method for class 'snowprofile' computeRTA(x, target = c("interface", "layer"))
computeRTA(x, target = c("interface", "layer")) ## S3 method for class 'snowprofileSet' computeRTA(x, target = c("interface", "layer")) ## S3 method for class 'snowprofile' computeRTA(x, target = c("interface", "layer"))
x |
a snowprofile or snowprofileSet. Profile layer properties must be known for all layers (i.e., no NAs in gtype, hardness, gsize allowed!) |
target |
Do you want to compute the index for the layers or for the layer interfaces? defaults to both. |
The input object will be returned with the new layer properties rta
/rta_interface
describing the RTA index added to the profile layers.
computeRTA(snowprofileSet)
: for snowprofileSets
computeRTA(snowprofile)
: for snowprofiles
fherla
Monti, F., & Schweizer, J. (2013). A relative difference approach to detect potential weak layers within a snow profile. Proceedings of the 2013 International Snow Science Workshop, Grenoble, France, 339–343. Retrieved from https://arc.lib.montana.edu/snow-science/item.php?id=1861
## apply function to snowprofileSet profileset <- computeRTA(SPgroup) ## apply function to snowprofile and plot output sp <- computeRTA(SPpairs$B_modeled1) plot(sp, TempProfile = FALSE, main = "RTA") lines(sp$layers$rta*5, sp$layers$height - 0.5*sp$layers$thickness, type = "b", xlim = c(0, 5)) lines(sp$layers$rta_interface*5, sp$layers$height, type = "b", xlim = c(0, 5), col = "red") abline(h = sp$layers$height, lty = "dotted", col = "grey") abline(v = 0.8*5, lty = "dashed")
## apply function to snowprofileSet profileset <- computeRTA(SPgroup) ## apply function to snowprofile and plot output sp <- computeRTA(SPpairs$B_modeled1) plot(sp, TempProfile = FALSE, main = "RTA") lines(sp$layers$rta*5, sp$layers$height - 0.5*sp$layers$thickness, type = "b", xlim = c(0, 5)) lines(sp$layers$rta_interface*5, sp$layers$height, type = "b", xlim = c(0, 5), col = "red") abline(h = sp$layers$height, lty = "dotted", col = "grey") abline(v = 0.8*5, lty = "dashed")
For each layer, compute the average density of all layers above, i.e. <rho>_slab
.
computeSLABrho(profile)
computeSLABrho(profile)
profile |
snowprofile object |
snowprofile object with added layers column $slab_rho
. Note that topmost layer is always NA
.
fherla
For each layer, compute the average density over grain size of all layers above, i.e. <rho/gs>_slab
.
This variable has been found to characterize the cohesion of slabs: new snow slabs tend to consist of low density & large grains, and
more cohesive slabs of older snow tend to consist of higher density & smaller grains (Mayer et al, 2022 in review).
computeSLABrhogs(profile, implementation = c("pub", "literal")[1])
computeSLABrhogs(profile, implementation = c("pub", "literal")[1])
profile |
snowprofile object |
implementation |
|
snowprofile object with added layers column $slab_rhogs
. Note that topmost layer is always NA
.
fherla
This routine computes the traditional lemons (German 'Nieten') based on absolute thresholds. Since the thresholds are
defined in Monti (2014) with different thresholds for manual versus observed profiles, this routine switches between the appropriate
thresholds based on the $type
field of the input profile. While manual
and whiteboard
profiles get one set of thresholds,
modeled
, vstation
, and aggregate
type profiles get another set.
computeTSA(x, target = c("interface", "layer")) ## S3 method for class 'snowprofileSet' computeTSA(x, target = c("interface", "layer")) ## S3 method for class 'snowprofile' computeTSA(x, target = c("interface", "layer"))
computeTSA(x, target = c("interface", "layer")) ## S3 method for class 'snowprofileSet' computeTSA(x, target = c("interface", "layer")) ## S3 method for class 'snowprofile' computeTSA(x, target = c("interface", "layer"))
x |
|
target |
Do you want to compute the index for the layers or for the layer interfaces? defaults to both. |
New layer properties tsa
/tsa_interface
describing the threshold sums are added to the profile layers. The TSA sums up to 6 indicators,
whereas >= 5 indicators indicate structurally unstable layers/interfaces.
computeTSA(snowprofileSet)
: for snowprofileSets
computeTSA(snowprofile)
: for snowprofiles
fherla
Schweizer, J., & Jamieson, J. B. (2007). A threshold sum approach to stability evaluation of manual snow profiles. Cold Regions Science and Technology, 47(1–2), 50–59. https://doi.org/10.1016/j.coldregions.2006.08.011
Monti, F., Schweizer, J., & Fierz, C. (2014). Hardness estimation and weak layer detection in simulated snow stratigraphy. Cold Regions Science and Technology, 103, 82–90. https://doi.org/10.1016/j.coldregions.2014.03.009
## apply function to snowprofileSet profileset <- computeTSA(SPgroup) ## apply function to snowprofile and plot output sp <- computeTSA(SPpairs$B_modeled1) plot(sp, TempProfile = FALSE, main = "TSA") lines(sp$layers$tsa/6*5, sp$layers$height - 0.5*sp$layers$thickness, type = "b", xlim = c(0, 5)) lines(sp$layers$tsa_interface/6*5, sp$layers$height, type = "b", xlim = c(0, 5), col = "red") abline(h = sp$layers$height, lty = "dotted", col = "grey") abline(v = 5/6*5, lty = "dashed")
## apply function to snowprofileSet profileset <- computeTSA(SPgroup) ## apply function to snowprofile and plot output sp <- computeTSA(SPpairs$B_modeled1) plot(sp, TempProfile = FALSE, main = "TSA") lines(sp$layers$tsa/6*5, sp$layers$height - 0.5*sp$layers$thickness, type = "b", xlim = c(0, 5)) lines(sp$layers$tsa_interface/6*5, sp$layers$height, type = "b", xlim = c(0, 5), col = "red") abline(h = sp$layers$height, lty = "dotted", col = "grey") abline(v = 5/6*5, lty = "dashed")
This routine derives the datetags of simulated snow profile layers from deposition dates. Datetags usually are deposition dates
for crust layers, and burial dates for other weak layers (e.g., SH, FC). If no datetags can be derived, a datetag column of NAs will
nevertheless be added to the snowprofile layers. The routine also adds a bdate
column for burial dates that are calculated along the way.
deriveDatetag(x, adjust_bdates = TRUE, ...) ## S3 method for class 'snowprofileSet' deriveDatetag(x, adjust_bdates = TRUE, ...) ## S3 method for class 'snowprofile' deriveDatetag(x, adjust_bdates = TRUE, ...) ## S3 method for class 'snowprofileLayers' deriveDatetag(x, adjust_bdates = TRUE, checkMonotonicity = TRUE, ...)
deriveDatetag(x, adjust_bdates = TRUE, ...) ## S3 method for class 'snowprofileSet' deriveDatetag(x, adjust_bdates = TRUE, ...) ## S3 method for class 'snowprofile' deriveDatetag(x, adjust_bdates = TRUE, ...) ## S3 method for class 'snowprofileLayers' deriveDatetag(x, adjust_bdates = TRUE, checkMonotonicity = TRUE, ...)
x |
a snowprofileSet, snowprofile or snowprofileLayers object |
adjust_bdates |
boolean switch to compute bdates similar to human interpretation. see Details. |
... |
passed on to subsequent methods |
checkMonotonicity |
check ascending order of layers. This acts as a check for whether multiple layers objects are stacked, which is not allowed. |
bdate
s are computed by taking the ddate
of the overlying layer. For snowpack simulations with thin layer
resolution, this approach yields very similar ddate
s and bdate
s for most layers, since most layers form and
instantly get buried by another layer of the same storm. To make bdate
s more similar to human interpretation,
bdate
s can be adjusted, so that (similar) layers with the same ddate
(i.e., same storm) inherit the same bdate
(similar means: identical gtype & hardness).
The input object will be returned with the columns datetag
and bdate
added to the profile layers
deriveDatetag(snowprofileSet)
: for snowprofileSets
deriveDatetag(snowprofile)
: for snowprofiles
deriveDatetag(snowprofileLayers)
: for snowprofileLayers
fherla
## This is not the most meaningful example, but it nicely illustrates the routine: print(SPpairs$A_manual) (A_addedDatetags <- deriveDatetag(SPpairs$A_manual))
## This is not the most meaningful example, but it nicely illustrates the routine: print(SPpairs$A_manual) (A_addedDatetags <- deriveDatetag(SPpairs$A_manual))
Export or write a snowprofile object to a CSV table
export.snowprofileCsv( profile, filename = stop("filename must be provided"), sep = ",", export.all = "Layers", variables = NA )
export.snowprofileCsv( profile, filename = stop("filename must be provided"), sep = ",", export.all = "Layers", variables = NA )
profile |
snowprofile object |
filename |
character string, e.g. 'path/to/file.csv' |
sep |
csv column separator as character string |
export.all |
one of If |
variables |
A tag-value list of the format, e.g. height = 'height_top', to specify column names of specific variables,
to customize column order, and/or to include specific profile meta data if |
Note that existing files with the specified filename will be overwritten without warning!
Writes csv file to disk, no return value in R
fherla
## export an entire snowprofile object: export.snowprofileCsv(SPpairs$A_manual, filename = file.path(tempdir(), 'file.csv'), export.all = TRUE) ## export only the layer properties of a snowprofile object, # and change the column order with few column names: # All layer variables will be exported, but the three ones provided in 'variables' # will be the first three columns of the csv table, and their column names will be changed # accordingly. export.snowprofileCsv(SPpairs$A_manual, filename = file.path(tempdir(), 'file.csv'), export.all = 'Layers', variables = list(height = 'height_top', hardness = 'hardness', gtype = 'gt1')) ## export all layer properties of a snowprofile object plus the station ID: export.snowprofileCsv(SPpairs$A_manual, filename = file.path(tempdir(), 'file.csv'), export.all = 'Layers', variables = list(station_id = 'station_id')) ## check the content of the exported csv file: csv_content <- read.csv(file.path(tempdir(), 'file.csv')) head(csv_content) ## or re-import the csv file as snowprofile object: csv_snowprofile <- snowprofileCsv(file.path(tempdir(), 'file.csv')) print(csv_snowprofile)
## export an entire snowprofile object: export.snowprofileCsv(SPpairs$A_manual, filename = file.path(tempdir(), 'file.csv'), export.all = TRUE) ## export only the layer properties of a snowprofile object, # and change the column order with few column names: # All layer variables will be exported, but the three ones provided in 'variables' # will be the first three columns of the csv table, and their column names will be changed # accordingly. export.snowprofileCsv(SPpairs$A_manual, filename = file.path(tempdir(), 'file.csv'), export.all = 'Layers', variables = list(height = 'height_top', hardness = 'hardness', gtype = 'gt1')) ## export all layer properties of a snowprofile object plus the station ID: export.snowprofileCsv(SPpairs$A_manual, filename = file.path(tempdir(), 'file.csv'), export.all = 'Layers', variables = list(station_id = 'station_id')) ## check the content of the exported csv file: csv_content <- read.csv(file.path(tempdir(), 'file.csv')) head(csv_content) ## or re-import the csv file as snowprofile object: csv_snowprofile <- snowprofileCsv(file.path(tempdir(), 'file.csv')) print(csv_snowprofile)
Find one or more layers of interest, such as persistent weak layers (PWL) in a snowprofile or snowprofileLayers object based on combinations of grain type, datetag, grain size, and stability indices (TSA/ RTA/ critical crack length/ p_unstable) of the layer. The routine can also be used for searching for crusts (or any other grain types).
findPWL( x, pwl_gtype = c("SH", "DH"), pwl_date = NA, date_range = c(-5, 0), date_range_earlier = as.difftime(date_range[1], units = "days"), date_range_later = as.difftime(date_range[2], units = "days"), bdate_range = c(-1, 1), bdate_range_earlier = as.difftime(bdate_range[1], units = "days"), bdate_range_later = as.difftime(bdate_range[2], units = "days"), threshold_gtype = pwl_gtype, threshold_gsize = NA, threshold_TSA = NA, threshold_RTA = NA, threshold_SK38 = NA, threshold_RC = NA, threshold_PU = NA ) labelPWL(x, ...)
findPWL( x, pwl_gtype = c("SH", "DH"), pwl_date = NA, date_range = c(-5, 0), date_range_earlier = as.difftime(date_range[1], units = "days"), date_range_later = as.difftime(date_range[2], units = "days"), bdate_range = c(-1, 1), bdate_range_earlier = as.difftime(bdate_range[1], units = "days"), bdate_range_later = as.difftime(bdate_range[2], units = "days"), threshold_gtype = pwl_gtype, threshold_gsize = NA, threshold_TSA = NA, threshold_RTA = NA, threshold_SK38 = NA, threshold_RC = NA, threshold_PU = NA ) labelPWL(x, ...)
x |
snowprofile or snowprofileLayers object |
pwl_gtype |
a vector of grain types of interest |
pwl_date |
a date of interest given as character ('YYYY-MM-DD') or as POSIXct; set to |
date_range |
a numeric array of length 2 that defines a date search window around |
date_range_earlier |
a difftime object of |
date_range_later |
a difftime object of |
bdate_range |
a numeric array of length 2 that defines a date search window around |
bdate_range_earlier |
a difftime object of |
bdate_range_later |
a difftime object of |
threshold_gtype |
specific grain types that are only deemed a PWL if they pass one or multiple thresholds (see next parameters) |
threshold_gsize |
a threshold grain size in order to deem |
threshold_TSA |
a threshold TSA value (see computeTSA) in order to deem |
threshold_RTA |
a threshold RTA value (see computeRTA) in order to deem |
threshold_SK38 |
a threshold SK38 in order to deem |
threshold_RC |
a threshold critical crack length in order to deem |
threshold_PU |
a threshold value for p_unstable in order to deem |
... |
passed on to findPWL |
In case date considerations are included in your search, either one of the date window conditions needs to be satisfied to return a given layer:
ddate
or datetag
within date_range
, or
bdate
within bdate_range
If the input object contains deposition dates (ddate
, mostly in simulated profiles),
but no bdates
, they are automatically computed by deriveDatetag;
otherwise the date window is applied to the datetag
(mostly for manual profiles).
If you apply thresholds to your search, only layers are returned that satisfy at least one of the provided thresholds.
The labelPWL
wrapper function is primarily used by sarp.snowprofile.alignment::averageSP
.
findPWL
: An index vector of PWLs that match the desired requirements
labelPWL
: The input object with an extra boolean column appended to the layer object, called $layerOfInterest
.
findPWL()
: Find layers of interest (e.g., PWLs) in snowprofile
or snowprofileLayers
labelPWL()
: Label layers of interest (e.g., weak layers) in snowprofile
fherla
## get index vector: findPWL(SPpairs$A_modeled) ## get layers subset: SPpairs$A_manual$layers[findPWL(SPpairs$A_manual), ] SPpairs$A_manual$layers[findPWL(SPpairs$A_manual, threshold_gsize = 2.2, threshold_gtype = c("FC", "FCxr")), ] ## all (SH, DH), and (FC, FCxr) >= 1 mm grain size: SPpairs$A_modeled$layers[findPWL(SPpairs$A_modeled, pwl_gtype = c("SH", "DH", "FC", "FCxr"), threshold_gsize = 1, threshold_gtype = c("FC", "FCxr")), ] ## use TSA threshold: SPpairs$A_modeled <- computeTSA(SPpairs$A_modeled) SPpairs$A_modeled$layers[findPWL(SPpairs$A_modeled, pwl_gtype = c("SH", "DH", "FC", "FCxr"), threshold_TSA = 4, threshold_gtype = c("FC", "FCxr")), ] ## searching for a specific pwl_date: ## let's construct one layer and an array of pwl_dates tl <- snowprofileLayers(height = 1, gtype = "SH", ddate = as.POSIXct("2020-12-15"), bdate = as.POSIXct("2020-12-20")) pwl_dates <- paste0("2020-12-", seq(14, 22)) ## which pwl_date will 'find' that layer? sapply(pwl_dates, function(dt) length(findPWL(tl, pwl_date = dt)) > 0) ## same example, but with bdate being NA: tl <- snowprofileLayers(height = 1, gtype = "SH", ddate = as.POSIXct("2020-12-15"), bdate = as.POSIXct(NA), dropNAs = FALSE) sapply(pwl_dates, function(dt) length(findPWL(tl, pwl_date = dt)) > 0) ## pwl_date example with proper profile: sp <- deriveDatetag(SPpairs$A_manual) sp$layers pwl_dates <- paste0("2019-02-", seq(18, 26)) names(pwl_dates) <- pwl_dates ## which pwl_date will 'find' the two layers with (b)date labels? list(pwl_date = lapply(pwl_dates, function(dt) { sp$layers[findPWL(sp, pwl_gtype = c("SH", "FC"), pwl_date = dt), c("height", "gtype", "ddate", "bdate")] })) ## same example as above, but including TSA threshold: sp <- computeTSA(sp) ## the SH layer has TSA 5, the FC layer has TSA 4: list(pwl_date = lapply(pwl_dates, function(dt) { sp$layers[findPWL(sp, pwl_gtype = c("SH", "FC"), pwl_date = dt, threshold_TSA = 5), c("height", "gtype", "ddate", "bdate")] })) ## --> no more FC layer in output since its TSA value is below the threshold! ## can also be used to search for crusts: SPpairs$A_manual$layers[findPWL(SPpairs$A_manual, pwl_gtype = "MFcr"), ]
## get index vector: findPWL(SPpairs$A_modeled) ## get layers subset: SPpairs$A_manual$layers[findPWL(SPpairs$A_manual), ] SPpairs$A_manual$layers[findPWL(SPpairs$A_manual, threshold_gsize = 2.2, threshold_gtype = c("FC", "FCxr")), ] ## all (SH, DH), and (FC, FCxr) >= 1 mm grain size: SPpairs$A_modeled$layers[findPWL(SPpairs$A_modeled, pwl_gtype = c("SH", "DH", "FC", "FCxr"), threshold_gsize = 1, threshold_gtype = c("FC", "FCxr")), ] ## use TSA threshold: SPpairs$A_modeled <- computeTSA(SPpairs$A_modeled) SPpairs$A_modeled$layers[findPWL(SPpairs$A_modeled, pwl_gtype = c("SH", "DH", "FC", "FCxr"), threshold_TSA = 4, threshold_gtype = c("FC", "FCxr")), ] ## searching for a specific pwl_date: ## let's construct one layer and an array of pwl_dates tl <- snowprofileLayers(height = 1, gtype = "SH", ddate = as.POSIXct("2020-12-15"), bdate = as.POSIXct("2020-12-20")) pwl_dates <- paste0("2020-12-", seq(14, 22)) ## which pwl_date will 'find' that layer? sapply(pwl_dates, function(dt) length(findPWL(tl, pwl_date = dt)) > 0) ## same example, but with bdate being NA: tl <- snowprofileLayers(height = 1, gtype = "SH", ddate = as.POSIXct("2020-12-15"), bdate = as.POSIXct(NA), dropNAs = FALSE) sapply(pwl_dates, function(dt) length(findPWL(tl, pwl_date = dt)) > 0) ## pwl_date example with proper profile: sp <- deriveDatetag(SPpairs$A_manual) sp$layers pwl_dates <- paste0("2019-02-", seq(18, 26)) names(pwl_dates) <- pwl_dates ## which pwl_date will 'find' the two layers with (b)date labels? list(pwl_date = lapply(pwl_dates, function(dt) { sp$layers[findPWL(sp, pwl_gtype = c("SH", "FC"), pwl_date = dt), c("height", "gtype", "ddate", "bdate")] })) ## same example as above, but including TSA threshold: sp <- computeTSA(sp) ## the SH layer has TSA 5, the FC layer has TSA 4: list(pwl_date = lapply(pwl_dates, function(dt) { sp$layers[findPWL(sp, pwl_gtype = c("SH", "FC"), pwl_date = dt, threshold_TSA = 5), c("height", "gtype", "ddate", "bdate")] })) ## --> no more FC layer in output since its TSA value is below the threshold! ## can also be used to search for crusts: SPpairs$A_manual$layers[findPWL(SPpairs$A_manual, pwl_gtype = "MFcr"), ]
Calculate missing data.frame columns based on the given ones, if possible.
format_snowprofileLayers( obj, target = "all", hs = NA, maxObservedDepth = NA, validate = TRUE, dropNAs = TRUE )
format_snowprofileLayers( obj, target = "all", hs = NA, maxObservedDepth = NA, validate = TRUE, dropNAs = TRUE )
obj |
snowprofileLayers object |
target |
string, indicating which fields are auto-filled ('all', 'height', 'depth', 'thickness', 'none') |
hs |
total snow height (cm) if not deductible from given fields |
maxObservedDepth |
the observed depth of the profile from the snow surface downwards.
Will only be used, if no |
validate |
Validate |
dropNAs |
Do you want to drop all columns consisting of NAs only? |
copy of obj with auto-filled columns
Gets colours for plotting snow density values in snowprofiles. Colours are consistent with niViz at https://niviz.org
getColoursDensity(Values, Resolution = 101, Verbose = FALSE)
getColoursDensity(Values, Resolution = 101, Verbose = FALSE)
Values |
Density values (kg/m3) |
Resolution |
Resolution of colour scale. Default is 100. |
Verbose |
Switch for writing out value and html colour tuplets for debugging. |
Array with HTML colour codes
phaegeli
getColoursGrainSize, getColoursGrainType, getColoursHardness, getColoursLWC, getColoursSnowTemp
Density <- seq(0,700, by=10) plot(x = rep(1,length(Density)), y = Density, col = getColoursDensity(Density), pch = 19, cex = 3)
Density <- seq(0,700, by=10) plot(x = rep(1,length(Density)), y = Density, col = getColoursDensity(Density), pch = 19, cex = 3)
Gets colours for plotting grain size values in snowprofiles. Colours are consistent with niViz at https://niviz.org
getColoursGrainSize(Values, Resolution = 101, Verbose = FALSE)
getColoursGrainSize(Values, Resolution = 101, Verbose = FALSE)
Values |
Liquid water content values |
Resolution |
Resolution of colour scale. Default is 100. |
Verbose |
Switch for writing out value and html colour tuplets for debugging. |
Array with HTML colour codes
phaegeli
getColoursDensity, getColoursGrainType, getColoursHardness, getColoursLWC, getColoursSnowTemp
GrainSize <- seq(0,6, by=0.1) plot(x = rep(1,length(GrainSize)), y = GrainSize, col = getColoursGrainSize(GrainSize), pch = 19, cex = 3)
GrainSize <- seq(0,6, by=0.1) plot(x = rep(1,length(GrainSize)), y = GrainSize, col = getColoursGrainSize(GrainSize), pch = 19, cex = 3)
Grain colours are defined in the grainDict
data.frame and the definitions can be changed with setColoursGrainType
getColoursGrainType(Grains, grainDict. = grainDict)
getColoursGrainType(Grains, grainDict. = grainDict)
Grains |
grain type (character or list of characters) |
grainDict. |
lookup table to use. Note, the easiest and best way to do this is via |
Array with HTML colour codes
phaegeli, shorton, fherla
setColoursGrainType, getColoursDensity, getColoursGrainSize, getColoursHardness, getColoursLWC, getColoursSnowTemp
Grains <- c('PP', 'DF', 'RG', 'FC', 'FCxr', 'DH', 'SH', 'MF', 'MFcr', 'IF') Colours <- getColoursGrainType(Grains) Colours plot(1:length(Grains), col = Colours, pch = 20, cex = 3) text(1:length(Grains), 1:length(Grains), Grains, pos = 1)
Grains <- c('PP', 'DF', 'RG', 'FC', 'FCxr', 'DH', 'SH', 'MF', 'MFcr', 'IF') Colours <- getColoursGrainType(Grains) Colours plot(1:length(Grains), col = Colours, pch = 20, cex = 3) text(1:length(Grains), 1:length(Grains), Grains, pos = 1)
Gets colours for plotting snow hardness values in snowprofiles.
getColoursHardness(Values, Resolution = 101, Verbose = FALSE)
getColoursHardness(Values, Resolution = 101, Verbose = FALSE)
Values |
Hardness values |
Resolution |
Resolution of colour scale. Default is 100. |
Verbose |
Switch for writing out value and html colour tuplets for debugging. |
Array with HTML colour codes
phaegeli
getColoursDensity, getColoursGrainSize, getColoursGrainType, getColoursLWC, getColoursSnowTemp
Hardness <- c(1:5) plot(x = rep(1,length(Hardness)), y = Hardness, col = getColoursHardness(Hardness), pch = 19,cex = 3)
Hardness <- c(1:5) plot(x = rep(1,length(Hardness)), y = Hardness, col = getColoursHardness(Hardness), pch = 19,cex = 3)
Gets colours for plotting LWC values in snowprofiles. Colours are consistent with niViz at https://niviz.org
getColoursLWC(Values, Resolution = 101, Verbose = FALSE)
getColoursLWC(Values, Resolution = 101, Verbose = FALSE)
Values |
Liquid water content values |
Resolution |
Resolution of colour scale. Default is 100. |
Verbose |
Switch for writing out value and html colour tuplets for debugging. |
Array with HTML colour codes
phaegeli
getColoursDensity, getColoursGrainSize, getColoursGrainType, getColoursHardness, getColoursSnowTemp
LWC <- seq(0,6, by = 0.1) plot(x = rep(1,length(LWC)), y = LWC, col = getColoursLWC(LWC), pch = 19, cex = 3)
LWC <- seq(0,6, by = 0.1) plot(x = rep(1,length(LWC)), y = LWC, col = getColoursLWC(LWC), pch = 19, cex = 3)
Gets colours for plotting the snow layer property 'percentage', as used for example for distributions from 0–1.
getColoursPercentage( Values, Resolution = 101, Min = 0, Max = 1, ClrRamp = c("Blues", "Greys", "Greys_transparent")[1] )
getColoursPercentage( Values, Resolution = 101, Min = 0, Max = 1, ClrRamp = c("Blues", "Greys", "Greys_transparent")[1] )
Values |
of the 'percentage' variable |
Resolution |
Resolution of colour scale. Default is 100. |
Min |
Minimum values of the percentage (for colouring) |
Max |
Maximum –=– |
ClrRamp |
Three different colourmaps can be chosen from: "Blues", "Greys", "Greys_transparent" |
Array with HTML colour codes
fherla
getColoursGrainSize, getColoursGrainType, getColoursHardness, getColoursLWC, getColoursSnowTemp, getColoursStability
prct <- seq(0, 1, by=0.1) plot(x = rep(1,length(prct)), y = prct, col = getColoursPercentage(prct), pch = 19, cex = 3) plot(x = rep(1,length(prct)), y = prct, col = getColoursPercentage(prct, ClrRamp = "Greys"), pch = 19, cex = 3)
prct <- seq(0, 1, by=0.1) plot(x = rep(1,length(prct)), y = prct, col = getColoursPercentage(prct), pch = 19, cex = 3) plot(x = rep(1,length(prct)), y = prct, col = getColoursPercentage(prct, ClrRamp = "Greys"), pch = 19, cex = 3)
Gets colours for plotting snow temperature values in snowprofiles. Colours are consistent with niViz at https://niviz.org
getColoursSnowTemp(Values, Resolution = 101, Verbose = FALSE)
getColoursSnowTemp(Values, Resolution = 101, Verbose = FALSE)
Values |
Snow temperature values |
Resolution |
Resolution of colour scale. Default is 100. |
Verbose |
Switch for writing out value and html colour tuplets for debugging. |
Array with HTML colour codes
phaegeli
getColoursDensity, getColoursGrainSize, getColoursGrainType, getColoursHardness, getColoursLWC
SnowTemp <- c(-25:0) plot(x = rep(1,length(SnowTemp)), y = SnowTemp, col = getColoursSnowTemp(SnowTemp), pch = 19,cex = 3)
SnowTemp <- c(-25:0) plot(x = rep(1,length(SnowTemp)), y = SnowTemp, col = getColoursSnowTemp(SnowTemp), pch = 19,cex = 3)
Gets colours for plotting snow stability indices in snowprofiles.
getColoursStability( Values, StabilityIndexThreshold = 0.77, StabilityIndexRange = c(0, 1), invers = FALSE, Resolution = 100 )
getColoursStability( Values, StabilityIndexThreshold = 0.77, StabilityIndexRange = c(0, 1), invers = FALSE, Resolution = 100 )
Values |
Stability index values |
StabilityIndexThreshold |
A scalar threshold that defines the transition from medium to poor stability. The color scheme will be adjusted so that this threshold becomes apparent from the colours. |
StabilityIndexRange |
The range the index spans, e.g. for TSA |
invers |
Indices like TSA/ RTA/ p_unstable increase the poorer layer stability gets. For indices with revers behaviour (e.g.,, critical crack length) switch this flag to |
Resolution |
Resolution of colour scale. Default is 100. |
Array with HTML colour codes
fherla
getColoursGrainSize, getColoursGrainType, getColoursHardness, getColoursLWC, getColoursSnowTemp, getColoursPercentage
p_unstable <- seq(0, 1, by=0.1) plot(x = rep(1,length(p_unstable)), y = p_unstable, col = getColoursStability(p_unstable), pch = 19, cex = 3) critical_crack_length <- c(seq(0.2, 0.8, by=0.1), 1.5, 2.5) plot(x = rep(1,length(critical_crack_length)), y = critical_crack_length, pch = 19, cex = 3, col = getColoursStability(critical_crack_length, StabilityIndexThreshold = 0.4, StabilityIndexRange = c(0, 3), invers = TRUE))
p_unstable <- seq(0, 1, by=0.1) plot(x = rep(1,length(p_unstable)), y = p_unstable, col = getColoursStability(p_unstable), pch = 19, cex = 3) critical_crack_length <- c(seq(0.2, 0.8, by=0.1), 1.5, 2.5) plot(x = rep(1,length(critical_crack_length)), y = critical_crack_length, pch = 19, cex = 3, col = getColoursStability(critical_crack_length, StabilityIndexThreshold = 0.4, StabilityIndexRange = c(0, 3), invers = TRUE))
The colours can be changed by calling the function setColoursGrainType, see examples below.
grainDict
grainDict
A data.frame
print(grainDict) ## change colours for subsequent plots: grainDict <- setColoursGrainType('sarp-reduced')
print(grainDict) ## change colours for subsequent plots: grainDict <- setColoursGrainType('sarp-reduced')
Check whether a profile is observed down to ground or not
hasUnobservedBasalLayer(x)
hasUnobservedBasalLayer(x)
x |
a snowprofile, or snowprofileLayers object |
boolean TRUE/FALSE
Import R_DEFAULT_PACKAGES
importRDefaultPackages()
importRDefaultPackages()
Insert a special layer at the bottom to indicate a snow profile that's unobserved from a specific point down to the ground internal function, not exported. used in snowprofileLayers
insertUnobservedBasalLayer(object, basal_offset, setBasalThicknessNA = FALSE)
insertUnobservedBasalLayer(object, basal_offset, setBasalThicknessNA = FALSE)
object |
snowprofileLayers object |
basal_offset |
a positive numeric scalar indicating the thickness of the basal unobserved layer(s) |
setBasalThicknessNA |
boolean TRUE/FALSE indicating whether the thickness of the inserted layer should be |
same object with basal layer inserted as individual row in the data.frame
fherla
Check if object is of class snowprofile
is.snowprofile(x)
is.snowprofile(x)
x |
object to test |
boolean
Check if object is of class snowprofileInstabilitySigns
is.snowprofileInstabilitySigns(x)
is.snowprofileInstabilitySigns(x)
x |
object to test |
boolean
Check if object is of class snowprofileLayers
is.snowprofileLayers(x)
is.snowprofileLayers(x)
x |
object to test |
boolean
Check if object is of class snowprofileSet
is.snowprofileSet(x)
is.snowprofileSet(x)
x |
object to test |
boolean
Check if object is of class snowprofileTests
is.snowprofileTests(x)
is.snowprofileTests(x)
x |
object to test |
boolean
Low-cost, efficient constructor function to be used by users who know what they're doing. If that's not you, use the high-level constructor snowprofile.
new_snowprofile( station = character(), station_id = character(), datetime = as.POSIXct(NA), latlon = as.double(c(NA, NA)), elev = double(), angle = double(), aspect = double(), hs = double(), maxObservedDepth = double(), type = character(), band = character(), zone = character(), comment = character(), hn24 = double(), hn72 = double(), ski_pen = double(), layers = snowprofileLayers(), tests = snowprofileTests(), instabilitySigns = snowprofileInstabilitySigns() )
new_snowprofile( station = character(), station_id = character(), datetime = as.POSIXct(NA), latlon = as.double(c(NA, NA)), elev = double(), angle = double(), aspect = double(), hs = double(), maxObservedDepth = double(), type = character(), band = character(), zone = character(), comment = character(), hn24 = double(), hn72 = double(), ski_pen = double(), layers = snowprofileLayers(), tests = snowprofileTests(), instabilitySigns = snowprofileInstabilitySigns() )
station |
character string |
station_id |
character string |
datetime |
date and time as class POSIXct in most meaningful timezone (timezone can be converted very easily:
e.g. |
latlon |
2-element vector latitude (first), longitude (second) |
elev |
profile elevation (m) |
angle |
slope angle (degree) |
aspect |
slope aspect (degree) |
hs |
total snow height (cm); if not provided, the field will be derived from the profile layers. |
maxObservedDepth |
equivalent to |
type |
character string, must be either 'manual', 'modeled', 'vstation', 'aggregate', or 'whiteboard' |
band |
character string describing elevation band as ALP, TL, BTL (alpine, treeline, below treeline) |
zone |
character string describing the zone or region of the profile location (e.g., BURNABY_MTN) |
comment |
character string with any text comments |
hn24 |
height of new snow within 24 h |
hn72 |
height of new snow within 72 h |
ski_pen |
skier penetration depth (m) |
layers |
snowprofileLayers object |
tests |
snowprofileTests object |
instabilitySigns |
snowprofileInstabilitySigns object |
snowprofile object
This is a wrapper function to bin several weak layers (or crusts) into vertical levels. The layers to be binned can be controlled with a provided index vector for full customization.
numberOfPWLsPerVerticalLevel(x, pwl_idx, depth_breaks = c(0, 30, 80, 150, Inf))
numberOfPWLsPerVerticalLevel(x, pwl_idx, depth_breaks = c(0, 30, 80, 150, Inf))
x |
snowprofile or snowprofileLayers object |
pwl_idx |
an index vector that corresponds to the layers of interest. Tip: this can also be a call to findPWL, see examples. |
depth_breaks |
a vector of break points referring to absolute depth values. |
This function returns a table
object
fherla
SH_idx <- findPWL(SPpairs$C_day1, pwl_gtype = "SH") numberOfPWLsPerVerticalLevel(SPpairs$C_day1, SH_idx) numberOfPWLsPerVerticalLevel(SPpairs$C_day2, findPWL(SPpairs$C_day2))
SH_idx <- findPWL(SPpairs$C_day1, pwl_gtype = "SH") numberOfPWLsPerVerticalLevel(SPpairs$C_day1, SH_idx) numberOfPWLsPerVerticalLevel(SPpairs$C_day2, findPWL(SPpairs$C_day2))
Plot hardness profile
## S3 method for class 'snowprofile' plot( x, TempProfile = TRUE, xlimTemp = NULL, Col = "auto", TopDown = "auto", axes = TRUE, xlab = "", emphasizeLayers = FALSE, emphasis = "95", failureLayers = FALSE, failureLayers.cex = 1, failureLayers.col = "red", nYTicks = 4, ymax = max(c(x$maxObservedDepth, x$hs), na.rm = TRUE), alignWithBottomUpPlot = FALSE, highlightUnobservedBasalLayers = TRUE, label.datetags = FALSE, ... )
## S3 method for class 'snowprofile' plot( x, TempProfile = TRUE, xlimTemp = NULL, Col = "auto", TopDown = "auto", axes = TRUE, xlab = "", emphasizeLayers = FALSE, emphasis = "95", failureLayers = FALSE, failureLayers.cex = 1, failureLayers.col = "red", nYTicks = 4, ymax = max(c(x$maxObservedDepth, x$hs), na.rm = TRUE), alignWithBottomUpPlot = FALSE, highlightUnobservedBasalLayers = TRUE, label.datetags = FALSE, ... )
x |
snowprofile object |
TempProfile |
draw unscaled temperature profile (default = TRUE)? Temperature data needs to be included in the
snowprofile object either under |
xlimTemp |
the x limits in degrees Celsius for the temperature profile (if left empty it scales to the range of temperature values) |
Col |
vector of colours corresponding to the grain types in the profile (defaults to a lookup table) |
TopDown |
Option to plot by depth instead of height with zero depth on top of plot (default = FALSE) |
axes |
Should axes be printed? |
xlab |
x-axis label, defaults to an empty string |
emphasizeLayers |
index OR character vector (grain types) of layers to be emphasized (i.e. all other layers become slightly transparent) |
emphasis |
2 digit quoted number between |
failureLayers |
height vector of failure layers that will be indicated with an arrow |
failureLayers.cex |
factor to shrink or enlarge the arrow |
failureLayers.col |
color of arrow, can also be a vector of same length as |
nYTicks |
number of tick marks at yaxis |
ymax |
the maximum ylim value |
alignWithBottomUpPlot |
useful when aligning the yaxis grids of bottom up profileSet plots and top down hardness plots. |
highlightUnobservedBasalLayers |
draw sine wave at lowest observed layer to highlight unobserved layers below |
label.datetags |
label the datetags of the snowprofile layers? (Won't produce a pretty plot, but give you some more information for analysis) |
... |
other parameters to barplot |
plot(SPpairs$A_manual) plot(SPpairs$A_manual, Col = 'black') plot(SPpairs$A_manual, emphasizeLayers = c(5, 11), failureLayers = SPpairs$A_manual$layers$height[5], failureLayers.cex = 1.5) plot(SPpairs$A_manual, emphasizeLayers = 'SH') plot(SPpairs$A_manual, TopDown = TRUE) plot(SPpairs$A_modeled, TempProfile = TRUE, xlimTemp = c(-30,10)) # highlight unobserved basal layers: plot(snowprofile(layers = snowprofileLayers(depth = c(40, 25, 0), hardness = c(2, 3, 1), gtype = c('FC', NA, 'PP'), hs = 70, maxObservedDepth = 50)), TopDown = TRUE, ymax = 80)
plot(SPpairs$A_manual) plot(SPpairs$A_manual, Col = 'black') plot(SPpairs$A_manual, emphasizeLayers = c(5, 11), failureLayers = SPpairs$A_manual$layers$height[5], failureLayers.cex = 1.5) plot(SPpairs$A_manual, emphasizeLayers = 'SH') plot(SPpairs$A_manual, TopDown = TRUE) plot(SPpairs$A_modeled, TempProfile = TRUE, xlimTemp = c(-30,10)) # highlight unobserved basal layers: plot(snowprofile(layers = snowprofileLayers(depth = c(40, 25, 0), hardness = c(2, 3, 1), gtype = c('FC', NA, 'PP'), hs = 70, maxObservedDepth = 50)), TopDown = TRUE, ymax = 80)
A flexible function to plot multiple snowprofiles either in a timeseries or various types of groups.
## S3 method for class 'snowprofileSet' plot( x, SortMethod = c("time", "unsorted", "hs", "elev", "presorted"), ColParam = c("gtype", "hardness", "density", "temp", "gsize", "ssi", "p_unstable", "crit_cut_length", "rta", "percentage"), TopDown = FALSE, DateStart = NA, DateEnd = NA, Timeseries_labels = c("weekly", "monthly", NA), ylim = NULL, OutlineLyrs = FALSE, emphasizeLayers = NULL, colAlpha = NA, colEmphasis = NA, OutlineProfile = NULL, HorizGrid = TRUE, VerticalGrid = TRUE, yaxis = TRUE, main = NA, ylab = NA, xlab = NA, box = TRUE, xticklabels = FALSE, xtick.las = 2, yPadding = 10, xPadding = 0.5, hardnessResidual = 1, hardnessScale = 1, hardnessOffset = -0.5, k = NULL, offset = as.Date(NA), add = FALSE, ... )
## S3 method for class 'snowprofileSet' plot( x, SortMethod = c("time", "unsorted", "hs", "elev", "presorted"), ColParam = c("gtype", "hardness", "density", "temp", "gsize", "ssi", "p_unstable", "crit_cut_length", "rta", "percentage"), TopDown = FALSE, DateStart = NA, DateEnd = NA, Timeseries_labels = c("weekly", "monthly", NA), ylim = NULL, OutlineLyrs = FALSE, emphasizeLayers = NULL, colAlpha = NA, colEmphasis = NA, OutlineProfile = NULL, HorizGrid = TRUE, VerticalGrid = TRUE, yaxis = TRUE, main = NA, ylab = NA, xlab = NA, box = TRUE, xticklabels = FALSE, xtick.las = 2, yPadding = 10, xPadding = 0.5, hardnessResidual = 1, hardnessScale = 1, hardnessOffset = -0.5, k = NULL, offset = as.Date(NA), add = FALSE, ... )
x |
An object of class snowprofileSet |
SortMethod |
How to arrange profiles along the x-axis. Options include timeseries (default = 'time'), in existing order of Profiles list ('unsorted'), sorted by HS ('hs'), or elevation ('elev') |
ColParam |
What parameter to show with colour. So far the following types are available: "gtype", "hardness", "density", "temp", "gsize", "ssi", "p_unstable", "crit_cut_length", "rta", "percentage". |
TopDown |
Option to plot by depth instead of height with zero depth on top of plot (default = FALSE) |
DateStart |
Start date for timeseries plots ( |
DateEnd |
End date for timeseries plots ( |
Timeseries_labels |
Label Saturdays "weekly", "monthly", or |
ylim |
Vertical range of plot |
OutlineLyrs |
Switch for outlining layers (default = FALSE) |
emphasizeLayers |
emphasize layers with different transparency than others, or a different color altogether? then set this argument to |
colAlpha |
the transparency setting for all layers (except the ones to be emphasized if you want to emphasize any). This can be useful for example if you want to overplot the grain type sequences with another variable, e.g. a percentage from a distribution. |
colEmphasis |
the color of the layers to be emphasized (only if you want a different color than defined by |
OutlineProfile |
vector of profile indices that will be outlined to highlight them |
HorizGrid |
Draw horizontal grid at layer heights (default = TRUE) |
VerticalGrid |
Draw vertical grid at xticks (default = TRUE) |
yaxis |
draw a y-axis? (either |
main |
Main title |
ylab |
y-axis label; disable ylab by providing an empty string (i.e., ylab = ”) |
xlab |
x-axis label; disable xlab by providing an empty string (i.e., xlab = ”) |
box |
Draw a box around the plot (default = TRUE) |
xticklabels |
Label the profiles with their "names", "originalIndices" (prior to sorting), "dates", or a custom character array |
xtick.las |
Orientation of labels if xticklabels is specified. |
yPadding |
Padding between ylim and limits of data, default = 10.
Note that R will still put padding by default. If you want to prohibit that entirely, specify |
xPadding |
Padding between xlim and limits of data, default = 0.5.
Note that R will still put padding by default. If you want to prohibit that entirely, specify |
hardnessResidual |
Value within |
hardnessScale |
A scaling factor that exaggerates the hardness profile to subsequent cells on the x-axis. Useful
for time series of sparse profile observations. Note that this scaling factor is unused when |
hardnessOffset |
offsets the profile location on the x-axis |
k |
a sorting vector if |
offset |
Provide a Date or POSIXct offset if you want to offset the vertical snow height/depth axis so that the offset date aligns with snow depth/height 0. |
add |
add the plot to an existing plot, or create new plot? |
... |
Additional parameters passed to plot() |
The routine allows you to plot coloured sequences only, or to include hardness profile information as well. See parameter
hardnessResidual
and the examples for more details.
To change the font size of labels etc, use par()
with the parameters cex.lab
, cex.axis
, etc.
shorton, fherla, phaegeli
## Standard profile timeline (e.g. https://niviz.org) plot(SPtimeline) ## Group of profiles with same timestamp plot(SPgroup, SortMethod = 'unsorted') # sorted in same order as list plot(SPgroup, SortMethod = 'hs') # sorted by snow height plot(SPgroup, SortMethod = 'elev') # sorted by elevation ## Colour layers by other properties plot(SPtimeline, ColParam = 'density') ## Align layers by depth instead of height plot(SPtimeline, TopDown = TRUE) ## Timelines with specific date ranges plot(SPtimeline, DateEnd = '2017-12-17') plot(SPtimeline, DateStart = '2017-12-15', DateEnd = '2017-12-17') ## Show hardness profile, too: plot(SPtimeline, hardnessResidual = 0.5) ## Additional examples of plot dimensions and labelling ## Label the indices of the profiles in the list: plot(SPgroup, SortMethod = 'elev', xticklabels = "originalIndices") ## ... and with minimized axis limits and their station ID names: plot(SPgroup, SortMethod = 'elev', xticklabels = sapply(SPgroup, function(x) x$station_id), yPadding = 0, xPadding = 0, xaxs = 'i', yaxs = 'i') ## sorted by depth, and without box: plot(SPgroup, SortMethod = 'hs', TopDown = TRUE, box = FALSE) ## Apply a date offset to investigate which layers formed around that day of interest: pwl_exists <- sapply(SPgroup, function(sp) {length(findPWL(sp, pwl_date = "2019-01-21", pwl_gtype = c("SH", "DH"), date_range_earlier = as.difftime(2, unit = "days"))) > 0}) k <- order(pwl_exists, decreasing = TRUE) plot(SPgroup, SortMethod = 'presorted', k = k, xticklabels = "originalIndices", offset = as.Date("2019-01-21"), xlab = "<-- Jan 21 PWL exists | does not exist -->") abline(v = max(which(pwl_exists[k]))+0.5, lty = "dashed") ## Emphasize specific layers ## (i) all labeled layers of interest: SPgroup <- snowprofileSet(lapply(SPgroup, labelPWL)) # label layers with default settings plot(SPgroup, SortMethod = "hs", emphasizeLayers = TRUE, colAlpha = 0.3) ## (ii) specific individual layers: plot(SPgroup, SortMethod = "hs", emphasizeLayers = list(pwl_gtype = c("SH", "DH"), pwl_date = "2019-01-21"), colAlpha = 0.3, colEmphasis = "black")
## Standard profile timeline (e.g. https://niviz.org) plot(SPtimeline) ## Group of profiles with same timestamp plot(SPgroup, SortMethod = 'unsorted') # sorted in same order as list plot(SPgroup, SortMethod = 'hs') # sorted by snow height plot(SPgroup, SortMethod = 'elev') # sorted by elevation ## Colour layers by other properties plot(SPtimeline, ColParam = 'density') ## Align layers by depth instead of height plot(SPtimeline, TopDown = TRUE) ## Timelines with specific date ranges plot(SPtimeline, DateEnd = '2017-12-17') plot(SPtimeline, DateStart = '2017-12-15', DateEnd = '2017-12-17') ## Show hardness profile, too: plot(SPtimeline, hardnessResidual = 0.5) ## Additional examples of plot dimensions and labelling ## Label the indices of the profiles in the list: plot(SPgroup, SortMethod = 'elev', xticklabels = "originalIndices") ## ... and with minimized axis limits and their station ID names: plot(SPgroup, SortMethod = 'elev', xticklabels = sapply(SPgroup, function(x) x$station_id), yPadding = 0, xPadding = 0, xaxs = 'i', yaxs = 'i') ## sorted by depth, and without box: plot(SPgroup, SortMethod = 'hs', TopDown = TRUE, box = FALSE) ## Apply a date offset to investigate which layers formed around that day of interest: pwl_exists <- sapply(SPgroup, function(sp) {length(findPWL(sp, pwl_date = "2019-01-21", pwl_gtype = c("SH", "DH"), date_range_earlier = as.difftime(2, unit = "days"))) > 0}) k <- order(pwl_exists, decreasing = TRUE) plot(SPgroup, SortMethod = 'presorted', k = k, xticklabels = "originalIndices", offset = as.Date("2019-01-21"), xlab = "<-- Jan 21 PWL exists | does not exist -->") abline(v = max(which(pwl_exists[k]))+0.5, lty = "dashed") ## Emphasize specific layers ## (i) all labeled layers of interest: SPgroup <- snowprofileSet(lapply(SPgroup, labelPWL)) # label layers with default settings plot(SPgroup, SortMethod = "hs", emphasizeLayers = TRUE, colAlpha = 0.3) ## (ii) specific individual layers: plot(SPgroup, SortMethod = "hs", emphasizeLayers = list(pwl_gtype = c("SH", "DH"), pwl_date = "2019-01-21"), colAlpha = 0.3, colEmphasis = "black")
Print snowprofile object
## S3 method for class 'snowprofile' print(x, pretty = TRUE, nLayers = NA, ...)
## S3 method for class 'snowprofile' print(x, pretty = TRUE, nLayers = NA, ...)
x |
snowprofile object |
pretty |
pretty print the object (data.frame-like instead of list-like) |
nLayers |
only print the first few layers (cf., head) |
... |
passed to print.default |
object gets printed to console
## pretty print SPpairs$A_manual ## or alternatively: print(SPpairs$A_manual) ## reduce number of layers printed: print(SPpairs$A_manual, nLayers = 6) ## print profile non-pretty (i.e., like the data is stored): print(SPpairs$A_manual, pretty = FALSE)
## pretty print SPpairs$A_manual ## or alternatively: print(SPpairs$A_manual) ## reduce number of layers printed: print(SPpairs$A_manual, nLayers = 6) ## print profile non-pretty (i.e., like the data is stored): print(SPpairs$A_manual, pretty = FALSE)
Convert snowprofile object into data.frame with a row for each layer and additional columns with metadata
## S3 method for class 'snowprofile' rbind(..., deparse.level = 1)
## S3 method for class 'snowprofile' rbind(..., deparse.level = 1)
... |
Object of class snowprofile |
deparse.level |
Argument for generic rbind method |
Metadata columns are calculated with summary.snowprofile
data.frame
shorton
summary.snowprofile, rbind.snowprofileSet
Profile <- SPgroup[[1]] ProfileTable <- rbind(Profile) head(ProfileTable)
Profile <- SPgroup[[1]] ProfileTable <- rbind(Profile) head(ProfileTable)
A wrapper to apply rbind.snowprofile to each profile in a snowprofileSet then concatenate
## S3 method for class 'snowprofileSet' rbind(..., deparse.level = 1)
## S3 method for class 'snowprofileSet' rbind(..., deparse.level = 1)
... |
Object of class snowprofileSet |
deparse.level |
Argument for generic rbind method |
Returns a large data.frame with a row for each layer and additional columns with metadata (calculated with summary.snowprofile)
data.frame
shorton
summary.snowprofile, rbind.snowprofile
## Create rbind table ProfileTable <- rbind(SPgroup) head(ProfileTable) ## Filter by layer properties SHlayers <- subset(ProfileTable, gtype == 'SH') summary(SHlayers) plot(elev ~ gsize, SHlayers)
## Create rbind table ProfileTable <- rbind(SPgroup) head(ProfileTable) ## Filter by layer properties SHlayers <- subset(ProfileTable, gtype == 'SH') summary(SHlayers) plot(elev ~ gsize, SHlayers)
Read contents of a SMET file https://models.slf.ch/docserver/meteoio/SMET_specifications.pdf
readSmet(Filename)
readSmet(Filename)
Filename |
Path to a smet file |
List containing metadata and data
shorton
writeSmet, snowprofileSno, snowprofilePrf, snowprofilePro
## Path to example smet Filename <- system.file('extdata', 'example.smet', package = 'sarp.snowprofile') Wx = readSmet(Filename) str(Wx)
## Path to example smet Filename <- system.file('extdata', 'example.smet', package = 'sarp.snowprofile') Wx = readSmet(Filename) str(Wx)
Reformat a malformatted snowprofile object. A malformatted object may use field names that deviate from our
suggested field names (e.g., grain_type
instead of gtype
), or it may use data types that are different than
what we suggest to use (e.g., ddate
as type Date
instead of POSIXct
). Basically, if your snowprofile object
fails the test of validate_snowprofile due to the above reason this function should fix it.
reformat_snowprofile(profile, currentFields = NULL, targetFields = NULL)
reformat_snowprofile(profile, currentFields = NULL, targetFields = NULL)
profile |
snowprofile object |
currentFields |
array of character strings specifying the current field names that you want to change |
targetFields |
array of same size than |
## check the malformatted profile: this_throws_error <- TRUE if (!this_throws_error) { validate_snowprofile(SPmalformatted[[1]]) } ## i.e., we see that elev and ddate are of wrong data type, ## and a warning that grain_type is an unknown layer property. ## reformat field types, but not the field name: betterProfile <- reformat_snowprofile(SPmalformatted[[1]]) ## i.e., no error is raised anymore, but only the grain_type warning ## so let's reformat also the field names: optimalProfile <- reformat_snowprofile(SPmalformatted[[1]], "grain_type", "gtype") ## reformat a list of profiles with the same configuration: SPmalformatted_reformatted <- lapply(SPmalformatted, reformat_snowprofile, currentFields = "grain_type", targetFields = "gtype") ## the malformatted profile set finally is correctly formatted: lapply(SPmalformatted_reformatted, validate_snowprofile)
## check the malformatted profile: this_throws_error <- TRUE if (!this_throws_error) { validate_snowprofile(SPmalformatted[[1]]) } ## i.e., we see that elev and ddate are of wrong data type, ## and a warning that grain_type is an unknown layer property. ## reformat field types, but not the field name: betterProfile <- reformat_snowprofile(SPmalformatted[[1]]) ## i.e., no error is raised anymore, but only the grain_type warning ## so let's reformat also the field names: optimalProfile <- reformat_snowprofile(SPmalformatted[[1]], "grain_type", "gtype") ## reformat a list of profiles with the same configuration: SPmalformatted_reformatted <- lapply(SPmalformatted, reformat_snowprofile, currentFields = "grain_type", targetFields = "gtype") ## the malformatted profile set finally is correctly formatted: lapply(SPmalformatted_reformatted, validate_snowprofile)
Before reading entire SNOWPACK output it can be helpful to scan the profile timestamps first
scanProfileDates(Filename, tz = "UTC")
scanProfileDates(Filename, tz = "UTC")
Filename |
filename |
tz |
time zone (default = 'UTC') |
vector of as.POSIXct timestamps
shorton
snowprofilePrf, snowprofilePro
## Path to example prf file Filename <- system.file('extdata', 'example.prf', package = 'sarp.snowprofile') ## Scan dates in file Dates <- scanProfileDates(Filename) print(Dates)
## Path to example prf file Filename <- system.file('extdata', 'example.prf', package = 'sarp.snowprofile') ## Scan dates in file Dates <- scanProfileDates(Filename) print(Dates)
fast uncorrected sample standard deviation https://en.wikipedia.org/wiki/Standard_deviation#Rapid_calculation_methods
sd_sample_uncorrected(x, xbar = mean(x), na.rm = FALSE)
sd_sample_uncorrected(x, xbar = mean(x), na.rm = FALSE)
x |
a numeric vector |
xbar |
arithmetic mean of x |
na.rm |
remove any NAs before computation of standard deviation? |
uncorrected sample standard deviation (i.e., a numeric scalar)
fherla
Currently, you can choose between 'iacs', 'iacs2', 'sarp', or 'sarp-reduced'.
setColoursGrainType(ScaleName)
setColoursGrainType(ScaleName)
ScaleName |
Name of graintype colour scale
|
data.frame containing the new colour values stored in grainDict
Horton, S., Nowak, S., and Haegeli, P.: Enhancing the operational value of snowpack models with visualization design principles, Nat. Hazards Earth Syst. Sci., 20, 1557–1572, doi:10.5194/nhess-20-1557-2020, 2020.
grainDict, getColoursGrainType
## Current/default grain type colours grainDict plot(SPpairs$A_manual, main = 'Snow profile with default colours') ## Change to IACS colours grainDict <- setColoursGrainType('IACS') grainDict plot(SPpairs$A_manual, main = 'Snow profile with IACS colours') ## Change to IACS colours with adjusted MFcr (darkred) grainDict <- setColoursGrainType('IACS2') grainDict plot(SPpairs$A_manual, main = 'Snow profile with IACS colours and adjusted darkred MFcr') ## Change to SARP colours grainDict <- setColoursGrainType('SARP') grainDict plot(SPpairs$A_manual, main = 'Snow profile with SARP colours') ## Change to reduced SARP colours grainDict <- setColoursGrainType('SARP-reduced') grainDict plot(SPpairs$A_manual, main = 'Snow profile with a reduced set of SARP colours')
## Current/default grain type colours grainDict plot(SPpairs$A_manual, main = 'Snow profile with default colours') ## Change to IACS colours grainDict <- setColoursGrainType('IACS') grainDict plot(SPpairs$A_manual, main = 'Snow profile with IACS colours') ## Change to IACS colours with adjusted MFcr (darkred) grainDict <- setColoursGrainType('IACS2') grainDict plot(SPpairs$A_manual, main = 'Snow profile with IACS colours and adjusted darkred MFcr') ## Change to SARP colours grainDict <- setColoursGrainType('SARP') grainDict plot(SPpairs$A_manual, main = 'Snow profile with SARP colours') ## Change to reduced SARP colours grainDict <- setColoursGrainType('SARP-reduced') grainDict plot(SPpairs$A_manual, main = 'Snow profile with a reduced set of SARP colours')
The IACS records grain types in major and minor classes, e.g. precipitation particles PP can be subclassified into stellar dendrites PPsd. Some of these subclasses are not supported in this R package and so this function simplifies the unsupported gran type subclasses into their supported main classes. If a given grain type cannot be simplified, a NA value is returned for it.
simplifyGtypes(gtypes, supported_gtypes = grainDict$gtype)
simplifyGtypes(gtypes, supported_gtypes = grainDict$gtype)
gtypes |
an array of character grain types following IACS standards |
supported_gtypes |
an array of supported grain types that will determine the simplification |
the modified input array
fherla
## create an array of gtypes gtypes <- c('FCxr', 'RGxf', 'PPsd', 'PP', 'IFrc', "KKfx") ## sinplify gtypes to supported_gtypes: simplifyGtypes(gtypes)
## create an array of gtypes gtypes <- c('FCxr', 'RGxf', 'PPsd', 'PP', 'IFrc', "KKfx") ## sinplify gtypes to supported_gtypes: simplifyGtypes(gtypes)
Conveniently create a snowprofile object. Calls low-level constructor (only available internally: new_snowprofile), asserts correctness through a snowprofile validator function (validate_snowprofile) and yields meaningful error messages. Use low-level constructor if you generate many (!) profiles.
snowprofile( station = as.character(NA), station_id = as.character(NA), datetime = as.POSIXct(NA), latlon = as.double(c(NA, NA)), elev = as.double(NA), angle = as.double(NA), aspect = as.double(NA), hs = as.double(NA), maxObservedDepth = as.double(NA), type = "manual", band = as.character(NA), zone = as.character(NA), comment = as.character(NA), hn24 = as.double(NA), hn72 = as.double(NA), ski_pen = as.double(NA), layers = snowprofileLayers(dropNAs = FALSE, validate = FALSE), tests = snowprofileTests(dropNAs = FALSE), instabilitySigns = snowprofileInstabilitySigns(dropNAs = FALSE), validate = TRUE, dropNAs = TRUE )
snowprofile( station = as.character(NA), station_id = as.character(NA), datetime = as.POSIXct(NA), latlon = as.double(c(NA, NA)), elev = as.double(NA), angle = as.double(NA), aspect = as.double(NA), hs = as.double(NA), maxObservedDepth = as.double(NA), type = "manual", band = as.character(NA), zone = as.character(NA), comment = as.character(NA), hn24 = as.double(NA), hn72 = as.double(NA), ski_pen = as.double(NA), layers = snowprofileLayers(dropNAs = FALSE, validate = FALSE), tests = snowprofileTests(dropNAs = FALSE), instabilitySigns = snowprofileInstabilitySigns(dropNAs = FALSE), validate = TRUE, dropNAs = TRUE )
station |
character string |
station_id |
character string |
datetime |
date and time as class POSIXct in most meaningful timezone (timezone can be converted very easily:
e.g. |
latlon |
2-element vector latitude (first), longitude (second) |
elev |
profile elevation (m) |
angle |
slope angle (degree) |
aspect |
slope aspect (degree) |
hs |
total snow height (cm); if not provided, the field will be derived from the profile layers. |
maxObservedDepth |
equivalent to |
type |
character string, must be either 'manual', 'modeled', 'vstation', 'aggregate', or 'whiteboard' |
band |
character string describing elevation band as ALP, TL, BTL (alpine, treeline, below treeline) |
zone |
character string describing the zone or region of the profile location (e.g., BURNABY_MTN) |
comment |
character string with any text comments |
hn24 |
height of new snow within 24 h |
hn72 |
height of new snow within 72 h |
ski_pen |
skier penetration depth (m) |
layers |
snowprofileLayers object |
tests |
snowprofileTests object |
instabilitySigns |
snowprofileInstabilitySigns object |
validate |
Validate the object with validate_snowprofile? |
dropNAs |
Do you want to drop non-mandatory |
snowprofile object
shorton, fherla
summary.snowprofile, plot.snowprofile, snowprofileLayers, snowprofileTests, snowprofileInstabilitySigns, SPpairs
## Empty snowprofile: snowprofile() ## Test profile: testProfile <- snowprofile(station = 'SARPstation', station_id = 'SARP007', datetime = as.POSIXct('2019/04/01 10:00:00', tz = 'PDT'), latlon = c(49.277223, -122.915084), aspect = 180, layers = snowprofileLayers(height = c(10, 25, 50), hardness = c(3, 2, 1), gtype = c('FC', NA, 'PP'))) summary(testProfile) plot(testProfile)
## Empty snowprofile: snowprofile() ## Test profile: testProfile <- snowprofile(station = 'SARPstation', station_id = 'SARP007', datetime = as.POSIXct('2019/04/01 10:00:00', tz = 'PDT'), latlon = c(49.277223, -122.915084), aspect = 180, layers = snowprofileLayers(height = c(10, 25, 50), hardness = c(3, 2, 1), gtype = c('FC', NA, 'PP'))) summary(testProfile) plot(testProfile)
Note, that this function only provides a starting point for loading caaml files into R. Currently, caaml files exported from niviz.org, or snowpilot.org should be compatible with this routine. However, this routine only extracts some metadata and some of the most important layer characteristics. While a temperature profile (that is independent from the layers) is extracted, no other variables that can be written into a caaml file are currently being read (such as stability test results, etc).
snowprofileCaaml( caamlFile, sourceType = NA, readStabilityTests = TRUE, validate = TRUE )
snowprofileCaaml( caamlFile, sourceType = NA, readStabilityTests = TRUE, validate = TRUE )
caamlFile |
'path/to/file.caaml' |
sourceType |
choose 'manual', 'modeled', 'vstation', 'aggregate' or 'whiteboard'; while this routine has some functionality built in to detect sourceTypes under certain circumstances, it needs to be provided in most cases. |
readStabilityTests |
boolean (this is still beta version and can throw errors sometimes) |
validate |
Should the resulting snowprofile object be validated by validate_snowprofile? |
There is still a bug related to non-numeric aspects (e.g., E instead of 90).
The snowprofileCsv function provides a lot more flexibility to read in data, if you can choose the format of your underlying data. Don't hesitate to reach out though if your caaml files throw errors and you need help! If you extend this routine, please also reach out and let us know, so we can update this package with your code extensions.
snowprofile object
fherla
## load example caaml file that ships with package: caamlFile <- system.file('extdata', 'example.caaml', package = 'sarp.snowprofile') ## read caaml file: profile <- snowprofileCaaml(caamlFile, sourceType = 'vstation') ## other file with slighlty different xml namespace, structure, etc (including stability test): caamlFile2 <- system.file('extdata', 'example2.caaml', package = 'sarp.snowprofile') profile2 <- snowprofileCaaml(caamlFile2, sourceType = 'manual')
## load example caaml file that ships with package: caamlFile <- system.file('extdata', 'example.caaml', package = 'sarp.snowprofile') ## read caaml file: profile <- snowprofileCaaml(caamlFile, sourceType = 'vstation') ## other file with slighlty different xml namespace, structure, etc (including stability test): caamlFile2 <- system.file('extdata', 'example2.caaml', package = 'sarp.snowprofile') profile2 <- snowprofileCaaml(caamlFile2, sourceType = 'manual')
Read csv file into a snowprofile object
snowprofileCsv( path, header = TRUE, sep = ",", use.swisscode = FALSE, height = "height", gtype = "gtype", hardness = "hardness", ..., crust.val = 2, tz = "UTC" )
snowprofileCsv( path, header = TRUE, sep = ",", use.swisscode = FALSE, height = "height", gtype = "gtype", hardness = "hardness", ..., crust.val = 2, tz = "UTC" )
path |
'path/to/file.csv' |
header |
is there a header line in the csv file to explain the column names? If not, specify a character vector of column names in the correct order. |
sep |
csv column separator as string |
use.swisscode |
boolean; are grain types given as (numeric) |
height |
character string referring to the csv column of the top layer interfaces |
gtype |
character string referring to the csv column of the grain types |
hardness |
character string referring to the csv column of the layer hardnesses |
... |
provide name-value pairs of additional csv columns (in the form
|
crust.val |
If a column 'crust' is provided, what value of 'crust' defines MFcr? Mostly, either 2 (default) or 1. See Details. |
tz |
time zone (default = 'UTC') |
The minimum information required to construct a valid snowprofile object is height
, gtype
and hardness
. Currently, substituting height
with
a depth vector is not supported.
If profile specific information is provided in the csv table, it can only be included into the snowprofile object through the exact field names (see above). However, layer specific information can be named arbitrarily (except for the three required fields).
Regarding swisscode: The SNOWPACK documentation specifies that MFcr are encoded as (gt1|gt2|gt3) = (7|x|2), i.e. gt1 == 7 and gt3 == 2. This is
also how this routine handles the grain type encoding per default. However, some csv tables might be provided using swisscode encoding and
providing gt1, gt2, and gt3 as individual one-digit columns. In those cases, gt3 could be defined as a boolean (0 or 1), where gt1 == 7 and gt3 == 1
represent crusts, instead of the aforementioned standard definition of gt1 == 7 and gt3 == 2. To handle these cases, crust.val
can be set to 1, instead
of its default crust.val = 2
.
snowprofile object
fherla
## imagine a csv table with a very straightforward format, ## similar to the following data.frame: (DF <- data.frame(height = c(50, 80, 100), gtype = c('FC', 'RG', 'PP'), hardness = c(1, 3, 2))) ## write DF to a temporary file: write.csv(DF, file = file.path(tempdir(), 'file.csv')) ## read this file very easily by profile <- snowprofileCsv(file.path(tempdir(), 'file.csv')) profile ## imagine a csv table that requires a bit more customization, ## similar to the following data.frame: (DF <- data.frame(ID = rep(1234, times = 3), layer_top = c(10.5, 15, 55.0), gt1 = c(5, 7, 2), gs = c(5.0, 1.5, 1.0), crust = c(0, 1, 0), hardness = c('F', 'P', '4F+'))) write.csv(DF, file = file.path(tempdir(), 'file.csv')) profile <- snowprofileCsv(file.path(tempdir(), 'file.csv'), height = 'layer_top', gtype = 'gt1', use.swisscode = TRUE, gsize = 'gs', crust.val = 1) profile ## Note that the csv column 'crust', which specifies whether a MF layer is actually # a MFcr layer, is already named correctly (i.e., 'crust'). If it were named 'freeze-crust', # we would need to add to the function call: `crust = 'freeze-crust'`. # Also note, that we need to provide `crust.val = 1`, since we're not using the standard definition # of swisscode MFcr encoding (see Details). ## let's assume you want to read the csv file an customize some names, e.g. GrainSIZE: profile <- snowprofileCsv(file.path(tempdir(), 'file.csv'), height = 'layer_top', gtype = 'gt1', use.swisscode = TRUE, GrainSIZE = 'gs') profile ## Note that generally in a snowprofile object layer properties can be custom named, # meta information, e.g. station_id, can not! I.e. you need to use the prescribed names.
## imagine a csv table with a very straightforward format, ## similar to the following data.frame: (DF <- data.frame(height = c(50, 80, 100), gtype = c('FC', 'RG', 'PP'), hardness = c(1, 3, 2))) ## write DF to a temporary file: write.csv(DF, file = file.path(tempdir(), 'file.csv')) ## read this file very easily by profile <- snowprofileCsv(file.path(tempdir(), 'file.csv')) profile ## imagine a csv table that requires a bit more customization, ## similar to the following data.frame: (DF <- data.frame(ID = rep(1234, times = 3), layer_top = c(10.5, 15, 55.0), gt1 = c(5, 7, 2), gs = c(5.0, 1.5, 1.0), crust = c(0, 1, 0), hardness = c('F', 'P', '4F+'))) write.csv(DF, file = file.path(tempdir(), 'file.csv')) profile <- snowprofileCsv(file.path(tempdir(), 'file.csv'), height = 'layer_top', gtype = 'gt1', use.swisscode = TRUE, gsize = 'gs', crust.val = 1) profile ## Note that the csv column 'crust', which specifies whether a MF layer is actually # a MFcr layer, is already named correctly (i.e., 'crust'). If it were named 'freeze-crust', # we would need to add to the function call: `crust = 'freeze-crust'`. # Also note, that we need to provide `crust.val = 1`, since we're not using the standard definition # of swisscode MFcr encoding (see Details). ## let's assume you want to read the csv file an customize some names, e.g. GrainSIZE: profile <- snowprofileCsv(file.path(tempdir(), 'file.csv'), height = 'layer_top', gtype = 'gt1', use.swisscode = TRUE, GrainSIZE = 'gs') profile ## Note that generally in a snowprofile object layer properties can be custom named, # meta information, e.g. station_id, can not! I.e. you need to use the prescribed names.
This routine reads blocks of snowprofile metadata, layers, tests, and stability signs. Columns contain different variables,
rows different observations. While metadata only contains one row, layers, tests, and signs consist of potentially multiple
rows. Within each block of information, mind the correct alignment of rows. Missing values (i.e., NA) need to be left blank
or called NA
. See the examples below including the example file shipped with the package.
snowprofileCsv_advanced( csvFile, meta = c("uid", "hs", "maxObservedDepth", "comment"), layers = c("depth", "height", "gtype", "hardness", "datetag", "gsize", "gtype_sec", "layer_comment"), tests = c("test", "result", "fract_char", "score", "test_depth", "test_comment"), instabilitySigns = c("instabilitySign_type", "instabilitySign_present", "instabilitySign_comment"), sep = ",", elev.units = "ft", tz = "UTC" )
snowprofileCsv_advanced( csvFile, meta = c("uid", "hs", "maxObservedDepth", "comment"), layers = c("depth", "height", "gtype", "hardness", "datetag", "gsize", "gtype_sec", "layer_comment"), tests = c("test", "result", "fract_char", "score", "test_depth", "test_comment"), instabilitySigns = c("instabilitySign_type", "instabilitySign_present", "instabilitySign_comment"), sep = ",", elev.units = "ft", tz = "UTC" )
csvFile |
'path/to/file.csv' |
meta |
column names of block metadata |
layers |
column names of block snowprofileLayers |
tests |
column names of block snowprofileTests |
instabilitySigns |
column names of block snowprofileInstabilitySigns |
sep |
csv column separator |
elev.units |
if set to "ft", the routine will convert to "m". Set to "m" (or anything else) if it should be unchanged |
tz |
time zone (default = 'UTC') |
fherla
## load example csv file that ships with package: csvFile <- system.file('extdata', 'example_adv.csv', package = 'sarp.snowprofile') profile <- snowprofileCsv_advanced(csvFile, meta = c("uid", "hs", "maxObservedDepth", "comment", "datetime", "zone", "station", "station_id", "aspect", "elev", "angle")) plot(profile)
## load example csv file that ships with package: csvFile <- system.file('extdata', 'example_adv.csv', package = 'sarp.snowprofile') profile <- snowprofileCsv_advanced(csvFile, meta = c("uid", "hs", "maxObservedDepth", "comment", "datetime", "zone", "station", "station_id", "aspect", "elev", "angle")) plot(profile)
Create a snowprofileInstabilitySigns object. Instability signs can for example be whumpfs, cracking, natural avalanches, skier accidental release, ski cutting, etc. For more information, see Canadian Avalanche Association. (2016). Observation Guidelines and Recording Standards for Weather, Snowpack, and Avalanches. Revelstoke, BC, Canada.
snowprofileInstabilitySigns( signsFrame = data.frame(type = as.character(NA), present = as.character(NA), comment = as.character(NA)), dropNAs = TRUE )
snowprofileInstabilitySigns( signsFrame = data.frame(type = as.character(NA), present = as.character(NA), comment = as.character(NA)), dropNAs = TRUE )
signsFrame |
a data.frame listing snowpack stability signs. Rows correspond to individual observations of instability signs
and columns describe at least the fields
|
dropNAs |
Should empty, non-mandatory columns be dropped from the final snowprofileInstabilitySigns object? |
Note: This class might be a temporary solution to digitize instability signs observed in proximity to snowprofiles. The information contained here, might be ported to a more general field observations class that is both independent from snowprofile objects and that is more in line with existing field observation standards.
snowprofileInstabilitySigns object
fherla
snowprofile, snowprofileLayers, snowprofileTests
## create a data.frame with instability sign observations (signsFrame <- data.frame(type = c("Na", "whumpf", "cracking", "Sa"), present = c(FALSE, TRUE, FALSE, FALSE))) ## create snowprofileInstabilitySigns object instabilitySigns <- snowprofileInstabilitySigns(signsFrame) ## create snowprofile object containing instability signs and check resulting object: snowprofile(instabilitySigns = instabilitySigns)
## create a data.frame with instability sign observations (signsFrame <- data.frame(type = c("Na", "whumpf", "cracking", "Sa"), present = c(FALSE, TRUE, FALSE, FALSE))) ## create snowprofileInstabilitySigns object instabilitySigns <- snowprofileInstabilitySigns(signsFrame) ## create snowprofile object containing instability signs and check resulting object: snowprofile(instabilitySigns = instabilitySigns)
Helper function to conveniently create a snowprofileLayers object, i.e. data.frame with mandatory column fields height (or depth) that provides vertical position of layers.
Layers need to be ordered in a sequential manner, and the routine will rearrange the layers so that the last row of the resulting dataframe corresponds to the snow surface.
If the vertical location of the layers is given by depth, make sure to provide hs
if it's known. Otherwise, provide the field maxObservedDepth
or layer thicknesses.
Providing only depth will issue a warning and set the corresponding lowest layer thickness to NA.
The resulting dataframe will contain all three fields height
, depth
, and thickness
, which will be auto-filled if not provided (see format_snowprofileLayers).
If the columns that describe layer properties are not of equal
lengths, their values will be recycled (default data.frame mechanism). Instead of individual layer characteristics, a data.frame can be provided, which will be converted into a snowprofileLayers class.
The constructor asserts correctness of the layers object by a call to validate_snowprofileLayers.
snowprofileLayers( height = as.double(NA), temperature = as.double(NA), density = as.double(NA), lwc = as.double(NA), gsize = as.double(NA), gsize_max = as.double(NA), gsize_avg = as.double(NA), gtype = as.factor(NA), gtype_sec = as.factor(NA), hardness = as.double(NA), ddate = as.POSIXct(NA), bdate = as.POSIXct(NA), datetag = as.Date(NA), ssi = as.double(NA), sphericity = as.double(NA), v_strain_rate = as.double(NA), crit_cut_length = as.double(NA), tsa = as.double(NA), tsa_interface = as.double(NA), rta = as.double(NA), rta_interface = as.double(NA), layerOfInterest = as.logical(NA), comment = as.character(NA), ..., hs = as.double(NA), maxObservedDepth = as.double(NA), layerFrame = NA, validate = TRUE, dropNAs = TRUE )
snowprofileLayers( height = as.double(NA), temperature = as.double(NA), density = as.double(NA), lwc = as.double(NA), gsize = as.double(NA), gsize_max = as.double(NA), gsize_avg = as.double(NA), gtype = as.factor(NA), gtype_sec = as.factor(NA), hardness = as.double(NA), ddate = as.POSIXct(NA), bdate = as.POSIXct(NA), datetag = as.Date(NA), ssi = as.double(NA), sphericity = as.double(NA), v_strain_rate = as.double(NA), crit_cut_length = as.double(NA), tsa = as.double(NA), tsa_interface = as.double(NA), rta = as.double(NA), rta_interface = as.double(NA), layerOfInterest = as.logical(NA), comment = as.character(NA), ..., hs = as.double(NA), maxObservedDepth = as.double(NA), layerFrame = NA, validate = TRUE, dropNAs = TRUE )
height |
height vector (cm) referring to the top layer interface. Instead of |
temperature |
snow temperature (deg C) |
density |
layer density (kg/m3) |
lwc |
liquid water content (%) |
gsize |
grain size (mm) |
gsize_max |
maximum grain size (mm) |
gsize_avg |
average grain size (mm) |
gtype |
grain type (character or factor) |
gtype_sec |
secondary grain type (character or factor) |
hardness |
numeric hand hardness (use char2numHHI to convert from character hardness) |
ddate |
deposition date of layer (POSIXct format). WARNING: if you provide character format, the time zone of your computer system will be assumed. |
bdate |
burial date of layer (POSIXct format). WARNING: if you provide character format, the time zone of your computer system will be assumed. |
datetag |
of layer (i.e., usually corresponds to |
ssi |
snow stability index (numeric) |
sphericity |
between 0 and 1 |
v_strain_rate |
viscous deformation rate (s^-1) |
crit_cut_length |
critical crack length (m) |
tsa |
threshold sum approach for structural instability (also called lemons); valid for the layer, i.e., the weakest interface adjacent to the layer. see computeTSA. |
tsa_interface |
same as tsa, but valid for top interface of corresponding layer |
rta |
relative threshold sum approach (following Monti et al 2013, ISSW paper); valid for the layer, i.e., the weakest interface adjacent to the layer. see computeRTA. |
rta_interface |
same as rta, but valid for top interface of corresponding layer |
layerOfInterest |
a boolean column to label specific layers of interest, e.g. weak layers. see labelPWL. |
comment |
character string |
... |
columns to include in the layers object. Note, that they need to correspond to the according height/depth array. e.g. hardness (can use character hardness or numeric hardness via char2numHHI), ddate (class POSIX), bdate (class Date) gtype (character or factor), density, temperature, gsize, lwc, gsize_max, gtype_sec, ssi, depth, thickness |
hs |
total snow height (cm), if not deductible from |
maxObservedDepth |
the observed depth of the profile from the snow surface downwards. Will only be used, if
no |
layerFrame |
a data.frame that's converted to a snowprofileLayers class if no other layer characteristics are provided |
validate |
Validate |
dropNAs |
Do you want to drop all columns consisting of NAs only? |
snowprofileLayers object as data.frame with strings as factors
shorton, fherla
## Empty layers object: snowprofileLayers() ## simple layers example that recycles the hardness 1F+: with warning issued! ## Try what happens if you provide ddate as character array without a timezone. snowprofileLayers(height = c(10, 25, 50), hardness = char2numHHI('1F+'), gtype = c('FC', NA, 'PP'), ddate = as.POSIXct(c(NA, NA, "2020-02-15 10:45:00"), tz = "Etc/GMT+7")) ## create snowprofileLayers object from data.frame ## and feed it into a snowprofile object: df <- data.frame(height = c(10, 25, 50), hardness = c(2, 3, 1), gtype = c('FC', NA, 'PP'), stringsAsFactors = TRUE) spL <- snowprofileLayers(layerFrame = df) (sp <- snowprofile(layers = spL)) ##### Create top-down recorded snowprofileLayers #### ## check out how the fields 'hs' and 'maxObservedDepth' are auto-filled in the ## resulting snowprofile object! ## 1.) Specify depth and hs: ## In that case the routine will assume that the deepest layer extends down to the ground (sp1 <- snowprofile(layers = snowprofileLayers(depth = c(40, 25, 0), hardness = c(2, 3, 1), gtype = c('FC', NA, 'PP'), hs = 50))) ## note that sp and sp1 are the same profiles: all(sapply(names(sp$layers), function(cols) {sp$layers[cols] == sp1$layers[cols]}), na.rm = TRUE) ## 2.) Specify depth, hs and thickness or maxObservedDepth: ## This will include a basal layer of NAs to fill the unobserved space down to the ground. (sp2 <- snowprofile(layers = snowprofileLayers(depth = c(40, 25, 0), hardness = c(2, 3, 1), gtype = c('FC', NA, 'PP'), hs = 70, maxObservedDepth = 50))) ## 3.) Specify depth and maxObservedDepth: ## This will include a basal layer of NAs which is 1 cm thick to flag the unknown basal layers. (sp3 <- snowprofile(layers = snowprofileLayers(depth = c(40, 25, 0), hardness = c(2, 3, 1), gtype = c('FC', NA, 'PP'), gsize = c(2, NA, NA), maxObservedDepth = 50))) ## 4.) Specify depth and thickness: ## This is equivalent to the example spL3 above! ## This will include a basal layer of NAs which is 1 cm thick to flag the unknown basal layers. (sp4 <- snowprofile(layers = snowprofileLayers(depth = c(40, 25, 0), thickness = c(10, 15, 25), hardness = c(2, 3, 1), gtype = c('FC', NA, 'PP')))) ## 5.) Specify only depth: issues warning! (sp5 <- snowprofile(layers = snowprofileLayers(depth = c(40, 25, 0), hardness = c(2, 3, 1), gtype = c('FC', NA, 'PP')))) ## plot all 5 top.down-recorded profiles: set <- snowprofileSet(list(sp1, sp2, sp3, sp4, sp5)) plot(set, SortMethod = "unsorted", xticklabels = "originalIndices", hardnessResidual = 0.1, hardnessScale = 1.5, TopDown = TRUE, main = "TopDown Plot") plot(set, SortMethod = "unsorted", xticklabels = "originalIndices", hardnessResidual = 0.1, hardnessScale = 1.5, TopDown = FALSE, main = "BottomUp Plot")
## Empty layers object: snowprofileLayers() ## simple layers example that recycles the hardness 1F+: with warning issued! ## Try what happens if you provide ddate as character array without a timezone. snowprofileLayers(height = c(10, 25, 50), hardness = char2numHHI('1F+'), gtype = c('FC', NA, 'PP'), ddate = as.POSIXct(c(NA, NA, "2020-02-15 10:45:00"), tz = "Etc/GMT+7")) ## create snowprofileLayers object from data.frame ## and feed it into a snowprofile object: df <- data.frame(height = c(10, 25, 50), hardness = c(2, 3, 1), gtype = c('FC', NA, 'PP'), stringsAsFactors = TRUE) spL <- snowprofileLayers(layerFrame = df) (sp <- snowprofile(layers = spL)) ##### Create top-down recorded snowprofileLayers #### ## check out how the fields 'hs' and 'maxObservedDepth' are auto-filled in the ## resulting snowprofile object! ## 1.) Specify depth and hs: ## In that case the routine will assume that the deepest layer extends down to the ground (sp1 <- snowprofile(layers = snowprofileLayers(depth = c(40, 25, 0), hardness = c(2, 3, 1), gtype = c('FC', NA, 'PP'), hs = 50))) ## note that sp and sp1 are the same profiles: all(sapply(names(sp$layers), function(cols) {sp$layers[cols] == sp1$layers[cols]}), na.rm = TRUE) ## 2.) Specify depth, hs and thickness or maxObservedDepth: ## This will include a basal layer of NAs to fill the unobserved space down to the ground. (sp2 <- snowprofile(layers = snowprofileLayers(depth = c(40, 25, 0), hardness = c(2, 3, 1), gtype = c('FC', NA, 'PP'), hs = 70, maxObservedDepth = 50))) ## 3.) Specify depth and maxObservedDepth: ## This will include a basal layer of NAs which is 1 cm thick to flag the unknown basal layers. (sp3 <- snowprofile(layers = snowprofileLayers(depth = c(40, 25, 0), hardness = c(2, 3, 1), gtype = c('FC', NA, 'PP'), gsize = c(2, NA, NA), maxObservedDepth = 50))) ## 4.) Specify depth and thickness: ## This is equivalent to the example spL3 above! ## This will include a basal layer of NAs which is 1 cm thick to flag the unknown basal layers. (sp4 <- snowprofile(layers = snowprofileLayers(depth = c(40, 25, 0), thickness = c(10, 15, 25), hardness = c(2, 3, 1), gtype = c('FC', NA, 'PP')))) ## 5.) Specify only depth: issues warning! (sp5 <- snowprofile(layers = snowprofileLayers(depth = c(40, 25, 0), hardness = c(2, 3, 1), gtype = c('FC', NA, 'PP')))) ## plot all 5 top.down-recorded profiles: set <- snowprofileSet(list(sp1, sp2, sp3, sp4, sp5)) plot(set, SortMethod = "unsorted", xticklabels = "originalIndices", hardnessResidual = 0.1, hardnessScale = 1.5, TopDown = TRUE, main = "TopDown Plot") plot(set, SortMethod = "unsorted", xticklabels = "originalIndices", hardnessResidual = 0.1, hardnessScale = 1.5, TopDown = FALSE, main = "BottomUp Plot")
Read .prf files from SNOWPACK model output
snowprofilePrf(Filename, ProfileDate = NA, tz = "UTC")
snowprofilePrf(Filename, ProfileDate = NA, tz = "UTC")
Filename |
path to prf file |
ProfileDate |
read a single profile from file (default = NA will read all profiles) |
tz |
time zone (default = 'UTC') |
Several SNOWPACK model output formats exist see SNOWPACK documentation
Definitions of PRF files are provided at https://models.slf.ch/docserver/snowpack/html/prf_format.html
PRF files typically contain profiles from the same station at multiple time steps. If a specific ProfileDate
is provided a single snowprofile object is returned (search available dates with scanProfileDates
), otherwise all profiles are read and a list of snowprofile objects is returned.
a single snowprofile object of list of multiple snowprofile objects
shorton
snowprofilePro, scanProfileDates, snowprofileSno
## Path to example prf file Filename <- system.file('extdata', 'example.prf', package = 'sarp.snowprofile') ## Scan dates in file Dates <- scanProfileDates(Filename) print(Dates) ## Read a single profile by date and plot ProfileDate <- Dates[3] Profile <- snowprofilePrf(Filename, ProfileDate = ProfileDate) plot(Profile) ## Read entire time series and plot Profiles <- snowprofilePrf(Filename) plot(Profiles, main = 'Timeseries read from example.prf')
## Path to example prf file Filename <- system.file('extdata', 'example.prf', package = 'sarp.snowprofile') ## Scan dates in file Dates <- scanProfileDates(Filename) print(Dates) ## Read a single profile by date and plot ProfileDate <- Dates[3] Profile <- snowprofilePrf(Filename, ProfileDate = ProfileDate) plot(Profile) ## Read entire time series and plot Profiles <- snowprofilePrf(Filename) plot(Profiles, main = 'Timeseries read from example.prf')
Read .pro files from SNOWPACK model output
snowprofilePro( Filename, ProfileDate = NA, tz = "UTC", remove_soil = TRUE, suppressWarnings = FALSE )
snowprofilePro( Filename, ProfileDate = NA, tz = "UTC", remove_soil = TRUE, suppressWarnings = FALSE )
Filename |
path to pro file |
ProfileDate |
read a single profile from file (default = NA will read all profiles) |
tz |
time zone (default = 'UTC') |
remove_soil |
if soil layers are present in PRO file, remove them from snowprofile objects? |
suppressWarnings |
boolean switch |
Several SNOWPACK model output formats exist see SNOWPACK documentation
Definitions of PRO files are provided at https://models.slf.ch/docserver/snowpack/html/pro_format.html and an example file is available at niViz
PRO files typically contain profiles from the same station at multiple time steps. If a specific ProfileDate
is provided a single snowprofile object is returned (search available dates with scanProfileDates
), otherwise all profiles are read and a list of snowprofile objects is returned.
a single snowprofile object of list of multiple snowprofile objects
shorton
snowprofilePrf, scanProfileDates, snowprofileSno
## Path to example pro file Filename <- system.file('extdata', 'example.pro', package = 'sarp.snowprofile') ## Download example pro file from niViz #Filename <- tempfile(fileext = '.pro') #download.file('https://niviz.org/resources/example.pro', Filename) ## Scan dates in file Dates <- scanProfileDates(Filename) print(Dates) ## Read a single profile by date and plot ProfileDate <- Dates[3] Profile <- snowprofilePro(Filename, ProfileDate = ProfileDate) plot(Profile) ## Read entire time series and plot Profiles <- snowprofilePro(Filename) plot(Profiles, main = 'Timeseries read from example.pro')
## Path to example pro file Filename <- system.file('extdata', 'example.pro', package = 'sarp.snowprofile') ## Download example pro file from niViz #Filename <- tempfile(fileext = '.pro') #download.file('https://niviz.org/resources/example.pro', Filename) ## Scan dates in file Dates <- scanProfileDates(Filename) print(Dates) ## Read a single profile by date and plot ProfileDate <- Dates[3] Profile <- snowprofilePro(Filename, ProfileDate = ProfileDate) plot(Profile) ## Read entire time series and plot Profiles <- snowprofilePro(Filename) plot(Profiles, main = 'Timeseries read from example.pro')
Constructor for class snowprofileSet
snowprofileSet(x = list())
snowprofileSet(x = list())
x |
list of snowprofile objects |
a snowprofileSet
snowprofile, summary.snowprofileSet
Read .sno files from SNOWPACK model input/output
snowprofileSno(Filename)
snowprofileSno(Filename)
Filename |
path to sno file |
Several SNOWPACK model output formats exist see SNOWPACK documentation
Definitions of SNO files are provided at https://models.slf.ch/docserver/snowpack/html/smet.html
a snowprofile object
shorton
snowprofilePro, snowprofilePrf, snowprofileCsv
## Path to example prf file Filename <- system.file('extdata', 'example.sno', package = 'sarp.snowprofile') ## Read snowprofile object Profile <- snowprofileSno(Filename) ## Note: plot.snowprofile won't work because sno files don't have harndess ## Plot a temperautre profile plot(snowprofileSet(list(Profile)), ColParam = 'temp')
## Path to example prf file Filename <- system.file('extdata', 'example.sno', package = 'sarp.snowprofile') ## Read snowprofile object Profile <- snowprofileSno(Filename) ## Note: plot.snowprofile won't work because sno files don't have harndess ## Plot a temperautre profile plot(snowprofileSet(list(Profile)), ColParam = 'temp')
Create a snowprofileTests object.
snowprofileTests( testsFrame = data.frame(type = as.character(NA), result = as.character(NA), score = as.double(NA), fract_char = as.character(NA), depth = as.double(NA), comment = as.character(NA)), dropNAs = TRUE )
snowprofileTests( testsFrame = data.frame(type = as.character(NA), result = as.character(NA), score = as.double(NA), fract_char = as.character(NA), depth = as.double(NA), comment = as.character(NA)), dropNAs = TRUE )
testsFrame |
a data.frame listing snowpack stability tests. Rows correspond to individual tests and columns describe at least the
fields
|
dropNAs |
Should empty, non-mandatory columns be dropped from the final snowprofileTests object? |
For more information, see Canadian Avalanche Association. (2016). Observation Guidelines and Recording Standards for Weather, Snowpack, and Avalanches (OGRS). Revelstoke, BC, Canada.
snowprofileTests object
fherla
snowprofile, snowprofileLayers, snowprofileInstabilitySigns
## create a data.frame with test observations (testsFrame <- data.frame(type = c("CT", "ST", "ECT"), result = c("E-M", "M", "P"), score = c(10, NA, 12), fract_char = c("SP", NA, NA), depth = c(40, 40, 40), comment = c("some comment on first test", "", ""))) ## create snowprofileTests object tests <- snowprofileTests(testsFrame) ## create snowprofile object containing test results and check resulting object: snowprofile(tests = tests)
## create a data.frame with test observations (testsFrame <- data.frame(type = c("CT", "ST", "ECT"), result = c("E-M", "M", "P"), score = c(10, NA, 12), fract_char = c("SP", NA, NA), depth = c(40, 40, 40), comment = c("some comment on first test", "", ""))) ## create snowprofileTests object tests <- snowprofileTests(testsFrame) ## create snowprofile object containing test results and check resulting object: snowprofile(tests = tests)
A list of 12 snowprofile objects.
SPgroup
SPgroup
A list with 12 entries, that are of class snowprofile
SPpairs, SPtimeline, plot.snowprofileSet
plot(SPgroup, SortMethod = 'unsorted', xticklabels = "originalIndices") plot(SPgroup, SortMethod = 'hs', xticklabels = "originalIndices")
plot(SPgroup, SortMethod = 'unsorted', xticklabels = "originalIndices") plot(SPgroup, SortMethod = 'hs', xticklabels = "originalIndices")
A list with two entries, each containing a snowprofile object. Both are malformatted, check out the examples in validate_snowprofile and reformat_snowprofile to learn how to fix it.
SPmalformatted
SPmalformatted
A list with several entries, that are of class snowprofile
validate_snowprofile, reformat_snowprofile, SPpairs, SPgroup, SPtimeline
A list with several entries, each containing a snowprofile object. Pairs of similar profiles are grouped by their names.
SPpairs
SPpairs
A list with several entries, that are of class snowprofile
## Each name refers to one snowprofile: names(SPpairs) opar <- par(no.readonly = TRUE) par(mfrow = c(1, 2)) plot(SPpairs$A_manual, main = 'SPpairs$A_manual') plot(SPpairs$A_modeled, main = 'SPpairs$A_modeled') par(opar)
## Each name refers to one snowprofile: names(SPpairs) opar <- par(no.readonly = TRUE) par(mfrow = c(1, 2)) plot(SPpairs$A_manual, main = 'SPpairs$A_manual') plot(SPpairs$A_modeled, main = 'SPpairs$A_modeled') par(opar)
Timeseries of snowprofiles #'
SPtimeline
SPtimeline
A list with several entries, that are of class snowprofile
summary(SPtimeline) plot(SPtimeline)
summary(SPtimeline) plot(SPtimeline)
Summary of a single snowprofile
## S3 method for class 'snowprofile' summary(object, fast = FALSE, ...)
## S3 method for class 'snowprofile' summary(object, fast = FALSE, ...)
object |
snowprofile object |
fast |
boolean switch for twice as fast computation. downside: keep only length-1 meta data, i.e., discard latlon, or nlayers.. |
... |
additional arguments for generic method |
Creates a one row data.frame where each column contains metadata.
Metadata is determines as elements of the snowprofile object list that are length = 1. An exception is made for latlon where separate columns for lat and lon are produces.
A derived value nLayers
is derived by counting the number of rows in $layers.
data.frame
shorton
Profile <- SPgroup[[1]] names(Profile) summary(Profile) lapply(SPgroup, summary)
Profile <- SPgroup[[1]] names(Profile) summary(Profile) lapply(SPgroup, summary)
Wrapper for summary.snowprofile, which only returns metadata for a single snowprofile object. summary.snowprofileSet provides metadata for multiple snowprofiles, which is useful for subsetting.
## S3 method for class 'snowprofileSet' summary(object, fast = TRUE, ...)
## S3 method for class 'snowprofileSet' summary(object, fast = TRUE, ...)
object |
list of snowprofile objects |
fast |
boolean switch to speed up computations, see summary.snowprofile |
... |
additional arguments for generic method |
data.frame
shorton
summary.snowprofile, rbind.snowprofileSet
## Extract metadata for a group of profiles Metadata <- summary(SPgroup) head(Metadata) ## Subsetting profiles with Metadata Alpine <- SPgroup[Metadata$elev > 2000] summary(Alpine) Shallow <- SPgroup[Metadata$hs < 150] summary(Shallow) Week2 <- SPtimeline[summary(SPtimeline)$date > '2017-12-15'] ## time comparison of fast--slow implementation ## expect 20 sec runtime # rbenchmark::benchmark(fast = {Metadata <- summary(SPgroup, fast = TRUE)}, # slow = {Metadata <- summary(SPgroup, fast = FALSE)}, # replications = 10**3)
## Extract metadata for a group of profiles Metadata <- summary(SPgroup) head(Metadata) ## Subsetting profiles with Metadata Alpine <- SPgroup[Metadata$elev > 2000] summary(Alpine) Shallow <- SPgroup[Metadata$hs < 150] summary(Shallow) Week2 <- SPtimeline[summary(SPtimeline)$date > '2017-12-15'] ## time comparison of fast--slow implementation ## expect 20 sec runtime # rbenchmark::benchmark(fast = {Metadata <- summary(SPgroup, fast = TRUE)}, # slow = {Metadata <- summary(SPgroup, fast = FALSE)}, # replications = 10**3)
A character array of grain types that can be translated into a numerical code by their indices.
swisscode
swisscode
A character array
print(swisscode) ## see numerical code for each grain type: rbind(swisscode, seq(length(swisscode)))
print(swisscode) ## see numerical code for each grain type: rbind(swisscode, seq(length(swisscode)))
Validator function that checks if snowprofile standards are being met and raises an error if mandatory fields are missing or data types are incorrect. The function raises a warning when unknown field names are encountered.
validate_snowprofile(object, silent = FALSE)
validate_snowprofile(object, silent = FALSE)
object |
a snowprofile object to be validated |
silent |
remain silent upon error (i.e., don't raise error, but only print it) |
Per default an error is raised when discovered, if silent = TRUE
the error is only printed and the
error message returned (Note: a warning is never returned but only printed!).
If the function is applied to multiple objects, the function returns NULL
for each object if no error
is encountered (see examples below).
## Validate individual snowprofile and raise an error ## in case of a malformatted profile: ## (1) no error validate_snowprofile(SPgroup[[1]]) ## (2) malformatted profile --> error this_throws_error <- TRUE if (!this_throws_error) { validate_snowprofile(SPmalformatted[[1]]) } ## Validate a list of snowprofiles and raise an error ## when the first error is encountered: ## (i.e., stop subsequent execution) ## (1) no error lapply(SPgroup, validate_snowprofile) ## (2) malformatted profile --> error if (!this_throws_error) { lapply(SPmalformatted, validate_snowprofile) } ## Validate a list of snowprofiles and continue execution, ## so that you get a comprehensive list of errors of all profiles: if (!this_throws_error) { errorlist <- lapply(SPmalformatted, validate_snowprofile, silent = TRUE) errorlist[sapply(errorlist, function(item) !is.null(item))] # print profiles that caused errors }
## Validate individual snowprofile and raise an error ## in case of a malformatted profile: ## (1) no error validate_snowprofile(SPgroup[[1]]) ## (2) malformatted profile --> error this_throws_error <- TRUE if (!this_throws_error) { validate_snowprofile(SPmalformatted[[1]]) } ## Validate a list of snowprofiles and raise an error ## when the first error is encountered: ## (i.e., stop subsequent execution) ## (1) no error lapply(SPgroup, validate_snowprofile) ## (2) malformatted profile --> error if (!this_throws_error) { lapply(SPmalformatted, validate_snowprofile) } ## Validate a list of snowprofiles and continue execution, ## so that you get a comprehensive list of errors of all profiles: if (!this_throws_error) { errorlist <- lapply(SPmalformatted, validate_snowprofile, silent = TRUE) errorlist[sapply(errorlist, function(item) !is.null(item))] # print profiles that caused errors }
Validator function that checks if class standards are being met and raises an error if not.
validate_snowprofileLayers(object, silent = FALSE)
validate_snowprofileLayers(object, silent = FALSE)
object |
to be tested |
silent |
remain silent upon error (i.e., don't throw error, but only print it) |
Per default an error is raised when discovered, if silent = TRUE
the error is only printed and the
error message returned.
Write data into a SMET file https://models.slf.ch/docserver/meteoio/SMET_specifications.pdf
writeSmet(smet, filename)
writeSmet(smet, filename)
smet |
A data structure that resembles a smet file (i.e., list containing metadata and a data.frame, see example in readSmet) |
filename |
Filepath to be written |
Generates smet file
fherla, shorton
readSmet, snowprofileSno, snowprofilePrf, snowprofilePro
## First read example smet file provided in package (Wx = readSmet(system.file('extdata', 'example.smet', package = 'sarp.snowprofile'))) ## Then write Wx to a new temp file and show the file writeSmet(Wx, filename = file.path(tempdir(), 'file.smet')) file.show(file.path(tempdir(), 'file.smet')) ## Check whether it can be read back in (WxNew <- readSmet(file.path(tempdir(), 'file.smet')))
## First read example smet file provided in package (Wx = readSmet(system.file('extdata', 'example.smet', package = 'sarp.snowprofile'))) ## Then write Wx to a new temp file and show the file writeSmet(Wx, filename = file.path(tempdir(), 'file.smet')) file.show(file.path(tempdir(), 'file.smet')) ## Check whether it can be read back in (WxNew <- readSmet(file.path(tempdir(), 'file.smet')))