@kairotic/app 0.0.0-stage → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (96) hide show
  1. package/README.md +9 -2
  2. package/index.html +1101 -0
  3. package/kairotic/api.cljs +362 -0
  4. package/kairotic/assistant.cljs +505 -0
  5. package/kairotic/backends/gun-backend.js +371 -0
  6. package/kairotic/canvas.cljs +751 -0
  7. package/kairotic/code.cljs +108 -0
  8. package/kairotic/components.cljs +838 -0
  9. package/kairotic/core.cljs +96 -0
  10. package/kairotic/corefns.cljs +473 -0
  11. package/kairotic/docs.mjs +2 -0
  12. package/kairotic/engine.cljs +482 -0
  13. package/kairotic/examples.mjs +96 -0
  14. package/kairotic/faust.cljs +225 -0
  15. package/kairotic/help.cljs +1036 -0
  16. package/kairotic/hiccup.cljs +566 -0
  17. package/kairotic/input.cljs +271 -0
  18. package/kairotic/kfile.mjs +138 -0
  19. package/kairotic/library.cljs +214 -0
  20. package/kairotic/links.cljs +41 -0
  21. package/kairotic/mt.cljs +1604 -0
  22. package/kairotic/mtboxes.cljs +276 -0
  23. package/kairotic/packages/analysis.mjs +64 -0
  24. package/kairotic/packages/controls.mjs +28 -0
  25. package/kairotic/packages/data.mjs +22 -0
  26. package/kairotic/packages/faust-units/cmaes.mjs +82 -0
  27. package/kairotic/packages/faust-units/graph.mjs +212 -0
  28. package/kairotic/packages/faust-units/listen.mjs +125 -0
  29. package/kairotic/packages/faust-units/notation.mjs +139 -0
  30. package/kairotic/packages/faust-units/parse.mjs +439 -0
  31. package/kairotic/packages/faust-units/recipe.mjs +195 -0
  32. package/kairotic/packages/faust-units/render.mjs +69 -0
  33. package/kairotic/packages/faust-units/units.mjs +130 -0
  34. package/kairotic/packages/faust-units/view.mjs +353 -0
  35. package/kairotic/packages/faust-units.mjs +9 -0
  36. package/kairotic/packages/io.mjs +58 -0
  37. package/kairotic/packages/net.mjs +28 -0
  38. package/kairotic/packages/patterns.mjs +34 -0
  39. package/kairotic/packages/spatial.mjs +22 -0
  40. package/kairotic/packages/spectral/shift.mjs +169 -0
  41. package/kairotic/packages/spectral.mjs +16 -0
  42. package/kairotic/packages/synth.mjs +28 -0
  43. package/kairotic/packages/theory/counterpoint.mjs +798 -0
  44. package/kairotic/packages/theory/mirror.mjs +221 -0
  45. package/kairotic/packages/theory.mjs +46 -0
  46. package/kairotic/patterns.cljs +538 -0
  47. package/kairotic/presets.cljs +227 -0
  48. package/kairotic/quantize.cljs +782 -0
  49. package/kairotic/record.cljs +169 -0
  50. package/kairotic/release.cljs +90 -0
  51. package/kairotic/ring.cljs +129 -0
  52. package/kairotic/ringaudio.cljs +232 -0
  53. package/kairotic/ringcore.mjs +270 -0
  54. package/kairotic/score.cljs +176 -0
  55. package/kairotic/shapes.cljs +283 -0
  56. package/kairotic/signal.cljs +327 -0
  57. package/kairotic/sounds.cljs +565 -0
  58. package/kairotic/sounds.mjs +108 -0
  59. package/kairotic/span.cljs +129 -0
  60. package/kairotic/spell.cljs +281 -0
  61. package/kairotic/structure.cljs +145 -0
  62. package/kairotic/talk.cljs +115 -0
  63. package/kairotic/tempo.cljs +226 -0
  64. package/kairotic/treecanvas.cljs +299 -0
  65. package/kairotic/tutorials.mjs +1283 -0
  66. package/kairotic/vendor/codemirror.mjs +23 -0
  67. package/package.json +23 -4
  68. package/page/00-work.cljs +862 -0
  69. package/page/01-commands.cljs +1219 -0
  70. package/page/02-patch-view.cljs +1051 -0
  71. package/page/03-history-view.cljs +481 -0
  72. package/page/04-panels.cljs +448 -0
  73. package/page/05-gestures.cljs +1247 -0
  74. package/page/06-connection.cljs +219 -0
  75. package/page/07-claude.cljs +430 -0
  76. package/page/08-sessions.cljs +423 -0
  77. package/page/09-learn.cljs +602 -0
  78. package/page/10-embed.cljs +469 -0
  79. package/page/11-startup.cljs +61 -0
  80. package/page/12-feedback.cljs +172 -0
  81. package/page/13-perform.cljs +325 -0
  82. package/page/14-editor.cljs +656 -0
  83. package/page/15-presets.cljs +230 -0
  84. package/page/16-release.cljs +242 -0
  85. package/page/17-sounds.cljs +147 -0
  86. package/page/18-lines.cljs +594 -0
  87. package/page/19-files.cljs +247 -0
  88. package/page/19-html.cljs +152 -0
  89. package/page/20-talk.cljs +527 -0
  90. package/page/21-net.cljs +110 -0
  91. package/page/22-learn.cljs +303 -0
  92. package/page/23-ids.cljs +233 -0
  93. package/page/24-clipboard.cljs +136 -0
  94. package/page/25-tidy.cljs +74 -0
  95. package/page/26-probes.cljs +111 -0
  96. package/sources.mjs +2 -0
