plotsimplify 0.1.0__tar.gz → 0.3.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.
Files changed (23) hide show
  1. {plotsimplify-0.1.0 → plotsimplify-0.3.0}/CLAUDE.md +12 -5
  2. {plotsimplify-0.1.0 → plotsimplify-0.3.0}/Cargo.lock +1 -1
  3. {plotsimplify-0.1.0 → plotsimplify-0.3.0}/Cargo.toml +1 -1
  4. {plotsimplify-0.1.0 → plotsimplify-0.3.0}/PKG-INFO +22 -1
  5. {plotsimplify-0.1.0 → plotsimplify-0.3.0}/README.md +21 -0
  6. {plotsimplify-0.1.0 → plotsimplify-0.3.0}/pyproject.toml +1 -1
  7. plotsimplify-0.3.0/python/plotsimplify/__init__.py +260 -0
  8. {plotsimplify-0.1.0 → plotsimplify-0.3.0}/python/plotsimplify/_plotsimplify.pyi +2 -2
  9. {plotsimplify-0.1.0 → plotsimplify-0.3.0}/src/core.rs +195 -28
  10. {plotsimplify-0.1.0 → plotsimplify-0.3.0}/src/lib.rs +25 -6
  11. {plotsimplify-0.1.0 → plotsimplify-0.3.0}/tests/reference_kernel.py +44 -27
  12. plotsimplify-0.3.0/tests/test_simplify.py +532 -0
  13. plotsimplify-0.1.0/python/plotsimplify/__init__.py +0 -130
  14. plotsimplify-0.1.0/tests/test_simplify.py +0 -272
  15. {plotsimplify-0.1.0 → plotsimplify-0.3.0}/.github/workflows/ci.yml +0 -0
  16. {plotsimplify-0.1.0 → plotsimplify-0.3.0}/.github/workflows/release.yml +0 -0
  17. {plotsimplify-0.1.0 → plotsimplify-0.3.0}/.gitignore +0 -0
  18. {plotsimplify-0.1.0 → plotsimplify-0.3.0}/LICENSE +0 -0
  19. {plotsimplify-0.1.0 → plotsimplify-0.3.0}/benchmarks/bench.py +0 -0
  20. {plotsimplify-0.1.0 → plotsimplify-0.3.0}/benchmarks/results.txt +0 -0
  21. {plotsimplify-0.1.0 → plotsimplify-0.3.0}/docs/downsampling-report.md +0 -0
  22. {plotsimplify-0.1.0 → plotsimplify-0.3.0}/python/plotsimplify/py.typed +0 -0
  23. {plotsimplify-0.1.0 → plotsimplify-0.3.0}/tests/__init__.py +0 -0
@@ -9,17 +9,24 @@ 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. Takes k >= 1 y series
13
+ sharing x, each with its own validity mask. It keeps every series' run
14
+ ends and gap starts, then scores each segment by its worst error over
15
+ the series valid at both ends (those are valid throughout it).
13
16
  - The 8-lane distance loops (`argmax_cross_*`, `argmax_seg_*`) are compiled
14
17
  again with AVX-512/AVX2 `target_feature` and picked at runtime
15
18
  (`PLOTSIMPLIFY_BASELINE=1` / `PLOTSIMPLIFY_NO_AVX512=1` force fallbacks).
16
19
  - Rust tests compare against textbook recursive RDP.
17
20
  - `src/lib.rs`: thin numpy-array bindings (`scan`, `rdp_keep`, `simd_level`),
18
- GIL released.
19
- - `python/plotsimplify/__init__.py`: the `simplify()` API. It converts
21
+ GIL released. `rdp_keep` takes y and valid as C-contiguous `(k, n)` arrays.
22
+ - `python/plotsimplify/__init__.py`: `simplify()` (1-D y) and
23
+ `simplify_many()` (k series), both via `_simplify`. It converts
20
24
  datetime64/int x to float offsets from the first valid point (exact in
21
- int64 first), handles pixel scaling and gap markers, and calls the kernel
22
- via the module global `_rs`.
25
+ int64 first), handles pixel scaling (one shared or per-series y axis) and
26
+ the gap policy, and calls the kernel via the module global `_rs`.
27
+ `gaps="shared"` ANDs all series' finiteness into every row of `valid`;
28
+ `"per_series"` leaves each row to `scan`, then checks x is sorted over the
29
+ union.
23
30
  - `tests/reference_kernel.py`: pure-NumPy implementation of `scan`/`rdp_keep`.
