plotsimplify 0.1.0__tar.gz → 0.2.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {plotsimplify-0.1.0 → plotsimplify-0.2.0}/CLAUDE.md +6 -3
- {plotsimplify-0.1.0 → plotsimplify-0.2.0}/Cargo.lock +1 -1
- {plotsimplify-0.1.0 → plotsimplify-0.2.0}/Cargo.toml +1 -1
- {plotsimplify-0.1.0 → plotsimplify-0.2.0}/PKG-INFO +8 -1
- {plotsimplify-0.1.0 → plotsimplify-0.2.0}/README.md +7 -0
- {plotsimplify-0.1.0 → plotsimplify-0.2.0}/pyproject.toml +1 -1
- {plotsimplify-0.1.0 → plotsimplify-0.2.0}/python/plotsimplify/__init__.py +39 -7
- {plotsimplify-0.1.0 → plotsimplify-0.2.0}/python/plotsimplify/_plotsimplify.pyi +1 -1
- {plotsimplify-0.1.0 → plotsimplify-0.2.0}/src/core.rs +92 -5
- {plotsimplify-0.1.0 → plotsimplify-0.2.0}/src/lib.rs +15 -4
- {plotsimplify-0.1.0 → plotsimplify-0.2.0}/tests/reference_kernel.py +17 -3
- {plotsimplify-0.1.0 → plotsimplify-0.2.0}/tests/test_simplify.py +158 -6
- {plotsimplify-0.1.0 → plotsimplify-0.2.0}/.github/workflows/ci.yml +0 -0
- {plotsimplify-0.1.0 → plotsimplify-0.2.0}/.github/workflows/release.yml +0 -0
- {plotsimplify-0.1.0 → plotsimplify-0.2.0}/.gitignore +0 -0
- {plotsimplify-0.1.0 → plotsimplify-0.2.0}/LICENSE +0 -0
- {plotsimplify-0.1.0 → plotsimplify-0.2.0}/benchmarks/bench.py +0 -0
- {plotsimplify-0.1.0 → plotsimplify-0.2.0}/benchmarks/results.txt +0 -0
- {plotsimplify-0.1.0 → plotsimplify-0.2.0}/docs/downsampling-report.md +0 -0
- {plotsimplify-0.1.0 → plotsimplify-0.2.0}/python/plotsimplify/py.typed +0 -0
- {plotsimplify-0.1.0 → plotsimplify-0.2.0}/tests/__init__.py +0 -0
|
@@ -9,17 +9,20 @@ crate); input handling lives in Python.
|
|
|
9
9
|
- `src/core.rs`: PyO3-free kernels.
|
|
10
10
|
- `scan`: one fused pass that ANDs finiteness into `valid` and returns
|
|
11
11
|
sortedness, the first/last valid index and the y range.
|
|
12
|
-
- `rdp_keep`: max-heap, largest-error-first RDP over each valid run.
|
|
12
|
+
- `rdp_keep`: max-heap, largest-error-first RDP over each valid run. Takes
|
|
13
|
+
k >= 1 y series sharing x (bands) and scores each segment by its worst
|
|
14
|
+
error over all of them.
|
|
13
15
|
- The 8-lane distance loops (`argmax_cross_*`, `argmax_seg_*`) are compiled
|
|
14
16
|
again with AVX-512/AVX2 `target_feature` and picked at runtime
|
|
15
17
|
(`PLOTSIMPLIFY_BASELINE=1` / `PLOTSIMPLIFY_NO_AVX512=1` force fallbacks).
|
|
16
18
|
- Rust tests compare against textbook recursive RDP.
|
|
17
19
|
- `src/lib.rs`: thin numpy-array bindings (`scan`, `rdp_keep`, `simd_level`),
|
|
18
|
-
GIL released.
|
|
20
|
+
GIL released. `rdp_keep` takes y as a C-contiguous `(k, n)` array.
|
|
19
21
|
- `python/plotsimplify/__init__.py`: the `simplify()` API. It converts
|
|
20
22
|
datetime64/int x to float offsets from the first valid point (exact in
|
|
21
23
|
int64 first), handles pixel scaling and gap markers, and calls the kernel
|
|
22
|
-
via the module global `_rs`.
|
|
24
|
+
via the module global `_rs`. Multi-series y is ANDed into `valid` in NumPy,
|
|
25
|
+
then `scan` runs once per series for the combined y range.
|
|
23
26
|
- `tests/reference_kernel.py`: pure-NumPy implementation of `scan`/`rdp_keep`.
|
|
24
27
|
Tests monkeypatch `plotsimplify._rs` with it and require **bit-identical**
|
|
25
28
|
results. A subprocess test does the same for the non-SIMD path.
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: plotsimplify
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.2.0
|
|
4
4
|
Classifier: Development Status :: 3 - Alpha
|
|
5
5
|
Classifier: Intended Audience :: Developers
|
|
6
6
|
Classifier: Intended Audience :: Science/Research
|
|
@@ -93,6 +93,13 @@ Prebuilt `abi3` wheels (Linux/macOS/Windows, x86-64 and arm64, Python
|
|
|
93
93
|
- **`max_points`.** Segments are split largest-error-first, so a budget
|
|
94
94
|
gives you the most important points in one pass, and `max_error` reports
|
|
95
95
|
the error you actually got.
|
|
96
|
+
- **Bands.** Pass several y series that share x, such as `mu ± sigma` or
|
|
97
|
+
a min/max envelope, as a `(len(x), k)` array or a list of arrays:
|
|
98
|
+
`simplify(t, [lo, hi])`. You get one set of indices, and every series is
|
|
99
|
+
within `eps` of its drawn line. Simplifying each edge separately and
|
|
100
|
+
taking the union of the indices doesn't give that: the extra points split
|
|
101
|
+
the other edge's segments, and its error can reach `2 * eps`. The joint
|
|
102
|
+
pass also keeps fewer points. A point is a gap if any series is NaN there.
|
|
96
103
|
- **Gaps.** Points with NaN `y` or NaT `x` are dropped, except the first
|
|
97
104
|
point of each gap. It's kept so the plot breaks the line instead of
|
|
98
105
|
joining across the gap.
|
|
@@ -67,6 +67,13 @@ Prebuilt `abi3` wheels (Linux/macOS/Windows, x86-64 and arm64, Python
|
|
|
67
67
|
- **`max_points`.** Segments are split largest-error-first, so a budget
|
|
68
68
|
gives you the most important points in one pass, and `max_error` reports
|
|
69
69
|
the error you actually got.
|
|
70
|
+
- **Bands.** Pass several y series that share x, such as `mu ± sigma` or
|
|
71
|
+
a min/max envelope, as a `(len(x), k)` array or a list of arrays:
|
|
72
|
+
`simplify(t, [lo, hi])`. You get one set of indices, and every series is
|
|
73
|
+
within `eps` of its drawn line. Simplifying each edge separately and
|
|
74
|
+
taking the union of the indices doesn't give that: the extra points split
|
|
75
|
+
the other edge's segments, and its error can reach `2 * eps`. The joint
|
|
76
|
+
pass also keeps fewer points. A point is a gap if any series is NaN there.
|
|
70
77
|
- **Gaps.** Points with NaN `y` or NaT `x` are dropped, except the first
|
|
71
78
|
point of each gap. It's kept so the plot breaks the line instead of
|
|
72
79
|
joining across the gap.
|
|
@@ -4,7 +4,7 @@ build-backend = "maturin"
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "plotsimplify"
|
|
7
|
-
version = "0.
|
|
7
|
+
version = "0.2.0"
|
|
8
8
|
description = "Rust-powered error-bounded time series simplification (Ramer-Douglas-Peucker) for plotting: keep only the points you can see"
|
|
9
9
|
readme = "README.md"
|
|
10
10
|
requires-python = ">=3.11"
|
|
@@ -24,7 +24,8 @@ class Simplified(NamedTuple):
|
|
|
24
24
|
indices: np.ndarray
|
|
25
25
|
"""int64 indices into the original x/y, sorted."""
|
|
26
26
|
max_error: float
|
|
27
|
-
"""Worst distance from a dropped point to the drawn line, in `eps` units.
|
|
27
|
+
"""Worst distance from a dropped point to the drawn line, in `eps` units.
|
|
28
|
+
With several y series, the worst over all of them."""
|
|
28
29
|
|
|
29
30
|
|
|
30
31
|
def simplify(
|
|
@@ -41,7 +42,12 @@ def simplify(
|
|
|
41
42
|
"""Pick the points of a time series needed to draw it within `eps` of the original.
|
|
42
43
|
|
|
43
44
|
x: sorted timestamps. numpy datetime64, integer or float.
|
|
44
|
-
y: values. NaN marks a gap.
|
|
45
|
+
y: values. NaN marks a gap. Either one series, or several that share x and
|
|
46
|
+
are drawn together, such as the edges of a band (mu ± sigma, min/max):
|
|
47
|
+
a 2-D array of shape (len(x), k), or a list/tuple of k 1-D arrays.
|
|
48
|
+
Several series get one set of indices, chosen so that every series is
|
|
49
|
+
within `eps` of its own drawn line. A point is a gap if any series is
|
|
50
|
+
NaN there.
|
|
45
51
|
|
|
46
52
|
With `width_px` and `height_px`, x and y are scaled to the plot's pixel size
|
|
47
53
|
first, so `eps` is in pixels (0.5 means "every dropped point is within half
|
|
@@ -72,7 +78,14 @@ def simplify(
|
|
|
72
78
|
|
|
73
79
|
xf, yf, valid = _prepare(x, y)
|
|
74
80
|
n = len(xf)
|
|
75
|
-
|
|
81
|
+
if len(yf) > 1:
|
|
82
|
+
valid &= np.isfinite(yf).all(axis=0)
|
|
83
|
+
# With several series `valid` is already final, so every scan sees the same
|
|
84
|
+
# points and returns the same sortedness and first/last; only the y ranges differ.
|
|
85
|
+
scans = [_rs.scan(xf, yj, valid) for yj in yf]
|
|
86
|
+
sorted_ok, first, last, _, _ = scans[0]
|
|
87
|
+
ymin = min(r[3] for r in scans)
|
|
88
|
+
ymax = max(r[4] for r in scans)
|
|
76
89
|
if not sorted_ok:
|
|
77
90
|
raise ValueError("x must be sorted (non-decreasing)")
|
|
78
91
|
if first < 0 or n <= 2:
|
|
@@ -107,12 +120,29 @@ def _gap_starts(valid):
|
|
|
107
120
|
return ~valid & prev
|
|
108
121
|
|
|
109
122
|
|
|
123
|
+
def _as_series(y):
|
|
124
|
+
"""y as a C-contiguous float64 array of shape (k, n): one row per series."""
|
|
125
|
+
if isinstance(y, (list, tuple)) and len(y) > 0 and np.ndim(y[0]) >= 1:
|
|
126
|
+
cols = [np.asarray(c, dtype=np.float64) for c in y]
|
|
127
|
+
if any(c.ndim != 1 or len(c) != len(cols[0]) for c in cols):
|
|
128
|
+
raise ValueError("each series in y must be a 1-D array of the same length")
|
|
129
|
+
return np.stack(cols)
|
|
130
|
+
a = np.asarray(y, dtype=np.float64)
|
|
131
|
+
if a.ndim == 1:
|
|
132
|
+
return np.ascontiguousarray(a[None, :])
|
|
133
|
+
if a.ndim == 2:
|
|
134
|
+
if a.shape[1] == 0:
|
|
135
|
+
raise ValueError("y must hold at least one series")
|
|
136
|
+
return np.ascontiguousarray(a.T)
|
|
137
|
+
raise ValueError("y must be 1-D, 2-D of shape (len(x), k), or a sequence of 1-D arrays")
|
|
138
|
+
|
|
139
|
+
|
|
110
140
|
def _prepare(x, y):
|
|
111
|
-
"""Convert inputs to contiguous float64 x
|
|
141
|
+
"""Convert inputs to contiguous float64 x, (k, n) y and an initial validity mask (NaT -> invalid)."""
|
|
112
142
|
x = np.asarray(x)
|
|
113
|
-
y =
|
|
114
|
-
if x.ndim != 1 or
|
|
115
|
-
raise ValueError("x
|
|
143
|
+
y = _as_series(y)
|
|
144
|
+
if x.ndim != 1 or len(x) != y.shape[1]:
|
|
145
|
+
raise ValueError("x must be 1-D and y must have one value per x")
|
|
116
146
|
|
|
117
147
|
if np.issubdtype(x.dtype, np.datetime64):
|
|
118
148
|
valid = ~np.isnat(x)
|
|
@@ -125,6 +155,8 @@ def _prepare(x, y):
|
|
|
125
155
|
|
|
126
156
|
# Subtract the first timestamp while still in int64: ns epochs (~1.7e18)
|
|
127
157
|
# don't fit float64's 53-bit mantissa, but offsets from the start do.
|
|
158
|
+
if len(xi) == 0:
|
|
159
|
+
return np.zeros(0, dtype=np.float64), y, valid
|
|
128
160
|
first = int(np.argmax(valid)) if valid.any() else 0
|
|
129
161
|
xf = (xi - xi[first]).astype(np.float64)
|
|
130
162
|
return xf, y, valid
|
|
@@ -5,6 +5,9 @@
|
|
|
5
5
|
//! - `rdp_keep`: RDP over each run of valid points, splitting segments
|
|
6
6
|
//! largest-error-first (a max-heap) so `max_points` gives the best greedy
|
|
7
7
|
//! budget. Marks kept points and gap markers; returns the max error left.
|
|
8
|
+
//! Takes one or more y series sharing x (e.g. the edges of a band) and
|
|
9
|
+
//! scores each segment by its worst error over all of them, so a single
|
|
10
|
+
//! set of kept points bounds every series.
|
|
8
11
|
//!
|
|
9
12
|
//! The distance loops are written as 8 independent lanes so LLVM vectorises
|
|
10
13
|
//! them, and are compiled again for AVX-512/AVX2 and picked at runtime. FMA
|
|
@@ -254,6 +257,22 @@ fn farthest(x: &[f64], y: &[f64], s: usize, e: usize, vertical: bool) -> (f64, u
|
|
|
254
257
|
(d.max(0.0).sqrt(), s + 1 + k)
|
|
255
258
|
}
|
|
256
259
|
|
|
260
|
+
/// `farthest` over several y series sharing x: the largest distance across
|
|
261
|
+
/// series and its point. Ties go to the lowest point index, then the first series.
|
|
262
|
+
#[inline(always)]
|
|
263
|
+
fn farthest_multi(x: &[f64], ys: &[&[f64]], s: usize, e: usize, vertical: bool) -> (f64, usize) {
|
|
264
|
+
// One call site, so `farthest` and its SIMD loops are inlined only once.
|
|
265
|
+
let (mut dmax, mut imax) = (f64::NEG_INFINITY, usize::MAX);
|
|
266
|
+
for y in ys {
|
|
267
|
+
let (d, k) = farthest(x, y, s, e, vertical);
|
|
268
|
+
if d > dmax || (d == dmax && k < imax) {
|
|
269
|
+
dmax = d;
|
|
270
|
+
imax = k;
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
(dmax, imax)
|
|
274
|
+
}
|
|
275
|
+
|
|
257
276
|
// ---------------------------------------------------------------- heap
|
|
258
277
|
|
|
259
278
|
/// Max-heap of segments keyed on the distance of their farthest point.
|
|
@@ -322,9 +341,11 @@ pub fn simd_level() -> &'static str {
|
|
|
322
341
|
|
|
323
342
|
// ---------------------------------------------------------------- kernels
|
|
324
343
|
|
|
344
|
+
/// `ys` holds one or more y series, each the length of `x`; `valid` must
|
|
345
|
+
/// already be false wherever any of them is non-finite (see `scan`).
|
|
325
346
|
pub fn rdp_keep(
|
|
326
347
|
x: &[f64],
|
|
327
|
-
|
|
348
|
+
ys: &[&[f64]],
|
|
328
349
|
valid: &[bool],
|
|
329
350
|
eps: f64,
|
|
330
351
|
vertical: bool,
|
|
@@ -332,6 +353,7 @@ pub fn rdp_keep(
|
|
|
332
353
|
keep: &mut [bool],
|
|
333
354
|
) -> f64 {
|
|
334
355
|
let n = x.len();
|
|
356
|
+
assert!(!ys.is_empty() && ys.iter().all(|y| y.len() == n));
|
|
335
357
|
let mut heap = Heap(Vec::new());
|
|
336
358
|
let mut count: i64 = 0;
|
|
337
359
|
|
|
@@ -357,7 +379,7 @@ pub fn rdp_keep(
|
|
|
357
379
|
count += 1;
|
|
358
380
|
}
|
|
359
381
|
if e0 - s0 >= 2 {
|
|
360
|
-
let (d, k) =
|
|
382
|
+
let (d, k) = farthest_multi(x, ys, s0, e0, vertical);
|
|
361
383
|
heap.push(Seg { d, s: s0, e: e0, k });
|
|
362
384
|
}
|
|
363
385
|
}
|
|
@@ -370,11 +392,11 @@ pub fn rdp_keep(
|
|
|
370
392
|
keep[k] = true;
|
|
371
393
|
count += 1;
|
|
372
394
|
if k - s >= 2 {
|
|
373
|
-
let (d, k1) =
|
|
395
|
+
let (d, k1) = farthest_multi(x, ys, s, k, vertical);
|
|
374
396
|
heap.push(Seg { d, s, e: k, k: k1 });
|
|
375
397
|
}
|
|
376
398
|
if e - k >= 2 {
|
|
377
|
-
let (d, k2) =
|
|
399
|
+
let (d, k2) = farthest_multi(x, ys, k, e, vertical);
|
|
378
400
|
heap.push(Seg { d, s: k, e, k: k2 });
|
|
379
401
|
}
|
|
380
402
|
}
|
|
@@ -554,7 +576,7 @@ mod tests {
|
|
|
554
576
|
let mut valid = vec![true; x.len()];
|
|
555
577
|
scan(x, y, &mut valid);
|
|
556
578
|
let mut keep = vec![false; x.len()];
|
|
557
|
-
let err = rdp_keep(x, y, &valid, eps, vertical, max_points, &mut keep);
|
|
579
|
+
let err = rdp_keep(x, &[y], &valid, eps, vertical, max_points, &mut keep);
|
|
558
580
|
let idx = keep
|
|
559
581
|
.iter()
|
|
560
582
|
.enumerate()
|
|
@@ -653,4 +675,69 @@ mod tests {
|
|
|
653
675
|
let (idx, _) = run(&x, &y, 0.5, true, 0);
|
|
654
676
|
assert_eq!(idx, [0, 4, 5, 8, 14, 15, 16, 19]);
|
|
655
677
|
}
|
|
678
|
+
|
|
679
|
+
fn run_multi(
|
|
680
|
+
x: &[f64],
|
|
681
|
+
ys: &[&[f64]],
|
|
682
|
+
eps: f64,
|
|
683
|
+
vertical: bool,
|
|
684
|
+
max_points: i64,
|
|
685
|
+
) -> (Vec<usize>, f64) {
|
|
686
|
+
let valid = vec![true; x.len()];
|
|
687
|
+
let mut keep = vec![false; x.len()];
|
|
688
|
+
let err = rdp_keep(x, ys, &valid, eps, vertical, max_points, &mut keep);
|
|
689
|
+
let idx = (0..x.len()).filter(|&i| keep[i]).collect();
|
|
690
|
+
(idx, err)
|
|
691
|
+
}
|
|
692
|
+
|
|
693
|
+
fn worst(x: &[f64], y: &[f64], idx: &[usize], vertical: bool) -> f64 {
|
|
694
|
+
let mut w: f64 = 0.0;
|
|
695
|
+
for p in idx.windows(2) {
|
|
696
|
+
for k in p[0] + 1..p[1] {
|
|
697
|
+
w = w.max(if vertical {
|
|
698
|
+
vert(x, y, k, p[0], p[1])
|
|
699
|
+
} else {
|
|
700
|
+
seg(x, y, k, p[0], p[1])
|
|
701
|
+
});
|
|
702
|
+
}
|
|
703
|
+
}
|
|
704
|
+
w
|
|
705
|
+
}
|
|
706
|
+
|
|
707
|
+
#[test]
|
|
708
|
+
fn one_series_in_multi_is_unchanged() {
|
|
709
|
+
let (x, y) = series(3000, 4);
|
|
710
|
+
for vertical in [true, false] {
|
|
711
|
+
for (eps, budget) in [(0.5, 0), (0.0, 200)] {
|
|
712
|
+
assert_eq!(
|
|
713
|
+
run_multi(&x, &[&y, &y], eps, vertical, budget),
|
|
714
|
+
run(&x, &y, eps, vertical, budget)
|
|
715
|
+
);
|
|
716
|
+
}
|
|
717
|
+
}
|
|
718
|
+
}
|
|
719
|
+
|
|
720
|
+
#[test]
|
|
721
|
+
fn band_bounds_every_series() {
|
|
722
|
+
let (x, a) = series(5000, 5);
|
|
723
|
+
let (_, b) = series(5000, 6);
|
|
724
|
+
let lo: Vec<f64> = a.iter().zip(&b).map(|(a, b)| a - 3.0 - b.abs()).collect();
|
|
725
|
+
let hi: Vec<f64> = a.iter().zip(&b).map(|(a, b)| a + 3.0 + b.abs()).collect();
|
|
726
|
+
let ys: [&[f64]; 3] = [&lo, &a, &hi];
|
|
727
|
+
for vertical in [true, false] {
|
|
728
|
+
for (eps, budget) in [(0.5, 0), (0.0, 300)] {
|
|
729
|
+
let (idx, err) = run_multi(&x, &ys, eps, vertical, budget);
|
|
730
|
+
let w = ys
|
|
731
|
+
.iter()
|
|
732
|
+
.map(|y| worst(&x, y, &idx, vertical))
|
|
733
|
+
.fold(0.0, f64::max);
|
|
734
|
+
if budget == 0 {
|
|
735
|
+
assert!(w <= eps + 1e-9, "{w}");
|
|
736
|
+
} else {
|
|
737
|
+
assert_eq!(idx.len(), budget as usize);
|
|
738
|
+
}
|
|
739
|
+
assert!((w - err).abs() <= 1e-9 * w.max(1.0), "{w} vs {err}");
|
|
740
|
+
}
|
|
741
|
+
}
|
|
742
|
+
}
|
|
656
743
|
}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
pub mod core;
|
|
2
2
|
|
|
3
|
-
use numpy::{PyReadonlyArray1, PyReadwriteArray1};
|
|
3
|
+
use numpy::{PyReadonlyArray1, PyReadonlyArray2, PyReadwriteArray1, PyUntypedArrayMethods};
|
|
4
4
|
use pyo3::exceptions::PyValueError;
|
|
5
5
|
use pyo3::prelude::*;
|
|
6
6
|
|
|
@@ -27,25 +27,36 @@ fn scan<'py>(
|
|
|
27
27
|
}
|
|
28
28
|
|
|
29
29
|
/// rdp_keep(x, y, valid, eps, vertical, max_points, keep) -> max_error; updates `keep` in place.
|
|
30
|
+
///
|
|
31
|
+
/// `y` is a C-contiguous (k, n) array: k >= 1 series sharing `x`.
|
|
30
32
|
#[pyfunction]
|
|
31
33
|
#[allow(clippy::too_many_arguments)]
|
|
32
34
|
fn rdp_keep<'py>(
|
|
33
35
|
py: Python<'py>,
|
|
34
36
|
x: PyReadonlyArray1<'py, f64>,
|
|
35
|
-
y:
|
|
37
|
+
y: PyReadonlyArray2<'py, f64>,
|
|
36
38
|
valid: PyReadonlyArray1<'py, bool>,
|
|
37
39
|
eps: f64,
|
|
38
40
|
vertical: bool,
|
|
39
41
|
max_points: i64,
|
|
40
42
|
mut keep: PyReadwriteArray1<'py, bool>,
|
|
41
43
|
) -> PyResult<f64> {
|
|
44
|
+
let (k, n) = (y.shape()[0], y.shape()[1]);
|
|
42
45
|
let (x, y, valid) = (x.as_slice()?, y.as_slice()?, valid.as_slice()?);
|
|
43
46
|
let keep = keep.as_slice_mut()?;
|
|
44
|
-
|
|
47
|
+
if k == 0 {
|
|
48
|
+
return Err(PyValueError::new_err("y must hold at least one series"));
|
|
49
|
+
}
|
|
50
|
+
check_len(x.len(), n)?;
|
|
45
51
|
check_len(x.len(), valid.len())?;
|
|
46
52
|
check_len(x.len(), keep.len())?;
|
|
53
|
+
let ys: Vec<&[f64]> = if n == 0 {
|
|
54
|
+
vec![&[]; k]
|
|
55
|
+
} else {
|
|
56
|
+
y.chunks_exact(n).collect()
|
|
57
|
+
};
|
|
47
58
|
// Release the GIL: other Python threads keep running while we crunch.
|
|
48
|
-
Ok(py.detach(|| core::rdp_keep(x,
|
|
59
|
+
Ok(py.detach(|| core::rdp_keep(x, &ys, valid, eps, vertical, max_points, keep)))
|
|
49
60
|
}
|
|
50
61
|
|
|
51
62
|
/// Which SIMD path the distance loops use on this CPU: "avx512", "avx2" or "baseline".
|
|
@@ -61,9 +61,23 @@ def _farthest(x, y, s, e, vertical):
|
|
|
61
61
|
return float(np.sqrt(max(d[i], 0.0))), s + 1 + i
|
|
62
62
|
|
|
63
63
|
|
|
64
|
+
def _farthest_multi(x, ys, s, e, vertical):
|
|
65
|
+
"""`_farthest` over each row of ys: the largest distance, ties to the lowest
|
|
66
|
+
point index, then the first series."""
|
|
67
|
+
dmax, imax = _farthest(x, ys[0], s, e, vertical)
|
|
68
|
+
for y in ys[1:]:
|
|
69
|
+
d, k = _farthest(x, y, s, e, vertical)
|
|
70
|
+
if d > dmax or (d == dmax and k < imax):
|
|
71
|
+
dmax, imax = d, k
|
|
72
|
+
return dmax, imax
|
|
73
|
+
|
|
74
|
+
|
|
64
75
|
def rdp_keep(x, y, valid, eps, vertical, max_points, keep):
|
|
65
76
|
"""Mark points to keep (in place); return the max error of the result.
|
|
66
77
|
|
|
78
|
+
y has shape (k, n): one or more series sharing x. Each segment is scored
|
|
79
|
+
by its worst distance over all series.
|
|
80
|
+
|
|
67
81
|
Every gap's first point and every run's endpoints are kept; then segments
|
|
68
82
|
are split at their farthest point, largest distance first, until the
|
|
69
83
|
largest remaining distance is <= eps or `max_points` (if > 0) is reached.
|
|
@@ -90,7 +104,7 @@ def rdp_keep(x, y, valid, eps, vertical, max_points, keep):
|
|
|
90
104
|
heap = []
|
|
91
105
|
for s0, e0 in zip(run_starts.tolist(), run_ends.tolist()):
|
|
92
106
|
if e0 - s0 >= 2:
|
|
93
|
-
d, k =
|
|
107
|
+
d, k = _farthest_multi(x, y, s0, e0, vertical)
|
|
94
108
|
heap.append((-d, s0, e0, k))
|
|
95
109
|
heapq.heapify(heap)
|
|
96
110
|
|
|
@@ -102,9 +116,9 @@ def rdp_keep(x, y, valid, eps, vertical, max_points, keep):
|
|
|
102
116
|
keep[k] = True
|
|
103
117
|
count += 1
|
|
104
118
|
if k - s >= 2:
|
|
105
|
-
d1, k1 =
|
|
119
|
+
d1, k1 = _farthest_multi(x, y, s, k, vertical)
|
|
106
120
|
heapq.heappush(heap, (-d1, s, k, k1))
|
|
107
121
|
if e - k >= 2:
|
|
108
|
-
d2, k2 =
|
|
122
|
+
d2, k2 = _farthest_multi(x, y, k, e, vertical)
|
|
109
123
|
heapq.heappush(heap, (-d2, k, e, k2))
|
|
110
124
|
return 0.0
|
|
@@ -158,6 +158,41 @@ def test_all_nan_and_tiny_inputs():
|
|
|
158
158
|
assert simplify(np.arange(5.0), np.full(5, np.nan)).indices.tolist() == [0]
|
|
159
159
|
|
|
160
160
|
|
|
161
|
+
EMPTY_X = [
|
|
162
|
+
np.array([], dtype=np.float64),
|
|
163
|
+
np.array([], dtype=np.int64),
|
|
164
|
+
np.array([], dtype=np.uint32),
|
|
165
|
+
np.array([], dtype="datetime64[ns]"),
|
|
166
|
+
]
|
|
167
|
+
EMPTY_KW = [
|
|
168
|
+
{},
|
|
169
|
+
dict(width_px=800, height_px=300),
|
|
170
|
+
dict(max_points=10),
|
|
171
|
+
dict(width_px=800, height_px=300, max_points=10, y_range=(0.0, 1.0)),
|
|
172
|
+
]
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
@pytest.mark.parametrize("metric", ["vertical", "perpendicular"])
|
|
176
|
+
@pytest.mark.parametrize("kw", EMPTY_KW)
|
|
177
|
+
@pytest.mark.parametrize("x", EMPTY_X, ids=lambda a: str(a.dtype))
|
|
178
|
+
def test_empty_input(x, kw, metric):
|
|
179
|
+
r = simplify(x, np.array([]), metric=metric, **kw)
|
|
180
|
+
assert r.indices.dtype == np.int64 and len(r.indices) == 0
|
|
181
|
+
assert r.max_error == 0.0
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
@pytest.mark.parametrize("metric", ["vertical", "perpendicular"])
|
|
185
|
+
@pytest.mark.parametrize("kw", EMPTY_KW)
|
|
186
|
+
@pytest.mark.parametrize("n", [1, 2, 5, 50])
|
|
187
|
+
def test_all_invalid_input(n, kw, metric):
|
|
188
|
+
# All-NaN y, and all-NaT x: just the one gap marker.
|
|
189
|
+
t = np.full(n, np.datetime64("NaT", "ns"))
|
|
190
|
+
for x, y in [(np.arange(n), np.full(n, np.nan)), (t, np.zeros(n))]:
|
|
191
|
+
r = simplify(x, y, metric=metric, **kw)
|
|
192
|
+
assert r.indices.tolist() == [0]
|
|
193
|
+
assert r.max_error == 0.0
|
|
194
|
+
|
|
195
|
+
|
|
161
196
|
def test_datetime64_matches_seconds():
|
|
162
197
|
x, y = random_series(2000, 3)
|
|
163
198
|
t = np.datetime64("2026-01-01T00:00:00", "ns") + (x * 1e9).astype("timedelta64[ns]")
|
|
@@ -238,6 +273,24 @@ def gappy_series():
|
|
|
238
273
|
return x, y
|
|
239
274
|
|
|
240
275
|
|
|
276
|
+
def gappy_band():
|
|
277
|
+
x, y = gappy_series()
|
|
278
|
+
rng = np.random.default_rng(0)
|
|
279
|
+
ys = np.column_stack([y - 3, y + rng.normal(0, 1, len(y)), y + 3])
|
|
280
|
+
ys[30_000:30_005, 2] = np.nan
|
|
281
|
+
return x, ys
|
|
282
|
+
|
|
283
|
+
|
|
284
|
+
def simd_check_outputs():
|
|
285
|
+
"""Results compared between the SIMD and forced-baseline builds."""
|
|
286
|
+
out = []
|
|
287
|
+
for x, y in (gappy_series(), gappy_band()):
|
|
288
|
+
out += [
|
|
289
|
+
simplify(x, y, metric=m, **kw) for m in ("vertical", "perpendicular") for kw in CASES
|
|
290
|
+
]
|
|
291
|
+
return out
|
|
292
|
+
|
|
293
|
+
|
|
241
294
|
@pytest.mark.parametrize("metric", ["vertical", "perpendicular"])
|
|
242
295
|
@pytest.mark.parametrize("kw", CASES)
|
|
243
296
|
def test_identical_to_numpy_reference(metric, kw, monkeypatch):
|
|
@@ -254,19 +307,118 @@ def test_baseline_simd_path_is_identical(tmp_path):
|
|
|
254
307
|
script = (
|
|
255
308
|
"import numpy as np, sys\n"
|
|
256
309
|
"sys.path.insert(0, %r)\n"
|
|
257
|
-
"from tests.test_simplify import
|
|
258
|
-
"from plotsimplify import
|
|
310
|
+
"from tests.test_simplify import simd_check_outputs\n"
|
|
311
|
+
"from plotsimplify import simd_level\n"
|
|
259
312
|
"assert simd_level() == 'baseline', simd_level()\n"
|
|
260
|
-
"
|
|
261
|
-
"out = [simplify(x, y, metric=m, **kw) for m in ('vertical', 'perpendicular') for kw in CASES]\n"
|
|
313
|
+
"out = simd_check_outputs()\n"
|
|
262
314
|
"np.save(%r, np.array([r.max_error for r in out]))\n"
|
|
263
315
|
"np.save(%r, np.concatenate([r.indices for r in out]))\n"
|
|
264
316
|
) % (str(Path(__file__).parent.parent), str(tmp_path / "err.npy"), str(tmp_path / "idx.npy"))
|
|
265
317
|
env = dict(os.environ, PLOTSIMPLIFY_BASELINE="1")
|
|
266
318
|
subprocess.run([sys.executable, "-c", script], check=True, env=env)
|
|
267
|
-
|
|
268
|
-
out = [simplify(x, y, metric=m, **kw) for m in ("vertical", "perpendicular") for kw in CASES]
|
|
319
|
+
out = simd_check_outputs()
|
|
269
320
|
np.testing.assert_array_equal(
|
|
270
321
|
np.load(tmp_path / "idx.npy"), np.concatenate([r.indices for r in out])
|
|
271
322
|
)
|
|
272
323
|
np.testing.assert_array_equal(np.load(tmp_path / "err.npy"), [r.max_error for r in out])
|
|
324
|
+
|
|
325
|
+
|
|
326
|
+
# ---------- several y series (bands) ----------
|
|
327
|
+
|
|
328
|
+
|
|
329
|
+
def band(n, seed):
|
|
330
|
+
rng = np.random.default_rng(seed)
|
|
331
|
+
x = np.arange(n, dtype=np.float64)
|
|
332
|
+
mu = np.cumsum(rng.normal(0, 1, n))
|
|
333
|
+
s = 5 + np.abs(np.cumsum(rng.normal(0, 0.3, n)))
|
|
334
|
+
return x, mu - s, mu + s
|
|
335
|
+
|
|
336
|
+
|
|
337
|
+
def test_band_union_of_separate_passes_breaks_bound_but_joint_does_not():
|
|
338
|
+
# The repro from issue #2: the union of per-series index sets can put a
|
|
339
|
+
# dropped point up to 2 * eps from the drawn line; the joint pass can't.
|
|
340
|
+
x, lo, hi = band(5000, 0)
|
|
341
|
+
k = np.union1d(simplify(x, lo, eps=0.5).indices, simplify(x, hi, eps=0.5).indices)
|
|
342
|
+
assert max(max_error(x, y, k, vert_dist) for y in (lo, hi)) > 0.5
|
|
343
|
+
|
|
344
|
+
r = simplify(x, np.column_stack([lo, hi]), eps=0.5)
|
|
345
|
+
assert max(max_error(x, y, r.indices, vert_dist) for y in (lo, hi)) <= 0.5
|
|
346
|
+
assert len(r.indices) <= len(k)
|
|
347
|
+
|
|
348
|
+
|
|
349
|
+
@pytest.mark.parametrize("metric,dist", [("vertical", vert_dist), ("perpendicular", seg_dist)])
|
|
350
|
+
@pytest.mark.parametrize("kw", [dict(eps=0.5), dict(eps=0.0, max_points=300)])
|
|
351
|
+
def test_band_reported_error_is_worst_over_series(metric, dist, kw):
|
|
352
|
+
x, lo, hi = band(4000, 1)
|
|
353
|
+
mid = (lo + hi) / 2
|
|
354
|
+
r = simplify(x, [lo, mid, hi], metric=metric, **kw)
|
|
355
|
+
worst = max(max_error(x, y, r.indices, dist) for y in (lo, mid, hi))
|
|
356
|
+
assert r.max_error == pytest.approx(worst, abs=1e-9)
|
|
357
|
+
if "max_points" in kw:
|
|
358
|
+
assert len(r.indices) == kw["max_points"]
|
|
359
|
+
else:
|
|
360
|
+
assert worst <= kw["eps"] + 1e-9
|
|
361
|
+
|
|
362
|
+
|
|
363
|
+
def test_band_error_bound_in_pixels():
|
|
364
|
+
x, lo, hi = band(3000, 2)
|
|
365
|
+
w, h, eps = 800, 300, 0.5
|
|
366
|
+
for metric, dist in [("vertical", vert_dist), ("perpendicular", seg_dist)]:
|
|
367
|
+
idx = simplify(x, (lo, hi), eps=eps, width_px=w, height_px=h, metric=metric).indices
|
|
368
|
+
# The default y range spans all series.
|
|
369
|
+
y0, y1 = lo.min(), hi.max()
|
|
370
|
+
px = (x - x[0]) * w / (x[-1] - x[0])
|
|
371
|
+
for y in (lo, hi):
|
|
372
|
+
assert max_error(px, (y - y0) * h / (y1 - y0), idx, dist) <= eps + 1e-9
|
|
373
|
+
|
|
374
|
+
|
|
375
|
+
def test_band_input_forms_agree():
|
|
376
|
+
x, lo, hi = band(2000, 3)
|
|
377
|
+
a = simplify(x, np.column_stack([lo, hi]))
|
|
378
|
+
for y in ([lo, hi], (lo, hi), [lo.tolist(), hi.tolist()], np.asfortranarray(np.c_[lo, hi])):
|
|
379
|
+
b = simplify(x, y)
|
|
380
|
+
np.testing.assert_array_equal(a.indices, b.indices)
|
|
381
|
+
assert a.max_error == b.max_error
|
|
382
|
+
|
|
383
|
+
|
|
384
|
+
def test_one_column_matches_1d():
|
|
385
|
+
x, y = random_series(3000, 4)
|
|
386
|
+
for metric in ("vertical", "perpendicular"):
|
|
387
|
+
for kw in CASES:
|
|
388
|
+
a = simplify(x, y, metric=metric, **kw)
|
|
389
|
+
for yy in (y[:, None], [y], [y, y]):
|
|
390
|
+
b = simplify(x, yy, metric=metric, **kw)
|
|
391
|
+
np.testing.assert_array_equal(a.indices, b.indices)
|
|
392
|
+
assert a.max_error == b.max_error
|
|
393
|
+
|
|
394
|
+
|
|
395
|
+
def test_band_gaps_are_the_union():
|
|
396
|
+
x = np.arange(20.0)
|
|
397
|
+
lo, hi = np.zeros(20), np.ones(20)
|
|
398
|
+
lo[5:8] = np.nan
|
|
399
|
+
hi[7:9] = np.nan
|
|
400
|
+
hi[15] = np.nan
|
|
401
|
+
assert simplify(x, [lo, hi]).indices.tolist() == [0, 4, 5, 9, 14, 15, 16, 19]
|
|
402
|
+
|
|
403
|
+
|
|
404
|
+
def test_band_bad_args():
|
|
405
|
+
x = np.arange(5.0)
|
|
406
|
+
with pytest.raises(ValueError, match="same length"):
|
|
407
|
+
simplify(x, [np.zeros(5), np.zeros(4)])
|
|
408
|
+
with pytest.raises(ValueError, match="one value per x"):
|
|
409
|
+
simplify(x, np.zeros((4, 2)))
|
|
410
|
+
with pytest.raises(ValueError, match="at least one"):
|
|
411
|
+
simplify(x, np.zeros((5, 0)))
|
|
412
|
+
with pytest.raises(ValueError):
|
|
413
|
+
simplify(x, np.zeros((5, 2, 1)))
|
|
414
|
+
|
|
415
|
+
|
|
416
|
+
@pytest.mark.parametrize("metric", ["vertical", "perpendicular"])
|
|
417
|
+
@pytest.mark.parametrize("kw", CASES)
|
|
418
|
+
def test_band_identical_to_numpy_reference(metric, kw, monkeypatch):
|
|
419
|
+
x, ys = gappy_band()
|
|
420
|
+
got = simplify(x, ys, metric=metric, **kw)
|
|
421
|
+
monkeypatch.setattr(plotsimplify, "_rs", reference_kernel)
|
|
422
|
+
ref = simplify(x, ys, metric=metric, **kw)
|
|
423
|
+
np.testing.assert_array_equal(got.indices, ref.indices)
|
|
424
|
+
assert got.max_error == ref.max_error
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|