@kairotic/app 0.2.2 → 0.2.3

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.
@@ -0,0 +1,150 @@
1
+ // SPDX-License-Identifier: MPL-2.0
2
+ // @kairotic/theory · soft.mjs: how every engine of Kairotic weighs its decisions.
3
+ //
4
+ // The hard rules (a kernel's check) decide what may be; these soft rules decide what is likely. A candidate costs
5
+ // something by the shape of its own line (melodicParts) and by the vertical it makes with another voice
6
+ // (verticalParts), each rule by its id and weight; an engine chooses among the candidates with a future by a softmax
7
+ // of −cost / temperature (choose, pick), colder where few futures are left (temperature). The comes box
8
+ // (counterpoint.mjs), the studies' engines (Studies 38–53) and the agents Claude builds weigh with this one module,
9
+ // so the same weights mean the same music everywhere, and changing a weight changes it for all of them.
10
+ //
11
+ // A pitch is a step of a scale (a degree, or a step of a system of N steps), as the kernels count them; a line is one
12
+ // pitch a unit, a note held being the same pitch again.
13
+
14
+ /** The soft rules, as Study 42 lists them (the melodic contour after Bach, #181; the vertical ones). */
15
+ export const SOFT = [
16
+ { id: "leap-size", scope: "melodic", weight: 1, doc: "Leaps cost little, only by their size (a 3rd 0.2, a 4th 0.4, a 5th 0.5, a 6th or an octave 0.8)." },
17
+ { id: "tie", scope: "melodic", weight: 1.5, doc: "A note held over the beat (a tie): the same pitch again is held, not struck again." },
18
+ { id: "contrary-after-leap", scope: "melodic", weight: 1.2, doc: "After a leap, going on the same way (twice as much leaping again): a leap is compensated by contrary motion." },
19
+ { id: "step-back", scope: "melodic", weight: 1.2, doc: "After a 4th or more, turning back by leap rather than by step (filling the gap)." },
20
+ { id: "leap-after-leap", scope: "melodic", weight: 0.6, doc: "Two leaps in a row." },
21
+ { id: "return", scope: "melodic", weight: 1, doc: "Going straight back to the note before (A B A)." },
22
+ { id: "hover", scope: "melodic", weight: 0.6, doc: "A note heard among the last ones, each time: the line moves on." },
23
+ { id: "run", scope: "melodic", weight: 1.5, doc: "More than four moves the same way." },
24
+ { id: "open", scope: "melodic", weight: 1, doc: "Still inside less than a 5th after six notes: the line opens up." },
25
+ { id: "climax", scope: "melodic", weight: 1.5, doc: "Reaching the highest note again (one climax)." },
26
+ { id: "sequence", scope: "melodic", weight: 1.5, doc: "The last two moves again (two thirds of it for the last three): a mechanical sequence." },
27
+ { id: "memory", scope: "memory", weight: 1, doc: "Memory of the work: a figure of two moves it used earlier (not just before) costs less." },
28
+ { id: "novelty", scope: "memory", weight: 0.3, doc: "Novelty: the same move as the last one costs a little more." },
29
+ { id: "motion", scope: "vertical", weight: 2.5, doc: "Contrary motion preferred: oblique costs half, similar 0.8 of the weight." },
30
+ { id: "direct-perfect", scope: "vertical", weight: 3, doc: "Similar motion into a 5th (into an octave or a unison it is not allowed)." },
31
+ { id: "imperfect-run", scope: "vertical", weight: 2, doc: "More than three parallel 3rds or 6ths in a row." },
32
+ { id: "passing", scope: "vertical", weight: 1, doc: "A dissonance passing on a weak beat: the life of second species (it costs less)." },
33
+ { id: "suspension-life", scope: "vertical", weight: 1.5, doc: "A suspension: the life of fourth species (it costs less)." },
34
+ { id: "alternation", scope: "vertical", weight: 1.5, doc: "The same vertical as two notes before but not as the last (3 6 3 6 …)." },
35
+ { id: "modal", scope: "mode", weight: 1, doc: "The mode's final and tenor cost less (more on a strong beat): the dux of the comes box keeps to its mode." },
36
+ { id: "imitation", scope: "imitation", weight: 1, doc: "How far the comes strays from imitating the dux, by the degree of imitation asked (the comes box)." },
37
+ ];
38
+ export const defaultWeights = () => Object.fromEntries(SOFT.map((r) => [r.id, r.weight]));
39
+
40
+ const LEAP_COST = { 0: 0, 1: 0, 2: 0.2, 3: 0.4, 4: 0.5, 5: 0.8, 7: 0.8 };
41
+ const sign = (x) => (x > 0) - (x < 0);
42
+ const dedupe = (line) => line.filter((x, i) => i === 0 || x !== line[i - 1]);
43
+ const lastMove = (l) => (l.length >= 2 ? l[l.length - 1] - l[l.length - 2] : null);
44
+ /** A candidate's whole cost: the sum of its parts. */
45
+ export const total = (parts) => Object.values(parts).reduce((a, b) => a + b, 0);
46
+
47
+ /** The soft cost of x after a line, by rule (the line's own shape), as canon.cljs's melodic-parts. */
48
+ export function melodicParts(line, x, W = defaultWeights()) {
49
+ const parts = {}, w = (id) => W[id] ?? 0;
50
+ const prev = line.length ? line[line.length - 1] : null;
51
+ if (prev === null || prev === undefined) return parts;
52
+ if (x === prev) { parts.tie = w("tie"); return clean(parts); }
53
+ // the rest on the notes struck: a note held is one note
54
+ const L = dedupe(line), m = lastMove(L), s = x - prev, n = Math.abs(s), all = [...L, x], tl = L.length;
55
+ const mv = []; for (let i = 1; i < L.length; i++) mv.push(L[i] - L[i - 1]); mv.push(s);
56
+ const M = mv.length;
57
+ if (n > 0) parts["leap-size"] = w("leap-size") * (LEAP_COST[n] ?? 1.5);
58
+ if (tl >= 2 && n > 0 && x === L[tl - 2]) parts.return = w("return");
59
+ const k = L.slice(0, -1).slice(-3).filter((y) => y === x).length;
60
+ if (k > 0) parts.hover = k * w("hover");
61
+ if (m !== null && Math.abs(m) >= 2 && n > 0 && sign(m) === sign(s)) parts["contrary-after-leap"] = w("contrary-after-leap") * (n >= 2 ? 2 : 1);
62
+ if (m !== null && Math.abs(m) >= 3 && n > 1) parts["step-back"] = w("step-back");
63
+ if (m !== null && Math.abs(m) >= 2 && n >= 2) parts["leap-after-leap"] = w("leap-after-leap");
64
+ if (n > 0) { let run = 0; for (let i = M - 1; i >= 0 && mv[i] !== 0 && sign(mv[i]) === sign(s); i--) run++; if (run > 4) parts.run = w("run"); }
65
+ if (tl >= 5 && Math.max(...all) - Math.min(...all) < 4) parts.open = w("open");
66
+ if (tl > 1 && s > 0 && x === Math.max(...L)) parts.climax = w("climax");
67
+ const eq = (a, b) => a.length === b.length && a.every((v, i) => v === b[i]);
68
+ if (M >= 4 && mv[M - 1] === mv[M - 3] && mv[M - 2] === mv[M - 4] && mv[M - 1] !== mv[M - 2]) parts.sequence = w("sequence");
69
+ else if (M >= 6 && eq(mv.slice(M - 3), mv.slice(M - 6, M - 3))) parts.sequence = (2 / 3) * w("sequence");
70
+ else if (m !== null && n > 0) { for (let i = 0; i < M - 3; i++) if (mv[i] === m && mv[i + 1] === s) { parts.memory = -w("memory"); break; } }
71
+ if (m !== null && m === s && n > 0) parts.novelty = w("novelty");
72
+ return clean(parts);
73
+ }
74
+
75
+ /**
76
+ * The soft cost of the vertical (x, c) at the next time, as canon.cljs's vertical-parts. D and C are the two lines
77
+ * so far (pitches a unit, null before a voice enters). ctx: {quality(lo, hi), N (steps a period), lowerFirst(x, c),
78
+ * strong(t), dissonant(x, c), suspension (whether the vertical at t is a suspension), fifth (optional: the class of the
79
+ * system's fifth, for a system whose perfect intervals are more than the octave and the fifth)}.
80
+ */
81
+ export function verticalParts(D, C, x, c, ctx, W = defaultWeights()) {
82
+ const parts = {}, w = (id) => W[id] ?? 0, t = D.length, N = ctx.N;
83
+ const prev = t ? D[t - 1] : null, pc = t ? C[t - 1] : null;
84
+ const mod = (a) => ((a % N) + N) % N;
85
+ if (c === null || c === undefined || pc === null || pc === undefined || prev === null || prev === undefined) return parts;
86
+ const dx = x - prev, dc = c - pc, [lo, hi] = ctx.lowerFirst(x, c);
87
+ const motion = dx === 0 && dc === 0 ? "none" : dx === 0 || dc === 0 ? "oblique" : sign(dx) === sign(dc) ? "similar" : "contrary";
88
+ if (motion === "oblique") parts.motion = 0.5 * w("motion");
89
+ if (motion === "similar") parts.motion = 0.8 * w("motion");
90
+ if (motion === "similar" && ctx.quality(lo, hi) === "perfect" && mod(hi - lo) !== 0 && (ctx.fifth === undefined || mod(hi - lo) === ctx.fifth)) parts["direct-perfect"] = w("direct-perfect");
91
+ if (motion === "similar" && ctx.quality(lo, hi) === "imperfect") {
92
+ const cls = mod(hi - lo);
93
+ let run = 1;
94
+ for (let i = t - 1; i >= 1; i--) {
95
+ const a = D[i], b = C[i], a0 = D[i - 1], b0 = C[i - 1];
96
+ if ([a, b, a0, b0].some((v) => v === null || v === undefined)) break;
97
+ const [l, h] = ctx.lowerFirst(a, b);
98
+ if (ctx.quality(l, h) === "imperfect" && mod(h - l) === cls && sign(a - a0) === sign(b - b0) && a !== a0) run++; else break;
99
+ }
100
+ if (run > 3) parts["imperfect-run"] = w("imperfect-run");
101
+ }
102
+ if (!ctx.strong(t) && ctx.dissonant(x, c)) parts.passing = -w("passing");
103
+ if (ctx.suspension) parts["suspension-life"] = -w("suspension-life");
104
+ if (t >= 2) {
105
+ const cl = (a, b) => (a === null || a === undefined || b === null || b === undefined ? null : mod(Math.abs(a - b)));
106
+ const iv = cl(x, c), i1 = cl(D[t - 1], C[t - 1]), i2 = cl(D[t - 2], C[t - 2]);
107
+ if (i1 !== null && i2 !== null && iv === i2 && iv !== i1) parts.alternation = w("alternation");
108
+ }
109
+ return clean(parts);
110
+ }
111
+
112
+ function clean(parts) { for (const k of Object.keys(parts)) if (parts[k] === 0) delete parts[k]; return parts; }
113
+
114
+ /** The temperature, colder where few futures are left when it follows the divergence (as canon.cljs). */
115
+ export function temperature(temp, follow, futures) {
116
+ const f = typeof futures === "bigint" ? Number(futures) : futures;
117
+ const bits = f > 0 ? Math.log2(f) : -1;
118
+ return follow ? temp * Math.min(1, Math.max(0, bits) / 8) : temp;
119
+ }
120
+
121
+ /** The engine's choice among candidates {futures, cost}: a softmax of −cost / temperature (r in [0, 1)); at
122
+ * temperature 0 the cheapest. Only candidates with a future are chosen. */
123
+ export function choose(cands, temp, r = Math.random) {
124
+ const ok = cands.filter((c) => c.futures > 0);
125
+ if (!ok.length) return null;
126
+ if (temp <= 0.001) return ok.slice().sort((a, b) => a.cost - b.cost || a.note - b.note)[0];
127
+ const m = Math.min(...ok.map((c) => c.cost)), ws = ok.map((c) => Math.exp((m - c.cost) / temp));
128
+ let x = r() * ws.reduce((a, b) => a + b, 0);
129
+ for (let j = 0; j < ok.length; j++) { x -= ws[j]; if (x < 0) return ok[j]; }
130
+ return ok[ok.length - 1];
131
+ }
132
+
133
+ /** A choice among candidates by a cost function (the comes box's): at temperature 0, or without a random number r in
134
+ * [0, 1), the cheapest; above it a softmax of −cost / temperature drawn with r. Unlike choose, it does not ask for
135
+ * futures (the candidates are already those with one). */
136
+ export function pick(cands, cost, temp, r) {
137
+ const cs = cands.slice().sort((p, q) => cost(p) - cost(q) || (p.note ?? -100) - (q.note ?? -100));
138
+ if (!cs.length || !(temp > 0.001) || r === undefined || r === null) return cs[0] || null;
139
+ const m = cost(cs[0]), ws = cs.map((c) => Math.exp((m - cost(c)) / temp)), x = r * ws.reduce((a, v) => a + v, 0);
140
+ let acc = 0;
141
+ for (let j = 0; j < cs.length; j++) { acc += ws[j]; if (x < acc) return cs[j]; }
142
+ return cs[cs.length - 1];
143
+ }
144
+
145
+ /** How a line moves, for the pages and the tests: the share of steps, 3rds and larger leaps among its moves. */
146
+ export function shape(lines) {
147
+ let st = 0, th = 0, lp = 0, tot = 0;
148
+ for (const l of lines) { const L = dedupe(l); for (let i = 1; i < L.length; i++) { const n = Math.abs(L[i] - L[i - 1]); tot++; if (n === 1) st++; else if (n === 2) th++; else lp++; } }
149
+ return tot ? { steps: st / tot, thirds: th / tot, leaps: lp / tot, moves: tot } : { steps: 0, thirds: 0, leaps: 0, moves: 0 };
150
+ }
@@ -1,28 +1,16 @@
1
1
  // Generated by packages/build.mjs
