diverse_shuffle 0.1.0-x86_64-linux

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
+ SHA256:
3
+ metadata.gz: cb143bd30a73493da3c0060eb1114aeff28b9dc9c5cd3be762d79bdffe6fc083
4
+ data.tar.gz: 13f02a36f49f92e9efc97f1d8f13a0734a1b190a278f3f93143961eef1ae771a
5
+ SHA512:
6
+ metadata.gz: 515bdf90f07967631c6d4fd276f2ebeee18f54f37d0b9bad9863fc09dd62626ad676e8eca618170e28090c803bda2a65245dbd365fa7da5329dc692766abe3b5
7
+ data.tar.gz: 9f6552178895dddb8318be635c9150d2a47011c8dea00d62653f3ba2793e49615ca876916f68679a45c4d50d7bae9382fbc87f98e1b6d6f22c3bd6df6924aec7
data/CHANGELOG.md ADDED
@@ -0,0 +1,6 @@
1
+ # Changelog
2
+
3
+ ## 0.1.0 (2026-11-26)
4
+
5
+ - First release: greedy, MMR and DPP placement under vector and attribute rules, with loosening; a Rust engine
6
+ (precompiled for x86_64/aarch64 Linux and x86_64/arm64 macOS) and a pure-Ruby engine that place identically.
data/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Love Wins Media, Inc.
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 all
13
+ 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 THE
21
+ SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,91 @@
1
+ # diverse_shuffle
2
+
3
+ A seeded shuffle where neighbouring songs aren't too alike. You give it songs, how far apart pairs of tracks are
4
+ (cosine distances from your vector store, say) and which attributes they share (voice, era, show), plus hard rules
5
+ over those: how far a song must be from the songs just before it, how many of the window may share an attribute,
6
+ how many songs must pass before an attribute comes back. It places every song, in an order that's the same for the
7
+ same seed.
8
+
9
+ The work runs in Rust (a native extension, precompiled for Linux and macOS on x86_64 and ARM). Where it isn't built,
10
+ a pure-Ruby engine places the songs instead, with exactly the same result: the specs hold the two engines to each
11
+ other on random pools, mode by mode, and every float is worked out in the same order on both sides.
12
+
13
+ On a 500-song pool with six rules, the Rust engine places every song in about 40 to 55 ms; the Ruby engine takes
14
+ about 1.1 s.
15
+
16
+ ## Install
17
+
18
+ ```ruby
19
+ gem 'diverse_shuffle'
20
+ ```
21
+
22
+ ## Use
23
+
24
+ ```ruby
25
+ require 'diverse_shuffle'
26
+ E = DiverseShuffle::Engine
27
+
28
+ # Three tracks; four songs (two play the same track, one is a song nothing is known about).
29
+ sound = E::VectorRule.new(weight: 1.0, min_distance: 0.25, pairs: [[0, 1, 0.42], [0, 2, 0.07], [1, 2, 0.6]])
30
+ # Per track, one list of value ids per key (here one key, the show), or nil for a track with no attributes.
31
+ show = E::MatchRule.new(weight: 0.5, min_gap: 2, values: [[[7]], [[7]], [[3]]])
32
+ pool = E::Pool.new(songs: [0, 1, 2, nil], tracks: 3, rules: [sound, show])
33
+
34
+ E.place(pool, seed: 'tuesday', mode: :mmr)
35
+ # => [#<data DiverseShuffle::Engine::Placement song=1, level=0, considered=4, rejected=0>, ...]
36
+ ```
37
+
38
+ `song` is an index into `pool.songs`; `level` is how far the rules had to loosen for the song to pass (0 when they
39
+ didn't); `considered` and `rejected` say how many songs were looked at for the slot and how many were ruled out.
40
+
41
+ ### Modes
42
+
43
+ - `:greedy` takes, for each slot, the first song in shuffled order that passes every hard rule.
44
+ - `:mmr` takes the best of the first `mmr_k` passing songs by soft score (how far the song sits from the window
45
+ before it, weighted per rule), plus up to `mmr_jitter` of randomness.
46
+ - `:dpp` picks spread-out sets of `dpp_batch` songs (greedy MAP inference for a determinantal point process, with
47
+ incremental Cholesky), then places each set with the greedy rules.
48
+
49
+ ### Rules
50
+
51
+ - `VectorRule.new(weight:, pairs:, min_distance: nil)`: `pairs` are `[track, track, distance]`. A song must be at
52
+ least `min_distance` from the songs it's compared with. A pair with no distance is unknown and never rules a song
53
+ out.
54
+ - `MatchRule.new(weight:, values:, max_same_in_window: nil, min_gap: nil)`: two songs are the same when they share a
55
+ value on every key. Fewer than `max_same_in_window` songs of the window may be the same, and none of the last
56
+ `min_gap`.
57
+
58
+ ### Settings
59
+
60
+ `E::Settings.new(window: 3, compare: :window, loosen_steps: 3, loosen_factor: 0.75, mmr_k: 8, mmr_jitter: 0.15,
61
+ dpp_batch: 8)`, passed as `settings:`.
62
+
63
+ - `window`: how many songs back the hard rules and the soft score look.
64
+ - `compare`: `:window` compares distances against every song in the window, `:previous` against the one before
65
+ only.
66
+ - `loosen_steps`, `loosen_factor`: when no song passes, the rules loosen a step at a time (distances times
67
+ `loosen_factor` per step, one more same song allowed in the window, the gap one shorter); past the last step every
68
+ song passes, so it never stalls.
69
+
70
+ ### Engines
71
+
72
+ `DiverseShuffle::Engine.engine` says which engine `place` uses: `:native` where the extension is loaded, else
73
+ `:ruby`. Set `DIVERSE_SHUFFLE_ENGINE=ruby` to use Ruby anyway, or pass `engine: :ruby`.
74
+
75
+ ## Develop
76
+
77
+ ```sh
78
+ bundle install
79
+ bundle exec rake compile # builds the Rust extension (needs a Rust toolchain)
80
+ bundle exec rspec # specs, including the Rust engine against the Ruby one
81
+ cargo test --manifest-path ext/diverse_shuffle/Cargo.toml --no-default-features
82
+ ```
83
+
84
+ ## Release
85
+
86
+ Bump `DiverseShuffle::Engine::VERSION`, add a CHANGELOG entry, merge to main and run the Release workflow (or push
87
+ a `vX.Y.Z` tag). It builds the platform gems and the source gem and publishes them with RubyGems trusted publishing.
88
+
89
+ ## License
90
+
91
+ MIT. Made by Love Wins Media, Inc.
@@ -0,0 +1,149 @@
1
+ # frozen_string_literal: true
2
+
3
+ module DiverseShuffle
4
+ module Engine
5
+ # A rule over measured vectors: how far apart two tracks are, from the distances you give for pairs of tracks
6
+ # (cosine distance from your vector store, say). A pair with no distance is unknown.
7
+ #
8
+ # VectorRule.new(weight: 1.0, min_distance: 0.25, pairs: [[0, 1, 0.42], [0, 2, 0.07]])
9
+ #
10
+ # - weight: how much the rule counts in the soft score (0 leaves it out of the score).
11
+ # - min_distance: the hard rule: a song must be at least this far from the songs it's compared with; nil for none.
12
+ # - pairs: [track, track, distance] triples, track indexes into Pool#tracks. A pair given one way counts both ways;
13
+ # given both ways, each way keeps its own distance. A track is 0.0 from itself.
14
+ class VectorRule
15
+ attr_reader :weight, :min_distance, :pairs
16
+
17
+ def initialize(weight:, pairs:, min_distance: nil)
18
+ @weight = Float(weight)
19
+ @min_distance = min_distance && Float(min_distance)
20
+ @pairs = pairs
21
+ end
22
+
23
+ def vector? = true
24
+
25
+ # Whether the rule can rule a song out.
26
+ def hard? = !min_distance.nil?
27
+
28
+ # This rule loosened `level` steps: min_distance times factor**level.
29
+ def loosened(level, factor)
30
+ return self if level.zero? || min_distance.nil?
31
+
32
+ VectorRule.new(weight:, pairs:, min_distance: min_distance * (factor**level))
33
+ end
34
+ end
35
+
36
+ # A rule over attributes: two songs are the same when, on every one of the rule's keys, they share a value.
37
+ #
38
+ # MatchRule.new(weight: 0.5, max_same_in_window: 1, values: [[[3], [7]], [[3], []], nil])
39
+ #
40
+ # - weight: how much the rule counts in the soft score.
41
+ # - max_same_in_window: the hard rule: fewer than this many of the window's songs may be the same; nil for none.
42
+ # - min_gap: the hard rule: none of the last min_gap songs may be the same; nil for none.
43
+ # - values: per track, one list of value ids per key (values you number yourself: equal ids are equal values), or
44
+ # nil for a track with no attributes at all. A key with no values never matches.
45
+ class MatchRule
46
+ attr_reader :weight, :max_same_in_window, :min_gap, :values
47
+
48
+ def initialize(weight:, values:, max_same_in_window: nil, min_gap: nil)
49
+ @weight = Float(weight)
50
+ @max_same_in_window = max_same_in_window && Integer(max_same_in_window)
51
+ @min_gap = min_gap && Integer(min_gap)
52
+ raise ArgumentError, 'max_same_in_window must not be negative' if @max_same_in_window&.negative?
53
+ raise ArgumentError, 'min_gap must not be negative' if @min_gap&.negative?
54
+
55
+ @values = values
56
+ end
57
+
58
+ def vector? = false
59
+
60
+ def hard? = !max_same_in_window.nil? || !min_gap.nil?
61
+
62
+ # This rule loosened `level` steps: max_same_in_window plus level, min_gap minus level (not below 0).
63
+ def loosened(level, _factor)
64
+ return self if level.zero? || !hard?
65
+
66
+ MatchRule.new(weight:, values:, max_same_in_window: max_same_in_window && (max_same_in_window + level),
67
+ min_gap: min_gap && [min_gap - level, 0].max)
68
+ end
69
+ end
70
+
71
+ # How the shuffle places songs.
72
+ #
73
+ # - window: how many songs back the hard rules (and the soft score) look.
74
+ # - compare: :window (min_distance against every song in the window) or :previous (against the one before only).
75
+ # - loosen_steps, loosen_factor: when no song passes, the rules loosen a step at a time, this many steps (see
76
+ # VectorRule#loosened and MatchRule#loosened); past the last step every song passes.
77
+ # - mmr_k, mmr_jitter: :mmr takes the best of the first mmr_k passing songs by soft score plus up to mmr_jitter of
78
+ # randomness.
79
+ # - dpp_batch: :dpp picks spread-out sets of this many songs.
80
+ Settings = Data.define(:window, :compare, :loosen_steps, :loosen_factor, :mmr_k, :mmr_jitter, :dpp_batch) do
81
+ def initialize(window: 3, compare: :window, loosen_steps: 3, loosen_factor: 0.75, mmr_k: 8, mmr_jitter: 0.15,
82
+ dpp_batch: 8)
83
+ compare = compare.to_sym
84
+ raise ArgumentError, 'compare must be :window or :previous' unless %i[window previous].include?(compare)
85
+
86
+ super(window: at_least(window, 0, 'window'), compare:, loosen_steps: at_least(loosen_steps, 0, 'loosen_steps'),
87
+ loosen_factor: Float(loosen_factor), mmr_k: at_least(mmr_k, 1, 'mmr_k'), mmr_jitter: Float(mmr_jitter),
88
+ dpp_batch: at_least(dpp_batch, 1, 'dpp_batch'))
89
+ end
90
+
91
+ private
92
+
93
+ def at_least(value, floor, name)
94
+ value = Integer(value)
95
+ raise ArgumentError, "#{name} must be at least #{floor}" if value < floor
96
+
97
+ value
98
+ end
99
+ end
100
+
101
+ # The songs to place and what's known about them.
102
+ #
103
+ # - songs: per song, the index of its track, or nil for a song nothing is known about. Several songs may share a
104
+ # track.
105
+ # - tracks: how many tracks the rules' pairs and values index.
106
+ # - rules: VectorRule and MatchRule, in order (the soft score adds them up in this order).
107
+ class Pool
108
+ attr_reader :songs, :tracks, :rules
109
+
110
+ def initialize(songs:, tracks:, rules:)
111
+ @songs = songs.map { |track| track && Integer(track) }
112
+ @tracks = Integer(tracks)
113
+ @rules = rules
114
+ check!
115
+ end
116
+
117
+ def size = songs.size
118
+
119
+ private
120
+
121
+ def check!
122
+ songs.each { check_track!(it) if it }
123
+ rules.each { it.vector? ? check_pairs!(it) : check_values!(it) }
124
+ end
125
+
126
+ def check_track!(track)
127
+ raise ArgumentError, "track #{track} out of range" unless track.is_a?(Integer) && track.between?(0, tracks - 1)
128
+ end
129
+
130
+ def check_pairs!(rule)
131
+ rule.pairs.each do |a, b, _distance|
132
+ check_track!(a)
133
+ check_track!(b)
134
+ end
135
+ end
136
+
137
+ def check_values!(rule)
138
+ raise ArgumentError, 'a MatchRule needs values for every track' unless rule.values.size == tracks
139
+
140
+ keys = rule.values.compact.map(&:size).uniq
141
+ raise ArgumentError, 'every track of a MatchRule needs the same keys' if keys.size > 1
142
+ end
143
+ end
144
+
145
+ # Where one song went: the song (its index in Pool#songs), the loosening level it passed at, how many songs were
146
+ # looked at for the slot and how many of those were ruled out.
147
+ Placement = Data.define(:song, :level, :considered, :rejected)
148
+ end
149
+ end
@@ -0,0 +1,48 @@
1
+ # frozen_string_literal: true
2
+
3
+ module DiverseShuffle
4
+ module Engine
5
+ # The seeded generator: SplitMix64, seeded by the 64-bit FNV-1a hash of the seed text, so the same seed always gives
6
+ # the same draws (and the Rust engine draws exactly the same numbers).
7
+ class Rng
8
+ MASK = 0xFFFF_FFFF_FFFF_FFFF
9
+ GOLDEN = 0x9e37_79b9_7f4a_7c15
10
+
11
+ # FNV-1a over the text's bytes.
12
+ def self.fnv(text)
13
+ text.to_s.each_byte.reduce(0xcbf2_9ce4_8422_2325) do |state, byte|
14
+ ((state ^ byte) * 0x0000_0100_0000_01b3) & MASK
15
+ end
16
+ end
17
+
18
+ # SplitMix64's output function.
19
+ def self.mix(state)
20
+ z = ((state ^ (state >> 30)) * 0xbf58_476d_1ce4_e5b9) & MASK
21
+ z = ((z ^ (z >> 27)) * 0x94d0_49bb_1331_11eb) & MASK
22
+ z ^ (z >> 31)
23
+ end
24
+
25
+ def initialize(seed)
26
+ @state = self.class.fnv(seed)
27
+ end
28
+
29
+ def next_u64
30
+ @state = (@state + GOLDEN) & MASK
31
+ self.class.mix(@state)
32
+ end
33
+
34
+ # A float in [0, 1).
35
+ def float = (next_u64 >> 11) / 9_007_199_254_740_992.0
36
+
37
+ # Fisher-Yates, from the last element down.
38
+ def shuffle(items)
39
+ result = items.dup
40
+ (result.size - 1).downto(1) do |i|
41
+ j = next_u64 % (i + 1)
42
+ result[i], result[j] = result[j], result[i]
43
+ end
44
+ result
45
+ end
46
+ end
47
+ end
48
+ end
@@ -0,0 +1,262 @@
1
+ # frozen_string_literal: true
2
+
3
+ module DiverseShuffle
4
+ module Engine
5
+ # The engine in plain Ruby (Engine::Ruby): the reference the Rust engine is held to, and the one used where the
6
+ # native extension isn't built. Songs are indexes into the pool; every pair answer is worked out once and kept.
7
+ class Ruby
8
+ # Distance assumed when nothing is known, for the soft score.
9
+ UNKNOWN = 0.5
10
+ UNSET = Object.new.freeze
11
+
12
+ def initialize(pool, settings, seed)
13
+ @pool = pool
14
+ @settings = settings
15
+ @rng = Rng.new(seed)
16
+ @size = pool.size
17
+ @songs = pool.songs
18
+ @rules = pool.rules
19
+ @matrices = @rules.map { |rule| rule.vector? ? matrix(rule) : nil }
20
+ @attrs = @rules.map { |rule| rule.vector? ? nil : attrs_flags(rule) }
21
+ @cache = @rules.map { Array.new(@size * @size, UNSET) }
22
+ @levels = (0..settings.loosen_steps).map do |level|
23
+ @rules.map { |rule| rule.loosened(level, settings.loosen_factor) }
24
+ end
25
+ end
26
+
27
+ # Placements for every song, in order.
28
+ def place(mode)
29
+ remaining = @rng.shuffle((0...@size).to_a)
30
+ mode == :dpp ? batches(remaining) : sequence(remaining, [], mode, [])
31
+ end
32
+
33
+ private
34
+
35
+ def sequence(remaining, history, mode, placements)
36
+ remaining = remaining.dup
37
+ until remaining.empty?
38
+ placement = place_one(remaining, history, mode)
39
+ remaining.delete_at(remaining.index(placement.song))
40
+ history << placement.song
41
+ placements << placement
42
+ end
43
+ placements
44
+ end
45
+
46
+ def place_one(remaining, history, mode)
47
+ (0..(@settings.loosen_steps + 1)).each do |level|
48
+ rules = @levels[level]
49
+ passing, rejected = candidates(remaining, history, rules, mode)
50
+ next if passing.empty?
51
+
52
+ return Placement.new(song: pick(passing, history, mode), level:, considered: passing.size + rejected,
53
+ rejected:)
54
+ end
55
+ end
56
+
57
+ def candidates(remaining, history, rules, mode)
58
+ limit = mode == :mmr ? @settings.mmr_k : 1
59
+ passing = []
60
+ rejected = 0
61
+ window = history.last(@settings.window)
62
+ remaining.each do |song|
63
+ rules.nil? || passes?(song, history, window, rules) ? passing << song : rejected += 1
64
+ break if passing.size >= limit
65
+ end
66
+ [passing, rejected]
67
+ end
68
+
69
+ def pick(passing, history, mode)
70
+ return passing.first unless mode == :mmr
71
+
72
+ window = history.last(@settings.window)
73
+ passing.each_with_index.max_by do |song, index|
74
+ [score(song, window) + (@settings.mmr_jitter * @rng.float), -index]
75
+ end.first
76
+ end
77
+
78
+ def passes?(song, history, window, rules)
79
+ rules.each_with_index.all? do |rule, index|
80
+ next true unless rule.hard?
81
+
82
+ if rule.vector?
83
+ distance_passes?(index, rule, song, history,
84
+ window)
85
+ else
86
+ match_passes?(index, rule, song, history, window)
87
+ end
88
+ end
89
+ end
90
+
91
+ def distance_passes?(index, rule, song, history, window)
92
+ compared = @settings.compare == :previous ? history.last(1) : window
93
+ closest = compared.filter_map { distance(index, song, it) }.min
94
+ closest.nil? || closest >= rule.min_distance
95
+ end
96
+
97
+ def match_passes?(index, rule, song, history, window)
98
+ return false if rule.max_same_in_window && window.count { same?(index, song, it) } >= rule.max_same_in_window
99
+
100
+ rule.min_gap.nil? || history.last(rule.min_gap).none? { same?(index, song, it) }
101
+ end
102
+
103
+ # How far the song sits from the window before it, from 0 (alike) to 1, weighted per rule.
104
+ def score(song, window)
105
+ return 1.0 if window.empty?
106
+
107
+ weighted = @rules.each_with_index.filter_map do |rule, index|
108
+ next if rule.weight.zero?
109
+
110
+ distance = window_distance(index, rule, song, window)
111
+ [rule.weight, distance] unless distance.nil?
112
+ end
113
+ blend(weighted)
114
+ end
115
+
116
+ def window_distance(index, rule, song, window)
117
+ if rule.vector?
118
+ window.filter_map { distance(index, song, it) }.min&.clamp(0.0, 1.0)
119
+ elsif @attrs[index][song]
120
+ window.any? { same?(index, song, it) } ? 0.0 : 1.0
121
+ end
122
+ end
123
+
124
+ # How far apart two songs are over every weighted rule (DPP's kernel).
125
+ def pair_distance(first, second)
126
+ weighted = @rules.each_with_index.filter_map do |rule, index|
127
+ next if rule.weight.zero?
128
+
129
+ distance = distance(index, first, second)
130
+ [rule.weight, distance] unless distance.nil?
131
+ end
132
+ blend(weighted)
133
+ end
134
+
135
+ def blend(weighted)
136
+ return UNKNOWN if weighted.empty?
137
+
138
+ total = weighted.sum(&:first)
139
+ total.zero? ? UNKNOWN : weighted.sum { |weight, distance| weight * distance } / total
140
+ end
141
+
142
+ # A rule's distance between two songs, 0 to 1, or nil when unknown. For an attribute rule, 0 when the same and
143
+ # 1 when not, when both songs have the rule's attributes.
144
+ def distance(index, first, second)
145
+ slot = (first * @size) + second
146
+ cached = @cache[index][slot]
147
+ return cached unless cached.equal?(UNSET)
148
+
149
+ @cache[index][slot] = compute_distance(index, first, second)
150
+ end
151
+
152
+ def compute_distance(index, first, second)
153
+ if @rules[index].vector?
154
+ mine = @songs[first]
155
+ theirs = @songs[second]
156
+ return nil unless mine && theirs
157
+ return 0.0 if mine == theirs
158
+
159
+ @matrices[index][(mine * @pool.tracks) + theirs]&.clamp(0.0, 1.0)
160
+ elsif @attrs[index][first] && @attrs[index][second]
161
+ same?(index, first, second) ? 0.0 : 1.0
162
+ end
163
+ end
164
+
165
+ # Whether two songs share a value on every one of an attribute rule's keys.
166
+ def same?(index, first, second)
167
+ mine = @songs[first]
168
+ theirs = @songs[second]
169
+ return false unless mine && theirs
170
+
171
+ values = @rules[index].values
172
+ a = values[mine]
173
+ b = values[theirs]
174
+ return false unless a && b
175
+
176
+ a.each_with_index.all? { |ids, key| !ids.empty? && !b[key].empty? && ids.intersect?(b[key]) }
177
+ end
178
+
179
+ # Per song, whether it has attributes and every one of the rule's keys.
180
+ def attrs_flags(rule)
181
+ @songs.map do |track|
182
+ values = track && rule.values[track]
183
+ values ? values.all? { !it.empty? } : false
184
+ end
185
+ end
186
+
187
+ # Distances between tracks, track-major, nil where unknown. A pair given one way counts both ways.
188
+ def matrix(rule)
189
+ tracks = @pool.tracks
190
+ found = Array.new(tracks * tracks)
191
+ rule.pairs.each do |a, b, distance|
192
+ found[(a * tracks) + b] = Float(distance)
193
+ found[(b * tracks) + a] ||= Float(distance)
194
+ end
195
+ found
196
+ end
197
+
198
+ def dpp = @dpp ||= Dpp.new(self, @rng, @settings.mmr_jitter)
199
+
200
+ def batches(remaining)
201
+ history = []
202
+ placements = []
203
+ until remaining.empty?
204
+ batch = dpp.pick(remaining, [@settings.dpp_batch, remaining.size].min)
205
+ remaining -= batch
206
+ sequence(@rng.shuffle(batch), history, :greedy, placements)
207
+ end
208
+ placements
209
+ end
210
+
211
+ # Greedy MAP inference for a determinantal point process (Chen, Zhang & Zhou 2018, fast greedy with incremental
212
+ # Cholesky). Kernel L = q_i (1 - distance_ij) q_j, each song's quality q a little random so equal sets don't
213
+ # always win. Fills from the pool's order once the kernel can't tell songs apart.
214
+ class Dpp
215
+ def initialize(engine, rng, jitter)
216
+ @engine = engine
217
+ @rng = rng
218
+ @jitter = jitter
219
+ end
220
+
221
+ def pick(pool, size)
222
+ @pool = pool
223
+ @quality = pool.map { 1.0 + (@jitter * @rng.float) }
224
+ @gains = @quality.map { it * it }
225
+ @basis = Array.new(pool.size) { [] }
226
+ @chosen = []
227
+ @taken = Array.new(pool.size, false)
228
+ size.times { break unless added_best? }
229
+ picked = @chosen.map { pool[it] }
230
+ picked + (pool - picked).first(size - picked.size)
231
+ end
232
+
233
+ private
234
+
235
+ def added_best?
236
+ best = @gains.each_index.reject { @taken[it] }.max_by { [@gains[it], -it] }
237
+ return false if best.nil? || @gains[best] <= 1e-9
238
+
239
+ @chosen << best
240
+ @taken[best] = true
241
+ project(best)
242
+ true
243
+ end
244
+
245
+ def project(best)
246
+ root = Math.sqrt(@gains[best])
247
+ @pool.each_index do |i|
248
+ next if @taken[i]
249
+
250
+ e = (kernel(best, i) - @basis[best].zip(@basis[i]).sum { |a, b| a * b }) / root
251
+ @basis[i] << e
252
+ @gains[i] -= e * e
253
+ end
254
+ end
255
+
256
+ def kernel(first, second)
257
+ @quality[first] * @quality[second] * (1.0 - @engine.send(:pair_distance, @pool[first], @pool[second]))
258
+ end
259
+ end
260
+ end
261
+ end
262
+ end
@@ -0,0 +1,7 @@
1
+ # frozen_string_literal: true
2
+
3
+ module DiverseShuffle
4
+ module Engine
5
+ VERSION = '0.1.0'
6
+ end
7
+ end
@@ -0,0 +1,86 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative 'diverse_shuffle/version'
4
+ require_relative 'diverse_shuffle/rng'
5
+ require_relative 'diverse_shuffle/pool'
6
+ require_relative 'diverse_shuffle/ruby_engine'
7
+
8
+ # Songs in a random order where neighbouring songs aren't too alike: a seeded shuffle under hard rules (how far apart
9
+ # songs must be, how often the same attribute may come up in a window) with a soft score for how spread out the
10
+ # order is. Three modes:
11
+ #
12
+ # - :greedy takes, for each slot, the first song in shuffled order that passes every hard rule.
13
+ # - :mmr takes the best of the first few passing songs by soft score, with a little randomness.
14
+ # - :dpp picks spread-out sets of songs (a determinantal point process), then places each set with the greedy rules.
15
+ #
16
+ # When no song passes, the rules loosen a step at a time, so it never stalls. The same seed always gives the same
17
+ # order, from the Rust engine or the Ruby one.
18
+ #
19
+ # Everything lives under DiverseShuffle::Engine, so an app can keep its own DiverseShuffle namespace around it.
20
+ #
21
+ # pool = DiverseShuffle::Engine::Pool.new(songs: [0, 1, 2, nil], tracks: 3, rules: [...])
22
+ # DiverseShuffle::Engine.place(pool, seed: 'tuesday', mode: :mmr) # => [Placement, ...]
23
+ module DiverseShuffle
24
+ # The shuffle: Engine.place, the pool and rules it places (Pool, VectorRule, MatchRule, Settings) and its two
25
+ # engines, Native (Rust) and Ruby.
26
+ module Engine
27
+ class Error < StandardError; end
28
+
29
+ MODES = %i[greedy mmr dpp].freeze
30
+
31
+ begin
32
+ require_relative "diverse_shuffle/#{RUBY_VERSION[/\d+\.\d+/]}/diverse_shuffle"
33
+ rescue LoadError
34
+ begin
35
+ require_relative 'diverse_shuffle/diverse_shuffle'
36
+ rescue LoadError
37
+ nil # No native extension built for this platform: the Ruby engine places songs.
38
+ end
39
+ end
40
+
41
+ # Whether the Rust engine is loaded.
42
+ def self.native? = defined?(Native) ? true : false
43
+
44
+ # :native or :ruby: the engine #place uses. DIVERSE_SHUFFLE_ENGINE=ruby picks Ruby even where Rust is built.
45
+ def self.engine
46
+ return :ruby if ENV['DIVERSE_SHUFFLE_ENGINE'] == 'ruby' || !native?
47
+
48
+ :native
49
+ end
50
+
51
+ # Every song of the pool, placed: an Array of Placement in play order.
52
+ def self.place(pool, seed:, mode: :greedy, settings: Settings.new, engine: self.engine)
53
+ mode = mode.to_sym
54
+ raise Error, "mode must be one of #{MODES.join(', ')}" unless MODES.include?(mode)
55
+
56
+ case engine
57
+ when :ruby then Ruby.new(pool, settings, seed.to_s).place(mode)
58
+ when :native then native_place(pool, settings, seed.to_s, mode)
59
+ else raise Error, "engine must be :native or :ruby, not #{engine.inspect}"
60
+ end
61
+ end
62
+
63
+ def self.native_place(pool, settings, seed, mode)
64
+ raise Error, 'the native engine is not built for this platform' unless native?
65
+
66
+ rows = Native.place(pool.songs.map { it || -1 }, pool.tracks, pool.rules.map { native_rule(it) },
67
+ native_settings(settings), seed, MODES.index(mode))
68
+ rows.map { |song, level, considered, rejected| Placement.new(song:, level:, considered:, rejected:) }
69
+ end
70
+
71
+ def self.native_rule(rule)
72
+ if rule.vector?
73
+ [0, rule.weight, rule.min_distance || Float::NAN, -1, -1, rule.pairs.map { |a, b, d| [a, b, Float(d)] }, []]
74
+ else
75
+ [1, rule.weight, Float::NAN, rule.max_same_in_window || -1, rule.min_gap || -1, [],
76
+ rule.values]
77
+ end
78
+ end
79
+
80
+ def self.native_settings(settings)
81
+ [settings.window, settings.compare == :previous, settings.loosen_steps, settings.loosen_factor,
82
+ settings.mmr_k, settings.mmr_jitter, settings.dpp_batch]
83
+ end
84
+ private_class_method :native_place, :native_rule, :native_settings
85
+ end
86
+ end
metadata ADDED
@@ -0,0 +1,58 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: diverse_shuffle
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: x86_64-linux
6
+ authors:
7
+ - Love Wins Media, Inc.
8
+ bindir: bin
9
+ cert_chain: []
10
+ date: 1980-01-02 00:00:00.000000000 Z
11
+ dependencies: []
12
+ description: |
13
+ Places songs in a random order under hard rules (how far apart neighbouring songs must be, by measured distance
14
+ or by shared attributes) with a soft score for how spread out the order is: greedy, MMR or DPP. The same seed
15
+ gives the same order from the Rust engine or the Ruby one.
16
+ executables: []
17
+ extensions: []
18
+ extra_rdoc_files: []
19
+ files:
20
+ - CHANGELOG.md
21
+ - LICENSE
22
+ - README.md
23
+ - lib/diverse_shuffle.rb
24
+ - lib/diverse_shuffle/diverse_shuffle.so
25
+ - lib/diverse_shuffle/pool.rb
26
+ - lib/diverse_shuffle/rng.rb
27
+ - lib/diverse_shuffle/ruby_engine.rb
28
+ - lib/diverse_shuffle/version.rb
29
+ homepage: https://github.com/lwm-luminx/diverse_shuffle
30
+ licenses:
31
+ - MIT
32
+ metadata:
33
+ homepage_uri: https://github.com/lwm-luminx/diverse_shuffle
34
+ source_code_uri: https://github.com/lwm-luminx/diverse_shuffle
35
+ changelog_uri: https://github.com/lwm-luminx/diverse_shuffle/blob/main/CHANGELOG.md
36
+ rubygems_mfa_required: 'true'
37
+ rdoc_options: []
38
+ require_paths:
39
+ - lib
40
+ required_ruby_version: !ruby/object:Gem::Requirement
41
+ requirements:
42
+ - - ">="
43
+ - !ruby/object:Gem::Version
44
+ version: '4.0'
45
+ - - "<"
46
+ - !ruby/object:Gem::Version
47
+ version: 4.1.dev
48
+ required_rubygems_version: !ruby/object:Gem::Requirement
49
+ requirements:
50
+ - - ">="
51
+ - !ruby/object:Gem::Version
52
+ version: '0'
53
+ requirements: []
54
+ rubygems_version: 4.0.20
55
+ specification_version: 4
56
+ summary: A seeded shuffle where neighbouring songs are not too alike, in Rust with
57
+ a pure-Ruby fallback.
58
+ test_files: []