Skip to content

Javascript

libspot has also been ported to the browser (and more generally to the js ecosystem) through webassembly thanks to emscripten.

Install

You can get the library through npm (or other package manager).

npm install libspot
yarn add libspot

You then get a typescript library that wraps the webassembly code.

Get started

import { Spot, ANOMALY } from "libspot";
import Plotly from "plotly.js-dist-min";

// Fancyness -----------------------------------------------------------------
const colors = {
  bg: "#242933",
  stream: "#88c0d0",
  threshold: "#ebcb8b",
  anomaly: "#bf616a",
  axes: "#eceff4",
};

// Plotly structures ---------------------------------------------------------
const layout = {
  plot_bgcolor: colors.bg,
  paper_bgcolor: colors.bg,
  xaxis: {
    linecolor: colors.axes,
    tickfont: {
      color: colors.axes,
      showgrid: false,
    },
  },
  yaxis: {
    linecolor: colors.axes,
    tickfont: {
      color: colors.axes,
      showgrid: false,
    },
  },
};

let stream = {
  x: [],
  y: [],
  mode: "lines",
  name: "Data",
  line: {
    color: colors.stream,
  },
};

let anomalies = {
  x: [],
  y: [],
  mode: "markers",
  name: "Anomalies",
  marker: {
    color: colors.anomaly,
  },
};

const gaussianRandom = () => {
  // N(0, 1)
  const u = 1 - Math.random(); // Converting [0,1) to (0,1]
  const v = Math.random();
  return Math.sqrt(-2.0 * Math.log(u)) * Math.cos(2.0 * Math.PI * v);
};

// Spot job ------------------------------------------------------------------
const s = new Spot({ q: 1e-6, level: level, maxExcess: 1000 });

// fit to input data
const train = Float64Array.from({ length: 20000 }, () => gaussianRandom());
s.fit(train);

// run
for (let i = 0; i < 1000; i++) {
  const x = gaussianRandom();

  stream.x.push(i);
  stream.y.push(x);

  let r = s.step(x);
  if (r === ANOMALY) {
    anomalies.x.push(i);
    anomalies.y.push(x);
  }
}

// plot
Plotly.newPlot("myDiv", [stream, anomalies], layout);