mvtsa 1.0__py3-none-any.whl

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 (77) hide show
  1. mvtsa/__init__.py +51 -0
  2. mvtsa/_base.py +348 -0
  3. mvtsa/_numba.py +46 -0
  4. mvtsa/cli.py +125 -0
  5. mvtsa/clustering/__init__.py +15 -0
  6. mvtsa/clustering/distance_based.py +182 -0
  7. mvtsa/clustering/feature_based.py +215 -0
  8. mvtsa/clustering/partitional.py +330 -0
  9. mvtsa/datasets/__init__.py +10 -0
  10. mvtsa/datasets/_bundled.py +59 -0
  11. mvtsa/datasets/data/README.md +22 -0
  12. mvtsa/datasets/data/basicmotions.npz +0 -0
  13. mvtsa/datasets/data/gunpoint.npz +0 -0
  14. mvtsa/datasets/data/japanesevowels.npz +0 -0
  15. mvtsa/datasets/fetch.py +95 -0
  16. mvtsa/datasets/generators.py +548 -0
  17. mvtsa/distances.py +161 -0
  18. mvtsa/evaluation/__init__.py +42 -0
  19. mvtsa/evaluation/clustering_metrics.py +141 -0
  20. mvtsa/evaluation/segmentation_metrics.py +143 -0
  21. mvtsa/evaluation/validation.py +278 -0
  22. mvtsa/explain.py +158 -0
  23. mvtsa/io.py +147 -0
  24. mvtsa/mlops/__init__.py +11 -0
  25. mvtsa/mlops/config.py +105 -0
  26. mvtsa/mlops/monitoring.py +229 -0
  27. mvtsa/mlops/pipeline.py +156 -0
  28. mvtsa/mlops/registry.py +280 -0
  29. mvtsa/preprocessing.py +363 -0
  30. mvtsa/representation/__init__.py +77 -0
  31. mvtsa/representation/episodes.py +193 -0
  32. mvtsa/representation/features.py +168 -0
  33. mvtsa/representation/graphs.py +207 -0
  34. mvtsa/representation/images.py +107 -0
  35. mvtsa/representation/matrix_profile.py +107 -0
  36. mvtsa/representation/pca_models.py +496 -0
  37. mvtsa/representation/piecewise.py +149 -0
  38. mvtsa/representation/spd.py +111 -0
  39. mvtsa/representation/symbolic.py +152 -0
  40. mvtsa/segmentation/__init__.py +113 -0
  41. mvtsa/segmentation/bayesian.py +176 -0
  42. mvtsa/segmentation/consensus.py +95 -0
  43. mvtsa/segmentation/costs.py +518 -0
  44. mvtsa/segmentation/fisher.py +294 -0
  45. mvtsa/segmentation/fuzzy.py +236 -0
  46. mvtsa/segmentation/hmm.py +219 -0
  47. mvtsa/segmentation/latent.py +435 -0
  48. mvtsa/segmentation/neighbors.py +209 -0
  49. mvtsa/segmentation/online.py +133 -0
  50. mvtsa/segmentation/predictive.py +183 -0
  51. mvtsa/segmentation/profiles.py +232 -0
  52. mvtsa/segmentation/search.py +602 -0
  53. mvtsa/segmentation/selection.py +176 -0
  54. mvtsa/segmentation/states.py +279 -0
  55. mvtsa/simplify.py +192 -0
  56. mvtsa/viz/__init__.py +50 -0
  57. mvtsa/viz/_style.py +54 -0
  58. mvtsa/viz/clustering.py +201 -0
  59. mvtsa/viz/evaluation.py +144 -0
  60. mvtsa/viz/representation.py +135 -0
  61. mvtsa/viz/segmentation.py +189 -0
  62. mvtsa/viz/series.py +164 -0
  63. mvtsa/viz/warping.py +135 -0
  64. mvtsa/warping/__init__.py +54 -0
  65. mvtsa/warping/_dp.py +330 -0
  66. mvtsa/warping/alignment.py +161 -0
  67. mvtsa/warping/averaging.py +106 -0
  68. mvtsa/warping/diagnostics.py +110 -0
  69. mvtsa/warping/dtw.py +316 -0
  70. mvtsa/warping/elastic.py +173 -0
  71. mvtsa/warping/learning.py +141 -0
  72. mvtsa/warping/segment_dtw.py +471 -0
  73. mvtsa-1.0.dist-info/METADATA +171 -0
  74. mvtsa-1.0.dist-info/RECORD +77 -0
  75. mvtsa-1.0.dist-info/WHEEL +4 -0
  76. mvtsa-1.0.dist-info/entry_points.txt +2 -0
  77. mvtsa-1.0.dist-info/licenses/LICENSE +21 -0
