changefinder 0.4__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.
@@ -0,0 +1,246 @@
1
+ # -*- coding: utf-8 -*-
2
+ import copy
3
+ import math
4
+ import warnings
5
+
6
+ import numpy as np
7
+ from scipy import stats
8
+ from statsmodels.tsa.arima.model import ARIMA
9
+
10
+ __version__ = "0.4"
11
+
12
+ # Lower bound for variances. Keeps log-likelihood computations finite when a
13
+ # series becomes (nearly) perfectly predictable and the estimated variance
14
+ # collapses to zero.
15
+ _EPS = 1e-12
16
+
17
+
18
+ def LevinsonDurbin(r, lpcOrder):
19
+ """
20
+ Solve the Yule-Walker equations with the Levinson-Durbin recursion.
21
+
22
+ Returns ``(a, e)`` where ``a`` is the AR coefficient vector of length
23
+ ``lpcOrder + 1`` with ``a[0] == 1`` and ``e`` is the final prediction
24
+ error power.
25
+
26
+ The recursion is guarded against degenerate inputs: a zero lag-0
27
+ autocovariance returns the trivial predictor, and the recursion stops
28
+ early (keeping the lower-order solution) when the prediction error
29
+ vanishes or the reflection coefficient leaves ``(-1, 1)``. The latter can
30
+ happen because the SDAR autocovariance estimates are not guaranteed to
31
+ form a positive definite Toeplitz matrix.
32
+
33
+ Original implementation from
34
+ http://aidiary.hatenablog.com/entry/20120415/1334458954
35
+ """
36
+ r = np.asarray(r, dtype=np.float64)
37
+ assert lpcOrder >= 1, "lpcOrder must be 1 or more."
38
+ assert len(r) >= lpcOrder + 1, "r must have lpcOrder + 1 elements or more."
39
+
40
+ a = np.zeros(lpcOrder + 1, dtype=np.float64)
41
+ a[0] = 1.0
42
+ if not np.isfinite(r[0]) or r[0] <= _EPS:
43
+ return a, 0.0
44
+
45
+ lam = - r[1] / r[0]
46
+ if not abs(lam) < 1.0:
47
+ return a, r[0]
48
+ a[1] = lam
49
+ e = r[0] * (1.0 - lam * lam)
50
+
51
+ for k in range(1, lpcOrder):
52
+ if not e > _EPS:
53
+ break
54
+ lam = 0.0
55
+ for j in range(k + 1):
56
+ lam -= a[j] * r[k + 1 - j]
57
+ lam /= e
58
+ if not abs(lam) < 1.0:
59
+ break
60
+
61
+ prev = a[:k + 1].copy()
62
+ a[1:k + 2] = prev[1:k + 1].tolist() + [0.0]
63
+ a[1:k + 2] += lam * prev[k::-1]
64
+ e *= (1.0 - lam * lam)
65
+
66
+ return a, e
67
+
68
+
69
+ class _SDAR_1Dim(object):
70
+ """
71
+ Sequentially Discounting AR model estimation (Yamanishi & Takeuchi).
72
+
73
+ ``update(x_t, term)`` scores ``x_t`` with the model learned from
74
+ ``x_1 .. x_{t-1}`` (``-log p_{t-1}(x_t | x^{t-1})``) and then updates the
75
+ model with ``x_t``. ``term`` holds the ``order`` previous observations.
76
+ """
77
+
78
+ def __init__(self, r, order):
79
+ assert 0.0 < r < 1.0, "r must be in (0, 1)."
80
+ self._r = r
81
+ self._order = order
82
+ self._mu = 0.0
83
+ self._sigma = 0.0
84
+ self._c = np.zeros(self._order + 1, dtype=np.float64)
85
+ self._a = np.zeros(self._order + 1, dtype=np.float64)
86
+ self._a[0] = 1.0
87
+ self._initialized = False
88
+
89
+ def _predict(self, term):
90
+ return np.dot(-self._a[1:], (term[::-1] - self._mu)) + self._mu
91
+
92
+ def _score(self, x, xhat):
93
+ resid = x - xhat
94
+ sigma = max(self._sigma, _EPS)
95
+ # Negative Gaussian log-likelihood, evaluated in log space so that it
96
+ # never overflows/underflows.
97
+ return 0.5 * math.log(2.0 * math.pi * sigma) + 0.5 * resid * resid / sigma
98
+
99
+ def _learn(self, x, term):
100
+ self._mu = (1.0 - self._r) * self._mu + self._r * x
101
+ self._c[0] = (1.0 - self._r) * self._c[0] + self._r * (x - self._mu) * (x - self._mu)
102
+ for i in range(1, self._order + 1):
103
+ self._c[i] = (1.0 - self._r) * self._c[i] + self._r * (x - self._mu) * (term[-i] - self._mu)
104
+ self._a, _ = LevinsonDurbin(self._c, self._order)
105
+ xhat = self._predict(term)
106
+ resid = x - xhat
107
+ self._sigma = (1.0 - self._r) * self._sigma + self._r * resid * resid
108
+ return xhat
109
+
110
+ def update(self, x, term):
111
+ assert len(term) >= self._order, "term must be order or more"
112
+ term = np.asarray(term, dtype=np.float64)[-self._order:]
113
+ x = float(x)
114
+ if not self._initialized:
115
+ # No model has been learned yet: start from the level of the
116
+ # history, learn x_t and bootstrap the first score from that model.
117
+ self._mu = float(np.mean(term))
118
+ self._initialized = True
119
+ xhat = self._learn(x, term)
120
+ return self._score(x, xhat), xhat
121
+ # Score x_t under p_{t-1}, then learn x_t.
122
+ xhat = self._predict(term)
123
+ score = self._score(x, xhat)
124
+ self._learn(x, term)
125
+ return score, xhat
126
+
127
+
128
+ class _ChangeFinderAbstract(object):
129
+ def update(self, x, inplace=True):
130
+ """
131
+ Feed one observation and return ``(score, predict)``.
132
+
133
+ With ``inplace=False`` the score is computed for ``x`` without
134
+ learning it: the detector's state is left untouched, so repeated
135
+ calls with the same observation return the same result.
136
+ """
137
+ if not inplace:
138
+ return copy.deepcopy(self)._update(x)
139
+ return self._update(x)
140
+
141
+ def _add_one(self, one, ts, size):
142
+ ts.append(one)
143
+ if len(ts) == size + 1:
144
+ ts.pop(0)
145
+
146
+ def _smoothing(self, ts):
147
+ return sum(ts) / float(len(ts))
148
+
149
+
150
+ class ChangeFinder(_ChangeFinderAbstract):
151
+ def __init__(self, r=0.5, order=1, smooth=7):
152
+ assert order > 0, "order must be 1 or more."
153
+ assert smooth > 2, "term must be 3 or more."
154
+ self._smooth = smooth
155
+ self._smooth2 = int(round(self._smooth / 2.0))
156
+ self._order = order
157
+ self._r = r
158
+ self._ts = []
159
+ self._first_scores = []
160
+ self._smoothed_scores = []
161
+ self._second_scores = []
162
+ self._sdar_first = _SDAR_1Dim(r, self._order)
163
+ self._sdar_second = _SDAR_1Dim(r, self._order)
164
+
165
+ def _update(self, x):
166
+ score = 0
167
+ predict = x
168
+ predict2 = 0
169
+ if len(self._ts) == self._order: # 第一段学習
170
+ score, predict = self._sdar_first.update(x, self._ts)
171
+ self._add_one(score, self._first_scores, self._smooth)
172
+ self._add_one(x, self._ts, self._order)
173
+ second_target = None
174
+ if len(self._first_scores) == self._smooth: # 平滑化
175
+ second_target = self._smoothing(self._first_scores)
176
+ if second_target is not None and len(self._smoothed_scores) == self._order: # 第二段学習
177
+ score, predict2 = self._sdar_second.update(second_target, self._smoothed_scores)
178
+ self._add_one(score,
179
+ self._second_scores, self._smooth2)
180
+ if second_target is not None:
181
+ self._add_one(second_target, self._smoothed_scores, self._order)
182
+ if len(self._second_scores) == self._smooth2:
183
+ return self._smoothing(self._second_scores), predict
184
+ else:
185
+ return 0.0, predict
186
+
187
+
188
+ class ChangeFinderARIMA(_ChangeFinderAbstract):
189
+ def __init__(self, term=30, smooth=7, order=(1, 0, 0)):
190
+ assert smooth > 2, "term must be 3 or more."
191
+ assert term > smooth, "term must be more than smooth"
192
+
193
+ self._term = term
194
+ self._smooth = smooth
195
+ self._smooth2 = int(round(self._smooth / 2.0))
196
+ self._order = order
197
+ self._ts = []
198
+ self._first_scores = []
199
+ self._smoothed_scores = []
200
+ self._second_scores = []
201
+
202
+ def _calc_outlier_score(self, ts, target):
203
+ def outlier_score(residuals, x):
204
+ m = residuals.mean()
205
+ s = np.std(residuals, ddof=1)
206
+ if not np.isfinite(s) or s < math.sqrt(_EPS):
207
+ s = math.sqrt(_EPS)
208
+ return -stats.norm.logpdf(x, m, s)
209
+ ts = np.asarray(ts, dtype=np.float64)
210
+ with warnings.catch_warnings():
211
+ warnings.simplefilter("ignore")
212
+ arima_model = ARIMA(ts, order=self._order)
213
+ result = arima_model.fit()
214
+ pred = float(np.asarray(result.forecast(1)).ravel()[0])
215
+ resid = np.asarray(result.resid, dtype=np.float64)
216
+ return outlier_score(resid, x=target - pred), pred
217
+
218
+ def _update(self, x):
219
+ score = 0
220
+ predict = x
221
+ predict2 = 0
222
+ if len(self._ts) == self._term: # 第一段学習
223
+ try:
224
+ score, predict = self._calc_outlier_score(self._ts, x)
225
+ self._add_one(score, self._first_scores, self._smooth)
226
+ except Exception:
227
+ self._add_one(x, self._ts, self._term)
228
+ return 0, predict
229
+ self._add_one(x, self._ts, self._term)
230
+ second_target = None
231
+ if len(self._first_scores) == self._smooth: # 平滑化
232
+ second_target = self._smoothing(self._first_scores)
233
+ if second_target is not None and len(self._smoothed_scores) == self._term: # 第二段学習
234
+ try:
235
+ score, predict2 = self._calc_outlier_score(self._smoothed_scores, second_target)
236
+ self._add_one(score,
237
+ self._second_scores, self._smooth2)
238
+ except Exception:
239
+ self._add_one(second_target, self._smoothed_scores, self._term)
240
+ return 0, predict
241
+ if second_target is not None:
242
+ self._add_one(second_target, self._smoothed_scores, self._term)
243
+ if len(self._second_scores) == self._smooth2:
244
+ return self._smoothing(self._second_scores), predict
245
+ else:
246
+ return 0.0, predict
@@ -0,0 +1,73 @@
1
+ Metadata-Version: 2.4
2
+ Name: changefinder
3
+ Version: 0.4
4
+ Summary: Online Change-Point Detection Library based on ChangeFinder Algorithm.
5
+ Author-email: Shunsuke Aihara <aihara@argmax.jp>
6
+ License: MIT License
7
+ Project-URL: Homepage, https://github.com/shunsukeaihara/changefinder
8
+ Keywords: scipy,numpy,timeseries analysis,change point detection
9
+ Classifier: Programming Language :: Python
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: License :: OSI Approved :: MIT License
12
+ Classifier: Topic :: Scientific/Engineering
13
+ Requires-Python: >=3.8
14
+ Description-Content-Type: text/x-rst
15
+ License-File: LICENSE.txt
16
+ Requires-Dist: numpy>=1.20
17
+ Requires-Dist: scipy>=1.7
18
+ Requires-Dist: statsmodels>=0.13
19
+ Provides-Extra: test
20
+ Requires-Dist: pytest>=7; extra == "test"
21
+ Dynamic: license-file
22
+
23
+ changefinder
24
+ ============
25
+
26
+ Online Change-Point Detection Library based on ChangeFinder Algorithm.
27
+
28
+ Requirements
29
+ ------------
30
+
31
+ * Python 3.8 or later
32
+ * numpy >= 1.20
33
+ * scipy >= 1.7
34
+ * statsmodels >= 0.13
35
+
36
+ Install
37
+ -------
38
+
39
+ ::
40
+
41
+ pip install .
42
+
43
+ Usage
44
+ -----
45
+
46
+ ::
47
+
48
+ import changefinder
49
+
50
+ cf = changefinder.ChangeFinder(r=0.1, order=1, smooth=7)
51
+ for x in data:
52
+ score, predict = cf.update(x)
53
+
54
+ ``ChangeFinderARIMA`` offers the same ``update`` interface using an ARIMA
55
+ model instead of SDAR for the first and second stage.
56
+
57
+ Test
58
+ ----
59
+
60
+ ::
61
+
62
+ pip install .[test]
63
+ pytest
64
+
65
+ Authors & Contributors
66
+ ----------------------
67
+
68
+ * Shunsuke Aihara - http://argmax.jp
69
+
70
+ License
71
+ =======
72
+
73
+ This code is licensed under MIT License.
@@ -0,0 +1,6 @@
1
+ changefinder/__init__.py,sha256=tOW0DslMtEUD0fSuhLVkZYyhQXF-CpLyaurJ6D_LFWM,9235
2
+ changefinder-0.4.dist-info/licenses/LICENSE.txt,sha256=rcvE78hF6nuK2j4m44buwW7jMKjWGJrlixD2F_FTAzo,1082
3
+ changefinder-0.4.dist-info/METADATA,sha256=lsMeg7IKYZEzobco3q-RRM7GihsPrfbvgkaNC8C2SuE,1509
4
+ changefinder-0.4.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
5
+ changefinder-0.4.dist-info/top_level.txt,sha256=moDhmdJwhjFyLYWK2j3rqbOo7oZo-0tu5VSmxg4eQ7w,13
6
+ changefinder-0.4.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2013 Shunsuke Aihara
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
@@ -0,0 +1 @@
1
+ changefinder