@kairotic/app 0.0.0-stage → 0.2.1

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.
Files changed (96) hide show
  1. package/README.md +9 -2
  2. package/index.html +1101 -0
  3. package/kairotic/api.cljs +362 -0
  4. package/kairotic/assistant.cljs +505 -0
  5. package/kairotic/backends/gun-backend.js +371 -0
  6. package/kairotic/canvas.cljs +751 -0
  7. package/kairotic/code.cljs +108 -0
  8. package/kairotic/components.cljs +838 -0
  9. package/kairotic/core.cljs +96 -0
  10. package/kairotic/corefns.cljs +473 -0
  11. package/kairotic/docs.mjs +2 -0
  12. package/kairotic/engine.cljs +482 -0
  13. package/kairotic/examples.mjs +96 -0
  14. package/kairotic/faust.cljs +225 -0
  15. package/kairotic/help.cljs +1036 -0
  16. package/kairotic/hiccup.cljs +566 -0
  17. package/kairotic/input.cljs +271 -0
  18. package/kairotic/kfile.mjs +138 -0
  19. package/kairotic/library.cljs +214 -0
  20. package/kairotic/links.cljs +41 -0
  21. package/kairotic/mt.cljs +1604 -0
  22. package/kairotic/mtboxes.cljs +276 -0
  23. package/kairotic/packages/analysis.mjs +64 -0
  24. package/kairotic/packages/controls.mjs +28 -0
  25. package/kairotic/packages/data.mjs +22 -0
  26. package/kairotic/packages/faust-units/cmaes.mjs +82 -0
  27. package/kairotic/packages/faust-units/graph.mjs +212 -0
  28. package/kairotic/packages/faust-units/listen.mjs +125 -0
  29. package/kairotic/packages/faust-units/notation.mjs +139 -0
  30. package/kairotic/packages/faust-units/parse.mjs +439 -0
  31. package/kairotic/packages/faust-units/recipe.mjs +195 -0
  32. package/kairotic/packages/faust-units/render.mjs +69 -0
  33. package/kairotic/packages/faust-units/units.mjs +130 -0
  34. package/kairotic/packages/faust-units/view.mjs +353 -0
  35. package/kairotic/packages/faust-units.mjs +9 -0
  36. package/kairotic/packages/io.mjs +58 -0
  37. package/kairotic/packages/net.mjs +28 -0
  38. package/kairotic/packages/patterns.mjs +34 -0
  39. package/kairotic/packages/spatial.mjs +22 -0
  40. package/kairotic/packages/spectral/shift.mjs +169 -0
  41. package/kairotic/packages/spectral.mjs +16 -0
  42. package/kairotic/packages/synth.mjs +28 -0
  43. package/kairotic/packages/theory/counterpoint.mjs +798 -0
  44. package/kairotic/packages/theory/mirror.mjs +221 -0
  45. package/kairotic/packages/theory.mjs +46 -0
  46. package/kairotic/patterns.cljs +538 -0
  47. package/kairotic/presets.cljs +227 -0
  48. package/kairotic/quantize.cljs +782 -0
  49. package/kairotic/record.cljs +169 -0
  50. package/kairotic/release.cljs +90 -0
  51. package/kairotic/ring.cljs +129 -0
  52. package/kairotic/ringaudio.cljs +232 -0
  53. package/kairotic/ringcore.mjs +270 -0
  54. package/kairotic/score.cljs +176 -0
  55. package/kairotic/shapes.cljs +283 -0
  56. package/kairotic/signal.cljs +327 -0
  57. package/kairotic/sounds.cljs +565 -0
  58. package/kairotic/sounds.mjs +108 -0
  59. package/kairotic/span.cljs +129 -0
  60. package/kairotic/spell.cljs +281 -0
  61. package/kairotic/structure.cljs +145 -0
  62. package/kairotic/talk.cljs +115 -0
  63. package/kairotic/tempo.cljs +226 -0
  64. package/kairotic/treecanvas.cljs +299 -0
  65. package/kairotic/tutorials.mjs +1283 -0
  66. package/kairotic/vendor/codemirror.mjs +23 -0
  67. package/package.json +23 -4
  68. package/page/00-work.cljs +862 -0
  69. package/page/01-commands.cljs +1219 -0
  70. package/page/02-patch-view.cljs +1051 -0
  71. package/page/03-history-view.cljs +481 -0
  72. package/page/04-panels.cljs +448 -0
  73. package/page/05-gestures.cljs +1247 -0
  74. package/page/06-connection.cljs +219 -0
  75. package/page/07-claude.cljs +430 -0
  76. package/page/08-sessions.cljs +423 -0
  77. package/page/09-learn.cljs +602 -0
  78. package/page/10-embed.cljs +469 -0
  79. package/page/11-startup.cljs +61 -0
  80. package/page/12-feedback.cljs +172 -0
  81. package/page/13-perform.cljs +325 -0
  82. package/page/14-editor.cljs +656 -0
  83. package/page/15-presets.cljs +230 -0
  84. package/page/16-release.cljs +242 -0
  85. package/page/17-sounds.cljs +147 -0
  86. package/page/18-lines.cljs +594 -0
  87. package/page/19-files.cljs +247 -0
  88. package/page/19-html.cljs +152 -0
  89. package/page/20-talk.cljs +527 -0
  90. package/page/21-net.cljs +110 -0
  91. package/page/22-learn.cljs +303 -0
  92. package/page/23-ids.cljs +233 -0
  93. package/page/24-clipboard.cljs +136 -0
  94. package/page/25-tidy.cljs +74 -0
  95. package/page/26-probes.cljs +111 -0
  96. package/sources.mjs +2 -0
