mini_histogram 0.1.0

Sign up to get free protection for your applications and to get access to all the features.
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: a1d07dadd88ba1bc23f7a24c225a8a7146a657f932122e4681843478ef61ec14
4
+ data.tar.gz: fed4add367a52b8dc55f67389877ed6444413c10899c6cb1979af262aa279f7c
5
+ SHA512:
6
+ metadata.gz: 407f81d19278447ed837bf983e7794a229eefeee71d5f68f1b1b20929e755057a5047296554c84ec0af6144f2340c6d08dd1770327aa1f28633b80ca01e5e0ef
7
+ data.tar.gz: 989f6b2acc56666c9c20c9bb05944a828ed2cef0cab0fc8a54fd7aa7ebb272e2ce7bbee37ecf465d489021be07cc1777e249d54f1fb088c4ffdfc754c3dddf60
@@ -0,0 +1,8 @@
1
+ /.bundle/
2
+ /.yardoc
3
+ /_yardoc/
4
+ /coverage/
5
+ /doc/
6
+ /pkg/
7
+ /spec/reports/
8
+ /tmp/
@@ -0,0 +1,10 @@
1
+ ---
2
+ language: ruby
3
+ cache: bundler
4
+ rvm:
5
+ - 2.1
6
+ - 2.2
7
+ - 2.5
8
+ - 2.6
9
+ - 2.7.0
10
+ before_install: gem install bundler -v 2.1.2
@@ -0,0 +1,74 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ In the interest of fostering an open and welcoming environment, we as
6
+ contributors and maintainers pledge to making participation in our project and
7
+ our community a harassment-free experience for everyone, regardless of age, body
8
+ size, disability, ethnicity, gender identity and expression, level of experience,
9
+ nationality, personal appearance, race, religion, or sexual identity and
10
+ orientation.
11
+
12
+ ## Our Standards
13
+
14
+ Examples of behavior that contributes to creating a positive environment
15
+ include:
16
+
17
+ * Using welcoming and inclusive language
18
+ * Being respectful of differing viewpoints and experiences
19
+ * Gracefully accepting constructive criticism
20
+ * Focusing on what is best for the community
21
+ * Showing empathy towards other community members
22
+
23
+ Examples of unacceptable behavior by participants include:
24
+
25
+ * The use of sexualized language or imagery and unwelcome sexual attention or
26
+ advances
27
+ * Trolling, insulting/derogatory comments, and personal or political attacks
28
+ * Public or private harassment
29
+ * Publishing others' private information, such as a physical or electronic
30
+ address, without explicit permission
31
+ * Other conduct which could reasonably be considered inappropriate in a
32
+ professional setting
33
+
34
+ ## Our Responsibilities
35
+
36
+ Project maintainers are responsible for clarifying the standards of acceptable
37
+ behavior and are expected to take appropriate and fair corrective action in
38
+ response to any instances of unacceptable behavior.
39
+
40
+ Project maintainers have the right and responsibility to remove, edit, or
41
+ reject comments, commits, code, wiki edits, issues, and other contributions
42
+ that are not aligned to this Code of Conduct, or to ban temporarily or
43
+ permanently any contributor for other behaviors that they deem inappropriate,
44
+ threatening, offensive, or harmful.
45
+
46
+ ## Scope
47
+
48
+ This Code of Conduct applies both within project spaces and in public spaces
49
+ when an individual is representing the project or its community. Examples of
50
+ representing a project or community include using an official project e-mail
51
+ address, posting via an official social media account, or acting as an appointed
52
+ representative at an online or offline event. Representation of a project may be
53
+ further defined and clarified by project maintainers.
54
+
55
+ ## Enforcement
56
+
57
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be
58
+ reported by contacting the project team at richard.schneeman+foo@gmail.com. All
59
+ complaints will be reviewed and investigated and will result in a response that
60
+ is deemed necessary and appropriate to the circumstances. The project team is
61
+ obligated to maintain confidentiality with regard to the reporter of an incident.
62
+ Further details of specific enforcement policies may be posted separately.
63
+
64
+ Project maintainers who do not follow or enforce the Code of Conduct in good
65
+ faith may face temporary or permanent repercussions as determined by other
66
+ members of the project's leadership.
67
+
68
+ ## Attribution
69
+
70
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
71
+ available at [https://contributor-covenant.org/version/1/4][version]
72
+
73
+ [homepage]: https://contributor-covenant.org
74
+ [version]: https://contributor-covenant.org/version/1/4/
data/Gemfile ADDED
@@ -0,0 +1,7 @@
1
+ source "https://rubygems.org"
2
+
3
+ # Specify your gem's dependencies in mini_histogram.gemspec
4
+ gemspec
5
+
6
+ gem "rake", "~> 12.0"
7
+ gem "minitest", "~> 5.0"
@@ -0,0 +1,26 @@
1
+ PATH
2
+ remote: .
3
+ specs:
4
+ mini_histogram (0.1.0)
5
+
6
+ GEM
7
+ remote: https://rubygems.org/
8
+ specs:
9
+ m (1.5.1)
10
+ method_source (>= 0.6.7)
11
+ rake (>= 0.9.2.2)
12
+ method_source (0.9.2)
13
+ minitest (5.14.0)
14
+ rake (12.3.3)
15
+
16
+ PLATFORMS
17
+ ruby
18
+
19
+ DEPENDENCIES
20
+ m
21
+ mini_histogram!
22
+ minitest (~> 5.0)
23
+ rake (~> 12.0)
24
+
25
+ BUNDLED WITH
26
+ 2.1.2
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2020 schneems
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
@@ -0,0 +1,61 @@
1
+ # MiniHistogram
2
+
3
+ What's a histogram and why should you care? First read [Lies, Damned Lies, and Averages: Perc50, Perc95 explained for Programmers](https://schneems.com/2020/03/17/lies-damned-lies-and-averages-perc50-perc95-explained-for-programmers/). This library lets you build histograms in pure Ruby.
4
+
5
+ ## Installation
6
+
7
+ Add this line to your application's Gemfile:
8
+
9
+ ```ruby
10
+ gem 'mini_histogram'
11
+ ```
12
+
13
+ And then execute:
14
+
15
+ $ bundle install
16
+
17
+ Or install it yourself as:
18
+
19
+ $ gem install mini_histogram
20
+
21
+ ## Usage
22
+
23
+ Given an array, this class calculates the "edges" of a histogram these edges mark the boundries for "bins"
24
+
25
+ ```ruby
26
+ array = [1,1,1, 5, 5, 5, 5, 10, 10, 10]
27
+ histogram = MiniHistogram.new(array)
28
+ puts histogram.edges
29
+ # => [0.0, 2.0, 4.0, 6.0, 8.0, 10.0, 12.0]
30
+ ```
31
+
32
+ It also finds the weights (aka count of values) that would go in each bin:
33
+
34
+ ```
35
+ puts histogram.weights
36
+ # => [3, 0, 4, 0, 0, 3]
37
+ ```
38
+
39
+ This means that the `array` here had three items between 0.0 and 2.0, four items between 4.0 and 6.0 and three items between 10.0 and 12.0
40
+
41
+ Alternatives to this gem include https://github.com/mrkn/enumerable-statistics/. I needed this gem to be able to calculate a "shared" or "average" edge value as seen in this PR https://github.com/mrkn/enumerable-statistics/pull/23. So that I could add histograms to derailed benchmarks: https://github.com/schneems/derailed_benchmarks/pull/169. This gem provides a `MiniHistogram.set_average_edges!` method to help there. Also this gem does not require a native extension compilation (faster to install, but performance is slower), and this gem does not extend or monkeypatch an core classes.
42
+
43
+ [MiniHistogram API Docs](https://rubydoc.info/github/zombocom/mini_histogram/master/MiniHistogram)
44
+
45
+ ## Development
46
+
47
+ After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake test` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
48
+
49
+ To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and tags, and push the `.gem` file to [rubygems.org](https://rubygems.org).
50
+
51
+ ## Contributing
52
+
53
+ Bug reports and pull requests are welcome on GitHub at https://github.com/zombocom/mini_histogram. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [code of conduct](https://github.com/zombocom/mini_histogram/blob/master/CODE_OF_CONDUCT.md).
54
+
55
+ ## License
56
+
57
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
58
+
59
+ ## Code of Conduct
60
+
61
+ Everyone interacting in the MiniHistogram project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/zombocom/mini_histogram/blob/master/CODE_OF_CONDUCT.md).
@@ -0,0 +1,37 @@
1
+ require "bundler/gem_tasks"
2
+ require "rake/testtask"
3
+
4
+ $LOAD_PATH.unshift File.expand_path("./lib", __dir__)
5
+
6
+ Rake::TestTask.new(:test) do |t|
7
+ t.libs << "test"
8
+ t.libs << "lib"
9
+ t.test_files = FileList["test/**/*_test.rb"]
10
+ end
11
+
12
+ task :default => :test
13
+
14
+
15
+ task :bench do
16
+ require 'benchmark/ips'
17
+ require 'enumerable/statistics'
18
+ require 'mini_histogram'
19
+
20
+ array = 1000.times.map { rand }
21
+
22
+ edges = MiniHistogram.edges(array)
23
+ my_weights = MiniHistogram.counts_from_edges(array, edges: edges)
24
+ puts array.histogram.weights == my_weights
25
+ puts array.histogram.weights.inspect
26
+ puts my_weights.inspect
27
+
28
+
29
+ Benchmark.ips do |x|
30
+ x.report("enumerable stats") { array.histogram }
31
+ x.report("mini histogram ") {
32
+ edges = MiniHistogram.edges(array)
33
+ MiniHistogram.counts_from_edges(array, edges: edges)
34
+ }
35
+ x.compare!
36
+ end
37
+ end
@@ -0,0 +1,14 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require "bundler/setup"
4
+ require "mini_histogram"
5
+
6
+ # You can add fixtures and/or initialization code here to make experimenting
7
+ # with your gem easier. You can also use a different console, if you like.
8
+
9
+ # (If you use this, don't forget to add pry to your Gemfile!)
10
+ # require "pry"
11
+ # Pry.start
12
+
13
+ require "irb"
14
+ IRB.start(__FILE__)
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+ IFS=$'\n\t'
4
+ set -vx
5
+
6
+ bundle install
7
+
8
+ # Do any other automated setup that you need to do here
@@ -0,0 +1,209 @@
1
+ require "mini_histogram/version"
2
+ require 'math'
3
+
4
+ # A class for building histogram info
5
+ #
6
+ # Given an array, this class calculates the "edges" of a histogram
7
+ # these edges mark the boundries for "bins"
8
+ #
9
+ # array = [1,1,1, 5, 5, 5, 5, 10, 10, 10]
10
+ # histogram = MiniHistogram.new(array)
11
+ # puts histogram.edges
12
+ # # => [0.0, 2.0, 4.0, 6.0, 8.0, 10.0, 12.0]
13
+ #
14
+ # It also finds the weights (aka count of values) that would go in each bin:
15
+ #
16
+ # puts histogram.weights
17
+ # # => [3, 0, 4, 0, 0, 3]
18
+ #
19
+ # This means that the `array` here had three items between 0.0 and 2.0.
20
+ #
21
+ class MiniHistogram
22
+ class Error < StandardError; end
23
+ attr_reader :array, :left_p
24
+
25
+ def initialize(array, left_p: false, edges: nil)
26
+ @array = array
27
+ @left_p = left_p
28
+ @edges = edges
29
+ @weights = nil
30
+ end
31
+
32
+ def edges_min
33
+ edges.min
34
+ end
35
+
36
+ def edges_max
37
+ edges.max
38
+ end
39
+
40
+ # Sets the edge value to something new,
41
+ # also clears any previously calculated values
42
+ def set_edges(value)
43
+ @edges = value
44
+ @weights = nil # clear memoized value
45
+ end
46
+
47
+ def bin_size
48
+ edges[1] - edges[0]
49
+ end
50
+
51
+ # Weird name, right? There are multiple ways to
52
+ # calculate the number of "bins" a histogram should have, one
53
+ # of the most common is the "sturges" method
54
+ #
55
+ # Here are some alternatives from numpy:
56
+ # https://github.com/numpy/numpy/blob/d9b1e32cb8ef90d6b4a47853241db2a28146a57d/numpy/lib/histograms.py#L489-L521
57
+ def sturges
58
+ len = array.length
59
+ return 1.0 if len == 0
60
+
61
+ # return (long)(ceil(Math.log2(n)) + 1);
62
+ return Math.log2(len).ceil + 1
63
+ end
64
+
65
+ # Given an array of edges and an array we want to generate a histogram from
66
+ # return the counts for each "bin"
67
+ #
68
+ # Example:
69
+ #
70
+ # a = [1,1,1, 5, 5, 5, 5, 10, 10, 10]
71
+ # edges = [0.0, 2.0, 4.0, 6.0, 8.0, 10.0, 12.0]
72
+ #
73
+ # MiniHistogram.new(a).weights
74
+ # # => [3, 0, 4, 0, 0, 3]
75
+ #
76
+ # This means that the `a` array has 3 values between 0.0 and 2.0
77
+ # 4 values between 4.0 and 6.0 and three values between 10.0 and 12.0
78
+ def weights
79
+ return @weights if @weights
80
+
81
+ lo = edges.first
82
+ step = edges[1] - edges[0]
83
+
84
+ max_index = ((array.max - lo) / step).floor
85
+ @weights = Array.new(max_index + 1, 0)
86
+
87
+ array.each do |x|
88
+ index = ((x - lo) / step).floor
89
+ @weights[index] += 1
90
+ end
91
+
92
+ return @weights
93
+ end
94
+
95
+ # Finds the "edges" of a given histogram that will mark the boundries
96
+ # for the histogram's "bins"
97
+ #
98
+ # Example:
99
+ #
100
+ # a = [1,1,1, 5, 5, 5, 5, 10, 10, 10]
101
+ # MiniHistogram.new(a).edges
102
+ # # => [0.0, 2.0, 4.0, 6.0, 8.0, 10.0, 12.0]
103
+ #
104
+ # There are multiple ways to find edges, this was taken from
105
+ # https://github.com/mrkn/enumerable-statistics/issues/24
106
+ #
107
+ # Another good set of implementations is in numpy
108
+ # https://github.com/numpy/numpy/blob/d9b1e32cb8ef90d6b4a47853241db2a28146a57d/numpy/lib/histograms.py#L222
109
+ def edges
110
+ return @edges if @edges
111
+
112
+ hi = array.max
113
+ lo = array.min
114
+
115
+ nbins = sturges * 1.0
116
+
117
+ if hi == lo
118
+ start = hi
119
+ step = 1.0
120
+ divisor = 1.0
121
+ len = 1.0
122
+ else
123
+ bw = (hi - lo) / nbins
124
+ lbw = Math.log10(bw)
125
+ if lbw >= 0
126
+ step = 10 ** lbw.floor * 1.0
127
+ r = bw/step
128
+
129
+ if r <= 1.1
130
+ # do nothing
131
+ elsif r <= 2.2
132
+ step *= 2.0
133
+ elsif r <= 5.5
134
+ step *= 5.0
135
+ else
136
+ step *= 10
137
+ end
138
+ divisor = 1.0
139
+ start = step * (lo/step).floor
140
+ len = ((hi - start)/step).ceil
141
+ else
142
+ divisor = 10 ** - lbw.floor
143
+ r = bw * divisor
144
+ if r <= 1.1
145
+ # do nothing
146
+ elsif r <= 2.2
147
+ divisor /= 2.0
148
+ elsif r <= 5.5
149
+ divisor /= 5.0
150
+ else
151
+ divisor /= 10.0
152
+ end
153
+ step = 1.0
154
+ start = (lo * divisor).floor
155
+ len = (hi * divisor - start).ceil
156
+ end
157
+
158
+ if left_p
159
+ while (lo < start/divisor)
160
+ start -= step
161
+ end
162
+
163
+ while (start + (len - 1)*step)/divisor <= hi
164
+ len += 1
165
+ end
166
+ else
167
+ while lo <= start/divisor
168
+ start -= step
169
+ end
170
+ while (start + (len - 1)*step)/divisor < hi
171
+ len += 1
172
+ end
173
+ end
174
+
175
+ @edges = []
176
+ len.next.times.each do
177
+ @edges << start/divisor
178
+ start += step
179
+ end
180
+ return @edges
181
+ end
182
+ end
183
+
184
+ # Given an array of Histograms this function calcualtes
185
+ # an average edge size along with the minimum and maximum
186
+ # edge values. It then updates the edge value on all inputs
187
+ #
188
+ # The main pourpose of this method is to be able to chart multiple
189
+ # distributions against a similar axis
190
+ #
191
+ # See for more context: https://github.com/schneems/derailed_benchmarks/pull/169
192
+ def self.set_average_edges!(*array_of_histograms)
193
+ array_of_histograms.each { |x| raise "Input expected to be a histogram but is #{x.inspect}" unless x.is_a?(MiniHistogram) }
194
+ steps = array_of_histograms.map(&:bin_size)
195
+ avg_step_size = steps.inject(&:+).to_f / steps.length
196
+
197
+ max_edge = array_of_histograms.map(&:edges_max).max
198
+ min_edge = array_of_histograms.map(&:edges_min).min
199
+
200
+ average_edges = [min_edge]
201
+ while average_edges.last < max_edge
202
+ average_edges << average_edges.last + avg_step_size
203
+ end
204
+
205
+ array_of_histograms.each {|h| h.set_edges(average_edges) }
206
+
207
+ return array_of_histograms
208
+ end
209
+ end
@@ -0,0 +1,3 @@
1
+ class MiniHistogram
2
+ VERSION = "0.1.0"
3
+ end
@@ -0,0 +1,29 @@
1
+ require_relative 'lib/mini_histogram/version'
2
+
3
+ Gem::Specification.new do |spec|
4
+ spec.name = "mini_histogram"
5
+ spec.version = MiniHistogram::VERSION
6
+ spec.authors = ["schneems"]
7
+ spec.email = ["richard.schneeman+foo@gmail.com"]
8
+
9
+ spec.summary = %q{A small gem for building histograms out of Ruby arrays}
10
+ spec.description = %q{It makes histograms out of Ruby data. How cool is that!? Pretty cool if you ask me.}
11
+ spec.homepage = "https://github.com/zombocom/mini_histogram"
12
+ spec.license = "MIT"
13
+ spec.required_ruby_version = Gem::Requirement.new(">= 2.1.0")
14
+
15
+ spec.metadata["homepage_uri"] = spec.homepage
16
+ # spec.metadata["source_code_uri"] = "blerg"
17
+ # spec.metadata["changelog_uri"] = "blerg"
18
+
19
+ # Specify which files should be added to the gem when it is released.
20
+ # The `git ls-files -z` loads the files in the RubyGem that have been added into git.
21
+ spec.files = Dir.chdir(File.expand_path('..', __FILE__)) do
22
+ `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
23
+ end
24
+ spec.bindir = "exe"
25
+ spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
26
+ spec.require_paths = ["lib"]
27
+
28
+ spec.add_development_dependency "m"
29
+ end
metadata ADDED
@@ -0,0 +1,72 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: mini_histogram
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - schneems
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2020-03-21 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: m
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - ">="
18
+ - !ruby/object:Gem::Version
19
+ version: '0'
20
+ type: :development
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - ">="
25
+ - !ruby/object:Gem::Version
26
+ version: '0'
27
+ description: It makes histograms out of Ruby data. How cool is that!? Pretty cool
28
+ if you ask me.
29
+ email:
30
+ - richard.schneeman+foo@gmail.com
31
+ executables: []
32
+ extensions: []
33
+ extra_rdoc_files: []
34
+ files:
35
+ - ".gitignore"
36
+ - ".travis.yml"
37
+ - CODE_OF_CONDUCT.md
38
+ - Gemfile
39
+ - Gemfile.lock
40
+ - LICENSE.txt
41
+ - README.md
42
+ - Rakefile
43
+ - bin/console
44
+ - bin/setup
45
+ - lib/mini_histogram.rb
46
+ - lib/mini_histogram/version.rb
47
+ - mini_histogram.gemspec
48
+ homepage: https://github.com/zombocom/mini_histogram
49
+ licenses:
50
+ - MIT
51
+ metadata:
52
+ homepage_uri: https://github.com/zombocom/mini_histogram
53
+ post_install_message:
54
+ rdoc_options: []
55
+ require_paths:
56
+ - lib
57
+ required_ruby_version: !ruby/object:Gem::Requirement
58
+ requirements:
59
+ - - ">="
60
+ - !ruby/object:Gem::Version
61
+ version: 2.1.0
62
+ required_rubygems_version: !ruby/object:Gem::Requirement
63
+ requirements:
64
+ - - ">="
65
+ - !ruby/object:Gem::Version
66
+ version: '0'
67
+ requirements: []
68
+ rubygems_version: 3.1.2
69
+ signing_key:
70
+ specification_version: 4
71
+ summary: A small gem for building histograms out of Ruby arrays
72
+ test_files: []