BLS/NNLS (Bounded/Non-Negative Least Squares)

January 29, 2026 ยท View on GitHub

Bounded Least Squares and Non-Negative Least Squares for constrained optimization.

Functions

FunctionTypeDescription
bls_fit_aggAggregateBounded Least Squares with box constraints
nnls_fit_aggAggregateNon-Negative Least Squares (coefficients >= 0)
bls_fit_predict_aggAggregateFit and predict with GROUP BY support
bls_fit_predict_byTable MacroPer-group regression with long-format output

anofox_stats_bls_fit_agg

Bounded Least Squares with box constraints on coefficients.

Signature:

anofox_stats_bls_fit_agg(
    y DOUBLE,
    x LIST(DOUBLE),
    [options MAP]
) -> STRUCT

Options MAP:

KeyTypeDefaultDescription
fit_interceptBOOLEANfalseInclude intercept term
lower_boundDOUBLE-Lower bound for all coefficients
upper_boundDOUBLE-Upper bound for all coefficients
max_iterationsINTEGER1000Maximum iterations
toleranceDOUBLE1e-10Convergence tolerance

Returns: BlsFitResult STRUCT

Example:

-- Coefficients bounded between 0 and 1
SELECT bls_fit_agg(
    y,
    [x1, x2, x3],
    {'lower_bound': 0.0, 'upper_bound': 1.0}
)
FROM portfolio_data;

-- Only lower bound (coefficients >= 0)
SELECT bls_fit_agg(
    y,
    [x1, x2],
    {'lower_bound': 0.0}
)
FROM data;

anofox_stats_nnls_fit_agg

Non-Negative Least Squares - all coefficients constrained to be >= 0.

Signature:

anofox_stats_nnls_fit_agg(
    y DOUBLE,
    x LIST(DOUBLE),
    [options MAP]
) -> STRUCT

Options MAP:

KeyTypeDefaultDescription
fit_interceptBOOLEANfalseInclude intercept term
max_iterationsINTEGER1000Maximum iterations
toleranceDOUBLE1e-10Convergence tolerance

Returns: BlsFitResult STRUCT

Example:

-- Non-negative coefficients (e.g., mixture models)
SELECT nnls_fit_agg(spectrum, [component1, component2, component3])
FROM spectral_data;

-- Portfolio weights (no short selling)
SELECT nnls_fit_agg(returns, [stock1, stock2, stock3])
FROM portfolio_data;

-- Per-group NNLS
SELECT
    category,
    (nnls_fit_agg(y, [x1, x2])).coefficients
FROM data
GROUP BY category;

Use Cases

  • Spectral unmixing / mixture models: Component proportions must be non-negative
  • Portfolio optimization: No short selling constraint
  • Physical constraints: Concentrations, weights must be positive
  • Image processing: Non-negative matrix factorization
  • Signal processing: Source separation

See Also

  • OLS - Unconstrained regression
  • Ridge - Regularized regression
  • Table Macros - Per-group predictions