2
2
  export default {
3
3
  "package": "@kairotic/theory",
4
- "version": "0.11.0",
4
+ "version": "0.13.0",
5
5
  "api": 1,
6
6
  "author": "bonuoq",
7
7
  "license": "MPL-2.0",
8
8
  "components": [
9
- {
10
- "class": "cancrizans",
11
- "license": "MPL-2.0",
12
- "doc": "A crab canon written from both ends to the middle (Study 43): the comes is the dux backwards, both voices at once; with table, backwards and upside down about an axis ([:axis 62], a MIDI note; the final by default) — the one score read by a second player from across the table, a musical ambigram. It cannot be written from the beginning (the comes at the start is the dux at the end), so it is written by turns from both ends: each step a note at the start, then one at the end. A note that breaks a rule of the style (as comes's), or from which the work could not be closed, is corrected to the nearest one that can. On the right, the futuribles — the notes that can come next and the ways each leaves to close the work in the middle, counted exactly — and where the work is. When it closes, the dux and the comes go out (left) as patterns, {:note [...] :dur [...]} with the notes held joined, for a pbind and a player, and both as a musical tree (outlet 4), for a tree box, which shows it as a score. Notes as comes takes them: Hz, a list of keys held, [:midi 62], an event (:freq, or a player's :hz), or MIDI numbers with midi. :engine writes the next note itself; :back takes one back; :reset starts again. The system (Study 42) is comes's: diatonic by default, or meantone, septimal31 or pentatonic ([:system :septimal31]), and the mode one of its modes; the box's words name them in any order (cancrizans hypodorian, cancrizans pentatonic penta-A), or an EDN map; its modes, distances and tuning come with it. [:k -4], [:mode :hypodorian], [:system :pentatonic], [:bars 5], [:table true], [:axis 62] change the canon (and start again). With live (Study 46) the crab is played beat by beat: in the first half you play your note (or the nearest that can close the crab) and the box answers at the same beat with the end of your own line, written ahead (the notes that leave more futures first) — its futuribles say beforehand, as :end, what it will answer to each note (at temp 0, the default, exactly that; above it, the most likely, the box drawing among the answers with its seed: the same seed, the same game); two beats before the middle a cue {:cue :middle :in 2}; at the middle the rest of your line goes out (as a tree on outlet 4, for a tree box; at the end the whole crab) as the score to read — the box's answers so far, backwards, the first the last end of your line it wrote (with an odd number of beats the middle note is shared) —, and in the second half the box plays your first half backwards while you read it. Live, it sounds as a keyboard or a player does: the Hz of both voices — yours as played, corrected or read, and the box's — on the left, after their voice ids on the second outlet, for one synth~ (0→0, 1→1); a note held keeps its id — a note that is not the one written is said, as a deviation. On a pulse (the right inlet: a metro, a pulse) a beat goes on whether you played or not; without one, a note in is a beat. After the last beat, a note begins a new crab.",
13
- "source": ";; cancrizans · a crab canon written from both ends to the middle (discussions #172 and #192, Study 43)\n;; Part of @kairotic/theory. Written against the Kairotic API (api/…).\n;; The comes is the dux backwards, both voices at once (a crab); with table, backwards and upside down — the one\n;; score read by a second player from across the table, a musical ambigram. Such a canon cannot be written from\n;; the beginning: the comes at the start is the dux at the end. It is written from both ends to the middle, by\n;; turns: each step a note at the start, then one at the end, and the futuribles are the ways to close the work in\n;; the middle, counted exactly (mirror.mjs beside this component: Study 43's kernel, on counterpoint.mjs). A note\n;; that breaks a rule, or from which the work could not be closed, is corrected to the nearest one that can. When\n;; the work is closed, both voices go out as patterns, for a pbind and a player.\n;; With live (Study 46) the crab is played, beat by beat: in the first half you play your note and the box answers at\n;; the same beat with the end of your own line (written ahead, among the notes with a future, the ones that leave\n;; more of them first); a cue comes two beats before the middle; at the middle the rest of your line comes out as a\n;; score to read, and in the second half the box plays your first half backwards while you read it (a note you play\n;; that is not the one written is said, as a deviation). On a pulse (the right inlet) a beat goes on whether you\n;; played or not (the box plays your note for you); without one, a note in is a beat.\n(let [origins-cp [\"npm:@kairotic/theory@0.11.0/dist/counterpoint.mjs\" \"kairotic/packages/theory/counterpoint.mjs\"]\n origins-mi [\"npm:@kairotic/theory@0.11.0/dist/mirror.mjs\" \"kairotic/packages/theory/mirror.mjs\"]\n semis-of-hz (fn [f] (* 12 (/ (js/Math.log (/ f 261.6255653005986)) (js/Math.log 2))))\n ev-hz (fn [e] (let [h (or (:freq e) (:hz e))] (if (sequential? h) (first h) h)))\n log2 (fn [x] (/ (js/Math.log x) (js/Math.log 2)))\n params #{:mode :system :k :beats :bars :table :axis}\n ;; a key asked for is the note of the system it is nearest (within a quarter of a tone or so): not a correction\n off? (fn [asked x] (> (js/Math.abs (- asked x)) 0.45))\n ;; (chance: the temperature and the seed change the game, not the canon)\n chance #{:temp :seed}\n ;; (the box's words, then what was changed since: a mode or a system as a name, or a system as data)\n opts-of (fn [st args]\n (-> (merge {:mode (:mode args) :system (:system args) :k (:k args) :beats (:beats args) :bars (:bars args)\n :table (boolean (:table args)) :axis nil}\n (:over st))\n (update :mode #(some-> % name))\n ;; a system: a name (:pentatonic) or the data itself (an EDN map, Study 42)\n (update :system #(if (keyword? %) (name %) %))))\n fresh (fn [args] {:sig args :M [] :s 0 :pending nil :hist [] :k 0 :temp (:temp args) :seed (:seed args) :seed0 (:seed args)})\n load (fn [st o]\n (let [k (inc (:k st 0))]\n {:state (assoc st :k k :loading true :mi nil)\n :show {:main \"cancrizans\" :sub \"counting the futures…\"}\n :effects [[:kernel {:k k :opts o}]]}))\n ;; the dux as the kernel reads it: an array with holes where nothing is written yet\n js-M (fn [st n] (let [a (js/Array. n)] (doseq [[i v] (map-indexed vector (:M st))] (when (some? v) (aset a i v))) a))\n pos-of (fn [mi s] (when (< s (.-steps mi)) (vec (aget (.-order mi) s))))\n ;; the candidates for the next note: at the start of the step, or at its end once the start is chosen\n cands (fn [mi st]\n (let [s (:s st) M (js-M st (.-n mi))]\n (if (some? (:pending st)) (.fanSecond mi M s (:pending st)) (.fan mi M s))))\n futs (fn [cp mi st]\n (vec (for [c (cands mi st) :when (pos? (or (.-futures c) 0))]\n {:midi (.midi cp (.-note c)) :name (.name cp (.-note c)) :futures (.-futures c)})))\n ;; a voice as a pattern: the notes held over the beat joined\n pattern (fn [cp xs]\n (let [runs (partition-by identity xs)]\n {:note (mapv (fn [r] (.midi cp (first r))) runs) :dur (mapv count runs)}))\n report (fn [cp mi st extra]\n (let [n (.-n mi) lns (.lines mi (js-M st n)) s (:s st) steps (.-steps mi) pos (pos-of mi s)\n mid (fn [v] (when (and (some? v) (not (undefined? v))) (.midi cp v)))]\n (merge {:step s :steps steps :closed (>= s steps) :system (.-systemName cp) :mode (.-mode cp)\n :writing (cond (>= s steps) :closed (some? (:pending st)) :end :else :start)\n :beat (when pos (inc (if (some? (:pending st)) (peek pos) (first pos))))\n :futures (.count mi (js-M st n) s)\n :dux (mapv mid (array-seq (.-D lns))) :comes (mapv mid (array-seq (.-C lns)))}\n extra)))\n shown (fn [cp mi st]\n (let [steps (.-steps mi) s (:s st)]\n {:main (str (if (.-inverted mi) \"table · \" \"crab · \") (count (remove nil? (:M st))) \"/\" (.-n mi) \" notes\")\n :sub (cond (and (zero? s) (nil? (:pending st)) (.-modeNote cp)) (.-modeNote cp)\n (>= s steps) \"closed: the work is written\"\n (some? (:pending st)) (str \"now the note at the end · \" (.count mi (js-M st (.-n mi)) s) \" ways\")\n :else (str \"step \" (inc s) \"/\" steps \": the note at the start\"))}))\n ;; a line as a musical tree, for a score (a tree box): a measure of b beats, a beat a half note\n ;; (:dur 2), a note held over the beat tied, the last note to the end of its bar; from the bar of beat\n ;; `from`, and the beats before `upto` as rests (what is already played)\n voice-of (fn [cp xs b from upto]\n (let [n (count xs) x (fn [i] (let [v (get xs i)] (when (and (some? v) (not (undefined? v))) v)))\n beat (fn [i]\n (let [v (x i) dur (if (= i (dec n)) (* 2 (- b (mod i b))) 2)]\n (if (or (< i upto) (nil? v))\n [:rest {:dur dur}]\n [:note (cond-> {:pitch (/ (js/Math.round (* 1000 (.midi cp v))) 1000) :dur dur}\n (and (< (inc i) n) (>= (inc i) upto) (= v (x (inc i)))) (assoc :tie true))])))]\n (into [:voice]\n (for [bar (partition-by #(quot % b) (range (* b (quot from b)) n))]\n (into [:measure {:meter [b 2]}] (map beat bar))))))\n ;; the whole work, both voices, as a tree\n piece-of (fn [cp mi M]\n (let [b (or (.. mi -spec -b) 1) lns (.lines mi M)]\n [:piece (voice-of cp (vec (array-seq (.-D lns))) b 0 0) (voice-of cp (vec (array-seq (.-C lns))) b 0 0)]))\n at-point (fn [cp mi st extra]\n (let [closed (>= (:s st) (.-steps mi)) n (.-n mi) lns (.lines mi (js-M st n))]\n {:state st :show (shown cp mi st)\n :out (cond-> []\n closed (conj [4 (piece-of cp mi (js-M st n))])\n true (conj [3 (report cp mi st extra)] [2 (futs cp mi st)])\n closed (conj [1 (pattern cp (array-seq (.-C lns)))] [0 (pattern cp (array-seq (.-D lns)))]))}))\n ;; a pitch asked for (semitones above C4): the nearest candidate with a future; between two as near, the\n ;; one with more futures\n nearest (fn [cp cs asked]\n (let [ok (filter #(pos? (or (.-futures %) 0)) cs)]\n (when (seq ok)\n (first (sort-by (juxt #(js/Math.abs (- (.semis cp (.-note %)) asked)) #(- (.-futures %))) ok)))))\n write (fn [mi st vals]\n (let [pos (pos-of mi (:s st)) n (.-n mi)\n M (vec (concat (:M st) (repeat (max 0 (- n (count (:M st)))) nil)))]\n (assoc st :M (reduce (fn [M [p v]] (assoc M p v)) M (map vector pos vals))\n :s (inc (:s st)) :pending nil :hist (conj (:hist st) (select-keys st [:M :s :pending])))))\n choose (fn [cp mi st asked]\n (let [pos (pos-of mi (:s st))]\n (if-not pos\n {:state st}\n (let [c (nearest cp (cands mi st) asked)\n r (js/Math.round asked)\n extra (when c {:asked (+ 60 r) :played (.midi cp (.-note c)) :corrected (off? asked (.semis cp (.-note c)))})]\n (cond\n (nil? c) {:state st}\n (and (= 2 (count pos)) (nil? (:pending st))) (at-point cp mi (assoc st :pending (.-note c)) extra)\n (= 2 (count pos)) (at-point cp mi (write mi st [(:pending st) (.-note c)]) extra)\n :else (at-point cp mi (write mi st [(.-note c)]) extra))))))\n ;; the engine: the candidate nearest the note beside it (a step), more futures between two as near\n engine (fn [cp mi st]\n (let [pos (pos-of mi (:s st)) M (:M st)]\n (when pos\n (let [second? (some? (:pending st))\n nb (if second? (get M (inc (peek pos))) (get M (dec (first pos))))\n cs (filter #(pos? (or (.-futures %) 0)) (cands mi st))]\n (when (seq cs)\n (let [c (first (sort-by (juxt #(if nb (js/Math.abs (- (js/Math.abs (- (.-note %) nb)) 1)) 0) #(- (.-futures %))) cs))]\n (.semis cp (.-note c))))))))\n ;; ── live (Study 46): the crab played beat by beat ──\n leap-cost (fn [a b] (if (or (nil? a) (nil? b)) 0 (get {0 1.5 1 0 2 0.3 3 0.6 4 0.7 5 1 7 1} (js/Math.abs (- b a)) 2)))\n ;; a random number of the box's own (Park–Miller), kept in its state: a game can be played again\n rnd (fn [st] (let [x (mod (* (max 1 (:seed st 1)) 16807) 2147483647)] [(assoc st :seed x) (/ (dec x) 2147483646)]))\n;; a choice among candidates by their cost: at temperature 0 the cheapest (no chance in it), above it a softmax of\n ;; -cost/temperature drawn with the box's own random numbers (its seed: the same game again with the same seed)\n choose-by (fn [st cs cost temp]\n (let [cs (vec (sort-by (juxt cost #(.-note %)) cs))]\n (cond (empty? cs) [st nil]\n (<= (or temp 0) 0.001) [st (first cs)]\n :else (let [m (cost (first cs)) ws (mapv #(js/Math.exp (/ (- m (cost %)) temp)) cs)\n [st r] (rnd st) x (* r (reduce + ws))]\n [st (loop [j 0 acc 0] (let [acc (+ acc (nth ws j))]\n (if (or (< x acc) (= j (dec (count cs)))) (nth cs j) (recur (inc j) acc))))]))))\n ;; the end of your line, chosen by the box for your note a: a step from the note after it, the more futures\n ;; the better; :end in the futuribles is the cheapest (at temperature 0 the one the box will answer)\n end-cands (fn [mi st a]\n (let [s (:t st 0) n (.-n mi) q (- n 1 s)\n cs (filter #(pos? (or (.-futures %) 0)) (.fanSecond mi (js-M st n) s a))]\n [cs (fn [c] (- (leap-cost (.-note c) (get (:M st) (inc q))) (* 0.2 (log2 (.-futures c)))))]))\n end-for (fn [mi st a] (let [[cs cost] (end-cands mi st a)] (some-> (second (choose-by st cs cost 0)) .-note)))\n pick-end (fn [mi st a] (let [[cs cost] (end-cands mi st a) [st c] (choose-by st cs cost (:temp st 0))] (when c [st (.-note c)])))\n live-phase (fn [mi st] (let [t (:t st 0)] (cond (< t (.-steps mi)) :choose (< t (.-n mi)) :read :else :done)))\n engine-note (fn [mi st t] (let [e (get (:M st) (.source mi t))] (when (some? e) (.T mi e))))\n hz-of (fn [cp v] (* 440 (js/Math.pow 2 (/ (- (.midi cp v) 69) 12))))\n ;; what sounds at beat t, live: your note (as played, corrected or read) and the box's, as a keyboard or a\n ;; player sends them — their Hz (outlet 0) after their voice ids (outlet 1), for one synth~. A voice's id is\n ;; the beat where its note was struck: a note held over the beat keeps it and goes on sounding.\n sounding (fn [cp mi st t]\n (let [start (fn [xs] (loop [i (dec (count xs))] (if (and (pos? i) (= (nth xs i) (nth xs (dec i)))) (recur (dec i)) i)))\n you (subvec (:M st) 0 (inc t))\n box (mapv #(engine-note mi st %) (range (inc t)))\n vs (cond-> []\n (some? (peek you)) (conj [(keyword (str \"y\" (start you))) (hz-of cp (peek you))])\n (some? (peek box)) (conj [(keyword (str \"e\" (start box))) (hz-of cp (peek box))]))]\n [[1 (mapv first vs)] [0 (mapv second vs)]]))\n live-out (fn [cp mi st b]\n (let [ph (live-phase mi st) t (:t st 0) n (.-n mi) steps (.-steps mi)\n mid (fn [v] (when (some? v) (.midi cp v)))\n next-opts (case ph\n :choose (let [two? (= 2 (count (pos-of mi t)))]\n (vec (for [c (.fan mi (js-M st n) t) :when (pos? (or (.-futures c) 0))]\n (cond-> {:midi (.midi cp (.-note c)) :name (.name cp (.-note c)) :futures (.-futures c)}\n ;; what the box will answer at the end of your line if you play it\n two? (assoc :end (some->> (end-for mi st (.-note c)) (.midi cp)))))))\n :read [{:midi (mid (get (:M st) t)) :name (.name cp (get (:M st) t)) :futures 1}]\n [])]\n {:state st\n :show {:main (str (if (.-inverted mi) \"table\" \"crab\") \" live · beat \" (min n t) \"/\" n)\n :sub (case ph :choose (str \"play: \" (count next-opts) \" notes can close it\")\n :read (str \"read: \" (.name cp (get (:M st) t)))\n \"done: the crab is played\")}\n :out (cond-> [(case ph\n ;; the score (for a tree box): at the middle what is left of your line to read, the\n ;; beats of its bar already played as rests; at the end the whole crab, both voices.\n ;; Twice a crab, not every beat: each tree written into a tree box is an event of\n ;; the work's history\n :read (when (= t steps) [4 (voice-of cp (:M st) (.. mi -spec -b) t t)])\n :done [4 (piece-of cp mi (js-M st n))]\n nil)\n [3 (merge {:t (:t b) :phase ph :you (mid (:you b)) :engine (mid (:engine b)) :n n :middle steps :system (.-systemName cp) :mode (.-mode cp)\n :ways (if (= ph :choose) (.count mi (js-M st n) t) 1)}\n (select-keys b [:played :corrected :auto :deviation :expected])\n (when (= t (- steps 2)) {:cue :middle :in 2}))]\n [2 next-opts]]\n true (#(vec (remove nil? %)))\n (some? (:t b)) (into (if (some? (:you b)) (sounding cp mi st (:t b)) [])))}))\n ;; a beat: what you played (asked, or nil: on a pulse the box plays for you), and what the box answers\n live-beat (fn [cp mi st asked]\n (let [n (.-n mi) t (:t st 0) ph (live-phase mi st)]\n (case ph\n :choose\n (let [cs (filter #(pos? (or (.-futures %) 0)) (.fan mi (js-M st n) t))\n [st c] (if (some? asked)\n [st (first (sort-by (juxt #(js/Math.abs (- (.semis cp (.-note %)) asked)) #(- (.-futures %))) cs))]\n ;; nothing played on the pulse: the box plays your note, by the same taste\n (choose-by st cs (fn [c] (leap-cost (get (:M st) (dec t)) (.-note c))) (:temp st 0)))]\n (if-not c\n {:state st}\n (let [a (.-note c) pos (pos-of mi t)\n [st z] (if (= 2 (count pos)) (or (pick-end mi st a) [st nil]) [st nil])\n M (vec (concat (:M st) (repeat (max 0 (- n (count (:M st)))) nil)))\n M (cond-> (assoc M (first pos) a) (some? z) (assoc (second pos) z))\n st (assoc st :M M :t (inc t) :s (inc t))\n b {:t t :you a :engine (engine-note mi st t)\n :played (when (some? asked) (+ 60 (js/Math.round asked)))\n :corrected (and (some? asked) (off? asked (.semis cp a))) :auto (nil? asked)}]\n (live-out cp mi st b))))\n :read\n (let [w (get (:M st) t)\n dev (and (some? asked) (off? asked (.semis cp w)))\n st (cond-> (assoc st :t (inc t)) dev (update :devs (fnil inc 0)))]\n (live-out cp mi st (cond-> {:t t :you w :engine (engine-note mi st t)}\n dev (assoc :deviation true :played (+ 60 (js/Math.round asked)) :expected (.midi cp w)))))\n ;; done: a note begins a new crab\n (if (some? asked) (recur cp mi (assoc st :M [] :t 0 :s 0 :devs 0) asked) {:state st}))))\n asked-of (fn [value args]\n (cond\n (number? value) (if (:midi args) (- value 60) (when (pos? value) (semis-of-hz value)))\n (and (vector? value) (= :midi (first value)) (number? (second value))) (- (second value) 60)\n ;; an event: :freq (midiin, oscin) or :hz (a player's, a list: its first note)\n (and (map? value) (number? (ev-hz value)) (pos? (ev-hz value)) (pos? (or (:gate value) 1))) (semis-of-hz (ev-hz value))\n (and (sequential? value) (seq value) (every? number? value))\n (if (:midi args) (- (first value) 60) (semis-of-hz (first value)))\n :else nil))]\n {;; ── about ──\n :class \"cancrizans\"\n :license \"MPL-2.0\"\n :doc \"A crab canon written from both ends to the middle (Study 43): the comes is the dux backwards, both voices at once; with table, backwards and upside down about an axis ([:axis 62], a MIDI note; the final by default) — the one score read by a second player from across the table, a musical ambigram. It cannot be written from the beginning (the comes at the start is the dux at the end), so it is written by turns from both ends: each step a note at the start, then one at the end. A note that breaks a rule of the style (as comes's), or from which the work could not be closed, is corrected to the nearest one that can. On the right, the futuribles — the notes that can come next and the ways each leaves to close the work in the middle, counted exactly — and where the work is. When it closes, the dux and the comes go out (left) as patterns, {:note [...] :dur [...]} with the notes held joined, for a pbind and a player, and both as a musical tree (outlet 4), for a tree box, which shows it as a score. Notes as comes takes them: Hz, a list of keys held, [:midi 62], an event (:freq, or a player's :hz), or MIDI numbers with midi. :engine writes the next note itself; :back takes one back; :reset starts again. The system (Study 42) is comes's: diatonic by default, or meantone, septimal31 or pentatonic ([:system :septimal31]), and the mode one of its modes; the box's words name them in any order (cancrizans hypodorian, cancrizans pentatonic penta-A), or an EDN map; its modes, distances and tuning come with it. [:k -4], [:mode :hypodorian], [:system :pentatonic], [:bars 5], [:table true], [:axis 62] change the canon (and start again). With live (Study 46) the crab is played beat by beat: in the first half you play your note (or the nearest that can close the crab) and the box answers at the same beat with the end of your own line, written ahead (the notes that leave more futures first) — its futuribles say beforehand, as :end, what it will answer to each note (at temp 0, the default, exactly that; above it, the most likely, the box drawing among the answers with its seed: the same seed, the same game); two beats before the middle a cue {:cue :middle :in 2}; at the middle the rest of your line goes out (as a tree on outlet 4, for a tree box; at the end the whole crab) as the score to read — the box's answers so far, backwards, the first the last end of your line it wrote (with an odd number of beats the middle note is shared) —, and in the second half the box plays your first half backwards while you read it. Live, it sounds as a keyboard or a player does: the Hz of both voices — yours as played, corrected or read, and the box's — on the left, after their voice ids on the second outlet, for one synth~ (0→0, 1→1); a note held keeps its id — a note that is not the one written is said, as a deviation. On a pulse (the right inlet: a metro, a pulse) a beat goes on whether you played or not; without one, a note in is a beat. After the last beat, a note begins a new crab.\"\n :usage \"cancrizans [system] [mode] [k -7] [beats 2] [bars 6] [temp 0] [seed 1] [table] [live] [midi]\"\n :io [2 5]\n :size [170 46]\n :args [[:system nil] [:mode nil] [:k -7] [:beats 2] [:bars 6] [:temp 0] [:seed 1] [:table false] [:live false] [:midi false]]\n\n ;; ── tasks: the kernel and its count, outside the pure logic ──\n :tasks {:kernel (fn [{:keys [opts]} _box]\n (-> (js/Promise.all #js [(api/import-module origins-cp) (api/import-module origins-mi)])\n (.then (fn [[cp mm]]\n ;; the canon's mode, range and system from live (the box's pitches too: L's midi, name, semis)\n (let [L (.live cp (clj->js {:mode (:mode opts) :system (:system opts) :k (:k opts)\n :beats (:beats opts) :bars (:bars opts) :axis (:axis opts)}))\n sp (.-spec L)\n mi (.mirror mm #js {:tonic (.-tonic sp) :lo (.-lo sp) :hi (.-hi sp) :n (.-n sp) :b (.-b sp)\n :spacing (.-spacing sp) :starts (.-starts sp) :maxHold (.-b sp) :system (.-system sp)\n :transform #js {:kind (if (:table opts) \"table\" \"crab\") :k (.-k L) :axis (.-axis L)}})]\n (.then (.countAsync mi #js {}) (fn [_] {:cp L :mi mi})))))))}\n\n ;; ── logic ──\n :receive (fn [{:keys [inlet value state args]}]\n (let [st (if (and state (= args (:sig state))) state (assoc (fresh args) :k (:k state 0)))\n o (opts-of st args)\n {:keys [cp mi]} st]\n (cond\n (= inlet :task)\n (cond (not= (:k (:arg value)) (:k st)) {}\n (:error value) {:state (assoc st :loading false) :show {:main \"cancrizans\" :sub (str \"✗ \" (:error value))}}\n :else (let [{:keys [cp mi]} (:value value)\n st (assoc st :cp cp :mi mi :loading false :M [] :s 0 :pending nil :hist [])]\n (cond (:live args) (if-let [a (:waiting st)] (live-beat cp mi (dissoc st :waiting) a) (live-out cp mi (assoc st :t 0) {:t 0}))\n (:waiting st) (choose cp mi (dissoc st :waiting) (:waiting st))\n :else (at-point cp mi st nil))))\n\n ;; a parameter changed: a new work\n ;; the temperature or the seed: kept, the kernel as it is (a seed starts the game's chance again)\n (and (vector? value) (contains? chance (first value)) (number? (second value)))\n (let [[kk v] value]\n {:state (cond-> (assoc st kk v) (= kk :seed) (assoc :seed0 v))})\n\n (and (vector? value) (contains? params (first value)))\n (let [st (assoc-in st [:over (first value)] (second value))] (load st (opts-of st args)))\n\n (nil? mi)\n (let [a (asked-of value args) st (cond-> st (some? a) (assoc :waiting a))]\n (if (:loading st) {:state st} (load st o)))\n\n ;; live: a pulse is a beat (the note played since the last one, or the box's for you)\n (and (:live args) (= inlet 1))\n (let [a (:struck st)] (live-beat cp mi (assoc st :struck nil :pulsed true) a))\n (and (:live args) (#{:reset} value))\n (update (live-out cp mi (assoc st :M [] :t 0 :s 0 :devs 0 :struck nil :seed (:seed0 st 1)) {:t 0}) :out into [[1 []] [0 []]])\n (and (:live args) (#{:engine :bang} value)) (live-beat cp mi st nil)\n (and (:live args) (#{:back} value)) {:state st}\n (and (:live args) (some? (asked-of value args)))\n (let [a (asked-of value args)] (if (:pulsed st) {:state (assoc st :struck a)} (live-beat cp mi st a)))\n\n (#{:reset} value) (at-point cp mi (assoc st :M [] :s 0 :pending nil :hist []) nil)\n (#{:back} value)\n (cond (some? (:pending st)) (at-point cp mi (assoc st :pending nil) nil)\n (seq (:hist st)) (at-point cp mi (merge st (peek (:hist st)) {:hist (pop (:hist st))}) nil)\n :else {:state st})\n (#{:engine :bang} value)\n (if-let [a (engine cp mi st)] (choose cp mi st a) {:state st})\n\n :else\n (if-let [a (asked-of value args)] (choose cp mi st a) {:state st}))))\n\n ;; ── view ──\n :derive (fn [{:keys [shown]}] {:main (or (:main shown) \"cancrizans\") :sub (or (:sub shown) \"write the dux from both ends\")})\n :view [[:rect {:x 2 :y 2 :w 166 :h 42 :r 3 :stroke :grid :fill :bg}]\n [:text {:x 10 :y 20 :size 13} :$main]\n [:text {:x 10 :y 36 :size 9 :fill :soft} :$sub]]})\n"
14
- },
15
9
  {
16
10
  "class": "comes",
17
11
  "license": "MPL-2.0",
18
- "doc": "Counterpoint live: you play the dux and the comes answers, as a canon in a mode (Studies 41–43). Each note is checked against the rules of the style — the mode's range, its melodic intervals, consonance on the strong beats, a dissonance only passing on a weak one or held as a suspension, no parallel 5ths or octaves… — and against the future: a note from which the canon could not be finished is not allowed either. A note that breaks a rule is corrected to the nearest one that can be played (a black key too; between two as near, the more plausible), and the box says why. The comes is the dux's note d beats before, k steps away, in a strict canon (imitation 1); with less imitation it is chosen by the soft rules, near the dux's note (0.5–0.9), only following its motion (0.2–0.4) or free. With fourth, the dux is a cantus firmus (a note a bar) and the comes is syncopated. With inversion the comes is the dux upside down about an axis ([:axis 62], a MIDI note; the final by default); with augmentation it is the dux twice as slow (a strict canon, six bars at most). [:transform :inversion], [:transform :augmentation] or [:transform :canon] change it on the way. By turns (the default), one note in is one beat, and the same note again is held over the beat (a tie), as is :hold. With live, a pulse on the right inlet (a metro, a pulse) is a beat: a note lasts until the next one is struck; a note of three pulses in 2/2 turns the canon to 3/2, one longer than a bar ends the section, and the next note begins a new canon (with nocues it does neither: a note held longer than the canon allows makes it wait; the meter and the sections are then for other boxes to decide, with [:beats 3] and :end). :end ends the section from outside. The system (Study 42) is the scale, its tuning and its rules: diatonic by default, or meantone, septimal31 or pentatonic ([:system :septimal31]); the mode is one of its modes (diatonic: dorian, hypodorian … hypoaeolian; pentatonic: penta-C, penta-A, penta-D; septimal31: septimal, hypo-septimal). The box's words name the system and the mode in any order (comes dorian, comes pentatonic, comes pentatonic penta-A); a mode the system does not have is said, and its first mode taken, or one given as data, an EDN map ([:system {…}]); its modes, the distances at which it imitates and its tuning come with it (the notes out are tuned: Hz, or MIDI with a fraction), and a key is taken as the nearest note of the system. [:k -4], [:d 2], [:imitation 0.5], [:mode :hypodorian], [:system :pentatonic], [:beats 2], [:species 4] change the canon: at once by turns, at the next section live. It sounds as a keyboard or a player does: the Hz of both voices on the left and their voice ids on the second outlet (sent first), for one synth~ (0→0, 1→1) or a polyphonic faust~; a note held keeps its id and goes on sounding. On the right, the futuribles: the notes that can come next, the most plausible first, with their futures counted exactly; and where the canon is. Numbers are Hz, as a keyboard or midiin sends them (MIDI with midi); a list is the notes held (the first new one is played); an event too (from midiin, oscin, or a player's event outlet: :freq, or :hz). :engine lets it choose the next pair; with temp (or [:temp 1.5]) it draws the comes among the candidates (when the imitation is below 1) and, with :engine, the dux among the futuribles, with its own seed (seed, [:seed 7]: the same seed, the same game; :reset starts it again) — at 0, the default, the comes is the one the futuribles say; :back takes the last one back; :reset starts again.",
19
- "source": ";; comes · counterpoint live: you play the dux and it answers with the comes (discussions #172 and #192)\n;; Part of @kairotic/theory. Written against the Kairotic API (api/…).\n;; Study 41 as a box: the hard rules of a canon in the modes (meter, dissonance, ties and suspensions, fourth\n;; species, the ambitus, the voices between them, the degree of imitation) and the futures of every point counted\n;; exactly, in counterpoint.mjs beside this component (the same version of the package, on npm, or the page's own\n;; copy). A note that breaks a rule, or from which the canon could not be finished, is corrected to the nearest one\n;; that can (between two as near, the more plausible by the soft rules), and the box says why. Two ways to play:\n;; by turns (the default) one note in is one beat; the same note again is the note held (a tie)\n;; live (the word live) a pulse on the right inlet is a beat; a note lasts until the next one is struck. A\n;; note of three pulses in 2/2 turns the canon to 3/2; one longer than a bar ends the\n;; section, and the next note begins a new canon with the parameters as they are then.\n;; That is all it reads of time: more (the mode heard, a modulation, the meter, phrases)\n;; is for boxes of analysis, which tell it with messages ([:mode …], [:beats 3], end);\n;; with nocues the two cues are theirs too.\n(let [origins [\"npm:@kairotic/theory@0.11.0/dist/counterpoint.mjs\" \"kairotic/packages/theory/counterpoint.mjs\"]\n hz (fn [m] (* 440 (js/Math.pow 2 (/ (- m 69) 12))))\n semis-of-hz (fn [f] (* 12 (/ (js/Math.log (/ f 261.6255653005986)) (js/Math.log 2))))\n ev-hz (fn [e] (let [h (or (:freq e) (:hz e))] (if (sequential? h) (first h) h)))\n log2 (fn [x] (/ (js/Math.log x) (js/Math.log 2)))\n round2 (fn [x] (/ (js/Math.round (* 100 x)) 100))\n ;; the parameters that can change on the way (a message [:k -4], [:imitation 0.5], [:mode :hypodorian]…)\n params #{:mode :system :k :d :beats :imitation :bars :upbeat :species :transform :axis}\n ;; the canon as the kernel is asked for it: the box's text, what was changed since, the meter now\n opts-of (fn [st args]\n (let [o (merge {:mode (:mode args) :system (:system args) :k (:k args) :d (:d args) :beats (:beats args)\n :imitation (:imitation args) :bars (:bars args) :upbeat (:upbeat args)\n :species (if (:fourth args) 4 2)\n :transform (cond (:inversion args) :inversion (:augmentation args) :augmentation :else :canon)}\n (:over st))\n b (or (:meter st) (:beats o))]\n (-> o (assoc :beats b :maxHold b) (update :mode #(some-> % name)) (update :transform #(some-> % name))\n ;; a system: a name (:pentatonic) or the data itself (an EDN map, Study 42)\n (update :system #(if (keyword? %) (name %) %)))))\n ;; (a new text starts over)\n fresh (fn [args] {:sig args :D [] :C [] :pending [] :held [] :cps {} :wanted #{} :section 1\n :temp (:temp args) :seed (:seed args) :seed0 (:seed args)})\n ;; chance (the temperature and the seed): a random number of the box's own (Park–Miller), kept in its state;\n ;; at temperature 0 none is used, and the comes is the one the futuribles say\n rnd (fn [st] (let [x (mod (* (max 1 (:seed st 1)) 16807) 2147483647)] [(assoc st :seed x) (/ (dec x) 2147483646)]))\n chance (fn [st] (if (> (:temp st 0) 0.001)\n (let [[st r] (rnd st) [st r2] (rnd st)] [st #js {:temp (:temp st) :r r :r2 r2}])\n [st #js {}]))\n ;; a kernel for the canon o: counted already, being counted, or asked for now (a task, outside the pure logic)\n ensure (fn [st o]\n (if (or (contains? (:cps st) o) (contains? (:wanted st) o))\n [st []]\n [(update st :wanted conj o) [[:kernel {:opts o}]]]))\n ;; live: the canon as it is, and the same in 3/2 (a note of three pulses may turn it)\n ensure-live (fn [st args]\n (let [[st fx] (ensure st (opts-of st args))\n [st fx2] (ensure st (opts-of (assoc st :meter 3) args))]\n [st (into fx fx2)]))\n futs (fn [cp D C]\n (mapv (fn [f] (let [x (.-note f)]\n {:midi (.midi cp x) :name (.name cp x) :futures (.-futures f)\n :bits (round2 (log2 (.-futures f))) :score (round2 (.-score f))\n :comes (when (some? (.-comes f)) (.midi cp (.-comes f)))}))\n (.futuribles cp (clj->js D) (clj->js C))))\n report (fn [cp st r]\n (let [D (:D st) C (:C st) t (count D) n (.-n cp) b (.-beats cp) ph (.. cp -spec -phase)\n pos (+ (dec t) ph) cnt (.count cp (clj->js D) (clj->js C))]\n (cond-> {:t t :n n :finished (>= t n) :section (:section st) :meter b :system (.-systemName cp) :mode (.-mode cp)\n :futures cnt :bits (round2 (if (pos? cnt) (log2 cnt) -1))\n :dux (mapv (fn [x] (.midi cp x)) D)\n :comes-line (mapv (fn [c] (when (some? c) (.midi cp c))) C)\n :obligations (vec (.obligations cp (clj->js D) (clj->js C)))}\n (.-modeNote cp) (assoc :note (.-modeNote cp))\n (pos? t) (assoc :bar (inc (quot pos b)) :beat (inc (mod pos b))\n :held (and (> t 1) (= (peek D) (nth D (- t 2)))))\n r (assoc :asked (+ 60 (.-asked r)) :played (.midi cp (.-note r)) :corrected (.-corrected r)\n :reason (.-reason r) :comes (when (some? (.-comes r)) (.midi cp (.-comes r)))))))\n shown (fn [cp st r]\n (let [D (:D st) C (:C st) x (peek D) c (peek C)]\n {:status (str (when (:live st) (str \"§\" (:section st) \" · \")) (count D) \"/\" (.-n cp) \" · \"\n (round2 (log2 (max 1 (.count cp (clj->js D) (clj->js C))))) \" bits\"\n (when (:live st) (str \" · \" (.-beats cp) \"/2\")))\n :dux (if x (.name cp x) \"–\") :comes (if (some? c) (.name cp c) \"–\")\n :corrected (boolean (and r (.-corrected r))) :reason (or (when r (.-reason r)) (.-modeNote cp))}))\n ;; what sounds: both voices, as a keyboard or a player sends them — their Hz (outlet 0) after their voice ids\n ;; (outlet 1), for one synth~. A voice's id is where its note was struck (section and beat): a note held\n ;; keeps its id and goes on sounding; a note struck again, even the same, is a new id and is struck again.\n sounding (fn [cp st]\n (let [D (:D st) C (:C st)\n start (fn [xs] (loop [i (dec (count xs))] (if (and (pos? i) (= (nth xs i) (nth xs (dec i)))) (recur (dec i)) i)))\n sec (:section st 1)\n vs (cond-> []\n (seq D) (conj [(keyword (str \"d\" sec \"-\" (start D))) (hz (.midi cp (peek D)))])\n (some? (peek C)) (conj [(keyword (str \"c\" sec \"-\" (start C))) (hz (.midi cp (peek C)))]))]\n [[1 (mapv first vs)] [0 (mapv second vs)]]))\n silence [[1 []] [0 []]]\n ;; one pair placed: the dux as played (or corrected) and the comes with it, sounding together\n placed (fn [cp st r]\n (let [D0 (:D st) C0 (:C st)\n st (-> st (update :D conj (.-note r)) (update :C conj (.-comes r)))\n x (.-note r) c (.-comes r)\n done (>= (count (:D st)) (.-n cp))]\n {:state (cond-> st done (assoc :idle true :section (inc (:section st 1))))\n :show (shown cp st r)\n :out (into [[3 (report cp st r)] [2 (futs cp (:D st) (:C st))]] (sounding cp st))}))\n ;; a pitch asked for: after the last canon, a new one\n play (fn [cp st asked]\n (let [st (if (or (:idle st) (>= (count (:D st)) (.-n cp))) (assoc st :D [] :C [] :idle false) st)]\n (let [[st o] (chance st)]\n (if-let [r (.play cp (clj->js (:D st)) (clj->js (:C st)) asked o)]\n (placed cp st r)\n {:state st}))))\n merge-res (fn [a b] {:state (:state b) :show (or (:show b) (:show a)) :out (into (vec (:out a)) (:out b))\n :effects (into (vec (:effects a)) (:effects b))})\n chain (fn [cp st askeds] (reduce (fn [acc a] (merge-res acc (play cp (:state acc) a))) {:state st :out []} askeds))\n at-point (fn [cp st]\n {:state st :show (shown cp st nil)\n :out (into [[3 (report cp st nil)] [2 (futs cp (:D st) (:C st))]] silence)})\n ;; what a pitch asked for is (semitones above C4), from a number, a MIDI note, an event or the keys held\n asked-of (fn [value args st]\n (let [num (fn [v] (if (:midi args) (- v 60) (when (pos? v) (semis-of-hz v))))]\n (cond\n (number? value) (if (or (:midi args) (pos? value)) [:note (num value)] [:release])\n (and (vector? value) (= :midi (first value)) (number? (second value))) [:note (- (second value) 60)]\n ;; an event: :freq (midiin, oscin) or :hz (a player's, a list: its first note)\n (and (map? value) (number? (ev-hz value)))\n (if (and (pos? (ev-hz value)) (pos? (or (:gate value) 1))) [:note (semis-of-hz (ev-hz value))] [:release])\n (and (sequential? value) (every? number? value))\n (cond (empty? value) [:release]\n (some #{(first value)} (:held st)) [:same]\n :else [:note (num (first value))])\n :else nil)))\n ;; ── live: the section ends, and the next note begins a new canon ──\n cue (fn [st kind]\n (let [st (cond-> (assoc st :idle true :cur nil :dur 0 :section (inc (:section st 1)))\n (= kind :ternary) (assoc :meter 3))]\n {:state st\n :show {:status (str \"§\" (:section st) \" · \" (if (= kind :ternary) \"3/2 next\" \"a new canon next\"))}\n :out (into [[3 {:cue kind :section (:section st) :meter (or (:meter st) (:beats (:over st)))}]] silence)}))\n ;; a pulse: the note struck since the last one, or the one sounding held over the beat\n pulse (fn [st args at late]\n (let [period (when (and (:lastp st) (not late)) (- at (:lastp st)))\n st (cond-> st (not late) (assoc :lastp at) (and period (pos? period)) (assoc :period period))\n o (opts-of st args)\n cp (if (or (:idle st) (nil? (:cp st))) (get (:cps st) o) (:cp st))\n b (when cp (.-beats cp))]\n (cond\n ;; a new note: the canon goes on, or a new one begins (once its kernel is counted)\n (:struck st)\n (if cp\n (let [res (play cp (assoc st :cp cp) (:struck st))]\n (update res :state assoc :struck nil :cur (:struck st) :dur 1 :last :struck))\n (let [[st fx] (ensure-live st args)] {:state st :effects fx}))\n ;; nothing sounding: the comes rests (what still sounded is let go)\n (or (:idle st) (nil? (:cur st)) (nil? cp))\n {:state (assoc st :last :idle) :out (when (#{:hold :struck} (:last st)) silence)}\n ;; held three pulses in 2/2: the canon turns to 3/2\n (and (= 2 b) (>= (inc (:dur st)) 3) (not (:nocues args)))\n (let [res (cue st :ternary) [s2 fx] (ensure (:state res) (opts-of (:state res) args))]\n (assoc res :state (assoc s2 :last :cue) :effects fx))\n ;; held longer than a bar: the end of the section\n (and (> (inc (:dur st)) b) (not (:nocues args)))\n (let [res (cue st :end)] (assoc-in res [:state :last] :cue))\n ;; without cues, a note held longer than the canon allows: the canon waits for the next one\n (> (inc (:dur st)) b)\n {:state (assoc st :dur (inc (:dur st)) :last :wait)}\n ;; held over the beat (a tie)\n :else\n (if-let [r (let [[_ o] (chance st)] (.hold cp (clj->js (:D st)) (clj->js (:C st)) o))]\n (-> (placed cp (first (chance st)) r) (update :state assoc :dur (inc (:dur st)) :last :hold))\n {:state st}))))\n ;; a note struck in live: for the next pulse, or for the last one if it came just after it (late)\n strike (fn [st args at s]\n (let [late (and (:lastp st) (:period st) (< (- at (:lastp st)) (* 0.3 (:period st))))]\n (cond\n (and late (= :hold (:last st)) (seq (:D st)))\n (let [st (-> st (update :D pop) (update :C pop))\n res (play (:cp st) st s)]\n (update res :state assoc :cur s :dur 1 :last :struck :struck nil))\n (and late (#{:idle :cue} (:last st)))\n (pulse (assoc st :struck s) args at true)\n :else {:state (assoc st :struck s)})))]\n {;; ── about ──\n :class \"comes\"\n :license \"MPL-2.0\"\n :doc \"Counterpoint live: you play the dux and the comes answers, as a canon in a mode (Studies 41–43). Each note is checked against the rules of the style — the mode's range, its melodic intervals, consonance on the strong beats, a dissonance only passing on a weak one or held as a suspension, no parallel 5ths or octaves… — and against the future: a note from which the canon could not be finished is not allowed either. A note that breaks a rule is corrected to the nearest one that can be played (a black key too; between two as near, the more plausible), and the box says why. The comes is the dux's note d beats before, k steps away, in a strict canon (imitation 1); with less imitation it is chosen by the soft rules, near the dux's note (0.5–0.9), only following its motion (0.2–0.4) or free. With fourth, the dux is a cantus firmus (a note a bar) and the comes is syncopated. With inversion the comes is the dux upside down about an axis ([:axis 62], a MIDI note; the final by default); with augmentation it is the dux twice as slow (a strict canon, six bars at most). [:transform :inversion], [:transform :augmentation] or [:transform :canon] change it on the way. By turns (the default), one note in is one beat, and the same note again is held over the beat (a tie), as is :hold. With live, a pulse on the right inlet (a metro, a pulse) is a beat: a note lasts until the next one is struck; a note of three pulses in 2/2 turns the canon to 3/2, one longer than a bar ends the section, and the next note begins a new canon (with nocues it does neither: a note held longer than the canon allows makes it wait; the meter and the sections are then for other boxes to decide, with [:beats 3] and :end). :end ends the section from outside. The system (Study 42) is the scale, its tuning and its rules: diatonic by default, or meantone, septimal31 or pentatonic ([:system :septimal31]); the mode is one of its modes (diatonic: dorian, hypodorian … hypoaeolian; pentatonic: penta-C, penta-A, penta-D; septimal31: septimal, hypo-septimal). The box's words name the system and the mode in any order (comes dorian, comes pentatonic, comes pentatonic penta-A); a mode the system does not have is said, and its first mode taken, or one given as data, an EDN map ([:system {…}]); its modes, the distances at which it imitates and its tuning come with it (the notes out are tuned: Hz, or MIDI with a fraction), and a key is taken as the nearest note of the system. [:k -4], [:d 2], [:imitation 0.5], [:mode :hypodorian], [:system :pentatonic], [:beats 2], [:species 4] change the canon: at once by turns, at the next section live. It sounds as a keyboard or a player does: the Hz of both voices on the left and their voice ids on the second outlet (sent first), for one synth~ (0→0, 1→1) or a polyphonic faust~; a note held keeps its id and goes on sounding. On the right, the futuribles: the notes that can come next, the most plausible first, with their futures counted exactly; and where the canon is. Numbers are Hz, as a keyboard or midiin sends them (MIDI with midi); a list is the notes held (the first new one is played); an event too (from midiin, oscin, or a player's event outlet: :freq, or :hz). :engine lets it choose the next pair; with temp (or [:temp 1.5]) it draws the comes among the candidates (when the imitation is below 1) and, with :engine, the dux among the futuribles, with its own seed (seed, [:seed 7]: the same seed, the same game; :reset starts it again) — at 0, the default, the comes is the one the futuribles say; :back takes the last one back; :reset starts again.\"\n :usage \"comes [system] [mode] [k -7] [d 3] [beats 2] [imitation 1] [bars 8] [upbeat 0] [temp 0] [seed 1] [fourth] [inversion] [augmentation] [live] [nocues] [midi]\"\n :io [2 4]\n :size [150 46]\n :args [[:system nil] [:mode nil] [:k -7] [:d 3] [:beats 2] [:imitation 1] [:bars 8] [:upbeat 0] [:temp 0] [:seed 1] [:fourth false] [:inversion false] [:augmentation false] [:live false] [:nocues false] [:midi false]]\n\n ;; ── tasks: a kernel and its count, outside the pure logic ──\n :tasks {:kernel (fn [{:keys [opts]} _box]\n (-> (api/import-module origins)\n (.then (fn [m]\n (let [cp (.live m (clj->js opts))]\n (.then (.warm cp) (fn [_] {:cp cp})))))))}\n\n ;; ── logic ──\n :receive (fn [{:keys [inlet value state args at]}]\n (let [st (if (and state (= args (:sig state))) state (assoc (fresh args) :live (:live args)))\n at (or at 0)\n o (opts-of st args)\n cp (:cp st)]\n (cond\n ;; a kernel counted: kept; the one the canon waits for is the canon's, and what waited is played\n (= inlet :task)\n (let [o2 (:opts (:arg value))]\n (cond\n (not (contains? (:wanted st) o2)) {}\n (:error value) {:state (update st :wanted disj o2) :show {:status (str \"✗ \" (:error value))}}\n :else\n (let [k (:cp (:value value))\n st (-> st (update :wanted disj o2) (update :cps assoc o2 k))]\n (cond\n (or (not= o2 o) (and cp (not (:idle st)))) {:state st}\n (:live st) {:state (assoc st :cp k) :show (shown k st nil)}\n :else (let [waiting (:pending st) st (assoc st :cp k :pending [])]\n (if (seq waiting) (chain k st waiting) (at-point k st)))))))\n\n ;; a parameter changed: by turns at once (a new canon), live at the next section\n ;; chance: the temperature or the seed, kept (the canon as it is; a seed starts the chance again)\n (and (vector? value) (#{:temp :seed} (first value)) (number? (second value)))\n (let [[kk v] value] {:state (cond-> (assoc st kk v) (= kk :seed) (assoc :seed0 v))})\n\n (and (vector? value) (contains? params (first value)) (some? (second value)))\n (let [[kk v] value\n st (cond-> (assoc-in st [:over kk] v) (= kk :beats) (assoc :meter v))\n o (opts-of st args)\n [st fx] (ensure st o)]\n (if (:live st)\n {:state st :effects fx}\n (let [k (get (:cps st) o)\n st (assoc st :cp k :D [] :C [] :idle false)]\n (if k (assoc (at-point k st) :effects fx) {:state st :effects fx}))))\n\n ;; the pulse (live)\n (= inlet 1)\n (if (and (:live st) (or cp (get (:cps st) o)))\n (pulse st args at false)\n (let [[st fx] (if (:live st) (ensure-live st args) (ensure st o))] {:state st :effects fx}))\n\n ;; nothing to play with yet: the kernel is asked for (and what arrives is kept)\n (and (nil? cp) (not (:live st)))\n (let [a (asked-of value args st)\n st (cond-> st\n (= :note (first a)) (update :pending conj (second a))\n (and (sequential? value) (every? number? value)) (assoc :held (vec value)))\n [st fx] (ensure st o)]\n {:state st :effects fx :show {:status \"counting the futures…\"}})\n\n ;; the end of the section, from outside (an analysis that heard a cadence, a phrase…)\n (#{:end} value)\n (if (:idle st) {:state st} (cue st :end))\n\n (#{:reset} value)\n (if cp (at-point cp (assoc st :D [] :C [] :held [] :idle false :cur nil :struck nil :seed (:seed0 st 1))) {:state st})\n (#{:back} value)\n (if cp (at-point cp (-> st (update :D (fn [v] (if (seq v) (pop v) v))) (update :C (fn [v] (if (seq v) (pop v) v))))) {:state st})\n (#{:engine} value)\n (if cp\n (let [st (if (or (:idle st) (>= (count (:D st)) (.-n cp))) (assoc st :D [] :C [] :idle false) st)]\n (let [[st o] (chance st)]\n (if-let [r (.engine cp (clj->js (:D st)) (clj->js (:C st)) o)] (placed cp st r) {:state st})))\n {:state st})\n (and (not (:live st)) (#{:hold} value))\n (if (and cp (seq (:D st)) (not (:idle st)))\n (let [[st o] (chance st)]\n (if-let [r (.hold cp (clj->js (:D st)) (clj->js (:C st)) o)] (placed cp st r) {:state st}))\n {:state st})\n\n :else\n (let [[kind x] (asked-of value args st)\n st (if (and (sequential? value) (every? number? value)) (assoc st :held (vec value)) st)]\n (cond\n (and (= kind :note) (:live st)) (let [[st fx] (ensure-live st args) res (strike st args at x)]\n (update res :effects #(into (vec %) fx)))\n (= kind :note) (play cp st x)\n (and (= kind :release) (not (:live st))) {:state st :out [[1 []] [0 []]]}\n :else {:state st})))))\n\n ;; ── view ──\n :derive (fn [{:keys [shown]}]\n {:main (if (:dux shown) (str (:dux shown) \" → \" (:comes shown)) \"comes\")\n :sub (or (:status shown) \"play the dux\")\n :mark (if (:corrected shown) 4 0)})\n :view [[:rect {:x 2 :y 2 :w 146 :h 42 :r 3 :stroke :grid :fill :bg}]\n [:rect {:x 4 :y 4 :w :$mark :h 38 :r 1 :stroke nil :fill :kairos}]\n [:text {:x 12 :y 20 :size 13} :$main]\n [:text {:x 12 :y 36 :size 9 :fill :soft} :$sub]]})\n"
20
- },
21
- {
22
- "class": "euclid",
23
- "license": "MPL-2.0",
24
- "doc": "A Euclidean rhythm (Bjorklund's algorithm, after Toussaint): k onsets spread as evenly as they can be over n pulses — euclid 3 8 is the tresillo (3-3-2), euclid 5 8 the cinquillo, euclid 5 16 a rotation of the bossa nova, euclid 7 12 the bembé. Drawn as a necklace: the pulses around a circle, time clockwise from the top, the onsets joined into a polygon; pressing a pulse makes the rhythm start there (a rotation). A bang sends it; [:k 5], [:n 16], [:rotation 2], [:bars 4], [:meter \"3/4\"] (or a map of them) change it and send it when it is new, a number is k. Rhythm apart from pitch: out of the left outlet a musical tree, a bar of n pulses (4/4 for 8 or 16, 12/8 for 12, n/8 up to 12, else n/16; [:meter …] for another) with an :rtm whose shares are the intervals between onsets (a negative share a silence); bars repeat it, the pitches going on. Its right inlet (cold) takes the pitches the notes take in turn, starting again when they run out (talea and color): a map with :pitches or :pitch (kept as it is), a pattern of comes or cancrizans ({:note [...]}), a melody string (\"c4 e4 g4\"), a list of Hz (the keys held on a keyboard; MIDI with midi), notes or chords of a tree; :clear forgets them (every note c4). Outlet 1 is the :rtm map alone ({:shares [3 3 2] :pitches …}), to merge with other pitches (merge) and write as a node (vector :rtm %); outlet 2 the pulses, ones and zeros ([1 0 0 1 0 0 1 0]).",
25
- "source": ";; euclid · a Euclidean rhythm: k onsets spread as evenly as they can be over n pulses\n;; Part of @kairotic/theory. Written against the Kairotic API (api/…).\n;; Bjorklund's algorithm (Toussaint, \"The Euclidean algorithm generates traditional musical rhythms\", 2005):\n;; E(3,8) is the tresillo, E(5,8) the cinquillo, E(5,16) a rotation of the bossa nova, E(7,12) the bembé.\n;; The rhythm is drawn as a necklace — the n pulses around a circle, time running clockwise from the top,\n;; the onsets joined into a polygon — and pressing a pulse makes the rhythm start there (a rotation).\n;; What it sends is rhythm apart from pitch, as an :rtm of kairotic.mt (shares: the intervals between\n;; onsets, a negative share a silence), so that it can be merged with a map of pitches ({:pitches …}, the\n;; talea and color of an isorhythm) into a musical tree: the box does it with what reaches its right inlet,\n;; and its outlet 1 gives the bare :rtm map to merge elsewhere (merge, then vector :rtm %).\n(let [;; Bjorklund: k ones and n − k zeros, the remainder paired again and again (Euclid's algorithm)\n bjorklund (fn [k n]\n (cond (<= n 0) []\n (<= k 0) (vec (repeat n 0))\n (>= k n) (vec (repeat n 1))\n :else (loop [a (vec (repeat k [1])) b (vec (repeat (- n k) [0]))]\n (if (<= (count b) 1)\n (vec (apply concat (concat a b)))\n (let [m (min (count a) (count b))]\n (recur (mapv into (subvec a 0 m) (subvec b 0 m))\n (if (> (count a) m) (subvec a m) (subvec b m))))))))\n ;; a necklace read from pulse r on: the rhythm in a fixed position against the beat\n rotate (fn [xs r] (let [n (count xs)] (if (zero? n) xs (let [r (mod r n)] (vec (concat (subvec xs r) (subvec xs 0 r)))))))\n onsets-of (fn [ps] (vec (keep-indexed (fn [i x] (when (= 1 x) i)) ps)))\n ;; the intervals between onsets, around the circle (3 3 2): the rhythm as a necklace\n intervals-of (fn [ps] (let [os (onsets-of ps) n (count ps)]\n (if (empty? os) [] (mapv (fn [a b] (- b a)) os (conj (subvec os 1) (+ n (first os)))))))\n ;; the shares of an :rtm: from each onset to the next one (or the end of the bar); the pulses before the\n ;; first onset a silence (a negative share): 01001001 → [-1 3 3 1]\n shares-of (fn [ps] (let [os (onsets-of ps) n (count ps)]\n (cond (zero? n) []\n (empty? os) [(- n)]\n :else (vec (concat (when (pos? (first os)) [(- (first os))])\n (map (fn [a b] (- b a)) os (conj (subvec os 1) n)))))))\n ;; the meter of a bar of n pulses, when none is asked: the pulse a written value\n pow2? (fn [x] (and (pos? x) (== x (js/Math.pow 2 (js/Math.round (js/Math.log2 x))))))\n meter-of (fn [n] (cond (and (>= n 4) (pow2? n)) [4 4]\n (and (>= n 12) (zero? (mod n 3)) (pow2? (/ n 3))) [12 8]\n (< n 4) [n 4]\n (<= n 12) [n 8]\n :else [n 16]))\n ;; a meter asked for: [3 4], \"3/4\", \"7/8[2+2+3]\", or nil (as the pulses say)\n meter-arg (fn [v] (cond (and (sequential? v) (= 2 (count v)) (every? number? v)) (vec v)\n (string? v) v\n (keyword? v) (name v)\n :else nil))\n ;; pitches, as theory boxes take them: Hz by default, MIDI with midi; the MIDI notes kept to 3 decimals\n hz->m (fn [x] (when (and (number? x) (pos? x)) (/ (js/Math.round (* 1000 (+ 69 (* 12 (js/Math.log2 (/ x 440)))))) 1000)))\n ;; what reaches the right inlet, as the pitches of the :rtm (or nil, to forget them): a map of pitches\n ;; ({:pitches …} or {:pitch …}, kept as they are), a pattern ({:note [...]} of comes or cancrizans, MIDI;\n ;; nil a rest), a melody string (\"c4 e4 g4\"), a list of pitches (Hz, as a keyboard sends the keys held;\n ;; MIDI with midi), a list of notes or chords of a tree, or one pitch\n pitches-of (fn [midi? v]\n (let [p (fn [x] (if midi? x (hz->m x)))]\n (cond (#{:clear} v) nil\n (map? v) (cond (or (contains? v :pitches) (contains? v :pitch)) (select-keys v [:pitches :pitch])\n (sequential? (:note v)) {:pitches (mapv (fn [x] (if (number? x) x \"r\")) (:note v))}\n :else :ignore)\n (string? v) {:pitches v}\n (number? v) (if-let [m (p v)] {:pitch m} :ignore)\n (and (sequential? v) (keyword? (first v))) {:pitches [v]}\n (and (sequential? v) (seq v) (every? number? v)) (let [ms (vec (keep p v))] (if (seq ms) {:pitches ms} :ignore))\n (and (sequential? v) (seq v)) {:pitches (vec v)}\n :else :ignore)))\n ;; the color goes on over the bars: bar i begins where the notes of the bar before left it\n tokens (fn [ps] (cond (string? ps) (vec (remove #{\"\"} (.split (.trim ps) (js/RegExp. \"\\\\s+\"))))\n (sequential? ps) (vec ps)\n :else nil))\n color-at (fn [pm skip]\n (let [ts (tokens (:pitches pm))]\n (if (or (empty? ts) (zero? (mod skip (count ts))))\n pm\n (let [r (mod skip (count ts)) ts2 (vec (concat (subvec ts r) (subvec ts 0 r)))]\n (assoc pm :pitches (if (string? (:pitches pm)) (apply str (interpose \" \" ts2)) ts2))))))\n ;; everything the box knows: its words, changed by messages\n params (fn [args st]\n (let [o (merge args (:over st))\n n (max 1 (js/Math.round (or (:n o) 8)))]\n {:n n :k (api/clamp (js/Math.round (or (:k o) 3)) 0 n) :rotation (mod (js/Math.round (or (:rotation o) 0)) n)\n :bars (api/clamp (js/Math.round (or (:bars o) 1)) 1 64) :meter (or (:meter o) (meter-of n))}))\n ;; the rhythm as data: the pulses, its necklace, and the :rtm with the pitches merged\n rhythm (fn [{:keys [k n rotation bars meter]} pm]\n (let [ps (rotate (bjorklund k n) rotation)\n rtm (merge {:shares (shares-of ps)} (or pm {}))\n bar (fn [i] (let [a (color-at rtm (* i k))]\n (if (zero? i) [:measure {:meter meter} [:rtm a]] [:measure [:rtm a]])))]\n {:pulses ps :onsets (onsets-of ps) :intervals (intervals-of ps) :rtm rtm\n :tree (into [:voice] (map bar (range bars)))}))\n shown-of (fn [p r] (merge (select-keys p [:k :n :rotation :bars]) (select-keys r [:pulses :onsets :intervals])))\n ;; what goes out: the tree (0), the :rtm map (1), the pulses (2), the last first (as Max does)\n outs (fn [r] [[2 (:pulses r)] [1 (:rtm r)] [0 (:tree r)]])\n ;; a change: sent when what it makes is new (the same again changes nothing); a bang sends it anyway\n changed (fn [args st over always?]\n (let [st2 (assoc st :over over) p (params args st2) r (rhythm p (:pm st2))]\n (if (and (not always?) (= (:tree r) (:sent st)))\n {:state st2 :show (shown-of p r)}\n {:state (assoc st2 :sent (:tree r)) :show (shown-of p r) :out (outs r)})))\n polar (fn [cx cy R i n] (let [a (* 2 js/Math.PI (/ i n))] [(+ cx (* R (js/Math.sin a))) (- cy (* R (js/Math.cos a)))]))]\n {;; ── about ──\n :class \"euclid\"\n :license \"MPL-2.0\"\n :doc \"A Euclidean rhythm (Bjorklund's algorithm, after Toussaint): k onsets spread as evenly as they can be over n pulses — euclid 3 8 is the tresillo (3-3-2), euclid 5 8 the cinquillo, euclid 5 16 a rotation of the bossa nova, euclid 7 12 the bembé. Drawn as a necklace: the pulses around a circle, time clockwise from the top, the onsets joined into a polygon; pressing a pulse makes the rhythm start there (a rotation). A bang sends it; [:k 5], [:n 16], [:rotation 2], [:bars 4], [:meter \\\"3/4\\\"] (or a map of them) change it and send it when it is new, a number is k. Rhythm apart from pitch: out of the left outlet a musical tree, a bar of n pulses (4/4 for 8 or 16, 12/8 for 12, n/8 up to 12, else n/16; [:meter …] for another) with an :rtm whose shares are the intervals between onsets (a negative share a silence); bars repeat it, the pitches going on. Its right inlet (cold) takes the pitches the notes take in turn, starting again when they run out (talea and color): a map with :pitches or :pitch (kept as it is), a pattern of comes or cancrizans ({:note [...]}), a melody string (\\\"c4 e4 g4\\\"), a list of Hz (the keys held on a keyboard; MIDI with midi), notes or chords of a tree; :clear forgets them (every note c4). Outlet 1 is the :rtm map alone ({:shares [3 3 2] :pitches …}), to merge with other pitches (merge) and write as a node (vector :rtm %); outlet 2 the pulses, ones and zeros ([1 0 0 1 0 0 1 0]).\"\n :usage \"euclid [k 3] [n 8] [rotation 0] [bars 1] [midi]\"\n :io [2 3]\n :size [180 200]\n\n ;; ── arguments ──\n :args [[:k 3] [:n 8] [:rotation 0] [:bars 1] [:midi false]]\n\n ;; ── logic ──\n :receive (fn [{:keys [inlet value state args]}]\n (let [st (or state {:over {} :pm nil})\n over (:over st)\n set-over (fn [m] (changed args st (merge over m) false))]\n (if (= inlet 1)\n (let [pm (pitches-of (:midi args) value)]\n (if (= pm :ignore) {} {:state (assoc st :pm pm)}))\n (cond\n (#{:bang} value) (changed args st over true)\n (number? value) (set-over {:k value})\n (and (vector? value) (= :pressed (first value)) (number? (second value)))\n (let [p (params args st)] (set-over {:rotation (+ (:rotation p) (second value))}))\n (and (vector? value) (= 2 (count value)) (#{:k :n :rotation :bars} (first value)) (number? (second value)))\n (set-over {(first value) (second value)})\n (and (vector? value) (= :meter (first value))) (set-over {:meter (meter-arg (second value))})\n (map? value) (set-over (cond-> (select-keys value [:k :n :rotation :bars])\n (contains? value :meter) (assoc :meter (meter-arg (:meter value)))))\n :else {}))))\n ;; pressing a pulse: the rhythm starts there (sent once, on release)\n :gesture (fn [{:keys [up hit]}] (when (and up (number? hit)) [:pressed hit]))\n\n ;; ── view ──\n :draw (fn [{:keys [shown w h args]}]\n (let [p (or shown (let [n (max 1 (js/Math.round (or (:n args) 8)))\n k (api/clamp (js/Math.round (or (:k args) 3)) 0 n)\n ps (rotate (bjorklund k n) (or (:rotation args) 0))]\n {:k k :n n :pulses ps :onsets (onsets-of ps) :intervals (intervals-of ps)}))\n n (:n p) ps (:pulses p) os (:onsets p)\n cx (/ w 2) cy (/ (- h 30) 2) R (- (min cx cy) 16)\n r (cond (> n 32) 2.2 (> n 16) 3 :else 4.5)]\n (concat\n [[:circle {:cx cx :cy cy :r R :stroke :grid}]]\n ;; the start of the bar, at the top\n (let [[x1 y1] (polar cx cy (- R 9) 0 n) [x2 y2] (polar cx cy (+ R 9) 0 n)]\n [[:line {:x1 x1 :y1 y1 :x2 x2 :y2 y2 :stroke :kairos :weight 1.5 :opacity 0.8}]])\n (when (> (count os) 1) [[:path {:points (mapv (fn [i] (polar cx cy R i n)) os) :closed true :stroke :accent :weight 2}]])\n (for [i (range n)]\n (let [[x y] (polar cx cy R i n) on (= 1 (nth ps i 0))]\n [:group {:hit i}\n [[:circle {:cx x :cy y :r (if on (+ r 1.5) r) :fill (if on :accent :bg) :stroke (if on :accent :soft)}]]]))\n [[:text {:x cx :y (- h 15) :anchor :middle :size 10 :fill :ink}\n (str \"E(\" (:k p) \",\" n \")\" (when (pos? (or (:rotation p) 0)) (str \" ↻\" (:rotation p))))]\n [:text {:x cx :y (- h 3) :anchor :middle :size 9 :fill :soft}\n (if (seq (:intervals p)) (apply str (interpose \"-\" (:intervals p))) \"silence\")]])))})\n"
12
+ "doc": "Counterpoint live: you play the dux and the comes answers (Studies 41–46, 50). The comes is a reader of the dux at a speed: 1 a canon (the default), 0.5 an augmentation (twice as slow, a strict canon), −1 a crab (the dux backwards); inverted turns it upside down about the final (or [:axis 62]): an inversion, or with −1 a table canon, the score read from across the table. k steps away (−7 an octave below) and, forwards, d beats late. Each note is checked against the rules of the style — the mode's range, its melodic intervals, consonance on the strong beats, a dissonance passing on a weak one or held as a suspension, no parallel 5ths or octaves… — and against the future: a note from which the work could not be finished is not allowed either, and is corrected to the nearest one that can (a black key too), the box saying why. Forwards (speed 1 or 0.5) you play the dux and the comes answers: by turns (the default) one note in is one beat, the same note again (or :hold) held over it; with live a pulse on the right inlet (a metro) is a beat, a note lasts until the next, a note of three pulses in 2/2 turns the canon to 3/2 and one longer than a bar ends the section (with nocues neither: other boxes decide, with [:beats 3] and :end). With imitation below 1 the comes is chosen by the soft rules: near the dux's notes (0.5–0.9), following its motion (0.2–0.4) or free; with fourth your line is a cantus firmus and the comes syncopated. Backwards (speed −1) the work is written from both ends to the middle: by turns a note at the start, then one at the end; live (Study 46) your note, and at the same beat the box's answer at the end of your own line, a cue two beats before the middle, and at the middle the rest of your line to read (outlet 4) while the box plays your first half backwards. The system (Study 42) is diatonic by default, or meantone, septimal31, pentatonic, or an EDN map; the mode one of its modes; the box's words name them in any order (comes hypodorian, comes pentatonic penta-A -1). Out: the Hz of both voices sounding after their voice ids (outlet 1), for one synth~; the futuribles (outlet 2), the notes that can come next with their futures counted exactly; where the work is (outlet 3); and the finished work as a musical tree (outlet 4), for a tree box. [:speed -1], [:inverted true], [:k -4], [:d 2], [:mode …], [:system …], [:bars 5], [:imitation 0.5], [:beats 3], [:species 4], [:axis 62] change it; :engine, :back, :reset; [:temp 1.5], [:seed 7] its chance. Numbers are Hz (MIDI with midi); a list is the keys held; an event (:freq, or a player's :hz).",
13
+ "source": ";; comes · counterpoint live: you play the dux and the comes answers (discussions #172, #192 and #248)\n;; Part of @kairotic/theory. Written against the Kairotic API (api/…).\n;; One box for the canon and its mirrors, as Study 50 found them: the comes is a reader of the dux at a speed — 1 a\n;; canon, 1/2 an augmentation (twice as slow), −1 a crab (the dux backwards) — k steps away, d beats late, upright or\n;; inverted (an inversion; backwards and inverted, a table canon). The speed decides how the work is written, and so\n;; how it is played:\n;; speed > 0 forwards: you play the dux and the comes answers (Study 41's kernel in counterpoint.mjs). By turns\n;; (the default) one note in is one beat, the same note again the note held (a tie); live, a pulse on\n;; the right inlet is a beat and a note lasts until the next one is struck — a note of three pulses in\n;; 2/2 turns the canon to 3/2, one longer than a bar ends the section (unless nocues).\n;; speed −1 from both ends to the middle (Study 43's mirror.mjs): by turns, a note at the start, then one at the\n;; end; live (Study 46), your note and at the same beat the box's answer at the end of your own line,\n;; and at the middle the rest of your line to read while the box plays your first half backwards.\n;; The other speeds of Study 50 (a hemiola, 2/3; a sesquialtera, 3/2; a diminution, 2…) are not in the box yet.\n(let [;; a line as a musical tree (for a tree box): a measure of b beats, a beat a half note (:dur 2), a note held\n ;; over the beat tied, the last note to the end of its bar, nothing sounding a rest\n work-tree (fn [midi b & lines]\n (let [voice (fn [xs]\n (let [xs (vec xs) n (count xs)\n beat (fn [i] (let [v (get xs i) dur (if (= i (dec n)) (* 2 (- b (mod i b))) 2)]\n (if (nil? v)\n [:rest {:dur dur}]\n [:note (cond-> {:pitch (/ (js/Math.round (* 1000 (midi v))) 1000) :dur dur}\n (and (< (inc i) n) (= v (get xs (inc i)))) (assoc :tie true))])))]\n (into [:voice] (for [bar (partition-by #(quot % b) (range n))]\n (into [:measure {:meter [b 2]}] (map beat bar))))))]\n (into [:piece] (map voice lines))))\n ;; ── forwards: a canon, an inversion, an augmentation ──\n fwd (let [origins [\"npm:@kairotic/theory@0.13.0/dist/counterpoint.mjs\" \"kairotic/packages/theory/counterpoint.mjs\"]\n hz (fn [m] (* 440 (js/Math.pow 2 (/ (- m 69) 12))))\n semis-of-hz (fn [f] (* 12 (/ (js/Math.log (/ f 261.6255653005986)) (js/Math.log 2))))\n ev-hz (fn [e] (let [h (or (:freq e) (:hz e))] (if (sequential? h) (first h) h)))\n log2 (fn [x] (/ (js/Math.log x) (js/Math.log 2)))\n round2 (fn [x] (/ (js/Math.round (* 100 x)) 100))\n ;; the parameters that can change on the way (a message [:k -4], [:imitation 0.5], [:mode :hypodorian]…)\n params #{:mode :system :k :d :beats :imitation :bars :upbeat :species :axis}\n ;; the canon as the kernel is asked for it: the box's text, what was changed since, the meter now\n opts-of (fn [st args]\n (let [o (merge {:mode (:mode args) :system (:system args) :k (:k args) :d (:d args) :beats (:beats args)\n :imitation (:imitation args) :bars (:bars args) :upbeat (:upbeat args)\n :species (if (:fourth args) 4 2)\n :transform (cond (:inversion args) :inversion (:augmentation args) :augmentation :else :canon)}\n (:over st))\n b (or (:meter st) (:beats o))]\n (-> o (assoc :beats b :maxHold b) (update :mode #(some-> % name)) (update :transform #(some-> % name))\n ;; a system: a name (:pentatonic) or the data itself (an EDN map, Study 42)\n (update :system #(if (keyword? %) (name %) %)))))\n ;; (a new text starts over)\n fresh (fn [args] {:sig args :D [] :C [] :pending [] :held [] :cps {} :wanted #{} :section 1\n :temp (:temp args) :seed (:seed args) :seed0 (:seed args)})\n ;; chance (the temperature and the seed): a random number of the box's own (Park–Miller), kept in its state;\n ;; at temperature 0 none is used, and the comes is the one the futuribles say\n rnd (fn [st] (let [x (mod (* (max 1 (:seed st 1)) 16807) 2147483647)] [(assoc st :seed x) (/ (dec x) 2147483646)]))\n chance (fn [st] (if (> (:temp st 0) 0.001)\n (let [[st r] (rnd st) [st r2] (rnd st)] [st #js {:temp (:temp st) :r r :r2 r2}])\n [st #js {}]))\n ;; a kernel for the canon o: counted already, being counted, or asked for now (a task, outside the pure logic)\n ensure (fn [st o]\n (if (or (contains? (:cps st) o) (contains? (:wanted st) o))\n [st []]\n [(update st :wanted conj o) [[:kernel {:opts o}]]]))\n ;; live: the canon as it is, and the same in 3/2 (a note of three pulses may turn it)\n ensure-live (fn [st args]\n (let [[st fx] (ensure st (opts-of st args))\n [st fx2] (ensure st (opts-of (assoc st :meter 3) args))]\n [st (into fx fx2)]))\n futs (fn [cp D C]\n (mapv (fn [f] (let [x (.-note f)]\n {:midi (.midi cp x) :name (.name cp x) :futures (.-futures f)\n :bits (round2 (log2 (.-futures f))) :score (round2 (.-score f))\n :comes (when (some? (.-comes f)) (.midi cp (.-comes f)))}))\n (.futuribles cp (clj->js D) (clj->js C))))\n report (fn [cp st r]\n (let [D (:D st) C (:C st) t (count D) n (.-n cp) b (.-beats cp) ph (.. cp -spec -phase)\n pos (+ (dec t) ph) cnt (.count cp (clj->js D) (clj->js C))]\n (cond-> {:t t :n n :finished (>= t n) :section (:section st) :meter b :system (.-systemName cp) :mode (.-mode cp)\n :futures cnt :bits (round2 (if (pos? cnt) (log2 cnt) -1))\n :dux (mapv (fn [x] (.midi cp x)) D)\n :comes-line (mapv (fn [c] (when (some? c) (.midi cp c))) C)\n :obligations (vec (.obligations cp (clj->js D) (clj->js C)))}\n (.-modeNote cp) (assoc :note (.-modeNote cp))\n (pos? t) (assoc :bar (inc (quot pos b)) :beat (inc (mod pos b))\n :held (and (> t 1) (= (peek D) (nth D (- t 2)))))\n r (assoc :asked (+ 60 (.-asked r)) :played (.midi cp (.-note r)) :corrected (.-corrected r)\n :reason (.-reason r) :comes (when (some? (.-comes r)) (.midi cp (.-comes r)))))))\n shown (fn [cp st r]\n (let [D (:D st) C (:C st) x (peek D) c (peek C)]\n {:status (str (when (:live st) (str \"§\" (:section st) \" · \")) (count D) \"/\" (.-n cp) \" · \"\n (round2 (log2 (max 1 (.count cp (clj->js D) (clj->js C))))) \" bits\"\n (when (:live st) (str \" · \" (.-beats cp) \"/2\")))\n :dux (if x (.name cp x) \"–\") :comes (if (some? c) (.name cp c) \"–\")\n :corrected (boolean (and r (.-corrected r))) :reason (or (when r (.-reason r)) (.-modeNote cp))}))\n ;; what sounds: both voices, as a keyboard or a player sends them — their Hz (outlet 0) after their voice ids\n ;; (outlet 1), for one synth~. A voice's id is where its note was struck (section and beat): a note held\n ;; keeps its id and goes on sounding; a note struck again, even the same, is a new id and is struck again.\n sounding (fn [cp st]\n (let [D (:D st) C (:C st)\n start (fn [xs] (loop [i (dec (count xs))] (if (and (pos? i) (= (nth xs i) (nth xs (dec i)))) (recur (dec i)) i)))\n sec (:section st 1)\n vs (cond-> []\n (seq D) (conj [(keyword (str \"d\" sec \"-\" (start D))) (hz (.midi cp (peek D)))])\n (some? (peek C)) (conj [(keyword (str \"c\" sec \"-\" (start C))) (hz (.midi cp (peek C)))]))]\n [[1 (mapv first vs)] [0 (mapv second vs)]]))\n silence [[1 []] [0 []]]\n ;; one pair placed: the dux as played (or corrected) and the comes with it, sounding together\n placed (fn [cp st r]\n (let [D0 (:D st) C0 (:C st)\n st (-> st (update :D conj (.-note r)) (update :C conj (.-comes r)))\n x (.-note r) c (.-comes r)\n done (>= (count (:D st)) (.-n cp))]\n {:state (cond-> st done (assoc :idle true :section (inc (:section st 1))))\n :show (shown cp st r)\n :out (cond-> (into [[3 (report cp st r)] [2 (futs cp (:D st) (:C st))]] (sounding cp st))\n ;; finished: both voices as a musical tree (for a tree box, its score)\n done (conj [4 (work-tree (fn [v] (.midi cp v)) (.-beats cp) (:D st) (:C st))]))}))\n ;; a pitch asked for: after the last canon, a new one\n play (fn [cp st asked]\n (let [st (if (or (:idle st) (>= (count (:D st)) (.-n cp))) (assoc st :D [] :C [] :idle false) st)]\n (let [[st o] (chance st)]\n (if-let [r (.play cp (clj->js (:D st)) (clj->js (:C st)) asked o)]\n (placed cp st r)\n {:state st}))))\n merge-res (fn [a b] {:state (:state b) :show (or (:show b) (:show a)) :out (into (vec (:out a)) (:out b))\n :effects (into (vec (:effects a)) (:effects b))})\n chain (fn [cp st askeds] (reduce (fn [acc a] (merge-res acc (play cp (:state acc) a))) {:state st :out []} askeds))\n at-point (fn [cp st]\n {:state st :show (shown cp st nil)\n :out (into [[3 (report cp st nil)] [2 (futs cp (:D st) (:C st))]] silence)})\n ;; what a pitch asked for is (semitones above C4), from a number, a MIDI note, an event or the keys held\n asked-of (fn [value args st]\n (let [num (fn [v] (if (:midi args) (- v 60) (when (pos? v) (semis-of-hz v))))]\n (cond\n (number? value) (if (or (:midi args) (pos? value)) [:note (num value)] [:release])\n (and (vector? value) (= :midi (first value)) (number? (second value))) [:note (- (second value) 60)]\n ;; an event: :freq (midiin, oscin) or :hz (a player's, a list: its first note)\n (and (map? value) (number? (ev-hz value)))\n (if (and (pos? (ev-hz value)) (pos? (or (:gate value) 1))) [:note (semis-of-hz (ev-hz value))] [:release])\n (and (sequential? value) (every? number? value))\n (cond (empty? value) [:release]\n (some #{(first value)} (:held st)) [:same]\n :else [:note (num (first value))])\n :else nil)))\n ;; ── live: the section ends, and the next note begins a new canon ──\n cue (fn [st kind]\n (let [st (cond-> (assoc st :idle true :cur nil :dur 0 :section (inc (:section st 1)))\n (= kind :ternary) (assoc :meter 3))]\n {:state st\n :show {:status (str \"§\" (:section st) \" · \" (if (= kind :ternary) \"3/2 next\" \"a new canon next\"))}\n :out (into [[3 {:cue kind :section (:section st) :meter (or (:meter st) (:beats (:over st)))}]] silence)}))\n ;; a pulse: the note struck since the last one, or the one sounding held over the beat\n pulse (fn [st args at late]\n (let [period (when (and (:lastp st) (not late)) (- at (:lastp st)))\n st (cond-> st (not late) (assoc :lastp at) (and period (pos? period)) (assoc :period period))\n o (opts-of st args)\n cp (if (or (:idle st) (nil? (:cp st))) (get (:cps st) o) (:cp st))\n b (when cp (.-beats cp))]\n (cond\n ;; a new note: the canon goes on, or a new one begins (once its kernel is counted)\n (:struck st)\n (if cp\n (let [res (play cp (assoc st :cp cp) (:struck st))]\n (update res :state assoc :struck nil :cur (:struck st) :dur 1 :last :struck))\n (let [[st fx] (ensure-live st args)] {:state st :effects fx}))\n ;; nothing sounding: the comes rests (what still sounded is let go)\n (or (:idle st) (nil? (:cur st)) (nil? cp))\n {:state (assoc st :last :idle) :out (when (#{:hold :struck} (:last st)) silence)}\n ;; held three pulses in 2/2: the canon turns to 3/2\n (and (= 2 b) (>= (inc (:dur st)) 3) (not (:nocues args)))\n (let [res (cue st :ternary) [s2 fx] (ensure (:state res) (opts-of (:state res) args))]\n (assoc res :state (assoc s2 :last :cue) :effects fx))\n ;; held longer than a bar: the end of the section\n (and (> (inc (:dur st)) b) (not (:nocues args)))\n (let [res (cue st :end)] (assoc-in res [:state :last] :cue))\n ;; without cues, a note held longer than the canon allows: the canon waits for the next one\n (> (inc (:dur st)) b)\n {:state (assoc st :dur (inc (:dur st)) :last :wait)}\n ;; held over the beat (a tie)\n :else\n (if-let [r (let [[_ o] (chance st)] (.hold cp (clj->js (:D st)) (clj->js (:C st)) o))]\n (-> (placed cp (first (chance st)) r) (update :state assoc :dur (inc (:dur st)) :last :hold))\n {:state st}))))\n ;; a note struck in live: for the next pulse, or for the last one if it came just after it (late)\n strike (fn [st args at s]\n (let [late (and (:lastp st) (:period st) (< (- at (:lastp st)) (* 0.3 (:period st))))]\n (cond\n (and late (= :hold (:last st)) (seq (:D st)))\n (let [st (-> st (update :D pop) (update :C pop))\n res (play (:cp st) st s)]\n (update res :state assoc :cur s :dur 1 :last :struck :struck nil))\n (and late (#{:idle :cue} (:last st)))\n (pulse (assoc st :struck s) args at true)\n :else {:state (assoc st :struck s)})))]\n {;; ── tasks: a kernel and its count, outside the pure logic ──\n :tasks {:kernel (fn [{:keys [opts]} _box]\n (-> (api/import-module origins)\n (.then (fn [m]\n (let [cp (.live m (clj->js opts))]\n (.then (.warm cp) (fn [_] {:cp cp})))))))}\n \n ;; ── logic ──\n :receive (fn [{:keys [inlet value state args at]}]\n (let [st (if (and state (= args (:sig state))) state (assoc (fresh args) :live (:live args)))\n at (or at 0)\n o (opts-of st args)\n cp (:cp st)]\n (cond\n ;; a kernel counted: kept; the one the canon waits for is the canon's, and what waited is played\n (= inlet :task)\n (let [o2 (:opts (:arg value))]\n (cond\n (not (contains? (:wanted st) o2)) {}\n (:error value) {:state (update st :wanted disj o2) :show {:status (str \"✗ \" (:error value))}}\n :else\n (let [k (:cp (:value value))\n st (-> st (update :wanted disj o2) (update :cps assoc o2 k))]\n (cond\n (or (not= o2 o) (and cp (not (:idle st)))) {:state st}\n (:live st) {:state (assoc st :cp k) :show (shown k st nil)}\n :else (let [waiting (:pending st) st (assoc st :cp k :pending [])]\n (if (seq waiting) (chain k st waiting) (at-point k st)))))))\n \n ;; a parameter changed: by turns at once (a new canon), live at the next section\n ;; chance: the temperature or the seed, kept (the canon as it is; a seed starts the chance again)\n (and (vector? value) (#{:temp :seed} (first value)) (number? (second value)))\n (let [[kk v] value] {:state (cond-> (assoc st kk v) (= kk :seed) (assoc :seed0 v))})\n \n (and (vector? value) (contains? params (first value)) (some? (second value)))\n (let [[kk v] value\n st (cond-> (assoc-in st [:over kk] v) (= kk :beats) (assoc :meter v))\n o (opts-of st args)\n [st fx] (ensure st o)]\n (if (:live st)\n {:state st :effects fx}\n (let [k (get (:cps st) o)\n st (assoc st :cp k :D [] :C [] :idle false)]\n (if k (assoc (at-point k st) :effects fx) {:state st :effects fx}))))\n \n ;; the pulse (live)\n (= inlet 1)\n (if (and (:live st) (or cp (get (:cps st) o)))\n (pulse st args at false)\n (let [[st fx] (if (:live st) (ensure-live st args) (ensure st o))] {:state st :effects fx}))\n \n ;; nothing to play with yet: the kernel is asked for (and what arrives is kept)\n (and (nil? cp) (not (:live st)))\n (let [a (asked-of value args st)\n st (cond-> st\n (= :note (first a)) (update :pending conj (second a))\n (and (sequential? value) (every? number? value)) (assoc :held (vec value)))\n [st fx] (ensure st o)]\n {:state st :effects fx :show {:status \"counting the futures…\"}})\n \n ;; the end of the section, from outside (an analysis that heard a cadence, a phrase…)\n (#{:end} value)\n (if (:idle st) {:state st} (cue st :end))\n \n (#{:reset} value)\n (if cp (at-point cp (assoc st :D [] :C [] :held [] :idle false :cur nil :struck nil :seed (:seed0 st 1))) {:state st})\n (#{:back} value)\n (if cp (at-point cp (-> st (update :D (fn [v] (if (seq v) (pop v) v))) (update :C (fn [v] (if (seq v) (pop v) v))))) {:state st})\n (#{:engine} value)\n (if cp\n (let [st (if (or (:idle st) (>= (count (:D st)) (.-n cp))) (assoc st :D [] :C [] :idle false) st)]\n (let [[st o] (chance st)]\n (if-let [r (.engine cp (clj->js (:D st)) (clj->js (:C st)) o)] (placed cp st r) {:state st})))\n {:state st})\n (and (not (:live st)) (#{:hold} value))\n (if (and cp (seq (:D st)) (not (:idle st)))\n (let [[st o] (chance st)]\n (if-let [r (.hold cp (clj->js (:D st)) (clj->js (:C st)) o)] (placed cp st r) {:state st}))\n {:state st})\n \n :else\n (let [[kind x] (asked-of value args st)\n st (if (and (sequential? value) (every? number? value)) (assoc st :held (vec value)) st)]\n (cond\n (and (= kind :note) (:live st)) (let [[st fx] (ensure-live st args) res (strike st args at x)]\n (update res :effects #(into (vec %) fx)))\n (= kind :note) (play cp st x)\n (and (= kind :release) (not (:live st))) {:state st :out [[1 []] [0 []]]}\n :else {:state st})))))\n })\n ;; ── backwards: a crab or a table canon, from both ends to the middle ──\n crab (let [origins-cp [\"npm:@kairotic/theory@0.13.0/dist/counterpoint.mjs\" \"kairotic/packages/theory/counterpoint.mjs\"]\n origins-mi [\"npm:@kairotic/theory@0.13.0/dist/mirror.mjs\" \"kairotic/packages/theory/mirror.mjs\"]\n semis-of-hz (fn [f] (* 12 (/ (js/Math.log (/ f 261.6255653005986)) (js/Math.log 2))))\n ev-hz (fn [e] (let [h (or (:freq e) (:hz e))] (if (sequential? h) (first h) h)))\n log2 (fn [x] (/ (js/Math.log x) (js/Math.log 2)))\n params #{:mode :system :k :beats :bars :axis}\n ;; a key asked for is the note of the system it is nearest (within a quarter of a tone or so): not a correction\n off? (fn [asked x] (> (js/Math.abs (- asked x)) 0.45))\n ;; (chance: the temperature and the seed change the game, not the canon)\n chance #{:temp :seed}\n ;; (the box's words, then what was changed since: a mode or a system as a name, or a system as data)\n opts-of (fn [st args]\n (-> (merge {:mode (:mode args) :system (:system args) :k (:k args) :beats (:beats args) :bars (:bars args)\n :table (boolean (:table args)) :axis nil}\n (:over st))\n (update :mode #(some-> % name))\n ;; a system: a name (:pentatonic) or the data itself (an EDN map, Study 42)\n (update :system #(if (keyword? %) (name %) %))))\n fresh (fn [args] {:sig args :M [] :s 0 :pending nil :hist [] :k 0 :temp (:temp args) :seed (:seed args) :seed0 (:seed args)})\n load (fn [st o]\n (let [k (inc (:k st 0))]\n {:state (assoc st :k k :loading true :mi nil)\n :show {:main \"comes · crab\" :sub \"counting the futures…\"}\n :effects [[:mirror {:k k :opts o}]]}))\n ;; the dux as the kernel reads it: an array with holes where nothing is written yet\n js-M (fn [st n] (let [a (js/Array. n)] (doseq [[i v] (map-indexed vector (:M st))] (when (some? v) (aset a i v))) a))\n pos-of (fn [mi s] (when (< s (.-steps mi)) (vec (aget (.-order mi) s))))\n ;; the candidates for the next note: at the start of the step, or at its end once the start is chosen\n cands (fn [mi st]\n (let [s (:s st) M (js-M st (.-n mi))]\n (if (some? (:pending st)) (.fanSecond mi M s (:pending st)) (.fan mi M s))))\n futs (fn [cp mi st]\n (vec (for [c (cands mi st) :when (pos? (or (.-futures c) 0))]\n {:midi (.midi cp (.-note c)) :name (.name cp (.-note c)) :futures (.-futures c)})))\n ;; a voice as a pattern: the notes held over the beat joined\n pattern (fn [cp xs]\n (let [runs (partition-by identity xs)]\n {:note (mapv (fn [r] (.midi cp (first r))) runs) :dur (mapv count runs)}))\n report (fn [cp mi st extra]\n (let [n (.-n mi) lns (.lines mi (js-M st n)) s (:s st) steps (.-steps mi) pos (pos-of mi s)\n mid (fn [v] (when (and (some? v) (not (undefined? v))) (.midi cp v)))]\n (merge {:step s :steps steps :closed (>= s steps) :system (.-systemName cp) :mode (.-mode cp)\n :writing (cond (>= s steps) :closed (some? (:pending st)) :end :else :start)\n :beat (when pos (inc (if (some? (:pending st)) (peek pos) (first pos))))\n :futures (.count mi (js-M st n) s)\n :dux (mapv mid (array-seq (.-D lns))) :comes (mapv mid (array-seq (.-C lns)))}\n extra)))\n shown (fn [cp mi st]\n (let [steps (.-steps mi) s (:s st)]\n {:main (str (if (.-inverted mi) \"table · \" \"crab · \") (count (remove nil? (:M st))) \"/\" (.-n mi) \" notes\")\n :sub (cond (and (zero? s) (nil? (:pending st)) (.-modeNote cp)) (.-modeNote cp)\n (>= s steps) \"closed: the work is written\"\n (some? (:pending st)) (str \"now the note at the end · \" (.count mi (js-M st (.-n mi)) s) \" ways\")\n :else (str \"step \" (inc s) \"/\" steps \": the note at the start\"))}))\n ;; a line as a musical tree, for a score (a tree box): a measure of b beats, a beat a half note\n ;; (:dur 2), a note held over the beat tied, the last note to the end of its bar; from the bar of beat\n ;; `from`, and the beats before `upto` as rests (what is already played)\n voice-of (fn [cp xs b from upto]\n (let [n (count xs) x (fn [i] (let [v (get xs i)] (when (and (some? v) (not (undefined? v))) v)))\n beat (fn [i]\n (let [v (x i) dur (if (= i (dec n)) (* 2 (- b (mod i b))) 2)]\n (if (or (< i upto) (nil? v))\n [:rest {:dur dur}]\n [:note (cond-> {:pitch (/ (js/Math.round (* 1000 (.midi cp v))) 1000) :dur dur}\n (and (< (inc i) n) (>= (inc i) upto) (= v (x (inc i)))) (assoc :tie true))])))]\n (into [:voice]\n (for [bar (partition-by #(quot % b) (range (* b (quot from b)) n))]\n (into [:measure {:meter [b 2]}] (map beat bar))))))\n ;; the whole work, both voices, as a tree\n piece-of (fn [cp mi M]\n (let [b (or (.. mi -spec -b) 1) lns (.lines mi M)]\n [:piece (voice-of cp (vec (array-seq (.-D lns))) b 0 0) (voice-of cp (vec (array-seq (.-C lns))) b 0 0)]))\n at-point (fn [cp mi st extra]\n (let [closed (>= (:s st) (.-steps mi)) n (.-n mi) lns (.lines mi (js-M st n))]\n {:state st :show (shown cp mi st)\n :out (cond-> []\n closed (conj [4 (piece-of cp mi (js-M st n))])\n true (conj [3 (report cp mi st extra)] [2 (futs cp mi st)]))}))\n ;; a pitch asked for (semitones above C4): the nearest candidate with a future; between two as near, the\n ;; one with more futures\n nearest (fn [cp cs asked]\n (let [ok (filter #(pos? (or (.-futures %) 0)) cs)]\n (when (seq ok)\n (first (sort-by (juxt #(js/Math.abs (- (.semis cp (.-note %)) asked)) #(- (.-futures %))) ok)))))\n write (fn [mi st vals]\n (let [pos (pos-of mi (:s st)) n (.-n mi)\n M (vec (concat (:M st) (repeat (max 0 (- n (count (:M st)))) nil)))]\n (assoc st :M (reduce (fn [M [p v]] (assoc M p v)) M (map vector pos vals))\n :s (inc (:s st)) :pending nil :hist (conj (:hist st) (select-keys st [:M :s :pending])))))\n choose (fn [cp mi st asked]\n (let [pos (pos-of mi (:s st))]\n (if-not pos\n {:state st}\n (let [c (nearest cp (cands mi st) asked)\n r (js/Math.round asked)\n extra (when c {:asked (+ 60 r) :played (.midi cp (.-note c)) :corrected (off? asked (.semis cp (.-note c)))})]\n (cond\n (nil? c) {:state st}\n (and (= 2 (count pos)) (nil? (:pending st))) (at-point cp mi (assoc st :pending (.-note c)) extra)\n (= 2 (count pos)) (at-point cp mi (write mi st [(:pending st) (.-note c)]) extra)\n :else (at-point cp mi (write mi st [(.-note c)]) extra))))))\n ;; the engine: the candidate nearest the note beside it (a step), more futures between two as near\n engine (fn [cp mi st]\n (let [pos (pos-of mi (:s st)) M (:M st)]\n (when pos\n (let [second? (some? (:pending st))\n nb (if second? (get M (inc (peek pos))) (get M (dec (first pos))))\n cs (filter #(pos? (or (.-futures %) 0)) (cands mi st))]\n (when (seq cs)\n (let [c (first (sort-by (juxt #(if nb (js/Math.abs (- (js/Math.abs (- (.-note %) nb)) 1)) 0) #(- (.-futures %))) cs))]\n (.semis cp (.-note c))))))))\n ;; ── live (Study 46): the crab played beat by beat ──\n leap-cost (fn [a b] (if (or (nil? a) (nil? b)) 0 (get {0 1.5 1 0 2 0.3 3 0.6 4 0.7 5 1 7 1} (js/Math.abs (- b a)) 2)))\n ;; a random number of the box's own (Park–Miller), kept in its state: a game can be played again\n rnd (fn [st] (let [x (mod (* (max 1 (:seed st 1)) 16807) 2147483647)] [(assoc st :seed x) (/ (dec x) 2147483646)]))\n ;; a choice among candidates by their cost: at temperature 0 the cheapest (no chance in it), above it a softmax of\n ;; -cost/temperature drawn with the box's own random numbers (its seed: the same game again with the same seed)\n choose-by (fn [st cs cost temp]\n (let [cs (vec (sort-by (juxt cost #(.-note %)) cs))]\n (cond (empty? cs) [st nil]\n (<= (or temp 0) 0.001) [st (first cs)]\n :else (let [m (cost (first cs)) ws (mapv #(js/Math.exp (/ (- m (cost %)) temp)) cs)\n [st r] (rnd st) x (* r (reduce + ws))]\n [st (loop [j 0 acc 0] (let [acc (+ acc (nth ws j))]\n (if (or (< x acc) (= j (dec (count cs)))) (nth cs j) (recur (inc j) acc))))]))))\n ;; the end of your line, chosen by the box for your note a: a step from the note after it, the more futures\n ;; the better; :end in the futuribles is the cheapest (at temperature 0 the one the box will answer)\n end-cands (fn [mi st a]\n (let [s (:t st 0) n (.-n mi) q (- n 1 s)\n cs (filter #(pos? (or (.-futures %) 0)) (.fanSecond mi (js-M st n) s a))]\n [cs (fn [c] (- (leap-cost (.-note c) (get (:M st) (inc q))) (* 0.2 (log2 (.-futures c)))))]))\n end-for (fn [mi st a] (let [[cs cost] (end-cands mi st a)] (some-> (second (choose-by st cs cost 0)) .-note)))\n pick-end (fn [mi st a] (let [[cs cost] (end-cands mi st a) [st c] (choose-by st cs cost (:temp st 0))] (when c [st (.-note c)])))\n live-phase (fn [mi st] (let [t (:t st 0)] (cond (< t (.-steps mi)) :choose (< t (.-n mi)) :read :else :done)))\n engine-note (fn [mi st t] (let [e (get (:M st) (.source mi t))] (when (some? e) (.T mi e))))\n hz-of (fn [cp v] (* 440 (js/Math.pow 2 (/ (- (.midi cp v) 69) 12))))\n ;; what sounds at beat t, live: your note (as played, corrected or read) and the box's, as a keyboard or a\n ;; player sends them — their Hz (outlet 0) after their voice ids (outlet 1), for one synth~. A voice's id is\n ;; the beat where its note was struck: a note held over the beat keeps it and goes on sounding.\n sounding (fn [cp mi st t]\n (let [start (fn [xs] (loop [i (dec (count xs))] (if (and (pos? i) (= (nth xs i) (nth xs (dec i)))) (recur (dec i)) i)))\n you (subvec (:M st) 0 (inc t))\n box (mapv #(engine-note mi st %) (range (inc t)))\n vs (cond-> []\n (some? (peek you)) (conj [(keyword (str \"y\" (start you))) (hz-of cp (peek you))])\n (some? (peek box)) (conj [(keyword (str \"e\" (start box))) (hz-of cp (peek box))]))]\n [[1 (mapv first vs)] [0 (mapv second vs)]]))\n live-out (fn [cp mi st b]\n (let [ph (live-phase mi st) t (:t st 0) n (.-n mi) steps (.-steps mi)\n mid (fn [v] (when (some? v) (.midi cp v)))\n next-opts (case ph\n :choose (let [two? (= 2 (count (pos-of mi t)))]\n (vec (for [c (.fan mi (js-M st n) t) :when (pos? (or (.-futures c) 0))]\n (cond-> {:midi (.midi cp (.-note c)) :name (.name cp (.-note c)) :futures (.-futures c)}\n ;; what the box will answer at the end of your line if you play it\n two? (assoc :end (some->> (end-for mi st (.-note c)) (.midi cp)))))))\n :read [{:midi (mid (get (:M st) t)) :name (.name cp (get (:M st) t)) :futures 1}]\n [])]\n {:state st\n :show {:main (str (if (.-inverted mi) \"table\" \"crab\") \" live · beat \" (min n t) \"/\" n)\n :sub (case ph :choose (str \"play: \" (count next-opts) \" notes can close it\")\n :read (str \"read: \" (.name cp (get (:M st) t)))\n \"done: the crab is played\")}\n :out (cond-> [(case ph\n ;; the score (for a tree box): at the middle what is left of your line to read, the\n ;; beats of its bar already played as rests; at the end the whole crab, both voices.\n ;; Twice a crab, not every beat: each tree written into a tree box is an event of\n ;; the work's history\n :read (when (= t steps) [4 (voice-of cp (:M st) (.. mi -spec -b) t t)])\n :done [4 (piece-of cp mi (js-M st n))]\n nil)\n [3 (merge {:t (:t b) :phase ph :you (mid (:you b)) :engine (mid (:engine b)) :n n :middle steps :system (.-systemName cp) :mode (.-mode cp)\n :ways (if (= ph :choose) (.count mi (js-M st n) t) 1)}\n (select-keys b [:played :corrected :auto :deviation :expected])\n (when (= t (- steps 2)) {:cue :middle :in 2}))]\n [2 next-opts]]\n true (#(vec (remove nil? %)))\n (some? (:t b)) (into (if (some? (:you b)) (sounding cp mi st (:t b)) [])))}))\n ;; a beat: what you played (asked, or nil: on a pulse the box plays for you), and what the box answers\n live-beat (fn [cp mi st asked]\n (let [n (.-n mi) t (:t st 0) ph (live-phase mi st)]\n (case ph\n :choose\n (let [cs (filter #(pos? (or (.-futures %) 0)) (.fan mi (js-M st n) t))\n [st c] (if (some? asked)\n [st (first (sort-by (juxt #(js/Math.abs (- (.semis cp (.-note %)) asked)) #(- (.-futures %))) cs))]\n ;; nothing played on the pulse: the box plays your note, by the same taste\n (choose-by st cs (fn [c] (leap-cost (get (:M st) (dec t)) (.-note c))) (:temp st 0)))]\n (if-not c\n {:state st}\n (let [a (.-note c) pos (pos-of mi t)\n [st z] (if (= 2 (count pos)) (or (pick-end mi st a) [st nil]) [st nil])\n M (vec (concat (:M st) (repeat (max 0 (- n (count (:M st)))) nil)))\n M (cond-> (assoc M (first pos) a) (some? z) (assoc (second pos) z))\n st (assoc st :M M :t (inc t) :s (inc t))\n b {:t t :you a :engine (engine-note mi st t)\n :played (when (some? asked) (+ 60 (js/Math.round asked)))\n :corrected (and (some? asked) (off? asked (.semis cp a))) :auto (nil? asked)}]\n (live-out cp mi st b))))\n :read\n (let [w (get (:M st) t)\n dev (and (some? asked) (off? asked (.semis cp w)))\n st (cond-> (assoc st :t (inc t)) dev (update :devs (fnil inc 0)))]\n (live-out cp mi st (cond-> {:t t :you w :engine (engine-note mi st t)}\n dev (assoc :deviation true :played (+ 60 (js/Math.round asked)) :expected (.midi cp w)))))\n ;; done: a note begins a new crab\n (if (some? asked) (recur cp mi (assoc st :M [] :t 0 :s 0 :devs 0) asked) {:state st}))))\n asked-of (fn [value args]\n (cond\n (number? value) (if (:midi args) (- value 60) (when (pos? value) (semis-of-hz value)))\n (and (vector? value) (= :midi (first value)) (number? (second value))) (- (second value) 60)\n ;; an event: :freq (midiin, oscin) or :hz (a player's, a list: its first note)\n (and (map? value) (number? (ev-hz value)) (pos? (ev-hz value)) (pos? (or (:gate value) 1))) (semis-of-hz (ev-hz value))\n (and (sequential? value) (seq value) (every? number? value))\n (if (:midi args) (- (first value) 60) (semis-of-hz (first value)))\n :else nil))]\n {;; ── tasks: the kernel and its count, outside the pure logic ──\n :tasks {:mirror (fn [{:keys [opts]} _box]\n (-> (js/Promise.all #js [(api/import-module origins-cp) (api/import-module origins-mi)])\n (.then (fn [[cp mm]]\n ;; the canon's mode, range and system from live (the box's pitches too: L's midi, name, semis)\n (let [L (.live cp (clj->js {:mode (:mode opts) :system (:system opts) :k (:k opts)\n :beats (:beats opts) :bars (:bars opts) :axis (:axis opts)}))\n sp (.-spec L)\n mi (.mirror mm #js {:tonic (.-tonic sp) :lo (.-lo sp) :hi (.-hi sp) :n (.-n sp) :b (.-b sp)\n :spacing (.-spacing sp) :starts (.-starts sp) :maxHold (.-b sp) :system (.-system sp)\n :transform #js {:kind (if (:table opts) \"table\" \"crab\") :k (.-k L) :axis (.-axis L)}})]\n (.then (.countAsync mi #js {}) (fn [_] {:cp L :mi mi})))))))}\n \n ;; ── logic ──\n :receive (fn [{:keys [inlet value state args]}]\n (let [st (if (and state (= args (:sig state))) state (assoc (fresh args) :k (:k state 0)))\n o (opts-of st args)\n {:keys [cp mi]} st]\n (cond\n (= inlet :task)\n (cond (not= (:k (:arg value)) (:k st)) {}\n (:error value) {:state (assoc st :loading false) :show {:main \"comes · crab\" :sub (str \"✗ \" (:error value))}}\n :else (let [{:keys [cp mi]} (:value value)\n st (assoc st :cp cp :mi mi :loading false :M [] :s 0 :pending nil :hist [])]\n (cond (:live args) (if-let [a (:waiting st)] (live-beat cp mi (dissoc st :waiting) a) (live-out cp mi (assoc st :t 0) {:t 0}))\n (:waiting st) (choose cp mi (dissoc st :waiting) (:waiting st))\n :else (at-point cp mi st nil))))\n \n ;; a parameter changed: a new work\n ;; the temperature or the seed: kept, the kernel as it is (a seed starts the game's chance again)\n (and (vector? value) (contains? chance (first value)) (number? (second value)))\n (let [[kk v] value]\n {:state (cond-> (assoc st kk v) (= kk :seed) (assoc :seed0 v))})\n \n (and (vector? value) (contains? params (first value)))\n (let [st (assoc-in st [:over (first value)] (second value))] (load st (opts-of st args)))\n \n (nil? mi)\n (let [a (asked-of value args) st (cond-> st (some? a) (assoc :waiting a))]\n (if (:loading st) {:state st} (load st o)))\n \n ;; live: a pulse is a beat (the note played since the last one, or the box's for you)\n (and (:live args) (= inlet 1))\n (let [a (:struck st)] (live-beat cp mi (assoc st :struck nil :pulsed true) a))\n (and (:live args) (#{:reset} value))\n (update (live-out cp mi (assoc st :M [] :t 0 :s 0 :devs 0 :struck nil :seed (:seed0 st 1)) {:t 0}) :out into [[1 []] [0 []]])\n (and (:live args) (#{:engine :bang} value)) (live-beat cp mi st nil)\n (and (:live args) (#{:back} value)) {:state st}\n (and (:live args) (some? (asked-of value args)))\n (let [a (asked-of value args)] (if (:pulsed st) {:state (assoc st :struck a)} (live-beat cp mi st a)))\n \n (#{:reset} value) (at-point cp mi (assoc st :M [] :s 0 :pending nil :hist []) nil)\n (#{:back} value)\n (cond (some? (:pending st)) (at-point cp mi (assoc st :pending nil) nil)\n (seq (:hist st)) (at-point cp mi (merge st (peek (:hist st)) {:hist (pop (:hist st))}) nil)\n :else {:state st})\n (#{:engine :bang} value)\n (if-let [a (engine cp mi st)] (choose cp mi st a) {:state st})\n \n :else\n (if-let [a (asked-of value args)] (choose cp mi st a) {:state st}))))\n })\n ;; ── the relation: the box's words and what was changed since ([:speed -1], [:inverted true]) ──\n relation (fn [st args]\n (let [o (merge (select-keys args [:speed :inverted]) (select-keys (:over st) [:speed :inverted]))]\n {:speed (:speed o 1) :inverted (boolean (:inverted o))}))\n supported? (fn [{:keys [speed inverted]}] (or (== speed 1) (== speed -1) (and (== speed 0.5) (not inverted))))\n ;; the arguments each engine reads\n fwd-args (fn [args {:keys [speed inverted]}]\n (-> (select-keys args [:system :mode :k :d :beats :imitation :bars :upbeat :temp :seed :fourth :live :nocues :midi])\n (assoc :inversion (and inverted (== speed 1)) :augmentation (== speed 0.5))\n ;; (bars 0: the relation's own length, 8 bars forwards)\n (update :bars #(if (pos? %) % 8))))\n crab-args (fn [args {:keys [inverted]}]\n (-> (select-keys args [:system :mode :k :beats :bars :temp :seed :live :midi]) (assoc :table inverted)\n ;; (6 bars backwards: a crab is counted from both ends, and longer takes longer)\n (update :bars #(if (pos? %) % 6))))]\n {;; ── about ──\n :class \"comes\"\n :license \"MPL-2.0\"\n :doc \"Counterpoint live: you play the dux and the comes answers (Studies 41–46, 50). The comes is a reader of the dux at a speed: 1 a canon (the default), 0.5 an augmentation (twice as slow, a strict canon), −1 a crab (the dux backwards); inverted turns it upside down about the final (or [:axis 62]): an inversion, or with −1 a table canon, the score read from across the table. k steps away (−7 an octave below) and, forwards, d beats late. Each note is checked against the rules of the style — the mode's range, its melodic intervals, consonance on the strong beats, a dissonance passing on a weak one or held as a suspension, no parallel 5ths or octaves… — and against the future: a note from which the work could not be finished is not allowed either, and is corrected to the nearest one that can (a black key too), the box saying why. Forwards (speed 1 or 0.5) you play the dux and the comes answers: by turns (the default) one note in is one beat, the same note again (or :hold) held over it; with live a pulse on the right inlet (a metro) is a beat, a note lasts until the next, a note of three pulses in 2/2 turns the canon to 3/2 and one longer than a bar ends the section (with nocues neither: other boxes decide, with [:beats 3] and :end). With imitation below 1 the comes is chosen by the soft rules: near the dux's notes (0.5–0.9), following its motion (0.2–0.4) or free; with fourth your line is a cantus firmus and the comes syncopated. Backwards (speed −1) the work is written from both ends to the middle: by turns a note at the start, then one at the end; live (Study 46) your note, and at the same beat the box's answer at the end of your own line, a cue two beats before the middle, and at the middle the rest of your line to read (outlet 4) while the box plays your first half backwards. The system (Study 42) is diatonic by default, or meantone, septimal31, pentatonic, or an EDN map; the mode one of its modes; the box's words name them in any order (comes hypodorian, comes pentatonic penta-A -1). Out: the Hz of both voices sounding after their voice ids (outlet 1), for one synth~; the futuribles (outlet 2), the notes that can come next with their futures counted exactly; where the work is (outlet 3); and the finished work as a musical tree (outlet 4), for a tree box. [:speed -1], [:inverted true], [:k -4], [:d 2], [:mode …], [:system …], [:bars 5], [:imitation 0.5], [:beats 3], [:species 4], [:axis 62] change it; :engine, :back, :reset; [:temp 1.5], [:seed 7] its chance. Numbers are Hz (MIDI with midi); a list is the keys held; an event (:freq, or a player's :hz).\"\n :usage \"comes [system] [mode] [speed 1] [k -7] [d 3] [beats 2] [imitation 1] [bars 0] [upbeat 0] [temp 0] [seed 1] [inverted] [fourth] [live] [nocues] [midi]\"\n :io [2 5]\n :size [170 46]\n :args [[:system nil] [:mode nil] [:speed 1] [:k -7] [:d 3] [:beats 2] [:imitation 1] [:bars 0] [:upbeat 0] [:temp 0] [:seed 1]\n [:inverted false] [:fourth false] [:live false] [:nocues false] [:midi false]]\n\n ;; ── tasks: a kernel and its count (forwards), or the mirror's (backwards), outside the pure logic ──\n :tasks {:kernel (:kernel (:tasks fwd)) :mirror (:mirror (:tasks crab))}\n\n ;; ── logic: the relation chooses the engine; each keeps its own state ──\n :receive (fn [{:keys [inlet value state args] :as ctx}]\n (let [st (or state {})\n ;; the relation changed on the way: kept (a new work)\n st (if (and (vector? value) (#{:speed :inverted} (first value)))\n (assoc-in st [:over (first value)] (if (= :inverted (first value)) (boolean (second value)) (second value)))\n st)\n rel (relation st args)\n back? (neg? (:speed rel))]\n (cond\n (not (supported? rel))\n {:state st :show {:main \"comes\" :sub (str \"✗ speed \" (:speed rel) (when (:inverted rel) \" inverted\") \": 1, 0.5 or −1 (inverted: 1 or −1)\")}}\n ;; a task: to the engine that asked for it\n (= inlet :task)\n (let [e (if (= :mirror (:task value)) crab fwd) k (if (= :mirror (:task value)) :crab :fwd)\n a (if (= :mirror (:task value)) (crab-args args rel) (fwd-args args rel))\n r ((:receive e) (assoc ctx :state (get st k) :args a))]\n (cond-> (assoc r :state (assoc st k (:state r (get st k)))) (nil? (:state r)) (dissoc :state)))\n :else\n (let [[e k a] (if back? [crab :crab (crab-args args rel)] [fwd :fwd (fwd-args args rel)])\n ;; a relation message starts the engine again (a new work, its kernel asked for)\n value (if (and (vector? value) (#{:speed :inverted} (first value))) :reset value)\n sub (get st k)\n sub (if (and (= :reset value) (nil? sub)) nil sub)\n r ((:receive e) (assoc ctx :state sub :args a :value value))]\n (assoc r :state (assoc st k (if (contains? r :state) (:state r) sub)))))))\n\n ;; ── view ──\n :derive (fn [{:keys [shown]}]\n {:main (or (:main shown) (if (:dux shown) (str (:dux shown) \" → \" (:comes shown)) \"comes\"))\n :sub (or (:sub shown) (:status shown) \"play the dux\")\n :mark (if (:corrected shown) 4 0)})\n :view [[:rect {:x 2 :y 2 :w 166 :h 42 :r 3 :stroke :grid :fill :bg}]\n [:rect {:x 4 :y 4 :w :$mark :h 38 :r 1 :stroke nil :fill :kairos}]\n [:text {:x 12 :y 20 :size 13} :$main]\n [:text {:x 12 :y 36 :size 9 :fill :soft} :$sub]]})\n"
26
14
  },
27
15
  {
28
16
  "class": "fourier",
@@ -31,7 +31,7 @@
31
31
  "Promise that resolves when kairotic/ringcore.mjs is loaded as a worklet module in this AudioContext."
32
32
  [ac]
33
33
  (or (get @modules ac)
34
- (let [p (.addModule (.-audioWorklet ac) (.-href (js/URL. "kairotic/ringcore.mjs" (.-baseURI js/document))))]
34
+ (let [p (.addModule (.-audioWorklet ac) (.-href (js/URL. "kairotic/ringcore.mjs" (or (.-KAIROTIC_BASE js/window) (.-baseURI js/document)))))]
35
35
  (swap! modules assoc ac p)
36
36
  p)))
37
37
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kairotic/app",
3
- "version": "0.2.2",
3
+ "version": "0.2.3",
4
4
  "description": "The Kairotic app as files, for the claude.ai shell (site/shell.html) that loads it from jsDelivr",
5
5
  "author": "bonuoq",
6
6
  "license": "MPL-2.0",