Polynomial Library in BsplineQuantReg

Introduction

The ‘BsplineQuantReg’ package provides a comprehensive set of tools for polynomial manipulation, implemented in pure R with a consistent interface. All polynomial functions follow the Matlab decreasing power order convention, where a polynomial \(p(x) = a_0 + a_1 x + a_2 x^2\) is represented as c(a_2, a_1, a_0). This convention is also used in most libraries for polynomials in R and Python.

This library written in pure R provides most polynomial operations needed for spline and B-spline manipulations, such as addition, multiplication, derivatives, piecewise polynomials and evaluation.

content

This part covers:

  • Basic polynomial operations (addition, multiplication, evaluation, differentiation);
  • Piecewise polynomial (PP) form;
  • Callable and non-callable PP objects;
  • Extracting parameters from PP objects.

Basic polynomial operations

Polynomial multiplication

# (1 + x) * (1 + x) = x^2 + 2x + 1
p1 <- c(1, 1)  # x + 1
p2 <- c(1, 1)  # x + 1
product <- polymul(p1, p2)
print(product)  # c(1, 2, 1) -> x^2 + 2x + 1
## [1] 1 2 1
# (x^2 + 2x + 1) * (x - 1) = x^3 + x^2 - x - 1
p3 <- c(1, 2, 1)  # x^2 + 2x + 1
p4 <- c(1, -1)    # x - 1
polymul(p3, p4)
## [1]  1  1 -1 -1

Polynomial addition

# (1 + x) + (1 - x) = 2
polyadd(c(1, 1), c(1, -1))
## [1] 2 0
# (x^2 + 1) + (x + 1) = x^2 + x + 2
polyadd(c(1, 0, 1), c(1, 1))
## [1] 1 1 2

Polynomial evaluation

# P(x) = x^2 + x + 1
p <- c(1, 1, 1)  # x^2 + x + 1
poly_eval(p, c(0, 1, 2))  # returns c(1, 3, 7)
## [1] 1 3 7
# Evaluate at many points and plot
x <- seq(-2, 2, length.out = 10)
y <- poly_eval(c(-1, 0, 1), x)  # - x^2+1
plot(x, y, type = "l", main = "- x^2+1")

Polynomial differentiation

# P(x) = x^2 -> P'(x) = 2x
p <- c(1, 0, 0)  # x^2
polyderiv(p, der = 1)  # c(2, 0) -> 2x
## [1] 2 0
# Second derivative: P''(x) = 2
polyderiv(p, der = 2)  # c(2)
## [1] 2
# Higher order derivatives
p <- c(4, 3, 2, 1)  # 4x^3 + 3x^2 + 2x + 1
polyderiv(p, der = 2)  # 24x + 6
## [1] 24  6

Polynomial reduction

Removing the useless 0 at the beginning of the coefficients ensures that the effective degree = length-1.

# Remove leading zeros
reduce_pol(c(0, 0, 1, 2, 1))  # c(1, 2, 1) -> x^2 + 2x + 1
## [1] 1 2 1
reduce_pol(c(0, 0, 0, 5))     # c(5) -> constant polynomial
## [1] 5
# Reduction after addition

p1<-c(4,1,3,2)
p2<-c(-4,-1,2,-1)
p<-polyadd(p1,p2)
cat("automatic reduction after addition: \n", p) # 0,0,5,2
## automatic reduction after addition: 
##  5 1

Taylor basis change

# Convert (x-1)^2 to expansion around 0
# (x-1)^2 = x^2 - 2x + 1
coeffs_a <- c(1, 0, 0)  # (x-1)^2 in basis centered at a=1
change_polynomial_base_taylor(coeffs_a, a = 1, b = 0)
## [1]  1 -2  1
# Returns c(1, -2, 1) -> x^2 - 2x + 1

fundamental tool : when computing recursively the local coefficients of the Bsplines at degree \(n\), the different parts of the Bspline at degree \(n-1\) and the function \(\omega\) are first written on the canonical basis. The result is more interesting when each piece on the inter-knot \([t_\nu, t_{\nu+1}]\) is given on its local basis \((t-t_\nu)^i, ~i=0,1..,n\).

Piecewise polynomial (PP) form

Creating a PP object: code

The PP form represents a function defined piecewise by polynomials on different intervals.

# Create a piecewise polynomial with two intervals
# Interval 1: x^2 on [0, 1]
# Interval 2: 2x - 1 on [1, 2]
coeff <- matrix(c(
  1, 0, 0,   # x^2
  0, 2, -1   # 2x - 1
), nrow = 2, byrow = TRUE)

knots <- c(0, 1, 2)

Creating a PP object: the pp (piecewise polynomial) object

