All files / detect trcf-detector.ts

100% Statements 129/129
100% Branches 48/48
100% Functions 10/10
100% Lines 129/129

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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                  1x                     1x 1x                       1x 1x 1x 1x 1x 1x 1x 1x 1x   1x 28x 28x 28x 28x 28x 28x   28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 15x 13x 28x   28x 1940x 1940x 1940x   1940x 1940x 1940x 313x 313x 313x 313x     1940x   1940x 1940x 1940x 1940x 1940x 1940x 1940x 1940x 1940x 1940x 1940x 1940x   28x 7x 7x 7x 7x 7x 7x 7x 7x 7x   28x 6x 6x 6x 6x 6x 6x 6x 3x 3x 6x   28x 3x 3x 3x 3x 3x 3x   28x 16x 16x 16x 16x 16x 16x 16x 9x 11x 7x 7x 16x   28x 1940x 1940x 1940x 7x 7x 7x 7x 1940x   28x 1940x 509x 1519x 1519x 509x 1940x   28x 1940x 1940x 1940x 1940x 1940x 509x 509x 509x 509x 509x 509x 509x 1940x 28x  
/**
 * TrcfDetector — wraps @beshu-tech/trcf-ts with attribution and drift detection.
 *
 * Supports both univariate and multivariate scenarios. Multivariate mode is
 * auto-detected when DataPoint.dimensions is present AND non-empty.
 *
 * @module detect/trcf-detector
 */
 
import {
  createTimeSeriesDetector,
  createMultiVariateDetector,
} from '@beshu-tech/trcf-ts'
import type { AnomalyDetector } from '@beshu-tech/trcf-ts'
import type {
  DataPoint,
  DetectionResult,
  DimensionAttribution,
  IDetector,
} from '../types.js'
import { DimensionAttributor } from './attribution.js'
import { DriftDetector } from './drift.js'
 
export interface TrcfDetectorConfig {
  windowSize: number
  anomalyRate: number
  numberOfTrees: number
  normalize: boolean
  attributionEnabled: boolean
  driftEnabled: boolean
  driftDetector: 'adwin' | 'kswin'
}
 
const DEFAULT_CONFIG: TrcfDetectorConfig = {
  windowSize: 256,
  anomalyRate: 0.005,
  numberOfTrees: 30,
  normalize: true,
  attributionEnabled: true,
  driftEnabled: true,
  driftDetector: 'adwin',
}
 
export class TrcfDetector implements IDetector {
  private detector: AnomalyDetector
  private config: TrcfDetectorConfig
  private attributor: DimensionAttributor | null
  private driftDetector: DriftDetector | null
  private dimensionNames: string[] = []
  private isMultivariate = false
 
  constructor(config?: Partial<TrcfDetectorConfig>) {
    this.config = { ...DEFAULT_CONFIG, ...config }
    const trcfConfig = {
      anomalyRate: this.config.anomalyRate,
      windowSize: this.config.windowSize,
      numberOfTrees: this.config.numberOfTrees,
      normalize: this.config.normalize,
    }
    this.detector = createTimeSeriesDetector(trcfConfig)
    this.attributor = this.config.attributionEnabled ? new DimensionAttributor() : null
    this.driftDetector = this.config.driftEnabled
      ? new DriftDetector(this.config.driftDetector)
      : null
  }
 
  detect(point: DataPoint, _context: DataPoint[]): DetectionResult {
    this.ensureDetectorType(point)
    const inputArray = this.toInputArray(point)
    const raw = this.detector.detect(inputArray, point.timestamp)
 
    let driftDetected = false
    let driftDetails = undefined
    if (this.driftDetector) {
      const driftResult = this.driftDetector.update(point.value)
      driftDetected = driftResult.detected
      driftDetails = driftResult.detected ? driftResult.info : undefined
    }
 
    // Compute attribution for multivariate only
    const attribution = this.computeAttribution(point, inputArray, raw.score)
 
    return {
      isAnomaly: raw.isAnomaly,
      grade: raw.grade,
      score: raw.score,
      threshold: raw.threshold,
      confidence: raw.confidence,
      attribution,
      driftDetected,
      driftDetails,
      detectedAt: Date.now(),
    }
  }
 
  getState(): Uint8Array {
    const state = {
      config: this.config,
      isMultivariate: this.isMultivariate,
      dimensionNames: this.dimensionNames,
      trcfState: this.detector.getState(),
      driftState: this.driftDetector?.getState() ?? null,
    }
    return new TextEncoder().encode(JSON.stringify(state))
  }
 
  setState(state: Uint8Array): void {
    const parsed = JSON.parse(new TextDecoder().decode(state))
    this.config = { ...DEFAULT_CONFIG, ...parsed.config }
    this.isMultivariate = parsed.isMultivariate ?? false
    this.dimensionNames = parsed.dimensionNames ?? []
    this.attributor = this.config.attributionEnabled ? new DimensionAttributor() : null
    this.recreateDetector()
    this.driftDetector = this.config.driftEnabled
      ? (parsed.driftState ? DriftDetector.fromState(parsed.driftState) : new DriftDetector(this.config.driftDetector))
      : null
  }
 
  reset(): void {
    this.isMultivariate = false
    this.dimensionNames = []
    this.recreateDetector()
    this.driftDetector?.reset()
    this.attributor = this.config.attributionEnabled ? new DimensionAttributor() : null
  }
 
  private recreateDetector(): void {
    const tc = {
      anomalyRate: this.config.anomalyRate,
      windowSize: this.config.windowSize,
      numberOfTrees: this.config.numberOfTrees,
      normalize: this.config.normalize,
    }
    if (this.isMultivariate && this.dimensionNames.length > 0) {
      this.detector = createMultiVariateDetector({ ...tc, dimensions: this.dimensionNames.length } as any)
    } else {
      this.detector = createTimeSeriesDetector(tc)
    }
  }
 
  private ensureDetectorType(point: DataPoint): void {
    const dims = point.dimensions
    const hasDims = dims !== undefined && Object.keys(dims).length > 0
    if (hasDims && !this.isMultivariate) {
      this.dimensionNames = Object.keys(dims)
      this.isMultivariate = true
      this.recreateDetector()
    }
  }
 
  private toInputArray(point: DataPoint): number[] {
    if (!this.isMultivariate || this.dimensionNames.length === 0) return [point.value]
    return this.dimensionNames.map((name) => {
      const val = point.dimensions?.[name]
      return typeof val === 'number' && Number.isFinite(val) ? val : 0
    })
  }
 
  private computeAttribution(
    point: DataPoint,
    inputArray: number[],
    baselineScore: number
  ): DimensionAttribution[] {
    if (!this.attributor || !this.isMultivariate) return []
    return this.attributor.compute(
      point,
      [] as DataPoint[],
      inputArray,
      baselineScore,
      (arr, ts) => this.detector.detect(arr, ts).score
    )
  }
}