summaryrefslogtreecommitdiff
path: root/R/strats.R
blob: 0f558148a8a23731e6bd5564d0a01df4200eea2a (plain)
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
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
`%>%` <- magrittr::`%>%`

#' @useDynLib strats strats_compute_laplacian_matrix_product
strats_laplacian_matrix_product <- function (temporal_dependency, X) {
    out <- matrix (0, nrow (X), ncol (X))
    n <- as.integer (nrow (X))
    d <- as.integer (ncol (X))
    temporal_dependency <- as.numeric (temporal_dependency)
    omega <- as.integer (length (temporal_dependency))
    x <- as.numeric (X)
    .C (strats_compute_laplacian_matrix_product,
        n, d, omega, temporal_dependency, x, out)[[6]]
}

## Check the matrix product
check_matrix_product <- function () {
    X <- matrix (rnorm (24), 6, 4)
    temporal_dependency <- c (0.5, 0.2, 0.1)
    M <- matrix (0, 6, 6)
    for (omega in 0:3) {
        mij <- 1
        if (omega > 0) {
            mij <- temporal_dependency[omega]
        }
        for (i in 1:6) {
            j_plus <- i + omega
            j_minus <- i - omega
            if (j_plus <= 6) {
                M[i, j_plus] <- mij
            }
            if (j_minus >= 1) {
                M[i, j_minus] <- mij
            }
        }
    }
    D <- diag (rowSums (M), 6, 6)
    L <- D - M
    Y <- L %*% X
    Yhat <- strats_laplacian_matrix_product (temporal_dependency, X)
    stopifnot (nrow (Yhat) == nrow (Y))
    stopifnot (ncol (Yhat) == ncol (Y))
    stopifnot (max (abs (Yhat - Y)) < 1e-8)
}

#' Compute the STRATS loss
#'
#' @param T_normal a normal subset of the time series
#' @param T the time series
#' @param alpha the global detection regularizer
#' @param beta the residual analysis regularizer
#' @param gamma the contextual detection regularizer
#' @param dependency a vector giving the temporal dependency between
#'     an observation and the next observations (the temporal
#'     dependency is symmetric)
#' @param W the reconstruction matrix
#' @param R the residual matrix
#' @return the loss
#' @export
strats_loss <- function (T_normal, T, alpha, beta, gamma, dependency, W, R) {
    non_residual <- R - T
    (sum ((T - crossprod (W, T_normal) - R) ^ 2)
        + alpha * sum (sqrt (rowSums (W ^ 2)))
        + beta * sum (sqrt (rowSums (R ^ 2)))
        + gamma * sum (non_residual * strats_laplacian_matrix_product (dependency, non_residual)))
}

#' Compute the STRATS gradient wrt W
#'
#' @param T_normal a normal subset of the time series
#' @param T the time series
#' @param alpha the global detection regularizer
#' @param beta the residual analysis regularizer
#' @param gamma the contextual detection regularizer
#' @param dependency a vector giving the temporal dependency between
#'     an observation and the next observations (the temporal
#'     dependency is symmetric)
#' @param W the reconstruction matrix
#' @param R the residual matrix
#' @return the gradient wrt W
#' @export
strats_gradient_w <- function (T_normal, T, alpha, beta, gamma, dependency, W, R) {
    Dw <- 1 / (2 * sqrt (rowSums (W ^ 2)))
    Dw[!is.finite (Dw)] <- 0
    M <- tcrossprod (T_normal)
    diag (M) <- diag (M) + alpha * Dw
    2 * (M %*% W - tcrossprod (T_normal, T) + tcrossprod (T_normal, R))
}

#' Compute the STRATS gradient wrt R
#'
#' @param T_normal a normal subset of the time series
#' @param T the time series
#' @param alpha the global detection regularizer
#' @param beta the residual analysis regularizer
#' @param gamma the contextual detection regularizer
#' @param dependency a vector giving the temporal dependency between
#'     an observation and the next observations (the temporal
#'     dependency is symmetric)
#' @param W the reconstruction matrix
#' @param R the residual matrix
#' @return the gradient wrt R
#' @export
strats_gradient_r <- function (T_normal, T, alpha, beta, gamma, dependency, W, R) {
    Dr <- 1 / (2 * sqrt (rowSums (R ^ 2)))
    Dr[!is.finite (Dr)] <- 0
    2 * (crossprod (W, T_normal) - T + R + beta * sweep (R, 1, Dr, `*`) + gamma * strats_laplacian_matrix_product (dependency, R - T))
}