pp <- makpp(coeff, knot = knots)
print(pp)
## Piecewise Polynomial (PP) (non-callable)
## ================================
##   $degree: 2 
##   $knot: 0 1 2 
##  coefficients dimension: 2 x 3 
## 
##   $coeff:
##     Intervals 1 : 1, 0, 0 
##     Intervals 2 : 0, 2, -1 
##  Usage: pp_eval(pp, x_values)

Ploting the result

# Evaluate the PP form
x <- seq(0, 2, length.out = 100)
y <- evalpp(pp, x)

plot(x, y, type = "l", main = "Piecewise polynomial")
abline(v = knots, col = "red", lty = 2)

Callable and Non-callable PP objects

PP object, as well as Bspline objets, have 2 differents evaluation mode. The values on “x” can be computed through “evalpp(PP, x)”. But callable object can be evaluated more simply with as functions with the syntax: “PP(x)”.

One passes from one state to the other with “makpp(PP, callable=…)”: “callable=TRUE” or “callable=FALSE”.

Non callable PP objects

A non-callable PP object is a list with components, with the class “non_callable”:

  • coeff: matrix of polynomial coefficients
  • knot: knot positions
  • degree: polynomial degree
pp <- makpp(coeff, knots, callable = FALSE)
class(pp)  # "non_callable_pp"
## [1] "non_callable_pp"
# Access components
pp
## Piecewise Polynomial (PP) (non-callable)
## ================================
##   $degree: 2 
##   $knot: 0 1 2 
##  coefficients dimension: 2 x 3 
## 
##   $coeff:
##     Intervals 1 : 1, 0, 0 
##     Intervals 2 : 0, 2, -1 
##  Usage: pp_eval(pp, x_values)

Callable PP objects : construction example code

A callable PP object can be evaluated directly like a function.

pp_call <- makpp(coeff, knots, callable = TRUE)
class(pp_call)  # "callable_pp" "function"
## [1] "callable_pp" "function"
x <- seq(0, 2, length.out = 10)
paste(x,collapse = ",")
## [1] "0,0.222222222222222,0.444444444444444,0.666666666666667,0.888888888888889,1.11111111111111,1.33333333333333,1.55555555555556,1.77777777777778,2"
y <- pp_call(x)
paste(y,ollapse = ",")
##  [1] "0 ,"                  "0.0493827160493827 ," "0.197530864197531 ," 
##  [4] "0.444444444444444 ,"  "0.790123456790123 ,"  "-0.777777777777778 ,"
##  [7] "-0.333333333333333 ," "0.111111111111111 ,"  "0.555555555555555 ," 
## [10] "1 ,"

Callable PP objects : the informations

print(pp_call)
## Callable Piecewise Polynomial (PP) Object
## ==========================================
##   Degree: 2 
##   Intervals: 2 
##   Knots ( 3 ) : 0, 1, 2 
##  coefficients dimension: 2 x 3 
## 
##   $coeff:
##     Intervals 1 : 1, 0, 0 
##     Intervals 2 : 0, 2, -1 
##  Usage: pp(x_values) or evalpp(pp, x_values)

Callable PP objects : the plot

plot(pp_call, xlim = c(0, 2))

Extrapolating values

When evalpp() is called with x values outside the knot range (\(x < \text{knots}[1]\) or \(x > \text{knots}[\text{length(knots)}]\)), it automatically performs extrapolation by extension using the border polynomial piece (the first or last polynomial in the PP structure). For example, if the knot vector is c(0, 1, 2), points with \(x < 0\) will be evaluated using the polynomial from the first interval \([0, 1]\), while points with \(x > 2\) will use the polynomial from the last interval \([1, 2]\).

This is equivalent to “extending” the first and last piece of the spline. A warning message is printed to alert the user when extrapolation occurs.

Extrapolating values : example

coeff <- matrix(c(1, 0, 0, 0, 2, -1), nrow = 2, byrow = TRUE)
knots <- c(0, 1, 2)
pp <- makpp(coeff, knots, callable = TRUE)

x_test <- c(-0.5, 0.5, 1.5, 2.5)
y_test <- pp(x_test)
data.frame(x = x_test, y = y_test)
##      x    y
## 1 -0.5 0.25
## 2  0.5 0.25
## 3  1.5 0.00
## 4  2.5 2.00
# The values at -0.5 and 2.5 are extrapolated

Extracting parameters

For callable PP objects, use “get_parameters()”

params <- get_parameters(pp_call)
print(params$degree)
## [1] 2
print(params$knot)
## [1] 0 1 2
print(params$coeff)
##      [,1] [,2] [,3]
## [1,]    1    0    0
## [2,]    0    2   -1
print(pp)
## Callable Piecewise Polynomial (PP) Object
## ==========================================
##   Degree: 2 
##   Intervals: 2 
##   Knots ( 3 ) : 0, 1, 2 
##  coefficients dimension: 2 x 3 
## 
##   $coeff:
##     Intervals 1 : 1, 0, 0 
##     Intervals 2 : 0, 2, -1 
##  Usage: pp(x_values) or evalpp(pp, x_values)