mvtsa/__init__.py ADDED
@@ -0,0 +1,51 @@
1
+ """mvtsa -- multivariate time series analysis: segmentation, warping and clustering.
2
+
3
+ The package collects the time series segmentation, elastic similarity and
4
+ clustering methods developed by János Abonyi and his co-workers at the
5
+ University of Pannonia since 2003 -- PCA- and dynamic-PCA-based
6
+ segmentation, fuzzy segmentation with time-constrained PPCA clusters,
7
+ recursive-PCA on-line segmentation, Fisher-information-based goal-oriented
8
+ segmentation, correlation-based dynamic time warping, mixed dissimilarities
9
+ of piecewise linear approximations, episode-based trend analysis -- together
10
+ with the state of the art of the field and new methods, with evaluation,
11
+ visualization and MLOps tools.
12
+
13
+ Quick start::
14
+
15
+ import mvtsa as mv
16
+ X, cps, _ = mv.datasets.make_correlation_switching(n_segments=4, random_state=0)
17
+ seg = mv.segment(X, "pca", n_segments=4, n_components=1)
18
+ mv.viz.plot_segmentation(X, seg, truth=cps)
19
+
20
+ Subpackages: :mod:`mvtsa.segmentation`, :mod:`mvtsa.warping`,
21
+ :mod:`mvtsa.clustering`, :mod:`mvtsa.representation`,
22
+ :mod:`mvtsa.evaluation`, :mod:`mvtsa.viz`, :mod:`mvtsa.mlops`,
23
+ :mod:`mvtsa.datasets`; modules :mod:`mvtsa.preprocessing`,
24
+ :mod:`mvtsa.distances`, :mod:`mvtsa.simplify`, :mod:`mvtsa.explain`,
25
+ :mod:`mvtsa.io`.
26
+ """
27
+
28
+ __version__ = "1.0"
29
+
30
+ from . import ( # noqa: E402
31
+ clustering,
32
+ datasets,
33
+ distances,
34
+ evaluation,
35
+ explain,
36
+ io,
37
+ mlops,
38
+ preprocessing,
39
+ representation,
40
+ segmentation,
41
+ simplify,
42
+ viz,
43
+ warping,
44
+ )
45
+ from ._base import Segmentation, as_collection, as_series # noqa: E402
46
+ from .distances import pairwise_distances # noqa: E402
47
+ from .segmentation import segment # noqa: E402
48
+
49
+ __all__ = ["Segmentation", "as_series", "as_collection", "segment", "pairwise_distances", "segmentation", "warping",
50
+ "clustering", "representation", "evaluation", "viz", "mlops", "datasets", "preprocessing", "distances",
51
+ "simplify", "explain", "io", "__version__"]
mvtsa/_base.py ADDED
@@ -0,0 +1,348 @@
1
+ """Core data conventions of mvtsa.
2
+
3
+ A multivariate time series is a 2-D array ``X`` of shape ``(T, n)``: rows are
4
+ time samples, columns are variables (the notation of the book, ``X`` with
5
+ elements ``x_j(t)``). A univariate series may be given as a 1-D array; it is
6
+ treated as ``(T, 1)``. A *collection* is a list of such arrays, possibly of
7
+ different lengths; a 3-D array ``(N, T, n)`` and a pandas data frame are
8
+ accepted wherever a collection is expected.
9
+
10
+ A segmentation of a series of length ``T`` is represented by the sorted
11
+ *change points* ``0 < t_1 < ... < t_{c-1} < T``: the start indices of the
12
+ second, third, ... segment. Segment ``i`` is the half-open index range
13
+ ``[t_{i-1}, t_i)`` with ``t_0 = 0`` and ``t_c = T``.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ from collections.abc import Iterable, Iterator, Sequence
19
+ from dataclasses import dataclass, field
20
+ from typing import Any
21
+
22
+ import numpy as np
23
+
24
+ __all__ = [
25
+ "as_series",
26
+ "as_collection",
27
+ "check_random_state",
28
+ "Segmentation",
29
+ "BaseSegmenter",
30
+ ]
31
+
32
+
33
+ def as_series(X: Any, *, dtype=float, name: str = "X", allow_nan: bool = False) -> np.ndarray:
34
+ """Return ``X`` as a 2-D float array ``(T, n)``.
35
+
36
+ Accepts lists, 1-D or 2-D numpy arrays and pandas objects. A 1-D input
37
+ becomes a single column.
38
+
39
+ >>> as_series([1, 2, 3]).shape
40
+ (3, 1)
41
+ """
42
+ if hasattr(X, "to_numpy"):
43
+ X = X.to_numpy()
44
+ A = np.asarray(X, dtype=dtype)
45
+ if A.ndim == 1:
46
+ A = A[:, None]
47
+ if A.ndim != 2:
48
+ raise ValueError(f"{name} must be 1-D or 2-D (time x variables), got shape {A.shape}")
49
+ if A.shape[0] == 0:
50
+ raise ValueError(f"{name} is empty")
51
+ if not allow_nan and not np.all(np.isfinite(A)):
52
+ raise ValueError(f"{name} contains NaN or infinite values; see mvtsa.preprocessing.fill_missing")
53
+ return A
54
+
55
+
56
+ def as_collection(data: Any, *, dtype=float, allow_nan: bool = False) -> list[np.ndarray]:
57
+ """Return a collection of series as a list of ``(T_i, n)`` arrays.
58
+
59
+ ``data`` may be a list of arrays (of possibly different lengths), a 3-D
60
+ array ``(N, T, n)``, a 2-D array ``(N, T)`` of univariate series, or a
61
+ single 2-D series (which then becomes a collection of one).
62
+
63
+ >>> [x.shape for x in as_collection(np.zeros((4, 10)))]
64
+ [(10, 1), (10, 1), (10, 1), (10, 1)]
65
+ """
66
+ if hasattr(data, "to_numpy") and not isinstance(data, list | tuple):
67
+ data = data.to_numpy()
68
+ if isinstance(data, np.ndarray):
69
+ if data.ndim == 3:
70
+ return [as_series(x, dtype=dtype, allow_nan=allow_nan) for x in data]
71
+ if data.ndim == 2:
72
+ return [as_series(x, dtype=dtype, allow_nan=allow_nan) for x in data]
73
+ if data.ndim == 1 and data.dtype != object:
74
+ return [as_series(data, dtype=dtype, allow_nan=allow_nan)]
75
+ if isinstance(data, Iterable):
76
+ out = [as_series(x, dtype=dtype, allow_nan=allow_nan) for x in data]
77
+ if not out:
78
+ raise ValueError("empty collection")
79
+ n = {x.shape[1] for x in out}
80
+ if len(n) > 1:
81
+ raise ValueError(f"all series of a collection must have the same number of variables, got {sorted(n)}")
82
+ return out
83
+ raise TypeError(f"cannot interpret {type(data).__name__} as a collection of time series")
84
+
85
+
86
+ def check_random_state(seed) -> np.random.Generator:
87
+ """Return a numpy ``Generator`` from ``None``, an int or a generator."""
88
+ if isinstance(seed, np.random.Generator):
89
+ return seed
90
+ if isinstance(seed, np.random.RandomState):
91
+ return np.random.default_rng(seed.randint(0, 2**31 - 1))
92
+ return np.random.default_rng(seed)
93
+
94
+
95
+ def _clean_change_points(cps: Iterable[int], n_samples: int) -> np.ndarray:
96
+ a = np.unique(np.asarray(list(cps), dtype=int))
97
+ a = a[(a > 0) & (a < n_samples)]
98
+ return a
99
+
100
+
101
+ @dataclass
102
+ class Segmentation:
103
+ """A segmentation of one series.
104
+
105
+ Parameters
106
+ ----------
107
+ change_points : array of int
108
+ Sorted start indices of the 2nd, 3rd, ... segment (``0 < t < T``).
109
+ n_samples : int
110
+ Length ``T`` of the segmented series.
111
+ labels : array of int, optional
112
+ State (regime) label of each segment; segments with the same label
113
+ belong to the same state.
114
+ memberships : array (T, c), optional
115
+ Fuzzy memberships of the samples in the segments (fuzzy segmentation).
116
+ scores : array, optional
117
+ Method-specific score of each change point (e.g. merge cost,
118
+ change probability, classification score).
119
+ cost : float, optional
120
+ Total cost of the segmentation (cost-based methods).
121
+ meta : dict
122
+ Method name, parameters and other diagnostics.
123
+
124
+ Examples
125
+ --------
126
+ >>> s = Segmentation([3, 7], 10)
127
+ >>> s.segments
128
+ [(0, 3), (3, 7), (7, 10)]
129
+ >>> s.to_labels().tolist()
130
+ [0, 0, 0, 1, 1, 1, 1, 2, 2, 2]
131
+ """
132
+
133
+ change_points: np.ndarray
134
+ n_samples: int
135
+ labels: np.ndarray | None = None
136
+ memberships: np.ndarray | None = None
137
+ scores: np.ndarray | None = None
138
+ cost: float | None = None
139
+ meta: dict = field(default_factory=dict)
140
+
141
+ def __post_init__(self):
142
+ self.n_samples = int(self.n_samples)
143
+ self.change_points = _clean_change_points(self.change_points, self.n_samples)
144
+ if self.labels is not None:
145
+ self.labels = np.asarray(self.labels, dtype=int)
146
+ if len(self.labels) != self.n_segments:
147
+ raise ValueError("labels must have one entry per segment")
148
+ if self.scores is not None:
149
+ self.scores = np.asarray(self.scores, dtype=float)
150
+
151
+ # ------------------------------------------------------------------ basic views
152
+ @property
153
+ def n_segments(self) -> int:
154
+ return len(self.change_points) + 1
155
+
156
+ @property
157
+ def bounds(self) -> np.ndarray:
158
+ """``[0, t_1, ..., t_{c-1}, T]``."""
159
+ return np.concatenate([[0], self.change_points, [self.n_samples]]).astype(int)
160
+
161
+ @property
162
+ def segments(self) -> list[tuple[int, int]]:
163
+ """List of half-open ``(start, stop)`` index ranges."""
164
+ b = self.bounds
165
+ return [(int(b[i]), int(b[i + 1])) for i in range(len(b) - 1)]
166
+
167
+ @property
168
+ def lengths(self) -> np.ndarray:
169
+ return np.diff(self.bounds)
170
+
171
+ def __len__(self) -> int:
172
+ return self.n_segments
173
+
174
+ def __iter__(self) -> Iterator[tuple[int, int]]:
175
+ return iter(self.segments)
176
+
177
+ def __repr__(self) -> str:
178
+ cps = self.change_points.tolist()
179
+ if len(cps) > 8:
180
+ cps = cps[:4] + ["..."] + cps[-3:]
181
+ method = self.meta.get("method", "")
182
+ m = f", method={method!r}" if method else ""
183
+ return f"Segmentation(n_segments={self.n_segments}, n_samples={self.n_samples}, change_points={cps}{m})"
184
+
185
+ # ------------------------------------------------------------------ conversions
186
+ def to_labels(self, states: bool = False) -> np.ndarray:
187
+ """Label of every sample: its segment index, or its state if ``states``."""
188
+ idx = np.repeat(np.arange(self.n_segments), self.lengths)
189
+ if states:
190
+ if self.labels is None:
191
+ raise ValueError("this segmentation has no state labels")
192
+ return self.labels[idx]
193
+ return idx
194
+
195
+ @classmethod
196
+ def from_labels(cls, labels: Sequence[int], **kwargs) -> Segmentation:
197
+ """Build a segmentation from a per-sample label sequence.
198
+
199
+ Every run of equal labels becomes a segment; the run labels become
200
+ the state labels.
201
+
202
+ >>> Segmentation.from_labels([0, 0, 1, 1, 0]).labels.tolist()
203
+ [0, 1, 0]
204
+ """
205
+ lab = np.asarray(labels)
206
+ if lab.ndim != 1 or len(lab) == 0:
207
+ raise ValueError("labels must be a non-empty 1-D sequence")
208
+ cps = np.flatnonzero(lab[1:] != lab[:-1]) + 1
209
+ starts = np.concatenate([[0], cps])
210
+ _, states = np.unique(lab[starts], return_inverse=True)
211
+ return cls(cps, len(lab), labels=states, **kwargs)
212
+
213
+ def to_ruptures(self) -> list[int]:
214
+ """Breakpoints in the ``ruptures`` convention (the end ``T`` included)."""
215
+ return [*self.change_points.tolist(), self.n_samples]
216
+
217
+ @classmethod
218
+ def from_ruptures(cls, bkps: Sequence[int], **kwargs) -> Segmentation:
219
+ bk = list(bkps)
220
+ n = int(bk[-1])
221
+ return cls(bk[:-1], n, **kwargs)
222
+
223
+ def to_frame(self, X: np.ndarray | None = None, names: Sequence[str] | None = None):
224
+ """One row per segment: start, stop, length, state and (if ``X`` is given)
225
+ the mean of every variable."""
226
+ import pandas as pd
227
+
228
+ rows = []
229
+ for i, (a, b) in enumerate(self.segments):
230
+ r: dict[str, Any] = {"segment": i, "start": a, "stop": b, "length": b - a}
231
+ if self.labels is not None:
232
+ r["state"] = int(self.labels[i])
233
+ rows.append(r)
234
+ df = pd.DataFrame(rows)
235
+ if X is not None:
236
+ A = as_series(X)
237
+ nm = list(names) if names is not None else [f"x{j}" for j in range(A.shape[1])]
238
+ means = np.array([A[a:b].mean(0) for a, b in self.segments])
239
+ for j, c in enumerate(nm):
240
+ df[f"mean_{c}"] = means[:, j]
241
+ return df
242
+
243
+ def to_dict(self) -> dict:
244
+ d = {"change_points": self.change_points.tolist(), "n_samples": self.n_samples}
245
+ if self.labels is not None:
246
+ d["labels"] = self.labels.tolist()
247
+ if self.scores is not None:
248
+ d["scores"] = [float(s) for s in self.scores]
249
+ if self.cost is not None:
250
+ d["cost"] = float(self.cost)
251
+ if self.meta:
252
+ d["meta"] = {k: v for k, v in self.meta.items() if isinstance(v, str | int | float | bool | type(None))}
253
+ return d
254
+
255
+ @classmethod
256
+ def from_dict(cls, d: dict) -> Segmentation:
257
+ return cls(d["change_points"], d["n_samples"], labels=d.get("labels"), scores=d.get("scores"),
258
+ cost=d.get("cost"), meta=dict(d.get("meta", {})))
259
+
260
+ def with_labels(self, labels: Sequence[int]) -> Segmentation:
261
+ """Copy with state labels attached."""
262
+ return Segmentation(self.change_points.copy(), self.n_samples, labels=np.asarray(labels), scores=self.scores,
263
+ cost=self.cost, memberships=self.memberships, meta=dict(self.meta))
264
+
265
+ def shift(self, offset: int, n_samples: int | None = None) -> Segmentation:
266
+ """Change points moved by ``offset`` (used when a method works on a
267
+ lagged or trimmed copy of the series)."""
268
+ n = self.n_samples + offset if n_samples is None else n_samples
269
+ return Segmentation(self.change_points + offset, n, labels=self.labels, scores=self.scores, cost=self.cost,
270
+ meta=dict(self.meta))
271
+
272
+
273
+ class BaseSegmenter:
274
+ """Common interface of all segmentation methods.
275
+
276
+ Subclasses implement ``_segment(X) -> Segmentation``. ``fit`` stores the
277
+ result in ``segmentation_`` and ``change_points_``; ``segment`` returns it.
278
+ Parameters follow the scikit-learn conventions (``get_params``,
279
+ ``set_params``, ``sklearn.base.clone`` work).
280
+ """
281
+
282
+ def fit(self, X, y=None):
283
+ A = as_series(X)
284
+ seg = self._segment(A)
285
+ seg.meta.setdefault("method", type(self).__name__)
286
+ self.segmentation_ = seg
287
+ self.change_points_ = seg.change_points
288
+ self.n_samples_ = A.shape[0]
289
+ return self
290
+
291
+ def segment(self, X) -> Segmentation:
292
+ """Segment ``X`` and return the :class:`Segmentation`."""
293
+ return self.fit(X).segmentation_
294
+
295
+ def fit_predict(self, X, y=None) -> np.ndarray:
296
+ """Per-sample labels: state labels if the method assigns states,
297
+ otherwise segment indices."""
298
+ seg = self.segment(X)
299
+ return seg.to_labels(states=seg.labels is not None)
300
+
301
+ def _segment(self, X: np.ndarray) -> Segmentation: # pragma: no cover - abstract
302
+ raise NotImplementedError
303
+
304
+ # scikit-learn style parameter handling without requiring inheritance order
305
+ def get_params(self, deep: bool = True) -> dict:
306
+ import inspect
307
+
308
+ sig = inspect.signature(type(self).__init__)
309
+ out = {}
310
+ for name, p in sig.parameters.items():
311
+ if name == "self" or p.kind in (p.VAR_POSITIONAL, p.VAR_KEYWORD):
312
+ continue
313
+ val = getattr(self, name, p.default)
314
+ out[name] = val
315
+ if deep and hasattr(val, "get_params") and not isinstance(val, type):
316
+ for k, v in val.get_params(deep=True).items():
317
+ out[f"{name}__{k}"] = v
318
+ return out
319
+
320
+ def set_params(self, **params):
321
+ nested: dict[str, dict] = {}
322
+ for k, v in params.items():
323
+ if "__" in k:
324
+ head, tail = k.split("__", 1)
325
+ nested.setdefault(head, {})[tail] = v
326
+ else:
327
+ setattr(self, k, v)
328
+ for head, sub in nested.items():
329
+ getattr(self, head).set_params(**sub)
330
+ return self
331
+
332
+ def __repr__(self) -> str:
333
+ import inspect
334
+
335
+ sig = inspect.signature(type(self).__init__)
336
+ parts = []
337
+ for name, p in sig.parameters.items():
338
+ if name == "self" or p.kind in (p.VAR_POSITIONAL, p.VAR_KEYWORD):
339
+ continue
340
+ val = getattr(self, name, p.default)
341
+ if p.default is not inspect.Parameter.empty:
342
+ try:
343
+ if val is p.default or (not isinstance(val, np.ndarray) and val == p.default):
344
+ continue
345
+ except Exception: # noqa: BLE001 - comparisons of exotic objects
346
+ pass
347
+ parts.append(f"{name}={val!r}")
348
+ return f"{type(self).__name__}({', '.join(parts)})"
mvtsa/_numba.py ADDED
@@ -0,0 +1,46 @@
1
+ """Optional numba acceleration.
2
+
3
+ The dynamic-programming kernels of mvtsa (DTW and its relatives, soft-DTW,
4
+ edit distances, alignment) are written in a restricted, loop-based Python
5
+ that numba compiles when it is installed (``pip install "mvtsa[fast]"``).
6
+ Without numba the same functions run as plain Python; results are identical,
7
+ only slower. Set the environment variable ``MVTSA_DISABLE_NUMBA=1`` to force
8
+ the pure Python path (used by the test-suite to check both).
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import os
14
+
15
+ __all__ = ["njit", "HAVE_NUMBA", "prange"]
16
+
17
+ HAVE_NUMBA = False
18
+ if os.environ.get("MVTSA_DISABLE_NUMBA", "0") not in ("1", "true", "True"):
19
+ try: # pragma: no cover - depends on the environment
20
+ import numba as _nb
21
+
22
+ HAVE_NUMBA = True
23
+ except Exception: # noqa: BLE001
24
+ HAVE_NUMBA = False
25
+
26
+
27
+ def njit(*args, **kwargs):
28
+ """``numba.njit(cache=True)`` if numba is available, else the identity."""
29
+ if HAVE_NUMBA: # pragma: no cover - depends on the environment
30
+ kwargs.setdefault("cache", True)
31
+ if args and callable(args[0]) and len(args) == 1 and not kwargs.get("_force_kw"):
32
+ return _nb.njit(cache=True)(args[0])
33
+ return _nb.njit(*args, **kwargs)
34
+ if args and callable(args[0]):
35
+ return args[0]
36
+
37
+ def deco(f):
38
+ return f
39
+
40
+ return deco
41
+
42
+
43
+ if HAVE_NUMBA: # pragma: no cover
44
+ prange = _nb.prange
45
+ else:
46
+ prange = range
mvtsa/cli.py ADDED
@@ -0,0 +1,125 @@
1
+ """Command line interface.
2
+
3
+ Examples::
4
+
5
+ mvtsa segment data.csv --method pca --param n_segments=5 --out seg.json --plot seg.png
6
+ mvtsa distances collection_dir/ --metric dtw --out D.npy
7
+ mvtsa monitor reference.csv new.csv
8
+ mvtsa info
9
+
10
+ CSV files are read with pandas (numeric columns are the variables).
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import argparse
16
+ import json
17
+ import sys
18
+ from pathlib import Path
19
+
20
+ import numpy as np
21
+
22
+ __all__ = ["main"]
23
+
24
+
25
+ def _parse_value(v: str):
26
+ for conv in (int, float):
27
+ try:
28
+ return conv(v)
29
+ except ValueError:
30
+ pass
31
+ if v.lower() in ("true", "false"):
32
+ return v.lower() == "true"
33
+ if v.lower() == "none":
34
+ return None
35
+ return v
36
+
37
+
38
+ def _read_series(path):
39
+ import pandas as pd
40
+
41
+ df = pd.read_csv(path)
42
+ num = df.select_dtypes("number")
43
+ return num.to_numpy(float), list(num.columns)
44
+
45
+
46
+ def _cmd_segment(a):
47
+ from .segmentation import segment
48
+
49
+ X, names = _read_series(a.input)
50
+ params = dict(kv.split("=", 1) for kv in a.param)
51
+ seg = segment(X, a.method, **{k: _parse_value(v) for k, v in params.items()})
52
+ out = seg.to_dict()
53
+ print(json.dumps(out))
54
+ if a.out:
55
+ Path(a.out).write_text(json.dumps(out, indent=2))
56
+ if a.plot:
57
+ import matplotlib
58
+
59
+ matplotlib.use("Agg")
60
+ from .viz import plot_segmentation
61
+
62
+ ax = plot_segmentation(X, seg, names=names)
63
+ ax.figure.savefig(a.plot, bbox_inches="tight")
64
+ return 0
65
+
66
+
67
+ def _cmd_distances(a):
68
+ from .distances import pairwise_distances
69
+
70
+ files = sorted(Path(a.input).glob("*.csv"))
71
+ C = [_read_series(f)[0] for f in files]
72
+ D = pairwise_distances(C, metric=a.metric, n_jobs=a.n_jobs)
73
+ np.save(a.out, D)
74
+ print(f"{len(files)} series -> {a.out}")
75
+ return 0
76
+
77
+
78
+ def _cmd_monitor(a):
79
+ from .mlops import DriftMonitor
80
+
81
+ ref, _ = _read_series(a.reference)
82
+ new, _ = _read_series(a.new)
83
+ rep = DriftMonitor().fit(ref).update(new)
84
+ print(json.dumps(rep, indent=2))
85
+ return 1 if rep["drift"] else 0
86
+
87
+
88
+ def _cmd_info(a):
89
+ from . import __version__
90
+ from ._numba import HAVE_NUMBA
91
+ from .segmentation import SEGMENTERS
92
+
93
+ print(f"mvtsa {__version__} (numba acceleration: {'on' if HAVE_NUMBA else 'off'})")
94
+ print("segmentation methods:", ", ".join(sorted(SEGMENTERS)))
95
+ return 0
96
+
97
+
98
+ def main(argv=None) -> int:
99
+ p = argparse.ArgumentParser(prog="mvtsa", description="Multivariate time series analysis")
100
+ sub = p.add_subparsers(dest="cmd", required=True)
101
+ s = sub.add_parser("segment", help="segment a CSV series")
102
+ s.add_argument("input")
103
+ s.add_argument("--method", default="bottomup")
104
+ s.add_argument("--param", action="append", default=[], help="name=value (repeatable)")
105
+ s.add_argument("--out")
106
+ s.add_argument("--plot")
107
+ s.set_defaults(func=_cmd_segment)
108
+ d = sub.add_parser("distances", help="distance matrix of a folder of CSV series")
109
+ d.add_argument("input")
110
+ d.add_argument("--metric", default="dtw")
111
+ d.add_argument("--n-jobs", type=int, default=None)
112
+ d.add_argument("--out", default="distances.npy")
113
+ d.set_defaults(func=_cmd_distances)
114
+ m = sub.add_parser("monitor", help="drift report of new data against reference data")
115
+ m.add_argument("reference")
116
+ m.add_argument("new")
117
+ m.set_defaults(func=_cmd_monitor)
118
+ i = sub.add_parser("info", help="version and available methods")
119
+ i.set_defaults(func=_cmd_info)
120
+ a = p.parse_args(argv)
121
+ return a.func(a)
122
+
123
+
124
+ if __name__ == "__main__": # pragma: no cover
125
+ sys.exit(main())
@@ -0,0 +1,15 @@
1
+ """Clustering of time series, segments and trajectories."""
2
+
3
+ from .distance_based import (
4
+ ConsensusClustering,
5
+ DensityClustering,
6
+ HierarchicalClustering,
7
+ SpectralClustering,
8
+ coassociation_matrix,
9
+ )
10
+ from .feature_based import FeatureClustering, SegmentClustering, TrajectoryClustering, neighborhood_preservation
11
+ from .partitional import FuzzyCMedoids, KMedoids, KShape, TimeSeriesKMeans
12
+
13
+ __all__ = ["TimeSeriesKMeans", "KShape", "KMedoids", "FuzzyCMedoids", "HierarchicalClustering", "SpectralClustering",
14
+ "DensityClustering", "ConsensusClustering", "coassociation_matrix", "FeatureClustering",
15
+ "SegmentClustering", "TrajectoryClustering", "neighborhood_preservation"]