Class: Vizcore::Analysis::Smoother

Inherits:
Object
  • Object
show all
Defined in:
lib/vizcore/analysis/smoother.rb

Overview

Utility for smoothing scalar, hash, and array signals with EMA.

Instance Method Summary collapse

Constructor Details

#initialize(alpha: 0.35) ⇒ Smoother

Returns a new instance of Smoother.

Parameters:

  • alpha (Float) (defaults to: 0.35)

    default smoothing coefficient (0.0..1.0)



8
9
10
11
# File 'lib/vizcore/analysis/smoother.rb', line 8

def initialize(alpha: 0.35)
  @alpha = normalize_alpha(alpha)
  @states = {}
end

Instance Method Details

#reset(namespace = nil) ⇒ void

This method returns an undefined value.

Reset smoothing state.

Parameters:

  • namespace (Object, nil) (defaults to: nil)

    when provided, resets keys under this namespace only



57
58
59
60
61
62
63
# File 'lib/vizcore/analysis/smoother.rb', line 57

def reset(namespace = nil)
  return @states.clear if namespace.nil?

  @states.delete_if do |key, _value|
    key.is_a?(Array) && key.first == namespace
  end
end

#smooth(key, value, alpha: @alpha) ⇒ Float

Smooth one scalar value under a key.

Parameters:

  • key (Object)

    state key

  • value (Numeric)
  • alpha (Float) (defaults to: @alpha)

Returns:

  • (Float)


19
20
21
22
23
24
25
26
27
# File 'lib/vizcore/analysis/smoother.rb', line 19

def smooth(key, value, alpha: @alpha)
  normalized = Float(value)
  step = normalize_alpha(alpha)
  previous = @states[key]
  current = previous.nil? ? normalized : previous + (normalized - previous) * step
  @states[key] = current
rescue ArgumentError, TypeError
  0.0
end

#smooth_array(values, namespace:, alpha: @alpha) ⇒ Array<Float>

Smooth each value in an array independently.

Parameters:

  • values (Array)
  • namespace (Object)
  • alpha (Float) (defaults to: @alpha)

Returns:

  • (Array<Float>)


47
48
49
50
51
# File 'lib/vizcore/analysis/smoother.rb', line 47

def smooth_array(values, namespace:, alpha: @alpha)
  Array(values).each_with_index.map do |value, index|
    smooth([namespace, index], value, alpha: alpha)
  end
end

#smooth_hash(values, namespace:, alpha: @alpha) ⇒ Hash

Smooth each value in a hash independently.

Parameters:

  • values (Hash)
  • namespace (Object)
  • alpha (Float) (defaults to: @alpha)

Returns:

  • (Hash)


35
36
37
38
39
# File 'lib/vizcore/analysis/smoother.rb', line 35

def smooth_hash(values, namespace:, alpha: @alpha)
  Hash(values).each_with_object({}) do |(entry_key, value), result|
    result[entry_key] = smooth([namespace, entry_key], value, alpha: alpha)
  end
end