Extracting parameters for non-callable pp

non-callable PP objets are lists: access directly the parameters

pp <- makpp(pp_call, callable = FALSE, verbose = TRUE)
## transform 'callable_pp' to 'non_callable_pp'
pp$degree
## [1] 2
pp$knot
## [1] 0 1 2
pp$coeff
##      [,1] [,2] [,3]
## [1,]    1    0    0
## [2,]    0    2   -1
print(pp)
## Piecewise Polynomial (PP) (non-callable)
## ================================
##   $degree: 2 
##   $knot: 0 1 2 
##  coefficients dimension: 2 x 3 
## 
##   $coeff:
##     Intervals 1 : 1, 0, 0 
##     Intervals 2 : 0, 2, -1 
##  Usage: pp_eval(pp, x_values)

More examples: PP form manipulation

Extracting a single interval polynomial

# Get polynomial for interval i
pp <- makpp(pp_call, callable = FALSE)
interval_poly <- pp$coeff[1, ]  # first interval
print(interval_poly)
## [1] 1 0 0
# Evaluate on a subinterval
x_sub <- seq(0, 1, length.out = 20)
y_sub <- poly_eval(interval_poly, x_sub)

Create and visualising PP : new example code

knots <- seq(0, 1, length.out = 5)
degree <- 2
n_pieces <- length(knots) - 1

set.seed(2)
coeff <- matrix(c(20, 5, 1) * rnorm(n_pieces * (degree + 1)),
                nrow = n_pieces)

pp <- makpp(coeff, knot = knots, callable = TRUE)

x <- seq(0, 1, length.out = 200)
y <- pp(x)

Create and visualising PP : new example view

Comparison: PP vs B-spline : “bslinetopp()”, example code

sn <- c(0, 0, 0, 0, 0.25, 0.5, 0.75, 1, 1, 1, 1)
tn <- c(0, 0.25, 0.5, 0.75, 1)
set.seed(42)
coeff <- 10 * rnorm(7, 1)
Bspline <- list(coeff = coeff, knot = tn, degree = 3)
Bspline <- make_spline(Bspline)

pp_from_bspline <- Bsplinetopp(Bspline)

x <- seq(0, 1, length.out = 100)
y_bspline <- spline_eval(Bspline, x)
y_pp      <- evalpp(pp_from_bspline, x)

PP vs B-spline : visualisation

## Max |B-spline - PP| = 2.4869e-14
Comparison PP vs Bspline evaluation for the same base object

Comparison PP vs Bspline evaluation for the same base object

Summary of basic polynomial operations

Feature Function Description
Polynomial multiplication “polymul()” Multiply two polynomials
Polynomial addition “polyadd()” Add two polynomials
Polynomial evaluation “poly_eval()” Evaluate at points
Polynomial derivative “polyderiv()” Differentiate polynomial
Taylor shift “change_polynomial_base_taylor()” Change expansion point
PP creation “makpp()” Create PP form
PP evaluation “evalpp()” Evaluate PP at points
Callable PP “makpp(callable = TRUE)” PP as function
Extract params “get_parameters()” Extract from callable

Displaying polynomials in a human-readable form

The show_poly() function displays a polynomial as a human-readable mathematical equation. It supports both canonical and local bases, and can convert between different expansion points using Taylor’s formula.

A polynomial \(P(x) = \sum_{i=0}^d c_i (x-a)^i\) represented by coefficients c(c_d, c_{d-1}, ..., c_0) (decreasing power order) can be displayed in any basis \((x-b)^i\).

Basic usage

Canonical basis (default)

By default, show_poly() displays the polynomial in the canonical basis \(1, x, x^2, \dots\):

# P(x) = 3x^3 - 2x^2 + x - 5
p <- c(3, -2, 1, -5)
show_poly(p)
## [1] "3*x^3-2*x^2+1*x^1-5"

Display in local basis

Assuming we have a polynomial given on the canonical basis \(x^i\). To display it in the local basis \((x-b)^i\), use the b parameter:

# P(x) = 3(x-2)^3 - 2(x-2)^2 + (x-2) - 5
p <- c(3, -2, 1, -5)
show_poly(p, b = 2)
## [1] "3*(x-2)^3+16*(x-2)^2+29*(x-2)^1+13"

Converting between bases

By default, “show_poly(p, b = 2)” assumes that p is given on the canonical basis.

The a parameter specifies the basis in which the coefficients are given. The function automatically converts using “change_polynomial_base_taylor()”:

