Module: AnomalyDetection

Defined in:
lib/anomaly_detection.rb,
lib/anomaly_detection/version.rb

Constant Summary collapse

VERSION =
"0.1.4"

Class Method Summary collapse

Class Method Details

.detect(series, period:, max_anoms: 0.1, alpha: 0.05, direction: "both", plot: false, verbose: false) ⇒ Object

Raises:

  • (ArgumentError)


9
10
11
12
13
14
15
16
17
18
19
20
21
22
# File 'lib/anomaly_detection.rb', line 9

def detect(series, period:, max_anoms: 0.1, alpha: 0.05, direction: "both", plot: false, verbose: false)
  raise ArgumentError, "series must contain at least 2 periods" if series.size < period * 2

  if series.is_a?(Hash)
    sorted = series.sort_by { |k, _| k }
    x = sorted.map(&:last)
  else
    x = series
  end

  res = _detect(x, period, max_anoms, alpha, direction, verbose)
  res.map! { |i| sorted[i][0] } if series.is_a?(Hash)
  res
end

.plot(series, anomalies) ⇒ Object

TODO add tooltips



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
# File 'lib/anomaly_detection.rb', line 25

def plot(series, anomalies)
  require "vega"

  data =
    if series.is_a?(Hash)
      series.map { |k, v| {x: iso8601(k), y: v, anomaly: anomalies.include?(k)} }
    else
      series.map.with_index { |v, i| {x: i, y: v, anomaly: anomalies.include?(i)} }
    end

  if series.is_a?(Hash)
    x = {field: "x", type: "temporal"}
    x["scale"] = {type: "utc"} if series.keys.first.is_a?(Date)
  else
    x = {field: "x", type: "quantitative"}
  end

  Vega.lite
    .data(data)
    .layer([
      {
        mark: {type: "line"},
        encoding: {
          x: x,
          y: {field: "y", type: "quantitative", scale: {zero: false}},
          color: {value: "#fa9088"}
        }
      },
      {
        transform: [{"filter": "datum.anomaly == true"}],
        mark: {type: "point", size: 200},
        encoding: {
          x: x,
          y: {field: "y", type: "quantitative"},
          color: {value: "#19c7ca"}
        }
      }
    ])
    .config(axis: {title: nil, labelFontSize: 12})
end