24
31
  Tests monkeypatch `plotsimplify._rs` with it and require **bit-identical**
25
32
  results. A subprocess test does the same for the non-SIMD path.
@@ -96,7 +96,7 @@ checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
96
96
 
97
97
  [[package]]
98
98
  name = "plotsimplify"
99
- version = "0.1.0"
99
+ version = "0.3.0"
100
100
  dependencies = [
101
101
  "numpy",
102
102
  "pyo3",
@@ -1,6 +1,6 @@
1
1
  [package]
2
2
  name = "plotsimplify"
3
- version = "0.1.0"
3
+ version = "0.3.0"
4
4
  edition = "2021"
5
5
  description = "Error-bounded time series simplification (Ramer-Douglas-Peucker) for plotting, for Python (PyO3)"
6
6
  license = "MIT"
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: plotsimplify
3
- Version: 0.1.0
3
+ Version: 0.3.0
4
4
  Classifier: Development Status :: 3 - Alpha
5
5
  Classifier: Intended Audience :: Developers
6
6
  Classifier: Intended Audience :: Science/Research
@@ -93,6 +93,27 @@ 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
+ - **Several series, one x.** `simplify_many(t, ys)` picks one set of
97
+ indices from which every series is drawn within `eps`. Use it for bands
98
+ (`mu ± sigma`, min/max), stacked areas, OHLC, or a DataFrame's columns.
99
+ Simplifying each series separately and taking the union of the indices
100
+ doesn't give that bound: the extra points split the other series'
101
+ segments, and their error can reach `2 * eps`. The joint pass also keeps
102
+ fewer points.
103
+ - `ys` is a `(len(x), k)` array (one column per series), a list of
104
+ arrays, or a dict of arrays.
105
+ - `gaps="per_series"` (default): each series breaks at its own NaNs, and
106
+ a gap in one series costs the others nothing. `gaps="shared"`: a NaN in
107
+ any series is a gap in all of them, for drawings that need every series
108
+ at once, such as a filled band.
109
+ - `y_range` is one axis for all series (auto or `(lo, hi)`), or a list
110
+ with one `(lo, hi)` or `None` (auto) per series, for twin axes or
111
+ small multiples.
112
+
113
+ ```python
114
+ r = simplify_many(t, [lo, hi], width_px=1200, height_px=400, gaps="shared")
115
+ ax.fill_between(t[r.indices], lo[r.indices], hi[r.indices])
116
+ ```
96
117
  - **Gaps.** Points with NaN `y` or NaT `x` are dropped, except the first
97
118
  point of each gap. It's kept so the plot breaks the line instead of
98
119
  joining across the gap.
@@ -67,6 +67,27 @@ 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
+ - **Several series, one x.** `simplify_many(t, ys)` picks one set of
71
+ indices from which every series is drawn within `eps`. Use it for bands
72
+ (`mu ± sigma`, min/max), stacked areas, OHLC, or a DataFrame's columns.
73
+ Simplifying each series separately and taking the union of the indices
74
+ doesn't give that bound: the extra points split the other series'
75
+ segments, and their error can reach `2 * eps`. The joint pass also keeps
76
+ fewer points.
77
+ - `ys` is a `(len(x), k)` array (one column per series), a list of
78
+ arrays, or a dict of arrays.
79
+ - `gaps="per_series"` (default): each series breaks at its own NaNs, and
80
+ a gap in one series costs the others nothing. `gaps="shared"`: a NaN in
81
+ any series is a gap in all of them, for drawings that need every series
82
+ at once, such as a filled band.
83
+ - `y_range` is one axis for all series (auto or `(lo, hi)`), or a list
84
+ with one `(lo, hi)` or `None` (auto) per series, for twin axes or
85
+ small multiples.
86
+
87
+ ```python
88
+ r = simplify_many(t, [lo, hi], width_px=1200, height_px=400, gaps="shared")
89
+ ax.fill_between(t[r.indices], lo[r.indices], hi[r.indices])
90
+ ```
70
91
  - **Gaps.** Points with NaN `y` or NaT `x` are dropped, except the first
71
92
  point of each gap. It's kept so the plot breaks the line instead of
72
93
  joining across the gap.
@@ -4,7 +4,7 @@ build-backend = "maturin"
4
4
 
5
5
  [project]
6
6
  name = "plotsimplify"
7
- version = "0.1.0"
7
+ version = "0.3.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"
@@ -0,0 +1,260 @@
1
+ """plotsimplify: error-bounded time series simplification (RDP) for plotting.
2
+
3
+ The Ramer-Douglas-Peucker core runs in Rust (SIMD, GIL released); this module
4
+ handles input conversion (datetime64, ints, NaN/NaT gaps) and pixel scaling.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from collections.abc import Mapping
10
+ from typing import Literal, NamedTuple
11
+
12
+ import numpy as np
13
+
14
+ from . import _plotsimplify as _rs
15
+ from ._plotsimplify import __version__, simd_level
16
+
17
+ __all__ = ["Simplified", "simplify", "simplify_many", "simd_level", "__version__"]
18
+
19
+ Metric = Literal["vertical", "perpendicular"]
20
+ Gaps = Literal["per_series", "shared"]
21
+
22
+
23
+ class Simplified(NamedTuple):
24
+ """Result of `simplify` and `simplify_many`."""
25
+
26
+ indices: np.ndarray
27
+ """int64 indices into the original x/y, sorted."""
28
+ max_error: float
29
+ """Worst distance from a dropped point to the drawn line, in `eps` units.
30
+ For `simplify_many`, the worst over all series."""
31
+
32
+
33
+ def simplify(
34
+ x,
35
+ y,
36
+ *,
37
+ eps: float = 0.5,
38
+ width_px: float | None = None,
39
+ height_px: float | None = None,
40
+ y_range: tuple[float, float] | None = None,
41
+ metric: Metric = "vertical",
42
+ max_points: int | None = None,
43
+ ) -> Simplified:
44
+ """Pick the points of a time series needed to draw it within `eps` of the original.
45
+
46
+ x: sorted timestamps. numpy datetime64, integer or float.
47
+ y: 1-D values. NaN marks a gap. For several series that share x, use
48
+ `simplify_many`.
49
+
50
+ With `width_px` and `height_px`, x and y are scaled to the plot's pixel size
51
+ first, so `eps` is in pixels (0.5 means "every dropped point is within half
52
+ a pixel of the drawn line"). Without them, `eps` is in data units, which is
53
+ only meaningful with metric="vertical".
54
+
55
+ y_range: the plot's fixed y-axis limits, if it has them. Defaults to the data's min/max.
56
+
57
+ metric:
58
+ "vertical" distance measured straight up/down from the drawn line (default).
59
+ Guarantees max |y - drawn line| <= eps.
60
+ "perpendicular" Euclidean distance to the drawn segment.
61
+
62
+ Gaps: points with NaN y (or NaT x) are dropped except the first of each
63
+ gap, which is kept so the plot breaks the line instead of joining across it.
64
+
65
+ max_points: keep at most this many points. Segments are split largest error
66
+ first, so you get the best max_points-point approximation the greedy order
67
+ finds; check `max_error` for the bound you actually got. Every gap marker
68
+ and run endpoint is always kept, so data with very many gaps can exceed it.
69
+ """
70
+ y = np.ascontiguousarray(y, dtype=np.float64)
71
+ if y.ndim != 1:
72
+ raise ValueError("y must be 1-D; for several series sharing x, use simplify_many()")
73
+ if y_range is not None and not _is_pair(y_range):
74
+ raise ValueError("y_range must be a (lo, hi) pair")
75
+ return _simplify(x, y[None, :], eps, width_px, height_px, y_range, metric, max_points, "shared")
76
+
77
+
78
+ def simplify_many(
79
+ x,
80
+ ys,
81
+ *,
82
+ eps: float = 0.5,
83
+ width_px: float | None = None,
84
+ height_px: float | None = None,
85
+ y_range=None,
86
+ metric: Metric = "vertical",
87
+ max_points: int | None = None,
88
+ gaps: Gaps = "per_series",
89
+ ) -> Simplified:
90
+ """Pick one set of points from which every series in `ys` is drawn within `eps`.
91
+
92
+ Use this when several series share x and are sent or drawn together: the
93
+ edges of a band (mu ± sigma, min/max, a confidence interval), stacked
94
+ areas, OHLC, or the columns of a DataFrame. Every series gets the same
95
+ indices, and every series stays within `eps` of its own drawn line.
96
+ Simplifying each series with `simplify` and taking the union of the indices
97
+ doesn't give that: the extra points split the other series' segments, and
98
+ their error can reach 2 * eps.
99
+
100
+ ys: the series, as one of
101
+ - a 2-D array of shape (len(x), k), one column per series (like a
102
+ DataFrame's values, or matplotlib's `plot(x, Y)`),
103
+ - a list or tuple of k 1-D arrays,
104
+ - a mapping of name to 1-D array (the order of its values is used).
105
+
106
+ gaps: where each series breaks.
107
+ "per_series" each series has its own gaps (default). A NaN in one series
108
+ doesn't drop the others' data there.
109
+ "shared" a point is a gap in every series if any series is NaN
110
+ there, for drawings that need all series at once, such
111
+ as a filled band.
112
+
113
+ y_range (with width_px/height_px): the y-axis limits.
114
+ None one axis, auto-scaled to all the series.
115
+ (lo, hi) one axis with fixed limits.
116
+ [r_0, ..., r_{k-1}] an axis per series, such as twin axes or
117
+ small multiples: each entry is (lo, hi),
118
+ or None to auto-scale to that series.
119
+
120
+ The other arguments are as for `simplify`. If the series are in different
121
+ units and you work in data units (no width_px), scale them first, so that
122
+ one `eps` means the same thing for each: the result is only indices, so
123
+ pick from the unscaled arrays afterwards.
124
+ """
125
+ if gaps not in ("per_series", "shared"):
126
+ raise ValueError(f"gaps must be 'per_series' or 'shared', got {gaps!r}")
127
+ if np.ndim(x) != 1:
128
+ raise ValueError("x must be 1-D")
129
+ y = _as_rows(ys, len(x))
130
+ if y_range is not None and not _is_pair(y_range):
131
+ y_range = list(y_range)
132
+ if len(y_range) != len(y) or not all(r is None or _is_pair(r) for r in y_range):
133
+ raise ValueError("y_range must be (lo, hi), or one (lo, hi) or None per series in ys")
134
+ return _simplify(x, y, eps, width_px, height_px, y_range, metric, max_points, gaps)
135
+
136
+
137
+ def _simplify(x, y, eps, width_px, height_px, y_range, metric, max_points, gaps):
138
+ """y: (k, n) float64 rows. y_range: None, a pair, or a list of k (pair | None)."""
139
+ if metric not in ("vertical", "perpendicular"):
140
+ raise ValueError(f"metric must be 'vertical' or 'perpendicular', got {metric!r}")
141
+ if eps < 0:
142
+ raise ValueError("eps must be >= 0")
143
+ if (width_px is None) != (height_px is None):
144
+ raise ValueError("pass both width_px and height_px, or neither")
145
+
146
+ xf, xvalid = _prepare_x(x)
147
+ n = len(xf)
148
+ if y.shape[1] != n:
149
+ raise ValueError("x and y must have the same length")
150
+ k = len(y)
151
+
152
+ # One validity row per series. With shared gaps every row is the same mask,
153
+ # so the kernel sees one set of gaps.
154
+ valid = np.repeat(xvalid[None, :], k, axis=0)
155
+ if gaps == "shared" and k > 1:
156
+ valid &= np.isfinite(y).all(axis=0)
157
+ scans = [_rs.scan(xf, y[j], valid[j]) for j in range(k)]
158
+ if gaps == "shared" or k == 1:
159
+ sorted_ok, first, last = scans[0][:3]
160
+ else:
161
+ # Every series is drawn against the same x, so it must be sorted over
162
+ # the points any of them uses, not just within each series.
163
+ union = np.flatnonzero(valid.any(axis=0))
164
+ xu = xf[union]
165
+ sorted_ok = not bool(np.any(xu[1:] < xu[:-1]))
166
+ first, last = (int(union[0]), int(union[-1])) if len(union) else (-1, -1)
167
+ if not sorted_ok:
168
+ raise ValueError("x must be sorted (non-decreasing)")
169
+
170
+ vertical = metric == "vertical"
171
+ eps_k = float(eps)
172
+ err_scale = 1.0
173
+ if width_px is not None and first >= 0:
174
+ y0, y1 = _resolve_ranges(y_range, scans)
175
+ sy = [height_px / (b - a) if b > a else 1.0 for a, b in zip(y0, y1)]
176
+ if vertical and all(s == sy[0] for s in sy):
177
+ # Vertical distance in pixels = vertical distance in data units * sy,
178
+ # and x scaling doesn't affect it, so convert eps instead of the arrays.
179
+ eps_k = eps / sy[0]
180
+ err_scale = sy[0]
181
+ elif vertical:
182
+ y = y * np.array(sy)[:, None]
183
+ else:
184
+ x0, x1 = xf[first], xf[last]
185
+ sx = width_px / (x1 - x0) if x1 > x0 else 1.0
186
+ xf = (xf - x0) * sx
187
+ y = (y - np.array(y0)[:, None]) * np.array(sy)[:, None]
188
+
189
+ keep = np.zeros(n, dtype=np.bool_)
190
+ err = _rs.rdp_keep(xf, y, valid, eps_k, vertical, max_points or 0, keep)
191
+ return Simplified(np.flatnonzero(keep), float(err) * err_scale)
192
+
193
+
194
+ def _resolve_ranges(y_range, scans):
195
+ """Per-series (y0, y1) lists from y_range and each series' scanned min/max."""
196
+ k = len(scans)
197
+ if isinstance(y_range, list):
198
+ rs = [(s[3], s[4]) if r is None else r for r, s in zip(y_range, scans)]
199
+ return [float(r[0]) for r in rs], [float(r[1]) for r in rs]
200
+ if y_range is None:
201
+ y_range = (min(s[3] for s in scans), max(s[4] for s in scans))
202
+ return [y_range[0]] * k, [y_range[1]] * k
203
+
204
+
205
+ def _is_pair(r):
206
+ """A (lo, hi) pair of numbers, as opposed to a sequence of pairs."""
207
+ try:
208
+ return len(r) == 2 and all(v is not None and np.ndim(v) == 0 for v in r)
209
+ except TypeError:
210
+ return False
211
+
212
+
213
+ def _as_rows(ys, n):
214
+ """ys as a C-contiguous float64 array of shape (k, n): one row per series."""
215
+ if isinstance(ys, Mapping):
216
+ ys = list(ys.values())
217
+ if isinstance(ys, (list, tuple)):
218
+ cols = [np.asarray(c, dtype=np.float64) for c in ys]
219
+ if not cols:
220
+ raise ValueError("ys must hold at least one series")
221
+ if any(c.ndim != 1 for c in cols):
222
+ raise ValueError("each series in ys must be 1-D; for one series, use simplify()")
223
+ if any(len(c) != n for c in cols):
224
+ raise ValueError("each series in ys must have one value per x")
225
+ return np.stack(cols)
226
+ a = np.asarray(ys, dtype=np.float64)
227
+ if a.ndim != 2:
228
+ raise ValueError(
229
+ "ys must be a 2-D array of shape (len(x), k), or a list or mapping of 1-D arrays"
230
+ )
231
+ if a.shape[0] != n:
232
+ hint = " (got (k, len(x)); pass ys.T)" if a.shape[1] == n else ""
233
+ raise ValueError(f"a 2-D ys must have shape (len(x), k){hint}")
234
+ if a.shape[1] == 0:
235
+ raise ValueError("ys must hold at least one series")
236
+ return np.ascontiguousarray(a.T)
237
+
238
+
239
+ def _prepare_x(x):
240
+ """x as contiguous float64 plus its validity mask (NaT -> invalid)."""
241
+ x = np.asarray(x)
242
+ if x.ndim != 1:
243
+ raise ValueError("x must be 1-D")
244
+
245
+ if np.issubdtype(x.dtype, np.datetime64):
246
+ valid = ~np.isnat(x)
247
+ xi = x.view(np.int64)
248
+ elif np.issubdtype(x.dtype, np.integer):
249
+ valid = np.ones(len(x), dtype=np.bool_)
250
+ xi = x.astype(np.int64, copy=False)
251
+ else:
252
+ return np.ascontiguousarray(x, dtype=np.float64), np.ones(len(x), dtype=np.bool_)
253
+
254
+ # Subtract the first timestamp while still in int64: ns epochs (~1.7e18)
255
+ # don't fit float64's 53-bit mantissa, but offsets from the start do.
256
+ if len(xi) == 0:
257
+ return np.zeros(0, dtype=np.float64), valid
258
+ first = int(np.argmax(valid)) if valid.any() else 0
259
+ xf = (xi - xi[first]).astype(np.float64)
260
+ return xf, valid
@@ -9,8 +9,8 @@ def scan(
9
9
  ) -> tuple[bool, int, int, float, float]: ...
10
10
  def rdp_keep(
11
11
  x: npt.NDArray[np.float64],
12
- y: npt.NDArray[np.float64],
13
- valid: npt.NDArray[np.bool_],
12
+ y: npt.NDArray[np.float64], # (k, n), C-contiguous
13
+ valid: npt.NDArray[np.bool_], # (k, n), C-contiguous: one mask per series
14
14
  eps: float,
15
15
  vertical: bool,
16
16
  max_points: int,
@@ -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, each with its own validity mask,
9
+ //! and scores each segment by its worst error over the series drawn across
10
+ //! it, so a single 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,34 @@ 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 the series drawn across segment s-e: those valid at both
261
+ /// ends, which (see `rdp_keep`) are valid at every point in between. Returns the
262
+ /// largest distance and its point, or None if no series is drawn there. Ties go
263
+ /// to the lowest point index, then the first series.
264
+ #[inline(always)]
265
+ fn farthest_multi(
266
+ x: &[f64],
267
+ ys: &[&[f64]],
268
+ valids: &[&[bool]],
269
+ s: usize,
270
+ e: usize,
271
+ vertical: bool,
272
+ ) -> Option<(f64, usize)> {
273
+ // One call site, so `farthest` and its SIMD loops are inlined only once.
274
+ let mut best: Option<(f64, usize)> = None;
275
+ for (y, v) in ys.iter().zip(valids) {
276
+ if !(v[s] && v[e]) {
277
+ continue;
278
+ }
279
+ let (d, k) = farthest(x, y, s, e, vertical);
280
+ best = match best {
281
+ Some((dmax, imax)) if !(d > dmax || (d == dmax && k < imax)) => best,
282
+ _ => Some((d, k)),
283
+ };
284
+ }
285
+ best
286
+ }
287
+
257
288
  // ---------------------------------------------------------------- heap
258
289
 
259
290
  /// Max-heap of segments keyed on the distance of their farthest point.
@@ -322,44 +353,57 @@ pub fn simd_level() -> &'static str {
322
353
 
323
354
  // ---------------------------------------------------------------- kernels
324
355
 
356
+ /// RDP over one or more y series sharing `x`. `valids[j]` marks where series j
357
+ /// is drawn (finite, see `scan`); it is false in j's gaps.
358
+ ///
359
+ /// First every series' structural points are kept: the start and end of each
360
+ /// of its valid runs and the first point of each of its gaps. Between two
361
+ /// consecutive kept points a series is then either valid throughout or has no
362
+ /// valid point strictly inside (its gap would have put a kept point there), and
363
+ /// splitting a segment keeps that true. So a segment is scored only over the
364
+ /// series valid at both of its ends. With one series this is plain RDP over
365
+ /// each valid run.
325
366
  pub fn rdp_keep(
326
367
  x: &[f64],
327
- y: &[f64],
328
- valid: &[bool],
368
+ ys: &[&[f64]],
369
+ valids: &[&[bool]],
329
370
  eps: f64,
330
371
  vertical: bool,
331
372
  max_points: i64,
332
373
  keep: &mut [bool],
333
374
  ) -> f64 {
334
375
  let n = x.len();
376
+ assert!(!ys.is_empty() && ys.len() == valids.len());
377
+ assert!(ys.iter().all(|y| y.len() == n) && valids.iter().all(|v| v.len() == n));
335
378
  let mut heap = Heap(Vec::new());
336
379
  let mut count: i64 = 0;
337
380
 
338
- let mut i = 0;
339
- while i < n {
340
- if !valid[i] {
341
- keep[i] = true;
342
- count += 1;
343
- while i < n && !valid[i] {
344
- i += 1;
381
+ // Run starts and ends, and the first point of each gap. Point 0 is always
382
+ // one or the other. Interior points are done branch-free over three shifted
383
+ // slices, so the pass vectorises.
384
+ if n > 0 {
385
+ keep[0] = true;
386
+ }
387
+ if n >= 2 {
388
+ for v in valids {
389
+ keep[n - 1] |= v[n - 1] || v[n - 2];
390
+ let (prev, cur, next) = (&v[..n - 2], &v[1..n - 1], &v[2..]);
391
+ for (((kp, &p), &c), &nx) in keep[1..n - 1].iter_mut().zip(prev).zip(cur).zip(next) {
392
+ *kp |= (c & !(p & nx)) | (!c & p);
345
393
  }
346
- continue;
347
394
  }
348
- let s0 = i;
349
- while i < n && valid[i] {
350
- i += 1;
351
- }
352
- let e0 = i - 1;
353
- keep[s0] = true;
395
+ }
396
+ let mut prev: Option<usize> = None;
397
+ for i in (0..n).filter(|&i| keep[i]) {
354
398
  count += 1;
355
- if e0 != s0 {
356
- keep[e0] = true;
357
- count += 1;
358
- }
359
- if e0 - s0 >= 2 {
360
- let (d, k) = farthest(x, y, s0, e0, vertical);
361
- heap.push(Seg { d, s: s0, e: e0, k });
399
+ if let Some(a) = prev {
400
+ if i - a >= 2 {
401
+ if let Some((d, k)) = farthest_multi(x, ys, valids, a, i, vertical) {
402
+ heap.push(Seg { d, s: a, e: i, k });
403
+ }
404
+ }
362
405
  }
406
+ prev = Some(i);
363
407
  }
364
408
 
365
409
  while let Some(top) = heap.0.first() {
@@ -369,13 +413,16 @@ pub fn rdp_keep(
369
413
  let Seg { s, e, k, .. } = heap.pop();
370
414
  keep[k] = true;
371
415
  count += 1;
416
+ // Both halves are drawn by the same series as the whole, so neither is None.
372
417
  if k - s >= 2 {
373
- let (d, k1) = farthest(x, y, s, k, vertical);
374
- heap.push(Seg { d, s, e: k, k: k1 });
418
+ if let Some((d, k1)) = farthest_multi(x, ys, valids, s, k, vertical) {
419
+ heap.push(Seg { d, s, e: k, k: k1 });
420
+ }
375
421
  }
376
422
  if e - k >= 2 {
377
- let (d, k2) = farthest(x, y, k, e, vertical);
378
- heap.push(Seg { d, s: k, e, k: k2 });
423
+ if let Some((d, k2)) = farthest_multi(x, ys, valids, k, e, vertical) {
424
+ heap.push(Seg { d, s: k, e, k: k2 });
425
+ }
379
426
  }
380
427
  }
381
428
  0.0
@@ -554,7 +601,7 @@ mod tests {
554
601
  let mut valid = vec![true; x.len()];
555
602
  scan(x, y, &mut valid);
556
603
  let mut keep = vec![false; x.len()];
557
- let err = rdp_keep(x, y, &valid, eps, vertical, max_points, &mut keep);
604
+ let err = rdp_keep(x, &[y], &[&valid], eps, vertical, max_points, &mut keep);
558
605
  let idx = keep
559
606
  .iter()
560
607
  .enumerate()
@@ -653,4 +700,124 @@ mod tests {
653
700
  let (idx, _) = run(&x, &y, 0.5, true, 0);
654
701
  assert_eq!(idx, [0, 4, 5, 8, 14, 15, 16, 19]);
655
702
  }
703
+
704
+ /// Each series' validity comes from its own finiteness (per-series gaps).
705
+ fn run_multi(
706
+ x: &[f64],
707
+ ys: &[&[f64]],
708
+ eps: f64,
709
+ vertical: bool,
710
+ max_points: i64,
711
+ ) -> (Vec<usize>, f64) {
712
+ let valids: Vec<Vec<bool>> = ys
713
+ .iter()
714
+ .map(|y| {
715
+ let mut v = vec![true; x.len()];
716
+ scan(x, y, &mut v);
717
+ v
718
+ })
719
+ .collect();
720
+ let valids: Vec<&[bool]> = valids.iter().map(|v| v.as_slice()).collect();
721
+ let mut keep = vec![false; x.len()];
722
+ let err = rdp_keep(x, ys, &valids, eps, vertical, max_points, &mut keep);
723
+ let idx = (0..x.len()).filter(|&i| keep[i]).collect();
724
+ (idx, err)
725
+ }
726
+
727
+ fn worst(x: &[f64], y: &[f64], idx: &[usize], vertical: bool) -> f64 {
728
+ let mut w: f64 = 0.0;
729
+ for p in idx.windows(2) {
730
+ for k in p[0] + 1..p[1] {
731
+ w = w.max(if vertical {
732
+ vert(x, y, k, p[0], p[1])
733
+ } else {
734
+ seg(x, y, k, p[0], p[1])
735
+ });
736
+ }
737
+ }
738
+ w
739
+ }
740
+
741
+ #[test]
742
+ fn one_series_in_multi_is_unchanged() {
743
+ let (x, y) = series(3000, 4);
744
+ for vertical in [true, false] {
745
+ for (eps, budget) in [(0.5, 0), (0.0, 200)] {
746
+ assert_eq!(
747
+ run_multi(&x, &[&y, &y], eps, vertical, budget),
748
+ run(&x, &y, eps, vertical, budget)
749
+ );
750
+ }
751
+ }
752
+ }
753
+
754
+ #[test]
755
+ fn band_bounds_every_series() {
756
+ let (x, a) = series(5000, 5);
757
+ let (_, b) = series(5000, 6);
758
+ let lo: Vec<f64> = a.iter().zip(&b).map(|(a, b)| a - 3.0 - b.abs()).collect();
759
+ let hi: Vec<f64> = a.iter().zip(&b).map(|(a, b)| a + 3.0 + b.abs()).collect();
760
+ let ys: [&[f64]; 3] = [&lo, &a, &hi];
761
+ for vertical in [true, false] {
762
+ for (eps, budget) in [(0.5, 0), (0.0, 300)] {
763
+ let (idx, err) = run_multi(&x, &ys, eps, vertical, budget);
764
+ let w = ys
765
+ .iter()
766
+ .map(|y| worst(&x, y, &idx, vertical))
767
+ .fold(0.0, f64::max);
768
+ if budget == 0 {
769
+ assert!(w <= eps + 1e-9, "{w}");
770
+ } else {
771
+ assert_eq!(idx.len(), budget as usize);
772
+ }
773
+ assert!((w - err).abs() <= 1e-9 * w.max(1.0), "{w} vs {err}");
774
+ }
775
+ }
776
+ }
777
+
778
+ /// Worst error of one series over its own valid runs, which must start and end on kept points.
779
+ fn worst_runs(x: &[f64], y: &[f64], keep: &[usize], vertical: bool) -> f64 {
780
+ let mut w: f64 = 0.0;
781
+ let mut i = 0;
782
+ while i < y.len() {
783
+ if !y[i].is_finite() {
784
+ i += 1;
785
+ continue;
786
+ }
787
+ let s0 = i;
788
+ while i < y.len() && y[i].is_finite() {
789
+ i += 1;
790
+ }
791
+ let ks: Vec<usize> = keep.iter().copied().filter(|&k| k >= s0 && k < i).collect();
792
+ assert_eq!((ks[0], ks[ks.len() - 1]), (s0, i - 1), "run ends kept");
793
+ w = w.max(worst(x, y, &ks, vertical));
794
+ }
795
+ w
796
+ }
797
+
798
+ #[test]
799
+ fn per_series_gaps_bound_each_series_on_its_own_runs() {
800
+ let (x, a) = series(4000, 7);
801
+ let (_, mut b) = series(4000, 8);
802
+ let mut c = a.iter().map(|v| v * 2.0).collect::<Vec<_>>();
803
+ for v in &mut b[500..3500] {
804
+ *v = f64::NAN;
805
+ }
806
+ c[100] = f64::NAN;
807
+ c[3999] = f64::NAN;
808
+ let ys: [&[f64]; 3] = [&a, &b, &c];
809
+ for vertical in [true, false] {
810
+ let (idx, err) = run_multi(&x, &ys, 0.5, vertical, 0);
811
+ let w = ys
812
+ .iter()
813
+ .map(|y| worst_runs(&x, y, &idx, vertical))
814
+ .fold(0.0, f64::max);
815
+ assert!(w <= 0.5 + 1e-9, "{w}");
816
+ assert!((w - err).abs() <= 1e-9 * w.max(1.0), "{w} vs {err}");
817
+ // Gap markers of every series are kept.
818
+ for k in [100, 500, 3999] {
819
+ assert!(idx.contains(&k), "{k}");
820
+ }
821
+ }
822
+ }
656
823
  }