-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathChangePoint_MultiplePoints.py
More file actions
54 lines (44 loc) · 1.35 KB
/
Copy pathChangePoint_MultiplePoints.py
File metadata and controls
54 lines (44 loc) · 1.35 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
"""
Authors: Gerardo Lopez-Saldana <GerardoLopez@isa.utl.pt>
This implementation is based on the algorithm documented at:
http://www.inference.phy.cam.ac.uk/rpa23/papers/rpa-changepoint.pdf.
A Matlab implementation can be found at:
http://www.cs.toronto.edu/~rpa/changepoint.shtml
"""
from __future__ import division
import numpy
def CuSum(data):
Avg = numpy.average(data)
m = numpy.zeros(len(data) + 1, dtype=float)
# First element of cumulative sum is 0
for i in range(1,len(data)):
m[i] = m[i-1] + (data[i] - Avg)
return m
def Bootstrap(data, iterations):
c = CuSum(data)
sdiff = c.max() - c.min()
def Shuffled(x):
y = numpy.array(x)
numpy.random.shuffle(y)
return y
n = 0
for i in range(iterations):
b = CuSum(Shuffled(data))
bdiff = b.max() - b.min()
n += int(bdiff < sdiff)
return float(n)
def ChangePoint(data, confidence=95., iterations=1000.):
stack = [(data, 0)]
while stack:
data, offset = stack.pop()
if offset < 0:
continue
x = Bootstrap(data, iterations)
p = (x/iterations) * 100.0
if p > confidence:
c = CuSum(data)
mx = c.argmax()
yield mx + offset
stack.append((data[:mx], offset))
stack.append((data[mx:], offset+mx-1))
print data