Skip to content

fastLoess WebAssembly API Reference

The WebAssembly bindings provide a high-performance interface to the core Rust library, mirroring the Rust API structure.

StreamingLoess and OnlineLoess are documented separately: Streaming Adapter, Online Adapter

  • Dataset fits in memory
  • Need intervals, cross-validation, or diagnostics
  • Processing complete files

The Loess class is the main entry point for batch smoothing.

Constructor:

const { Loess } = require('fastloess-wasm');
const model = new Loess({ fraction: 0.5 });
console.log("typeof fit:", typeof model.fit);
typeof fit: function
  • options: An object containing LoessOptions fields.

Fits the model to the provided x and y typed arrays. Returns a LoessResult object.

const { Loess } = require('fastloess-wasm');
const n = 100;
const x = Float64Array.from({ length: n }, (_, i) => i * 2 * Math.PI / (n - 1));
const y = Float64Array.from(x, xi => Math.sin(xi) + 0.1);
const model = new Loess({ fraction: 0.5 });
const result = model.fit(x, y);
console.log("Fraction used:", result.fraction_used);
console.log("Iterations used:", result.iterations_used);
// or with per-observation weights:
const weights = new Float64Array(n).fill(1);
const resultWeighted = model.fit(x, y, weights);
Fraction used: 0.5
Iterations used: 3
FieldTypeDefaultDescription
fractionnumber0.67Smoothing fraction (bandwidth)
iterationsnumber3Number of robustifying iterations
weight_functionstring"tricube"Kernel weight function
robustness_methodstring"bisquare"Robustness method
degreestring"linear"Polynomial degree of local fit
dimensionsnumber1Number of predictor dimensions
distance_metricstring"normalized"Distance metric; use "minkowski:p" for custom p
weighted_metric_weightsnumber[]nullPer-dimension weights (used when distance_metric = "weighted")
surface_modestring"interpolation"Surface computation mode
cellnumbernullCell size for interpolation grid (smaller → more vertices, higher accuracy)
interpolation_verticesnumbernullNumber of interpolation vertices
zero_weight_fallbackstring"use_local_mean"Zero-weight handling
boundary_policystring"extend"Boundary handling policy
boundary_degree_fallbackbooleannullFall back to lower polynomial degree at boundaries when higher degrees fail
scaling_methodstring"mad"Residual scaling method
auto_convergenumbernullAuto-convergence tolerance
missingstring"error"Policy for non-finite (NaN/Inf) values in input data
parallelbooleantrueEnable parallel execution
outputsstring[][]Optional fields: "diagnostics", "residuals", "weights", "gradient" (or "derivative"), "se", "sorted"
intervals{ confidence?: number; prediction?: number }disabledGrouped confidence and prediction coverage levels.
cv{ fractions: number[]; method?: string; k?: number }disabledGrouped candidate fractions, method, and folds; seed is an outer option
seednumberunsetNon-negative safe-integer seed for reproducible CV folds, up to Number.MAX_SAFE_INTEGER.
retain_modelbooleanfalseRetain training data, enabling result.predict()
custom_weightsnumber[]nullPer-observation case weights — passed to fit(), not the options object

fraction is the most important parameter: it controls the size of the local neighbourhood used at each point.

RangeEffectUse case
0.1-0.3Fine detailRapidly changing signals
0.3-0.5BalancedGeneral purpose
0.5-0.7Heavy smoothingNoisy data
0.7-1.0Very smoothTrend extraction

iterations controls robustness to outliers, at the cost of speed.

ValueEffectPerformance
0No robustnessFastest
1-3ModerateRecommended
4-6StrongContaminated data
7+Very strongHeavy outliers

See: Weight Functions

  • "tricube" (default)
  • "epanechnikov"
  • "gaussian"
  • "uniform" (alias: "boxcar")
  • "biweight" (alias: "bisquare")
  • "triangle" (alias: "triangular")
  • "cosine"

See: Robustness

  • "bisquare" (default; alias: "biweight")
  • "huber"
  • "talwar"

See: Polynomial Degree

  • "constant" or "0" (degree 0)
  • "linear" or "1" (default, degree 1)
  • "quadratic" or "2" (degree 2)
  • "cubic" or "3" (degree 3)
  • "quartic" or "4" (degree 4)