gradient_error <- function (T_normal, T, alpha, beta, gamma, dependency, W, R) {
    gW <- matrix (0, nrow (T_normal), nrow (T))
    gR <- matrix (0, nrow (T), ncol (T))
    for (i in 1:nrow (T_normal)) {
        for (j in 1:nrow (T)) {
            W_minus <- W
            W_plus <- W
            W_minus[i, j] <- W_minus[i, j] - 1e-4
            W_plus[i, j] <- W_plus[i, j] + 1e-4
            l_minus <- strats_loss (T_normal, T, alpha, beta, gamma, dependency,
                                    W_minus, R)
            l_plus <- strats_loss (T_normal, T, alpha, beta, gamma, dependency,
                                   W_plus, R)
            gW[i, j] <- (l_plus - l_minus) / (2 * 1e-4)
        }
    }
    for (i in 1:nrow (T)) {
        for (j in 1:ncol (T)) {
            R_minus <- R
            R_plus <- R
            R_minus[i, j] <- R_minus[i, j] - 1e-4
            R_plus[i, j] <- R_plus[i, j] + 1e-4
            l_minus <- strats_loss (T_normal, T, alpha, beta, gamma, dependency,
                                    W, R_minus)
            l_plus <- strats_loss (T_normal, T, alpha, beta, gamma, dependency,
                                   W, R_plus)
            gR[i, j] <- (l_plus - l_minus) / (2 * 1e-4)
        }
    }
    gW_true <- strats_gradient_w (T_normal, T, alpha, beta, gamma, dependency, W, R)
    gR_true <- strats_gradient_r (T_normal, T, alpha, beta, gamma, dependency, W, R)
    max (max (abs (gW - gW_true)), max (abs (gR - gR_true)))
}

check_gradient <- function () {
    set.seed (1)
    for (i in 1:100) {
        n <- 100
        n_train <- 25
        d <- 10
        dependency <- c (0.5, 0.2, 0.1, 0.05, 0.02, 0.01, 0.005, 0.002, 0.001)
        T_normal <- matrix (rnorm (n_train * d), n_train, d)
        T <- matrix (rnorm (n * d), n, d)
        W <- matrix (rnorm (n_train * n), n_train, n)
        R <- matrix (rnorm (n * d), n, d)
        stopifnot (gradient_error (T_normal, T, 1000, 1000, 1000, dependency, W, R)
                   <= 1e-4)
    }
}

#' Check that the step size is adapted.
#'
#' @param T_normal a normal subset of the time series
#' @param T the time series
#' @param alpha the global detection regularizer
#' @param beta the residual analysis regularizer
#' @param gamma the contextual detection regularizer
#' @param dependency a vector giving the temporal dependency between
#'     an observation and the next observations (the temporal
#'     dependency is symmetric)
#' @param W the reconstruction matrix
#' @param R the residual matrix
#' @param gW the gradient wrt W at W
#' @param gR the gradient wrt R at R
#' @param step_w the step size for W (may be 0 to only update R)
#' @param step_r the step size for R (may be 0 to only update W)
#' @param loss_value the loss value at (W, R)
#' @return whether the step sizes for W and R are correct
#' @export
armijo <- function (T_normal, T, alpha, beta, gamma, dependency, W, R, gW, gR, step_w, step_r, loss_value) {
    nxt_w <- W - step_w * gW
    nxt_r <- R - step_r * gR
    loss_next <- strats_loss (T_normal, T, alpha, beta, gamma, dependency, nxt_w, nxt_r)
    loss_limit <- (loss_value
        + sum ((nxt_w - W) * gW)
        + sum ((nxt_r - R) * gR)
        + ifelse (step_w == 0, 0, 0.5 * sum ((nxt_w - W) ^ 2) / step_w)
        + ifelse (step_r == 0, 0, 0.5 * sum ((nxt_r - R) ^ 2) / step_r))
    (loss_next <= loss_limit)
}

