R/triangles.r

Defines functions sample_triangle_planar

Documented in sample_triangle_planar

#' @title Sample (with noise) from planar triangles
#'
#' @description This function generates uniform and stratified samples from
#'   configurations of planar triangles in 2-dimensional space, optionally with
#'   noise.
#'
#' @details The sample is generated by an area-preserving parameterization of
#'   the planar triangle. This parameterization was derived through the method
#'   for sampling 2-manifolds as described by Arvo (2001).

#' @template ref-arvo2001
#'

#' @name triangles
#' @param n Number of observations.
#' @param triangle The (x,y) coordinates of the vertices of a triangle,
#'   formatted in a 2x3 matrix
#' @param bins Number of intervals per dimension to stratify by. Default set to
#'   1, which generates a uniform sample.
#' @param sd Standard deviation of (independent multivariate) Gaussian noise.
#' @example inst/examples/ex-triangles.r
NULL

#' @rdname triangles
#' @export
sample_triangle_planar <- function(n, triangle, bins = 1, sd = 0) {
  #Checks to make sure 'triangle' input is a 2x3 matrix and if not, alerts the
  #user
  if (nrow(triangle) != 2 | ncol(triangle) != 3)
    stop ("The triangle's vertices must be inputed as a 2x3 matrix")
  #Samples n values from a stratified unit square or samples n values between
  #0 and 1 for unit square coordinates if uniform sample desired
  if (bins > 1) {
    unit_square <- sample_strat_square(n, bins)
    s <- unit_square[, 1]
    t <- unit_square[, 2]
  } else {
    s <- runif(n, 0, 1)
    t <- runif(n, 0, 1)
  }
  #Stores 3 coefficients of area-preserving parameterization of triangle in a
  #3xn matrix with different unit square coordinates (s,t)
  coeffs <- rbind(1 - sqrt(s), sqrt(s) * (1 - t), sqrt(s) * t)
  #Multiplies the matrix of the triangle's vertices by the matrix of
  #coefficients, and transposes the product to create an array of uniformly
  #sampled x and y coordinates
  res <- t(triangle %*% coeffs)
  colnames(res) <- c('x', 'y')
  add_noise(res, sd = sd)
}

Try the tdaunif package in your browser

Any scripts or data that you put into this service are public.

tdaunif documentation built on Sept. 10, 2023, 5:07 p.m.