@@ -0,0 +1,221 @@
1
+ // SPDX-License-Identifier: MPL-2.0
2
+ // @kairotic/theory · mirror.mjs, what the cancrizans box writes with: Study 43's mirror kernel as it is (its kernel
3
+ // is counterpoint.mjs). Kairotic · Study 43 · mirrors: canons by transformation, and the order in which a work is written.
4
+ //
5
+ // The comes is the dux transformed (a strict canon), and the transformation is data:
6
+ //
7
+ // canon the dux d beats later, k steps away C[t] = M[t-d] + k
8
+ // inversion the dux upside down about an axis (contrary motion) C[t] = 2·axis − M[t-d] + k
9
+ // augmentation the dux at half speed (each note m beats) C[t] = M[⌊(t-d)/m⌋] + k
10
+ // crab the dux backwards, both voices at once (retrograde) C[t] = M[n-1-t] + k
11
+ // table backwards and upside down: the score read by a second C[t] = 2·axis − M[n-1-t] + k
12
+ // player from across the table (a musical ambigram)
13
+ //
14
+ // The first three can be written from the beginning, a note a beat. A crab or a table canon cannot: the comes at
15
+ // the start is the dux at the end. They are written from both ends towards the middle — each step fixes a note at
16
+ // the start and one at the end — and the futuribles of a point are the ways to close the work in the middle.
17
+ //
18
+ // The rules are Study 42's (kernel.mjs, a system as data): at every time whose window of notes is known, the dux's
19
+ // rules and the pair's are asked, as the kernel asks them going forwards. The futures are counted exactly, memoized
20
+ // on the notes that still bear on a time not yet asked.
21
+ //
22
+ // M the dux, an array of n pitches, undefined where not written yet
23
+ // step how many steps of the order are done; order[step] the positions the next step writes (one or two)
24
+
25
+ import { canon, makeSystem, DIATONIC } from "./counterpoint.mjs"; // (Study 43: "./kernel.mjs")
26
+
27
+ export const KINDS = ["canon", "inversion", "augmentation", "crab", "table"];
28
+
29
+ /**
30
+ * spec: {tonic, lo, hi, n, b, phase, spacing, starts, system, on, maxHold, species,
31
+ * transform: {kind, k, d, axis, m}}
32
+ */
33
+ export function mirror(spec) {
34
+ const tr = { kind: "canon", k: -7, d: 3, m: 2, ...(spec.transform || {}) };
35
+ const { n, lo, hi } = spec;
36
+ const S = makeSystem(spec.system || DIATONIC);
37
+ const kind = KINDS.includes(tr.kind) ? tr.kind : "canon";
38
+ const k = tr.k, m = Math.max(1, Math.round(tr.m || 2));
39
+ const retro = kind === "crab" || kind === "table";
40
+ const inverted = kind === "inversion" || kind === "table";
41
+ const d = retro ? 0 : Math.max(0, tr.d);
42
+ const axis = tr.axis ?? spec.tonic;
43
+ /** The comes's note for a note x of the dux. */
44
+ const T = (x) => (inverted ? 2 * axis - x : x) + k;
45
+ /** Where the comes at time t comes from in the dux (a position), or null before it enters. */
46
+ const source = (t) => {
47
+ if (retro) return n - 1 - t;
48
+ if (t < d) return null;
49
+ return kind === "augmentation" ? Math.floor((t - d) / m) : t - d;
50
+ };
51
+ // the comes's range and starts, the dux's transformed
52
+ const [clo, chi] = [T(lo), T(hi)].sort((a, b) => a - b);
53
+ const starts = spec.starts || [spec.tonic];
54
+ // the rules: Study 42's kernel, with the comes as given (no degree of imitation: it is the transformation)
55
+ const R = canon({ ...spec, k, d, imitation: 0, clo, chi, cstarts: starts.map(T),
56
+ maxHold: spec.maxHold ?? 2 });
57
+ const b = spec.b || 1;
58
+ const L = Math.max((spec.maxHold ?? 2) + 1, b, 2); // how far back the rules look
59
+
60
+ // the order: forwards, or from both ends to the middle
61
+ const order = [];
62
+ if (retro) for (let i = 0; i <= n - 1 - i; i++) order.push(i === n - 1 - i ? [i] : [i, n - 1 - i]);
63
+ else for (let i = 0; i < n; i++) order.push([i]);
64
+ const steps = order.length;
65
+ // after s steps: which positions are written, which times can be asked (their window known), and the
66
+ // positions whose notes still bear on a time not asked yet (the memo's key)
67
+ const known = [new Set()];
68
+ for (let s = 0; s < steps; s++) known.push(new Set([...known[s], ...order[s]]));
69
+ const deps = (t) => {
70
+ const out = [];
71
+ for (let j = Math.max(0, t - L); j <= t; j++) { out.push(j); const q = source(j); if (q !== null) out.push(q); }
72
+ return out;
73
+ };
74
+ const askable = known.map((K) => {
75
+ const out = new Set();
76
+ for (let t = 0; t < n; t++) if (deps(t).every((p) => K.has(p))) out.add(t);
77
+ return out;
78
+ });
79
+ /** The times a step makes askable: their rules are asked when it is written. */
80
+ const newTimes = order.map((_, s) => [...askable[s + 1]].filter((t) => !askable[s].has(t)).sort((x, y) => x - y));
81
+ const bearing = known.map((K, s) => {
82
+ const out = new Set();
83
+ for (let t = 0; t < n; t++) if (!askable[s].has(t)) for (const p of deps(t)) if (K.has(p)) out.add(p);
84
+ return [...out].sort((x, y) => x - y);
85
+ });
86
+
87
+ /** The two voices of a dux (partly written): D = M, C where its source is written. */
88
+ function lines(M) {
89
+ const D = [], C = [];
90
+ for (let t = 0; t < n; t++) {
91
+ D.push(M[t]);
92
+ const q = source(t);
93
+ C.push(q === null ? null : M[q] === undefined ? undefined : T(M[q]));
94
+ }
95
+ return { D, C };
96
+ }
97
+
98
+ /** Why the rules at a time t refuse the work (null when they do not): the dux's, then the pair's. */
99
+ function askAt(D, C, t) {
100
+ const Dp = D.slice(0, t), Cp = C.slice(0, t);
101
+ return R.checkDux(Dp, Cp, D[t]) || R.checkPair(Dp, Cp, D[t], C[t]);
102
+ }
103
+
104
+ /** Why writing vals at step s is refused (null when it is not): the range, then the rules at the new times. */
105
+ function check(M, s, vals) {
106
+ if (s >= steps) return "the work is finished";
107
+ const pos = order[s];
108
+ for (const x of vals) if (x < lo || x > hi) return "out of range";
109
+ if (pos.length === 2 && vals.length === 1) return null; // the first of two: asked with the second
110
+ const M2 = M.slice(); pos.forEach((p, i) => { M2[p] = vals[i]; });
111
+ const { D, C } = lines(M2);
112
+ for (const t of newTimes[s]) { const r = askAt(D, C, t); if (r) return (retro ? `at beat ${t + 1}: ` : "") + r; }
113
+ return null;
114
+ }
115
+
116
+ // ─── the count ───
117
+ const memo = new Map();
118
+ const W = hi - lo + 2;
119
+ const key = (M, s) => { let c = s; for (const p of bearing[s]) c = c * W + (M[p] - lo + 1); return c; };
120
+ function countFrom(M, s) {
121
+ if (s >= steps) return 1;
122
+ const kk = key(M, s), got = memo.get(kk);
123
+ if (got !== undefined) return got;
124
+ let v = 0;
125
+ const pos = order[s];
126
+ if (pos.length === 1) {
127
+ for (let x = lo; x <= hi; x++) if (check(M, s, [x]) === null) { M[pos[0]] = x; v += countFrom(M, s + 1); M[pos[0]] = undefined; }
128
+ } else {
129
+ for (let a = lo; a <= hi; a++) for (let z = lo; z <= hi; z++)
130
+ if (check(M, s, [a, z]) === null) { M[pos[0]] = a; M[pos[1]] = z; v += countFrom(M, s + 1); M[pos[0]] = undefined; M[pos[1]] = undefined; }
131
+ }
132
+ memo.set(kk, v);
133
+ return v;
134
+ }
135
+ const blank = () => new Array(n).fill(undefined);
136
+ /** The ways to finish the work after s steps (M as written so far), exact. */
137
+ const count = (M = blank(), s = 0) => countFrom(M.slice(), s);
138
+ /** The count from the start a few milliseconds at a time (the browser stays free); resolves to it. */
139
+ function countAsync({ budget = 12, onProgress, cancelled } = {}) {
140
+ return new Promise((resolve) => {
141
+ // warm the memo bottom-up from the deepest steps: each pass counts what it can within its budget
142
+ const M = blank();
143
+ const stack = [{ s: 0, opts: null, i: 0, sum: 0 }];
144
+ const optsAt = (s) => {
145
+ const pos = order[s], out = [];
146
+ if (pos.length === 1) { for (let x = lo; x <= hi; x++) if (check(M, s, [x]) === null) out.push([x]); }
147
+ else for (let a = lo; a <= hi; a++) for (let z = lo; z <= hi; z++) if (check(M, s, [a, z]) === null) out.push([a, z]);
148
+ return out;
149
+ };
150
+ stack[0].opts = optsAt(0); stack[0].kk = key(M, 0);
151
+ let ticks = 0;
152
+ function step() {
153
+ if (cancelled && cancelled()) return resolve(null);
154
+ const end = performance.now() + budget;
155
+ while (stack.length) {
156
+ if ((++ticks & 63) === 0 && performance.now() > end) {
157
+ if (onProgress) { let fr = 0, w = 1; for (const f of stack) { w /= Math.max(1, f.opts.length); fr += Math.max(0, f.i - 1) * w; } onProgress(Math.min(1, fr), memo.size); }
158
+ setTimeout(step, 0); return;
159
+ }
160
+ const f = stack[stack.length - 1];
161
+ if (f.i >= f.opts.length) {
162
+ memo.set(f.kk, f.sum); stack.pop();
163
+ if (!stack.length) return resolve(f.sum);
164
+ for (const p of order[f.s - 1]) M[p] = undefined;
165
+ stack[stack.length - 1].sum += f.sum; continue;
166
+ }
167
+ const vals = f.opts[f.i++];
168
+ order[f.s].forEach((p, i) => { M[p] = vals[i]; });
169
+ const s2 = f.s + 1;
170
+ if (s2 >= steps) { f.sum += 1; for (const p of order[f.s]) M[p] = undefined; continue; }
171
+ const kk = key(M, s2), got = memo.get(kk);
172
+ if (got !== undefined) { f.sum += got; for (const p of order[f.s]) M[p] = undefined; continue; }
173
+ stack.push({ s: s2, opts: optsAt(s2), i: 0, sum: 0, kk });
174
+ }
175
+ }
176
+ if (steps === 0) return resolve(1);
177
+ step();
178
+ });
179
+ }
180
+
181
+ /** The candidates for the first note of step s: {note, reason} or {note, futures} (over the second, if two). */
182
+ function fan(M, s) {
183
+ const out = [], pos = order[s];
184
+ if (!pos) return out;
185
+ for (let x = lo; x <= hi; x++) {
186
+ if (pos.length === 1) {
187
+ const r = check(M, s, [x]);
188
+ if (r) { out.push({ note: x, reason: r }); continue; }
189
+ const M2 = M.slice(); M2[pos[0]] = x;
190
+ out.push({ note: x, reason: null, futures: count(M2, s + 1) });
191
+ } else {
192
+ let fut = 0, why = null, fits = 0;
193
+ for (let z = lo; z <= hi; z++) {
194
+ const r = check(M, s, [x, z]);
195
+ if (r) { why = why || r; continue; }
196
+ fits++;
197
+ const M2 = M.slice(); M2[pos[0]] = x; M2[pos[1]] = z; fut += count(M2, s + 1);
198
+ }
199
+ out.push(fits ? { note: x, reason: null, futures: fut } : { note: x, reason: `no note at beat ${pos[1] + 1} fits: ${why}` });
200
+ }
201
+ }
202
+ return out;
203
+ }
204
+ /** The candidates for the second note of step s (at the end), the first being a. */
205
+ function fanSecond(M, s, a) {
206
+ const pos = order[s], out = [];
207
+ for (let z = lo; z <= hi; z++) {
208
+ const r = check(M, s, [a, z]);
209
+ if (r) { out.push({ note: z, reason: r }); continue; }
210
+ const M2 = M.slice(); M2[pos[0]] = a; M2[pos[1]] = z;
211
+ out.push({ note: z, reason: null, futures: count(M2, s + 1) });
212
+ }
213
+ return out;
214
+ }
215
+
216
+ return { spec, kind, n, k, d, m, axis, retro, inverted, order, steps, source, T, lines, check, count, countAsync, fan,
217
+ fanSecond, rules: R, system: S, newTimes, bearing, memo, roles: (D, C) => R.roles(D, C) };
218
+ }
219
+
220
+ // api/import-module hands a component the default export
221
+ export default { mirror, KINDS };
@@ -0,0 +1,46 @@
1
+ // Generated by packages/build.mjs
2
+ export default {
3
+ "package": "@kairotic/theory",
4
+ "version": "0.11.0",
5
+ "api": 1,
6
+ "author": "bonuoq",
7
+ "license": "MPL-2.0",
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
+ {
16
+ "class": "comes",
17
+ "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"
26
+ },
27
+ {
28
+ "class": "fourier",
29
+ "license": "MPL-2.0",
30
+ "doc": "The six Fourier coefficients of what sounds, from its pitch classes: f1 chromatic, f2 dyadic, f3 triadic, f4 octatonic, f5 diatonic, f6 whole-tone — how close it is to dividing the octave evenly in 1…6 parts. A list of pitches (Hz, as a keyboard or midiin sends them; MIDI or 0…11 with midi) or of 12 weights (a chroma, from chroma~), or a number as a note (the last n notes count: 4); :clear empties it. Each coefficient is drawn as a point in its circle with its trail; their magnitudes (0…1) go out on the left, their phases (degrees) on the right.",
31
+ "source": ";; fourier · the six Fourier coefficients of a pitch-class distribution\n;; Part of @kairotic/theory. Written against the Kairotic API (api/…).\n;; The DFT of the weights of the twelve pitch classes (Lewin, Quinn, Amiot, Yust): coefficient k measures\n;; how close what sounds is to the even division of the octave in k parts — f1 chromatic, f2 dyadic\n;; (tritones), f3 triadic (augmented), f4 octatonic (diminished), f5 diatonic, f6 whole-tone. Each is a\n;; point inside its circle (magnitude, 0…1, and phase), with its trail over the last changes.\n(let [TAU (* 2 js/Math.PI)\n labels [\"chromatic\" \"dyadic\" \"triadic\" \"octatonic\" \"diatonic\" \"whole-tone\"]\n trail-max 48\n ;; what arrives as pitches: Hz (a keyboard, midiin, a player, pitch~), or MIDI (or 0…11) with the word midi;\n ;; a chroma (12 values between 0 and 1) as it is. 0 Hz (a silence) is nothing\n as-pitches (fn [args v]\n (let [hz->m (fn [x] (when (and (number? x) (pos? x)) (+ 69 (* 12 (/ (js/Math.log (/ x 440)) (js/Math.log 2))))))\n chroma? (fn [xs] (and (= 12 (count xs)) (every? (fn [x] (and (number? x) (<= 0 x 1))) xs)))]\n (cond (some #{:midi} args) v\n (number? v) (hz->m v)\n (and (sequential? v) (seq v) (every? number? v) (not (chroma? v))) (vec (keep hz->m v))\n :else v)))\n notes-of (fn [args] (api/clamp (or (first (filter number? args)) 4) 1 24))\n weights (fn [xs]\n (let [w (vec (repeat 12 0))]\n (if (and (= 12 (count xs)) (every? (fn [x] (and (number? x) (<= 0 x 1))) xs))\n (vec xs)\n (reduce (fn [w x] (if (number? x) (update w (mod (js/Math.round x) 12) + 1) w)) w xs))))\n ;; [re im] of each coefficient 1…6, divided by the total weight (so a single class has magnitude 1)\n dft (fn [w]\n (let [tot (reduce + w)]\n (vec (for [k (range 1 7)]\n (if (pos? tot)\n [(/ (reduce + (map-indexed (fn [p x] (* x (js/Math.cos (/ (* TAU k p) 12)))) w)) tot)\n (- (/ (reduce + (map-indexed (fn [p x] (* x (js/Math.sin (/ (* TAU k p) 12)))) w)) tot))]\n [0 0])))))\n mag (fn [[a b]] (js/Math.hypot a b))\n r3 (fn [x] (/ (js/Math.round (* 1000 x)) 1000))]\n {;; ── about ──\n :class \"fourier\"\n :license \"MPL-2.0\"\n :doc \"The six Fourier coefficients of what sounds, from its pitch classes: f1 chromatic, f2 dyadic, f3 triadic, f4 octatonic, f5 diatonic, f6 whole-tone — how close it is to dividing the octave evenly in 1…6 parts. A list of pitches (Hz, as a keyboard or midiin sends them; MIDI or 0…11 with midi) or of 12 weights (a chroma, from chroma~), or a number as a note (the last n notes count: 4); :clear empties it. Each coefficient is drawn as a point in its circle with its trail; their magnitudes (0…1) go out on the left, their phases (degrees) on the right.\"\n :usage \"fourier [notes] [midi]\"\n :io [1 2]\n :size [300 214]\n\n ;; ── logic ──\n :receive (fn [{:keys [value state args]}]\n (let [value (as-pitches args value)\n st (or state {:notes [] :f (vec (repeat 6 [0 0])) :trail (vec (repeat 6 []))})\n send (fn [st w]\n (let [f (dft w)\n st (assoc st :f f :trail (mapv (fn [t p] (vec (take-last trail-max (conj t p)))) (:trail st) f))]\n {:state st :show st\n :out [[1 (mapv (fn [[a b]] (r3 (* (/ 180 js/Math.PI) (js/Math.atan2 (- b) a)))) f)]\n [0 (mapv (fn [p] (r3 (mag p))) f)]]}))]\n (cond\n (#{:clear} value) {:state nil :show nil}\n (number? value) (let [ns (vec (take-last (notes-of args) (conj (:notes st) value)))]\n (send (assoc st :notes ns) (weights ns)))\n (and (sequential? value) (seq value) (every? number? value)) (send (assoc st :notes []) (weights value))\n :else {})))\n\n ;; ── view ──\n :draw (fn [{:keys [shown w h]}]\n (let [cw (/ w 3) R (- (min (/ cw 2) (/ (- h 10) 4)) 12)]\n (apply concat\n (for [k (range 6)]\n (let [cx (+ (/ cw 2) (* cw (mod k 3))) cy (+ 14 R (* (quot k 3) (/ (- h 6) 2)))\n f (get-in shown [:f k] [0 0])\n pt (fn [[a b]] [(+ cx (* R a)) (+ cy (* R b))])\n [x y] (pt f)]\n [[:circle {:cx cx :cy cy :r R :stroke :grid}]\n [:line {:x1 (- cx R) :y1 cy :x2 (+ cx R) :y2 cy :stroke :grid :weight 0.6}]\n [:curve {:points (mapv pt (get-in shown [:trail k] [])) :stroke :accent :weight 1.2 :opacity 0.45}]\n [:line {:x1 cx :y1 cy :x2 x :y2 y :stroke :accent :weight 1.6}]\n [:circle {:cx x :cy y :r 3.4 :fill :accent :stroke nil}]\n [:text {:x (- cx R) :y (- cy R 3) :size 9 :fill :ink} (str \"f\" (inc k))]\n [:text {:x (+ cx R) :y (- cy R 3) :anchor :end :size 8 :fill :soft} (.toFixed (mag f) 2)]\n [:text {:x cx :y (+ cy R 11) :anchor :middle :size 8 :fill :soft} (nth labels k)]])))))})\n"
32
+ },
33
+ {
34
+ "class": "pcclock",
35
+ "license": "MPL-2.0",
36
+ "doc": "A pitch-class set on the clock face: the twelve classes around a circle, C at the top. A list of pitches (Hz, as a keyboard or midiin sends them; MIDI or 0…11 with midi) is the set; a list of 12 values between 0 and 1 is a chroma (from chroma~), and its classes above 0.5 are the set; a number is a note, and the last n notes (4) are the set; :clear empties it. It draws the set as a polygon (the sets before it fading behind) and its axes of symmetry by inversion, and sends its prime form (left) and its interval vector (middle) when it changes. Pressing a pitch class sends it (right).",
37
+ "source": ";; pcclock · a pitch-class set on the clock face\n;; Part of @kairotic/theory. Written against the Kairotic API (api/…).\n;; The twelve pitch classes around a circle (C at the top, clockwise by semitones). What arrives is drawn\n;; as a polygon, with the sets before it fading behind, and the axes about which it is symmetric by\n;; inversion. Its prime form and interval vector go out; pressing a pitch class sends it.\n(let [names [\"C\" \"C♯\" \"D\" \"E♭\" \"E\" \"F\" \"F♯\" \"G\" \"A♭\" \"A\" \"B♭\" \"B\"]\n TAU (* 2 js/Math.PI)\n ;; what arrives as pitches: Hz (a keyboard, midiin, a player, pitch~), or MIDI (or 0…11) with the word midi;\n ;; a chroma (12 values between 0 and 1) as it is. 0 Hz (a silence) is nothing\n as-pitches (fn [args v]\n (let [hz->m (fn [x] (when (and (number? x) (pos? x)) (+ 69 (* 12 (/ (js/Math.log (/ x 440)) (js/Math.log 2))))))\n chroma? (fn [xs] (and (= 12 (count xs)) (every? (fn [x] (and (number? x) (<= 0 x 1))) xs)))]\n (cond (some #{:midi} args) v\n (number? v) (hz->m v)\n (and (sequential? v) (seq v) (every? number? v) (not (chroma? v))) (vec (keep hz->m v))\n :else v)))\n notes-of (fn [args] (api/clamp (or (first (filter number? args)) 4) 1 24))\n ;; what arrives, as a weight for each pitch class: a list of 12 values between 0 and 1 is a chroma\n ;; (from chroma~), any other list are pitches (Hz, as a keyboard or midiin sends them; MIDI or 0…11 with midi)\n weights (fn [xs]\n (let [w (vec (repeat 12 0))]\n (if (and (= 12 (count xs)) (every? (fn [x] (and (number? x) (<= 0 x 1))) xs))\n (mapv (fn [x] (if (> x 0.5) x 0)) xs)\n (reduce (fn [w x] (if (number? x) (update w (mod (js/Math.round x) 12) + 1) w)) w xs))))\n pcset (fn [w] (vec (keep-indexed (fn [i x] (when (pos? x) i)) w)))\n ivec (fn [s] (let [c (frequencies (for [a s b s :when (< a b)] (let [d (mod (- b a) 12)] (min d (- 12 d)))))]\n (mapv (fn [k] (get c k 0)) (range 1 7))))\n rotations (fn [s] (let [s (vec (sort s)) n (count s)]\n (for [i (range n)] (vec (concat (subvec s i) (map (fn [x] (+ x 12)) (subvec s 0 i)))))))\n zeroed (fn [r] (mapv (fn [x] (- x (first r))) r))\n ;; the most packed rotation, of the set or of its inversion (Rahn): smallest span, then from the right\n prime (fn [s] (when (seq s)\n (reduce (fn [a b] (if (neg? (compare [(peek b) (vec (rseq b))] [(peek a) (vec (rseq a))])) b a))\n (map zeroed (concat (rotations s) (rotations (map (fn [x] (mod (- 12 x) 12)) s)))))))\n axes (fn [s] (let [ss (set s)] (vec (for [n (range 12) :when (and (seq s) (= ss (set (map (fn [x] (mod (- n x) 12)) s))))] n))))\n polar (fn [cx cy r p] (let [a (* p (/ TAU 12))] [(+ cx (* r (js/Math.sin a))) (- cy (* r (js/Math.cos a)))]))\n ;; the state: the last notes (numbers), the weights shown, and the sets before (for the trail)\n show-of (fn [st w] (let [s (pcset w)\n trail (vec (take-last 4 (if (and (seq (:set st)) (not= s (:set st))) (conj (:trail st []) (:set st)) (:trail st []))))]\n (assoc st :w w :set s :trail trail)))]\n {;; ── about ──\n :class \"pcclock\"\n :license \"MPL-2.0\"\n :doc \"A pitch-class set on the clock face: the twelve classes around a circle, C at the top. A list of pitches (Hz, as a keyboard or midiin sends them; MIDI or 0…11 with midi) is the set; a list of 12 values between 0 and 1 is a chroma (from chroma~), and its classes above 0.5 are the set; a number is a note, and the last n notes (4) are the set; :clear empties it. It draws the set as a polygon (the sets before it fading behind) and its axes of symmetry by inversion, and sends its prime form (left) and its interval vector (middle) when it changes. Pressing a pitch class sends it (right).\"\n :usage \"pcclock [notes] [midi]\"\n :io [1 3]\n :size [200 222]\n\n ;; ── logic ──\n :receive (fn [{:keys [value state args]}]\n (let [value (as-pitches args value)\n st (or state {:notes [] :w (vec (repeat 12 0)) :set [] :trail []})\n send (fn [st2] (let [s (:set st2)]\n {:state st2 :show st2\n :out (if (= s (:set st)) [] [[1 (ivec s)] [0 (or (prime s) [])]])}))]\n (cond\n (and (vector? value) (= :pressed (first value)) (number? (second value))) {:out [[2 (second value)]]}\n (#{:clear} value) (send (show-of (assoc st :notes []) (vec (repeat 12 0))))\n (number? value) (let [ns (vec (take-last (notes-of args) (conj (:notes st) value)))]\n (send (show-of (assoc st :notes ns) (weights ns))))\n (and (sequential? value) (every? number? value)) (send (show-of (assoc st :notes []) (weights value)))\n :else {})))\n\n ;; ── view ──\n :draw (fn [{:keys [shown w h]}]\n (let [cx (/ w 2) cy (/ (- h 26) 2) R (- (min cx cy) 22)\n wt (or (:w shown) (repeat 12 0)) s (or (:set shown) []) mx (reduce max 1e-9 wt)\n pf (prime s)]\n (concat\n [[:circle {:cx cx :cy cy :r R :stroke :grid}]]\n (for [[i t] (map-indexed vector (:trail shown)) :when (> (count t) 1)]\n [:path {:points (mapv (fn [p] (polar cx cy R p)) t) :closed true :stroke :accent :weight 1 :opacity (* 0.14 (inc i))}])\n (for [n (axes s)]\n (let [[x1 y1] (polar cx cy (+ R 14) (/ n 2)) [x2 y2] (polar cx cy (+ R 14) (+ 6 (/ n 2)))]\n [:line {:x1 x1 :y1 y1 :x2 x2 :y2 y2 :stroke :kairos :weight 1 :opacity 0.8}]))\n (when (> (count s) 1) [[:path {:points (mapv (fn [p] (polar cx cy R p)) s) :closed true :stroke :accent :weight 2}]])\n (for [p (range 12)]\n (let [[x y] (polar cx cy R p) [lx ly] (polar cx cy (+ R 13) p) v (nth wt p 0) on (pos? v)]\n [:group {:hit p}\n [[:circle {:cx x :cy y :r (if on (+ 3.5 (* 3.5 (/ v mx))) 3.5) :fill (if on :accent :bg) :stroke (if on :accent :soft)}]\n [:text {:x lx :y (+ ly 3.5) :anchor :middle :size 9 :fill (if on :ink :soft)} (nth names p)]]]))\n [[:text {:x cx :y (- h 14) :anchor :middle :size 9 :fill :ink}\n (if (seq s) (str \"(\" (apply str (map (fn [x] (case x 10 \"t\" 11 \"e\" (str x))) pf)) \") <\" (apply str (ivec s)) \">\") \"—\")]\n [:text {:x cx :y (- h 3) :anchor :middle :size 8 :fill :soft}\n (let [n (count (axes s))] (cond (empty? s) \"no set\" (zero? n) \"asymmetric\" (= 1 n) \"1 axis\" :else (str n \" axes\")))]])))\n ;; pressing a pitch class: sent once, on release\n :gesture (fn [{:keys [up hit]}] (when (and up (number? hit)) [:pressed hit]))})\n"
38
+ },
39
+ {
40
+ "class": "tonnetz",
41
+ "license": "MPL-2.0",
42
+ "doc": "Triads on the Tonnetz: pitch classes on a lattice of fifths (to the right) and major and minor thirds (up), where a major or minor triad is a triangle and the neo-Riemannian moves P, L and R cross an edge. A list of pitches (Hz, as a keyboard or midiin sends them; MIDI or 0…11 with midi) or of 12 weights (a chroma, above 0.5), or a number as a note (the last n notes count: 3); :clear forgets the path. It lights what sounds, fills the triads it contains and joins the triad found to the ones before (the path of the harmony, up to 24 steps). The triad goes out on the left when it changes (:C, :am…); pressing a node sends its pitch class (right).",
43
+ "source": ";; tonnetz · triads on the Tonnetz, and the path of the harmony\n;; Part of @kairotic/theory. Written against the Kairotic API (api/…).\n;; Pitch classes on a triangular lattice: fifths to the right, major thirds up and to the right, minor\n;; thirds up and to the left. A major or minor triad is a triangle; moving between triads that share two\n;; notes (the neo-Riemannian P, L and R) is crossing an edge. What sounds lights its nodes, fills the\n;; triads it contains, and the triad found is joined to the ones before: the path of the harmony, placed\n;; at each step on the copy nearest the last (the lattice repeats). Pressing a node sends its class.\n(let [names [\"C\" \"C♯\" \"D\" \"E♭\" \"E\" \"F\" \"F♯\" \"G\" \"A♭\" \"A\" \"B♭\" \"B\"]\n kws [:C :C# :D :Eb :E :F :F# :G :Ab :A :Bb :B]\n I (range -4 5) J (range -2 3)\n path-max 24\n ;; what arrives as pitches: Hz (a keyboard, midiin, a player, pitch~), or MIDI (or 0…11) with the word midi;\n ;; a chroma (12 values between 0 and 1) as it is. 0 Hz (a silence) is nothing\n as-pitches (fn [args v]\n (let [hz->m (fn [x] (when (and (number? x) (pos? x)) (+ 69 (* 12 (/ (js/Math.log (/ x 440)) (js/Math.log 2))))))\n chroma? (fn [xs] (and (= 12 (count xs)) (every? (fn [x] (and (number? x) (<= 0 x 1))) xs)))]\n (cond (some #{:midi} args) v\n (number? v) (hz->m v)\n (and (sequential? v) (seq v) (every? number? v) (not (chroma? v))) (vec (keep hz->m v))\n :else v)))\n notes-of (fn [args] (api/clamp (or (first (filter number? args)) 3) 1 24))\n pcs-of (fn [xs]\n (if (and (= 12 (count xs)) (every? (fn [x] (and (number? x) (<= 0 x 1))) xs))\n (set (keep-indexed (fn [i x] (when (> x 0.5) i)) xs))\n (set (map (fn [x] (mod (js/Math.round x) 12)) (filter number? xs)))))\n node-pc (fn [i j] (mod (+ (* 7 i) (* 4 j)) 12))\n ;; the triangles of the lattice in unit coordinates: [kind root nodes]\n tris (vec (for [i I j J [kind ns] [[:major [[i j] [(inc i) j] [i (inc j)]]] [:minor [[(inc i) j] [i (inc j)] [(inc i) (inc j)]]]]\n :when (every? (fn [[a b]] (and (<= -4 a 4) (<= -2 b 2))) ns)]\n {:kind kind :nodes ns :pcs (set (map (fn [[a b]] (node-pc a b)) ns))\n :root (if (= kind :major) (node-pc i j) (node-pc i (inc j)))}))\n uxy (fn [[i j]] [(+ i (/ j 2)) (* j 0.8660254)])\n centre (fn [t] (let [ps (map uxy (:nodes t))] [(/ (reduce + (map first ps)) 3) (/ (reduce + (map second ps)) 3)]))\n d2 (fn [[a b] [c d]] (+ (* (- a c) (- a c)) (* (- b d) (- b d))))\n triad-of (fn [t] (if (= :major (:kind t)) (nth kws (:root t)) (keyword (str (str/lower-case (name (nth kws (:root t)))) \"m\"))))\n ;; the triad inside the set nearest the last one (or the centre), or nil\n find-triad (fn [s prev]\n (first (sort-by (fn [t] (d2 (centre t) (or prev [0 0])))\n (filter (fn [t] (every? s (:pcs t))) tris))))]\n {;; ── about ──\n :class \"tonnetz\"\n :license \"MPL-2.0\"\n :doc \"Triads on the Tonnetz: pitch classes on a lattice of fifths (to the right) and major and minor thirds (up), where a major or minor triad is a triangle and the neo-Riemannian moves P, L and R cross an edge. A list of pitches (Hz, as a keyboard or midiin sends them; MIDI or 0…11 with midi) or of 12 weights (a chroma, above 0.5), or a number as a note (the last n notes count: 3); :clear forgets the path. It lights what sounds, fills the triads it contains and joins the triad found to the ones before (the path of the harmony, up to 24 steps). The triad goes out on the left when it changes (:C, :am…); pressing a node sends its pitch class (right).\"\n :usage \"tonnetz [notes] [midi]\"\n :io [1 2]\n :size [380 230]\n\n ;; ── logic ──\n :receive (fn [{:keys [value state args]}]\n (let [value (as-pitches args value)\n st (or state {:notes [] :pcs #{} :path [] :triad nil})\n step (fn [st s]\n (let [prev (when-let [t (peek (:path st))] (centre t))\n t (find-triad s prev)\n st (cond-> (assoc st :pcs s :triad t)\n (and t (not= t (peek (:path st)))) (update :path (fn [p] (vec (take-last path-max (conj p t))))))]\n {:state st :show st\n :out (if (and t (not= (:triad-name st) (triad-of t))) [[0 (triad-of t)]] [])}))\n named (fn [r] (if-let [t (get-in r [:state :triad])] (assoc-in r [:state :triad-name] (triad-of t)) r))]\n (cond\n (and (vector? value) (= :pressed (first value)) (number? (second value))) {:out [[1 (second value)]]}\n (#{:clear} value) {:state nil :show nil}\n (number? value) (let [ns (vec (take-last (notes-of args) (conj (:notes st) value)))]\n (named (step (assoc st :notes ns) (pcs-of ns))))\n (and (sequential? value) (every? number? value)) (named (step (assoc st :notes []) (pcs-of value)))\n :else {})))\n\n ;; ── view ──\n :draw (fn [{:keys [shown w h]}]\n (let [U (min (/ (- w 24) 10) (/ (- h 40) 3.6)) cx (/ w 2) cy (/ (- h 18) 2)\n xy (fn [[ux uy]] [(+ cx (* U ux)) (- cy (* U uy))])\n node (fn [i j] (xy (uxy [i j])))\n on (or (:pcs shown) #{}) path (:path shown []) cur (:triad shown)]\n (concat\n (for [i I j J [di dj] [[1 0] [0 1] [-1 1]]\n :let [a (+ i di) c (+ j dj)] :when (and (<= -4 a 4) (<= -2 c 2))]\n (let [[x1 y1] (node i j) [x2 y2] (node a c)] [:line {:x1 x1 :y1 y1 :x2 x2 :y2 y2 :stroke :grid :weight 1}]))\n (for [t tris :when (every? on (:pcs t))]\n [:path {:points (mapv (fn [n] (xy (uxy n))) (:nodes t)) :closed true :fill (if (= :major (:kind t)) :accent :kairos) :stroke nil :opacity 0.25}])\n (when cur [[:path {:points (mapv (fn [n] (xy (uxy n))) (:nodes cur)) :closed true :stroke (if (= :major (:kind cur)) :accent :kairos) :weight 2}]])\n (when (> (count path) 1) [[:curve {:points (mapv (fn [t] (xy (centre t))) path) :stroke :ink :weight 1.2 :opacity 0.6}]])\n (for [[k t] (map-indexed vector path)]\n (let [[x y] (xy (centre t))] [:circle {:cx x :cy y :r 2 :fill :ink :stroke nil :opacity (if (= k (dec (count path))) 1 0.45)}]))\n (for [i I j J]\n (let [[x y] (node i j) p (node-pc i j) lit (on p) r (* 0.26 U)]\n [:group {:hit p}\n [[:circle {:cx x :cy y :r r :fill (if lit :accent :bg) :stroke (if lit :accent :grid)}]\n [:text {:x x :y (+ y 3.2) :anchor :middle :size (max 7 (* 0.22 U)) :fill (if lit :bg :soft)} (nth names p)]]]))\n [[:text {:x 8 :y (- h 5) :size 9 :fill :ink}\n (if cur (str (name (triad-of cur)) \" · \" (count path) (if (= 1 (count path)) \" triad\" \" triads\") \" on the path\") \"no triad\")]])))\n ;; pressing a node: its pitch class, sent once, on release\n :gesture (fn [{:keys [up hit]}] (when (and up (number? hit)) [:pressed hit]))})\n"
44
+ }
45
+ ]
46
+ };