categorical_distribution 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA1:
3
+ metadata.gz: 53bacc10077bb5dc4e4662c482f5f7e998574704
4
+ data.tar.gz: 096ebc9b023c6b842bbe60b1ef6fab7f412d0521
5
+ SHA512:
6
+ metadata.gz: 296d5956f4d2dcf59d032fb6f10f809407e27aeb6557d9949a60fc76abc8f459618890a9d3d303f9ac57e167d61a0f72e97fedce6b992b10cb9a011326a12aab
7
+ data.tar.gz: e1de5a78bc59289acf47978b1a0010b95841cd33349f839cd4ba62e6f8f24b5e82d05ba2f9061bf04a3e9594b170968887b0b5365da1a091028287126883b6fe
data/.gitignore ADDED
@@ -0,0 +1,9 @@
1
+ /.bundle/
2
+ /.yardoc
3
+ /Gemfile.lock
4
+ /_yardoc/
5
+ /coverage/
6
+ /doc/
7
+ /pkg/
8
+ /spec/reports/
9
+ /tmp/
data/.travis.yml ADDED
@@ -0,0 +1,5 @@
1
+ sudo: false
2
+ language: ruby
3
+ rvm:
4
+ - 2.2.5
5
+ before_install: gem install bundler -v 1.13.1
data/Gemfile ADDED
@@ -0,0 +1,4 @@
1
+ source 'https://rubygems.org'
2
+
3
+ # Specify your gem's dependencies in categorical_distribution.gemspec
4
+ gemspec
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2016 Zane Geiger
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.
data/README.md ADDED
@@ -0,0 +1,55 @@
1
+ # CategoricalDistribution
2
+
3
+ This gem provides an implementation of a [categorical distribution](https://en.wikipedia.org/wiki/Categorical_distribution) using [Vose's Alias Method](https://en.wikipedia.org/wiki/Allas_method). More details on the implementation can be found [here](http://www.keithschwarz.com/darts-dice-coins).
4
+ The algorithm chooses a random item, with a weighted probability given on initialization, in constant time, after an O(n) initialization step.
5
+
6
+ ## Installation
7
+
8
+ Add this line to your application's Gemfile:
9
+
10
+ ```ruby
11
+ gem 'categorical_distribution'
12
+ ```
13
+
14
+ And then execute:
15
+
16
+ $ bundle
17
+
18
+ Or install it yourself as:
19
+
20
+ $ gem install categorical_distribution
21
+
22
+ ## Usage
23
+
24
+ r = CategoricalDistribution.new({ a: 1, b: 2, c: 3 })
25
+ r.rand #=> :a
26
+ r.rand #=> :b
27
+ r.rand #=> :c
28
+ r.rand #=> :c
29
+ r.rand #=> :b
30
+
31
+ r = CategoricalDistribution.new([1, 1, 1])
32
+ r.take(5) #=> [1, 2, 1, 1, 2]
33
+
34
+ r = CategoricalDistribution.new([1, 3], ['heads', 'tails'])
35
+ r.rand #=> "tails"
36
+ r.rand #=> "tails"
37
+ r.rand #=> "tails"
38
+ r.rand #=> "tails"
39
+ r.rand #=> "heads"
40
+
41
+ ## Development
42
+
43
+ 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.
44
+
45
+ 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).
46
+
47
+ ## Contributing
48
+
49
+ Bug reports and pull requests are welcome on GitHub at https://github.com/zanecodes/categorical_distribution.
50
+
51
+
52
+ ## License
53
+
54
+ The gem is available as open source under the terms of the [MIT License](http://opensource.org/licenses/MIT).
55
+
data/Rakefile ADDED
@@ -0,0 +1,10 @@
1
+ require "bundler/gem_tasks"
2
+ require "rake/testtask"
3
+
4
+ Rake::TestTask.new(:test) do |t|
5
+ t.libs << "test"
6
+ t.libs << "lib"
7
+ t.test_files = FileList['test/**/*_test.rb']
8
+ end
9
+
10
+ task :default => :test
data/bin/console ADDED
@@ -0,0 +1,14 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require "bundler/setup"
4
+ require "categorical_distribution"
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
data/bin/setup ADDED
@@ -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,26 @@
1
+ # coding: utf-8
2
+ lib = File.expand_path('../lib', __FILE__)
3
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
4
+ require 'categorical_distribution/version'
5
+
6
+ Gem::Specification.new do |spec|
7
+ spec.name = "categorical_distribution"
8
+ spec.version = CategoricalDistribution::VERSION
9
+ spec.authors = ["Zane Geiger"]
10
+ spec.email = ["zanecodes@gmail.com"]
11
+
12
+ spec.summary = "Generates values from a categorical probability distribution in O(1) using Vose's Alias Method."
13
+ spec.homepage = "https://github.com/zanecodes/categorical_distribution"
14
+ spec.license = "MIT"
15
+
16
+ spec.files = `git ls-files -z`.split("\x0").reject do |f|
17
+ f.match(%r{^(test|spec|features)/})
18
+ end
19
+ spec.bindir = "exe"
20
+ spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
21
+ spec.require_paths = ["lib"]
22
+
23
+ spec.add_development_dependency "bundler", "~> 1.13"
24
+ spec.add_development_dependency "rake", "~> 10.0"
25
+ spec.add_development_dependency "minitest", "~> 5.0"
26
+ end
@@ -0,0 +1,3 @@
1
+ module CategoricalDistribution
2
+ VERSION = "0.1.0"
3
+ end
@@ -0,0 +1,211 @@
1
+ require 'forwardable'
2
+
3
+ # Generate values from a categorical probability distribution in constant time.
4
+ # Uses Vose's Alias Method to construct a table of probabilities and aliases.
5
+ # To generate a value, we pick an entry in the distribution at random, and then pick
6
+ # either the value or the alias, using a biased coin flip.
7
+ #
8
+ # Table construction is O(n), index generation is O(1).
9
+ #
10
+ # See http://www.keithschwarz.com/darts-dice-coins for a detailed explanation.
11
+
12
+ class CategoricalDistribution
13
+ extend Forwardable
14
+ include Enumerable
15
+
16
+
17
+ # :call-seq:
18
+ # CategoricalDistribution.new(p={})
19
+ # CategoricalDistribution.new(p=[])
20
+ # CategoricalDistribution.new(p=[], values=[])
21
+ #
22
+ # Constructs a categorical random distribution from a set of probabilities
23
+ # and, optionally, values.
24
+ #
25
+ # These can be passed as an array of probabilities and an array of values,
26
+ # or as a hash of values to probabilities.
27
+ #
28
+ # If necessary, probabilities will be normalized so that they sum to one.
29
+ # If no values are provided, they will default to the respective indices of
30
+ # each probability.
31
+ #
32
+ # Raises an +ArgumentError+ if any probability is negative.
33
+ #
34
+ # CategoricalDistribution.new
35
+ # #=> {}
36
+ #
37
+ # CategoricalDistribution.new([Rational(1, 5), Rational(4, 5)])
38
+ # #=> {0 => (1/5), 1 => (4/5)}
39
+ #
40
+ # CategoricalDistribution.new([1, 1, 1])
41
+ # #=> {0 => (1/3), 1 => (1/3), 2 => (1/3)}
42
+ #
43
+ # CategoricalDistribution.new([1, 1, 1], [:a, :b, :c])
44
+ # #=> {:a => (1/3), :b => (1/3), :c => (1/3)}
45
+ #
46
+ # CategoricalDistribution.new({a: 1, b: 2, c: 3})
47
+ # #=> {:a => (1/6), :b => (1/3), :c => (1/2)}
48
+
49
+ def initialize(p={}, values=nil)
50
+ if p.respond_to?(:keys) && p.respond_to?(:values)
51
+ values, p = p.keys, p.values
52
+ else
53
+ values ||= p.each_index.to_a
54
+ end
55
+
56
+ raise ArgumentError, 'probabilities must be positive' if p.any? { |value| value < 0 }
57
+
58
+ sum = p.reduce(:+)
59
+ p.map! { |value| Rational(value, sum) } unless sum == 1
60
+
61
+ @p = Hash[[values, p].transpose].freeze
62
+
63
+ n = p.size
64
+ @prob = Array.new(n, Rational(1))
65
+ @alias = Array.new(n)
66
+
67
+ p.map! { |value| value * n }
68
+
69
+ small, large = p.each_index.partition { |i| p[i] < 1 }
70
+
71
+ until small.empty?
72
+ l = small.pop
73
+ g = large.pop
74
+
75
+ @prob[l] = p[l]
76
+ @alias[l] = g
77
+
78
+ p[g] -= 1 - p[l]
79
+ (p[g] < 1 ? small : large) << g
80
+ end
81
+ end
82
+
83
+
84
+ # :call-seq:
85
+ # distribution.rand -> obj or nil
86
+ # distribution.rand(random: rng) -> obj or nil
87
+ #
88
+ # Return a value from the probability distribution, or +nil+ if it is empty.
89
+ #
90
+ # The optional rng argument will be used as the random number generator.
91
+ #
92
+ # distribution = CategoricalDistribution.new({a: 1, b: 2, c: 3})
93
+ # distribution.rand #=> :b
94
+ # distribution.rand #=> :c
95
+ # distribution.rand #=> :c
96
+
97
+ def rand(random: Random)
98
+ return if @prob.empty?
99
+
100
+ i = random.rand(@prob.size)
101
+ random.rand <= @prob[i] ? @p.keys[i] : @p.keys[@alias[i]]
102
+ end
103
+
104
+
105
+ # :call-seq:
106
+ # distribution.each { |item| block } -> nil
107
+ # distribution.each -> Enumerator
108
+ #
109
+ # Calls the given block infinitely many times, passing a value from the
110
+ # distribution as a parameter.
111
+ #
112
+ # An Enumerator is returned if no block is given.
113
+ #
114
+ # distribution = CategoricalDistribution.new([1, 2, 3])
115
+ # distribution.each { |x| print x, " -- " }
116
+ #
117
+ # produces:
118
+ #
119
+ # 1 -- 2 -- 2 -- 0 -- 1 -- ...
120
+
121
+ def each(random: Random)
122
+ return enum_for(:each) unless block_given?
123
+
124
+ loop { yield rand } unless empty?
125
+ end
126
+
127
+
128
+ # Returns the distribution's values and their probabilities, as a hash of
129
+ # objects to Rationals which sum to one, or an empty hash if the distribution is empty.
130
+ #
131
+ # CategoricalDistribution.new([1, 1, 1]).probabilities
132
+ # #=> {0 => (1/3), 1 => (1/3), 2 => (1/3)}
133
+ #
134
+ # CategoricalDistribution.new.probabilities
135
+ # #=> {}
136
+
137
+ def probabilities
138
+ @p
139
+ end
140
+
141
+
142
+ # :call_seq:
143
+ # distribution == other_distribution -> bool
144
+ #
145
+ # Equality --- Two probability distributions are equal if they contain the
146
+ # same values and if each value has the same probability as the corresponding
147
+ # value in other_distribution.
148
+ #
149
+ # CategoricalDistribution.new([1, 2]) == CategoricalDistribution.new([1, 2, 3])
150
+ # #=> false
151
+ #
152
+ # CategoricalDistribution.new([1, 2, 3]) == CategoricalDistribution.new([1, 2, 3])
153
+ # #=> true
154
+ #
155
+ # CategoricalDistribution.new([1, 2, 3]) == CategoricalDistribution.new([1, 1, 1])
156
+ # #=> false
157
+ #
158
+ # CategoricalDistribution.new([1, 2], [:a, :b]) == CategoricalDistribution.new([1, 2], [:a, :c])
159
+ # #=> false
160
+
161
+ def ==(other)
162
+ self.probabilities == other.probabilities
163
+ end
164
+
165
+
166
+ # :call_seq:
167
+ # distribution.eql?(other) -> true or false
168
+ #
169
+ # Returns true if self and other are the same object, or are both probability
170
+ # distributions with the same values and probabilities.
171
+
172
+ def eql?(other)
173
+ self.equal?(other) ||
174
+ (self.class == other.class && self.probabilities == other.probabilities)
175
+ end
176
+
177
+
178
+ def_delegators :@p, :empty?, :hash, :length, :size, :to_s
179
+
180
+ ##
181
+ # :method: empty?
182
+ # :call_seq:
183
+ # distribution.empty? -> true or false
184
+ #
185
+ # Returns true if self contains no values.
186
+ #
187
+ # distribution = CategoricalDistribution.new
188
+ # distribution.empty? #=> true
189
+
190
+ ##
191
+ # :method: hash
192
+ # :call_seq:
193
+ # distribution.hash -> fixnum
194
+ #
195
+ # Compute a hash-code for this probability distribution.
196
+ #
197
+ # Two distributions with the same values and probabilities will have the same
198
+ # hash code (and will compare using #eql?).
199
+ #
200
+ # See also Hash#hash.
201
+
202
+ ##
203
+ # :method: length
204
+ # :call_seq:
205
+ # distribution.length -> int
206
+ #
207
+ # Returns the number of values in self. May be zero.
208
+ #
209
+ # CategoricalDistribution.new([1, 2, 3, 4]).length #=> 4
210
+ # CategoricalDistribution.new.length #=> 0
211
+ end
metadata ADDED
@@ -0,0 +1,98 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: categorical_distribution
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Zane Geiger
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2016-10-15 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: bundler
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - "~>"
18
+ - !ruby/object:Gem::Version
19
+ version: '1.13'
20
+ type: :development
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: '1.13'
27
+ - !ruby/object:Gem::Dependency
28
+ name: rake
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - "~>"
32
+ - !ruby/object:Gem::Version
33
+ version: '10.0'
34
+ type: :development
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - "~>"
39
+ - !ruby/object:Gem::Version
40
+ version: '10.0'
41
+ - !ruby/object:Gem::Dependency
42
+ name: minitest
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - "~>"
46
+ - !ruby/object:Gem::Version
47
+ version: '5.0'
48
+ type: :development
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - "~>"
53
+ - !ruby/object:Gem::Version
54
+ version: '5.0'
55
+ description:
56
+ email:
57
+ - zanecodes@gmail.com
58
+ executables: []
59
+ extensions: []
60
+ extra_rdoc_files: []
61
+ files:
62
+ - ".gitignore"
63
+ - ".travis.yml"
64
+ - Gemfile
65
+ - LICENSE.txt
66
+ - README.md
67
+ - Rakefile
68
+ - bin/console
69
+ - bin/setup
70
+ - categorical_distribution.gemspec
71
+ - lib/categorical_distribution.rb
72
+ - lib/categorical_distribution/version.rb
73
+ homepage: https://github.com/zanecodes/categorical_distribution
74
+ licenses:
75
+ - MIT
76
+ metadata: {}
77
+ post_install_message:
78
+ rdoc_options: []
79
+ require_paths:
80
+ - lib
81
+ required_ruby_version: !ruby/object:Gem::Requirement
82
+ requirements:
83
+ - - ">="
84
+ - !ruby/object:Gem::Version
85
+ version: '0'
86
+ required_rubygems_version: !ruby/object:Gem::Requirement
87
+ requirements:
88
+ - - ">="
89
+ - !ruby/object:Gem::Version
90
+ version: '0'
91
+ requirements: []
92
+ rubyforge_project:
93
+ rubygems_version: 2.4.5.1
94
+ signing_key:
95
+ specification_version: 4
96
+ summary: Generates values from a categorical probability distribution in O(1) using
97
+ Vose's Alias Method.
98
+ test_files: []