package intel import ( "math" "sort" "time" ) // Trend is the relative change from prev to cur ((cur-prev)/prev). With no // previous activity it is 0 if cur is 0 and 1 (+100%) otherwise. func Trend(cur, prev float64) float64 { if prev == 0 { if cur == 0 { return 0 } return 1 } return (cur - prev) / prev } // Spike is an hour whose volume stands out from the previous 7 days. type Spike struct { At time.Time `json:"at"` Value int `json:"value"` Baseline float64 `json:"baseline"` // median of the previous 7 days Threshold float64 `json:"threshold"` // median + 3*MAD } // Spike parameters. const ( SpikeMin = 10 spikeWindow = 7 * 24 * time.Hour spikeMinPrior = 24 maxSpikeInput = 24 * 90 ) func median(v []float64) float64 { if len(v) == 0 { return 0 } s := append([]float64(nil), v...) sort.Float64s(s) m := len(s) / 2 if len(s)%2 == 1 { return s[m] } return (s[m-1] + s[m]) / 2 } // Spikes flags hours (hourly[i] at at[i], in chronological order) whose count // exceeds median + 3*MAD of the preceding 7 days and is at least 10. An hour // needs at least 24 samples in its window to be judged. Input is capped at // 90 days. func Spikes(hourly []int, at []time.Time) []Spike { n := len(hourly) if len(at) < n { n = len(at) } if n > maxSpikeInput { hourly, at, n = hourly[n-maxSpikeInput:n], at[n-maxSpikeInput:n], maxSpikeInput } var out []Spike lo := 0 for i := 0; i < n; i++ { for lo < i && at[i].Sub(at[lo]) > spikeWindow { lo++ } if i-lo < spikeMinPrior || hourly[i] < SpikeMin { continue } w := make([]float64, 0, i-lo) for j := lo; j < i; j++ { w = append(w, float64(hourly[j])) } med := median(w) dev := make([]float64, len(w)) for k, x := range w { dev[k] = math.Abs(x - med) } thr := med + 3*median(dev) if float64(hourly[i]) > thr { out = append(out, Spike{At: at[i], Value: hourly[i], Baseline: med, Threshold: thr}) } } return out } // MTTB returns the median and 90th percentile (nearest rank) of the time from // first sighting to ban, given [first, banned] pairs. Negative spans are // ignored. func MTTB(pairs [][2]time.Time) (med, p90 time.Duration) { d := make([]float64, 0, len(pairs)) for _, p := range pairs { if x := p[1].Sub(p[0]); x >= 0 { d = append(d, float64(x)) } } if len(d) == 0 { return 0, 0 } sort.Float64s(d) med = time.Duration(median(d)) idx := int(math.Ceil(0.9*float64(len(d)))) - 1 if idx < 0 { idx = 0 } return med, time.Duration(d[idx]) } // Concentration is the share (0..1) of the total held by the top largest // entries of counts. func Concentration(counts map[string]int, top int) float64 { if top <= 0 { return 0 } v := make([]int, 0, len(counts)) total := 0 for _, c := range counts { if c > 0 { v = append(v, c) total += c } } if total == 0 { return 0 } sort.Sort(sort.Reverse(sort.IntSlice(v))) if top > len(v) { top = len(v) } s := 0 for _, c := range v[:top] { s += c } return float64(s) / float64(total) }