File: changepoint.tcl

package info (click to toggle)
tcllib 2.0%2Bdfsg-5
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 83,560 kB
  • sloc: tcl: 306,798; ansic: 14,272; sh: 3,035; xml: 1,766; yacc: 1,157; pascal: 881; makefile: 124; perl: 84; f90: 84; python: 33; ruby: 13; php: 11
file content (311 lines) | stat: -rw-r--r-- 9,558 bytes parent folder | download | duplicates (2)
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
# changepoint.tcl --
#     Statistical procedures for change point detection:
#     - Implementation of the CUSUM procedure to detect changes in the
#       mean of a series of data
#
#       Partly based on: https://www.itl.nist.gov/div898/handbook/pmc/section3/pmc323.htm
#
#       Note:
#       Since there do not seem to be online resources for the finer details, the
#       implementation uses simple guidelines as found for instance at
#       https://en.wikipedia.org/wiki/CUSUM.
#
#       There are two commands:
#       - One to examine a complete time series
#       - One (OO style) to examine data from a time series online
#
#    - Implementation of the binary segmentation algorithm
#

package require Tcl 8.6 9
package require TclOO
package require math::statistics
package provide math::changepoint 0.2

namespace eval ::math::changepoint {
    namespace export cusum-detect cusum-online binary-segmentation
}

# cusum-detect --
#     Procedure to examine a given data series and return the location
#     of the first change (if any)
#
# Arguments:
#     data                    List of values to be examined
#     args                    (Optional) key-value pairs to define the parameters:
#                             -target value    -- the target (or mean) for the time series
#                             -tolerance value -- the tolerated standard deviation
#                             -kfactor         -- the factor by which to multiply the
#                                                 standard deviation (defaults to 0.5,
#                                                 typically between 0.5 and 1.0
#                             -hfactor         -- the factor determining the limits
#                                                 betweem which the "cusum" statistic
#                                                 is accepted (typicaly 3.0-5.0, default 4.0)
#
# Result:
#     Index of the location of the first change or an empty string
#
# Note:
#     The CUSUM procedure is rather sensitive and details regarding the limits differ
#     between descriptions. This is a straightforward implementation.
#
#     If no options are given, the given time series is used for the target and the
#     tolerance.
#
#     Because of the senstivity using the raw data may give spurious results.
#
proc ::math::changepoint::cusum-detect {data args} {

    set kfactor   0.5
    set hfactor   4.0

    set target    {}
    set tolerance {}

    foreach {key value} $args {
        if { [string match "-*" $key] } {
            set name [string range $key 1 end]
            set $name $value
        } else {
            return -code error "Unknown/invalid option: $key"
        }
    }

    if { $target eq {} } {
        set target [::math::statistics::mean $data]
    }

    if { $tolerance eq {} } {
        set tolerance [::math::statistics::stdev $data]
    }

    set k [expr {$kfactor * $tolerance}]
    set h [expr {$hfactor * $tolerance}]

    set Shi 0.0
    set Slo 0.0

    set location {}
    set index    0
    foreach value $data {
        set Shi [expr {max( 0.0, $Shi + $value - $target - $k )}]
        set Slo [expr {max( 0.0, $Slo + $target - $value - $k )}]

        if { $Shi > $h || $Slo > $h } {
            set location $index
            break
        }

        incr index
    }

    return $location
}

