Class: ToHistogram::Bucketizer

Inherits:
Object
  • Object
show all
Defined in:
lib/bucketizer.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(array, num_buckets: 20, bucket_width: 'auto', percentile: 100) ⇒ Bucketizer

Returns a new instance of Bucketizer.



7
8
9
10
11
12
13
14
# File 'lib/bucketizer.rb', line 7

def initialize(array, num_buckets: 20, bucket_width: 'auto', percentile: 100)
  @arr                = prepare_data(array)
  @num_buckets        = num_buckets
  @percentile         = percentile

  remove_elements_outside_of_percentile
  @bucket_width  = (bucket_width == 'auto') ? get_bucket_increment : bucket_width
end

Instance Attribute Details

#bucket_widthObject (readonly)

Returns the value of attribute bucket_width.



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

def bucket_width
  @bucket_width
end

Instance Method Details

#create_bucketsObject



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/bucketizer.rb', line 17

def create_buckets
  l_index               = 0
  last_bucket           = @arr[0]
  next_bucket           = get_initial_next_bucket(@bucket_width)
  buckets               = []

  # Deal with the special case where we have elements that == 0 and an increment sizes of 1 (count 0 as a value and don't lump it in with 1)
  if(@arr.count(0) > 0 && next_bucket == 1)
    bucket_0 = []
    @arr.count(0).times { bucket_0 << @arr.shift }
    buckets << Bucket.new(0, 0, bucket_0)

    last_bucket = 1
    next_bucket = 2
  end

  # Iterate thorough the remainder of the list in the normal case
  @arr.each_with_index do |e, i|
    break if buckets.length == (@num_buckets - 1)

    if (e >= next_bucket)
      buckets << Bucket.new(last_bucket, next_bucket - 1, @arr[l_index..(i - 1)])

      # Special case here also where all of the results fit into the first bucket
      if buckets[0].contents.length == @arr.length
        l_index = (@arr.length)
        break
      end

      l_index = i
      last_bucket = next_bucket
      next_bucket += @bucket_width

      # Add empty buckets until the next bucket is greater than the current l_index
      while(next_bucket < @arr[l_index])

        buckets << Bucket.new(last_bucket, next_bucket - 1, [])
        last_bucket = next_bucket
        next_bucket += @bucket_width
      end
    end
  end

  # Stuff the remainder into the last bucket
  if(l_index <= (@arr.length - 1))
    buckets << Bucket.new(last_bucket, next_bucket - 1, @arr[l_index..(@arr.length - 1)])
  end

  return buckets
end