plotsimplify 0.2.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.
- {plotsimplify-0.2.0 → plotsimplify-0.3.0}/CLAUDE.md +12 -8
- {plotsimplify-0.2.0 → plotsimplify-0.3.0}/Cargo.lock +1 -1
- {plotsimplify-0.2.0 → plotsimplify-0.3.0}/Cargo.toml +1 -1
- {plotsimplify-0.2.0 → plotsimplify-0.3.0}/PKG-INFO +22 -8
- {plotsimplify-0.2.0 → plotsimplify-0.3.0}/README.md +21 -7
- {plotsimplify-0.2.0 → plotsimplify-0.3.0}/pyproject.toml +1 -1
- plotsimplify-0.3.0/python/plotsimplify/__init__.py +260 -0
- {plotsimplify-0.2.0 → plotsimplify-0.3.0}/python/plotsimplify/_plotsimplify.pyi +1 -1
- {plotsimplify-0.2.0 → plotsimplify-0.3.0}/src/core.rs +125 -45
- {plotsimplify-0.2.0 → plotsimplify-0.3.0}/src/lib.rs +19 -11
- {plotsimplify-0.2.0 → plotsimplify-0.3.0}/tests/reference_kernel.py +41 -38
- {plotsimplify-0.2.0 → plotsimplify-0.3.0}/tests/test_simplify.py +150 -42
- plotsimplify-0.2.0/python/plotsimplify/__init__.py +0 -162
- {plotsimplify-0.2.0 → plotsimplify-0.3.0}/.github/workflows/ci.yml +0 -0
- {plotsimplify-0.2.0 → plotsimplify-0.3.0}/.github/workflows/release.yml +0 -0
- {plotsimplify-0.2.0 → plotsimplify-0.3.0}/.gitignore +0 -0
- {plotsimplify-0.2.0 → plotsimplify-0.3.0}/LICENSE +0 -0
- {plotsimplify-0.2.0 → plotsimplify-0.3.0}/benchmarks/bench.py +0 -0
- {plotsimplify-0.2.0 → plotsimplify-0.3.0}/benchmarks/results.txt +0 -0
- {plotsimplify-0.2.0 → plotsimplify-0.3.0}/docs/downsampling-report.md +0 -0
- {plotsimplify-0.2.0 → plotsimplify-0.3.0}/python/plotsimplify/py.typed +0 -0
- {plotsimplify-0.2.0 → plotsimplify-0.3.0}/tests/__init__.py +0 -0
|
@@ -9,20 +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
|
|
13
|
-
|
|
14
|
-
|
|
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).
|
|
15
16
|
- The 8-lane distance loops (`argmax_cross_*`, `argmax_seg_*`) are compiled
|
|
16
17
|
again with AVX-512/AVX2 `target_feature` and picked at runtime
|
|
17
18
|
(`PLOTSIMPLIFY_BASELINE=1` / `PLOTSIMPLIFY_NO_AVX512=1` force fallbacks).
|
|
18
19
|
- Rust tests compare against textbook recursive RDP.
|
|
19
20
|
- `src/lib.rs`: thin numpy-array bindings (`scan`, `rdp_keep`, `simd_level`),
|
|
20
|
-
GIL released. `rdp_keep` takes y as
|
|
21
|
-
- `python/plotsimplify/__init__.py`:
|
|
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
|
|
22
24
|
datetime64/int x to float offsets from the first valid point (exact in
|
|
23
|
-
int64 first), handles pixel scaling
|
|
24
|
-
|
|
25
|
-
|
|
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.
|
|
26
30
|
- `tests/reference_kernel.py`: pure-NumPy implementation of `scan`/`rdp_keep`.
|
|
27
31
|
Tests monkeypatch `plotsimplify._rs` with it and require **bit-identical**
|
|
28
32
|
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.3.0
|
|
4
4
|
Classifier: Development Status :: 3 - Alpha
|
|
5
5
|
Classifier: Intended Audience :: Developers
|
|
6
6
|
Classifier: Intended Audience :: Science/Research
|
|
@@ -93,13 +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
|
-
- **
|
|
97
|
-
|
|
98
|
-
`
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
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
|
+
```
|
|
103
117
|
- **Gaps.** Points with NaN `y` or NaT `x` are dropped, except the first
|
|
104
118
|
point of each gap. It's kept so the plot breaks the line instead of
|
|
105
119
|
joining across the gap.
|
|
@@ -67,13 +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
|
-
- **
|
|
71
|
-
|
|
72
|
-
`
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
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
|
+
```
|
|
77
91
|
- **Gaps.** Points with NaN `y` or NaT `x` are dropped, except the first
|
|
78
92
|
point of each gap. It's kept so the plot breaks the line instead of
|
|
79
93
|
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.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
|
|
@@ -10,7 +10,7 @@ def scan(
|
|
|
10
10
|
def rdp_keep(
|
|
11
11
|
x: npt.NDArray[np.float64],
|
|
12
12
|
y: npt.NDArray[np.float64], # (k, n), C-contiguous
|
|
13
|
-
valid: npt.NDArray[np.bool_],
|
|
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,9 +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
|
|
9
|
-
//! scores each segment by its worst error over
|
|
10
|
-
//! set of kept points bounds every series.
|
|
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.
|
|
11
11
|
//!
|
|
12
12
|
//! The distance loops are written as 8 independent lanes so LLVM vectorises
|
|
13
13
|
//! them, and are compiled again for AVX-512/AVX2 and picked at runtime. FMA
|
|
@@ -257,20 +257,32 @@ fn farthest(x: &[f64], y: &[f64], s: usize, e: usize, vertical: bool) -> (f64, u
|
|
|
257
257
|
(d.max(0.0).sqrt(), s + 1 + k)
|
|
258
258
|
}
|
|
259
259
|
|
|
260
|
-
/// `farthest` over
|
|
261
|
-
///
|
|
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.
|
|
262
264
|
#[inline(always)]
|
|
263
|
-
fn farthest_multi(
|
|
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)> {
|
|
264
273
|
// One call site, so `farthest` and its SIMD loops are inlined only once.
|
|
265
|
-
let
|
|
266
|
-
for y in ys {
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
dmax = d;
|
|
270
|
-
imax = k;
|
|
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;
|
|
271
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
|
+
};
|
|
272
284
|
}
|
|
273
|
-
|
|
285
|
+
best
|
|
274
286
|
}
|
|
275
287
|
|
|
276
288
|
// ---------------------------------------------------------------- heap
|
|
@@ -341,47 +353,57 @@ pub fn simd_level() -> &'static str {
|
|
|
341
353
|
|
|
342
354
|
// ---------------------------------------------------------------- kernels
|
|
343
355
|
|
|
344
|
-
///
|
|
345
|
-
///
|
|
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.
|
|
346
366
|
pub fn rdp_keep(
|
|
347
367
|
x: &[f64],
|
|
348
368
|
ys: &[&[f64]],
|
|
349
|
-
|
|
369
|
+
valids: &[&[bool]],
|
|
350
370
|
eps: f64,
|
|
351
371
|
vertical: bool,
|
|
352
372
|
max_points: i64,
|
|
353
373
|
keep: &mut [bool],
|
|
354
374
|
) -> f64 {
|
|
355
375
|
let n = x.len();
|
|
356
|
-
assert!(!ys.is_empty() && ys.
|
|
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));
|
|
357
378
|
let mut heap = Heap(Vec::new());
|
|
358
379
|
let mut count: i64 = 0;
|
|
359
380
|
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
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);
|
|
367
393
|
}
|
|
368
|
-
continue;
|
|
369
394
|
}
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
}
|
|
374
|
-
let e0 = i - 1;
|
|
375
|
-
keep[s0] = true;
|
|
395
|
+
}
|
|
396
|
+
let mut prev: Option<usize> = None;
|
|
397
|
+
for i in (0..n).filter(|&i| keep[i]) {
|
|
376
398
|
count += 1;
|
|
377
|
-
if
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
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
|
+
}
|
|
384
405
|
}
|
|
406
|
+
prev = Some(i);
|
|
385
407
|
}
|
|
386
408
|
|
|
387
409
|
while let Some(top) = heap.0.first() {
|
|
@@ -391,13 +413,16 @@ pub fn rdp_keep(
|
|
|
391
413
|
let Seg { s, e, k, .. } = heap.pop();
|
|
392
414
|
keep[k] = true;
|
|
393
415
|
count += 1;
|
|
416
|
+
// Both halves are drawn by the same series as the whole, so neither is None.
|
|
394
417
|
if k - s >= 2 {
|
|
395
|
-
let (d, k1) = farthest_multi(x, ys, s, k, vertical)
|
|
396
|
-
|
|
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
|
+
}
|
|
397
421
|
}
|
|
398
422
|
if e - k >= 2 {
|
|
399
|
-
let (d, k2) = farthest_multi(x, ys, k, e, vertical)
|
|
400
|
-
|
|
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
|
+
}
|
|
401
426
|
}
|
|
402
427
|
}
|
|
403
428
|
0.0
|
|
@@ -576,7 +601,7 @@ mod tests {
|
|
|
576
601
|
let mut valid = vec![true; x.len()];
|
|
577
602
|
scan(x, y, &mut valid);
|
|
578
603
|
let mut keep = vec![false; x.len()];
|
|
579
|
-
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);
|
|
580
605
|
let idx = keep
|
|
581
606
|
.iter()
|
|
582
607
|
.enumerate()
|
|
@@ -676,6 +701,7 @@ mod tests {
|
|
|
676
701
|
assert_eq!(idx, [0, 4, 5, 8, 14, 15, 16, 19]);
|
|
677
702
|
}
|
|
678
703
|
|
|
704
|
+
/// Each series' validity comes from its own finiteness (per-series gaps).
|
|
679
705
|
fn run_multi(
|
|
680
706
|
x: &[f64],
|
|
681
707
|
ys: &[&[f64]],
|
|
@@ -683,9 +709,17 @@ mod tests {
|
|
|
683
709
|
vertical: bool,
|
|
684
710
|
max_points: i64,
|
|
685
711
|
) -> (Vec<usize>, f64) {
|
|
686
|
-
let
|
|
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();
|
|
687
721
|
let mut keep = vec![false; x.len()];
|
|
688
|
-
let err = rdp_keep(x, ys, &
|
|
722
|
+
let err = rdp_keep(x, ys, &valids, eps, vertical, max_points, &mut keep);
|
|
689
723
|
let idx = (0..x.len()).filter(|&i| keep[i]).collect();
|
|
690
724
|
(idx, err)
|
|
691
725
|
}
|
|
@@ -740,4 +774,50 @@ mod tests {
|
|
|
740
774
|
}
|
|
741
775
|
}
|
|
742
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
|
+
}
|
|
743
823
|
}
|
|
@@ -11,6 +11,15 @@ fn check_len(a: usize, b: usize) -> PyResult<()> {
|
|
|
11
11
|
Ok(())
|
|
12
12
|
}
|
|
13
13
|
|
|
14
|
+
/// The k rows of a flat C-contiguous (k, n) array.
|
|
15
|
+
fn rows<T>(a: &[T], k: usize, n: usize) -> Vec<&[T]> {
|
|
16
|
+
if n == 0 {
|
|
17
|
+
vec![&a[..0]; k]
|
|
18
|
+
} else {
|
|
19
|
+
a.chunks_exact(n).collect()
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
|
|
14
23
|
/// scan(x, y, valid) -> (sorted_ok, first, last, ymin, ymax); updates `valid` in place.
|
|
15
24
|
#[pyfunction]
|
|
16
25
|
fn scan<'py>(
|
|
@@ -28,35 +37,34 @@ fn scan<'py>(
|
|
|
28
37
|
|
|
29
38
|
/// rdp_keep(x, y, valid, eps, vertical, max_points, keep) -> max_error; updates `keep` in place.
|
|
30
39
|
///
|
|
31
|
-
/// `y`
|
|
40
|
+
/// `y` and `valid` are C-contiguous (k, n) arrays: k >= 1 series sharing `x`,
|
|
41
|
+
/// each with its own validity mask.
|
|
32
42
|
#[pyfunction]
|
|
33
43
|
#[allow(clippy::too_many_arguments)]
|
|
34
44
|
fn rdp_keep<'py>(
|
|
35
45
|
py: Python<'py>,
|
|
36
46
|
x: PyReadonlyArray1<'py, f64>,
|
|
37
47
|
y: PyReadonlyArray2<'py, f64>,
|
|
38
|
-
valid:
|
|
48
|
+
valid: PyReadonlyArray2<'py, bool>,
|
|
39
49
|
eps: f64,
|
|
40
50
|
vertical: bool,
|
|
41
51
|
max_points: i64,
|
|
42
52
|
mut keep: PyReadwriteArray1<'py, bool>,
|
|
43
53
|
) -> PyResult<f64> {
|
|
44
54
|
let (k, n) = (y.shape()[0], y.shape()[1]);
|
|
45
|
-
let (x, y, valid) = (x.as_slice()?, y.as_slice()?, valid.as_slice()?);
|
|
46
|
-
let keep = keep.as_slice_mut()?;
|
|
47
55
|
if k == 0 {
|
|
48
56
|
return Err(PyValueError::new_err("y must hold at least one series"));
|
|
49
57
|
}
|
|
58
|
+
if valid.shape() != y.shape() {
|
|
59
|
+
return Err(PyValueError::new_err("valid must have the same shape as y"));
|
|
60
|
+
}
|
|
61
|
+
let (x, y, valid) = (x.as_slice()?, y.as_slice()?, valid.as_slice()?);
|
|
62
|
+
let keep = keep.as_slice_mut()?;
|
|
50
63
|
check_len(x.len(), n)?;
|
|
51
|
-
check_len(x.len(), valid.len())?;
|
|
52
64
|
check_len(x.len(), keep.len())?;
|
|
53
|
-
let ys
|
|
54
|
-
vec![&[]; k]
|
|
55
|
-
} else {
|
|
56
|
-
y.chunks_exact(n).collect()
|
|
57
|
-
};
|
|
65
|
+
let (ys, valids) = (rows(y, k, n), rows(valid, k, n));
|
|
58
66
|
// Release the GIL: other Python threads keep running while we crunch.
|
|
59
|
-
Ok(py.detach(|| core::rdp_keep(x, &ys,
|
|
67
|
+
Ok(py.detach(|| core::rdp_keep(x, &ys, &valids, eps, vertical, max_points, keep)))
|
|
60
68
|
}
|
|
61
69
|
|
|
62
70
|
/// Which SIMD path the distance loops use on this CPU: "avx512", "avx2" or "baseline".
|
|
@@ -61,51 +61,55 @@ 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
|
|
66
|
-
point index, then the first series."""
|
|
67
|
-
|
|
68
|
-
for y in ys
|
|
64
|
+
def _farthest_multi(x, ys, valid, s, e, vertical):
|
|
65
|
+
"""`_farthest` over the rows of ys valid at both s and e: the largest distance,
|
|
66
|
+
ties to the lowest point index, then the first series. None if no row is."""
|
|
67
|
+
best = None
|
|
68
|
+
for y, v in zip(ys, valid):
|
|
69
|
+
if not (v[s] and v[e]):
|
|
70
|
+
continue
|
|
69
71
|
d, k = _farthest(x, y, s, e, vertical)
|
|
70
|
-
if d >
|
|
71
|
-
|
|
72
|
-
return
|
|
72
|
+
if best is None or d > best[0] or (d == best[0] and k < best[1]):
|
|
73
|
+
best = (d, k)
|
|
74
|
+
return best
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def _structural(v):
|
|
78
|
+
"""Run starts, run ends and the first point of each gap of one mask."""
|
|
79
|
+
n = len(v)
|
|
80
|
+
prev = np.concatenate(([False], v[:-1]))
|
|
81
|
+
nxt = np.concatenate((v[1:], [False]))
|
|
82
|
+
first = np.zeros(n, dtype=np.bool_)
|
|
83
|
+
first[:1] = True
|
|
84
|
+
return np.where(v, ~prev | ~nxt, first | prev)
|
|
73
85
|
|
|
74
86
|
|
|
75
87
|
def rdp_keep(x, y, valid, eps, vertical, max_points, keep):
|
|
76
88
|
"""Mark points to keep (in place); return the max error of the result.
|
|
77
89
|
|
|
78
|
-
y
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
are split at their farthest point,
|
|
83
|
-
largest remaining distance is <= eps or
|
|
90
|
+
y and valid have shape (k, n): one or more series sharing x, each with its
|
|
91
|
+
own validity mask. Every series' run endpoints and the first point of each
|
|
92
|
+
of its gaps are kept. Between consecutive kept points a series is then
|
|
93
|
+
valid throughout or not drawn at all, so each segment is scored over the
|
|
94
|
+
series valid at both its ends. Segments are split at their farthest point,
|
|
95
|
+
largest distance first, until the largest remaining distance is <= eps or
|
|
96
|
+
`max_points` (if > 0) is reached.
|
|
84
97
|
"""
|
|
85
98
|
n = len(x)
|
|
86
99
|
if n == 0:
|
|
87
100
|
return 0.0
|
|
88
101
|
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
run_ends = np.flatnonzero(edges == -1) - 1
|
|
94
|
-
gap_starts = np.flatnonzero(edges[:-1] == -1) # index right after a run ends
|
|
95
|
-
if not valid[0]:
|
|
96
|
-
gap_starts = np.concatenate(([0], gap_starts))
|
|
97
|
-
gap_starts = gap_starts[gap_starts < n]
|
|
98
|
-
|
|
99
|
-
keep[gap_starts] = True
|
|
100
|
-
keep[run_starts] = True
|
|
101
|
-
keep[run_ends] = True
|
|
102
|
-
count = int(np.count_nonzero(keep))
|
|
102
|
+
for v in valid:
|
|
103
|
+
keep |= _structural(v)
|
|
104
|
+
kept = np.flatnonzero(keep).tolist()
|
|
105
|
+
count = len(kept)
|
|
103
106
|
|
|
104
107
|
heap = []
|
|
105
|
-
for
|
|
106
|
-
if
|
|
107
|
-
|
|
108
|
-
|
|
108
|
+
for a, b in zip(kept, kept[1:]):
|
|
109
|
+
if b - a >= 2:
|
|
110
|
+
r = _farthest_multi(x, y, valid, a, b, vertical)
|
|
111
|
+
if r is not None:
|
|
112
|
+
heap.append((-r[0], a, b, r[1]))
|
|
109
113
|
heapq.heapify(heap)
|
|
110
114
|
|
|
111
115
|
while heap:
|
|
@@ -115,10 +119,9 @@ def rdp_keep(x, y, valid, eps, vertical, max_points, keep):
|
|
|
115
119
|
_, s, e, k = heapq.heappop(heap)
|
|
116
120
|
keep[k] = True
|
|
117
121
|
count += 1
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
heapq.heappush(heap, (-d2, k, e, k2))
|
|
122
|
+
for a, b in ((s, k), (k, e)):
|
|
123
|
+
if b - a >= 2:
|
|
124
|
+
r = _farthest_multi(x, y, valid, a, b, vertical)
|
|
125
|
+
if r is not None:
|
|
126
|
+
heapq.heappush(heap, (-r[0], a, b, r[1]))
|
|
124
127
|
return 0.0
|
|
@@ -8,7 +8,7 @@ import numpy as np
|
|
|
8
8
|
import pytest
|
|
9
9
|
|
|
10
10
|
import plotsimplify
|
|
11
|
-
from plotsimplify import simplify
|
|
11
|
+
from plotsimplify import simplify, simplify_many
|
|
12
12
|
|
|
13
13
|
from . import reference_kernel
|
|
14
14
|
|
|
@@ -281,13 +281,18 @@ def gappy_band():
|
|
|
281
281
|
return x, ys
|
|
282
282
|
|
|
283
283
|
|
|
284
|
+
MANY_CASES = [dict(kw, gaps=g) for kw in CASES for g in ("per_series", "shared")] + [
|
|
285
|
+
dict(eps=0.2, width_px=900, height_px=300, y_range=[None, (-50.0, 50.0), None]),
|
|
286
|
+
]
|
|
287
|
+
|
|
288
|
+
|
|
284
289
|
def simd_check_outputs():
|
|
285
290
|
"""Results compared between the SIMD and forced-baseline builds."""
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
+
metrics = ("vertical", "perpendicular")
|
|
292
|
+
x, y = gappy_series()
|
|
293
|
+
out = [simplify(x, y, metric=m, **kw) for m in metrics for kw in CASES]
|
|
294
|
+
x, ys = gappy_band()
|
|
295
|
+
out += [simplify_many(x, ys, metric=m, **kw) for m in metrics for kw in MANY_CASES]
|
|
291
296
|
return out
|
|
292
297
|
|
|
293
298
|
|
|
@@ -323,7 +328,7 @@ def test_baseline_simd_path_is_identical(tmp_path):
|
|
|
323
328
|
np.testing.assert_array_equal(np.load(tmp_path / "err.npy"), [r.max_error for r in out])
|
|
324
329
|
|
|
325
330
|
|
|
326
|
-
# ---------- several y series
|
|
331
|
+
# ---------- several y series: simplify_many ----------
|
|
327
332
|
|
|
328
333
|
|
|
329
334
|
def band(n, seed):
|
|
@@ -334,25 +339,42 @@ def band(n, seed):
|
|
|
334
339
|
return x, mu - s, mu + s
|
|
335
340
|
|
|
336
341
|
|
|
337
|
-
def
|
|
342
|
+
def test_union_of_separate_passes_breaks_bound_but_joint_does_not():
|
|
338
343
|
# The repro from issue #2: the union of per-series index sets can put a
|
|
339
344
|
# dropped point up to 2 * eps from the drawn line; the joint pass can't.
|
|
340
345
|
x, lo, hi = band(5000, 0)
|
|
341
346
|
k = np.union1d(simplify(x, lo, eps=0.5).indices, simplify(x, hi, eps=0.5).indices)
|
|
342
347
|
assert max(max_error(x, y, k, vert_dist) for y in (lo, hi)) > 0.5
|
|
343
348
|
|
|
344
|
-
r =
|
|
349
|
+
r = simplify_many(x, [lo, hi], eps=0.5)
|
|
345
350
|
assert max(max_error(x, y, r.indices, vert_dist) for y in (lo, hi)) <= 0.5
|
|
346
351
|
assert len(r.indices) <= len(k)
|
|
347
352
|
|
|
348
353
|
|
|
354
|
+
def gappy_trio(n=4000, seed=1):
|
|
355
|
+
x, lo, hi = band(n, seed)
|
|
356
|
+
mid = (lo + hi) / 2
|
|
357
|
+
lo[300:340] = np.nan
|
|
358
|
+
mid[2000:3500] = np.nan
|
|
359
|
+
hi[3999] = np.nan
|
|
360
|
+
return x, [lo, mid, hi]
|
|
361
|
+
|
|
362
|
+
|
|
363
|
+
def shared_mask(ys):
|
|
364
|
+
bad = ~np.all([np.isfinite(y) for y in ys], axis=0)
|
|
365
|
+
return [np.where(bad, np.nan, y) for y in ys]
|
|
366
|
+
|
|
367
|
+
|
|
368
|
+
@pytest.mark.parametrize("gaps", ["per_series", "shared"])
|
|
349
369
|
@pytest.mark.parametrize("metric,dist", [("vertical", vert_dist), ("perpendicular", seg_dist)])
|
|
350
370
|
@pytest.mark.parametrize("kw", [dict(eps=0.5), dict(eps=0.0, max_points=300)])
|
|
351
|
-
def
|
|
352
|
-
x,
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
371
|
+
def test_bound_and_reported_error_over_all_series(gaps, metric, dist, kw):
|
|
372
|
+
x, ys = gappy_trio()
|
|
373
|
+
r = simplify_many(x, ys, metric=metric, gaps=gaps, **kw)
|
|
374
|
+
# `max_error` checks each series over its own valid runs (and that their
|
|
375
|
+
# endpoints were kept); with shared gaps, a run ends where any series breaks.
|
|
376
|
+
drawn = ys if gaps == "per_series" else shared_mask(ys)
|
|
377
|
+
worst = max(max_error(x, y, r.indices, dist) for y in drawn)
|
|
356
378
|
assert r.max_error == pytest.approx(worst, abs=1e-9)
|
|
357
379
|
if "max_points" in kw:
|
|
358
380
|
assert len(r.indices) == kw["max_points"]
|
|
@@ -360,11 +382,38 @@ def test_band_reported_error_is_worst_over_series(metric, dist, kw):
|
|
|
360
382
|
assert worst <= kw["eps"] + 1e-9
|
|
361
383
|
|
|
362
384
|
|
|
363
|
-
def
|
|
385
|
+
def test_per_series_gaps_dont_drop_other_series_data():
|
|
386
|
+
x = np.arange(1000.0)
|
|
387
|
+
a = np.sin(x / 50)
|
|
388
|
+
b = a + 1
|
|
389
|
+
b[100:900] = np.nan
|
|
390
|
+
r = simplify_many(x, [a, b], eps=0.01)
|
|
391
|
+
# `a` is bounded over its whole range, just as on its own.
|
|
392
|
+
assert max_error(x, a, r.indices, vert_dist) <= 0.01
|
|
393
|
+
assert np.count_nonzero((r.indices > 100) & (r.indices < 900)) > 10
|
|
394
|
+
# With shared gaps, a's points under b's gap are gone: only the marker is left.
|
|
395
|
+
shared = simplify_many(x, [a, b], eps=0.01, gaps="shared").indices
|
|
396
|
+
assert not np.any((shared > 100) & (shared < 900))
|
|
397
|
+
|
|
398
|
+
|
|
399
|
+
def test_gap_markers():
|
|
400
|
+
x = np.arange(20.0)
|
|
401
|
+
lo, hi = np.zeros(20), np.ones(20)
|
|
402
|
+
lo[5:8] = np.nan
|
|
403
|
+
hi[7:9] = np.nan
|
|
404
|
+
hi[15] = np.nan
|
|
405
|
+
# Each series' run ends and gap starts.
|
|
406
|
+
assert simplify_many(x, [lo, hi]).indices.tolist() == [0, 4, 5, 6, 7, 8, 9, 14, 15, 16, 19]
|
|
407
|
+
# One combined set of gaps.
|
|
408
|
+
shared = simplify_many(x, [lo, hi], gaps="shared").indices.tolist()
|
|
409
|
+
assert shared == [0, 4, 5, 9, 14, 15, 16, 19]
|
|
410
|
+
|
|
411
|
+
|
|
412
|
+
def test_error_bound_in_pixels_shared_axis():
|
|
364
413
|
x, lo, hi = band(3000, 2)
|
|
365
414
|
w, h, eps = 800, 300, 0.5
|
|
366
415
|
for metric, dist in [("vertical", vert_dist), ("perpendicular", seg_dist)]:
|
|
367
|
-
idx =
|
|
416
|
+
idx = simplify_many(x, [lo, hi], eps=eps, width_px=w, height_px=h, metric=metric).indices
|
|
368
417
|
# The default y range spans all series.
|
|
369
418
|
y0, y1 = lo.min(), hi.max()
|
|
370
419
|
px = (x - x[0]) * w / (x[-1] - x[0])
|
|
@@ -372,53 +421,112 @@ def test_band_error_bound_in_pixels():
|
|
|
372
421
|
assert max_error(px, (y - y0) * h / (y1 - y0), idx, dist) <= eps + 1e-9
|
|
373
422
|
|
|
374
423
|
|
|
375
|
-
def
|
|
424
|
+
def test_error_bound_in_pixels_axis_per_series():
|
|
425
|
+
# Twin axes: temperature in degrees and pressure in pascals.
|
|
426
|
+
x, a = random_series(3000, 12)
|
|
427
|
+
_, b = random_series(3000, 13)
|
|
428
|
+
b = 101_325 + 1000 * b
|
|
429
|
+
w, h, eps = 800, 300, 0.5
|
|
430
|
+
px = (x - x[0]) * w / (x[-1] - x[0])
|
|
431
|
+
for y_range in ([None, None], [(a.min() - 5, a.max() + 5), None]):
|
|
432
|
+
for metric, dist in [("vertical", vert_dist), ("perpendicular", seg_dist)]:
|
|
433
|
+
r = simplify_many(
|
|
434
|
+
x, [a, b], eps=eps, width_px=w, height_px=h, metric=metric, y_range=y_range
|
|
435
|
+
)
|
|
436
|
+
worst = 0.0
|
|
437
|
+
for y, rng in zip((a, b), y_range):
|
|
438
|
+
y0, y1 = rng or (y.min(), y.max())
|
|
439
|
+
worst = max(worst, max_error(px, (y - y0) * h / (y1 - y0), r.indices, dist))
|
|
440
|
+
assert worst <= eps + 1e-9
|
|
441
|
+
assert r.max_error == pytest.approx(worst, abs=1e-9)
|
|
442
|
+
# On one shared axis, the pascal series' range squashes `a`, so drawn on its
|
|
443
|
+
# own axis it is many pixels off.
|
|
444
|
+
shared = simplify_many(x, [a, b], eps=eps, width_px=w, height_px=h).indices
|
|
445
|
+
assert max_error(px, (a - a.min()) * h / (a.max() - a.min()), shared, vert_dist) > 5
|
|
446
|
+
|
|
447
|
+
|
|
448
|
+
def test_input_forms_agree():
|
|
376
449
|
x, lo, hi = band(2000, 3)
|
|
377
|
-
a =
|
|
378
|
-
for
|
|
379
|
-
|
|
450
|
+
a = simplify_many(x, np.column_stack([lo, hi]))
|
|
451
|
+
for ys in (
|
|
452
|
+
[lo, hi],
|
|
453
|
+
(lo, hi),
|
|
454
|
+
[lo.tolist(), hi.tolist()],
|
|
455
|
+
{"lo": lo, "hi": hi},
|
|
456
|
+
np.asfortranarray(np.c_[lo, hi]),
|
|
457
|
+
np.c_[lo, np.zeros_like(lo), hi][:, ::2],
|
|
458
|
+
):
|
|
459
|
+
b = simplify_many(x, ys)
|
|
380
460
|
np.testing.assert_array_equal(a.indices, b.indices)
|
|
381
461
|
assert a.max_error == b.max_error
|
|
382
462
|
|
|
383
463
|
|
|
384
|
-
|
|
385
|
-
|
|
464
|
+
@pytest.mark.parametrize("gaps", ["per_series", "shared"])
|
|
465
|
+
def test_one_series_matches_simplify(gaps):
|
|
466
|
+
x, y = gappy_series()
|
|
386
467
|
for metric in ("vertical", "perpendicular"):
|
|
387
468
|
for kw in CASES:
|
|
388
469
|
a = simplify(x, y, metric=metric, **kw)
|
|
389
|
-
for
|
|
390
|
-
b =
|
|
470
|
+
for ys in (y[:, None], [y], [y, y]):
|
|
471
|
+
b = simplify_many(x, ys, metric=metric, gaps=gaps, **kw)
|
|
391
472
|
np.testing.assert_array_equal(a.indices, b.indices)
|
|
392
473
|
assert a.max_error == b.max_error
|
|
393
474
|
|
|
394
475
|
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
476
|
+
@pytest.mark.parametrize("gaps", ["per_series", "shared"])
|
|
477
|
+
@pytest.mark.parametrize("kw", [{}, dict(width_px=800, height_px=300, max_points=5)])
|
|
478
|
+
def test_many_empty_and_all_invalid(gaps, kw):
|
|
479
|
+
e = simplify_many(np.array([], dtype="datetime64[ns]"), np.zeros((0, 2)), gaps=gaps, **kw)
|
|
480
|
+
assert e.indices.tolist() == [] and e.max_error == 0.0
|
|
481
|
+
nan = np.full(5, np.nan)
|
|
482
|
+
r = simplify_many(np.arange(5), [nan, nan], gaps=gaps, **kw)
|
|
483
|
+
assert r.indices.tolist() == [0] and r.max_error == 0.0
|
|
484
|
+
|
|
485
|
+
|
|
486
|
+
def test_per_series_x_must_be_sorted_across_series():
|
|
487
|
+
# Each series alone is sorted, but together they go back in time.
|
|
488
|
+
x = np.array([0.0, 2.0, 1.0, 3.0])
|
|
489
|
+
a = np.array([0.0, 1.0, np.nan, 2.0])
|
|
490
|
+
b = np.array([0.0, np.nan, 1.0, 2.0])
|
|
491
|
+
simplify(x, a)
|
|
492
|
+
simplify(x, b)
|
|
493
|
+
with pytest.raises(ValueError, match="sorted"):
|
|
494
|
+
simplify_many(x, [a, b])
|
|
495
|
+
simplify_many(x, [a, b], gaps="shared") # index 1 and 2 are gaps in both
|
|
402
496
|
|
|
403
497
|
|
|
404
|
-
def
|
|
498
|
+
def test_many_bad_args():
|
|
405
499
|
x = np.arange(5.0)
|
|
406
|
-
with pytest.raises(ValueError, match="same length"):
|
|
407
|
-
simplify(x, [np.zeros(5), np.zeros(4)])
|
|
408
500
|
with pytest.raises(ValueError, match="one value per x"):
|
|
409
|
-
|
|
501
|
+
simplify_many(x, [np.zeros(5), np.zeros(4)])
|
|
502
|
+
with pytest.raises(ValueError, match="pass ys.T"):
|
|
503
|
+
simplify_many(x, np.zeros((2, 5)))
|
|
504
|
+
with pytest.raises(ValueError, match=r"shape \(len\(x\), k\)"):
|
|
505
|
+
simplify_many(x, np.zeros((4, 2)))
|
|
410
506
|
with pytest.raises(ValueError, match="at least one"):
|
|
411
|
-
|
|
412
|
-
with pytest.raises(ValueError):
|
|
413
|
-
|
|
507
|
+
simplify_many(x, np.zeros((5, 0)))
|
|
508
|
+
with pytest.raises(ValueError, match="at least one"):
|
|
509
|
+
simplify_many(x, [])
|
|
510
|
+
with pytest.raises(ValueError, match="use simplify"):
|
|
511
|
+
simplify_many(x, [0.0, 1.0, 2.0, 3.0, 4.0])
|
|
512
|
+
with pytest.raises(ValueError, match="2-D"):
|
|
513
|
+
simplify_many(x, np.zeros(5))
|
|
514
|
+
with pytest.raises(ValueError, match="gaps"):
|
|
515
|
+
simplify_many(x, [x], gaps="any")
|
|
516
|
+
with pytest.raises(ValueError, match="y_range"):
|
|
517
|
+
simplify_many(x, [x, x], y_range=[(0, 1)], width_px=10, height_px=10)
|
|
518
|
+
with pytest.raises(ValueError, match="use simplify_many"):
|
|
519
|
+
simplify(x, np.zeros((5, 2)))
|
|
520
|
+
with pytest.raises(ValueError, match="y_range"):
|
|
521
|
+
simplify(x, x, y_range=[(0, 1), (0, 1)], width_px=10, height_px=10)
|
|
414
522
|
|
|
415
523
|
|
|
416
524
|
@pytest.mark.parametrize("metric", ["vertical", "perpendicular"])
|
|
417
|
-
@pytest.mark.parametrize("kw",
|
|
418
|
-
def
|
|
525
|
+
@pytest.mark.parametrize("kw", MANY_CASES)
|
|
526
|
+
def test_many_identical_to_numpy_reference(metric, kw, monkeypatch):
|
|
419
527
|
x, ys = gappy_band()
|
|
420
|
-
got =
|
|
528
|
+
got = simplify_many(x, ys, metric=metric, **kw)
|
|
421
529
|
monkeypatch.setattr(plotsimplify, "_rs", reference_kernel)
|
|
422
|
-
ref =
|
|
530
|
+
ref = simplify_many(x, ys, metric=metric, **kw)
|
|
423
531
|
np.testing.assert_array_equal(got.indices, ref.indices)
|
|
424
532
|
assert got.max_error == ref.max_error
|
|
@@ -1,162 +0,0 @@
|
|
|
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 typing import Literal, NamedTuple
|
|
10
|
-
|
|
11
|
-
import numpy as np
|
|
12
|
-
|
|
13
|
-
from . import _plotsimplify as _rs
|
|
14
|
-
from ._plotsimplify import __version__, simd_level
|
|
15
|
-
|
|
16
|
-
__all__ = ["Simplified", "simplify", "simd_level", "__version__"]
|
|
17
|
-
|
|
18
|
-
Metric = Literal["vertical", "perpendicular"]
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
class Simplified(NamedTuple):
|
|
22
|
-
"""Result of `simplify`."""
|
|
23
|
-
|
|
24
|
-
indices: np.ndarray
|
|
25
|
-
"""int64 indices into the original x/y, sorted."""
|
|
26
|
-
max_error: float
|
|
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."""
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
def simplify(
|
|
32
|
-
x,
|
|
33
|
-
y,
|
|
34
|
-
*,
|
|
35
|
-
eps: float = 0.5,
|
|
36
|
-
width_px: float | None = None,
|
|
37
|
-
height_px: float | None = None,
|
|
38
|
-
y_range: tuple[float, float] | None = None,
|
|
39
|
-
metric: Metric = "vertical",
|
|
40
|
-
max_points: int | None = None,
|
|
41
|
-
) -> Simplified:
|
|
42
|
-
"""Pick the points of a time series needed to draw it within `eps` of the original.
|
|
43
|
-
|
|
44
|
-
x: sorted timestamps. numpy datetime64, integer or float.
|
|
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.
|
|
51
|
-
|
|
52
|
-
With `width_px` and `height_px`, x and y are scaled to the plot's pixel size
|
|
53
|
-
first, so `eps` is in pixels (0.5 means "every dropped point is within half
|
|
54
|
-
a pixel of the drawn line"). Without them, `eps` is in data units, which is
|
|
55
|
-
only meaningful with metric="vertical".
|
|
56
|
-
|
|
57
|
-
y_range: the plot's fixed y-axis limits, if it has them. Defaults to the data's min/max.
|
|
58
|
-
|
|
59
|
-
metric:
|
|
60
|
-
"vertical" distance measured straight up/down from the drawn line (default).
|
|
61
|
-
Guarantees max |y - drawn line| <= eps.
|
|
62
|
-
"perpendicular" Euclidean distance to the drawn segment.
|
|
63
|
-
|
|
64
|
-
Gaps: points with NaN y (or NaT x) are dropped except the first of each
|
|
65
|
-
gap, which is kept so the plot breaks the line instead of joining across it.
|
|
66
|
-
|
|
67
|
-
max_points: keep at most this many points. Segments are split largest error
|
|
68
|
-
first, so you get the best max_points-point approximation the greedy order
|
|
69
|
-
finds; check `max_error` for the bound you actually got. Every gap marker
|
|
70
|
-
and run endpoint is always kept, so data with very many gaps can exceed it.
|
|
71
|
-
"""
|
|
72
|
-
if metric not in ("vertical", "perpendicular"):
|
|
73
|
-
raise ValueError(f"metric must be 'vertical' or 'perpendicular', got {metric!r}")
|
|
74
|
-
if eps < 0:
|
|
75
|
-
raise ValueError("eps must be >= 0")
|
|
76
|
-
if (width_px is None) != (height_px is None):
|
|
77
|
-
raise ValueError("pass both width_px and height_px, or neither")
|
|
78
|
-
|
|
79
|
-
xf, yf, valid = _prepare(x, y)
|
|
80
|
-
n = len(xf)
|
|
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)
|
|
89
|
-
if not sorted_ok:
|
|
90
|
-
raise ValueError("x must be sorted (non-decreasing)")
|
|
91
|
-
if first < 0 or n <= 2:
|
|
92
|
-
return Simplified(np.flatnonzero(valid | _gap_starts(valid)), 0.0)
|
|
93
|
-
|
|
94
|
-
vertical = metric == "vertical"
|
|
95
|
-
eps_k = float(eps)
|
|
96
|
-
if width_px is not None:
|
|
97
|
-
y0, y1 = (ymin, ymax) if y_range is None else y_range
|
|
98
|
-
sy = height_px / (y1 - y0) if y1 > y0 else 1.0
|
|
99
|
-
if vertical:
|
|
100
|
-
# Vertical distance in pixels = vertical distance in data units * sy,
|
|
101
|
-
# and x scaling doesn't affect it, so convert eps instead of the arrays.
|
|
102
|
-
eps_k = eps / sy
|
|
103
|
-
else:
|
|
104
|
-
x0, x1 = xf[first], xf[last]
|
|
105
|
-
sx = width_px / (x1 - x0) if x1 > x0 else 1.0
|
|
106
|
-
xf = (xf - x0) * sx
|
|
107
|
-
yf = (yf - y0) * sy
|
|
108
|
-
|
|
109
|
-
keep = np.zeros(n, dtype=np.bool_)
|
|
110
|
-
err = _rs.rdp_keep(xf, yf, valid, eps_k, vertical, max_points or 0, keep)
|
|
111
|
-
if width_px is not None and vertical:
|
|
112
|
-
err *= sy
|
|
113
|
-
return Simplified(np.flatnonzero(keep), float(err))
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
def _gap_starts(valid):
|
|
117
|
-
if len(valid) == 0:
|
|
118
|
-
return valid
|
|
119
|
-
prev = np.concatenate(([True], valid[:-1]))
|
|
120
|
-
return ~valid & prev
|
|
121
|
-
|
|
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
|
-
|
|
140
|
-
def _prepare(x, y):
|
|
141
|
-
"""Convert inputs to contiguous float64 x, (k, n) y and an initial validity mask (NaT -> invalid)."""
|
|
142
|
-
x = np.asarray(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")
|
|
146
|
-
|
|
147
|
-
if np.issubdtype(x.dtype, np.datetime64):
|
|
148
|
-
valid = ~np.isnat(x)
|
|
149
|
-
xi = x.view(np.int64)
|
|
150
|
-
elif np.issubdtype(x.dtype, np.integer):
|
|
151
|
-
valid = np.ones(len(x), dtype=np.bool_)
|
|
152
|
-
xi = x.astype(np.int64, copy=False)
|
|
153
|
-
else:
|
|
154
|
-
return np.ascontiguousarray(x, dtype=np.float64), y, np.ones(len(x), dtype=np.bool_)
|
|
155
|
-
|
|
156
|
-
# Subtract the first timestamp while still in int64: ns epochs (~1.7e18)
|
|
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
|
|
160
|
-
first = int(np.argmax(valid)) if valid.any() else 0
|
|
161
|
-
xf = (xi - xi[first]).astype(np.float64)
|
|
162
|
-
return xf, y, valid
|
|
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
|