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
When to Use Batch Adapter
Section titled “When to Use Batch Adapter”- Dataset fits in memory
- Need intervals, cross-validation, or diagnostics
- Processing complete files
Classes
Section titled “Classes”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: functionoptions: An object containingLoessOptionsfields.
fit(x, y)
Section titled “fit(x, y)”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.5Iterations used: 3Options Structures
Section titled “Options Structures”LoessOptions
Section titled “LoessOptions”| Field | Type | Default | Description |
|---|---|---|---|
fraction | number | 0.67 | Smoothing fraction (bandwidth) |
iterations | number | 3 | Number of robustifying iterations |
weight_function | string | "tricube" | Kernel weight function |
robustness_method | string | "bisquare" | Robustness method |
degree | string | "linear" | Polynomial degree of local fit |
dimensions | number | 1 | Number of predictor dimensions |
distance_metric | string | "normalized" | Distance metric; use "minkowski:p" for custom p |
weighted_metric_weights | number[] | null | Per-dimension weights (used when distance_metric = "weighted") |
surface_mode | string | "interpolation" | Surface computation mode |
cell | number | null | Cell size for interpolation grid (smaller → more vertices, higher accuracy) |
interpolation_vertices | number | null | Number of interpolation vertices |
zero_weight_fallback | string | "use_local_mean" | Zero-weight handling |
boundary_policy | string | "extend" | Boundary handling policy |
boundary_degree_fallback | boolean | null | Fall back to lower polynomial degree at boundaries when higher degrees fail |
scaling_method | string | "mad" | Residual scaling method |
auto_converge | number | null | Auto-convergence tolerance |
missing | string | "error" | Policy for non-finite (NaN/Inf) values in input data |
parallel | boolean | true | Enable parallel execution |
outputs | string[] | [] | Optional fields: "diagnostics", "residuals", "weights", "gradient" (or "derivative"), "se", "sorted" |
intervals | { confidence?: number; prediction?: number } | disabled | Grouped confidence and prediction coverage levels. |
cv | { fractions: number[]; method?: string; k?: number } | disabled | Grouped candidate fractions, method, and folds; seed is an outer option |
seed | number | unset | Non-negative safe-integer seed for reproducible CV folds, up to Number.MAX_SAFE_INTEGER. |
retain_model | boolean | false | Retain training data, enabling result.predict() |
custom_weights | number[] | null | Per-observation case weights — passed to fit(), not the options object |
Options
Section titled “Options”fraction
Section titled “fraction”fraction is the most important parameter: it controls the size of the local neighbourhood used at each point.
| Range | Effect | Use case |
|---|---|---|
| 0.1-0.3 | Fine detail | Rapidly changing signals |
| 0.3-0.5 | Balanced | General purpose |
| 0.5-0.7 | Heavy smoothing | Noisy data |
| 0.7-1.0 | Very smooth | Trend extraction |
iterations
Section titled “iterations”iterations controls robustness to outliers, at the cost of speed.
| Value | Effect | Performance |
|---|---|---|
| 0 | No robustness | Fastest |
| 1-3 | Moderate | Recommended |
| 4-6 | Strong | Contaminated data |
| 7+ | Very strong | Heavy outliers |
weight_function
Section titled “weight_function”See: Weight Functions
"tricube"(default)"epanechnikov""gaussian""uniform"(alias:"boxcar")"biweight"(alias:"bisquare")"triangle"(alias:"triangular")"cosine"
robustness_method
Section titled “robustness_method”See: Robustness
"bisquare"(default; alias:"biweight")"huber""talwar"
degree
Section titled “degree”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)
dimensions
Section titled “dimensions”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
distance_metric
Section titled “distance_metric”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"plusweighted_metric_weightsfor per-dimension scaling (alias:"weighted_euclidean")
weighted_metric_weights
Section titled “weighted_metric_weights”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 unlessdistance_metric = "weighted"is set- A
number[]of per-dimension weights, required whendistance_metric = "weighted"
surface_mode
Section titled “surface_mode”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.
| Mode | Behavior | Speed | Accuracy |
|---|---|---|---|
"interpolation" (default) | Evaluate at vertices, interpolate between | Faster | Slight approximation |
"direct" | Evaluate at every query point | Slower | Full 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]
interpolation_vertices
Section titled “interpolation_vertices”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
zero_weight_fallback
Section titled “zero_weight_fallback”Behavior when all neighborhood weights are zero:
| Option | Behavior |
|---|---|
"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 |
boundary_policy
Section titled “boundary_policy”See: Boundary Handling
"extend"(default; alias:"pad")"reflect"(alias:"mirror")"zero""noboundary"(alias:"none")
boundary_degree_fallback
Section titled “boundary_degree_fallback”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 boundariesfalse— raises an error instead of silently falling back
scaling_method
Section titled “scaling_method”See: Scaling Methods
"mad"(default; alias:"median_absolute_deviation")"mar"(alias:"median_absolute_residual")"mean"(alias:"mean_absolute_residual")
auto_converge
Section titled “auto_converge”See: Robustness
Convergence tolerance for early stopping of robustness iterations. null (default) disables early stopping.
missing
Section titled “missing”Policy for handling non-finite (NaN/Inf) values in x/y (and custom weights):
| Option | Behavior |
|---|---|
"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".
parallel
Section titled “parallel”Enable multi-threaded execution via the Rayon-based web worker pool.
true(default) — parallelizes the local regression fitsfalse— forces single-threaded execution
outputs: se
Section titled “outputs: se”See: Intervals
Computes hat-matrix statistics (effective degrees of freedom, leverage, delta1/delta2) in addition to standard errors.
outputs: diagnostics
Section titled “outputs: diagnostics”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.
outputs: residuals
Section titled “outputs: residuals”Include per-point residuals (y - fitted) in the result.
outputs: weights
Section titled “outputs: weights”Include the final per-point robustness weights (from the last robustness iteration) in the result.
outputs: gradient
Section titled “outputs: gradient”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.
outputs: sorted
Section titled “outputs: sorted”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.
intervals.confidence
Section titled “intervals.confidence”See: Intervals
Confidence level for the confidence interval around the mean response (e.g. 0.95). null (default) disables confidence intervals.
intervals.prediction
Section titled “intervals.prediction”See: Intervals
Confidence level for the prediction interval for new observations (e.g. 0.95). null (default) disables prediction intervals.
CV Options
Section titled “CV Options”See: Cross-Validation
cv.method:"kfold"(default) — fast, evaluates each candidate fraction overcv.kfolds;"loocv"— slow, exhaustive leave-one-out cross-validationcv.k: Number of folds for k-fold CV. Ignored whencv_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, from0throughNumber.MAX_SAFE_INTEGER.null(default) uses a random seed; fractional, negative, non-finite, and unsafe values throw.
retain_model
Section titled “retain_model”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.
custom_weights
Section titled “custom_weights”See: Custom Weights
Per-observation weights, passed to fit() rather than the options object.
Result Structure
Section titled “Result Structure”LoessResult
Section titled “LoessResult”| Field | Type | Description |
|---|---|---|
x | Float64Array | x values (same order as input) |
y | Float64Array | Smoothed y values |
fraction_used | number | Fraction used (set or selected by CV) |
iterations_used | number | undefined | Robustness iterations actually performed |
standard_errors | Float64Array | undefined | Per-point SE (if "se" output) |
confidence_lower | Float64Array | undefined | Lower confidence bounds |
confidence_upper | Float64Array | undefined | Upper confidence bounds |
prediction_lower | Float64Array | undefined | Lower prediction bounds |
prediction_upper | Float64Array | undefined | Upper prediction bounds |
residuals | Float64Array | undefined | Residuals (if "residuals" output) |
robustness_weights | Float64Array | undefined | Robustness weights (if "weights" output) |
cv_scores | Float64Array | undefined | CV score per tested fraction |
diagnostics | Diagnostics | undefined | Fit metrics (if "diagnostics" output) |
enp | number | undefined | Equivalent number of parameters (if "se" output) |
trace_hat | number | undefined | Trace of hat matrix (if "se" output) |
delta1 | number | undefined | First delta statistic (if "se" output) |
delta2 | number | undefined | Second delta statistic (if "se" output) |
residual_scale | number | undefined | Residual scale estimate (if "se" output) |
leverage | Float64Array | undefined | Per-point hat-matrix diagonal (if "se" output) |
gradient | Float64Array | undefined | Per-point local fit gradient, flattened (if "gradient" output, surface_mode = "direct" only) |
dimensions | number | Number of predictor dimensions |
Diagnostics
Section titled “Diagnostics”| Field | Type | Description |
|---|---|---|
rmse | number | Root Mean Squared Error |
mae | number | Mean Absolute Error |
r_squared | number | R-squared |
residual_sd | number | Robust residual scale estimate (1.4826 * MAD) |
effective_df | number | undefined | Effective degrees of freedom |
aic | number | undefined | AIC |
aicc | number | undefined | AICc |
Predict
Section titled “Predict”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.
Example
Section titled “Example”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 dataconst 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 ]