Class: RunningStat

Inherits:
Object
  • Object
show all
Defined in:
lib/running_stat.rb,
lib/running_stat/version.rb,
lib/running_stat/lua/variance.rb,
lib/running_stat/redis_backend.rb,
lib/running_stat/lua/push_datum.rb,
lib/running_stat/invalid_data_error.rb,
lib/running_stat/insufficient_data_error.rb

Defined Under Namespace

Modules: Lua, RedisBackend Classes: InsufficientDataError, InvalidDataError

Constant Summary collapse

BASE_KEY =
'running_stat:v1'
VERSION =
'0.1.0'

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(data_bucket, opts = {}) ⇒ RunningStat

Returns a new instance of RunningStat.



19
20
21
22
# File 'lib/running_stat.rb', line 19

def initialize(data_bucket, opts = {})
  @data_bucket = data_bucket
  @redis = opts[:redis]
end

Class Method Details

.instance(data_bucket, opts = {}) ⇒ Object

Returns an instance of RunningStat for the given dataset



15
16
17
# File 'lib/running_stat.rb', line 15

def self.instance(data_bucket, opts = {})
  new(data_bucket, opts)
end

Instance Method Details

#cardinalityObject

Returns the number of data points seen, or 0 if the stat does not exist



32
33
34
# File 'lib/running_stat.rb', line 32

def cardinality
  redis.hget(bucket_key, RedisBackend::COUNT_FIELD).to_i
end

#flushObject

Resets the stat to reflect an empty dataset



58
59
60
# File 'lib/running_stat.rb', line 58

def flush
  redis.del(bucket_key)
end

#meanObject

Returns the arithmetic mean of data points seen, or 0.0 if non-existent



37
38
39
# File 'lib/running_stat.rb', line 37

def mean
  redis.hget(bucket_key, RedisBackend::MEAN_FIELD).to_f
end

#push(datum) ⇒ Object

Adds a piece of numerical data to the dataset’s stats



25
26
27
28
29
# File 'lib/running_stat.rb', line 25

def push(datum)
  redis.eval(Lua::PUSH_DATUM, [bucket_key], [Float(datum)])
rescue ArgumentError => e
  raise InvalidDataError.new(e)  # datum was non-numerical
end

#std_devObject

Returns the standard deviation of the dataset so far, or raises an InsufficientDataError if insufficient data (< 2 datapoints) has been pushed



53
54
55
# File 'lib/running_stat.rb', line 53

def std_dev
  Math.sqrt(variance)
end

#varianceObject

Returns the sample variance of the dataset so far, or raises an InsufficientDataError if insufficient data (< 2 datapoints) has been pushed



44
45
46
47
48
# File 'lib/running_stat.rb', line 44

def variance
  redis.eval(Lua::VARIANCE, [bucket_key], []).to_f
rescue Redis::CommandError => e
  raise InsufficientDataError.new(e)  # only CommandError possible
end