# cusum-online --
#     Class to examine data passed in against expected properties
#
# Arguments:
#     data                    List of values to be examined
#     args                    (Optional) key-value pairs to define the parameters:
#                             -target value    -- the target (or mean) for the time series
#                             -tolerance value -- the tolerated standard deviation
#                             -kfactor         -- the factor by which to multiply the
#                                                 standard deviation (defaults to 0.5,
#                                                 typically between 0.5 and 1.0
#                             -hfactor         -- the factor determining the limits
#                                                 betweem which the "cusum" statistic
#                                                 is accepted (typicaly 3.0-5.0, default 4.0)
#
# Result:
#     Index of the location of the first change or an empty string
#
# Note:
#     All parameters used in this algorithm are set to default values.
#     The threshold are based on 3 * stdev and a quick detection of
#     a change of 1 * stdev.
#
::oo::class create ::math::changepoint::cusum-online {
    variable target    {}
    variable tolerance {}
    variable Slo       0.0
    variable Shi       0.0
    variable k         0.0
    variable h         0.0

    #
    # Constructor:
    # - two key-value pairs required: -target and -tolerance
    #
    constructor {args} {
        variable target
        variable tolerance
        variable k
        variable h

        set kfactor 0.5
        set hfactor 4.0

        foreach {option value} $args {
            switch -- $option {
                "-target"    { set target    $value }
                "-tolerance" { set tolerance $value }
                "-kfactor"   { set kfactor   $value }
                "-hfactor"   { set hfactor   $value }
                default {
                    return -code error "Unknown/invalid option: $option"
                }
            }
        }

        if { $target eq {} || $tolerance eq {} } {
            return -code error "Values for target and tolerance are required"
        }

        set k [expr {$kfactor * $tolerance}]
        set h [expr {$hfactor * $tolerance}]

        set Shi 0.0
        set Slo 0.0

    }

    #
    # Restart the object
    #
    method reset {} {
        variable Slo
        variable Shi

        set Shi 0.0
        set Slo 0.0
    }

    #
    # Add a new value to the object and examine it. If the cusum exceeds
    # the range, 1 is returned, otherwise 0.
    #
    method examine {value} {
        variable Slo
        variable Shi
        variable k
        variable h

        set Shi [expr {max( 0.0, $Shi + $value - $target - $k )}]
        set Slo [expr {max( 0.0, $Slo + $target - $value - $k )}]

        return [expr { $Shi > $h || $Slo > $h }]
    }
}

# binary-segmentation --
#     Apply the binary segmentation method recursively to find change points
#
# Arguments:
#     series            The series in question
#     args              Key-value pairs defining the options:
#                       -minlength 5    Minimum number of points in each segment
#                       -threshold 1.0  Factor applied to the standard deviation
#                                       functioning as a threshold for accepting
#                                       the change in cost function as an improvement
# Result:
#     List of indices where change points have been detected
#
proc ::math::changepoint::binary-segmentation {series args} {
    set minlength 5
    set threshold 1.0

    foreach {key value} $args {
        switch -- $key {
            "-minlength" {
                set minlength $value
            }
            "-threshold" {
                set threshold $value
            }
            default {
                return -error "Unknown keyword: $key"
            }
        }
    }

    if { [llength $series] < $minlength } {
        return -error "Series too short - at least $minlength values expected"
    }

    #
    # The real work is done by this procedure
    #
    set indices [BinSegRecursive 0 $series $minlength $threshold]

    return $indices
}

# BinSegRecursive --
#     Procedure for doing the actual work
#
# Arguments:
#     first            Index of the first value in the segment wrt the original series
#     series           Series/segment to be examined
#     minlength        Minimum length
#     threshold        Factor for the standard deviation
#
proc ::math::changepoint::BinSegRecursive {first series minlength threshold} {

    set length [llength $series]

    if { $length < $minlength } {
        return {}
    }

    #
    # Overall parameters
    #
    set stdev [::math::statistics::stdev $series]
    set idxmin  -1
    set maxcost [expr {$length * $stdev ** 2}]
    set mincost $maxcost

    #
    # Calculate the cost function for each split of the series
    #
    for {set idx $minlength} {$idx < $length-$minlength} {incr idx} {
        set segment1 [lrange $series 0 $idx]
        set segment2 [lrange $series [expr {$idx+1}] end]

        set stdev1   [::math::statistics::stdev $segment1]
        set stdev2   [::math::statistics::stdev $segment2]

        set cost     [expr {($idx+1) * $stdev1**2 + ($length-$idx) * $stdev2**2}]
        if { $cost < $mincost } {
            set mincost $cost
            set idxmin  $idx
        }
    }

    #
    # Do we accept it?
    #
    set indices {}

    if { $maxcost > $mincost + $threshold * $stdev ** 2 } {
        set segment1 [lrange $series 0 $idxmin]
        set segment2 [lrange $series [expr {$idxmin+1}] end]

        set left  [BinSegRecursive [expr {$first+0}]       $segment1 $minlength $threshold]
        set right [BinSegRecursive [expr {$first+$idxmin}] $segment2 $minlength $threshold]

        set indices [list [expr {$first+$idxmin}]]

        if { [llength $left] > 0 } {
            set indices [concat $left $indices]
        }

        if { [llength $right] > 0 } {
            set indices [concat $indices $right]
        }
    }

    return $indices
}