line_search_w <- function (T_normal, T, alpha, beta, gamma, dependency, W, R, gW, gR, step, loss_value) {
    if (armijo (T_normal, T, alpha, beta, gamma, dependency, W, R, gW, gR, step, 0, loss_value)) {
        step
    } else {
        cat (sprintf ("%g is not sufficient for step_w.\n", step), file = stderr ())
        line_search_w (T_normal, T, alpha, beta, gamma, dependency, W, R, gW, gR, step / 2, loss_value)
    }
}

line_search_r <- function (T_normal, T, alpha, beta, gamma, dependency, W, R, gW, gR, step, loss_value) {
    if (armijo (T_normal, T, alpha, beta, gamma, dependency, W, R, gW, gR, 0, step, loss_value)) {
        step
    } else {
        cat (sprintf ("%g is not sufficient for step_r.\n", step), file = stderr ())
        line_search_r (T_normal, T, alpha, beta, gamma, dependency, W, R, gW, gR, step / 2, loss_value)
    }
}

strats_iteration <- function (T_normal, T, alpha, beta, gamma, dependency,
                              loss_value = NULL,
                              W = NULL, R = NULL, step_w = NULL, step_r = NULL) {
    if (is.null (W)) {
        W <- diag (1, nrow (T_normal), nrow (T))
        row.names (W) <- row.names (T_normal)
        colnames (W) <- row.names (T)
    }
    if (is.null (R)) {
        R <- matrix (0, nrow (T), ncol (T))
        row.names (R) <- row.names (T)
        colnames (R) <- colnames (T)
    }
    if (is.null (loss_value)) {
        loss_value <- strats_loss (T_normal, T, alpha, beta, gamma, dependency, W, R)
    }
    if (is.null (step_w)) {
        step_w <- 1
    }
    if (is.null (step_r)) {
        step_r <- 1
    }
    ## Optimize W:
    gW <- strats_gradient_w (T_normal, T, alpha, beta, gamma, dependency, W, R)
    gR <- matrix (0, nrow (T), ncol (T))
    step_w <- line_search_w (T_normal, T, alpha, beta, gamma, dependency, W, R, gW, gR, step_w, loss_value)
    cat (sprintf ("Using step W: %g\n", step_w), file = stderr ())
    W <- W - step_w * gW
    loss_value <- strats_loss (T_normal, T, alpha, beta, gamma, dependency, W, R)
    ## Optimize R:
    gW <- matrix (0, nrow (T_normal), nrow (T))
    gR <- strats_gradient_r (T_normal, T, alpha, beta, gamma, dependency, W, R)
    step_r <- line_search_r (T_normal, T, alpha, beta, gamma, dependency, W, R, gW, gR, step_r, loss_value)
    cat (sprintf ("Using step R: %g\n", step_r), file = stderr ())
    R <- R - step_r * gR
    loss_value <- strats_loss (T_normal, T, alpha, beta, gamma, dependency, W, R)
    list (loss_value = loss_value,
          W = W, R = R, step_w = step_w, step_r = step_r)
}

strats_sample <- function (T, n_points) {
    i <- ceiling (nrow (T) * ((1:n_points) / n_points))
    T[i,, drop = FALSE]
}

#' Apply the STRATS algorithm.
#'
#' The algorithm uses a normal time series, it is either passed as
#' T_normal, or sampled from T with n_normal points.
#'
#' @param T the time series
#' @param alpha the global detection regularizer
#' @param beta the residual analysis regularizer
#' @param gamma the contextual detection regularizer
#' @param dependency a vector giving the temporal dependency between
#'     an observation and the next observations (the temporal
#'     dependency is symmetric)
#' @param T_normal a time series with normal data
#' @param n_normal the number of normal points to sample
#' @param maxiter how many gradient descent iterations to make
#' @return the STRATS model, as a list with key 'anomalies' bound to a
#'     tibble with 'observation' (the index in T), 'score' (the
#'     anomaly score) and 'rank' (the anomaly rank).
#' @export
strats <- function (T, alpha, beta, gamma, dependency,
                    T_normal = NULL,
                    n_normal = NULL,
                    maxiter = 100) {
    if (is.null (T_normal)
        && is.null (n_normal)) {
        stop ("Either pas n_normal, the number of samples to take for normal, or pass T_normal")
    }
    if (is.null (T_normal)) {
        T_normal <- strats_sample (T, n_normal)
    }
    T <- as.matrix (T)
    T_normal <- as.matrix (T_normal)
    dependency <- c (dependency)
    stopifnot (is.finite (alpha))
    stopifnot (is.finite (beta))
    stopifnot (is.finite (gamma))
    stopifnot (alpha >= 0)
    stopifnot (beta >= 0)
    stopifnot (gamma >= 0)
    stopifnot (all (is.finite (dependency)))
    stopifnot (all (dependency >= 0))
    stopifnot (all (is.finite (T)))
    stopifnot (all (is.finite (T_normal)))
    stopifnot (ncol (T) == ncol (T_normal))
    model <- list ()
    for (i in 1:maxiter) {
        last_loss <- model$loss_value
        model <- strats_iteration (T_normal, T, alpha, beta, gamma, dependency,
                                   model$loss_value,
                                   model$W, model$R, model$step_w, model$step_r)
        cat (sprintf ("New model with loss value: %g.\n", model$loss_value),
             file = stderr ())
        if (!is.null (last_loss)) {
            stopifnot (model$loss_value <= last_loss)
        }
    }
    model$anomalies <- (tibble::tibble (observation = seq_len (nrow (model$R)),
                                        score = rowSums (model$R ^ 2))
        %>% dplyr::arrange (-score)
        %>% dplyr::mutate (rank = seq_len (nrow (model$R))))
    model
}