See: Multivariate LOESS

Number of predictor dimensions. Set to match the number of columns in a multivariate x array.

  • Any integer >= 1; 1 (default) is univariate

See: Multivariate LOESS

  • "normalized" (default — scales each dimension by its range; alias: "norm")
  • "euclidean" (alias: "euclid")
  • "manhattan" (alias: "l1")
  • "chebyshev" (alias: "linf")
  • "minkowski" (Euclidean when no suffix; use "minkowski:p" for custom p, e.g. "minkowski:3")
  • "weighted" plus weighted_metric_weights for per-dimension scaling (alias: "weighted_euclidean")

See: Multivariate LOESS

Per-dimension weights, one per dimension declared in dimensions. Only used when distance_metric = "weighted"; setting distance_metric = "weighted" without providing this raises an error.

  • null (default) — has no effect unless distance_metric = "weighted" is set
  • A number[] of per-dimension weights, required when distance_metric = "weighted"

See: Polynomial Degree

Controls whether the local polynomial is evaluated at every query point or at a sparser grid of anchor vertices with Hermite cubic interpolation in between.

ModeBehaviorSpeedAccuracy
"interpolation" (default)Evaluate at vertices, interpolate betweenFasterSlight approximation
"direct"Evaluate at every query pointSlowerFull precision

Cell size for the interpolation grid, as a fraction of the data range. Smaller values place more vertices (denser grid), improving accuracy at the cost of speed. Only applies when surface_mode = "interpolation".

  • null (default) — uses the library default (0.2)
  • Any number in (0, 1]

Caps the maximum number of interpolation vertices, overriding the count implied by cell. Only applies when surface_mode = "interpolation".

  • null (default) — uses the library default (no explicit cap)
  • Any integer >= 1

Behavior when all neighborhood weights are zero:

OptionBehavior
"use_local_mean" (default; aliases: "local_mean", "mean")Use the mean of the neighborhood
"return_original" (alias: "original")Return the original y value
"return_none" (alias: "none")Return NaN

See: Boundary Handling

  • "extend" (default; alias: "pad")
  • "reflect" (alias: "mirror")
  • "zero"
  • "noboundary" (alias: "none")

Whether to reduce the polynomial degree at boundary vertices when the requested degree can’t be fit there (e.g., not enough neighbours). Only applies when surface_mode = "interpolation".

  • null (default) — uses the library default (enabled)
  • true — falls back to a lower degree at boundaries
  • false — raises an error instead of silently falling back

See: Scaling Methods

  • "mad" (default; alias: "median_absolute_deviation")
  • "mar" (alias: "median_absolute_residual")
  • "mean" (alias: "mean_absolute_residual")

See: Robustness

Convergence tolerance for early stopping of robustness iterations. null (default) disables early stopping.

Policy for handling non-finite (NaN/Inf) values in x/y (and custom weights):

OptionBehavior
"error" (default)Throw an error if any value is non-finite
"drop"Silently remove observations (rows) where any x dimension or y is non-finite before fitting

Note: A length mismatch between x and y always throws, even under "drop".

Enable multi-threaded execution via the Rayon-based web worker pool.

  • true (default) — parallelizes the local regression fits
  • false — forces single-threaded execution

See: Intervals

Computes hat-matrix statistics (effective degrees of freedom, leverage, delta1/delta2) in addition to standard errors.

See: Diagnostics

Include a Diagnostics object (RMSE, MAE, R², AIC/AICc, effective degrees of freedom) in the result. AIC/AICc/effective_df additionally require outputs: ["se"] (or confidence/prediction intervals) to be populated, since they depend on hat-matrix statistics.

Include per-point residuals (y - fitted) in the result.

Include the final per-point robustness weights (from the last robustness iteration) in the result.

Each local polynomial fit (degree >= linear) already computes per-dimension coefficients internally, but only the fitted value is normally kept; this exposes that per-point gradient (rate of change of the smoothed surface, dimensions values per point, flattened) in result.gradient, enabling sensitivity/rate-of-change analysis at effectively no extra computation cost. Only supported when surface_mode is "direct" — the default "interpolation" mode only stores value+gradient at a sparse grid of vertices, not enough to reconstruct an exact per-point gradient, so fit() throws instead of silently leaving gradient as undefined. Omitted by default.

