Class: RailsDataExplorer::Utils::DataQuantizer

Inherits:
Object
  • Object
show all
Defined in:
lib/rails_data_explorer/utils/data_quantizer.rb

Overview

Responsibilities:

* Map a large set of quantitative/temporal/geo input values to a (countable)
  smaller set – such as rounding values to some unit of precision.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(data_series, options = {}) ⇒ DataQuantizer

Returns a new instance of DataQuantizer.



14
15
16
17
18
19
20
21
22
23
24
# File 'lib/rails_data_explorer/utils/data_quantizer.rb', line 14

def initialize(data_series, options = {})
  @options = {
    nice: true,
    type: 'midtread', # 'midtread' or 'midrise'
    number_of_bins: 100, # assuming 1000px wide chart, 10px per bin
    delta: nil,
  }.merge(options)
  @data_series = data_series
  @number_of_bins = @options[:number_of_bins]
  init_attrs
end

Instance Attribute Details

#deltaObject

Returns the value of attribute delta.



12
13
14
# File 'lib/rails_data_explorer/utils/data_quantizer.rb', line 12

def delta
  @delta
end

#number_of_binsObject

Returns the value of attribute number_of_bins.



12
13
14
# File 'lib/rails_data_explorer/utils/data_quantizer.rb', line 12

def number_of_bins
  @number_of_bins
end

Instance Method Details

#init_attrsObject



26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/rails_data_explorer/utils/data_quantizer.rb', line 26

def init_attrs
  # Compute boundaries
  if @options[:nice]
    range = @data_series.max_val - @data_series.min_val
    rounding_factor = 10.0 ** Math.log10([range, GREATER_ZERO].max).floor
    @min_val = (@data_series.min_val / rounding_factor).floor * rounding_factor
    @max_val = (@data_series.max_val / rounding_factor).ceil * rounding_factor
  else
    @min_val = @data_series.min_val
    @max_val = @data_series.max_val
  end
  # Compute delta
  @delta = if @options[:delta]
    @options[:delta]
  else
    (@max_val - @min_val) / @number_of_bins.to_f
  end
end

#valuesObject



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
# File 'lib/rails_data_explorer/utils/data_quantizer.rb', line 45

def values
  @values ||= (
    case @options[:type]
    when 'midrise'
      @data_series.values.map { |e|
        index_of_quantized_value = ((e - @min_val) / @delta).round
        (
          (index_of_quantized_value * @delta) +
          (@delta / 2.0) +
          @min_val
        )
      }
    when 'midtread'
      @data_series.values.map { |e|
        index_of_quantized_value = ((e - @min_val) / [@delta, GREATER_ZERO].max).round
        (
          (index_of_quantized_value * @delta) +
          @min_val
        )
      }
    else
      raise "Handle this type: #{ @options[:type].inspect }"
    end
  )
end