#' Test a configuration for STRATS with synthetic anomaly injection
#'
#' @param T the time series
#' @param alpha the global detection regularizer
#' @param beta the residual analysis regularizer
#' @param gamma the contextual detection regularizer
#' @param dependency a vector giving the temporal dependency between
#'     an observation and the next observations (the temporal
#'     dependency is symmetric)
#' @param T_normal a time series with normal data
#' @param n_normal the number of normal points to sample
#' @param maxiter how many gradient descent iterations to make
#' @return the mean rank of the injected anomalies. Lower is better.
#' @export
strats_test <- function (T, alpha, beta, gamma, dependency,
                         T_normal = NULL,
                         n_normal = NULL,
                         maxiter = 100) {
    ## Inject 1 anomaly, learn STRATS, and check the rank of the
    ## anomaly. Repeat 10 times with different anomalies. Return the
    ## mean.
    do.call (mean, lapply (1:10, function (seed) {
        set.seed (seed)
        i_base <- sample (seq_len (nrow (T)), 1)
        i_anomaly <- sample (seq_len (nrow (T)), 1)
        which_swapped <- sample (seq_len (ncol (T)), ceiling (ncol (T) / 2))
        t <- T[i_anomaly,]
        t_base <- T[i_base,]
        t[which_swapped] <- t_base[which_swapped]
        T[i_anomaly,] <- t
        model <- strats (T, alpha, beta, gamma, dependency,
                         T_normal = T_normal, n_normal = n_normal,
                         maxiter = maxiter)
        cat (sprintf ("WTF?? %s\n",
                      paste (colnames (model$anomalies), collapse = "\n")),
             file = stderr ())
        (model$anomalies
            %>% dplyr::filter (observation == i_anomaly))$rank[1]
    }))
}

#' Tune STRATS with synthetic anomalies
#'
#' @param T the time series
#' @param dependency a vector giving the temporal dependency between
#'     an observation and the next observations (the temporal
#'     dependency is symmetric)
#' @param T_normal a time series with normal data
#' @param n_normal the number of normal points to sample
#' @param maxiter how many gradient descent iterations to make
#' @return a tibble, with columns alpha, beta, gamma, and error (the error
#'     on synthetic anomalies).
#' @export
strats_tune <- function (T, dependency,
                         T_normal = NULL,
                         n_normal = NULL,
                         maxiter = 100) {
    set.seed (1)
    do.call (rbind, lapply (1:20, function (seed) {
        set.seed (seed)
        alpha <- signif (10^runif (1, -3, 3), 1)
        beta <- signif (10^runif (1, -3, 3), 1)
        gamma <- signif (10^runif (1, -3, 3), 1)
        error <- strats_test (T, alpha, beta, gamma, dependency,
                              T_normal = T_normal,
                              n_normal = n_normal,
                              maxiter = maxiter)
        cat (sprintf ("Alpha: %g, beta: %g, gamma: %g, error: %g\n",
                      alpha, beta, gamma, error),
             file = stderr ())
        tibble::tibble (alpha = alpha, beta = beta, gamma = gamma,
                        error = error)
    }))
}