musicalism 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
+ SHA256:
3
+ metadata.gz: 36f0dda967d4bf1cfabc3aa724f5b90282ab368ba41d6b0e9ed07fdac36bac6b
4
+ data.tar.gz: 796475a00adc724c4c318d12ccbe93d6ea03119036b75c1c4ae4286ea5b762f8
5
+ SHA512:
6
+ metadata.gz: ff6cb1c8f03202ecdb84ba3504297b880d138d1501513b834dc508672c582d334cf1ad656230e983e1a23eb20ed1254b71b9f16173a0b5b94d46a1858722c2c8
7
+ data.tar.gz: cd99eaee60ccf1660b1be6e84deaadcce7a26194b8fdfdb11d1cc8387ab5d3503523fd8f5ee5a837fd15cedf1f3d96d9141d2e90c635aa93068ea58b173b96cb
data/LICENSE ADDED
@@ -0,0 +1,22 @@
1
+ Copyright (c) 2012 Yann Marquet
2
+
3
+ MIT License
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining
6
+ a copy of this software and associated documentation files (the
7
+ "Software"), to deal in the Software without restriction, including
8
+ without limitation the rights to use, copy, modify, merge, publish,
9
+ distribute, sublicense, and/or sell copies of the Software, and to
10
+ permit persons to whom the Software is furnished to do so, subject to
11
+ the following conditions:
12
+
13
+ The above copyright notice and this permission notice shall be
14
+ included in all copies or substantial portions of the Software.
15
+
16
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
17
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
19
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
20
+ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
21
+ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
22
+ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,197 @@
1
+ # Musicalism
2
+
3
+ Music theory in plain Ruby: notes, scales, chords, keys, and the paths between keys.
4
+
5
+ Musicalism answers harmonic questions so that a live-coding engine can play the answers. Ask it for the V chord of A minor, the pivot chord between C major and G major, or the shortest smooth route from C major to F# major. It gives back notes with octaves and MIDI numbers, ready to send as note-ons. It has no runtime dependencies, no clock and no I/O.
6
+
7
+ It was written for [archaeopteryx](https://github.com/StupidCodeFactory/archaeopteryx), whose clips and key journeys are built on it.
8
+
9
+ ```ruby
10
+ key = Musicalism::Key['C major']
11
+ key.modulate_to('G major', via: :vi).map(&:to_s)
12
+ # => ["C major", "A minor", "D major", "G major"]
13
+ key.modulate_to('G major', via: :vi).map(&:to_midi)
14
+ # => [[60, 64, 67], [60, 64, 69], [62, 66, 69], [62, 67, 71]] voice-led
15
+ ```
16
+
17
+ ## Installation
18
+
19
+ Musicalism needs Ruby 3.2 or later.
20
+
21
+ ```bash
22
+ gem install musicalism
23
+ ```
24
+
25
+ or in a Gemfile:
26
+
27
+ ```ruby
28
+ gem 'musicalism', '~> 0.1'
29
+ ```
30
+
31
+ ## Notes
32
+
33
+ ```ruby
34
+ note = Musicalism::Note.new('C#4') # or Note.new('C#', 4)
35
+ note.pitch # => "C#"
36
+ note.octave # => 4
37
+ note.to_midi # => 61
38
+ note.next # => D4
39
+
40
+ Musicalism::Note.new('B#3') == Musicalism::Note.new('C4') # => true, enharmonic notes are equal
41
+ Musicalism::Note.from_midi(61) # => C#4
42
+ ```
43
+
44
+ Notes cover the piano range, A0 to C8, in scientific pitch notation (C4 = 60). The octave belongs to the letter, so B#3 and C4 are both MIDI 60. A note outside the range raises `Musicalism::Note::UnkownNoteError`.
45
+
46
+ ## Scales
47
+
48
+ ```ruby
49
+ Musicalism::MajorScale.new('D').notes # => D4 E4 F#4 G4 A4 B4 C#5
50
+ Musicalism::MajorScale.new('Bb').alterations # => ["Bb", "Eb"]
51
+ ```
52
+
53
+ `MajorScale`, `MinorScale` (natural), `HarmonicMinorScale` and `MelodicMinorScale` (ascending) spell each degree with the next letter name, so `MajorScale.new('E#')` uses C##.
54
+
55
+ ## Keys
56
+
57
+ `Key` is the main API. `Scale` is the layer underneath it.
58
+
59
+ ```ruby
60
+ key = Musicalism::Key['C major'] # or Key.major('C'), Key.minor('A'), Key['F# minor']
61
+
62
+ key.relative # => A minor
63
+ key.parallel # => C minor
64
+ key.dominant_key # => G major
65
+ key.subdominant_key # => F major
66
+ key.signature # => []
67
+ key.note(5) # => G4
68
+ key.note(9) # => D5 (degrees past 7 go up an octave)
69
+ ```
70
+
71
+ Two keys are equal when the tonic is spelled the same and the mode matches, so `Key['Db major'] != Key['C# major']`.
72
+
73
+ ### Chords by roman numeral
74
+
75
+ ```ruby
76
+ key.chord(:V) # => G major, G4 B4 D5
77
+ key.chord(:V).to_midi # => [67, 71, 74]
78
+ key.chord(:vi, inversion: 1) # => C5 E5 A5
79
+ Musicalism::Key['A minor'].chord(:V) # => E major (V and vii come from harmonic minor)
80
+
81
+ key.numerals # => [:I, :ii, :iii, :IV, :V, :vi, :vii]
82
+ key.chords(:subdominant) # => F major, D minor, A minor
83
+ ```
84
+
85
+ `chord` accepts numerals in either case. `chords` groups the triads by harmonic function, primary chord first:
86
+
87
+ | Function | Degrees |
88
+ |-------------|-------------|
89
+ | tonic | I, vi, iii |
90
+ | subdominant | IV, ii, vi |
91
+ | dominant | V, vii |
92
+
93
+ ### Chords
94
+
95
+ ```ruby
96
+ chord = Musicalism::Chord.new(%w[E4 G4 C5].map { |name| Musicalism::Note.new(name) })
97
+ chord.to_s # => "C major" (any inversion)
98
+ chord.quality # => :major
99
+ chord.inverse(1) # => G4 C5 E5, the lowest note moves up an octave
100
+ ```
101
+
102
+ `voiced_near(previous)` picks the inversion and octave that moves the fewest semitones from the chord before it. `Chord.voice_lead(chords)` applies that along a progression.
103
+
104
+ ## Modulation
105
+
106
+ ```ruby
107
+ key = Musicalism::Key['C major']
108
+
109
+ key.pivot_chords('G major').map(&:to_s)
110
+ # => ["A minor: vi in C major = ii in G major",
111
+ # "E minor: iii in C major = vi in G major",
112
+ # "C major: I in C major = IV in G major",
113
+ # "G major: V in C major = I in G major"]
114
+
115
+ key.modulate_to('G major') # I, a random pivot, V, I of G major
116
+ key.modulate_to('G major', via: :vi) # choose the pivot by its numeral in C major
117
+ key.modulate_to('G major', random: Random.new(4))
118
+ key.modulate_to('G major', voice_leading: false)
119
+ ```
120
+
121
+ The pivot is drawn at random from the shared chords that are tonic in neither key, so repeated modulations vary. Seed `random:` to repeat one. The chords are voice-led unless you pass `voice_leading: false`.
122
+
123
+ ## The key graph
124
+
125
+ Each step on the graph modulates to the dominant, subdominant or relative key, and each step always has a pivot chord. The graph tells you how far apart two keys are and how to get from one to the other.
126
+
127
+ ```ruby
128
+ key.closely_related # => G major, F major, A minor
129
+ key.distance_to('F# major') # => 6
130
+ key.farthest_distance # => 7
131
+ key.keys_at(2) # => D major, E minor, Bb major, D minor
132
+
133
+ key.path_to('F# major', random: Random.new(1))
134
+ # => C major, F major, Bb major, Eb major, Ab major, Db major, F# major
135
+
136
+ key.modulate_through(key.path_to('D major'))
137
+ # => C major, E minor, D major, G major, B minor, A major, D major
138
+ ```
139
+
140
+ `path_to` picks one of the shortest routes at random. `modulate_through` chains modulations along any list of keys, respelling enharmonic keys so that crossing from F# major to Db major still uses a pivot. `Key.major('C#').simplest_spelling` returns Db major.
141
+
142
+ Musicalism never decides where to go next. Walking the graph, and choosing the direction and timing, is up to the caller, for example archaeopteryx's journeys.
143
+
144
+ ## Micro modulations
145
+
146
+ These are short tonicizations that borrow from a passing key without leaving the current one:
147
+
148
+ ```ruby
149
+ key.tonicize(:ii) # => D minor, the local key on ii
150
+ key.secondary_dominant(:V) # => D major, which is V/V
151
+ key.two_five(:IV) # => G minor, C major: ii and V leading to F
152
+ ```
153
+
154
+ ## With archaeopteryx
155
+
156
+ archaeopteryx walks the key graph like an arpeggiator whose notes are keys. Clips follow the walk bar by bar:
157
+
158
+ ```ruby
159
+ Archaeopteryx::Journey.register :voyage, from: 'C major', mode: :up_down, range: 3, rate: 4
160
+
161
+ Archaeopteryx::Clip.register :pads do
162
+ follow :voyage do |key, step|
163
+ chord key.chord(:I), 16, [1] + [0] * 15
164
+ chord key.secondary_dominant(:V), 16, [0] * 12 + [1, 0, 0, 0] if step.farthest? && step.last_bar?
165
+ end
166
+ end
167
+ ```
168
+
169
+ See archaeopteryx's `script/journey_demo` for a full example.
170
+
171
+ ## Development
172
+
173
+ ```bash
174
+ bundle install
175
+ bundle exec rspec
176
+ script/console
177
+ ```
178
+
179
+ ## Releasing
180
+
181
+ Versions follow [semantic versioning](https://semver.org). A push to master publishes nothing on its own. The gem is published only when a `vMAJOR.MINOR.PATCH` tag is pushed:
182
+
183
+ 1. Bump `Musicalism::VERSION` in `lib/musicalism/version.rb` and merge to master.
184
+ 2. Tag the merge commit on master and push the tag:
185
+
186
+ ```bash
187
+ git tag -a v0.2.0 -m "musicalism 0.2.0"
188
+ git push origin v0.2.0
189
+ ```
190
+
191
+ The `Release gem` workflow (`.github/workflows/release.yml`) then checks that the tag matches `Musicalism::VERSION` and points at a commit on master. It runs the specs, builds the gem and pushes it to RubyGems. If any check fails, nothing is published.
192
+
193
+ It authenticates with RubyGems trusted publishing, so no API key is stored in the repository. Set it up once on rubygems.org: add a trusted publisher (a pending one before the first release) for the repository `StupidCodeFactory/musicalism`, the workflow `release.yml` and the environment `rubygems`.
194
+
195
+ ## License
196
+
197
+ MIT, see [LICENSE](LICENSE).
@@ -0,0 +1,91 @@
1
+ module Musicalism
2
+ class Chord
3
+ TRIAD_QUALITIES = {
4
+ [4, 3] => :major,
5
+ [3, 4] => :minor,
6
+ [3, 3] => :diminished,
7
+ [4, 4] => :augmented
8
+ }.freeze
9
+ VOICING_OCTAVE_SHIFTS = (-2..2).freeze
10
+
11
+ attr_reader :notes
12
+
13
+ def self.voice_lead(chords)
14
+ chords.drop(1).each_with_object(chords.first(1)) { |chord, led| led << chord.voiced_near(led.last) }
15
+ end
16
+
17
+ def initialize(notes, options = {})
18
+ @notes = notes
19
+ inversion = options.delete(:inversion) || 0
20
+ inverse! inversion if inversion > 0
21
+ end
22
+
23
+ def inverse(depth)
24
+ self.class.new(@notes.dup, inversion: depth)
25
+ end
26
+
27
+ def inverse!(depth)
28
+ depth.times { @notes.push(@notes.shift.up_an_octave) }
29
+ end
30
+
31
+ def quality
32
+ TRIAD_QUALITIES[root_position&.intervals]
33
+ end
34
+
35
+ def root
36
+ root_position&.notes&.first
37
+ end
38
+
39
+ def spelling
40
+ notes.map(&:pitch)
41
+ end
42
+
43
+ def to_midi
44
+ notes.map(&:to_midi)
45
+ end
46
+
47
+ def voiced_near(previous)
48
+ candidate_voicings.min_by { |voicing| voicing.movement_from(previous) }
49
+ end
50
+
51
+ def ==(other)
52
+ @notes == other.notes
53
+ end
54
+
55
+ def to_s
56
+ quality ? "#{root.pitch} #{quality}" : spelling.join(' ')
57
+ end
58
+
59
+ def inspect
60
+ "#<#{self.class.name} #{notes.map { |note| "#{note.pitch}#{note.octave}" }.join(' ')}>"
61
+ end
62
+
63
+ protected
64
+
65
+ def intervals
66
+ notes.each_cons(2).map { |lower, upper| upper.to_midi - lower.to_midi }
67
+ end
68
+
69
+ def movement_from(other)
70
+ to_midi.sort.zip(other.to_midi.sort).sum { |mine, theirs| (mine - theirs).abs }
71
+ end
72
+
73
+ def shifted_by_octaves(octaves)
74
+ self.class.new(notes.map { |note| Note.new(note.pitch, note.octave + octaves) })
75
+ rescue Note::UnkownNoteError
76
+ nil
77
+ end
78
+
79
+ private
80
+
81
+ def candidate_voicings
82
+ (0...notes.size).flat_map do |inversion|
83
+ VOICING_OCTAVE_SHIFTS.filter_map { |octaves| inverse(inversion).shifted_by_octaves(octaves) }
84
+ end
85
+ end
86
+
87
+ def root_position
88
+ (0...notes.size).map { |depth| inverse(depth) }.find { |rotation| TRIAD_QUALITIES.key?(rotation.intervals) }
89
+ end
90
+ end
91
+ end
@@ -0,0 +1,70 @@
1
+ module Musicalism
2
+ # Basic definitions of musical intervals
3
+ class Interval
4
+ SEMITONE = 1
5
+
6
+ def perfect_unison
7
+ 0
8
+ end
9
+ alias diminished_second perfect_unison
10
+
11
+ def minor_second
12
+ SEMITONE
13
+ end
14
+ alias augmented_unison minor_second
15
+
16
+ def major_second
17
+ SEMITONE * 2
18
+ end
19
+ alias diminished_third major_second
20
+
21
+ def minor_third
22
+ SEMITONE * 3
23
+ end
24
+ alias augmented_second minor_third
25
+
26
+ def major_third
27
+ SEMITONE * 4
28
+ end
29
+ alias diminished_forth major_third
30
+
31
+ def perfect_forth
32
+ SEMITONE * 5
33
+ end
34
+ alias augmented_third perfect_forth
35
+
36
+ def augmented_forth
37
+ SEMITONE * 6
38
+ end
39
+ alias diminished_fifth augmented_forth
40
+
41
+ def perfect_fifth
42
+ SEMITONE * 7
43
+ end
44
+ alias diminished_sixth perfect_fifth
45
+
46
+ def minor_sixth
47
+ SEMITONE * 8
48
+ end
49
+ alias augmented_fith minor_sixth
50
+
51
+ def major_sixth
52
+ SEMITONE * 9
53
+ end
54
+ alias diminished_seventh major_sixth
55
+
56
+ def minor_seventh
57
+ SEMITONE * 10
58
+ end
59
+ alias augmented_sixth minor_seventh
60
+
61
+ def major_seventh
62
+ SEMITONE * 11
63
+ end
64
+ alias diminished_octave major_seventh
65
+
66
+ def perfect_octave
67
+ SEMITONE * 12
68
+ end
69
+ end
70
+ end
@@ -0,0 +1,280 @@
1
+ module Musicalism
2
+ class Key
3
+ MODES = %i[major minor].freeze
4
+ ROMAN_NUMERALS = %w[I II III IV V VI VII].freeze
5
+ HARMONIC_FUNCTIONS = {
6
+ tonic: %w[I VI III],
7
+ subdominant: %w[IV II VI],
8
+ dominant: %w[V VII]
9
+ }.freeze
10
+ DEGREES_FROM_HARMONIC_MINOR = %i[dominant subtonic].freeze
11
+ PREFERRED_PIVOT_NUMERALS = HARMONIC_FUNCTIONS[:subdominant]
12
+ NEUTRAL_PIVOT_RANK = PREFERRED_PIVOT_NUMERALS.size
13
+ TONIC_PIVOT_RANK = NEUTRAL_PIVOT_RANK + 1
14
+ QUALITIES_WRITTEN_UPPER_CASE = %i[major augmented].freeze
15
+
16
+ attr_reader :tonic, :mode
17
+
18
+ class << self
19
+ def major(tonic)
20
+ new(tonic, :major)
21
+ end
22
+
23
+ def minor(tonic)
24
+ new(tonic, :minor)
25
+ end
26
+
27
+ def coerce(key_or_name)
28
+ key_or_name.is_a?(Key) ? key_or_name : self[key_or_name]
29
+ end
30
+
31
+ def [](name)
32
+ tonic, mode = name.split
33
+ new(tonic, mode.to_s.downcase.to_sym)
34
+ end
35
+ end
36
+
37
+ def initialize(tonic, mode)
38
+ raise ArgumentError, "#{mode} is not a key mode, use major or minor" unless MODES.include?(mode)
39
+
40
+ @tonic = tonic.is_a?(Note) ? tonic : Note.new(tonic)
41
+ @mode = mode
42
+ end
43
+
44
+ def major?
45
+ mode == :major
46
+ end
47
+
48
+ def minor?
49
+ mode == :minor
50
+ end
51
+
52
+ def scale
53
+ @scale ||= (major? ? MajorScale : MinorScale).new(tonic)
54
+ end
55
+
56
+ def signature
57
+ scale.alterations
58
+ end
59
+
60
+ def relative
61
+ major? ? Key.minor(scale.notes[5].down_an_octave) : Key.major(scale.notes[2])
62
+ end
63
+
64
+ def parallel
65
+ Key.new(tonic, major? ? :minor : :major)
66
+ end
67
+
68
+ def dominant_key
69
+ neighbour_on_circle_of_fifths(scale.notes[4])
70
+ end
71
+
72
+ def subdominant_key
73
+ neighbour_on_circle_of_fifths(scale.notes[3])
74
+ end
75
+
76
+ def note(degree)
77
+ raise ArgumentError, "degree must be 1 or more, got #{degree}" if degree < 1
78
+
79
+ octaves_up, index = (degree - 1).divmod(scale.notes.size)
80
+ octaves_up.times.reduce(scale.notes[index]) { |note, _| note.up_an_octave }
81
+ end
82
+
83
+ def chord(numeral, inversion: 0)
84
+ degree = Scale::DEGREES.fetch(degree_index(numeral))
85
+ scale_for(degree).degree_chord(degree, inversion: inversion)
86
+ end
87
+
88
+ def chords(harmonic_function = nil)
89
+ numerals_for(harmonic_function).map { |numeral| chord(numeral) }
90
+ end
91
+
92
+ def numerals
93
+ ROMAN_NUMERALS.zip(chords).map do |numeral, chord|
94
+ (QUALITIES_WRITTEN_UPPER_CASE.include?(chord.quality) ? numeral : numeral.downcase).to_sym
95
+ end
96
+ end
97
+
98
+ def pivot_chords(destination)
99
+ destination = Key.coerce(destination)
100
+ shared_chords_with(destination).sort_by.with_index { |pivot, position| [pivot_rank(pivot), position] }
101
+ end
102
+
103
+ def modulate_to(destination, via: nil, random: Random, voice_leading: true)
104
+ destination = Key.coerce(destination)
105
+ pivot = via ? chosen_pivot(destination, via) : random_pivot(destination, random)
106
+ progression = [chord(:I), pivot&.chord, destination.chord(:V), destination.chord(:I)].compact
107
+ voice_leading ? Chord.voice_lead(progression) : progression
108
+ end
109
+
110
+ def modulate_through(keys, random: Random, voice_leading: true)
111
+ stops = [self] + keys.map { |key| Key.coerce(key) }.drop_while { |key| key.enharmonic_to?(self) }
112
+ progression = stops.each_cons(2).with_index.flat_map do |(from, to), hop|
113
+ chords = from.modulate_to(from.spelling_sharing_most_chords(to), random:, voice_leading: false)
114
+ hop.zero? ? chords : chords.drop(1)
115
+ end
116
+ voice_leading ? Chord.voice_lead(progression) : progression
117
+ end
118
+
119
+ def tonicize(numeral)
120
+ local_tonic_chord = chord(numeral)
121
+ unless MODES.include?(local_tonic_chord.quality)
122
+ raise ArgumentError, "#{numeral} in #{self} is a #{local_tonic_chord.quality} chord, it cannot be a local tonic"
123
+ end
124
+
125
+ Key.new(local_tonic_chord.root, local_tonic_chord.quality)
126
+ end
127
+
128
+ def secondary_dominant(numeral)
129
+ tonicize(numeral).chord(:V)
130
+ end
131
+
132
+ def two_five(numeral)
133
+ local_key = tonicize(numeral)
134
+ [local_key.chord(:ii), local_key.chord(:V)]
135
+ end
136
+
137
+ def simplest_spelling
138
+ enharmonic_spellings.min_by { |key| key.signature.size }
139
+ end
140
+
141
+ def closely_related
142
+ [dominant_key, subdominant_key, relative].map { |key| key.simplest_spelling.with_tonic_octave(tonic.octave) }
143
+ end
144
+
145
+ def distance_to(other)
146
+ other = Key.coerce(other)
147
+ keys_by_distance.index { |keys| keys.any? { |key| key.enharmonic_to?(other) } }
148
+ end
149
+
150
+ def keys_at(distance)
151
+ keys_by_distance.fetch(distance, [])
152
+ end
153
+
154
+ def farthest_distance
155
+ keys_by_distance.size - 1
156
+ end
157
+
158
+ def path_to(destination, random: Random)
159
+ destination = Key.coerce(destination)
160
+ distances = destination.distances_by_pitch_class_and_mode
161
+ path = [self]
162
+ path << path.last.one_step_closer(distances, random) until path.last.enharmonic_to?(destination)
163
+ path[0..-2] + [destination]
164
+ end
165
+
166
+ def ==(other)
167
+ other.is_a?(Key) && tonic.pitch == other.tonic.pitch && mode == other.mode
168
+ end
169
+
170
+ def to_s
171
+ "#{tonic.pitch} #{mode}"
172
+ end
173
+
174
+ def inspect
175
+ "#<#{self.class.name} #{self}>"
176
+ end
177
+
178
+ protected
179
+
180
+ def pitch_class_and_mode
181
+ [tonic.to_midi % Note::SEMITONES_PER_OCTAVE, mode]
182
+ end
183
+
184
+ def enharmonic_to?(other)
185
+ pitch_class_and_mode == other.pitch_class_and_mode
186
+ end
187
+
188
+ def with_tonic_octave(octave)
189
+ Key.new(Note.new(tonic.pitch, octave), mode)
190
+ end
191
+
192
+ def distances_by_pitch_class_and_mode
193
+ keys_by_distance.each_with_index.flat_map do |keys, distance|
194
+ keys.map { |key| [key.pitch_class_and_mode, distance] }
195
+ end.to_h
196
+ end
197
+
198
+ def spelling_sharing_most_chords(key)
199
+ key.enharmonic_spellings.max_by { |spelling| pivot_chords(spelling).size }
200
+ end
201
+
202
+ def enharmonic_spellings
203
+ [self] + tonic.transpose(0).map(&:pitch)
204
+ .reject { |pitch| pitch == tonic.pitch || pitch.length > 2 }
205
+ .map { |pitch| Key.new(Note.new(pitch, tonic.octave), mode) }
206
+ end
207
+
208
+ def one_step_closer(distances, random)
209
+ closely_related.select { |key| distances[key.pitch_class_and_mode] == distances[pitch_class_and_mode] - 1 }
210
+ .sample(random:)
211
+ end
212
+
213
+ private
214
+
215
+ def keys_by_distance
216
+ reached = Set[pitch_class_and_mode]
217
+ levels = [[self]]
218
+ loop do
219
+ farther = levels.last.flat_map(&:closely_related)
220
+ .uniq { |key| key.pitch_class_and_mode }
221
+ .reject { |key| reached.include?(key.pitch_class_and_mode) }
222
+ return levels if farther.empty?
223
+
224
+ reached.merge(farther.map { |key| key.pitch_class_and_mode })
225
+ levels << farther
226
+ end
227
+ end
228
+
229
+ def shared_chords_with(destination)
230
+ chords.zip(numerals).product(destination.chords.zip(destination.numerals))
231
+ .filter_map do |(chord, from_numeral), (destination_chord, to_numeral)|
232
+ next unless chord.spelling == destination_chord.spelling
233
+
234
+ Pivot.new(chord:, from_key: self, from_numeral:, to_key: destination, to_numeral:)
235
+ end
236
+ end
237
+
238
+ def pivot_rank(pivot)
239
+ return TONIC_PIVOT_RANK if tonic_in_either_key?(pivot)
240
+
241
+ PREFERRED_PIVOT_NUMERALS.index(pivot.to_numeral.to_s.upcase) || NEUTRAL_PIVOT_RANK
242
+ end
243
+
244
+ def tonic_in_either_key?(pivot)
245
+ [pivot.from_numeral, pivot.to_numeral].any? { |numeral| numeral.to_s.upcase == 'I' }
246
+ end
247
+
248
+ def random_pivot(destination, random)
249
+ pivot_chords(destination).reject { |pivot| tonic_in_either_key?(pivot) }.sample(random:)
250
+ end
251
+
252
+ def chosen_pivot(destination, via)
253
+ return via if via.is_a?(Pivot)
254
+
255
+ pivot_chords(destination).find { |pivot| pivot.from_numeral.to_s.casecmp?(via.to_s) } ||
256
+ raise(ArgumentError, "#{via} in #{self} is not a chord of #{destination}")
257
+ end
258
+
259
+ def neighbour_on_circle_of_fifths(note)
260
+ Key.new(Note.new(note.pitch, tonic.octave), mode)
261
+ end
262
+
263
+ def scale_for(degree)
264
+ minor? && DEGREES_FROM_HARMONIC_MINOR.include?(degree) ? HarmonicMinorScale.new(tonic) : scale
265
+ end
266
+
267
+ def degree_index(numeral)
268
+ ROMAN_NUMERALS.index(numeral.to_s.upcase) ||
269
+ raise(ArgumentError, "#{numeral} is not a roman numeral between I and VII")
270
+ end
271
+
272
+ def numerals_for(harmonic_function)
273
+ return ROMAN_NUMERALS if harmonic_function.nil?
274
+
275
+ HARMONIC_FUNCTIONS.fetch(harmonic_function) do
276
+ raise ArgumentError, "#{harmonic_function} is not a harmonic function, use tonic, subdominant or dominant"
277
+ end
278
+ end
279
+ end
280
+ end
@@ -0,0 +1,150 @@
1
+ module Musicalism
2
+ class Note
3
+ include Comparable
4
+
5
+ class UnkownNoteError < ArgumentError; end
6
+
7
+ attr_reader :pitch, :octave, :alteration
8
+
9
+ NOTES = [
10
+ ['G##', 'A', 'Bbb'],
11
+ ['A#', 'Bb', 'Cbb'],
12
+ ['A##', 'B', 'Cb'],
13
+ ['B#', 'C', 'Dbb'],
14
+ ['B##', 'C#', 'Db'],
15
+ ['C##', 'D', 'Ebb'],
16
+ ['D#', 'Eb'],
17
+ ['D##', 'E', 'Fb'],
18
+ ['F', 'E#', 'Gbb'],
19
+ ['E##', 'F#', 'Gb'],
20
+ ['F##', 'G', 'Abb'],
21
+ ['G#', 'Ab']
22
+ ]
23
+
24
+ LOWEST_MIDI_NOTE_NUMBER = 21
25
+ HIGHEST_MIDI_NOTE_NUMBER = 108
26
+ MIDI_NUMBER_OF_C0 = 12
27
+ SEMITONES_PER_OCTAVE = 12
28
+ NATURAL_SEMITONES_FROM_C = { 'C' => 0, 'D' => 2, 'E' => 4, 'F' => 5, 'G' => 7, 'A' => 9, 'B' => 11 }.freeze
29
+ ALTERATION_SEMITONES = { '#' => 1, 'b' => -1 }.freeze
30
+ SPELLINGS_FROM_C = NOTES.rotate(NOTES.index { |spellings| spellings.include?('C') }).freeze
31
+
32
+ NOTE_PARTS = %i[pitch octave alteration]
33
+ class << self
34
+ def parse_note_and_alteration(string)
35
+ matchdata = string.match(NOTE_PARSER)
36
+ raise UnkownNoteError, "#{string} is not a valid note" if matchdata.nil?
37
+
38
+ Hash[NOTE_PARTS.zip(matchdata.values_at(*NOTE_PARTS))].tap do |parts|
39
+ parts[:pitch].capitalize!
40
+ parts[:alteration] = nil if parts[:alteration] == ''
41
+ parts[:octave] = Integer(parts[:octave] || DEFAULT_CENTER_OCTAVE)
42
+ end
43
+ end
44
+
45
+ def each
46
+ (LOWEST_MIDI_NOTE_NUMBER..HIGHEST_MIDI_NOTE_NUMBER).each { |midi_number| yield from_midi(midi_number) }
47
+ end
48
+
49
+ def from_midi(midi_number)
50
+ octave, pitch_class = (midi_number - MIDI_NUMBER_OF_C0).divmod(SEMITONES_PER_OCTAVE)
51
+ new("#{natural_or_sharp_spelling(SPELLINGS_FROM_C[pitch_class])}#{octave}")
52
+ end
53
+
54
+ private
55
+
56
+ def natural_or_sharp_spelling(spellings)
57
+ spellings.find { |name| name.match?(/\A[A-G]\z/) } ||
58
+ spellings.find { |name| name.match?(/\A[A-G]#\z/) }
59
+ end
60
+ end
61
+
62
+ NOTE_PARSER = /
63
+ ^(?<pitch>a(?<alteration>\#{0,2}))(?<octave>0)$|
64
+ ^(?<pitch>b(?<alteration>[\#b]{0,2}))(?<octave>0)$|
65
+ ^(?<pitch>[a-g](?<alteration>[\#b]{0,2}))(?<octave>[1-6])$|
66
+ ^(?<pitch>(?:[cdefga])(?<alteration>[\#b]{0,2}))(?<octave>7)$|
67
+ ^(?<pitch>b(?<alteration>\#)?)(?<octave>7)$|
68
+ ^(?<pitch>b(?<alteration>b{1,2}?))(?<octave>7)$|
69
+ ^(?<pitch>c(?<alteration>b{1,2})?)(?<octave>8)$|
70
+ ^(?<pitch>[a-g](?<alteration>[\#b]{0,2}))$
71
+ /ix
72
+
73
+ DEFAULT_CENTER_OCTAVE = 4
74
+
75
+ def initialize(note, octave = nil)
76
+ parsed_note_info = self.class.parse_note_and_alteration("#{note}#{octave}")
77
+ self.pitch = parsed_note_info[:pitch]
78
+ self.octave = parsed_note_info[:octave]
79
+ self.alteration = parsed_note_info[:alteration]
80
+ end
81
+
82
+ def next
83
+ self.class.from_midi(to_midi + 1)
84
+ end
85
+
86
+ def letter
87
+ pitch[0]
88
+ end
89
+
90
+ def up_an_octave
91
+ self.class.new(pitch, octave + 1)
92
+ end
93
+
94
+ def down_an_octave
95
+ self.class.new(pitch, octave - 1)
96
+ end
97
+
98
+ def interval_from(note)
99
+ target_index = NOTES.index { |a| a.include?(note.pitch) }
100
+ self_index = NOTES.index { |a| a.include?(pitch) }
101
+ if self_index > target_index
102
+ self_index - target_index
103
+ elsif (target_index % 12).zero?
104
+ 0
105
+ else
106
+ target_index - self_index
107
+ end
108
+ end
109
+
110
+ def transpose(interval)
111
+ new_note_index = pitch_index + interval
112
+
113
+ new_pitches = if NOTES.length > new_note_index
114
+ NOTES[new_note_index]
115
+ else
116
+ NOTES[new_note_index - NOTES.length]
117
+ end
118
+
119
+ new_pitches.map { |p| self.class.new p }
120
+ end
121
+
122
+ def to_midi
123
+ MIDI_NUMBER_OF_C0 + (octave * SEMITONES_PER_OCTAVE) + semitones_above_c
124
+ end
125
+
126
+ def <=>(other)
127
+ to_midi <=> other.to_midi
128
+ end
129
+
130
+ private
131
+
132
+ attr_writer :pitch, :octave, :alteration
133
+
134
+ def note?(note)
135
+ NOTES.flatten.include?(note)
136
+ end
137
+
138
+ def pitch_index
139
+ NOTES.index { |a| a.include?(pitch) }
140
+ end
141
+
142
+ def semitones_above_c
143
+ NATURAL_SEMITONES_FROM_C.fetch(letter) + alteration_semitones
144
+ end
145
+
146
+ def alteration_semitones
147
+ pitch[1..].each_char.sum { |sign| ALTERATION_SEMITONES.fetch(sign) }
148
+ end
149
+ end
150
+ end
@@ -0,0 +1,11 @@
1
+ module Musicalism
2
+ Pivot = Data.define(:chord, :from_key, :from_numeral, :to_key, :to_numeral) do
3
+ def to_s
4
+ "#{chord}: #{from_numeral} in #{from_key} = #{to_numeral} in #{to_key}"
5
+ end
6
+
7
+ def inspect
8
+ "#<#{self.class.name} #{self}>"
9
+ end
10
+ end
11
+ end
@@ -0,0 +1,2 @@
1
+ module Musicalism
2
+ end
@@ -0,0 +1,16 @@
1
+ module Musicalism
2
+ class MajorScale < Scale
3
+ private
4
+
5
+ def scale_structure
6
+ [
7
+ interval_generator.major_second,
8
+ interval_generator.major_third,
9
+ interval_generator.perfect_forth,
10
+ interval_generator.perfect_fifth,
11
+ interval_generator.major_sixth,
12
+ interval_generator.major_seventh
13
+ ]
14
+ end
15
+ end
16
+ end
@@ -0,0 +1,9 @@
1
+ module Musicalism
2
+ class HarmonicMinorScale < MinorScale
3
+ private
4
+
5
+ def scale_structure
6
+ super[0..-2] + [interval_generator.major_seventh]
7
+ end
8
+ end
9
+ end
@@ -0,0 +1,9 @@
1
+ module Musicalism
2
+ class MelodicMinorScale < MinorScale
3
+ private
4
+
5
+ def scale_structure
6
+ super[0..-3] + [interval_generator.major_sixth, interval_generator.major_seventh]
7
+ end
8
+ end
9
+ end
@@ -0,0 +1,18 @@
1
+ module Musicalism
2
+ class MinorScale < Scale
3
+ private
4
+
5
+ def scale_structure
6
+ [
7
+ interval_generator.major_second,
8
+ interval_generator.minor_third,
9
+ interval_generator.perfect_forth,
10
+ interval_generator.perfect_fifth,
11
+ interval_generator.minor_sixth,
12
+ interval_generator.minor_seventh
13
+ ]
14
+ end
15
+ end
16
+ end
17
+ require 'musicalism/scale/minor/harmonic'
18
+ require 'musicalism/scale/minor/melodic'
@@ -0,0 +1,57 @@
1
+ module Musicalism
2
+ class Scale
3
+ attr_reader :root_note, :interval_generator
4
+
5
+ DEGREES = %i[
6
+ tonic
7
+ supertonic
8
+ mediant
9
+ subdominant
10
+ dominant
11
+ submediant
12
+ subtonic
13
+ ].freeze
14
+
15
+ LETTERS = %w[C D E F G A B].freeze
16
+ ORDER_OF_SHARPS = %w[F C G D A E B].freeze
17
+ ORDER_OF_FLATS = ORDER_OF_SHARPS.reverse.freeze
18
+
19
+ def initialize(root_note)
20
+ @root_note = root_note.is_a?(Note) ? root_note : Note.new(root_note)
21
+ @interval_generator = Interval.new
22
+ end
23
+
24
+ def notes
25
+ @notes ||= scale_structure.each_with_object([root_note]) do |semitones_from_root, scale|
26
+ scale << next_degree_note(scale.last, semitones_from_root)
27
+ end
28
+ end
29
+
30
+ def alterations
31
+ flats, sharps = notes.map(&:pitch).select { |pitch| pitch.length > 1 }.partition { |pitch| pitch.end_with?('b') }
32
+ flats.sort_by { |pitch| ORDER_OF_FLATS.index(pitch[0]) } + sharps.sort_by { |pitch| ORDER_OF_SHARPS.index(pitch[0]) }
33
+ end
34
+
35
+ def degree_chord(degree, options = {})
36
+ Chord.new(tertian_from(DEGREES.index(degree)), options)
37
+ end
38
+
39
+ private
40
+
41
+ def tertian_from(degree_index)
42
+ notes_over_two_octaves.values_at(degree_index, degree_index + 2, degree_index + 4)
43
+ end
44
+
45
+ def notes_over_two_octaves
46
+ notes + notes.map(&:up_an_octave)
47
+ end
48
+
49
+ def next_degree_note(previous_note, semitones_from_root)
50
+ letter = LETTERS[(LETTERS.index(previous_note.letter) + 1) % LETTERS.size]
51
+ pitch = root_note.transpose(semitones_from_root).map(&:pitch).find { |spelling| spelling.start_with?(letter) }
52
+ Note.new(pitch, letter == 'C' ? previous_note.octave + 1 : previous_note.octave)
53
+ end
54
+ end
55
+ end
56
+ require 'musicalism/scale/major'
57
+ require 'musicalism/scale/minor'
@@ -0,0 +1,3 @@
1
+ module Musicalism
2
+ VERSION = '0.1.0'
3
+ end
data/lib/musicalism.rb ADDED
@@ -0,0 +1,18 @@
1
+ require 'musicalism/interval'
2
+ require 'musicalism/note'
3
+ require 'musicalism/chord'
4
+ require 'musicalism/scale'
5
+ require 'musicalism/pivot'
6
+ require 'musicalism/key'
7
+ require 'musicalism/version'
8
+
9
+ module Musicalism
10
+ # RYTHMS = [
11
+ # DOUBLE_WHOLE_NOTE = 2.to_r,
12
+ # WHOLE_NOTE = :wn,
13
+ # HALF_NOTE = :hn,
14
+ # QUARTER_NOTE = :qn,
15
+ # EIGHTH_NOTE = ,
16
+
17
+ # ].freeze
18
+ end
metadata ADDED
@@ -0,0 +1,126 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: musicalism
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Yann Marquet
8
+ bindir: bin
9
+ cert_chain: []
10
+ date: 1980-01-02 00:00:00.000000000 Z
11
+ dependencies:
12
+ - !ruby/object:Gem::Dependency
13
+ name: debug
14
+ requirement: !ruby/object:Gem::Requirement
15
+ requirements:
16
+ - - ">="
17
+ - !ruby/object:Gem::Version
18
+ version: '0'
19
+ type: :development
20
+ prerelease: false
21
+ version_requirements: !ruby/object:Gem::Requirement
22
+ requirements:
23
+ - - ">="
24
+ - !ruby/object:Gem::Version
25
+ version: '0'
26
+ - !ruby/object:Gem::Dependency
27
+ name: rake
28
+ requirement: !ruby/object:Gem::Requirement
29
+ requirements:
30
+ - - ">="
31
+ - !ruby/object:Gem::Version
32
+ version: '0'
33
+ type: :development
34
+ prerelease: false
35
+ version_requirements: !ruby/object:Gem::Requirement
36
+ requirements:
37
+ - - ">="
38
+ - !ruby/object:Gem::Version
39
+ version: '0'
40
+ - !ruby/object:Gem::Dependency
41
+ name: rspec
42
+ requirement: !ruby/object:Gem::Requirement
43
+ requirements:
44
+ - - ">="
45
+ - !ruby/object:Gem::Version
46
+ version: '0'
47
+ type: :development
48
+ prerelease: false
49
+ version_requirements: !ruby/object:Gem::Requirement
50
+ requirements:
51
+ - - ">="
52
+ - !ruby/object:Gem::Version
53
+ version: '0'
54
+ - !ruby/object:Gem::Dependency
55
+ name: rspec-its
56
+ requirement: !ruby/object:Gem::Requirement
57
+ requirements:
58
+ - - ">="
59
+ - !ruby/object:Gem::Version
60
+ version: '0'
61
+ type: :development
62
+ prerelease: false
63
+ version_requirements: !ruby/object:Gem::Requirement
64
+ requirements:
65
+ - - ">="
66
+ - !ruby/object:Gem::Version
67
+ version: '0'
68
+ - !ruby/object:Gem::Dependency
69
+ name: yard
70
+ requirement: !ruby/object:Gem::Requirement
71
+ requirements:
72
+ - - ">="
73
+ - !ruby/object:Gem::Version
74
+ version: '0'
75
+ type: :development
76
+ prerelease: false
77
+ version_requirements: !ruby/object:Gem::Requirement
78
+ requirements:
79
+ - - ">="
80
+ - !ruby/object:Gem::Version
81
+ version: '0'
82
+ description: Notes, scales, chords, keys, modulations and the key graph, for live
83
+ coding and MIDI
84
+ email:
85
+ - ymarquet@gmail.com
86
+ executables: []
87
+ extensions: []
88
+ extra_rdoc_files: []
89
+ files:
90
+ - LICENSE
91
+ - README.md
92
+ - lib/musicalism.rb
93
+ - lib/musicalism/chord.rb
94
+ - lib/musicalism/interval.rb
95
+ - lib/musicalism/key.rb
96
+ - lib/musicalism/note.rb
97
+ - lib/musicalism/pivot.rb
98
+ - lib/musicalism/rythm.rb
99
+ - lib/musicalism/scale.rb
100
+ - lib/musicalism/scale/major.rb
101
+ - lib/musicalism/scale/minor.rb
102
+ - lib/musicalism/scale/minor/harmonic.rb
103
+ - lib/musicalism/scale/minor/melodic.rb
104
+ - lib/musicalism/version.rb
105
+ homepage: https://github.com/StupidCodeFactory/musicalism
106
+ licenses:
107
+ - MIT
108
+ metadata: {}
109
+ rdoc_options: []
110
+ require_paths:
111
+ - lib
112
+ required_ruby_version: !ruby/object:Gem::Requirement
113
+ requirements:
114
+ - - ">="
115
+ - !ruby/object:Gem::Version
116
+ version: '3.2'
117
+ required_rubygems_version: !ruby/object:Gem::Requirement
118
+ requirements:
119
+ - - ">="
120
+ - !ruby/object:Gem::Version
121
+ version: '0'
122
+ requirements: []
123
+ rubygems_version: 4.0.20
124
+ specification_version: 4
125
+ summary: 'Music theory in plain Ruby: keys, chords and the paths between them'
126
+ test_files: []