R/mkDmat.R

Defines functions mkDmat

################################################################################
#
# Create a deriv matrix for shape-constrained splines with domain bounds
# Maybe export for "advanced" use?
#
################################################################################

mkDmat <- function(d, s, knots, ord, intercept, lower = -Inf, upper = Inf){

  #----- Create initial matrix

  # Create diff matrices for each derivative order (including "zero" deriv)
  alldm <- lapply(rev(seq_len(d)), dm, knots = knots, ord = ord)
  alldm <- c(alldm, list(diag(length(knots) - ord)))

  # Matrix multiply everything
  Cmat <- s * Reduce("%*%", alldm)

  #----- Remove rows with domain

  # Determine the constraints to be kept
  nk <- length(knots)
  upkn <- knots[(ord + 1):(nk - d)]
  lokn <- knots[(d + 1):(length(knots) - ord)]
  keep <- (upkn > lower) & (lokn < upper)

  # Remove from Cmat
  Cmat <- Cmat[keep,, drop = F]

  #----- Clean and return

  # Optionally remove intercept
  if (!intercept) Cmat <- Cmat[,-1, drop = F]

  # Return
  Cmat
}

Try the cirls package in your browser

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

cirls documentation built on Sept. 13, 2025, 1:09 a.m.