1.0.3 • Published 8 months ago
cobs-ts v1.0.3
COBS-TS
A TypeScript implementation of Constrained B-Splines (COBS), based on the R package cobs.
Description
COBS-TS provides qualitatively constrained (regression) smoothing splines via linear programming and sparse matrices. It supports various constraints including:
- Monotonicity (increasing/decreasing)
- Convexity/Concavity
- Periodicity
- Pointwise constraints
Installation
npm install cobs-ts
Usage
import { Cobs } from 'cobs-ts';
// Example 1: Basic spline fitting
const x = [1, 2, 3, 4, 5];
const y = [1.1, 2.3, 2.9, 3.8, 4.2];
const cobs = new Cobs();
const result = cobs.fit(x, y);
console.log(result.fitted); // Fitted values
console.log(result.knots); // Knot locations
console.log(result.coefficients); // Spline coefficients
// Evaluate at a specific point
const value = result.evaluate(2.5);
// Example 2: Fitting with constraints
const constrainedResult = cobs.fit(x, y, {
constraints: [
{ type: 'monotone', increasing: true }, // Monotone increasing
{ type: 'pointwise', x: 3, y: 3, operator: '>=' } // Point constraint
],
degree: 2,
numKnots: 10,
lambda: 0.5
});
// Access the fit results
console.log(constrainedResult.fitted); // Fitted values
console.log(constrainedResult.residuals); // Residuals
console.log(constrainedResult.coefficients); // Spline coefficients
// Evaluate derivatives
const derivative = constrainedResult.evaluateDerivative(2.5);
const secondDerivative = constrainedResult.evaluateSecondDerivative(2.5);
Features
- B-spline basis functions of degree 1 or 2
- Multiple constraint types
- Automatic knot selection
- Information criterion (AIC, BIC, SIC) for model selection
- Sparse matrix implementation for efficient computation
- Support for weighted fitting
- Quantile regression capability
API
Cobs.fit(x: number[], y: number[], options?: CobsOptions): CobsResult
Main function for fitting constrained B-splines.
Options
constraint
: 'none' | 'increase' | 'decrease' | 'convex' | 'concave' | 'periodic'weights
: number[] - Observation weightsknots
: number | number[] - Number of knots or explicit knot locationsdegree
: 1 | 2 - Degree of B-spline basistau
: number - Quantile level (default: 0.5 for median regression)lambda
: number | null - Smoothing parameteric
: 'AIC' | 'BIC' | 'SIC' - Information criterion for model selectionpointwise
: PointwiseConstraint[] - Additional pointwise constraintsmaxiter
: number - Maximum number of iterationsnknots
: number - Number of knots if not explicitly specifiedkeep
: boolean - Whether to keep additional fitting information
Development
# Install dependencies
npm install
# Build
npm run build
# Run tests
npm test
# Run linter
npm run lint
License
GPL-2.0-or-later (matching the original R package license)
References
- Original R package by Pin T. Ng and Martin Maechler
- He, X. and Ng, P. (1999): "COBS: Qualitatively Constrained Smoothing via Linear Programming"; Computational Statistics, 14, 315-337.