Module: RunningStat::Lua

Defined in:
lib/running_stat/lua/variance.rb,
lib/running_stat/lua/push_datum.rb

Constant Summary collapse

VARIANCE =

Keys:

bucket - the hash corresponding to the dataset metric

Arguments:

nothing

Effects:

nothing

Returns:

the sample variance of the dataset, as a stringified float
<<-EOLUA
  local bucket_key = KEYS[1]

  local values = redis.call("HMGET", bucket_key, "#{RedisBackend::COUNT_FIELD}", "#{RedisBackend::M2_FIELD}")
  local count = tonumber(values[1]) or 0
  if count < 2 then
    return redis.error_reply("#{InsufficientDataError::ERROR_STRING}")
  else
    local m2 = tonumber(values[2]) or 0.0
    return tostring(m2 / (count - 1))
  end
EOLUA
VARIANCE_SHA1 =
Digest::SHA1.hexdigest(VARIANCE).freeze
PUSH_DATUM =

Keys:

bucket - the hash corresponding to the dataset metric

Arguments:

datum - the number to be added to the dataset

Effects:

calculates running stats (mean, variance, std_dev)

Returns:

nothing
<<-EOLUA
  local bucket_key = KEYS[1]
  local datum = ARGV[1]

  local mean = tonumber(redis.call("HGET", bucket_key, "#{RedisBackend::MEAN_FIELD}")) or 0.0
  local delta = datum - mean

  local count = redis.call("HINCRBY", bucket_key, "#{RedisBackend::COUNT_FIELD}", 1)
  mean = redis.call("HINCRBYFLOAT", bucket_key, "#{RedisBackend::MEAN_FIELD}", tostring(delta / count))
  redis.call("HINCRBYFLOAT", bucket_key, "#{RedisBackend::M2_FIELD}", tostring(delta * (datum - mean)))
EOLUA
PUSH_DATUM_SHA1 =
Digest::SHA1.hexdigest(PUSH_DATUM).freeze