# Coefficients are in basis (x-2)^k, display in canonical basis
p <- c(3, -2, 1, -5)  # in basis (x-2)^i
show_poly(p, a = 2, b = 0)
## [1] "3*x^3-20*x^2+45*x^1-39"

Examples with different bases

Positive and negative centres

# Center at positive value
p <- c(1, 0, 2)  # (x-3)^2 + 2
show_poly(p, b = 3)
## [1] "1*(x-3)^2+6*(x-3)^1+11"
# Center at negative value
p <- c(1, 0, 2)  # (x+2)^2 + 2
show_poly(p, b = -2)
## [1] "1*(x+2)^2-4*(x+2)^1+6"

Controlling output format: number of digits

p <- c(1/3, -2/7, 1/5)
show_poly(p, digits = 2)
## [1] "0.33*x^2-0.29*x^1+0.2"
show_poly(p, digits = 7)
## [1] "0.3333333*x^2-0.2857143*x^1+0.2"

Integration with show_pp()

The show_poly() function is used internally by show_pp() to display piecewise polynomials:

The display functions “show_pp()” offer several customization options:

  • local: Control the basis (TRUE for local, FALSE for canonical)
  • digits: Number of significant digits (default: 4)
  • verbose: Display additional PP information

Integration with show_pp() code example

# Create a PP with two intervals
knot <- c(0, 0.5, 1)
coeff <- matrix(c(1, 2, 0.5, 0, 1, -1), nrow = 2, ncol = 3, byrow = TRUE)
pp <- makpp(coeff, knot)

# Display in local basis
show_pp(pp, local = TRUE, digits = 3)
##      [,1]                  [,2]                       
## [1,] "  [0.0000, 0.5000] " "1*x^2+2*x^1+0.5"          
## [2,] "  [0.5000, 1.0000] " "0*(x-0.5)^2+1*(x-0.5)^1-1"

Integration with show_pp() new example

# Create a PP with two intervals
knots <- c(0, 0.5, 1)
coeff <- matrix(c(1, 2, 0.5, 0, 1, -1), nrow = 2, ncol = 3, byrow = TRUE)
pp <- makpp(coeff, knot=knots)

# Display in canonical basis (1, x, x², ...)
show_pp(pp, local = FALSE)
##      [,1]                  [,2]             
## [1,] "  [0.0000, 0.5000] " "1*x^2+2*x^1+0.5"
## [2,] "  [0.5000, 1.0000] " "0*x^2+1*x^1-1.5"

Integration with show_pp() example with spline

For spline objects, the conversion to PP is automatic:

# Create a B-spline and display its polynomial form
sn <- c(0, 0, 0, 0, 0.3, 0.6, 1, 1, 1, 1)
basis <- Bspline_base(sn, degree = 3)
basis$coeff <- c(1, -0.5, 2, 0.5, -1, 0.75)
basis<-make_spline(basis)

show_pp(basis, local = TRUE, verbose = TRUE)
## Piecewise Polynomial (PP) (non-callable)
## ================================
##   $degree: 3 
##   $knot: 0 0.3 0.6 1 
##  coefficients dimension: 3 x 4 
## 
##   $coeff:
##     Intervals 1 : -133.3333, 91.6667, -15, 1 
##     Intervals 2 : 28.4203, -28.3333, 4, 1.15 
##     Intervals 3 : 43.0325, -2.7551, -5.3265, 0.5673 
##  Usage: pp_eval(pp, x_values)
##      [,1]                 
## [1,] "  [0.0000, 0.3000] "
## [2,] "  [0.3000, 0.6000] "
## [3,] "  [0.6000, 1.0000] "
##      [,2]                                                        
## [1,] "-133.3333*x^3+91.6667*x^2-15*x^1+1"                        
## [2,] "28.4203*(x-0.3)^3-28.3333*(x-0.3)^2+4*(x-0.3)^1+1.15"      
## [3,] "43.0325*(x-0.6)^3-2.7551*(x-0.6)^2-5.3265*(x-0.6)^1+0.5673"

show_poly with B-splines: decompose the use of “show_pp()”

#convert to pp
pp<-Bsplinetopp(basis)
# Display each piece and compare with show_pp()
cat("Piece 1: ", show_poly(pp$coeff[1, ], b = 0), "\n")
## Piece 1:  -133.3333*x^3+91.6667*x^2-15*x^1+1
cat("Piece 2: ", show_poly(pp$coeff[2, ], b = 0), "\n")
## Piece 2:  28.4203*x^3-28.3333*x^2+4*x^1+1.15
cat("Piece 3: ", show_poly(pp$coeff[3, ], b = 0), "\n")
## Piece 3:  43.0325*x^3-2.7551*x^2-5.3265*x^1+0.5673