@kairotic/app 0.0.0-stage → 0.2.2

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,1604 @@
1
+ ;; SPDX-License-Identifier: MPL-2.0
2
+ ;; Kairotic · mt (musical time)
3
+ ;; Musical-temporal data as EDN trees, in the hiccup style: [:tag {attributes} & children].
4
+ ;; It is the common language of notation, composition and CAC in Kairotic: components take trees and
5
+ ;; return trees, and a canvas, a freqt or a score can show one. Like bach's llll it nests freely;
6
+ ;; unlike it, attributes have names, so any extra data (bach's slots) is just one more key.
7
+ ;;
8
+ ;; Time is in beats (a quarter note = 1); :tempo (beats per minute, 60 by default) turns it into seconds.
9
+ ;;
10
+ ;; sequential :seq :voice :section :measure {:meter [3 4]} :tuplet {:ratio [3 2]} children one after another
11
+ ;; a measure groups its units with {:meter [5 8] :groups [2 3]}, or {:meter "5/8[2+3]"}
12
+ ;; simultaneous :par :piece :chord children at once
13
+ ;; leaves :note {:pitch "c4" | 60.5 | :hz 440, :dur 1} :rest {:dur 1}
14
+ ;; :param {:name :cutoff :value 400 :to 2000 :dur 4} a parameter change (a ramp with :to)
15
+ ;; :dyn {:mark "mf"} · {:mark "<" :dur 2} a dynamic, or a hairpin
16
+ ;; :text {:text "dolce"} a text indication
17
+ ;; :use {:ref :motif :transpose 5} a fragment defined in :defs, varied
18
+ ;; :rtm {:shares [1 [1 [1 1 1]] -1 2] :pitches "c4 d4 e4"} proportional rhythm: shares of
19
+ ;; its :dur (or of its measure); note values and tuplets follow from shares and meter
20
+ ;; strings "c4/1 e4/.5 r/1 c4+e4+g4/2" melody shorthand inside any container
21
+ ;;
22
+ ;; Any node may carry :at (an offset from the start of its parent; it does not move the parent's
23
+ ;; cursor), :id, and any other key. Notes also take :art [:staccato :accent], :dyn "p", :text "…",
24
+ ;; :gliss [[0 0] [1 -150]] (cents over the note's duration), :env [[0 0] [0.1 1] [1 0]], :vel 0.8.
25
+ ;; A written name may carry :cents (its deviation: {:pitch "c4" :cents 50} is a quarter tone above c4).
26
+ ;; :tie true goes on into the next note of the same pitch (across a barline or into a tuplet: one sound,
27
+ ;; tied in the score); :grace true is a grace note before the next one (it takes no time in its container).
28
+ ;; A :voice with :staff "name" is written as a layer of that staff (voices that share it, layers 1, 2 …).
29
+ ;; A note without :dur lasts as long as the previous one of its container (1 at first). :defs (a map
30
+ ;; of fragments) can sit in the attributes of any container; [:use {:ref k}] takes them from there.
31
+
32
+ (ns kairotic.mt
33
+ (:require [clojure.string :as str]
34
+ [clojure.edn :as edn]
35
+ [kairotic.canvas :as cv]
36
+ [kairotic.score :as sc]
37
+ [kairotic.spell :as sp]))
38
+
39
+ ;; ───────── nodes ─────────
40
+
41
+ (def seq-tags #{:seq :voice :measure :tuplet})
42
+ (def par-tags #{:par :chord})
43
+ ;; a work: in a :piece or a :section, voices (and :par) sound together from its start, and anything
44
+ ;; else — sections in a piece, measures in a section — follows in order
45
+ (def block-tags #{:piece :section})
46
+ (def mark-tags #{:param :dyn :text})
47
+ (def known-tags (into (into (into (into #{:note :rest :use :rtm} seq-tags) par-tags) block-tags) mark-tags))
48
+
49
+ (defn node? [x] (and (vector? x) (keyword? (first x))))
50
+ (defn tag [n] (when (node? n) (first n)))
51
+ (defn attrs [n] (let [a (second n)] (if (map? a) a {})))
52
+ (defn kids [n] (if (map? (second n)) (subvec n 2) (subvec n 1)))
53
+ (defn make [t a ks] (into (if (seq a) [t a] [t]) ks))
54
+ ;; a node keeps its metadata (where it comes from in the written tree) when it changes
55
+ (defn with-attrs [n a] (with-meta (make (tag n) a (kids n)) (meta n)))
56
+ (defn with-kids [n ks] (with-meta (make (tag n) (attrs n) ks) (meta n)))
57
+ (defn update-attrs [n f & args] (with-attrs n (apply f (attrs n) args)))
58
+
59
+ (defn tree? "Is x a musical tree (or a string of melody)?" [x] (or (node? x) (string? x)))
60
+
61
+ ;; ───────── pitch ─────────
62
+
63
+ (def pc-names ["c" "c#" "d" "d#" "e" "f" "f#" "g" "g#" "a" "a#" "b"])
64
+
65
+ (defn midi-of
66
+ "The pitch of a note as a MIDI number (with decimals for microtones), or nil."
67
+ [a]
68
+ (cond
69
+ (number? (:hz a)) (when (pos? (:hz a)) (cv/hz->midi (:hz a)))
70
+ (some? (:pitch a)) (when-let [m (sc/pitch (:pitch a))] (+ m (/ (or (:cents a) 0) 100)))
71
+ :else nil))
72
+
73
+ (defn pitch-name
74
+ "60 → \"c4\"; a fractional pitch stays a number."
75
+ [m]
76
+ (if (and (number? m) (= m (js/Math.round m)))
77
+ (str (nth pc-names (mod m 12)) (dec (js/Math.floor (/ m 12))))
78
+ m))
79
+
80
+ (defn spelling-of
81
+ "How a note's pitch is written ({:step :alter :oct}, kairotic.spell), when it is a name; nil for numbers and Hz."
82
+ [a]
83
+ (when-not (number? (:hz a)) (sp/parse (:pitch a))))
84
+
85
+ (defn respell
86
+ "A name for MIDI pitch m (an integer) like the name it had: a natural when there is one, else a flat for
87
+ a flat and a sharp for a sharp (bb4 + 1 = b4, eb4 - 1 = d4, db4 + 3 = e4, eb4 + 3 = gb4)."
88
+ [m was]
89
+ (let [sign (if was (js/Math.sign (:alter was)) 1)]
90
+ (first (sort-by (fn [x] [(js/Math.abs (:alter x)) (if (= (js/Math.sign (:alter x)) sign) 0 1)])
91
+ (filter (fn [x] (<= (js/Math.abs (:alter x)) 1)) (sp/spellings m))))))
92
+
93
+ (defn set-midi
94
+ "Writes a new pitch in the attributes of a note, in the same kind of value it had (name, number or Hz);
95
+ a name keeps the way it was written as far as it can (see respell)."
96
+ [a m]
97
+ (cond
98
+ (number? (:hz a)) (assoc a :hz (cv/round-to (cv/midi->hz m) 3))
99
+ (and (or (string? (:pitch a)) (keyword? (:pitch a))) (== m (js/Math.round m)))
100
+ (assoc (dissoc a :cents) :pitch (sp/->name (respell (js/Math.round m) (spelling-of a))))
101
+ (string? (:pitch a)) (assoc (dissoc a :cents) :pitch (pitch-name (cv/round-to m 3)))
102
+ (keyword? (:pitch a)) (assoc (dissoc a :cents) :pitch (pitch-name (cv/round-to m 3)))
103
+ :else (assoc (dissoc a :cents) :pitch (cv/round-to m 3))))
104
+
105
+ ;; ───────── melody shorthand ─────────
106
+
107
+ (defn melody
108
+ "\"c4/1 d4/.5 r/1 c4+e4+g4/2 f4\" → nodes. A token without /dur keeps the previous duration."
109
+ [txt]
110
+ (loop [toks (remove str/blank? (str/split (str/trim (str txt)) #"\s+")) prev 1 out []]
111
+ (if (empty? toks)
112
+ out
113
+ (let [[p d] (str/split (first toks) #"/" 2)
114
+ dur (if (seq d) (let [x (js/parseFloat d)] (if (js/isNaN x) prev x)) prev)
115
+ node (if (= "r" (str/lower-case p))
116
+ [:rest {:dur dur}]
117
+ (let [ps (str/split p #"\+")]
118
+ (doseq [x ps] (when-not (sc/pitch x) (throw (js/Error. (str "I don't understand the note «" x "» (use c4, f#3, bb2)")))))
119
+ (if (= 1 (count ps))
120
+ [:note {:pitch (str/lower-case (first ps)) :dur dur}]
121
+ (into [:chord {:dur dur}] (for [x ps] [:note {:pitch (str/lower-case x)}])))))]
122
+ (recur (rest toks) dur (conj out node))))))
123
+
124
+ ;; ───────── numbers: exact fractions [n d] ─────────
125
+
126
+ (defn- gcd [a b] (if (zero? b) (js/Math.abs a) (recur b (mod a b))))
127
+ (defn- lcm [a b] (/ (* a b) (gcd a b)))
128
+ (defn- r-norm [[n d]] (let [g (gcd n d)] [(/ n g) (/ d g)]))
129
+
130
+ (defn- rat
131
+ "x as a fraction [n d] (d > 0): exact for the beats music uses (halves, thirds, fifths, eighths…)."
132
+ [x]
133
+ (let [s (if (neg? x) -1 1) x (js/Math.abs x)]
134
+ (loop [h1 1 h0 0 k1 0 k0 1 y x i 0]
135
+ (let [a (js/Math.floor y) h (+ (* a h1) h0) k (+ (* a k1) k0)]
136
+ (if (or (< (js/Math.abs (- x (/ h k))) 1e-9) (> i 40) (== y a))
137
+ [(* s h) k]
138
+ (recur h h1 k k1 (/ 1 (- y a)) (inc i)))))))
139
+
140
+ (defn- r+ [[a b] [c d]] (r-norm [(+ (* a d) (* c b)) (* b d)]))
141
+ (defn- r- [[a b] [c d]] (r-norm [(- (* a d) (* c b)) (* b d)]))
142
+ (defn- r-div [[a b] [c d]] (r-norm [(* a d) (* b c)]))
143
+ (defn- r< [[a b] [c d]] (< (* a d) (* c b)))
144
+
145
+ (defn- prime-factors "12 → [2 2 3] (smallest first: a span halves before it thirds)." [n]
146
+ (loop [n n f 2 out []]
147
+ (cond (< n 2) out
148
+ (> (* f f) n) (conj out n)
149
+ (zero? (mod n f)) (recur (/ n f) f (conj out f))
150
+ :else (recur n (inc f) out))))
151
+
152
+ ;; ───────── meters: groups and metric weight ─────────
153
+ ;; A meter is [p q] (p units of 1/q), and a measure may group its units: {:meter [5 8] :groups [2 3]},
154
+ ;; also written "5/8[2+3]". Groups say where the beats fall (beams, metric weight); without them a
155
+ ;; meter groups as it is usually read (6/8 in two dotted quarters, 3/4 in three quarters).
156
+ ;;
157
+ ;; Metric level (after Rastrum, smoge/Rastrum): 0 at the start of the bar, 1 at the start of a group,
158
+ ;; and deeper for each division of a group (or of the bar) by the prime factors of its units, twos
159
+ ;; first, then halving. Indispensability: Clarence Barlow's ranking of how much each pulse is needed
160
+ ;; for the meter to be heard as itself (N−1 the downbeat … 0 the most dispensable). It is composition
161
+ ;; data, not notation: 3/4 and 6/8 hold the same six eighths and rank them differently. For a grouped
162
+ ;; meter Kairotic ranks by metric level, then by Barlow inside each group, then the earlier group.
163
+
164
+ (defn parse-meter
165
+ "\"5/8[2+3]\" → {:meter [5 8] :groups [2 3]}; \"3/4\" → {:meter [3 4]}; nil if it is not a meter."
166
+ [s]
167
+ (when-let [[_ p q g] (re-matches #"\s*(\d+)\s*/\s*(\d+)\s*(?:\[\s*([\d\s+]+?)\s*\])?\s*" (str s))]
168
+ (cond-> {:meter [(js/parseInt p 10) (js/parseInt q 10)]}
169
+ g (assoc :groups (mapv (fn [x] (js/parseInt x 10)) (str/split (str/trim g) #"\s*\+\s*"))))))
170
+
171
+ (defn meter-of
172
+ "A meter as {:meter [p q] :groups [a b …]} (no :groups when it has none), from [5 8], \"5/8[2+3]\",
173
+ {:meter … :groups …} or a measure."
174
+ [x]
175
+ (cond
176
+ (node? x) (meter-of (attrs x))
177
+ (string? x) (or (parse-meter x)
178
+ (throw (js/Error. (str "a meter is [p q], \"p/q\" or \"p/q[a+b…]\", not " (pr-str x)))))
179
+ (map? x) (let [m (meter-of (or (:meter x) [4 4]))]
180
+ (if (seq (:groups x)) (assoc m :groups (vec (:groups x))) m))
181
+ (and (vector? x) (= 2 (count x)) (every? number? x) (every? pos? x)) {:meter x}
182
+ :else (throw (js/Error. (str "a meter is [p q], \"p/q\" or \"p/q[a+b…]\", not " (pr-str x))))))
183
+
184
+ (defn- with-meter-attrs
185
+ "The attributes of a measure with its meter read: :meter \"5/8[2+3]\" → :meter [5 8] :groups [2 3]."
186
+ [a]
187
+ (if (string? (:meter a))
188
+ (let [m (meter-of (:meter a))]
189
+ (cond-> (assoc a :meter (:meter m)) (and (:groups m) (not (:groups a))) (assoc :groups (:groups m))))
190
+ a))
191
+
192
+ (defn meter-level
193
+ "The metric level of a position (beats from the start of the bar): 0 the bar, 1 a group, then deeper;
194
+ 20 for a position no division reaches (inside a tuplet)."
195
+ [meter pos]
196
+ (let [{[p q] :meter g :groups} (meter-of meter)
197
+ bar (* p (/ 4 q))
198
+ x (rat (let [m (mod pos bar)] (if (< (js/Math.abs (- m bar)) 1e-9) 0 m)))]
199
+ (if (zero? (first x))
200
+ 0
201
+ (loop [gs (or (seq g) [p]) start [0 1]]
202
+ (if (empty? gs)
203
+ 20
204
+ (let [n (first gs) span (r-norm [(* 4 n) q]) local (r- x start)]
205
+ (if-not (r< local span)
206
+ (recur (rest gs) (r+ start span))
207
+ (if (zero? (first local))
208
+ 1
209
+ (loop [fs (concat (prime-factors n) (repeat 16 2)) step span i 1]
210
+ (if (empty? fs)
211
+ 20
212
+ (let [step (r-div step [(first fs) 1])]
213
+ (if (= 1 (second (r-div local step)))
214
+ (+ (if (seq g) 1 0) i)
215
+ (recur (rest fs) step (inc i))))))))))))))
216
+
217
+ (declare barlow-basic)
218
+
219
+ (defn- barlow
220
+ "Barlow's indispensability ψ of pulse n (from 1) in a stratification (prime factors, top first)."
221
+ [n strata]
222
+ (let [z (count strata) total (reduce * 1 strata) ps (vec (concat [1] strata [1]))]
223
+ (reduce + 0 (for [r (range z)]
224
+ (let [inner (reduce * 1 (map (fn [k] (ps (- (inc z) k))) (range (inc r))))
225
+ outer (reduce * 1 (map ps (range (- z r))))
226
+ m (ps (- z r))
227
+ digit (inc (mod (inc (quot (mod (- n 2) total) inner)) m))]
228
+ (* outer (barlow-basic digit m)))))))
229
+
230
+ (defn- barlow-basic
231
+ "Barlow's basic indispensability Ψ of pulse n (from 1) in a prime p; primes above 3 build on p−1."
232
+ [n p]
233
+ (if (<= p 3)
234
+ (mod (+ p n -2) p)
235
+ (let [w (fn [x] (if (zero? x) 0 1))
236
+ q (barlow (+ n -1 (w (- p n))) (vec (reverse (prime-factors (dec p)))))
237
+ quarter (quot p 4)
238
+ beyond (w (- p n 1))]
239
+ (+ (* (+ q (w (quot q quarter))) beyond) (* quarter (- 1 beyond))))))
240
+
241
+ (defn- pulse-count
242
+ "How many pulses of `pulse` beats fit in a unit of the meter (nil: the unit itself)."
243
+ [q pulse]
244
+ (let [per (if pulse (/ (/ 4 q) pulse) 1)]
245
+ (when-not (and (>= per 1) (< (js/Math.abs (- per (js/Math.round per))) 1e-9))
246
+ (throw (js/Error. (str "a pulse of " pulse " beats does not divide the unit of a " q "-meter"))))
247
+ (js/Math.round per)))
248
+
249
+ (defn pulses
250
+ "The pulses of a bar, in beats from its start: one per unit, or per `pulse` beats."
251
+ ([meter] (pulses meter nil))
252
+ ([meter pulse]
253
+ (let [{[p q] :meter} (meter-of meter) per (pulse-count q pulse) pb (/ (/ 4 q) per)]
254
+ (mapv (fn [i] (* i pb)) (range (* p per))))))
255
+
256
+ (defn indispensability
257
+ "Barlow's indispensability of every pulse of a bar (one per unit, or per `pulse` beats), in order:
258
+ 3/4 in eighths → [5 0 3 1 4 2]; 6/8 → [5 0 2 4 1 3]. The downbeat is the highest."
259
+ ([meter] (indispensability meter nil))
260
+ ([meter pulse]
261
+ (let [{[p q] :meter g :groups :as m} (meter-of meter)
262
+ per (pulse-count q pulse)
263
+ n (* p per)
264
+ strata (fn [units] (vec (concat (prime-factors units) (prime-factors per))))]
265
+ (if-not (seq g)
266
+ (let [s (strata p)] (mapv (fn [i] (barlow (inc i) s)) (range n)))
267
+ (let [pb (/ (/ 4 q) per)
268
+ group-of (vec (mapcat (fn [gi k] (repeat (* k per) gi)) (range) g))
269
+ within (vec (mapcat (fn [k] (let [s (strata k)] (map (fn [i] (barlow (inc i) s)) (range (* k per))))) g))
270
+ order (sort-by (fn [i] [(meter-level m (* i pb)) (- (within i)) (group-of i)]) (range n))
271
+ rank (into {} (map-indexed (fn [r i] [i (- n 1 r)]) order))]
272
+ (mapv rank (range n)))))))
273
+
274
+ (defn indispensability-at
275
+ "The indispensability of a position (beats from the start of the bar), or nil off the pulses."
276
+ ([meter pos] (indispensability-at meter pos nil))
277
+ ([meter pos pulse]
278
+ (let [{[_ q] :meter} (meter-of meter) pb (/ (/ 4 q) (pulse-count q pulse)) x (/ pos pb) i (js/Math.round x)]
279
+ (when (< (js/Math.abs (- x i)) 1e-6) (get (indispensability meter pulse) i)))))
280
+
281
+ ;; ───────── transformations (tree → tree) ─────────
282
+
283
+ (defn walk-notes
284
+ "Applies f to the attributes of every note."
285
+ [f n]
286
+ (cond
287
+ (not (node? n)) n
288
+ (= :note (tag n)) (with-attrs n (f (attrs n)))
289
+ :else (with-kids n (mapv (fn [k] (walk-notes f k)) (kids n)))))
290
+
291
+ (defn first-pitch [n]
292
+ (cond (not (node? n)) nil
293
+ (= :note (tag n)) (midi-of (attrs n))
294
+ :else (some first-pitch (kids n))))
295
+
296
+ (declare expand)
297
+
298
+ (defn- spelled-notes [t] (keep (fn [x] (when (and (node? x) (= :note (tag x))) (spelling-of (attrs x)))) (tree-seq node? kids t)))
299
+
300
+ (defn transpose
301
+ "Moves every pitch by n semitones (decimals: microtones), or by an interval (\"M3\", \"-P5\", \"A4\",
302
+ [steps semitones]). Written names move by that interval and keep their spelling (c4 e4 g4 by \"m3\" is
303
+ eb4 g4 bb4); by a number of semitones they move by the interval it is usually written as (1 a minor
304
+ second, 6 the augmented fourth or the diminished fifth, whichever needs fewer alterations). Its keys
305
+ (:key) move by the same interval."
306
+ [n tree]
307
+ (let [t (expand tree)
308
+ iv (cond (and (number? n) (== n (js/Math.round n)))
309
+ (if (= 6 (mod n 12))
310
+ (let [alts (fn [iv] (reduce + (map (fn [s] (js/Math.abs (:alter (sp/transpose-spelling s iv)))) (spelled-notes t))))
311
+ a (sp/interval-of-semitones n false) d (sp/interval-of-semitones n true)]
312
+ (if (< (alts d) (alts a)) d a))
313
+ (sp/interval-of-semitones n))
314
+ (number? n) nil
315
+ :else (or (sp/interval n) (throw (js/Error. (str "An interval is a number of semitones or a name like M3, -P5, A4: not " (pr-str n))))))
316
+ semis (if iv (second iv) n)
317
+ ;; keys move with the notes (by a number with decimals, a microtone, they stay)
318
+ keys-moved (fn keys-moved [x]
319
+ (if-not (node? x)
320
+ x
321
+ (let [x (if (and iv (contains? (attrs x) :key)) (update-attrs x update :key sp/transpose-key iv) x)]
322
+ (if (= :note (tag x)) x (with-kids x (mapv keys-moved (kids x)))))))]
323
+ (keys-moved
324
+ (walk-notes (fn [a]
325
+ (if-let [s (and iv (spelling-of a))]
326
+ (assoc a :pitch (sp/->name (sp/transpose-spelling s iv)))
327
+ (if-let [m (midi-of a)] (set-midi a (+ m semis)) a)))
328
+ t))))
329
+
330
+ (defn invert
331
+ "Mirrors every pitch around a pivot (by default, the first pitch)."
332
+ ([tree] (invert nil tree))
333
+ ([pivot tree]
334
+ (let [t (expand tree)
335
+ p (or (if (or (string? pivot) (keyword? pivot)) (sc/pitch pivot) pivot) (first-pitch t) 60)
336
+ ;; a written pivot (or the first written note) mirrors names on the line of fifths too
337
+ ps (or (when (or (string? pivot) (keyword? pivot)) (sp/parse pivot))
338
+ (when (nil? pivot) (first (spelled-notes t))))]
339
+ (walk-notes (fn [a] (if-let [m (midi-of a)]
340
+ (cond-> (if-let [s (and ps (spelling-of a))]
341
+ (assoc a :pitch (sp/->name (sp/invert-spelling s ps)))
342
+ (set-midi a (- (* 2 p) m)))
343
+ (:gliss a) (assoc :gliss (mapv (fn [[x c]] [x (- c)]) (:gliss a))))
344
+ a))
345
+ t))))
346
+
347
+ (defn explicit
348
+ "Writes in every note, rest and chord of a sequence the duration it takes from the previous one."
349
+ [n]
350
+ (if-not (node? n)
351
+ n
352
+ (let [seqy (seq-tags (tag n))]
353
+ (with-kids n
354
+ (loop [ks (kids n) prev 1 out []]
355
+ (if (empty? ks)
356
+ out
357
+ (let [k (first ks)
358
+ durable (and (node? k) (#{:note :rest :chord} (tag k)) (not (:at (attrs k))) (not (:grace (attrs k))))
359
+ d (when durable (or (:dur (attrs k)) prev))
360
+ k (explicit (if (and durable seqy) (update-attrs k assoc :dur d) k))]
361
+ (recur (rest ks) (if (and durable seqy) d prev) (conj out k)))))))))
362
+
363
+ (defn with-meters
364
+ "Writes in every measure the meter (and groups) it takes from the previous one (4/4 at first); a
365
+ meter written as \"5/8[2+3]\" becomes :meter [5 8] :groups [2 3]. A new meter without groups has none;
366
+ groups without a meter keep the meter."
367
+ [tree]
368
+ (let [last-m (atom {:meter [4 4]})]
369
+ (letfn [(go [n]
370
+ (cond
371
+ (not (node? n)) n
372
+ (= :measure (tag n))
373
+ (let [a (with-meter-attrs (attrs n))
374
+ cur (cond (:meter a) (cond-> {:meter (:meter a)} (seq (:groups a)) (assoc :groups (vec (:groups a))))
375
+ (seq (:groups a)) (assoc @last-m :groups (vec (:groups a)))
376
+ :else @last-m)]
377
+ (reset! last-m cur)
378
+ (with-meta (make :measure (merge (dissoc a :groups) cur) (mapv go (kids n))) (meta n)))
379
+ :else (with-kids n (mapv go (kids n)))))]
380
+ (go tree))))
381
+
382
+ (defn scale-meter
383
+ "The meter of a measure whose durations are multiplied by f: 4/4 × 2 = 8/4, 3/4 × 0.5 = 3/8."
384
+ [[p q] f]
385
+ (let [p2 (* p f) q2 (/ q f)]
386
+ (cond (= p2 (js/Math.round p2)) [p2 q]
387
+ (and (= q2 (js/Math.round q2)) (pos? q2)) [p q2]
388
+ :else [p2 q])))
389
+
390
+ (defn augment
391
+ "Multiplies every duration (and offset) by f: 2 doubles, 0.5 halves. Measures change their meter."
392
+ [f tree]
393
+ (letfn [(go [n]
394
+ (if-not (node? n)
395
+ n
396
+ (let [a (attrs n)
397
+ a (cond-> a
398
+ (number? (:dur a)) (update :dur * f)
399
+ (number? (:at a)) (update :at * f)
400
+ (and (= :measure (tag n)) (vector? (:meter a))) (update :meter scale-meter f))
401
+ ;; groups count units: they grow with the numerator
402
+ a (let [p0 (first (:meter (attrs n))) p1 (first (:meter a))]
403
+ (if (and (seq (:groups a)) (number? p0) (not= p0 p1))
404
+ (update a :groups (fn [g] (mapv (fn [x] (* x (/ p1 p0))) g)))
405
+ a))]
406
+ (make (tag n) a (mapv go (kids n))))))]
407
+ (go (with-meters (explicit (expand tree))))))
408
+
409
+ (defn retrograde
410
+ "Plays it backwards: the children of every sequence in reverse order (glissandi too)."
411
+ [tree]
412
+ (letfn [(go [n]
413
+ (cond
414
+ (not (node? n)) n
415
+ (= :note (tag n)) (let [a (attrs n)]
416
+ (if (:gliss a)
417
+ (let [g (:gliss a) end (second (peek g))]
418
+ (with-attrs n (-> (set-midi a (+ (midi-of a) (/ end 100)))
419
+ (assoc :gliss (vec (reverse (mapv (fn [[x c]] [(- 1 x) (- c end)]) g)))))))
420
+ n))
421
+ (seq-tags (tag n)) (with-kids n (vec (reverse (mapv go (kids n)))))
422
+ (block-tags (tag n)) (let [ks (mapv go (kids n))
423
+ together? (fn [k] (or (not (node? k)) (#{:voice :par} (tag k)) (some? (:at (attrs k)))))
424
+ slots (vec (keep-indexed (fn [i k] (when-not (together? k) i)) ks))
425
+ moved (zipmap slots (reverse (map ks slots)))]
426
+ (with-kids n (vec (map-indexed (fn [i k] (get moved i k)) ks))))
427
+ :else (with-kids n (mapv go (kids n)))))]
428
+ (go (with-meters (explicit (expand tree))))))
429
+
430
+ (defn rotate
431
+ "Moves the first k elements of the top sequence to its end (negative k: the other way)."
432
+ [k tree]
433
+ (let [t (with-meters (explicit (expand tree))) ks (kids t) n (count ks)]
434
+ (if (zero? n) t (let [k (mod k n)] (with-kids t (vec (concat (drop k ks) (take k ks))))))))
435
+
436
+ (declare measured? duration)
437
+
438
+ (defn as-voice [t nm] (if (= :voice (tag t)) (update-attrs t assoc :name nm) [:voice {:name nm} t]))
439
+
440
+ (defn- canon*
441
+ "The tree (the dux) against the comes, entering `delay` beats later. When the dux is written in measures and
442
+ the delay is a whole number of them, the comes enters after rest bars."
443
+ [delay t comes]
444
+ (let [first-m (first (filter (fn [x] (and (node? x) (= :measure (tag x)))) (tree-seq node? kids t)))
445
+ [p q] (when first-m (:meter (attrs first-m)))
446
+ bar (when p (* p (/ 4 q)))
447
+ bars (when bar (/ delay bar))]
448
+ (if (and bars (pos? bars) (= bars (js/Math.round bars)))
449
+ (let [v2 (as-voice comes "comes")
450
+ rests (vec (repeat bars [:measure {:meter [p q]} [:rest {:dur bar}]]))]
451
+ [:par {:name "canon"} (as-voice t "dux") (with-kids v2 (into rests (kids v2)))])
452
+ [:par {:name "canon"} (as-voice t "dux") [:voice {:name "comes"} [:seq {:at delay} comes]]])))
453
+
454
+ (defn canon
455
+ "The tree against itself, entering `delay` beats later and transposed by `interval`. When it is
456
+ written in measures and the delay is a whole number of them, the second voice enters after rest bars.
457
+ With a map, the words of the heads (discussion \"Heads on a span of time\"): {:d beats later, :k an
458
+ interval (semitones or a name, M3, -P5), :speed of the comes (0.5 twice as slow, 2 twice as fast, −1
459
+ backwards: a crab), :inversion (upside down, around the dux's first pitch)}."
460
+ ([delay tree]
461
+ (if (map? delay)
462
+ (let [{:keys [d k speed inversion]} delay
463
+ t (with-meters (explicit (expand tree)))
464
+ s (if (and (number? speed) (not (zero? speed))) speed 1)
465
+ comes (cond->> t
466
+ inversion (invert nil)
467
+ (neg? s) retrograde
468
+ (not= 1 (js/Math.abs s)) (augment (/ 1 (js/Math.abs s)))
469
+ true (transpose (or k 0)))]
470
+ (canon* (or d 1) t comes))
471
+ (canon delay 0 tree)))
472
+ ([delay interval tree]
473
+ (let [t (with-meters (explicit (expand tree)))]
474
+ (canon* delay t (transpose interval t)))))
475
+
476
+ (defn apply-ops
477
+ "The variations a [:use …] or a box can ask for, in a fixed order."
478
+ [a tree]
479
+ (cond->> tree
480
+ (:transpose a) (transpose (:transpose a))
481
+ (some? (:invert a)) (invert (if (true? (:invert a)) nil (:invert a)))
482
+ (:retrograde a) retrograde
483
+ (:augment a) (augment (:augment a))))
484
+
485
+ ;; ───────── expansion: strings and references ─────────
486
+
487
+ (def op-keys #{:ref :transpose :invert :retrograde :augment})
488
+
489
+ (defn- from [x src] (if (node? x) (with-meta x src) x))
490
+
491
+ ;; ───────── proportional rhythm (:rtm) ─────────
492
+ ;; A rhythm written as shares, as in the RTM trees of OpenMusic and PWGL (and Rastrum, for
493
+ ;; SuperCollider): a number is a share, a negative number a silence, and [weight [shares …]] divides a
494
+ ;; share further. Shares are relative (a common factor changes nothing); the :rtm lasts its :dur, or
495
+ ;; fills its measure. Note values and tuplets are not written: they follow from shares and meter. When
496
+ ;; the equal unit of a level is a written value (a power of two of a beat: 1, 1/2, 2…) the notes take
497
+ ;; it as it is; when not, the level becomes a tuplet of the smallest written value that is not shorter.
498
+ ;; Three shares of a 3/4 bar are quarters; three of a 4/4 bar, a 3:2 of halves.
499
+ ;; Pitches go to the notes in order and start again when they run out (talea and color).
500
+
501
+ (defn- pow2? [d] (loop [d d] (cond (= d 1) true (or (< d 1) (odd? d)) false :else (recur (/ d 2)))))
502
+
503
+ (defn- pow2-at-least
504
+ "The smallest power of two (of a beat) that is not shorter than the fraction [n d], as a fraction."
505
+ [[n d]]
506
+ (let [ge (fn [[a b]] (>= (* a d) (* n b)))]
507
+ (if (ge [1 1])
508
+ (loop [p [1 1]] (let [h [(first p) (* 2 (second p))]] (if (ge h) (recur h) p)))
509
+ (loop [p [2 1]] (if (ge p) p (recur [(* 2 (first p)) 1]))))))
510
+
511
+ (defn- read-shares [s] (if (string? s) (edn/read-string s) s))
512
+
513
+ (defn- rtm-item [x]
514
+ (cond
515
+ (and (number? x) (not (zero? x))) {:w (js/Math.abs x) :rest (neg? x)}
516
+ (and (sequential? x) (= 2 (count x)) (number? (first x)) (pos? (first x)) (sequential? (second x)))
517
+ {:w (first x) :subs (second x)}
518
+ :else (throw (js/Error. (str "rtm: a share is a number (negative: a rest) or [weight [shares …]], not " (pr-str x))))))
519
+
520
+ (defn- integer-weights
521
+ "Weights as whole numbers without a common factor: [2 2 2] → [1 1 1], [0.5 1] → [1 2]."
522
+ [ws]
523
+ (let [rs (mapv rat ws)
524
+ l (reduce lcm 1 (map second rs))
525
+ is (mapv (fn [[n d]] (* n (/ l d))) rs)
526
+ g (reduce gcd 0 is)]
527
+ (mapv (fn [i] (/ i g)) is)))
528
+
529
+ (defn- rtm-nodes
530
+ "The nodes of shares that last total (a fraction of written beats); next-leaf makes each note."
531
+ [shares total next-leaf depth]
532
+ (let [shares (read-shares shares)]
533
+ (when (> depth 16) (throw (js/Error. "rtm: shares nested too deep")))
534
+ (when-not (and (sequential? shares) (seq shares))
535
+ (throw (js/Error. (str "rtm: :shares is a list of shares, like [1 [1 [1 1 1]] -1 2], not " (pr-str shares)))))
536
+ (let [items (mapv rtm-item shares)
537
+ ws (integer-weights (map :w items))
538
+ s (reduce + ws)
539
+ unit (r-norm [(first total) (* (second total) s)])
540
+ tup? (not (pow2? (second unit)))
541
+ u (if tup? (pow2-at-least unit) unit)
542
+ nodes (vec (mapcat (fn [it w]
543
+ (let [d (r-norm [(* w (first u)) (second u)])
544
+ beats (/ (first d) (second d))]
545
+ (cond (:subs it) (rtm-nodes (:subs it) d next-leaf (inc depth))
546
+ (:rest it) [[:rest {:dur beats}]]
547
+ :else [(next-leaf beats)])))
548
+ items ws))]
549
+ (if tup?
550
+ ;; s written units in the time of total: s:(total/u)
551
+ (let [[a b] (r-norm [(* (first total) (second u)) (* (second total) (first u))])
552
+ ratio (if (= b 1) [s a] (let [g (gcd (* s b) a)] [(/ (* s b) g) (/ a g)]))]
553
+ [(into [:tuplet {:ratio ratio}] nodes)])
554
+ nodes))))
555
+
556
+ (defn- rtm-leaves
557
+ "A function that gives the next note of an :rtm, with a duration: its :pitches in turn (a melody
558
+ string, or a list of pitches), starting again when they run out; \"r\" there is a rest."
559
+ [a]
560
+ (let [src (:pitches a)
561
+ pool (vec (cond (string? src) (melody src)
562
+ (sequential? src) (mapcat (fn [p] (cond (string? p) (melody p)
563
+ (number? p) [[:note {:pitch p}]]
564
+ (node? p) [p]
565
+ :else []))
566
+ src)
567
+ :else []))
568
+ default [:note {:pitch (or (:pitch a) "c4")}]
569
+ i (volatile! 0)]
570
+ (fn [beats]
571
+ (let [n (if (seq pool) (nth pool (mod @i (count pool))) default)]
572
+ (vswap! i inc)
573
+ (update-attrs n assoc :dur beats)))))
574
+
575
+ (defn- rtm-expand
576
+ "The nodes an :rtm stands for. Its notes remember the :rtm they come from ({:src path :rtm true})."
577
+ [n path bar]
578
+ (let [a (attrs n)
579
+ total (cond (some? (:dur a)) (:dur a)
580
+ bar (let [[p q] bar] (* p (/ 4 q)))
581
+ :else 4)
582
+ _ (when-not (and (number? total) (pos? total))
583
+ (throw (js/Error. (str "rtm: :dur is a positive number of beats, not " (pr-str total)))))
584
+ src (if path {:src path :rtm true} (meta n))
585
+ mark (fn mark [x] (if (node? x) (from (with-kids x (mapv mark (kids x))) src) x))
586
+ nodes (mapv mark (rtm-nodes (:shares a) (rat total) (rtm-leaves a) 0))
587
+ extra (dissoc a :shares :pitches :pitch :dur)]
588
+ (if (seq extra) [(from (into [:seq extra] nodes) src)] nodes)))
589
+
590
+ ;; ───────── proportional rhythm: cells (share lists → share lists) ─────────
591
+
592
+ (defn cell-retrograde
593
+ "Shares backwards, at every level: [1 [2 [1 3]]] → [[2 [3 1]] 1]."
594
+ [shares]
595
+ (vec (reverse (map (fn [x] (if (sequential? x) [(first x) (cell-retrograde (second x))] x)) (read-shares shares)))))
596
+
597
+ (defn cell-rotate
598
+ "Moves the first k shares to the end (negative k: the other way)."
599
+ [k shares]
600
+ (let [xs (vec (read-shares shares)) n (count xs)]
601
+ (if (zero? n) xs (let [k (mod k n)] (vec (concat (drop k xs) (take k xs)))))))
602
+
603
+ (defn cell-at
604
+ "The share at path: [i] is the i-th share; [i j] the j-th inside the i-th, when it is divided."
605
+ [shares path]
606
+ (loop [xs (read-shares shares) p (seq path)]
607
+ (if (nil? p)
608
+ xs
609
+ (let [x (nth (vec xs) (first p) nil)]
610
+ (cond (nil? (next p)) x
611
+ (and (sequential? x) (sequential? (second x))) (recur (second x) (next p))
612
+ :else nil)))))
613
+
614
+ (defn cell-replace-at
615
+ "Divides the share at path into cell, keeping its weight: a cell can grow inside itself
616
+ ((cell-replace-at seed [1] seed))."
617
+ [shares path cell]
618
+ (let [xs (vec (read-shares shares)) [i & more] path x (nth xs i nil)]
619
+ (when (nil? x) (throw (js/Error. (str "cell-replace-at: no share at " (pr-str path)))))
620
+ (assoc xs i
621
+ (if (seq more)
622
+ (if (and (sequential? x) (sequential? (second x)))
623
+ [(first x) (cell-replace-at (second x) more cell)]
624
+ (throw (js/Error. (str "cell-replace-at: the share at " (pr-str (vec (take 1 path))) " is not divided"))))
625
+ [(if (sequential? x) (first x) (js/Math.abs x)) (vec (read-shares cell))]))))
626
+
627
+ ;; ───────── expansion ─────────
628
+
629
+ (defn expand*
630
+ "Expands n; every node remembers where it was written: {:src path} (and {:sub [i …]} inside a
631
+ melody string, {:rtm true} for what an :rtm stands for); nodes that come from :defs have no :src.
632
+ ctx carries the meter in force (as :with-meters reads it) so that an :rtm can fill its measure."
633
+ ([n defs depth] (expand* n defs depth nil))
634
+ ([n defs depth path] (expand* n defs depth path {:meter (volatile! [4 4]) :bar nil}))
635
+ ([n defs depth path ctx]
636
+ (cond
637
+ (string? n) (vec (map-indexed (fn [i x]
638
+ (let [x (if (= :chord (tag x))
639
+ (with-kids x (vec (map-indexed (fn [j k] (from k (when path {:src path :sub [i j]}))) (kids x))))
640
+ x)]
641
+ (from x (when path {:src path :sub [i]}))))
642
+ (melody n)))
643
+ (not (node? n)) []
644
+ (= :use (tag n))
645
+ (let [a (attrs n) r (:ref a) k (if (string? r) (keyword r) r) d (get defs k)]
646
+ (when (> depth 24) (throw (js/Error. (str "Fragments that use each other without end (" r ")"))))
647
+ (when-not d (throw (js/Error. (str "No fragment " (pr-str r) " in :defs"))))
648
+ (let [xs (expand* d defs (inc depth) nil ctx)
649
+ body (if (= 1 (count xs)) (first xs) (into [:seq] xs))
650
+ varied (apply-ops a body)
651
+ extra (apply dissoc a op-keys)]
652
+ [(from (if (seq extra) [:seq extra varied] varied) (if path {:src path :use true} (meta n)))]))
653
+ (= :rtm (tag n)) (rtm-expand n path (:bar ctx))
654
+ :else
655
+ (let [measure? (= :measure (tag n))
656
+ a (cond-> (attrs n) measure? with-meter-attrs)
657
+ defs (merge defs (:defs a))
658
+ _ (when (and measure? (vector? (:meter a))) (vreset! (:meter ctx) (:meter a)))
659
+ ;; only the direct children of a measure fill it
660
+ kctx (assoc ctx :bar (when measure? @(:meter ctx)))]
661
+ [(from (make (tag n) (dissoc a :defs)
662
+ (vec (apply concat (mapv (fn [i k] (expand* k defs depth (when path (conj path i)) kctx))
663
+ (range) (kids n)))))
664
+ (if path {:src path} (meta n)))]))))
665
+
666
+ (defn- one-node [xs] (if (<= (count xs) 1) (first xs) (into [:seq] xs)))
667
+
668
+ (defn expand
669
+ "Strings become notes, [:use …] the fragments they name, varied, and [:rtm …] its notes, rests and
670
+ tuplets. A list of nodes becomes a :seq."
671
+ [x]
672
+ (cond
673
+ (string? x) (into [:seq] (melody x))
674
+ (and (sequential? x) (not (node? x))) (expand (into [:seq] x))
675
+ :else (one-node (expand* x {} 0 nil))))
676
+
677
+ (defn expand-source
678
+ "Expands a written tree remembering, in each node's metadata, where it was written ({:src path},
679
+ {:sub [i]} inside a melody string), and in the root which box it comes from ({:from :b2}): a score
680
+ that shows it can then edit the written tree."
681
+ [t box-id]
682
+ (vary-meta (one-node (expand* t {} 0 [])) assoc :from box-id))
683
+
684
+ ;; ───────── time: flattening ─────────
685
+
686
+ (defn- add-ev [acc ev] (conj! acc ev))
687
+
688
+ (defn place
689
+ "Places node n at t (beats) with a time scale; adds its events to acc and returns where it ends."
690
+ [n t scale ctx acc]
691
+ (let [tg (tag n) a (attrs n)]
692
+ (cond
693
+ ;; a grace note sounds briefly where it is, and the time goes on as if it were not there
694
+ (and (= :note tg) (:grace a))
695
+ (let [m (midi-of a)]
696
+ (when m
697
+ (add-ev acc (merge (dissoc a :pitch :hz :cents :dur :at :id)
698
+ {:kind :note :t t :dur (* scale (or (:dur a) 0.125)) :pitch m :voice (:voice ctx) :path (:path ctx)}
699
+ (when-let [w (spelling-of a)] {:name (sp/->name w)}))))
700
+ t)
701
+
702
+ (= :note tg)
703
+ (let [d (* scale (or (:dur a) (:dur ctx) 1)) m (midi-of a)]
704
+ (when m
705
+ (add-ev acc (merge (dissoc a :pitch :hz :cents :dur :at :id)
706
+ {:kind :note :t t :dur d :pitch m :voice (:voice ctx) :path (:path ctx)}
707
+ (when (:id a) {:id (:id a)})
708
+ (when-let [w (spelling-of a)] {:name (sp/->name w)}))))
709
+ (+ t d))
710
+
711
+ (= :rest tg) (+ t (* scale (or (:dur a) (:dur ctx) 1)))
712
+
713
+ (mark-tags tg)
714
+ (do (add-ev acc (merge (dissoc a :at) {:kind tg :t t :dur (* scale (or (:dur a) 0)) :voice (:voice ctx) :path (:path ctx)}))
715
+ t)
716
+
717
+ (= :chord tg)
718
+ (let [d (* scale (or (:dur a) (:dur ctx) 1))]
719
+ (doseq [[i k] (map-indexed vector (kids n)) :when (node? k)]
720
+ (place k t 1 {:voice (:voice ctx) :dur d :path (conj (:path ctx) i)} acc))
721
+ (+ t d))
722
+
723
+ (block-tags tg)
724
+ (let [ctx (cond-> ctx (:tempo a) (assoc :tempo (:tempo a)))]
725
+ (loop [ks (map-indexed vector (kids n)) cur t end t]
726
+ (if (empty? ks)
727
+ (max cur end)
728
+ (let [[i k] (first ks)]
729
+ (if-not (node? k)
730
+ (recur (rest ks) cur end)
731
+ (let [ka (attrs k) c2 (assoc ctx :path (conj (:path ctx) i) :dur nil)]
732
+ (cond
733
+ (some? (:at ka)) (recur (rest ks) cur (max end (place k (+ t (* scale (:at ka))) scale c2 acc)))
734
+ (#{:voice :par} (tag k)) (recur (rest ks) cur (max end (place k t scale c2 acc)))
735
+ :else (let [e (place k cur scale c2 acc)] (recur (rest ks) e (max end e))))))))))
736
+
737
+ (par-tags tg)
738
+ (let [ctx ctx]
739
+ (reduce (fn [end [i k]]
740
+ (if (node? k)
741
+ (let [at (:at (attrs k))
742
+ s (+ t (* scale (or at 0)))
743
+ e (place k s scale (assoc ctx :path (conj (:path ctx) i) :dur nil) acc)]
744
+ (max end e))
745
+ end))
746
+ t (map-indexed vector (kids n))))
747
+
748
+ (seq-tags tg)
749
+ (let [scale (cond
750
+ (and (= :tuplet tg) (vector? (:ratio a))) (let [[p q] (:ratio a)] (* scale (/ q p)))
751
+ :else scale)
752
+ voice (if (= :voice tg) (or (:name a) (:id a) (str "v" (count (:path ctx)) "-" (last (:path ctx)))) (:voice ctx))]
753
+ (loop [ks (map-indexed vector (kids n)) cur t prev nil]
754
+ (if (empty? ks)
755
+ cur
756
+ (let [[i k] (first ks)]
757
+ (if-not (node? k)
758
+ (recur (rest ks) cur prev)
759
+ (let [ka (attrs k)
760
+ durable (and (#{:note :rest :chord} (tag k)) (not (:grace ka)))
761
+ prev (if (and durable (:dur ka)) (:dur ka) prev)
762
+ c2 {:voice voice :dur (when durable prev) :path (conj (:path ctx) i) :tempo (:tempo ctx)}]
763
+ (if (some? (:at ka))
764
+ (do (place k (+ t (* scale (:at ka))) scale c2 acc) (recur (rest ks) cur prev))
765
+ (recur (rest ks) (place k cur scale c2 acc) prev))))))))
766
+
767
+ :else t)))
768
+
769
+ (defn- join-ties
770
+ "Events in time order with every tied note (:tie) joined to the note it goes on in: the next note of
771
+ its voice with the same pitch that starts where it ends. One sound, one event (it keeps the first's keys)."
772
+ [evs]
773
+ (let [same? (fn [a b] (< (js/Math.abs (- a b)) 1e-6))]
774
+ (loop [es evs out (transient []) open {}]
775
+ (if (empty? es)
776
+ (mapv (fn [e] (if (= :note (:kind e)) (dissoc e :tie) e)) (persistent! out))
777
+ (let [e (first es)]
778
+ (if-not (and (= :note (:kind e)) (not (:grace e)))
779
+ (recur (rest es) (conj! out e) open)
780
+ (let [k [(:voice e) (cv/round-to (:pitch e) 4)]
781
+ [i end] (get open k)]
782
+ (if (and i (same? end (:t e)))
783
+ (let [prev (nth out i)
784
+ joined (assoc prev :dur (cv/round-to (+ (:dur prev) (:dur e)) 6))]
785
+ (recur (rest es) (assoc! out i joined)
786
+ (if (:tie e) (assoc open k [i (+ (:t e) (:dur e))]) (dissoc open k))))
787
+ (let [idx (count out)]
788
+ (recur (rest es) (conj! out e)
789
+ (if (:tie e) (assoc open k [idx (+ (:t e) (:dur e))]) (dissoc open k))))))))))))
790
+
791
+ (defn events
792
+ "The flat list of events of a tree, in time order: {:kind :note|:param|:dyn|:text, :t :dur (beats),
793
+ :pitch (MIDI) for notes, :voice, :path (where it is in the tree), and every other key of the node}."
794
+ [tree]
795
+ (let [t (expand tree) acc (transient [])]
796
+ (place t 0 1 {:path [] :voice nil} acc)
797
+ (->> (persistent! acc)
798
+ (map (fn [e] (-> e (update :t cv/round-to 6) (update :dur cv/round-to 6))))
799
+ (sort-by (juxt :t (fn [e] (- (or (:pitch e) 0)))))
800
+ join-ties)))
801
+
802
+ (defn duration "How long a tree lasts, in beats." [tree]
803
+ (let [t (expand tree) acc (transient [])] (cv/round-to (place t 0 1 {:path []} acc) 6)))
804
+
805
+ (defn tempo-of [tree] (or (:tempo (attrs (expand tree))) 60))
806
+
807
+ (defn notes [tree] (filterv (fn [e] (= :note (:kind e))) (events tree)))
808
+
809
+ (defn pitches "The pitches, in time order: as they are written (names), or names for whole numbers." [tree]
810
+ (mapv (fn [e] (if (and (:name e) (== (:pitch e) (js/Math.round (:pitch e)))) (:name e) (pitch-name (:pitch e)))) (notes tree)))
811
+
812
+ (defn summary [tree]
813
+ (try
814
+ (let [es (events tree) ns (filter (fn [e] (= :note (:kind e))) es)
815
+ vs (count (distinct (keep :voice ns)))]
816
+ (str (count ns) " notes" (when (> vs 1) (str " · " vs " voices")) " · " (cv/fmt (duration tree)) " beats"
817
+ (let [k (count (remove (fn [e] (= :note (:kind e))) es))] (when (pos? k) (str " · " k " marks")))))
818
+ (catch :default e (str "error: " (.-message e)))))
819
+
820
+ ;; ───────── checking ─────────
821
+
822
+ (defn problems
823
+ "What is wrong in a tree (unknown tags, notes without pitch, measures that do not add up): a list of texts."
824
+ [tree]
825
+ (let [out (atom [])
826
+ say (fn [& xs] (swap! out conj (apply str xs)))]
827
+ (letfn [(go [n path]
828
+ (cond
829
+ (string? n) (try (melody n) (catch :default e (say (.-message e))))
830
+ (not (node? n)) (say "not a node at " (pr-str path) ": " (pr-str n))
831
+ :else
832
+ (let [tg (tag n)
833
+ a (if (= :measure tg)
834
+ (try (with-meter-attrs (attrs n))
835
+ (catch :default e (say (.-message e) " at " (pr-str path)) (dissoc (attrs n) :meter)))
836
+ (attrs n))]
837
+ (when-not (known-tags tg) (say "unknown tag " tg " at " (pr-str path)))
838
+ (when (and (= :note tg) (nil? (midi-of a))) (say "a note without a pitch I understand at " (pr-str path) ": " (pr-str a)))
839
+ (when (and (:dur a) (not (and (number? (:dur a)) (>= (:dur a) 0)))) (say "a duration is a number of beats at " (pr-str path)))
840
+ (when (and (= :measure tg) (vector? (:meter a)))
841
+ (let [[p q] (:meter a) want (* p (/ 4 q))
842
+ ;; the measure itself, so that an :rtm in it fills its meter
843
+ got (try (duration (make :measure (dissoc a :at) (kids n))) (catch :default _ nil))]
844
+ (when (and got (> (js/Math.abs (- got want)) 1e-6))
845
+ (say "measure " (pr-str path) " lasts " (cv/fmt got) " beats; its meter " p "/" q " asks for " (cv/fmt want)))))
846
+ (doseq [[i k] (map-indexed vector (kids n))] (go k (conj path i))))))]
847
+ (go tree [])
848
+ ;; groups must add up to the meter they group (inherited meters included)
849
+ (letfn [(gs [n path]
850
+ (when (node? n)
851
+ (let [{[p q] :meter g :groups} (attrs n)]
852
+ (when (and (= :measure (tag n)) (seq g))
853
+ (cond (not (every? (fn [x] (and (number? x) (pos? x) (== x (js/Math.round x)))) g))
854
+ (say "groups are whole numbers of units, at " (pr-str path) ": " (pr-str g))
855
+ (not= p (reduce + g))
856
+ (say "groups " (pr-str g) " at " (pr-str path) " add up to " (reduce + g) "; the meter " p "/" q " has " p " units"))))
857
+ (doseq [[i k] (map-indexed vector (kids n))] (gs k (conj path i)))))]
858
+ (when (empty? @out) (try (gs (with-meters tree) []) (catch :default e (say (.-message e))))))
859
+ (when (empty? @out)
860
+ (try (expand tree) (catch :default e (say (.-message e))))))
861
+ @out))
862
+
863
+ (defn warning? "A problem that does not stop the tree from being read and played (a measure that does not add up)." [msg]
864
+ (str/starts-with? msg "measure "))
865
+
866
+ (defn errors "The problems that make a tree unusable." [t] (vec (remove warning? (problems t))))
867
+ (defn warnings "The problems a tree can live with while it is being written." [t] (vec (filter warning? (problems t))))
868
+
869
+ ;; ───────── reading (EDN text → tree) and writing (tree → text) ─────────
870
+
871
+ (defn read-tree
872
+ "EDN text → tree (one form; several become a :seq). Only reads data: nothing is evaluated."
873
+ [text]
874
+ (let [forms (edn/read-string (str "[" text "\n]"))]
875
+ (cond (empty? forms) nil
876
+ (= 1 (count forms)) (first forms)
877
+ :else (into [:seq] forms))))
878
+
879
+ (defn pp
880
+ "A tree as text, one container per line, indented."
881
+ ([tree] (pp tree 0))
882
+ ([n depth]
883
+ (if-not (node? n)
884
+ (pr-str n)
885
+ (let [a (attrs n) ks (kids n)
886
+ head (str "[" (pr-str (tag n)) (when (seq a) (str " " (pr-str a))))
887
+ nested? (some (fn [k] (and (node? k) (seq (kids k)))) ks)]
888
+ (if (or (not nested?) (empty? ks))
889
+ (str head (apply str (map (fn [k] (str " " (pp k 0))) ks)) "]")
890
+ (str head
891
+ (apply str (map (fn [k] (str "\n" (apply str (repeat (inc depth) " ")) (pp k (inc depth)))) ks))
892
+ "]"))))))
893
+
894
+ ;; ───────── conversions: canvas, freqt, score ─────────
895
+
896
+ (defn ->strokes
897
+ "A tree as freqt data: one stroke per note (Hz over beats), with its glissando and its :look (weight,
898
+ gradient, texture, colour), if the note has one."
899
+ [tree]
900
+ (let [ns (notes tree)]
901
+ {:strokes (into {}
902
+ (for [[i e] (map-indexed vector ns)
903
+ :let [t0 (:t e) d (max 0.01 (:dur e)) hz (cv/midi->hz (:pitch e))
904
+ g (or (:gliss e) [[0 0] [1 0]])
905
+ g (if (< (count g) 2) [[0 0] [1 0]] g)]]
906
+ [(keyword (str "t" (inc i)))
907
+ (cv/with-look {:pts (mapv (fn [[x c]] [(cv/round-to (+ t0 (* d x)) 4) (cv/round-to (cv/cents->hz c hz) 3)]) g)}
908
+ (:look e))]))
909
+ :gx nil :gy nil}))
910
+
911
+ (defn ->canvas
912
+ "A tree as data for a generic canvas: time along X, pitch along a log Y."
913
+ [tree]
914
+ (let [d (->strokes tree)
915
+ ys (mapcat (fn [[_ s]] (map second (:pts s))) (:strokes d))
916
+ lo (if (seq ys) (/ (apply min ys) 1.2) 100) hi (if (seq ys) (* (apply max ys) 1.2) 1000)]
917
+ (assoc d :ax {:x {:lo 0 :hi (max 1 (duration tree)) :log false} :y {:lo lo :hi hi :log true}})))
918
+
919
+ (defn <-strokes
920
+ "Freqt (or canvas) data as a tree: one note per stroke, placed with :at; bends become :gliss."
921
+ [d]
922
+ (into [:voice {:name "strokes"}]
923
+ [(into [:par]
924
+ (for [[_ s] (cv/sorted-strokes d)
925
+ :let [pts (:pts s) [t0 f0] (first pts) [t1 _] (peek pts)
926
+ m (cv/hz->midi f0) mr (js/Math.round m)
927
+ dur (max 0.01 (- t1 t0))
928
+ g (mapv (fn [[t f]] [(cv/round-to (/ (- t t0) dur) 3) (cv/round-to (cv/hz->cents f (cv/midi->hz mr)) 1)]) pts)
929
+ flat? (every? (fn [[_ c]] (< (js/Math.abs (- c (second (first g)))) 1)) g)]]
930
+ [:note (cond-> {:at (cv/round-to t0 4) :dur (cv/round-to dur 4)
931
+ :pitch (if (< (js/Math.abs (- m mr)) 0.02) (pitch-name mr) (cv/round-to m 2))}
932
+ (not flat?) (assoc :pitch (pitch-name mr) :gliss g))]))]))
933
+
934
+ (defn ->voice
935
+ "A tree as the voice data kairotic.score draws approximately (a sixteenth grid)."
936
+ [tree]
937
+ (let [ns (notes tree)]
938
+ {:tempo (tempo-of tree) :meter [4 4]
939
+ :events (into {} (for [[i e] (map-indexed vector ns)
940
+ :let [m (:pitch e) mr (js/Math.round m) dv (js/Math.round (* 100 (- m mr)))]]
941
+ [(keyword (str "e" (inc i)))
942
+ (cond-> {:t (:t e) :pitch (max 0 (min 127 mr)) :dur (max 0.25 (:dur e))}
943
+ (>= (js/Math.abs dv) 5) (assoc :txt (str (when (pos? dv) "+") dv)))]))}))
944
+
945
+ ;; ───────── measured notation (MEI) ─────────
946
+ ;; When a voice is written in :measure nodes, each one becomes a bar: notes, rests, chords and tuplets
947
+ ;; as written, with dynamics, articulations and texts. Outside tuplets each value is written where the
948
+ ;; beats can be seen (metric-split); :tie and :grace notes are written as ties and grace notes. A tree
949
+ ;; without measures (or a freqt's strokes) is first quantized into measures by kairotic.quantize.
950
+
951
+ (def mei-durs [[8 "breve" 0] [6 "1" 1] [4 "1" 0] [3 "2" 1] [2 "2" 0] [1.5 "4" 1] [1 "4" 0] [0.75 "8" 1] [0.5 "8" 0]
952
+ [0.375 "16" 1] [0.25 "16" 0] [0.1875 "32" 1] [0.125 "32" 0] [0.0625 "64" 0]])
953
+
954
+ (declare split-dur)
955
+
956
+ (defn written-value
957
+ "The single written value (plain or dotted) that lasts d beats, as [beats mei-dur dots], or nil."
958
+ [d]
959
+ (first (filter (fn [[b]] (< (js/Math.abs (- b d)) 1e-6)) mei-durs)))
960
+
961
+ (defn metric-split
962
+ "How a note (or a rest) of d beats that starts at pos (beats from the start of its bar) is written:
963
+ written values [beats mei-dur dots] …, tied, cut where the meter has to be seen. bounds are where the
964
+ beats (or groups) of the bar start, from its start. A note may run over a beat when it starts at least
965
+ as strong as every beat it covers (a half note on the downbeat of 4/4, a dotted quarter on beat 2 of
966
+ 3/4) or, not a rest, as a syncopation centred on one beat and as long as that beat's unit (eighth –
967
+ quarter – eighth; quarter – half – quarter). Inside a beat any written value goes (a sixteenth and a
968
+ dotted eighth). In a simple meter a rest over a beat is not dotted."
969
+ [meter bounds pos d rest?]
970
+ (let [{[p q] :meter g :groups :as m} (meter-of meter)
971
+ bar (* p (/ 4 q))
972
+ eps 1e-6
973
+ lv (fn [x] (meter-level m x))
974
+ bs (vec (sort (filter (fn [b] (< eps b (- bar eps))) bounds)))
975
+ ends (conj bs bar)
976
+ unit-at (fn [b] (- (or (first (filter (fn [x] (and (> x (+ b eps)) (<= (lv x) (lv b)))) ends)) bar) b))
977
+ simple? (and (<= q 4) (empty? g))
978
+ allowed? (fn [a e]
979
+ (let [wv (written-value (- e a))
980
+ crossed (filter (fn [b] (< (+ a eps) b (- e eps))) bs)]
981
+ (and wv
982
+ (or (empty? crossed)
983
+ (and (every? (fn [b] (<= (lv a) (lv b))) crossed)
984
+ (not (and rest? simple? (pos? (nth wv 2)))))
985
+ (and (not rest?) (= 1 (count crossed))
986
+ (let [b (first crossed)]
987
+ (and (< (js/Math.abs (- (- b a) (- e b))) eps)
988
+ (< (js/Math.abs (- (- e a) (unit-at b))) eps))))))))]
989
+ (if (or (> (+ pos d) (+ bar eps)) (neg? pos))
990
+ (split-dur d)
991
+ (loop [a pos out []]
992
+ (let [left (- (+ pos d) a)]
993
+ (if (or (< left 0.03) (> (count out) 16))
994
+ (if (empty? out) (split-dur d) out)
995
+ (let [e (+ a left)
996
+ hit (first (filter (fn [x] (allowed? a x))
997
+ (cons e (reverse (filter (fn [b] (< (+ a eps) b (- e eps))) bs)))))]
998
+ (if hit
999
+ (recur hit (conj out (written-value (- hit a))))
1000
+ ;; nothing written reaches a beat: the longest value that fits before the next one
1001
+ (let [nb (min e (or (first (filter (fn [b] (> b (+ a eps))) bs)) e))
1002
+ [b du dots] (or (first (filter (fn [[b]] (<= b (+ (- nb a) eps))) mei-durs)) (peek mei-durs))]
1003
+ (recur (+ a b) (conj out [b du dots])))))))))))
1004
+
1005
+ (defn split-dur
1006
+ "A duration in beats as written values ([beats mei-dur dots] …), tied when it needs more than one."
1007
+ [d]
1008
+ (loop [left d out []]
1009
+ (if (or (< left 0.03) (> (count out) 8))
1010
+ (if (empty? out) [[d "64" 0]] out)
1011
+ (let [[b du dots] (or (first (filter (fn [[b]] (<= b (+ left 1e-6))) mei-durs)) (peek mei-durs))]
1012
+ (recur (- left b) (conj out [b du dots]))))))
1013
+
1014
+ (def artic-names {:staccato "stacc" :accent "acc" :tenuto "ten" :marcato "marc" :staccatissimo "stacciss"
1015
+ :fermata nil :spiccato "spicc" :up-bow "upbow" :down-bow "dnbow"})
1016
+
1017
+ (defn esc-xml [s] (-> (str s) (str/replace "&" "&amp;") (str/replace "<" "&lt;") (str/replace "\"" "&quot;")))
1018
+
1019
+ (defn measured? [tree] (boolean (some (fn [x] (and (node? x) (= :measure (tag x)))) (tree-seq node? kids (expand tree)))))
1020
+
1021
+ (defn voices-of
1022
+ "The voices of a tree: its :voice nodes, or the whole tree as one voice."
1023
+ [t]
1024
+ (let [vs (filter (fn [x] (and (node? x) (= :voice (tag x)))) (tree-seq node? kids t))]
1025
+ (if (seq vs) (vec vs) [[:voice t]])))
1026
+
1027
+ (defn measures-of [v]
1028
+ (letfn [(go [n] (cond (not (node? n)) []
1029
+ (= :measure (tag n)) [n]
1030
+ :else (mapcat go (kids n))))]
1031
+ (vec (go v))))
1032
+
1033
+ ;; ───────── spelling: names for notes written as numbers (issue #88) ─────────
1034
+
1035
+ (declare update-at node-at)
1036
+
1037
+ (defn key-times
1038
+ "Where a tree says its key: [[beat key] …] — the :key of the tree (or of a section or voice) from 0,
1039
+ and a measure's :key from where that measure starts (in the first voice)."
1040
+ [t]
1041
+ (let [t (with-meters t)
1042
+ root (some (fn [x] (when (and (node? x) (not= :measure (tag x)) (some? (:key (attrs x)))) (:key (attrs x))))
1043
+ (tree-seq node? kids t))
1044
+ ms (measures-of (first (voices-of t)))
1045
+ starts (reductions + 0 (map (fn [m] (let [[p q] (or (:meter (attrs m)) [4 4])] (* p (/ 4 q)))) ms))]
1046
+ (vec (concat (when (some? root) [[0 root]])
1047
+ (keep (fn [[m st]] (when (some? (:key (attrs m))) [st (:key (attrs m))])) (map vector ms starts))))))
1048
+
1049
+ (defn- note-base
1050
+ "The integer pitch a note is written from, and what is left in cents: 60.5 → [60 50] (a quarter tone
1051
+ above), 60.3 → [60 30], 60.7 → [61 -30]."
1052
+ [m]
1053
+ (let [f (js/Math.floor m) frac (- m f)
1054
+ b (if (< (js/Math.abs (- frac 0.5)) 0.08) f (js/Math.round m))]
1055
+ [b (js/Math.round (* 100 (- m b)))]))
1056
+
1057
+ (defn spellings-for
1058
+ "Names for the notes of an expanded tree that have none (numbers, Hz), chosen by kairotic.spell:
1059
+ {path spelling} (paths as mt/events gives them). The key is the tree's (key-times) where it says it;
1060
+ where not, it is estimated bar by bar (or every 4 beats) from the notes around."
1061
+ [t]
1062
+ (let [evs (filterv (fn [e] (= :note (:kind e))) (events t))]
1063
+ (if (empty? evs)
1064
+ {}
1065
+ (let [kt (key-times t)
1066
+ bar-len (if-let [m (first (measures-of (first (voices-of (with-meters t)))))]
1067
+ (let [[p q] (or (:meter (attrs m)) [4 4])] (* p (/ 4 q)))
1068
+ 4)
1069
+ ;; a key is only estimated from four pitch classes or more that fit one clearly: around the bar,
1070
+ ;; else the whole tree, else none (C)
1071
+ ;; each note counts once, however long (Temperley's flat input)
1072
+ weights (fn [es] (reduce (fn [v e] (update v (mod (first (note-base (:pitch e))) 12) + 1))
1073
+ (vec (repeat 12 0)) es))
1074
+ enough? (fn [w] (>= (count (filter pos? w)) 4))
1075
+ whole (let [w (weights evs)] (if (enough? w) (or (sp/estimate-sig w) 0) 0))
1076
+ estimated (fn [t0]
1077
+ (let [w (weights (filter (fn [e] (and (< (:t e) (+ t0 (* 1.5 bar-len))) (> (+ (:t e) (:dur e)) (- t0 (* 0.5 bar-len))))) evs))]
1078
+ (if (enough? w) (or (sp/estimate-sig w) whole) whole)))
1079
+ sig-at (memoize (fn [bar]
1080
+ (let [t0 (* bar bar-len)
1081
+ k (last (filter (fn [[b _]] (<= b (+ t0 1e-6))) kt))]
1082
+ (if k (or (:sig (sp/parse-key (second k))) 0) (estimated t0)))))
1083
+ steps (->> evs
1084
+ (group-by (fn [e] (cv/round-to (:t e) 4)))
1085
+ (sort-by key)
1086
+ (mapv (fn [[t0 es]]
1087
+ {:sig (sig-at (js/Math.floor (/ (+ t0 1e-6) bar-len)))
1088
+ :notes (mapv (fn [e] (let [a (attrs (node-at t (:path e)))]
1089
+ {:id (:path e) :voice (:voice e)
1090
+ :midi (first (note-base (:pitch e)))
1091
+ :fixed (spelling-of a)}))
1092
+ es)})))]
1093
+ (into {} (remove (fn [[p _]] (spelling-of (attrs (node-at t p)))) (sp/spell-steps steps)))))))
1094
+
1095
+ (defn spell
1096
+ "The tree with names for its notes written as numbers: 61 → \"c#4\" or \"db4\", by the key and the line
1097
+ (kairotic.spell); a quarter tone keeps it as :cents (60.5 → \"c4\" :cents 50). Names already written,
1098
+ and notes in Hz, stay as they are."
1099
+ [tree]
1100
+ (let [t (expand tree)
1101
+ names (spellings-for t)]
1102
+ (reduce (fn [t [path s]]
1103
+ (update-at t path (fn [n] (let [a (attrs n)]
1104
+ (if (number? (:pitch a))
1105
+ (let [[_ c] (note-base (:pitch a))]
1106
+ (with-attrs n (cond-> (assoc a :pitch (sp/->name s)) (not (zero? c)) (assoc :cents c))))
1107
+ n)))))
1108
+ t names)))
1109
+
1110
+ (defn ->mei
1111
+ "Measured notation of a tree. Returns {:mei text :pieces [{:id :t :staff}]} (ids → beats, for cursors)."
1112
+ [tree pre]
1113
+ (let [t (with-meters (explicit (expand tree)))
1114
+ ;; names for the notes written as numbers (kairotic.spell), beside their pitch: :spelled
1115
+ t (reduce (fn [t [path s]] (update-at t path (fn [n] (update-attrs n assoc :spelled (sp/->name s)))))
1116
+ t (spellings-for t))
1117
+ ;; the work in sections (or one), each with its voices; a voice is a staff, by name, across sections
1118
+ sections (letfn [(go [n] (cond (not (node? n)) []
1119
+ (= :section (tag n)) [n]
1120
+ :else (mapcat go (kids n))))]
1121
+ (let [ss (vec (go t))] (if (seq ss) ss [t])))
1122
+ sec-voices (mapv (fn [sc] (vec (map-indexed (fn [i v] [(or (:name (attrs v)) (str "voice " (inc i))) v]) (voices-of sc))))
1123
+ sections)
1124
+ ;; a voice is a staff, or a layer of one: voices with the same :staff share it (layer 1, 2 …)
1125
+ voice-staff (reduce (fn [m [k v]] (if (contains? m k) m (assoc m k (str (or (:staff (attrs v)) k)))))
1126
+ {} (apply concat sec-voices))
1127
+ voice-order (vec (distinct (mapcat (fn [vs] (map first vs)) sec-voices)))
1128
+ staves (vec (distinct (map voice-staff voice-order)))
1129
+ layers-of (into {} (for [sk staves] [sk (filterv (fn [k] (= sk (voice-staff k))) voice-order)]))
1130
+ staff-of (zipmap staves (map inc (range)))
1131
+ cur-layer (atom 1)
1132
+ bar-list (vec (mapcat (fn [si vs]
1133
+ (let [mss (mapv (fn [[k v]] [k (measures-of v)]) vs)
1134
+ n (reduce max 1 (map (comp count second) mss))]
1135
+ (for [i (range n)]
1136
+ {:cells (into {} (for [[k ms] mss :let [m (get ms i)] :when m] [k m]))
1137
+ :label (when (and (zero? i) (> (count sections) 1)) (:name (attrs (nth sections si))))
1138
+ :end (and (= i (dec n)) (< si (dec (count sections))))})))
1139
+ (range) sec-voices))
1140
+ nbars (count bar-list)
1141
+ ;; [meter groups] of a bar (every measure carries them: with-meters)
1142
+ mg-at (fn [i] (or (some (fn [j] (some (fn [m] (let [a (attrs m)] (when (:meter a) [(:meter a) (seq (:groups a))])))
1143
+ (vals (:cells (nth bar-list j)))))
1144
+ (reverse (range (inc (max 0 (min i (dec nbars)))))))
1145
+ [[4 4] nil]))
1146
+ meter-at (fn [i] (first (mg-at i)))
1147
+ ;; the key of a bar: a measure's :key from there on, else the tree's (or a section's, a voice's);
1148
+ ;; :none, or :accidentals :every anywhere above the measures, writes every accidental
1149
+ root-key (some (fn [x] (when (and (node? x) (not= :measure (tag x)) (some? (:key (attrs x)))) (:key (attrs x))))
1150
+ (tree-seq node? kids t))
1151
+ every-all (boolean (some (fn [x] (and (node? x) (#{:every "every"} (:accidentals (attrs x))))) (tree-seq node? kids t)))
1152
+ key-at (memoize (fn [i] (let [raw (or (some (fn [j] (some (fn [m] (:key (attrs m))) (vals (:cells (nth bar-list j)))))
1153
+ (reverse (range (inc (max 0 (min i (dec nbars)))))))
1154
+ root-key)
1155
+ k (sp/parse-key raw)]
1156
+ {:sig (or (:sig k) 0) :every (or every-all (boolean (:none k)))})))
1157
+ ;; a grouped meter is written as its groups: 2+3/8
1158
+ meter-count (fn [i] (let [[[p _] g] (mg-at i)] (if g (str/join "+" g) p)))
1159
+ counter (atom 0)
1160
+ nid (fn [] (str "m-" pre (swap! counter inc)))
1161
+ pieces (atom [])
1162
+ ctrl (atom {}) ; bar → control events (dynam, dir, hairpin, tie)
1163
+ ctl! (fn [bar x] (swap! ctrl update bar (fnil conj []) x))
1164
+ acc-mem (atom {}) ; [staff bar] → {[step oct] alteration shown}
1165
+ open-gliss (atom {}) ; [staff layer] → {:id :bar :end :c} of a note that bends into the next
1166
+ gliss-dir (fn [staff gl] (str "<dir staff=\"" staff "\" startid=\"#" (:id gl) "\" place=\"above\"><rend fontstyle=\"italic\">gliss. "
1167
+ (if (pos? (:c gl)) "↗ +" "↘ ") (js/Math.round (:c gl)) "¢</rend></dir>"))
1168
+ open-ties (atom {}) ; [staff layer pitch] → [id bar] of a note tied (:tie) to the next one
1169
+ bar-start (atom {})
1170
+ _ (reduce (fn [acc i] (swap! bar-start assoc i acc) (let [[p q] (meter-at i)] (+ acc (* p (/ 4 q))))) 0 (range (inc nbars)))
1171
+ tstamp (fn [bar beat] (let [[_ q] (meter-at bar)] (cv/round-to (inc (* beat (/ q 4))) 4)))
1172
+ ;; where beams may run in a bar: its groups, or its beats (dotted in 6/8, 9/8, 12/8; the whole
1173
+ ;; bar in 2/8 and 3/8), as [start end] in absolute beats
1174
+ beam-spans (fn [i]
1175
+ (let [[[p q] g] (mg-at i) u (/ 4 q) len (* p u)
1176
+ lens (cond g (map (fn [k] (* k u)) g)
1177
+ (<= q 4) (repeat (js/Math.ceil len) 1)
1178
+ (and (zero? (mod p 3)) (> p 3)) (repeat (quot p 3) (* 3 u))
1179
+ (<= p 3) [len]
1180
+ :else (concat (repeat (js/Math.floor len) 1)
1181
+ (let [r (- len (js/Math.floor len))] (when (> r 1e-9) [r]))))
1182
+ starts (reductions + (get @bar-start i) lens)]
1183
+ (vec (map vector starts (rest starts)))))
1184
+ ;; consecutive notes and chords of an eighth or shorter, inside one span, under one <beam>
1185
+ beam-join (fn [items spans]
1186
+ (let [inside (fn [x] (if (= spans :all)
1187
+ 0
1188
+ (first (keep-indexed (fn [i [s0 e0]]
1189
+ (when (and (> (:t0 x) (- s0 1e-6)) (< (:t0 x) (- e0 1e-6))
1190
+ (<= (:t1 x) (+ e0 1e-6)))
1191
+ i))
1192
+ spans))))
1193
+ flush-run (fn [out run] (if (>= (count run) 2)
1194
+ (str out "<beam>" (apply str (map :xml run)) "</beam>")
1195
+ (str out (apply str (map :xml run)))))]
1196
+ (loop [xs items run [] sp nil out ""]
1197
+ (if (empty? xs)
1198
+ (flush-run out run)
1199
+ (let [x (first xs) i (when (:beam x) (inside x))]
1200
+ (cond
1201
+ (nil? i) (recur (rest xs) [] nil (str (flush-run out run) (:xml x)))
1202
+ (or (empty? run) (= i sp)) (recur (rest xs) (conj run x) i out)
1203
+ :else (recur (rest xs) [x] i (flush-run out run))))))))
1204
+ where (fn [abs] ; absolute beat → [bar beat-in-bar]
1205
+ (let [bar (or (last (filter (fn [i] (<= (get @bar-start i) (+ abs 1e-6))) (range nbars))) 0)]
1206
+ [bar (- abs (get @bar-start bar))]))
1207
+ note-xml (fn [a staff abs id durattr art? src]
1208
+ (let [m (midi-of a)
1209
+ [b _] (where abs)
1210
+ {:keys [sig every]} (key-at b)
1211
+ ;; the written name (or the one spell chose), and what is left of the pitch in cents
1212
+ written (or (spelling-of a) (sp/parse (:spelled a)))
1213
+ [base dv] (if written
1214
+ [written (js/Math.round (* 100 (- m (sp/->midi written))))]
1215
+ (let [[bm c] (note-base m)]
1216
+ [(first (sort-by (fn [x] (js/Math.abs (- (sp/fifths x) (sp/key-center sig)))) (sp/spellings bm))) c]))
1217
+ ;; half-way between two semitones (± 8 cents): a quarter-tone accidental
1218
+ qtr (cond (< (js/Math.abs (- dv 50)) 8) 1 (< (js/Math.abs (+ dv 50)) 8) -1)
1219
+ dv (- dv (* 50 (or qtr 0)))
1220
+ alter (:alter base)
1221
+ sym (if qtr
1222
+ (get {[0 1] "1qs" [1 1] "3qs" [-1 1] "1qf" [-2 1] "3qf" [0 -1] "1qf" [-1 -1] "3qf" [1 -1] "1qs" [2 -1] "3qs"} [alter qtr])
1223
+ (get {2 "x" 1 "s" 0 "n" -1 "f" -2 "ff"} alter))
1224
+ ;; an accidental lasts to the end of the bar, for its staff, step and octave: shown when
1225
+ ;; it changes what the key (or the bar so far) says, and as a courtesy after a bar that
1226
+ ;; changed it; not on a note a tie goes on into
1227
+ k [(:step base) (:oct base)]
1228
+ cont? (or (not art?) (contains? @open-ties [staff @cur-layer (cv/round-to m 3)]))
1229
+ here (get-in @acc-mem [[staff b] k])
1230
+ before (get-in @acc-mem [[staff (dec b)] k])
1231
+ state (if qtr [alter qtr] alter)
1232
+ expected (if (some? here) here (sp/key-alter sig (:step base)))
1233
+ show? (cond cont? false
1234
+ qtr true
1235
+ every (or (not (zero? alter)) (not= alter (sp/key-alter sig (:step base))))
1236
+ (not= state expected) true
1237
+ (and (nil? here) (some? before) (not= before state)) true
1238
+ :else false)
1239
+ _ (swap! acc-mem assoc-in [[staff b] k] state)
1240
+ arts (when art? (let [x (:art a) xs (if (sequential? x) x (when x [x]))]
1241
+ (seq (keep (fn [k] (get artic-names (keyword k))) xs))))]
1242
+ (swap! pieces conj {:id id :t abs :staff staff :src src :midi m :name (sp/->name base)})
1243
+ (str "<note xml:id=\"" id "\" pname=\"" (sp/letters (:step base)) "\" oct=\"" (:oct base) "\""
1244
+ (cond show? (str " accid=\"" sym "\"")
1245
+ (and sym (not= sym "n")) (str " accid.ges=\"" sym "\""))
1246
+ durattr
1247
+ (when arts (str " artic=\"" (str/join " " arts) "\""))
1248
+ (if (>= (js/Math.abs dv) 5)
1249
+ (str "><verse n=\"1\"><syl>" (when (pos? dv) "+") dv "</syl></verse></note>")
1250
+ "/>"))))
1251
+ marks! (fn [a staff bar id]
1252
+ (when-let [d (:dyn a)] (ctl! bar (str "<dynam staff=\"" staff "\" startid=\"#" id "\">" (esc-xml d) "</dynam>")))
1253
+ (when-let [x (:text a)] (ctl! bar (str "<dir staff=\"" staff "\" startid=\"#" id "\"><rend fontstyle=\"italic\">" (esc-xml x) "</rend></dir>"))))
1254
+ ;; writes the children of a container; scale converts written beats to sounding beats (tuplets);
1255
+ ;; spans: where beams may run (:all inside a tuplet)
1256
+ layer (fn layer [ks staff bar abs scale spans]
1257
+ (loop [ks ks abs abs items []]
1258
+ (if (empty? ks)
1259
+ [(beam-join items spans) abs]
1260
+ (let [k (first ks) a (attrs k) tg (tag k)]
1261
+ (cond
1262
+ (not (node? k)) (recur (rest ks) abs items)
1263
+ (mark-tags tg)
1264
+ (let [[b beat] (where abs)]
1265
+ (case tg
1266
+ :dyn (let [mk (str (:mark a))]
1267
+ (if (#{"<" ">"} mk)
1268
+ (let [[b2 beat2] (where (+ abs (* scale (or (:dur a) 1))))]
1269
+ (ctl! b (str "<hairpin staff=\"" staff "\" form=\"" (if (= "<" mk) "cres" "dim") "\" tstamp=\"" (tstamp b beat)
1270
+ "\" tstamp2=\"" (- b2 b) "m+" (tstamp b2 beat2) "\"/>")))
1271
+ (ctl! b (str "<dynam staff=\"" staff "\" tstamp=\"" (tstamp b beat) "\">" (esc-xml mk) "</dynam>"))))
1272
+ :text (ctl! b (str "<dir staff=\"" staff "\" tstamp=\"" (tstamp b beat) "\"><rend fontstyle=\"italic\">" (esc-xml (:text a)) "</rend></dir>"))
1273
+ nil)
1274
+ (recur (rest ks) abs items))
1275
+ (= :tuplet tg)
1276
+ (let [[p q] (or (:ratio a) [3 2])
1277
+ [inner end] (layer (kids k) staff bar abs (* scale (/ q p)) :all)]
1278
+ (recur (rest ks) end
1279
+ (conj items {:t0 abs :t1 end
1280
+ :xml (str "<tuplet num=\"" p "\" numbase=\"" q "\" bracket.visible=\"true\" num.visible=\"true\">" inner "</tuplet>")})))
1281
+ (#{:seq :section :voice} tg)
1282
+ (let [[inner end] (layer (kids k) staff bar abs scale spans)]
1283
+ (recur (rest ks) end (conj items {:t0 abs :t1 end :xml inner})))
1284
+ ;; a grace note: small, before the next note, and it takes no time
1285
+ (and (= :note tg) (:grace a) (midi-of a))
1286
+ (let [id (nid)
1287
+ x (note-xml (dissoc a :art) staff abs id " dur=\"8\" grace=\"unacc\"" true (meta k))]
1288
+ (recur (rest ks) abs (conj items {:t0 abs :t1 abs :xml x})))
1289
+ ;; a rest that fills its bar: a bar rest
1290
+ (and (= :rest tg) (not= spans :all)
1291
+ (let [[b beat] (where abs) [[p q]] (mg-at b)]
1292
+ (and (< (js/Math.abs beat) 1e-6) (< (js/Math.abs (- (* scale (or (:dur a) 1)) (* p (/ 4 q)))) 1e-6))))
1293
+ (let [id (nid)]
1294
+ (swap! pieces conj {:id id :t abs :staff staff :src (meta k)})
1295
+ (recur (rest ks) (+ abs (* scale (or (:dur a) 1)))
1296
+ (conj items {:t0 abs :t1 abs :xml (str (if (> @cur-layer 1) "<mSpace xml:id=\"" "<mRest xml:id=\"") id "\"/>")})))
1297
+ (#{:note :rest :chord} tg)
1298
+ (let [d (or (:dur a) 1)
1299
+ [b beat] (where abs)
1300
+ ;; outside a tuplet a note is cut where the meter has to be seen
1301
+ parts (if (not= spans :all)
1302
+ (let [[mtr g] (mg-at b)]
1303
+ (metric-split (cond-> {:meter mtr} g (assoc :groups (vec g)))
1304
+ (map (fn [[s _]] (- s (get @bar-start b))) (beam-spans b))
1305
+ beat (* scale d) (= :rest tg)))
1306
+ (split-dur d))
1307
+ chord-ns (when (= :chord tg)
1308
+ (vec (filter (fn [n] (and (node? n) (= :note (tag n)) (midi-of (attrs n)))) (kids k))))
1309
+ ;; the notes of this one, with their pitches: a tie may come into them, or go on from them
1310
+ members (case tg :note [a] :chord (mapv attrs chord-ns) [])
1311
+ tie-key (fn [m] [staff @cur-layer (cv/round-to (midi-of m) 3)])
1312
+ part-items
1313
+ (loop [ps parts pabs abs prev-ids nil acc []]
1314
+ (if (empty? ps)
1315
+ (do (when prev-ids
1316
+ (doseq [[m id] (map vector members prev-ids)]
1317
+ (if (or (:tie a) (:tie m))
1318
+ (swap! open-ties assoc (tie-key m) [id b])
1319
+ (swap! open-ties dissoc (tie-key m))))
1320
+ ;; a note that bends (:gliss, more than 30 cents) glides into the next one
1321
+ (when-let [g (and (= :note tg) (not (:tie a)) (seq (:gliss a)))]
1322
+ (let [c0 (second (first g)) c1 (second (last g))]
1323
+ (when (>= (js/Math.abs (- c1 c0)) 30)
1324
+ (swap! open-gliss assoc [staff @cur-layer]
1325
+ {:id (last prev-ids) :bar b :end (+ (midi-of a) (/ c1 100)) :c (- c1 c0)})))))
1326
+ acc)
1327
+ (let [[pb du dots] (first ps)
1328
+ durattr (str " dur=\"" du "\"" (when (pos? dots) " dots=\"1\""))
1329
+ first? (nil? prev-ids)
1330
+ [x ids] (case tg
1331
+ :rest (let [id (nid)] (swap! pieces conj {:id id :t pabs :staff staff :src (meta k)})
1332
+ [(str "<rest xml:id=\"" id "\"" durattr "/>") nil])
1333
+ :note (let [id (nid)] [(note-xml a staff pabs id durattr first? (meta k)) [id]])
1334
+ :chord (let [cid (nid)
1335
+ ns chord-ns
1336
+ ids (mapv (fn [_] (nid)) ns)]
1337
+ [(str "<chord xml:id=\"" cid "\"" durattr
1338
+ (let [x (:art a) xs (if (sequential? x) x (when x [x]))
1339
+ arts (seq (keep (fn [kk] (get artic-names (keyword kk))) xs))]
1340
+ (when (and first? arts) (str " artic=\"" (str/join " " arts) "\"")))
1341
+ ">"
1342
+ (apply str (map (fn [n id] (note-xml (attrs n) staff pabs id "" first? (meta n))) ns ids))
1343
+ "</chord>")
1344
+ ids]))]
1345
+ (when (and first? (seq ids)) (marks! a staff b (first ids)))
1346
+ ;; a tie from the note before (:tie), across a barline or into a tuplet
1347
+ (when first?
1348
+ (when-let [gl (get @open-gliss [staff @cur-layer])]
1349
+ (let [hit (and (= :note tg) (seq ids) (< (js/Math.abs (- (midi-of a) (:end gl))) 0.5))]
1350
+ (ctl! (:bar gl) (if hit
1351
+ (str "<gliss startid=\"#" (:id gl) "\" endid=\"#" (first ids) "\"/>")
1352
+ (gliss-dir staff gl)))
1353
+ (swap! open-gliss dissoc [staff @cur-layer])))
1354
+ (doseq [[m id] (map vector members (or ids []))]
1355
+ (when-let [[s sb] (get @open-ties (tie-key m))]
1356
+ (ctl! sb (str "<tie startid=\"#" s "\" endid=\"#" id "\"/>"))))
1357
+ ;; a tie only goes into the very next note of its staff
1358
+ (swap! open-ties (fn [o] (into {} (remove (fn [[[st ly _] _]] (and (= st staff) (= ly @cur-layer))) o)))))
1359
+ (when (and prev-ids ids)
1360
+ (doseq [[s e] (map vector prev-ids ids)]
1361
+ (ctl! b (str "<tie startid=\"#" s "\" endid=\"#" e "\"/>"))))
1362
+ (recur (rest ps) (+ pabs (* scale pb)) ids
1363
+ (conj acc {:t0 pabs :t1 (+ pabs (* scale pb)) :xml x
1364
+ :beam (and (not= :rest tg) (contains? #{"8" "16" "32" "64"} du))})))))]
1365
+ (recur (rest ks) (+ abs (* scale d)) (into items part-items)))
1366
+ :else (recur (rest ks) abs items))))))
1367
+ clefs (mapv (fn [k] (let [ps (for [vs sec-voices [kk v] vs :when (= (voice-staff kk) k)
1368
+ n (tree-seq node? kids v) :when (= :note (tag n))
1369
+ :let [m (midi-of (attrs n))] :when m] m)
1370
+ mean (if (seq ps) (/ (reduce + ps) (count ps)) 64)]
1371
+ (if (< mean 57) ["F" 4] ["G" 2])))
1372
+ staves)
1373
+ ;; every bar's staves first, then the measures with their control events: a tie into the next
1374
+ ;; bar is written in the bar where it starts, once that one is done
1375
+ staff-xmls (vec (for [i (range nbars)
1376
+ :let [{:keys [cells]} (nth bar-list i)]]
1377
+ (apply str
1378
+ (for [sk staves
1379
+ :let [staff (staff-of sk)]]
1380
+ (str "<staff n=\"" staff "\">"
1381
+ (apply str
1382
+ (for [[li k] (map-indexed vector (get layers-of sk))
1383
+ :let [m (get cells k)
1384
+ _ (reset! cur-layer (inc li))
1385
+ [xml _] (if m (layer (kids m) staff i (get @bar-start i) 1 (beam-spans i)) ["" 0])]
1386
+ ;; a second layer with nothing in this bar is not written
1387
+ :when (or (zero? li) (seq xml))]
1388
+ (str "<layer n=\"" (inc li) "\">"
1389
+ (if (seq xml) xml (str "<mRest xml:id=\"" (nid) "\"/>"))
1390
+ "</layer>")))
1391
+ "</staff>")))))
1392
+ ;; a bend at the very end goes nowhere: a text says it
1393
+ _ (doseq [[[st _] gl] @open-gliss] (ctl! (:bar gl) (gliss-dir st gl)))
1394
+ bars (vec (for [i (range nbars)
1395
+ :let [{:keys [label end]} (nth bar-list i)]]
1396
+ (do (when (seq label)
1397
+ (ctl! i (str "<dir staff=\"1\" tstamp=\"1\" place=\"above\"><rend fontweight=\"bold\">" (esc-xml label) "</rend></dir>")))
1398
+ (str "<measure n=\"" (inc i) "\"" (when end " right=\"dbl\"") ">"
1399
+ (nth staff-xmls i)
1400
+ (apply str (get @ctrl i))
1401
+ "</measure>"))))
1402
+ [_ q0] (meter-at 0)]
1403
+ {:mei (str "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
1404
+ "<mei xmlns=\"http://www.music-encoding.org/ns/mei\" meiversion=\"5.0\">"
1405
+ "<meiHead><fileDesc><titleStmt><title>Kairotic</title></titleStmt><pubStmt/></fileDesc></meiHead>"
1406
+ "<music><body><mdiv><score>"
1407
+ "<scoreDef meter.count=\"" (meter-count 0) "\" meter.unit=\"" q0 "\" key.sig=\"" (sp/mei-key-sig (:sig (key-at 0))) "\">"
1408
+ "<staffGrp" (when (> (count staves) 1) " bar.thru=\"false\"") ">"
1409
+ (apply str (for [[i [shape line]] (map-indexed vector clefs)
1410
+ :let [k (nth staves i)]]
1411
+ (str "<staffDef n=\"" (inc i) "\" lines=\"5\" clef.shape=\"" shape "\" clef.line=\"" line "\""
1412
+ (when (or (> (count staves) 1) (not (str/starts-with? k "voice "))) (str " label=\"" (esc-xml k) "\""))
1413
+ "/>")))
1414
+ "</staffGrp></scoreDef><section>"
1415
+ (apply str
1416
+ (map-indexed (fn [i x]
1417
+ ;; a change of meter or key is written before its bar
1418
+ (let [mc (and (pos? i) (not= (mg-at i) (mg-at (dec i))))
1419
+ kc (and (pos? i) (not= (:sig (key-at i)) (:sig (key-at (dec i)))))]
1420
+ (if (or mc kc)
1421
+ (let [[_ q] (meter-at i)]
1422
+ (str "<scoreDef" (when mc (str " meter.count=\"" (meter-count i) "\" meter.unit=\"" q "\""))
1423
+ (when kc (str " key.sig=\"" (sp/mei-key-sig (:sig (key-at i))) "\"")) "/>" x))
1424
+ x)))
1425
+ bars))
1426
+ "</section></score></mdiv></body></music></mei>")
1427
+ :pieces (vec (sort-by :t @pieces))}))
1428
+
1429
+ (defn ->score
1430
+ "MEI for a tree: measured when it has measures, an approximation on a sixteenth grid if not (kept for
1431
+ older code: kairotic.quantize/->score quantizes a tree without measures, and the page uses that one)."
1432
+ [tree pre]
1433
+ (if (measured? tree) (->mei tree pre) (sc/->mei-voice (->voice tree) pre)))
1434
+
1435
+ ;; ───────── playing: change points for a synth and parameters ─────────
1436
+
1437
+ (defn schedule
1438
+ "What a player sends, in seconds: [[sec [[outlet value] …]] …]. Outlet 0: the Hz of the notes sounding
1439
+ (a list), sent after outlet 1: their ids (one voice per note, for synth~); outlet 2: parameters
1440
+ [name value] (ramps in small steps); outlet 3: marks [:dyn \"mf\"] [:text \"…\"]."
1441
+ [tree]
1442
+ (let [k (/ 60 (tempo-of tree))
1443
+ es (events tree)
1444
+ ns (filter (fn [e] (= :note (:kind e))) es)
1445
+ nid (into {} (map-indexed (fn [i e] [e (keyword (str "n" (inc i)))]) ns))
1446
+ hz-at (fn [e t] (let [u (if (pos? (:dur e)) (/ (- t (:t e)) (:dur e)) 0)
1447
+ g (:gliss e)
1448
+ c (if (and g (>= (count g) 2))
1449
+ (let [[[x0 c0] [x1 c1]] (or (first (filter (fn [[[a] [b]]] (<= a u b)) (partition 2 1 g)))
1450
+ [(first g) (peek g)])]
1451
+ (if (= x0 x1) c1 (+ c0 (* (- c1 c0) (/ (- u x0) (- x1 x0))))))
1452
+ 0)]
1453
+ (cv/round-to (cv/cents->hz c (cv/midi->hz (:pitch e))) 3)))
1454
+ points (sort (distinct (concat (mapcat (fn [e] (concat [(:t e) (+ (:t e) (:dur e))]
1455
+ (when (:gliss e) (map (fn [[x]] (+ (:t e) (* x (:dur e)))) (:gliss e)))))
1456
+ ns)
1457
+ [0])))
1458
+ sound (for [t points
1459
+ :let [on (filter (fn [e] (and (<= (:t e) (+ t 1e-9)) (< (+ t 1e-9) (+ (:t e) (:dur e))))) ns)]]
1460
+ [(* k t) [[1 (mapv nid on)] [0 (mapv (fn [e] (hz-at e t)) on)]]])
1461
+ params (mapcat (fn [e]
1462
+ (let [nm (:name e) v0 (:value e) v1 (:to e) d (:dur e)]
1463
+ (if (and (number? v0) (number? v1) (pos? d))
1464
+ (for [i (range 21)] [(* k (+ (:t e) (* d (/ i 20)))) [[2 [nm (cv/round-to (+ v0 (* (- v1 v0) (/ i 20))) 4)]]]])
1465
+ [[(* k (:t e)) [[2 [nm v0]]]]])))
1466
+ (filter (fn [e] (= :param (:kind e))) es))
1467
+ marks (for [e es :when (#{:dyn :text} (:kind e))]
1468
+ [(* k (:t e)) [[3 [(:kind e) (or (:mark e) (:text e))]]]])]
1469
+ (->> (concat sound params marks)
1470
+ (group-by first)
1471
+ (sort-by key)
1472
+ (mapv (fn [[t xs]] [t (vec (mapcat second xs))])))))
1473
+
1474
+ ;; ───────── editing: operations on paths, and the difference between two trees ─────────
1475
+ ;; A path is the list of child indices from the root ([] is the root; attributes are not counted).
1476
+ ;; These operations are the events of a tree box's history (Study 20), so an edit is one node:
1477
+ ;; [:set path x] replaces the node (or string) at path
1478
+ ;; [:attrs path {…}] replaces its attributes
1479
+ ;; [:insert path x] inserts x so that it ends up at path
1480
+ ;; [:remove path] removes the node at path
1481
+
1482
+ (defn node-at "The node (or string) at path, or nil." [t path]
1483
+ (reduce (fn [n i] (when (and (node? n) (integer? i)) (get (kids n) i))) t path))
1484
+
1485
+ (defn- update-at [t path f]
1486
+ (if (empty? path)
1487
+ (f t)
1488
+ (let [i (first path) ks (kids t)]
1489
+ (if (and (node? t) (integer? i) (< -1 i (count ks)))
1490
+ (with-kids t (assoc ks i (update-at (get ks i) (rest path) f)))
1491
+ (throw (js/Error. (str "no node at " (pr-str path))))))))
1492
+
1493
+ (defn apply-op
1494
+ "The tree after one edit operation (or an error if its path does not exist)."
1495
+ [t [op path x]]
1496
+ (let [path (vec path)]
1497
+ (case op
1498
+ :set (update-at t path (constantly x))
1499
+ :attrs (update-at t path (fn [n] (if (node? n) (with-attrs n (or x {})) n)))
1500
+ :insert (do (when (empty? path) (throw (js/Error. "insert needs a parent")))
1501
+ (update-at t (pop path)
1502
+ (fn [n] (let [ks (kids n) i (max 0 (min (peek path) (count ks)))]
1503
+ (with-kids n (into (conj (subvec ks 0 i) x) (subvec ks i)))))))
1504
+ :remove (do (when (empty? path) (throw (js/Error. "the root cannot be removed")))
1505
+ (update-at t (pop path)
1506
+ (fn [n] (let [ks (kids n) i (peek path)]
1507
+ (if (< -1 i (count ks)) (with-kids n (into (subvec ks 0 i) (subvec ks (inc i)))) n)))))
1508
+ (throw (js/Error. (str "unknown edit " (pr-str op)))))))
1509
+
1510
+ (defn- lcs-pairs
1511
+ "Pairs [i j] of equal elements of a and b, in order (longest common subsequence)."
1512
+ [a b]
1513
+ (let [n (count a) m (count b)
1514
+ dp (make-array (* (inc n) (inc m)))
1515
+ at (fn [i j] (or (aget dp (+ (* i (inc m)) j)) 0))]
1516
+ (doseq [i (range (dec n) -1 -1) j (range (dec m) -1 -1)]
1517
+ (aset dp (+ (* i (inc m)) j)
1518
+ (if (= (nth a i) (nth b j)) (inc (at (inc i) (inc j))) (max (at (inc i) j) (at i (inc j))))))
1519
+ (loop [i 0 j 0 out []]
1520
+ (cond (or (>= i n) (>= j m)) out
1521
+ (= (nth a i) (nth b j)) (recur (inc i) (inc j) (conj out [i j]))
1522
+ (>= (at (inc i) j) (at i (inc j))) (recur (inc i) j out)
1523
+ :else (recur i (inc j) out)))))
1524
+
1525
+ (declare diff)
1526
+
1527
+ (defn- diff-kids [a b path]
1528
+ (let [anchors (lcs-pairs a b)
1529
+ bounds (concat [[-1 -1]] anchors [[(count a) (count b)]])
1530
+ segments (map (fn [[[i0 j0] [i1 j1]]] [(inc i0) i1 (inc j0) j1]) (partition 2 1 bounds))]
1531
+ ;; from right to left, so that the indices of what is still to do do not move
1532
+ (vec (mapcat (fn [[os oe ns ne]]
1533
+ (let [olds (subvec a os oe) news (subvec b ns ne) k (min (count olds) (count news))]
1534
+ (concat
1535
+ (for [i (range (dec (count olds)) (dec k) -1)] [:remove (conj path (+ os i))])
1536
+ (for [i (range k (count news))] [:insert (conj path (+ os i)) (nth news i)])
1537
+ (mapcat (fn [i] (diff (nth olds i) (nth news i) (conj path (+ os i)))) (range (dec k) -1 -1)))))
1538
+ (reverse segments)))))
1539
+
1540
+ (defn diff
1541
+ "The edit operations that turn tree a into tree b, node by node (as few as it reasonably can)."
1542
+ ([a b] (diff a b []))
1543
+ ([a b path]
1544
+ (cond
1545
+ (= a b) []
1546
+ (and (node? a) (node? b) (= (tag a) (tag b)))
1547
+ (vec (concat (diff-kids (kids a) (kids b) path)
1548
+ (when (not= (attrs a) (attrs b)) [[:attrs path (attrs b)]])))
1549
+ :else [[:set path b]])))
1550
+
1551
+ (defn ops-summary "A short description of an edit, for the history and the REPL." [[op path x]]
1552
+ (str (name op) " " (pr-str path)
1553
+ (case op
1554
+ (:set :insert) (str " " (let [t (pr-str x)] (if (> (count t) 60) (str (subs t 0 57) "…") t)))
1555
+ :attrs (str " " (pr-str x))
1556
+ "")))
1557
+
1558
+ ;; ───────── metric weight in a tree ─────────
1559
+
1560
+ (defn- leaf-onsets
1561
+ "[[path onset] …] of the notes and chords of a measure (onsets in beats from its start)."
1562
+ [m]
1563
+ (let [acc (transient [])]
1564
+ (place m 0 1 {:path [] :voice nil} acc)
1565
+ (->> (persistent! acc)
1566
+ (filter (fn [e] (= :note (:kind e))))
1567
+ (map (fn [e] (let [p (:path e)] [(if (= :chord (tag (node-at m (pop p)))) (pop p) p) (:t e)])))
1568
+ distinct
1569
+ vec)))
1570
+
1571
+ (defn- thin-measure [amount m]
1572
+ (let [ls (leaf-onsets m)
1573
+ n (count ls)
1574
+ k (if (< amount 1) (js/Math.round (* amount n)) (min n (js/Math.round amount)))
1575
+ {[_ q] :meter :as mtr} (meter-of (attrs m))
1576
+ unit (/ 4 q)
1577
+ ;; the coarsest pulse (the unit, halved up to six times) that holds every onset: Barlow ranks there
1578
+ pulse (first (filter (fn [pb] (every? (fn [[_ t]] (let [x (/ t pb)] (< (js/Math.abs (- x (js/Math.round x))) 1e-6))) ls))
1579
+ (map (fn [e] (/ unit (js/Math.pow 2 e))) (range 7))))
1580
+ ranks (when pulse (indispensability mtr pulse))
1581
+ weight (fn [[_ t]] [(meter-level mtr t)
1582
+ (- (if ranks (nth ranks (js/Math.round (/ t pulse)) -1) -1))
1583
+ t])
1584
+ kept (set (map first (take k (sort-by weight ls))))]
1585
+ (reduce (fn [mm [path _]]
1586
+ (if (kept path)
1587
+ mm
1588
+ (apply-op mm [:set path [:rest {:dur (:dur (attrs (node-at mm path)))}]])))
1589
+ m ls)))
1590
+
1591
+ (defn thin
1592
+ "Keeps, in every measure, the notes on its strongest positions (metric level, then Barlow's
1593
+ indispensability) and turns the others into rests: amount is a share of the notes (0.5) or how many
1594
+ (3). Without measures, the whole tree is weighed as one bar of quarters."
1595
+ [amount tree]
1596
+ (let [t (with-meters (explicit (expand tree)))
1597
+ measured (some (fn [x] (and (node? x) (= :measure (tag x)))) (tree-seq node? kids t))]
1598
+ (letfn [(go [n]
1599
+ (cond (not (node? n)) n
1600
+ (= :measure (tag n)) (thin-measure amount n)
1601
+ :else (with-kids n (mapv go (kids n)))))]
1602
+ (if measured
1603
+ (go t)
1604
+ (first (kids (thin-measure amount [:measure {:meter [(max 1 (js/Math.ceil (duration t))) 4]} t])))))))