When selected in outputs, it reorders every result field (residuals, intervals, etc.) by x in an ascending manner, instead of in original input order. To get both orderings, sort the default result client-side (e.g. by the returned x array’s sort order) instead of calling fit() twice.

See: Intervals

Confidence level for the confidence interval around the mean response (e.g. 0.95). null (default) disables confidence intervals.

See: Intervals

Confidence level for the prediction interval for new observations (e.g. 0.95). null (default) disables prediction intervals.

See: Cross-Validation

  • cv.method: "kfold" (default) — fast, evaluates each candidate fraction over cv.k folds; "loocv" — slow, exhaustive leave-one-out cross-validation
  • cv.k: Number of folds for k-fold CV. Ignored when cv_method = "loocv".
  • cv.fractions: Candidate fractions to evaluate. Cross-validation is disabled unless this is set.
  • seed: Non-negative safe-integer seed for reproducible k-fold shuffling, from 0 through Number.MAX_SAFE_INTEGER. null (default) uses a random seed; fractional, negative, non-finite, and unsafe values throw.

See: Predict

Retains the fitted model’s training data, enabling result.predict(newX, options) to evaluate the fit at out-of-sample query points not in the training set. false (default) — no extra memory/copy cost unless requested.

See: Custom Weights

Per-observation weights, passed to fit() rather than the options object.

FieldTypeDescription
xFloat64Arrayx values (same order as input)
yFloat64ArraySmoothed y values
fraction_usednumberFraction used (set or selected by CV)
iterations_usednumber | undefinedRobustness iterations actually performed
standard_errorsFloat64Array | undefinedPer-point SE (if "se" output)
confidence_lowerFloat64Array | undefinedLower confidence bounds
confidence_upperFloat64Array | undefinedUpper confidence bounds
prediction_lowerFloat64Array | undefinedLower prediction bounds
prediction_upperFloat64Array | undefinedUpper prediction bounds
residualsFloat64Array | undefinedResiduals (if "residuals" output)
robustness_weightsFloat64Array | undefinedRobustness weights (if "weights" output)
cv_scoresFloat64Array | undefinedCV score per tested fraction
diagnosticsDiagnostics | undefinedFit metrics (if "diagnostics" output)
enpnumber | undefinedEquivalent number of parameters (if "se" output)
trace_hatnumber | undefinedTrace of hat matrix (if "se" output)
delta1number | undefinedFirst delta statistic (if "se" output)
delta2number | undefinedSecond delta statistic (if "se" output)
residual_scalenumber | undefinedResidual scale estimate (if "se" output)
leverageFloat64Array | undefinedPer-point hat-matrix diagonal (if "se" output)
gradientFloat64Array | undefinedPer-point local fit gradient, flattened (if "gradient" output, surface_mode = "direct" only)
dimensionsnumberNumber of predictor dimensions
FieldTypeDescription
rmsenumberRoot Mean Squared Error
maenumberMean Absolute Error
r_squarednumberR-squared
residual_sdnumberRobust residual scale estimate (1.4826 * MAD)
effective_dfnumber | undefinedEffective degrees of freedom
aicnumber | undefinedAIC
aiccnumber | undefinedAICc

result.predict(newX, options) -> PredictOutput

Section titled “result.predict(newX, options) -> PredictOutput”

Evaluates the fitted model at out-of-sample query points (flattened, dimensions values per point). Requires retain_model: true on the constructor before fit(), otherwise throws.

const { Loess } = require('fastloess-wasm');
const x = new Float64Array([1, 2, 3, 4, 5]);
const y = new Float64Array([2.1, 4.0, 6.2, 8.0, 10.1]);
// Fit data
const model = new Loess({ fraction: 0.5 });
const result = model.fit(x, y);
console.log("Smoothed Y:", result.y);
Smoothed Y: Float64Array(5) [ 2.1, 4, 6.2, 8, 10.1 ]