@@ -0,0 +1,782 @@
1
+ ;; SPDX-License-Identifier: MPL-2.0
2
+ ;; Kairotic · quantize
3
+ ;; Free time written as measured notation (issue #86): the strokes of a freqt, or the notes of a tree
4
+ ;; without measures, become a tree of measures, tuplets, ties and grace notes, which kairotic.mt writes
5
+ ;; as MEI (and Verovio draws). The tree is plain EDN: it can be read, kept and edited like any other.
6
+ ;;
7
+ ;; How (after bach.quantize, FOMUS, Nauert):
8
+ ;; 1. the frame: the meter comes from the bar grid of the buffer (:gx, its cycles: [4] → 4/4,
9
+ ;; [1.5 1.5 1] → 8/8 [3+3+2]) or from the options; without a grid, 4/4.
10
+ ;; 2. each bar is cut in spans (the beats of a simple meter; the groups, or dotted beats, of 6/8, 7/8 …)
11
+ ;; and every span tries a set of divisions (1 2 3 4 5 6 7 8, and those of its own units); each
12
+ ;; division costs the distance from the starts (and, less, the ends) to its points, how deep the
13
+ ;; points it uses are (the beat, its half, its quarters, then much more for 32nds; a third, a fifth…),
14
+ ;; being a tuplet (3 less than 5, 5 less than 7) and the notes it loses (two starts that fall on one
15
+ ;; point, a note that shrinks to nothing). In a simple meter two beats may also go
16
+ ;; together (a half-note triplet). Each span keeps its few cheapest divisions, and the plan of a
17
+ ;; bar chooses among them with its neighbours in view: changing kind of division (binary, triplet,
18
+ ;; quintuplet…) from one region to the next costs :coh, so that a lone triplet among eighths pays
19
+ ;; twice and a run of triplets once (issue #108; the bar starts from the kind the one before ended
20
+ ;; with). The cheapest plan of each bar wins.
21
+ ;; A beat can also be cut in halves (a dotted beat in its eighths), each with its own division.
22
+ ;; 3. notes that overlap go to different voices (layers of one staff), all on the same points;
23
+ ;; the notes are written on those points: chords where starts meet, rests in the gaps,
24
+ ;; a tie where a note goes on over a barline or into or out of a tuplet, a grace note for a note too
25
+ ;; short for any point. How each value is written (where the beats have to be seen) is kairotic.mt's
26
+ ;; work (mt/metric-split), so that hand-written trees get it too.
27
+ ;;
28
+ ;; Options (all optional): {:meter "5/8[2+3]" :meters ["3/4" "3/4" "5/8[2+3]"] :divs [1 2 3 4 5 6 7 8] :merge [3 5 6] :grace true
29
+ ;; :chord 0.04 :legato 0.25 :tempo 72 :w {:err 8 :off 0.35 :cpx 1 :lost 1.5 :coh 0.5}}. :divs are the divisions a
30
+ ;; span may take, :merge those of two beats together ([] for none), :chord how close two starts are to be
31
+ ;; one chord (beats), :legato the largest gap before the next note that is not a rest (beats; 0: every gap
32
+ ;; is), :key the key the score is written in ("eb", "c#m", :none; without it no signature, and names
33
+ ;; from the key the notes suggest), :time how the notes' time becomes beats (:track finds the beats of notes
34
+ ;; played freely, in seconds or at any tempo: kairotic.tempo; a map [[time beat] …] is one found and kept;
35
+ ;; without it their time is already in beats), :w the weights of the cost; :voices (2) how many voices overlapping notes may take, :overlap how
36
+ ;; much a note may run into the next and stay in its voice, :nest false for no beats cut in parts, and
37
+ ;; :meters a meter for each bar (the last going on: meter changes, issue #107), :fix {beat-start choice} the divisions chosen by hand (n, [n1 n2] or [:merge n]: see `choices`).
38
+ ;; With :time (played time), :ref-bpm (100) weighs the error of a note in seconds rather than in beats: faster than
39
+ ;; ref-bpm, :err weighs less, in proportion (down to a third), so that what a player is off by in milliseconds does
40
+ ;; not turn into finer divisions at fast tempos (nil: in beats, as without :time).
41
+
42
+ (ns kairotic.quantize
43
+ (:require [kairotic.canvas :as cv]
44
+ [kairotic.spell :as sp]
45
+ [kairotic.mt :as mt]
46
+ [kairotic.tempo :as tm]))
47
+
48
+ (def eps 1e-6)
49
+ (defn- near? [a b] (< (js/Math.abs (- a b)) eps))
50
+ (defn- whole? [x] (near? x (js/Math.round x)))
51
+ (defn- gcd [a b] (if (zero? b) (js/Math.abs a) (recur b (mod a b))))
52
+
53
+ (def defaults
54
+ {:divs [1 2 3 4 5 6 7 8]
55
+ :ref-bpm 100
56
+ :merge [3 5 6]
57
+ :grace true
58
+ :chord 0.04
59
+ :legato 0.25
60
+ :voices 2
61
+ :nest true
62
+ :overlap 0.15
63
+ :w {:err 8 :off 0.35 :cpx 1 :lost 1.5 :coh 0.5}})
64
+
65
+ ;; ───────── 1. the frame ─────────
66
+
67
+ (defn- default-groups [p q]
68
+ (cond (<= q 4) (vec (repeat p 1))
69
+ (and (zero? (mod p 3)) (> p 3)) (vec (repeat (quot p 3) 3))
70
+ (<= p 3) [p]
71
+ :else nil))
72
+
73
+ (defn meter-of-grid
74
+ "The meter a bar grid (:gx) stands for: its cycles, in beats, counted in quarters when they are whole
75
+ ([4] → 4/4, [3] → 3/4, [2 3] → 5/4 [2+3]), in eighths when they need them ([1.5 1.5] → 6/8,
76
+ [1.5 1.5 1] → 8/8 [3+3+2]), and so on. Without a grid, 4/4."
77
+ [gx]
78
+ (let [cs (vec (or (seq (:cycles gx)) [4]))
79
+ q (first (filter (fn [q] (every? (fn [c] (and (pos? c) (whole? (* c (/ q 4))))) cs)) [4 8 16 32]))]
80
+ (if-not q
81
+ {:meter [4 4]}
82
+ (let [us (mapv (fn [c] (js/Math.round (* c (/ q 4)))) cs) p (reduce + us)]
83
+ (cond-> {:meter [p q]} (and (> (count us) 1) (not= us (default-groups p q))) (assoc :groups us))))))
84
+
85
+ (defn sane-choice
86
+ "A division chosen for a span: n (the span in n), [n1 n2 …] (cut in parts, each its own division) or
87
+ [:merge n] (with the next beat, in n). nil if it is none of those."
88
+ [c]
89
+ (let [n? (fn [x] (and (number? x) (whole? x) (<= 1 x 24)))]
90
+ (cond (n? c) (js/Math.round c)
91
+ (and (vector? c) (= :merge (first c)) (n? (second c))) [:merge (js/Math.round (second c))]
92
+ (and (vector? c) (<= 2 (count c) 3) (every? n? c)) (mapv js/Math.round c)
93
+ :else nil)))
94
+
95
+ (defn sane-fix
96
+ "The divisions chosen by hand, {span-start choice} (beats → see sane-choice), without what does not read."
97
+ [f]
98
+ (when (map? f)
99
+ (not-empty (into {} (for [[k v] f :let [c (sane-choice v)] :when (and (number? k) (>= k 0) c)] [k c])))))
100
+
101
+ (defn sane-spell
102
+ "Names chosen by hand for notes of a quantized score: {[beat midi] name} (the beat where the note starts
103
+ in the score, its MIDI pitch), keeping only names that sound that pitch."
104
+ [m]
105
+ (when (map? m)
106
+ (not-empty (into {} (for [[k v] m
107
+ :let [[t p] (when (vector? k) k) w (sp/parse v)]
108
+ :when (and (number? t) (number? p) w (= (sp/->midi w) (js/Math.round p)))]
109
+ [[t (js/Math.round p)] (sp/->name w)])))))
110
+
111
+ (defn respell-by-hand
112
+ "A tree with the names chosen by hand (:spell, see sane-spell) on the notes that start at that beat
113
+ with that pitch."
114
+ [t spell]
115
+ (if (empty? spell)
116
+ t
117
+ (let [evs (filter (fn [e] (= :note (:kind e))) (mt/events t))]
118
+ (reduce (fn [t e]
119
+ (if-let [nm (some (fn [[[bt p] v]] (when (and (< (js/Math.abs (- bt (:t e))) 1e-4) (= p (js/Math.round (:pitch e)))) v)) spell)]
120
+ (mt/apply-op t [:attrs (:path e) (assoc (mt/attrs (mt/node-at t (:path e))) :pitch nm)])
121
+ t))
122
+ t evs))))
123
+
124
+ (defn options
125
+ "The options of a quantization, with the defaults, and its meter ({:meter [p q] :groups …}): the one
126
+ given, or that of the bar grid gx."
127
+ [opts gx]
128
+ (let [o (merge defaults (when (map? opts) opts))
129
+ ints (fn [xs] (vec (filter (fn [n] (and (number? n) (whole? n) (<= 1 n 24))) (when (sequential? xs) xs))))]
130
+ (assoc o
131
+ :meter (if (some? (:meter opts)) (mt/meter-of (if (map? (:meter opts)) (:meter opts) {:meter (:meter opts) :groups (:groups opts)}))
132
+ (meter-of-grid gx))
133
+ :divs (let [d (ints (:divs o))] (if (seq d) d (:divs defaults)))
134
+ :merge (ints (:merge o))
135
+ :chord (let [x (:chord o)] (if (and (number? x) (>= x 0)) x (:chord defaults)))
136
+ :legato (let [x (:legato o)] (if (and (number? x) (>= x 0)) x (:legato defaults)))
137
+ :overlap (let [x (:overlap o)] (if (and (number? x) (>= x 0)) x (:overlap defaults)))
138
+ :voices (let [x (:voices o)] (if (and (number? x) (whole? x) (<= 1 x 4)) (js/Math.round x) (:voices defaults)))
139
+ :fix (sane-fix (:fix o))
140
+ :key (let [k (:key o)] (when (and (some? k) (sp/parse-key k)) k))
141
+ :spell (sane-spell (:spell o))
142
+ :step (when (and (map? gx) (number? (:step gx)) (pos? (:step gx))) (:step gx))
143
+ ;; a meter for each bar, the last one going on (issue #107): ["3/4" "3/4" "5/8[2+3]"]
144
+ :meters (let [ms (:meters o)]
145
+ (when (and (sequential? ms) (seq ms))
146
+ (not-empty (vec (keep (fn [m] (try (mt/meter-of (if (map? m) m {:meter m})) (catch :default _ nil))) ms)))))
147
+ ;; played time (issue #106): :track finds the beats, a map [[time beat] …] is one kept
148
+ :time (let [x (:time o)] (cond (= x :track) :track (some? x) (tm/sane-map x) :else nil))
149
+ :w (merge (:w defaults) (when (map? (:w opts)) (:w opts))))))
150
+
151
+ (declare plan)
152
+
153
+ (defn track-map
154
+ "The time map of notes played freely (issue #106): the beats found by kairotic.tempo, and how many quarters
155
+ each is worth (½, 1, 1½ or 2, so that a bar holds a whole number of them) chosen by analysis by synthesis:
156
+ with the downbeat among the two beats where the notes weigh most (tempo/phase-weights), by analysis by
157
+ synthesis: the choice whose quantization costs least, with a preference for moderate tempos (around 100 bpm,
158
+ :prior-w). Measured on the benchmark (issue #105, --timed) against simpler rules. When the phase is
159
+ ambiguous it can miss a pickup: :downbeat (the time of a note known to start a bar) fixes it. nil when no
160
+ beat is found."
161
+ [notes o]
162
+ (when-let [{:keys [os beats period]} (tm/beats-of notes (:track o))]
163
+ (let [{[p q] :meter} (:meter o) BL (* p (/ 4 q))
164
+ P (/ (- (peek beats) (first beats)) (max 1 (dec (count beats))))
165
+ lp (fn [bpm] (let [x (/ (js/Math.log (/ bpm (or (:prior-bpm o) 100))) js/Math.LN2)] (* x x)))
166
+ o1 (dissoc o :time :fix)
167
+ ;; for each value of the beat, the two phases where the notes weigh most (tempo/phase-weights)
168
+ ;; (with :downbeat, the time of a note known to be on a downbeat, the phase that puts one there)
169
+ db (:downbeat o)
170
+ bv (vec beats)
171
+ db-i (when (number? db) (apply min-key (fn [i] (js/Math.abs (- (bv i) db))) (range (count bv))))
172
+ cands (for [u [0.5 1 1.5 2] :when (whole? (/ BL u))
173
+ :let [m (js/Math.round (/ BL u)) pw (tm/phase-weights os beats m)]
174
+ k (if db-i [(mod db-i m)] (take 2 (sort-by (fn [k] (- (pw k))) (range m))))]
175
+ (tm/map-of beats u m k))
176
+ cost (fn [mp] (+ (reduce + (map :cost (:rs (plan (tm/map-notes notes mp) o1))))
177
+ (* (or (:prior-w o) 3) (lp (tm/tempo-of-map mp)))))]
178
+ (when (seq cands) (apply min-key cost cands)))))
179
+
180
+ (def ^:private tracked (memoize (fn [notes o] (track-map notes o))))
181
+
182
+ (defn time-map-of
183
+ "The time map notes in free time are quantized through (options :time): the one kept, the one found
184
+ (:track, from the onsets and the meter), or nil (their time is already in beats)."
185
+ [notes o]
186
+ (let [x (:time o)]
187
+ (cond (vector? x) x
188
+ (= x :track) (tracked (mapv (fn [n] (select-keys n [:on :off :attrs])) notes) (select-keys o [:meter :meters :w :divs :merge :nest :chord :prior-w :prior-bpm :downbeat :track]))
189
+ :else nil)))
190
+
191
+ (defn timed
192
+ "Notes in free time onto beats, through their time map (see time-map-of): [notes map]."
193
+ [notes o]
194
+ (if-let [m (time-map-of notes o)] [(tm/map-notes notes m) m] [notes nil]))
195
+
196
+ (defn spans
197
+ "The spans of a bar the quantizer divides, as [start length units] (beats from the bar's start, and
198
+ how many units of the meter): the beats of a simple meter (in 5/4 [2+3] too); the groups of a meter
199
+ in eighths or shorter, or its dotted beats (6/8 in two), or the whole bar (3/8); else pairs of units
200
+ and a last three (7/8 → 2+2+3)."
201
+ [meter]
202
+ (let [{[p q] :meter g :groups} (mt/meter-of meter) u (/ 4 q)
203
+ us (cond (<= q 4) (repeat p 1)
204
+ (seq g) g
205
+ (and (zero? (mod p 3)) (> p 3)) (repeat (quot p 3) 3)
206
+ (<= p 3) [p]
207
+ :else (let [n2 (quot p 2)] (if (odd? p) (concat (repeat (dec n2) 2) [3]) (repeat n2 2))))
208
+ lens (map (fn [k] (* k u)) us)]
209
+ (mapv vector (reductions + 0 lens) lens us)))
210
+
211
+ ;; ───────── 2. the divisions of a span ─────────
212
+
213
+ (defn- odd-part [n] (loop [n n] (if (and (pos? n) (even? n)) (recur (/ n 2)) n)))
214
+
215
+ (defn- largest-prime [n]
216
+ (loop [n n f 2 top 1]
217
+ (cond (< n 2) top
218
+ (> (* f f) n) (max top n)
219
+ (zero? (mod n f)) (recur (/ n f) f f)
220
+ :else (recur n (inc f) top))))
221
+
222
+ (defn tuplet-of
223
+ "The tuplet n points in a span of L beats need: nil when their unit is a written value (plain or
224
+ dotted: three in a quarter of 6/8 are eighths), [n m] when it is not (n in the time of m: 3 in a
225
+ quarter are [3 2] eighths, 5 are [5 4] sixteenths), or :none when no tuplet writes it."
226
+ [L n]
227
+ (let [u (/ L n) x (* u 64)]
228
+ (if (and (whole? x) (#{1 3} (odd-part (js/Math.round x))))
229
+ nil
230
+ (let [up (loop [w 1] (cond (< w (- u eps)) (recur (* 2 w)) (>= (/ w 2) (- u eps)) (recur (/ w 2)) :else w))
231
+ down (loop [w up] (if (> w (+ u eps)) (recur (/ w 2)) w))
232
+ m (some (fn [w] (let [m (/ L w)] (when (whole? m) (js/Math.round m)))) [up down])]
233
+ (if m [n m] :none)))))
234
+
235
+ (defn complexity
236
+ "What a division costs before any note is put on it: a tuplet, by its largest prime (3, 5, 7, more),
237
+ a grid of dotted values a little, and a very little more for each point (between two divisions that
238
+ place the notes alike, the simpler one)."
239
+ [L n]
240
+ (let [tup (tuplet-of L n)]
241
+ (+ (* 0.01 n)
242
+ (cond (nil? tup) (if (= 3 (odd-part (js/Math.round (* 64 (/ L n))))) 0.05 0)
243
+ (= :none tup) 99
244
+ :else (let [[a b] tup g (gcd a b)]
245
+ (case (largest-prime (* (/ a g) (/ b g))) 3 0.25 5 0.5 7 0.7 1.0))))))
246
+
247
+ (defn depth
248
+ "How deep point k of n in a span of L beats is, as a cost to read a note there: 0 on the beat, little on
249
+ its half, more on its quarters, much on eighths of a beat and below (32nds); in a tuplet, by how many
250
+ parts its fraction of the span has (a third, a fifth …)."
251
+ [L n k]
252
+ (if (zero? (mod k n))
253
+ 0
254
+ (if (nil? (tuplet-of L n))
255
+ (let [x (* k (/ L n))
256
+ den (loop [d 1] (if (or (whole? (* x d)) (> d 64)) d (recur (* 2 d))))]
257
+ (case den 1 0 2 0.05 4 0.15 8 0.8 16 1.2 1.5))
258
+ (let [d (/ n (gcd k n))]
259
+ (case d 2 0.05 4 0.15 (+ 0.1 (* 0.05 d)))))))
260
+
261
+ (defn- points-in [pts a b] (filterv (fn [p] (and (>= (:t p) (- a eps)) (< (:t p) (- b eps)))) pts))
262
+
263
+ (defn span-options
264
+ "Every division of the span [s, s+L) for the points that fall in it ({:t :kind :on|:off :note i}),
265
+ cheapest first: [{:n :tup :cost}]. merged?: two beats together (only the :merge divisions)."
266
+ [s L units pts o merged?]
267
+ (let [W (:w o)
268
+ divs (distinct (concat (if merged?
269
+ (:merge o)
270
+ (concat (:divs o) (map (fn [k] (* units k)) [1 2 4])
271
+ (when-let [st (:step o)] (let [n (/ L st)] (when (and (whole? n) (<= n 16)) [(js/Math.round n)])))))))]
272
+ (->> (for [n divs
273
+ :when (and (<= 1 n 24) (not (and merged? (= 1 n))))
274
+ :let [tup (tuplet-of L n)]
275
+ :when (not= :none tup)
276
+ :let [g (/ L n)
277
+ ks (mapv (fn [p] (js/Math.round (/ (- (:t p) s) g))) pts)
278
+ err (reduce + (map (fn [p k] (* (if (= :on (:kind p)) 1 (:off W)) (js/Math.abs (- (:t p) (+ s (* k g))))))
279
+ pts ks))
280
+ ons (filter (fn [[p _]] (= :on (:kind p))) (map vector pts ks))
281
+ ;; starts that meet on one point though they were not together: one is lost (or a chord)
282
+ clash (reduce + (for [[_ grp] (group-by second ons) :when (> (count grp) 1)
283
+ :let [ts (map (comp :t first) grp)]]
284
+ (if (> (- (apply max ts) (apply min ts)) (:chord o)) (dec (count grp)) 0)))
285
+ ;; a note that starts and ends on the same point vanishes
286
+ gone (count (filter (fn [[_ xs]] (and (= 2 (count xs)) (apply = (map second xs))))
287
+ (group-by (comp :note first) (map vector pts ks))))
288
+ deep (reduce + (map (fn [p k] (* (if (= :on (:kind p)) 1 (:off W)) (depth L n k))) pts ks))
289
+ cost (+ (* (:err W) err)
290
+ (* (:cpx W) (+ (complexity L n) deep (if merged? 0.1 0)))
291
+ (* (:lost W) (+ clash gone)))
292
+ ;; the division its notes need: the fewest points that hold the same ones (two eighths on
293
+ ;; a grid of six need two)
294
+ need (/ n (reduce gcd n ks))]]
295
+ {:n n :tup tup :cost cost :need need})
296
+ (sort-by :cost)
297
+ vec)))
298
+
299
+ (defn- nested-of
300
+ "The span cut in parts (halves of a beat, the three eighths of a dotted beat), each with its own
301
+ cheapest division, when one of them needs a tuplet the whole span cannot give; or nil."
302
+ [s L u pts o]
303
+ (let [k (cond (and (= u 3) (zero? (mod (* 64 L) 3))) 3 (or (= u 1) (= u 2)) 2 :else nil)]
304
+ (when (and k (:nest o))
305
+ (let [pl (/ L k)
306
+ parts (mapv (fn [i] (let [ps (+ s (* i pl))]
307
+ (assoc (first (span-options ps pl (/ u k) (points-in pts ps (+ ps pl)) o false)) :s ps :L pl)))
308
+ (range k))]
309
+ (when (some :tup parts)
310
+ {:s s :L L :n k :tup nil :parts parts
311
+ :cost (+ (reduce + (map :cost parts)) (* (:cpx (:w o)) 0.15))})))))
312
+
313
+ (defn best-of-span
314
+ "The cheapest way to divide one span [s, s+L) of u units: a division of the whole span, or the span cut
315
+ in parts (halves of a beat, the three eighths of a dotted beat) each with its own division, when one of
316
+ them needs a tuplet the whole span cannot give (an eighth and a triplet of sixteenths). {:s :L :n :tup
317
+ :cost}, with :parts [regions] when it is cut."
318
+ [s L u pts o]
319
+ (let [flat (assoc (first (span-options s L u (points-in pts s (+ s L)) o false)) :s s :L L)
320
+ nested (nested-of s L u pts o)]
321
+ (if (and nested (< (:cost nested) (:cost flat))) nested flat)))
322
+
323
+ (defn- span-candidates
324
+ "The few cheapest ways to divide a span (issue #108: the plan of a bar chooses among them with its
325
+ neighbours in view): the best divisions of the whole span, and the span cut in parts."
326
+ [s L u pts o]
327
+ (let [in (points-in pts s (+ s L))]
328
+ (vec (concat (map (fn [x] (assoc x :s s :L L)) (take 4 (span-options s L u in o false)))
329
+ (when-let [x (nested-of s L u pts o)] [x])))))
330
+
331
+ (defn family
332
+ "The kind of division a region has, for coherence between neighbours (issue #108): :none when it puts
333
+ one point on the span (the beat alone: it says nothing), :bin for written values (halves, quarters, the
334
+ eighths of a dotted beat), and for a tuplet the largest prime of its count (3, 5, 7…), all by the
335
+ points its notes use (:need), not the grid it is written on: two eighths on a grid of six are binary.
336
+ A span cut in parts has the family of its tuplet part."
337
+ [r]
338
+ (let [m (or (:need r) (:n r))
339
+ tup (if (and (:need r) (:L r)) (tuplet-of (:L r) m) (:tup r))]
340
+ (cond (:parts r) (or (some (fn [p] (let [f (family p)] (when (number? f) f))) (:parts r)) :bin)
341
+ (= 1 m) :none
342
+ (vector? tup) (largest-prime (first tup))
343
+ :else :bin)))
344
+
345
+ (defn- after
346
+ "The family in force after a region: its own, or the one before when it says nothing."
347
+ [fam r] (let [f (family r)] (if (= f :none) fam f)))
348
+
349
+ (defn- switch-cost
350
+ "What it costs to go from one family to another between neighbouring regions (:coh of the weights): a
351
+ lone triplet among eighths pays twice, a run of triplets once."
352
+ [fam r o]
353
+ (let [f (family r)]
354
+ (if (or (= f :none) (= fam :none) (= f fam)) 0 (or (:coh (:w o)) 0))))
355
+
356
+ (def ^:private forced -1e6)
357
+
358
+ (defn- fix-at [o s] (some (fn [[k v]] (when (near? k s) v)) (:fix o)))
359
+ (defn- merge-choice? [c] (and (vector? c) (= :merge (first c))))
360
+
361
+ (defn- choose-span
362
+ "The division c chosen for the span [s, s+L) (n, or [n1 n2 …] for its parts) as a region that the plan
363
+ takes whatever it costs, or nil when the span cannot take it."
364
+ [s L u pts o c]
365
+ (let [with (fn [ps pl pu n] (some-> (first (filter (fn [x] (= n (:n x)))
366
+ (span-options ps pl pu (points-in pts ps (+ ps pl)) (update o :divs conj n) false)))
367
+ (assoc :s ps :L pl)))]
368
+ (cond (number? c) (some-> (with s L u c) (assoc :cost forced))
369
+ (and (vector? c) (number? (first c)))
370
+ (let [k (count c) pl (/ L k)
371
+ parts (mapv (fn [i n] (with (+ s (* i pl)) pl (/ u k) n)) (range k) c)]
372
+ (when (every? some? parts) {:s s :L L :n k :tup nil :parts parts :cost forced}))
373
+ :else nil)))
374
+
375
+ (defn bar-plan
376
+ "The cheapest way to divide one bar (it starts at beat b0) for the points in it: its regions
377
+ [{:s :L :n :tup :cost}] in order, each a span (or two beats together) with its division. Each span
378
+ weighs its few cheapest divisions with its neighbours in view: changing kind of division (binary,
379
+ triplet, quintuplet…) from one region to the next costs (:coh, issue #108). fam is the kind in force
380
+ before the bar (the one the bar before ended with)."
381
+ ([b0 meter pts o] (bar-plan b0 meter pts o :none))
382
+ ([b0 meter pts o fam]
383
+ (let [{[_ q] :meter g :groups} (mt/meter-of meter)
384
+ sps (mapv (fn [[s L u]] [(+ b0 s) L u]) (spans meter))
385
+ n (count sps)
386
+ simple? (and (<= q 4) (empty? g))
387
+ ;; a division chosen by hand (:fix) is the only candidate there; else the few cheapest
388
+ single (mapv (fn [[s L u]] (or (let [c (fix-at o s)] (when (and c (not (merge-choice? c))) (some-> (choose-span s L u pts o c) vector)))
389
+ (span-candidates s L u pts o)))
390
+ sps)
391
+ merged (fn [i] (when (and simple? (even? i) (< (inc i) n) (near? (second (sps i)) (second (sps (inc i)))))
392
+ (let [[s L u] (sps i) c (fix-at o s) mc (when (merge-choice? c) (second c))
393
+ xs (span-options s (* 2 L) (* 2 u) (points-in pts s (+ s L L)) (cond-> o mc (update :merge conj mc)) true)]
394
+ (if mc
395
+ (some-> (first (filter (fn [x] (= mc (:n x))) xs)) (assoc :cost forced :s s :L (* 2 L)) vector)
396
+ (when (seq (:merge o)) (mapv (fn [x] (assoc x :s s :L (* 2 L))) (take 2 xs)))))))
397
+ ;; states: at each span boundary, for each family in force, the cheapest [cost path]
398
+ add (fn [m f c p] (if (or (nil? (m f)) (< c (first (m f)))) (assoc m f [c p]) m))
399
+ step (fn [st i j rs] (reduce (fn [st [f [c p]]]
400
+ (reduce (fn [st r] (update st j add (after f r) (+ c (:cost r) (switch-cost f r o)) (conj p r))) st rs))
401
+ st (st i)))
402
+ st (reduce (fn [st i]
403
+ (cond-> (step st i (inc i) (single i))
404
+ (merged i) (step i (+ i 2) (merged i))))
405
+ (assoc (vec (repeat (inc n) {})) 0 {fam [0 []]})
406
+ (range n))
407
+ [_ path] (apply min-key first (vals (st n)))]
408
+ ;; a span divided in parts is as many regions
409
+ (vec (mapcat (fn [r] (or (:parts r) [r])) path)))))
410
+
411
+ ;; ───────── 3. the notes on the points ─────────
412
+
413
+ (defn- region-at [rs t] (first (filter (fn [r] (and (>= t (- (:s r) eps)) (< t (- (+ (:s r) (:L r)) eps)))) rs)))
414
+
415
+ (defn- snap [rs t]
416
+ (if-let [r (region-at rs t)]
417
+ (let [g (/ (:L r) (:n r))] (cv/round-to (+ (:s r) (* g (js/Math.round (/ (- t (:s r)) g)))) 9))
418
+ t))
419
+
420
+ (defn- unit-at [rs t] (if-let [r (region-at rs t)] (/ (:L r) (:n r)) 1))
421
+
422
+ (defn- first-attrs [a first?] (if first? a (dissoc a :gliss :art :dyn :text)))
423
+
424
+ (defn- region-nodes
425
+ "The nodes of the segments that fall in [a, b): notes, chords and rests, cut where the region cuts
426
+ them (the piece before a cut is tied: :tie), with the grace notes before a segment's first piece.
427
+ tup: written durations are the sounding ones × n/m."
428
+ [a b tup segs graces]
429
+ (vec (mapcat (fn [sg]
430
+ (let [x (max (:s sg) a) e (min (:e sg) b)]
431
+ (when (> e (+ x eps))
432
+ (let [;; written values live on a lattice of 1/128 beat (dyadic, or dotted)
433
+ wd (/ (js/Math.round (* 128 (if tup (* (- e x) (/ (first tup) (second tup))) (- e x)))) 128)
434
+ first? (near? x (:s sg))
435
+ tie? (and (:notes sg) (> (:e sg) (+ e eps)))
436
+ ns (:notes sg)]
437
+ (concat
438
+ (when (and first? ns)
439
+ (for [gn (get graces (cv/round-to (:s sg) 6))]
440
+ [:note (assoc (dissoc (:attrs gn) :gliss :dur) :grace true)]))
441
+ [(cond (nil? ns) [:rest {:dur wd}]
442
+ (= 1 (count ns)) [:note (cond-> (assoc (first-attrs (:attrs (first ns)) first?) :dur wd) tie? (assoc :tie true))]
443
+ :else (into [:chord (cond-> {:dur wd} tie? (assoc :tie true))]
444
+ (for [n ns] [:note (first-attrs (:attrs n) first?)])))])))))
445
+ segs)))
446
+
447
+ (defn- clean [notes]
448
+ (vec (sort-by (juxt :on (fn [n] (if (:grace? n) 0 1)) (fn [n] (- (or (mt/midi-of (:attrs n)) 0))))
449
+ (filter (fn [n] (and (number? (:on n)) (number? (:off n)) (>= (:on n) 0) (> (:off n) (:on n)))) notes))))
450
+
451
+ (defn- legato
452
+ "A note released just before the next one of its voice starts (less than :legato beats before it, and
453
+ less than half the time between their starts) reaches it: a small gap is not a rest."
454
+ [notes o]
455
+ (let [ons (vec (distinct (map :on notes)))]
456
+ (mapv (fn [n]
457
+ (if-let [nx (when-not (:grace? n) (first (filter (fn [t] (> t (+ (:on n) (:chord o)))) ons)))]
458
+ (let [gap (- nx (:off n))]
459
+ (if (and (pos? gap) (< gap (:legato o)) (< gap (* 0.5 (- nx (:on n))))) (assoc n :off nx) n))
460
+ n))
461
+ notes)))
462
+
463
+ (defn separate
464
+ "Notes in free time as voices that do not overlap (beyond :overlap beats): notes that start and end
465
+ together stay together (a chord); each one goes to a voice that is free when it starts, the nearest in
466
+ pitch to that voice's last note, or to a new one, up to :voices; past that, to the voice that ends
467
+ first (whose last note it cuts). The highest voice first."
468
+ [notes o]
469
+ (let [notes (clean notes)
470
+ pitch-of (fn [n] (or (mt/midi-of (:attrs n)) 60))
471
+ mean (fn [ns] (/ (reduce + (map pitch-of ns)) (count ns)))
472
+ together? (fn [a b] (and (< (js/Math.abs (- (:on a) (:on b))) (+ (:chord o) eps))
473
+ (< (js/Math.abs (- (:off a) (:off b))) (max (:chord o) (* 0.25 (- (:off b) (:on b)))))))
474
+ events (reduce (fn [evs n] (let [lst (peek evs)] (if (and lst (together? (first lst) n)) (conj (pop evs) (conj lst n)) (conj evs [n]))))
475
+ [] notes)
476
+ vs (reduce (fn [vs ev]
477
+ (let [on (:on (first ev)) off (reduce max (map :off ev)) p (mean ev)
478
+ free (filter (fn [i] (<= (:end (vs i)) (+ on (:overlap o)))) (range (count vs)))
479
+ pick (cond (seq free) (apply min-key (fn [i] (+ (js/Math.abs (- p (:pitch (vs i)))) (* 0.01 i))) free)
480
+ (< (count vs) (:voices o)) nil
481
+ :else (apply min-key (fn [i] (:end (vs i))) (range (count vs))))]
482
+ (cond
483
+ ;; notes together while several voices are free: each to the nearest of them
484
+ (and (> (count ev) 1) (> (count free) 1))
485
+ (reduce (fn [vs [i ns]] (update vs i (fn [v] (-> v (assoc :end (reduce max (map :off ns)) :pitch (mean ns)) (update :notes into ns)))))
486
+ vs (group-by (fn [n] (apply min-key (fn [i] (js/Math.abs (- (pitch-of n) (:pitch (vs i))))) free)) ev))
487
+ (nil? pick) (conj vs {:end off :pitch p :notes (vec ev)})
488
+ :else (update vs pick (fn [v] (-> v (assoc :end off :pitch p) (update :notes into ev)))))))
489
+ [] events)]
490
+ (mapv :notes (sort-by (fn [v] (- (mean (:notes v)))) vs))))
491
+
492
+ (defn- bar-len [meter] (let [{[p q] :meter} meter] (* p (/ 4 q))))
493
+
494
+ (defn bars
495
+ "The bars notes ending at maxoff (starting last at maxon) are written in: [{:b0 :L :meter}], each in its
496
+ meter (:meters, the last going on; else :meter). A last bar where nothing starts and the ends would go back
497
+ to its start is not a bar."
498
+ [o maxoff maxon]
499
+ (let [ms (or (:meters o) [(:meter o)])
500
+ meter-at (fn [i] (get ms i (peek ms)))
501
+ bs (loop [i 0 b0 0 out []]
502
+ (let [m (meter-at i) L (bar-len m) out (conj out {:b0 b0 :L L :meter m})]
503
+ (if (< (+ b0 L) (- maxoff eps)) (recur (inc i) (+ b0 L) out) out)))
504
+ lst (peek bs)
505
+ [_ L1] (first (spans (:meter lst)))]
506
+ (if (and (> (count bs) 1) (< maxon (- (:b0 lst) eps)) (< (- maxoff (:b0 lst)) (* 0.5 L1))) (pop bs) bs)))
507
+
508
+ (defn bar-at "The bar of a plan that holds beat t (the last one past the end)." [bs t]
509
+ (or (first (filter (fn [b] (< t (- (+ (:b0 b) (:L b)) eps))) bs)) (peek bs)))
510
+
511
+ (defn plan
512
+ "How the bars are divided for all these notes together (every voice on the same points): its bars
513
+ [{:b0 :L :meter}], and the regions [{:s :L :n :tup}] of every bar. (:meter and :BL are those of the first.)"
514
+ [notes o]
515
+ (let [maxoff (reduce max 0 (map :off notes))
516
+ maxon (reduce max 0 (map :on notes))
517
+ bs (bars o maxoff maxon)
518
+ pts (vec (sort-by :t (mapcat (fn [i n] [{:t (:on n) :kind :on :note i} {:t (:off n) :kind :off :note i}]) (range) notes)))]
519
+ {:meter (:meter (first bs)) :BL (:L (first bs)) :bars bs :nbars (count bs)
520
+ :total (let [b (peek bs)] (+ (:b0 b) (:L b)))
521
+ ;; bar by bar, each starting from the kind of division the one before ended with (issue #108)
522
+ :rs (first (reduce (fn [[rs fam] {:keys [b0 L meter]}]
523
+ (let [bar (bar-plan b0 meter (points-in pts b0 (+ b0 L)) o fam)]
524
+ [(into rs bar) (reduce after fam bar)]))
525
+ [[] :none] bs))}))
526
+
527
+ (defn write-voice
528
+ "One voice's notes (already free of overlaps but for small ones, which are cut) written on a plan as a
529
+ :voice of measures: chords where starts meet, rests in the gaps, ties over barlines and out of tuplets,
530
+ grace notes for notes that shrink to nothing."
531
+ [notes {:keys [bars total rs]} o]
532
+ (let [qs (mapv (fn [n] (assoc n :qon (snap rs (:on n)) :qoff (min total (snap rs (:off n))))) notes)
533
+ collapsed? (fn [n] (<= (:qoff n) (+ (:qon n) eps)))
534
+ starts (set (map (fn [n] (cv/round-to (:qon n) 6)) (remove collapsed? qs)))
535
+ grace? (fn [n] (and (:grace o) (collapsed? n) (contains? starts (cv/round-to (:qon n) 6))))
536
+ graces (group-by (fn [n] (cv/round-to (:qon n) 6)) (filter grace? qs))
537
+ real (->> qs (remove grace?)
538
+ (map (fn [n] (if (collapsed? n) (assoc n :qoff (min total (+ (:qon n) (unit-at rs (:qon n))))) n)))
539
+ (remove collapsed?))
540
+ groups (sort-by key (group-by (fn [n] (cv/round-to (:qon n) 6)) real))
541
+ sounding (map-indexed (fn [j [_ ns]]
542
+ (let [nxt (some-> (nth groups (inc j) nil) second first :qon)]
543
+ {:s (:qon (first ns)) :e (min (or nxt js/Infinity) (reduce max (map :qoff ns)))
544
+ :notes (vec (sort-by (fn [n] (mt/midi-of (:attrs n))) ns))}))
545
+ groups)
546
+ segs (loop [ss sounding t 0 out []]
547
+ (if (empty? ss)
548
+ (if (< t (- total eps)) (conj out {:s t :e total}) out)
549
+ (let [sg (first ss)]
550
+ (recur (rest ss) (:e sg) (cond-> out (> (:s sg) (+ t eps)) (conj {:s t :e (:s sg)}) true (conj sg))))))
551
+ ;; a bar says its meter when it is the first, or when the meter changes
552
+ bar-attrs (fn [i {{[p q] :meter g :groups} :meter}]
553
+ (let [prev (when (pos? i) (:meter (bars (dec i))))]
554
+ (cond-> {}
555
+ (or (zero? i) (not= (select-keys prev [:meter :groups]) (select-keys (:meter (bars i)) [:meter :groups])))
556
+ (merge (cond-> {:meter [p q]} (seq g) (assoc :groups (vec g))))
557
+ (and (zero? i) (some? (:key o))) (assoc :key (:key o)))))]
558
+ (into [:voice {}]
559
+ (for [[i {:keys [b0 L] :as bar}] (map-indexed vector bars)
560
+ :let [BL L
561
+ ;; a tuplet only for a voice that starts or ends something inside it (a note of
562
+ ;; this voice held through another voice's triplet is not written in a triplet)
563
+ inside? (fn [r] (some (fn [x] (< (+ (:s r) eps) x (- (+ (:s r) (:L r)) eps))) (mapcat (juxt :s :e) segs)))
564
+ regs (mapv (fn [r] (if (and (:tup r) (not (inside? r))) (assoc r :tup nil) r))
565
+ (filterv (fn [r] (and (>= (:s r) (- b0 eps)) (< (:s r) (- (+ b0 BL) eps)))) rs))
566
+ ;; plain regions next to each other are written together; a tuplet on its own
567
+ runs (reduce (fn [acc r]
568
+ (let [lst (peek acc)]
569
+ (if (and lst (nil? (:tup lst)) (nil? (:tup r)))
570
+ (conj (pop acc) (update lst :L + (:L r)))
571
+ (conj acc (select-keys r [:s :L :tup])))))
572
+ [] regs)]]
573
+ (into [:measure (bar-attrs i bar)]
574
+ (mapcat (fn [{:keys [s L tup]}]
575
+ (let [ns (region-nodes s (+ s L) tup segs graces)]
576
+ (if tup [(into [:tuplet {:ratio tup}] ns)] ns)))
577
+ runs))))))
578
+
579
+ (defn graces-first
580
+ "Notes played as grace notes (shorter than :grace-dur beats, starting less than 0.15 beat before a note at
581
+ least twice as long, which is not part of a run of short notes) moved onto the note they lead into, with
582
+ almost no length: they are written as its grace notes and do not ask for a fine division of the beat."
583
+ [notes o]
584
+ (if-not (:grace o)
585
+ notes
586
+ (let [g (or (:grace-dur o) 0.1)
587
+ ns (vec (sort-by :on notes))
588
+ n (count ns)]
589
+ (vec (map-indexed
590
+ (fn [i x]
591
+ (let [d (- (:off x) (:on x))
592
+ nxt (first (filter (fn [y] (> (:on y) (+ (:on x) 0.01))) (subvec ns (inc i))))]
593
+ (if (and nxt (< d g) (< (- (:on nxt) (:on x)) 0.15) (>= (- (:off nxt) (:on nxt)) (* 2 d)) (>= (- (:off nxt) (:on nxt)) 0.2))
594
+ (assoc x :on (:on nxt) :off (+ (:on nxt) 1e-4) :grace? true)
595
+ x)))
596
+ ns)))))
597
+
598
+ (defn- voices-of-notes [notes o] (mapv (fn [ns] (legato ns o)) (let [ss (separate (graces-first notes o) o)] (if (seq ss) ss [[]]))))
599
+
600
+ (defn notes->voices
601
+ "Notes in free time ({:on :off :attrs}, beats; :attrs those of the :note each becomes) as voices of
602
+ measures, quantized with the options o (see `options`): separated where they overlap (at most
603
+ :voices), all on one plan, the voices after the first as layers of its staff. nm names them."
604
+ ([notes o] (notes->voices notes o nil))
605
+ ([notes o nm]
606
+ (let [vs (voices-of-notes notes o)
607
+ pl (plan (vec (remove :grace? (apply concat vs))) o)
608
+ staff (or nm "voice 1")]
609
+ (vec (map-indexed (fn [i ns]
610
+ (let [v (write-voice ns pl o)]
611
+ (cond
612
+ (= 1 (count vs)) (if nm (mt/update-attrs v assoc :name nm) v)
613
+ :else (mt/update-attrs v assoc
614
+ :name (if (and nm (zero? i)) nm (str (or nm "voice") " " (inc i)))
615
+ :staff staff))))
616
+ vs)))))
617
+
618
+ (defn notes->voice
619
+ "Notes in free time as one voice of measures (overlapping notes are cut where the next one starts)."
620
+ [notes o]
621
+ (first (notes->voices notes (assoc o :voices 1))))
622
+
623
+ ;; ───────── choosing another division (stage 6) ─────────
624
+
625
+ (defn choices
626
+ "How the beat (or group) that holds beat t can be divided, for these notes in free time: {:s its start
627
+ :pair the start of the two beats it can go with (or nil) :current the division the plan gives it
628
+ :all [the current one, then the others, cheapest first]}. A division is n, [n1 n2] (in parts) or
629
+ [:merge n] (with the next beat)."
630
+ [notes o t]
631
+ (let [notes (first (timed notes o))
632
+ all-notes (vec (remove :grace? (apply concat (voices-of-notes notes o))))
633
+ {:keys [rs bars]} (plan all-notes o)
634
+ current-in (fn [rs s L]
635
+ (let [here (filterv (fn [r] (and (> (+ (:s r) (:L r)) (+ s eps)) (< (:s r) (- (+ s L) eps)))) rs)]
636
+ (cond (and (= 1 (count here)) (near? (:L (first here)) L)) (:n (first here))
637
+ (and (= 1 (count here)) (> (:L (first here)) (+ L eps))) [:merge (:n (first here))]
638
+ :else (mapv :n here))))
639
+ pts (vec (mapcat (fn [i n] [{:t (:on n) :kind :on :note i} {:t (:off n) :kind :off :note i}]) (range) all-notes))
640
+ {:keys [b0 meter]} (bar-at bars t)
641
+ {[_ q] :meter g :groups} meter
642
+ sps (mapv (fn [[s L u]] [(+ b0 s) L u]) (spans meter))
643
+ i (or (first (keep-indexed (fn [i [s L]] (when (and (>= t (- s eps)) (< t (- (+ s L) eps))) i)) sps)) 0)
644
+ [s L u] (sps i)
645
+ simple? (and (<= q 4) (empty? g))
646
+ pair (when simple? (cond (and (even? i) (< (inc i) (count sps)) (near? L (second (sps (inc i))))) i
647
+ (and (odd? i) (near? L (second (sps (dec i))))) (dec i)))
648
+ in (points-in pts s (+ s L))
649
+ ;; divisions that put the notes on other points (6 places a triplet where 3 does: it is not another choice)
650
+ flat (->> (span-options s L u in o false)
651
+ (reduce (fn [[seen out] x]
652
+ (let [g (/ L (:n x)) k (mapv (fn [p] (cv/round-to (* g (js/Math.round (/ (- (:t p) s) g))) 6)) in)]
653
+ (if (contains? seen k) [seen out] [(conj seen k) (conj out (:n x))])))
654
+ [#{} []])
655
+ second (take 5))
656
+ nested (let [x (best-of-span s L u pts (assoc o :nest true))] (when (:parts x) [(mapv :n (:parts x))]))
657
+ merged (when pair
658
+ (let [[ps pL pu] (sps pair)]
659
+ (map (fn [x] [:merge (:n x)])
660
+ (take 2 (span-options ps (* 2 pL) (* 2 pu) (points-in pts ps (+ ps pL pL)) (assoc o :merge [3 5 6]) true)))))
661
+ current (current-in rs s L)
662
+ ;; the order does not depend on what was chosen: the quantizer's own choice first
663
+ free-o (update o :fix (fn [f] (into {} (remove (fn [[x _]] (or (near? x s) (and pair (near? x (first (sps pair)))))) f))))
664
+ own (current-in (:rs (plan all-notes free-o)) s L)
665
+ all (vec (distinct (concat [own] flat nested merged)))]
666
+ {:s s :pair (when pair (first (sps pair))) :current current
667
+ :all (if (some #{current} all) all (conj all current))}))
668
+
669
+ (defn next-choice
670
+ "The next way to divide the beat that holds t (see `choices`), as the options with that choice in
671
+ their :fix: {:choice c :s span-start :opts opts'}. opts are the options as they are kept (with :fix)."
672
+ [notes opts gx t]
673
+ (let [{:keys [s pair current all]} (choices notes (options opts gx) t)
674
+ c (nth all (mod (inc (max 0 (.indexOf all current))) (count all)))
675
+ k (if (merge-choice? c) pair s)
676
+ fix (into {} (remove (fn [[x _]] (or (near? x s) (and pair (near? x pair)))) (:fix opts)))]
677
+ {:choice c :s k :opts (assoc (if (map? opts) opts {}) :fix (assoc fix k c))}))
678
+
679
+ ;; ───────── what is quantized ─────────
680
+
681
+ (defn strokes->notes
682
+ "The strokes of a freqt as notes in free time: each one a note at the pitch of its first point (with
683
+ decimals when it is between semitones), its bends a :gliss, as mt/<-strokes reads them."
684
+ [d]
685
+ (vec (for [[_ s] (cv/sorted-strokes d)
686
+ :let [pts (:pts s) [t0 f0] (first pts) [t1 _] (peek pts)
687
+ m (cv/hz->midi f0) mr (js/Math.round m)
688
+ dur (max 0.01 (- t1 t0))
689
+ gl (mapv (fn [[t f]] [(cv/round-to (/ (- t t0) dur) 3) (+ 0 (cv/round-to (cv/hz->cents f (cv/midi->hz mr)) 1))]) pts)
690
+ flat? (every? (fn [[_ c]] (< (js/Math.abs (- c (second (first gl)))) 1)) gl)]]
691
+ ;; numbers: the names are chosen afterwards, all together (mt/spell, issue #88)
692
+ {:on t0 :off (+ t0 dur)
693
+ :attrs (cond-> {:pitch (if (< (js/Math.abs (- m mr)) 0.02) mr (cv/round-to m 2))}
694
+ (not flat?) (assoc :pitch mr :gliss gl)
695
+ ;; the weight of a stroke is how strong its note was (as an event's :amp: 0.4 … 2.8 → 0 … 1):
696
+ ;; transcribe writes the strength of each attack so (issue #106)
697
+ (number? (get-in s [:look :w])) (assoc :vel (cv/round-to (max 0 (min 1 (/ (- (get-in s [:look :w]) 0.4) 2.4))) 3)))})))
698
+
699
+ (defn quantize
700
+ "A freqt's buffer as a measured tree (a :voice of :measure nodes), with options (see the top of this
701
+ file); its meter comes from the buffer's bar grid unless :meter is given."
702
+ ([d] (quantize d {}))
703
+ ([d opts]
704
+ (let [o (options opts (:gx d))
705
+ [ns m] (timed (strokes->notes d) o)
706
+ vs (notes->voices ns o)
707
+ t (if (= 1 (count vs)) (first vs) (into [:par {}] vs))
708
+ tempo (or (:tempo opts) (when m (js/Math.round (tm/tempo-of-map m))))]
709
+ (respell-by-hand (mt/spell (cond-> t tempo (mt/update-attrs assoc :tempo tempo))) (:spell o)))))
710
+
711
+ (defn tree-notes
712
+ "The notes of a tree without measures as notes in free time ({:on :off :attrs :voice}): a written name
713
+ stays (with its :cents), numbers stay numbers (they are spelled afterwards)."
714
+ [tree]
715
+ (let [xt (mt/expand tree)]
716
+ (vec (for [e (mt/events xt) :when (and (= :note (:kind e)) (not (:grace e)))]
717
+ {:on (:t e) :off (+ (:t e) (:dur e)) :voice (:voice e)
718
+ :attrs (merge (select-keys e [:art :dyn :text :vel :env :gliss])
719
+ (let [a (mt/attrs (mt/node-at xt (:path e))) w (mt/spelling-of a)]
720
+ (if w
721
+ (cond-> {:pitch (sp/->name w)} (:cents a) (assoc :cents (:cents a)))
722
+ {:pitch (if (whole? (:pitch e)) (js/Math.round (:pitch e)) (cv/round-to (:pitch e) 2))})))}))))
723
+
724
+ (defn tree-options
725
+ "The options a tree without measures is quantized with: its root's :quant (how its score is quantized,
726
+ as a freqt keeps them in its buffer) under the ones given, and its root's :grid for the meter."
727
+ [tree opts]
728
+ (let [a (mt/attrs (mt/expand tree))]
729
+ (options (merge (:quant a) opts) (:grid a))))
730
+
731
+ (defn quantize-tree
732
+ "A tree without measures (notes placed in free time, with :at or durations of any size) as a measured
733
+ tree: each of its voices quantized on its own, in the meter of the options (or of its root's :grid;
734
+ 4/4 by default). Its root's :quant are options too."
735
+ ([tree] (quantize-tree tree {}))
736
+ ([tree opts]
737
+ (let [o (tree-options tree opts)
738
+ ;; played time onto beats, all voices through one map (issue #106)
739
+ [ns m] (timed (tree-notes tree) o)
740
+ ;; played time: the error of a note is weighed in seconds, not in beats — 30 ms off is as much at 220 bpm as
741
+ ;; at 80, though it is a larger part of a beat (the Weimar Jazz Database, issue #106). At ref-bpm the
742
+ ;; weight is the one given; faster, it is less (less chasing of fine divisions), down to a third.
743
+ o (if-let [r (and m (number? (:ref-bpm o)) (pos? (:ref-bpm o)) (:ref-bpm o))]
744
+ (let [f (js/Math.min 1 (js/Math.max 0.33 (/ r (tm/tempo-of-map m))))] (update-in o [:w :err] * f))
745
+ o)
746
+ by-voice (sort-by key (group-by (fn [n] (or (:voice n) "")) ns))
747
+ ;; a voice keeps its name; one without (named by mt/events v<depth>-<index>) stays without
748
+ voices (fn [[nm ns]] (notes->voices (mapv (fn [n] (dissoc n :voice)) ns) o
749
+ (when (and (seq nm) (not (re-matches #"v\d+-\d*" nm))) nm)))
750
+ vs (vec (mapcat voices by-voice))
751
+ t (if (> (count vs) 1) (into [:par {}] vs) (or (first vs) (notes->voice [] o)))]
752
+ (respell-by-hand (mt/spell (mt/update-attrs t assoc :tempo (or (:tempo opts)
753
+ (when m (js/Math.round (* (tm/tempo-of-map m) (/ (mt/tempo-of tree) 60))))
754
+ (mt/tempo-of tree))))
755
+ (:spell o)))))
756
+
757
+ (defn measure-free-voices
758
+ "A measured tree whose voices without measures (a free voice beside the measured ones) are quantized
759
+ in the meter of its first measure, so that the whole tree is written in measures."
760
+ [tree]
761
+ (let [x (mt/expand tree)
762
+ first-m (first (filter (fn [n] (and (mt/node? n) (= :measure (mt/tag n)))) (tree-seq mt/node? mt/kids (mt/with-meters x))))
763
+ meter (select-keys (mt/attrs first-m) [:meter :groups])
764
+ free? (fn [v] (and (mt/node? v) (= :voice (mt/tag v)) (not (mt/measured? v))))]
765
+ (if (and (= :par (mt/tag x)) (some free? (mt/kids x)) first-m)
766
+ (mt/with-kids x (vec (mapcat (fn [k]
767
+ (if (free? k)
768
+ (let [q (quantize-tree k {:meter meter})]
769
+ (if (= :par (mt/tag q)) (mt/kids q) [q]))
770
+ [k]))
771
+ (mt/kids x))))
772
+ x)))
773
+
774
+ (defn ->score
775
+ "MEI for a score: a measured tree as it is, a tree without measures quantized, a freqt's buffer
776
+ quantized. Returns {:mei :pieces} (see mt/->mei)."
777
+ ([x pre] (->score x pre {}))
778
+ ([x pre opts]
779
+ (cond
780
+ (and (mt/tree? x) (mt/measured? x)) (mt/->mei (measure-free-voices x) pre)
781
+ (mt/tree? x) (mt/->mei (quantize-tree x opts) pre)
782
+ :else (mt/->mei (quantize x opts) pre))))