Histograffle

A sort of histogram object implemented in pure Ruby. Use it to count the occurrence of each of several things.

Simple example of its use and abuse

I am not a matematician, so this is not a mathematical library or explaination.

Sample use case: We have two lists of words, and want to count the occurrence of each word in the lists, first separately, and then together.


require 'rubygems'
require 'histograffle'

include Histograffle

reported_incidents = %w[rain thunder confusion fun rain rain theft]

hist_one = Histogram.new

hist_one.eat(reported_incidents)

hist_one.ladder.each do |count|
  puts "#{count}: #{hist_one[count].join(', ')}"
end

hist_two = Histogram.new

unreported_incidents = %w[monkey pig concert ufo airplane pig pig concert]

hist_two.eat(unreported_incidents)

hist_one << hist_two

API quickref

Histograffle::Histogram.new([serialized_data]) Create new instance.
hist.eat(item_or_array_or_histogram) Add the input. You can add histograms together this way.
hist[n] Return the occurrences of which there are n.
hist.distribution[n] Return the occurrences of which there are n.
hist.distribution Descending list of occurrence counts.
hist.ladder Ascending list of occurrence counts.
hist.top(n) Return the top n entries as a hash like {12 => 'a_word', 2 => 'some other word'}.
hist.flat_top(n) Same as above, return only a list of words with no differentiations.
hist << other_hist Add a histogram to another.
hist == other_hist True when they contain counts of the same entries.

There is also .to_mongo and .from_mongo serialization support.

To get copies of the raw data tables (see below), you use hist.data and hist.lookup.

Implementation

Each instance stores its data internally, in two hashes, quite simply. The data hash keys occurrences to counts. The lookup hash keys counts to occurrences. Occurrences can be any object.

Credit

LICENSE

(MIT License)

Copyright © 2009 Jostein Berre Eliassen

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the ‘Software’), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED ‘AS IS’, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.