lowess 0.99.9

High-performance LOWESS (Locally Weighted Scatterplot Smoothing)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
<!-- markdownlint-disable MD024 MD033 -->
# LOWESS Project

[![License](https://img.shields.io/badge/license-MIT%2FApache--2.0-blue.svg)](LICENSE-MIT)
[![Docs](https://img.shields.io/badge/docs-readthedocs-blue.svg)](https://lowess.readthedocs.io/)
[![Crates.io](https://img.shields.io/crates/v/lowess.svg)](https://crates.io/crates/lowess)
[![PyPI](https://img.shields.io/pypi/v/fastlowess.svg)](https://pypi.org/project/fastlowess/)
[![Conda](https://anaconda.org/conda-forge/fastlowess/badges/version.svg)](https://anaconda.org/conda-forge/fastlowess)
[![R-universe](https://thisisamirv.r-universe.dev/badges/rfastlowess)](https://thisisamirv.r-universe.dev/rfastlowess)
[![npm](https://img.shields.io/npm/v/fastlowess.svg)](https://www.npmjs.com/package/fastlowess)

<p align="center">
  <img src="https://raw.githubusercontent.com/thisisamirv/lowess-project/main/dev/logo.png" alt="One LOWESS to Rule Them All" width="400">
  <br>
  <em>One LOWESS to Rule Them All</em>
</p>

The fastest, most robust, and most feature-complete language-agnostic LOWESS (Locally Weighted Scatterplot Smoothing) implementation for **Rust**, **Python**, **R**, **Julia**, **JavaScript**, **C++**, and **WebAssembly**.

> [!IMPORTANT]
>
> The `lowess-project` contains a complete ecosystem for LOWESS smoothing:
>
> - **[`lowess`]https://github.com/thisisamirv/lowess-project/tree/main/crates/lowess** - Core single-threaded Rust implementation with `no_std` support
> - **[`fastLowess`]https://github.com/thisisamirv/lowess-project/tree/main/crates/fastLowess** - Parallel CPU and GPU-accelerated Rust wrapper with ndarray integration  
> - **[`R bindings`]https://github.com/thisisamirv/lowess-project/tree/main/bindings/r** - extendr-based R package
> - **[`Python bindings`]https://github.com/thisisamirv/lowess-project/tree/main/bindings/python** - PyO3-based Python package
> - **[`Julia bindings`]https://github.com/thisisamirv/lowess-project/tree/main/bindings/julia** - Native Julia package with C FFI
> - **[`JavaScript bindings`]https://github.com/thisisamirv/lowess-project/tree/main/bindings/nodejs** - Node.js package
> - **[`WebAssembly bindings`]https://github.com/thisisamirv/lowess-project/tree/main/bindings/wasm** - WASM package
> - **[`C++ bindings`]https://github.com/thisisamirv/lowess-project/tree/main/bindings/cpp** - Native C++ package with CMake integration

## LOESS vs. LOWESS

| Feature               | LOESS (This Crate)                | LOWESS                         |
|-----------------------|-----------------------------------|--------------------------------|
| **Polynomial Degree** | Linear, Quadratic, Cubic, Quartic | Linear (Degree 1)              |
| **Dimensions**        | Multivariate (n-D support)        | Univariate (1-D only)          |
| **Flexibility**       | High (Distance metrics)           | Standard                       |
| **Complexity**        | Higher (Matrix inversion)         | Lower (Weighted average/slope) |

> [!TIP]
> **Note:** For a **LOESS** implementation, use [`loess-project`]https://github.com/thisisamirv/loess-project.

---

## Documentation

> [!NOTE]
>
> ### 📚 [View the full documentation]https://lowess.readthedocs.io/

## Why this package?

### Speed

The `lowess` project crushes the competition in terms of speed, wether in single-threaded or multi-threaded parallel execution.

Speedup relative to Python's `statsmodels.lowess` (higher is better):

| Category                        | statsmodels | R (stats) | Serial | Parallel | GPU     |
|---------------------------------|-------------|-----------|--------|----------|---------|
| **Clustered**                   | 163ms       | 83×       | 203×   | **433×** | 32×     |
| **Constant Y**                  | 134ms       | 92×       | 212×   | **410×** | 18×     |
| **Delta** (large–none)          | 105ms       |||| **16×** |
| **Extreme Outliers**            | 489ms       | 106×      | 201×   | **388×** | 29×     |
| **Financial** (500–10K)         | 106ms       | 105×      | 252×   | **293×** | 12×     |
| **Fraction** (0.05–0.67)        | 221ms       | 104×      | 228×   | **391×** | 22×     |
| **Genomic** (1K–50K)            | 1833ms      ||| 20×      | **95×** |
| **High Noise**                  | 435ms       | 133×      | 134×   | **375×** | 32×     |
| **Iterations** (0–10)           | 204ms       | 115×      | 224×   | **386×** | 18×     |
| **Scale** (1K–50K)              | 1841ms      | 264×      | 487×   | **581×** | 98×     |
| **Scientific** (500–10K)        | 167ms       | 109×      | 205×   | **314×** | 15×     |
| **Scale Large**\* (100K–2M)     |||| **1.4×** | 0.3×    |

\*Scale Large benchmarks are relative to Serial (statsmodels cannot handle these sizes)

*The numbers are the average across a range of scenarios for each category (e.g., Delta from none, to small, medium, and large).*

### Robustness

This implementation is *more robust* than R's `lowess` and Python's `statsmodels` due to two key design choices:

**MAD-Based Scale Estimation:**

For robustness weight calculations, this crate uses *Median Absolute Deviation (MAD)* for scale estimation:

```text
s = median(|r_i - median(r)|)
```

In contrast, `statsmodels` and R's `lowess` uses the median of absolute residuals (MAR):

```text
s = median(|r_i|)
```

- MAD is a *breakdown-point-optimal* estimator—it remains valid even when up to 50% of data are outliers.
- The median-centering step removes asymmetric bias from residual distributions.
- MAD provides consistent outlier detection regardless of whether residuals are centered around zero.

**Boundary Padding:**

This crate applies a range of different *boundary policies* at dataset edges:

- **Extend**: Repeats edge values to maintain local neighborhood size.
- **Reflect**: Mirrors data symmetrically around boundaries.
- **Zero**: Pads with zeros (useful for signal processing).
- **NoBoundary**: Original Cleveland behavior

`statsmodels` and R's `lowess` do not apply boundary padding, which can lead to:

- Biased estimates near boundaries due to asymmetric local neighborhoods.
- Increased variance at the edges of the smoothed curve.

### Features

A variety of features, supporting a range of use cases:

| Feature              | This package  | statsmodels  | R (stats)    |
|----------------------|:-------------:|:------------:|:------------:|
| Kernel               | 7 options     | only Tricube | only Tricube |
| Robustness Weighting | 3 options     | only Huber   | only Huber   |
| Scale Estimation     | 2 options     | only MAR     | only MAR     |
| Boundary Padding     | 4 options     | no padding   | no padding   |
| Zero Weight Fallback | 3 options     | no           | no           |
| Auto Convergence     | yes           | no           | no           |
| Online Mode          | yes           | no           | no           |
| Streaming Mode       | yes           | no           | no           |
| Confidence Intervals | yes           | no           | no           |
| Prediction Intervals | yes           | no           | no           |
| Cross-Validation     | 2 options     | no           | no           |
| Parallel Execution   | yes           | no           | no           |
| GPU Acceleration     | yes*          | no           | no           |
| `no-std` Support     | yes           | no           | no           |

\* GPU acceleration is currently in beta and may not be available on all platforms.

## Validation

All implementations are **numerical twins** of R's `lowess`:

| Aspect          | Status         | Details                                       |
|-----------------|----------------|-----------------------------------------------|
| **Accuracy**    | ✅ EXACT MATCH | Max diff < 1e-12 across all scenarios         |
| **Consistency** | ✅ PERFECT     | Multiple scenarios pass with strict tolerance |
| **Robustness**  | ✅ VERIFIED    | Robust smoothing matches R exactly            |

## Installation

Currently available for R, Python, Julia, and Rust:

**R** (from R-universe, recommended):

```r
install.packages("rfastlowess", repos = "https://thisisamirv.r-universe.dev")
```

**Python** (from PyPI):

```bash
pip install fastlowess
```

Or from conda-forge:

```bash
conda install -c conda-forge fastlowess
```

**Rust** (lowess, no_std compatible):

```toml
[dependencies]
lowess = "0.99"
```

**Rust** (fastLowess, parallel + GPU):

```toml
[dependencies]
fastLowess = { version = "0.99", features = ["cpu"] }
```

**Julia** (from Julia General Registry):

```julia
using Pkg
Pkg.add("fastLowess")
```

**Node.js** (from npm):

```bash
npm install fastlowess
```

**WebAssembly** (from npm):

```bash
npm install fastlowess-wasm
```

Or via CDN:

```html
<script type="module">
  import init, { smooth } from 'https://unpkg.com/fastlowess-wasm@latest';
  await init();
</script>
```

**C++** (build from source):

```bash
make cpp
# Links against libfastlowess_cpp.so
```

## Quick Example

**R:**

```r
library(rfastlowess)

x <- c(1, 2, 3, 4, 5)
y <- c(2.0, 4.1, 5.9, 8.2, 9.8)

result <- fastlowess(x, y, fraction = 0.5, iterations = 3)
print(result$y)
```

**Python:**

```python
import fastlowess as fl
import numpy as np

x = np.array([1.0, 2.0, 3.0, 4.0, 5.0])
y = np.array([2.0, 4.1, 5.9, 8.2, 9.8])

result = fl.smooth(x, y, fraction=0.5, iterations=3)
print(result["y"])
```

**Rust:**

```rust
use lowess::prelude::*;

let x = vec![1.0, 2.0, 3.0, 4.0, 5.0];
let y = vec![2.0, 4.1, 5.9, 8.2, 9.8];

let model = Lowess::new()
    .fraction(0.5)
    .iterations(3)
    .adapter(Batch)
    .build()?;

let result = model.fit(&x, &y)?;
println!("{}", result);
```

**Julia:**

```julia
using fastlowess

x = [1.0, 2.0, 3.0, 4.0, 5.0]
y = [2.0, 4.1, 5.9, 8.2, 9.8]

result = fit(Lowess(fraction=0.5, iterations=3), x, y)
println(result.y)
```

**Node.js:**

```javascript
const { Lowess } = require('fastlowess');

const x = [1.0, 2.0, 3.0, 4.0, 5.0];
const y = [2.0, 4.1, 5.9, 8.2, 9.8];

const model = new Lowess({ fraction: 0.5, iterations: 3 });
const result = model.fit(x, y);
console.log(result.y);
```

**WebAssembly:**

```javascript
import init, { smooth } from 'fastlowess-wasm';

await init();

const x = new Float64Array([1.0, 2.0, 3.0, 4.0, 5.0]);
const y = new Float64Array([2.0, 4.1, 5.9, 8.2, 9.8]);

const result = smooth(x, y, { fraction: 0.5, iterations: 3 });
console.log(result.y);
```

**C++:**

```cpp
#include <fastlowess.hpp>

std::vector<double> x = {1.0, 2.0, 3.0, 4.0, 5.0};
std::vector<double> y = {2.0, 4.1, 5.9, 8.2, 9.8};

fastlowess::LowessOptions options;
options.fraction = 0.5;
options.iterations = 3;

fastlowess::Lowess model(options);
auto result = model.fit(x, y);

for (double val : result.y_vector()) std::cout << val << " ";
```

---

## API Reference

**R:**

```r
fastlowess(
    x, y,
    fraction = 0.5,
    iterations = 3L,
    delta = 0.01,
    weight_function = "tricube",
    robustness_method = "bisquare",
    zero_weight_fallback = "use_local_mean",
    boundary_policy = "extend",
    confidence_intervals = 0.95,
    prediction_intervals = 0.95,
    return_diagnostics = TRUE,
    return_residuals = TRUE,
    return_robustness_weights = TRUE,
    cv_fractions = c(0.3, 0.5, 0.7),
    cv_method = "kfold",
    cv_k = 5L,
    auto_converge = 1e-4,
    parallel = TRUE
)
```

**Python:**

```python
fastlowess.smooth(
    x, y,
    fraction=0.5,
    iterations=3,
    delta=0.01,
    weight_function="tricube",
    robustness_method="bisquare",
    zero_weight_fallback="use_local_mean",
    boundary_policy="extend",
    confidence_intervals=0.95,
    prediction_intervals=0.95,
    return_diagnostics=True,
    return_residuals=True,
    return_robustness_weights=True,
    cv_fractions=[0.3, 0.5, 0.7],
    cv_method="kfold",
    cv_k=5,
    auto_converge=1e-4,
    parallel=True
)
```

**Rust:**

```rust
Lowess::new()
    .fraction(0.5)              // Smoothing span (0, 1]
    .iterations(3)              // Robustness iterations
    .delta(0.01)                // Interpolation threshold
    .weight_function(Tricube)   // Kernel selection
    .robustness_method(Bisquare)
    .zero_weight_fallback(UseLocalMean)
    .boundary_policy(Extend)
    .confidence_intervals(0.95)
    .prediction_intervals(0.95)
    .return_diagnostics()
    .return_residuals()
    .return_robustness_weights()
    .cross_validate(KFold(5, &[0.3, 0.5, 0.7]).seed(123))
    .auto_converge(1e-4)
    .adapter(Batch)             // or Streaming, Online
    .parallel(true)             // fastLowess only
    .backend(CPU)               // fastLowess only: CPU or GPU
    .build()?;
```

**Julia:**

```julia
Lowess(;
    fraction=0.5,
    iterations=3,
    delta=NaN,  # NaN for auto
    weight_function="tricube",
    robustness_method="bisquare",
    zero_weight_fallback="use_local_mean",
    boundary_policy="extend",
    confidence_intervals=NaN,
    prediction_intervals=NaN,
    return_diagnostics=true,
    return_residuals=true,
    return_robustness_weights=true,
    cv_fractions=Float64[], # e.g. [0.3, 0.5]
    cv_method="kfold",
    cv_k=5,
    auto_converge=NaN,
    parallel=true
)
```

**Node.js:**

```javascript
new Lowess({
    fraction: 0.5,
    iterations: 3,
    delta: 0.01,
    weightFunction: "tricube",
    robustnessMethod: "bisquare",
    zeroWeightFallback: "use_local_mean",
    boundaryPolicy: "extend",
    confidenceIntervals: 0.95,
    predictionIntervals: 0.95,
    returnDiagnostics: true,
    returnResiduals: true,
    returnRobustnessWeights: true,
    cvFractions: [0.3, 0.5, 0.7],
    cvMethod: "kfold",
    cvK: 5,
    autoConverge: 1e-4,
    parallel: true
}).fit(x, y)
```

**WebAssembly:**

```javascript
smooth(x, y, {
    fraction: 0.5,
    iterations: 3,
    delta: 0.01,
    weightFunction: "tricube",
    robustnessMethod: "bisquare",
    zeroWeightFallback: "use_local_mean",
    boundaryPolicy: "extend",
    confidenceIntervals: 0.95,
    predictionIntervals: 0.95,
    returnDiagnostics: true,
    returnResiduals: true,
    returnRobustnessWeights: true,
    cvFractions: [0.3, 0.5, 0.7],
    cvMethod: "kfold",
    cvK: 5,
    autoConverge: 1e-4
})
```

**C++:**

```cpp
fastlowess::LowessOptions options;
options.fraction = 0.5;
options.iterations = 3;
options.delta = 0.01;
options.weight_function = "tricube";
options.robustness_method = "bisquare";
options.zero_weight_fallback = "use_local_mean";
options.boundary_policy = "extend";
options.confidence_intervals = 0.95;
options.prediction_intervals = 0.95;
options.return_diagnostics = true;
options.return_residuals = true;
options.return_robustness_weights = true;
options.cv_fractions = {0.3, 0.5, 0.7};
options.cv_method = "kfold";
options.cv_k = 5;
options.auto_converge = 1e-4;
options.parallel = true;

fastlowess::Lowess model(options);
auto result = model.fit(x, y);
```

## Result Structure

**R:**

```r
result$x, result$y, result$standard_errors
result$confidence_lower, result$confidence_upper
result$prediction_lower, result$prediction_upper
result$residuals, result$robustness_weights
result$diagnostics, result$iterations_used
result$fraction_used, result$cv_scores
```

**Python:**

```python
result.x, result.y, result.standard_errors
result.confidence_lower, result.confidence_upper
result.prediction_lower, result.prediction_upper
result.residuals, result.robustness_weights
result.diagnostics, result.iterations_used
result.fraction_used, result.cv_scores
```

**Rust:**

```rust
pub struct LowessResult<T> {
    pub x: Vec<T>,                           // Sorted x values
    pub y: Vec<T>,                           // Smoothed y values
    pub standard_errors: Option<Vec<T>>,
    pub confidence_lower: Option<Vec<T>>,
    pub confidence_upper: Option<Vec<T>>,
    pub prediction_lower: Option<Vec<T>>,
    pub prediction_upper: Option<Vec<T>>,
    pub residuals: Option<Vec<T>>,
    pub robustness_weights: Option<Vec<T>>,
    pub diagnostics: Option<Diagnostics<T>>,
    pub iterations_used: Option<usize>,
    pub fraction_used: T,
    pub cv_scores: Option<Vec<T>>,
}
```

**Julia:**

```julia
result.x, result.y, result.standard_errors
result.confidence_lower, result.confidence_upper
result.prediction_lower, result.prediction_upper
result.residuals, result.robustness_weights
result.diagnostics, result.iterations_used
result.fraction_used
```

**Node.js:**

```javascript
result.x, result.y, result.standardErrors
result.confidenceLower, result.confidenceUpper
result.predictionLower, result.predictionUpper
result.residuals, result.robustnessWeights
result.diagnostics, result.iterationsUsed
result.fractionUsed, result.cvScores
```

**WebAssembly:**

```javascript
result.x, result.y, result.standardErrors
result.confidenceLower, result.confidenceUpper
result.predictionLower, result.predictionUpper
result.residuals, result.robustnessWeights
result.diagnostics, result.iterationsUsed
result.fractionUsed, result.cvScores
```

**C++:**

```cpp
result.y_vector()              // std::vector<double>
result.confidence_lower()      // std::vector<double>
result.confidence_upper()      // std::vector<double>
result.prediction_lower()      // std::vector<double>
result.prediction_upper()      // std::vector<double>
result.residuals()             // std::vector<double>
result.robustness_weights()    // std::vector<double>
result.diagnostics()           // Diagnostics struct
result.iterations_used()       // size_t
result.fraction_used()         // double
```

---

## Contributing

Contributions are welcome! Please see the [CONTRIBUTING.md](https://github.com/thisisamirv/lowess-project/blob/main/CONTRIBUTING.md) file for more information.

## License

Licensed under either of:

- Apache License, Version 2.0 ([LICENSE-APACHE]LICENSE-APACHE or <https://www.apache.org/licenses/LICENSE-2.0>)
- MIT license ([LICENSE-MIT]LICENSE-MIT or <https://opensource.org/licenses/MIT>)

at your option.

## References

- Cleveland, W.S. (1979). "Robust Locally Weighted Regression and Smoothing Scatterplots". *JASA*.
- Cleveland, W.S. (1981). "LOWESS: A Program for Smoothing Scatterplots". *The American Statistician*.

## Citation

If you use this software in your research, please cite it using the [CITATION.cff](https://github.com/thisisamirv/lowess-project/blob/main/CITATION.cff) file or the BibTeX entry below:

```bibtex
@software{lowess_project,
  author = {Valizadeh, Amir},
  title = {LOWESS Project: High-Performance Locally Weighted Scatterplot Smoothing},
  year = {2026},
  url = {https://github.com/thisisamirv/lowess-project},
  license = {MIT OR Apache-2.0}
}
```