@kairotic/rhythm 0.1.1 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +60 -41
- package/dist/chance.mjs +9 -0
- package/dist/euclid.mjs +3 -3
- package/dist/homometric.mjs +9 -0
- package/dist/index.mjs +23 -5
- package/dist/necklace.mjs +3 -3
- package/dist/swap.mjs +9 -0
- package/package.json +6 -3
- package/src/chance.cljs +48 -0
- package/src/euclid.cljs +31 -131
- package/src/homometric.cljs +56 -0
- package/src/necklace.cljs +34 -9
- package/src/swap.cljs +69 -0
package/README.md
CHANGED
|
@@ -5,54 +5,73 @@
|
|
|
5
5
|
Rhythm as geometry, after Godfried Toussaint (*The Geometry of Musical Rhythm*; discussion
|
|
6
6
|
[#252](https://github.com/bonuoq/kairotic/discussions/252)). A rhythm that repeats is a **necklace**: k onsets among n
|
|
7
7
|
pulses around a circle — the same object as a pitch-class set on `pcclock` (in `@kairotic/theory`), measured with the
|
|
8
|
-
same geometry.
|
|
8
|
+
same geometry.
|
|
9
9
|
|
|
10
|
-
|
|
10
|
+
The package separates **making** a rhythm from **being** one. **Pulses** — ones and zeros, `[1 0 0 1 0 0 1 0]` — are
|
|
11
|
+
the common tongue of its boxes, as Hz are of pitch: generators make them, and the `necklace` holds them, draws them,
|
|
12
|
+
is their editor, measures them and writes them as music.
|
|
13
|
+
|
|
14
|
+
| Class | What it does |
|
|
11
15
|
|---|---|
|
|
12
|
-
| `euclid [k 3] [n 8] [rotation 0]
|
|
13
|
-
| `necklace [n 16] [bars 1] [midi]` | **
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
`euclid` keeps **rhythm apart from pitch**, as the `:rtm` of a musical tree does (see *Musical trees*,
|
|
19
|
-
`docs/mt.md`): the rhythm goes out as `[:rtm {:shares [3 3 2]}]`, the intervals between onsets as shares (a
|
|
20
|
-
negative share is a silence, as when a rotation leaves the first pulses empty), in a bar of n pulses (4/4 for
|
|
21
|
-
8 or 16, 12/8 for 12, n/8 up to 12, else n/16; `[:meter "3/4"]` for another). Its **right inlet** (cold) takes the
|
|
22
|
-
pitches its notes take in turn, starting again when they run out — *talea* and *color*: a map with `:pitches`
|
|
23
|
-
or `:pitch` (kept as it is), a pattern (`{:note [...]}`), a melody string, a list of Hz
|
|
24
|
-
(the keys held on a keyboard; MIDI with `midi`), notes or chords of a tree; `:clear` forgets them. With `bars`
|
|
25
|
-
the color goes on from bar to bar. Its middle outlet is the `:rtm` map alone, so any map of pitches can be
|
|
26
|
-
merged with it elsewhere (`merge`, then `vector :rtm %`). A bang sends it; `[:k 5]`, `[:n 16]`, `[:rotation 2]`,
|
|
27
|
-
`[:bars 4]`, `[:meter "3/4"]` (or one map of them) change it and send it when it is new; a number is k.
|
|
16
|
+
| `euclid [k 3] [n 8] [rotation 0]` | **a generator**: a Euclidean rhythm (Bjorklund's algorithm, after Toussaint) as pulses — k onsets as evenly as they can be over n pulses: `euclid 3 8` the tresillo, `5 8` the cinquillo, `5 16 6` the bossa nova, `7 12` the bembé. No view of its own: a bang sends the pulses; `[:k 5]`, `[:n 16]`, `[:rotation 6]` (or a map) change them, a number is k |
|
|
17
|
+
| `necklace [n 16] [bars 1] [midi] [fourier]` | **the rhythm box**: takes a rhythm in any notation, draws it on the circle with its axes of symmetry, lets you edit it (pressing a pulse adds or takes away an onset), sends its **measures** (interval vector, evenness, deep, flat, axes, gap, oddity, the rotation of E(k,n) it is, Fourier coefficients) and writes it as a **musical tree** with the pitches of its right inlet |
|
|
18
|
+
| `chance [k 3] [n 8] [seed 1]` | **a generator**: k onsets among n pulses drawn with a seed — each bang another rhythm, the same seed the same rhythms in the same order (in a room, from the history); `:reset` starts them again |
|
|
19
|
+
| `homometric` | **a generator from a rhythm**: the other rhythms with the same interval vector, not the same necklace turned or in a mirror (the two flat rhythms of 4 in 12; a half of an even cycle and its complement) — a list of pulses, and how many |
|
|
20
|
+
| `swap` | **how far apart two rhythms are** (Toussaint's swap distance): the left one against the right one (the reference, cold) — in the bar, around the circle, and as necklaces at the best rotation; with the Hamming distance beside it, and the directed swap distance when they hold different numbers of onsets |
|
|
28
21
|
|
|
29
22
|
```clojure
|
|
30
|
-
(box :b1 "msg :
|
|
31
|
-
(box :b2 "
|
|
32
|
-
(box :b3 "
|
|
33
|
-
(box :b4 "tree"
|
|
34
|
-
(
|
|
23
|
+
(box :b1 "msg [:rotation 6]" 40 20)
|
|
24
|
+
(box :b2 "euclid 5 16" 40 60)
|
|
25
|
+
(box :b3 "necklace fourier" 40 100)
|
|
26
|
+
(box :b4 "tree" 260 100)
|
|
27
|
+
(box :b5 "print" 40 420)
|
|
28
|
+
(connect :b1 0 :b2 0) (connect :b2 0 :b3 0) (connect :b3 0 :b4 0) (connect :b3 3 :b5 0)
|
|
35
29
|
```
|
|
36
30
|
|
|
37
|
-
|
|
31
|
+
## necklace
|
|
38
32
|
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
scale), **flat** when each occurs once. `:axes` are its axes of mirror symmetry (in pulses), `:gap` its longest
|
|
45
|
-
interval, `:oddity` true when no two onsets halve the cycle, and `:euclid` the rotation of E(k,n) it is (or nil).
|
|
46
|
-
It is an editor too: pressing a pulse (or a number, its index), `:complement`, `[:rotate 1]`, `[:n 12]`, `:clear`.
|
|
47
|
-
Its outlets are `euclid`'s, so either can feed the same trees and pitches; a necklace after a `euclid` names what
|
|
48
|
-
the euclid made:
|
|
33
|
+
**In (left)**: pulses (`euclid`'s outlet), intervals between onsets (`[3 3 2]`), box notation (`"x..x..x."`), an `:rtm`
|
|
34
|
+
map (`{:shares [3 3 2]}`), a tree with an `:rtm`, or `{:onsets [0 3 6] :n 8}`. A number (or pressing a pulse) adds or
|
|
35
|
+
takes away that onset; `:complement` swaps onsets and silences, `[:rotate 1]` starts it a pulse later, `[:n 12]` makes
|
|
36
|
+
the circle longer or shorter, `:clear` empties it, `[:bars 4]` and `[:meter "3/4"]` shape the tree, a bang sends it again.
|
|
37
|
+
The same rhythm again sends nothing.
|
|
49
38
|
|
|
50
|
-
|
|
51
|
-
(
|
|
52
|
-
(
|
|
53
|
-
|
|
54
|
-
(
|
|
55
|
-
|
|
56
|
-
|
|
39
|
+
**Its measures** (outlet 3), what Toussaint measures. The **interval vector** (`:ivec`) counts how often each distance
|
|
40
|
+
between onsets occurs (the son clave: `[0 1 2 2 0 3 2 0]`). **Evenness** (`:evenness`) is the sum of the chords between
|
|
41
|
+
all pairs of onsets (Block and Douthett) — arcs would give the six 4/4 claves the same value; chords tell the rumba from
|
|
42
|
+
the bossa nova —, and `:even` is that sum against the Euclidean rhythm's, 1 when it is as even. A rhythm is **deep**
|
|
43
|
+
when each distance occurs a different number of times (the bembé, as the diatonic scale), **flat** when each occurs
|
|
44
|
+
once. `:axes` are its axes of mirror symmetry (in pulses, drawn across the circle), `:gap` its longest interval,
|
|
45
|
+
`:oddity` true when no two onsets halve the cycle, and `:euclid` the rotation of E(k,n) it is (or nil). `:fourier` and
|
|
46
|
+
`:phases` are its **Fourier coefficients** f1 … f⌊n/2⌋ (after Amiot and Milne), magnitudes 0…1 and phases in degrees:
|
|
47
|
+
|f1| near 0 is a balanced rhythm, |f_k| is largest when k onsets are maximally even, the others are its periodicities
|
|
48
|
+
(in 16 pulses f4 the quarter notes, f3 a three against the four). With the word `fourier` the magnitudes are drawn,
|
|
49
|
+
a bar each, f_k in the kairos colour.
|
|
50
|
+
|
|
51
|
+
**As music** — rhythm **apart from pitch**, as the `:rtm` of a musical tree is (see *Musical trees*, `docs/mt.md`):
|
|
52
|
+
|
|
53
|
+
| outlet | |
|
|
54
|
+
|---|---|
|
|
55
|
+
| 0 | a **musical tree** for a `tree` box: `[:voice [:measure {:meter [4 4]} [:rtm {:shares [3 3 2]}]] …]` — the shares are the intervals between onsets, a negative share the silence before the first one; a bar of n pulses (4/4 for 8 or 16, 12/8 for 12 or 24, n/8 up to 12, else n/16; `[:meter …]` for another); `bars` repeat it |
|
|
56
|
+
| 1 | the **`:rtm` map** alone (`{:shares [3 3 2] :pitches …}`): merge any map of pitches into it (`merge`) and write it as a node (`vector :rtm %`) |
|
|
57
|
+
| 2 | the **pulses** |
|
|
58
|
+
| 3 | the **measures** |
|
|
59
|
+
|
|
60
|
+
Its **right inlet** (cold) takes the pitches the notes take in turn, starting again when they run out — *talea* and
|
|
61
|
+
*color*: a map with `:pitches` or `:pitch` (kept as it is), a pattern (`{:note [...]}`, as `comes` sends), a melody
|
|
62
|
+
string, a list of Hz (the keys held on a keyboard; MIDI with `midi`), notes or chords of a tree; `:clear` forgets them.
|
|
63
|
+
With `bars` the color goes on from bar to bar.
|
|
64
|
+
|
|
65
|
+
## Generators and relations
|
|
66
|
+
|
|
67
|
+
`euclid`, `chance` and `homometric` make pulses; `swap` compares two. They have no view: put a `necklace` after
|
|
68
|
+
a generator to see, edit, measure and hear what it made.
|
|
69
|
+
|
|
70
|
+
**swap** answers `{:swap :circular :necklace :rotation :hamming :necklace-hamming :n :k}`. A swap exchanges an onset
|
|
71
|
+
and the silence beside it; the distance is how many turn one rhythm into the other, so an onset moved far counts
|
|
72
|
+
more than one moved near — the Hamming distance (how many pulses differ) cannot tell: the son clave is 1 swap from
|
|
73
|
+
the rumba and 1 from the bossa nova, and 2 by Hamming from both. With different numbers of onsets it is the directed
|
|
74
|
+
swap distance (the tresillo is 0 from the cinquillo: it is inside it). `:circular` lets a swap cross the end of the
|
|
75
|
+
bar; `:necklace` turns the reference to where it comes nearest, and `:rotation` says how far.
|
|
57
76
|
|
|
58
77
|
Writing one of its classes in a work brings the package into it. Licence: [MPL-2.0](../../LICENSE).
|
package/dist/chance.mjs
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
// Generated by packages/build.mjs from src/chance.cljs
|
|
2
|
+
export default {
|
|
3
|
+
"class": "chance",
|
|
4
|
+
"version": "0.3.0",
|
|
5
|
+
"author": "bonuoq",
|
|
6
|
+
"license": "MPL-2.0",
|
|
7
|
+
"doc": "A generator of pulses, as euclid, with chance instead of evenness: each bang draws another rhythm of k onsets among n pulses, sent as pulses (ones and zeros) for a necklace. The draws are the seed's — the same seed, the same rhythms in the same order, for everyone in a room and again from the history; :reset starts its draws again. [:k 5], [:n 16], [:seed 7] (or a map of them) change it and start again; a number is k.",
|
|
8
|
+
"source": ";; chance · k onsets among n pulses, drawn with a seed\n;; Part of @kairotic/rhythm. Written against the Kairotic API (api/…).\n;; A generator of pulses, as euclid is, with chance instead of evenness: each bang draws another rhythm of k\n;; onsets among n pulses. The draws are the seed's: draw i of seed s is always the same rhythm, so the same\n;; seed plays the same game for everyone in a room and again from the history (:reset starts its draws\n;; again). Against euclid's, a necklace's measures say how even or uneven chance came out.\n(let [M 2147483647\n ;; Park–Miller, started from the seed and the number of the draw, a few turns to mix them\n rng (fn [seed i]\n (let [s (volatile! (inc (mod (+ (* 7919 (js/Math.abs (js/Math.round seed))) (* 104729 i) 12345) (dec M))))]\n (dotimes [_ 4] (vreset! s (mod (* @s 16807) M)))\n (fn [] (vreset! s (mod (* @s 16807) M)) (/ (dec @s) (dec M)))))\n ;; k of the n pulses, as a shuffle stopped after k (Fisher–Yates)\n draw (fn [k n seed i]\n (let [r (rng seed i)\n picked (loop [xs (vec (range n)) j 0]\n (if (= j k) (set (subvec xs 0 k))\n (let [m (+ j (js/Math.floor (* (r) (- n j)))) xj (nth xs j) xm (nth xs m)]\n (recur (assoc xs j xm m xj) (inc j)))))]\n (mapv (fn [p] (if (picked p) 1 0)) (range n))))\n params (fn [args over]\n (let [o (merge args over)\n n (api/clamp (js/Math.round (or (:n o) 8)) 1 128)]\n {:n n :k (api/clamp (js/Math.round (or (:k o) 3)) 0 n) :seed (or (:seed o) 1)}))]\n {;; ── about ──\n :class \"chance\"\n :license \"MPL-2.0\"\n :doc \"A generator of pulses, as euclid, with chance instead of evenness: each bang draws another rhythm of k onsets among n pulses, sent as pulses (ones and zeros) for a necklace. The draws are the seed's — the same seed, the same rhythms in the same order, for everyone in a room and again from the history; :reset starts its draws again. [:k 5], [:n 16], [:seed 7] (or a map of them) change it and start again; a number is k.\"\n :usage \"chance [k 3] [n 8] [seed 1]\"\n :io [1 1]\n\n ;; ── arguments ──\n :args [[:k 3] [:n 8] [:seed 1]]\n\n ;; ── logic ──\n :receive (fn [{:keys [value state args]}]\n (let [st (or state {:over {} :i 0})\n again (fn [over] {:state {:over over :i 0} :show (let [p (params args over)] (str (:k p) \"/\" (:n p) \" · seed \" (:seed p)))})]\n (cond\n (#{:bang} value) (let [p (params args (:over st)) i (:i st)]\n {:state (assoc st :i (inc i)) :show (str (:k p) \"/\" (:n p) \" · seed \" (:seed p) \" · draw \" (inc i))\n :out [[0 (draw (:k p) (:n p) (:seed p) i)]]})\n (#{:reset} value) (again (:over st))\n (number? value) (again (assoc (:over st) :k value))\n (and (vector? value) (= 2 (count value)) (#{:k :n :seed} (first value)) (number? (second value)))\n (again (assoc (:over st) (first value) (second value)))\n (map? value) (again (merge (:over st) (select-keys value [:k :n :seed])))\n :else {})))})\n"
|
|
9
|
+
};
|
package/dist/euclid.mjs
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
// Generated by packages/build.mjs from src/euclid.cljs
|
|
2
2
|
export default {
|
|
3
3
|
"class": "euclid",
|
|
4
|
-
"version": "0.
|
|
4
|
+
"version": "0.3.0",
|
|
5
5
|
"author": "bonuoq",
|
|
6
6
|
"license": "MPL-2.0",
|
|
7
|
-
"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
|
|
8
|
-
"source": ";; euclid · a Euclidean rhythm: k onsets spread as evenly as they can be over n pulses\n;; Part of @kairotic/rhythm. 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 [...]}, 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 ({: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"
|
|
7
|
+
"doc": "A Euclidean rhythm (Bjorklund's algorithm, after Toussaint), as pulses: k onsets spread as evenly as they can be over n pulses, from pulse rotation on — euclid 3 8 is the tresillo [1 0 0 1 0 0 1 0], euclid 5 8 the cinquillo, euclid 5 16 a rotation of the bossa nova (euclid 5 16 6 the bossa nova), euclid 7 12 the bembé. A generator with no view: a bang sends the pulses; [:k 5], [:n 16], [:rotation 2] (or a map of them) change them and send them when they are new, a number is k. Pulses are what every rhythm box takes: a necklace after it shows, edits and measures the rhythm, and writes it as a musical tree with pitches (euclid → necklace → tree).",
|
|
8
|
+
"source": ";; euclid · a Euclidean rhythm, as pulses: k onsets spread as evenly as they can be over n pulses\n;; Part of @kairotic/rhythm. 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;; A generator, almost a function: (euclid k n rotation) → pulses, ones and zeros — the common tongue of the\n;; rhythm boxes, as Hz are of pitch. It has no view: a necklace shows, edits, measures and writes as a tree\n;; what it makes (euclid → necklace → tree).\n(let [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 ;; 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 pulses-of (fn [args over]\n (let [o (merge args over)\n n (api/clamp (js/Math.round (or (:n o) 8)) 1 128)\n k (api/clamp (js/Math.round (or (:k o) 3)) 0 n)]\n {:k k :n n :rotation (mod (js/Math.round (or (:rotation o) 0)) n)\n :pulses (rotate (bjorklund k n) (or (:rotation o) 0))}))\n ;; a change: sent when the pulses are new (the same again changes nothing); a bang sends them anyway\n changed (fn [args st over always?]\n (let [r (pulses-of args over)\n shown (str \"E(\" (:k r) \",\" (:n r) \")\" (when (pos? (:rotation r)) (str \" ↻\" (:rotation r))))]\n (if (and (not always?) (= (:pulses r) (:sent st)))\n {:state (assoc st :over over) :show shown}\n {:state (assoc st :over over :sent (:pulses r)) :show shown :out [[0 (:pulses r)]]})))]\n {;; ── about ──\n :class \"euclid\"\n :license \"MPL-2.0\"\n :doc \"A Euclidean rhythm (Bjorklund's algorithm, after Toussaint), as pulses: k onsets spread as evenly as they can be over n pulses, from pulse rotation on — euclid 3 8 is the tresillo [1 0 0 1 0 0 1 0], euclid 5 8 the cinquillo, euclid 5 16 a rotation of the bossa nova (euclid 5 16 6 the bossa nova), euclid 7 12 the bembé. A generator with no view: a bang sends the pulses; [:k 5], [:n 16], [:rotation 2] (or a map of them) change them and send them when they are new, a number is k. Pulses are what every rhythm box takes: a necklace after it shows, edits and measures the rhythm, and writes it as a musical tree with pitches (euclid → necklace → tree).\"\n :usage \"euclid [k 3] [n 8] [rotation 0]\"\n :io [1 1]\n\n ;; ── arguments ──\n :args [[:k 3] [:n 8] [:rotation 0]]\n\n ;; ── logic ──\n :receive (fn [{:keys [value state args]}]\n (let [st (or state {:over {}})\n over (:over st)\n set-over (fn [m] (changed args st (merge over m) false))]\n (cond\n (#{:bang} value) (changed args st over true)\n (number? value) (set-over {:k value})\n (and (vector? value) (= 2 (count value)) (#{:k :n :rotation} (first value)) (number? (second value)))\n (set-over {(first value) (second value)})\n (map? value) (set-over (select-keys value [:k :n :rotation]))\n :else {})))})\n"
|
|
9
9
|
};
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
// Generated by packages/build.mjs from src/homometric.cljs
|
|
2
|
+
export default {
|
|
3
|
+
"class": "homometric",
|
|
4
|
+
"version": "0.3.0",
|
|
5
|
+
"author": "bonuoq",
|
|
6
|
+
"license": "MPL-2.0",
|
|
7
|
+
"doc": "The other rhythms with the same interval vector (Toussaint, after crystallography): homometric rhythms hold the same distances between onsets, as many times each, without being the same necklace turned or in a mirror — the two flat rhythms of four onsets in twelve; any half of the pulses of an even cycle and its complement, two drums with the same intervals. Given pulses, it searches every rhythm of as many onsets among as many pulses (when they are at most 7 000: any rhythm of 16 pulses) and sends the others it finds, each from its first onset, as a list of pulses (left: for nth, or one by one to a necklace) and how many there are (right); none, an empty list. A bang searches again.",
|
|
8
|
+
"source": ";; homometric · the other rhythms with the same interval vector\n;; Part of @kairotic/rhythm. Written against the Kairotic API (api/…).\n;; Two rhythms are homometric when they hold the same distances between onsets, as many times each — the\n;; same interval vector, the same \"histogram\" — without being the same necklace turned or seen in a mirror\n;; (Toussaint, after crystallography: Patterson, Rosenblatt and Seymour). The two flat rhythms of four onsets\n;; in twelve are homometric; so is any half of the pulses of an even cycle with its complement, which gives two\n;; drums (high and low congas) the same intervals. Given a rhythm as pulses, it searches every rhythm of as many\n;; onsets among as many pulses (up to 7 000 of them: any rhythm of 16 pulses; a moment for the largest) and sends the others it finds, each from its first onset, as a list of\n;; pulses (for nth, or a necklace one by one), and how many there are.\n(let [onsets-of (fn [ps] (vec (keep-indexed (fn [i x] (when (= 1 x) i)) ps)))\n pulses? (fn [v] (and (sequential? v) (seq v) (every? #{0 1} v)))\n dist (fn [n a b] (let [d (js/Math.abs (- a b))] (min d (- n d))))\n ivec-of (fn [n os] (let [c (frequencies (for [i (range (count os)) j (range (inc i) (count os))] (dist n (nth os i) (nth os j))))]\n (mapv (fn [d] (get c d 0)) (range 1 (inc (quot n 2))))))\n ;; a necklace up to rotation and mirror, as its smallest form starting at 0 (a bracelet)\n bracelet (fn [n os]\n (first (sort (for [f [identity (fn [x] (mod (- n x) n))] r (range n)]\n (vec (sort (map (fn [x] (mod (- (f x) r) n)) os)))))))\n ;; the subsets of 1…n−1 of size m (0 is always an onset: rotations are the same necklace)\n subsets (fn subsets [from n m]\n (cond (zero? m) [[]]\n (> m (- n from)) []\n :else (concat (map (fn [s] (cons from s)) (subsets (inc from) n (dec m))) (subsets (inc from) n m))))\n ;; how many rhythms the search goes through: C(n−1, k−1)\n choose (fn [a b] (reduce (fn [acc i] (/ (* acc (- a i)) (inc i))) 1 (range (min b (- a b)))))\n limit 7000\n search (fn [ps]\n (let [n (count ps) os (onsets-of ps) k (count os) target (ivec-of n os) own (bracelet n os)]\n (if (zero? k) []\n (->> (subsets 1 n (dec k))\n (map (fn [s] (vec (cons 0 s))))\n (filter (fn [o] (= target (ivec-of n o))))\n (map (fn [o] (bracelet n o)))\n distinct\n (remove (fn [b] (= b own)))\n sort\n (mapv (fn [b] (let [on (set b)] (mapv (fn [i] (if (on i) 1 0)) (range n)))))))))]\n {;; ── about ──\n :class \"homometric\"\n :license \"MPL-2.0\"\n :doc \"The other rhythms with the same interval vector (Toussaint, after crystallography): homometric rhythms hold the same distances between onsets, as many times each, without being the same necklace turned or in a mirror — the two flat rhythms of four onsets in twelve; any half of the pulses of an even cycle and its complement, two drums with the same intervals. Given pulses, it searches every rhythm of as many onsets among as many pulses (when they are at most 7 000: any rhythm of 16 pulses) and sends the others it finds, each from its first onset, as a list of pulses (left: for nth, or one by one to a necklace) and how many there are (right); none, an empty list. A bang searches again.\"\n :usage \"homometric\"\n :io [1 2]\n\n ;; ── logic ──\n :receive (fn [{:keys [value state]}]\n (let [st (or state {})\n go (fn [ps] (if (> (choose (dec (count ps)) (max 0 (dec (count (onsets-of ps))))) limit)\n {:state (assoc st :ps ps) :show (str \"too many to search (more than \" limit \" rhythms)\")}\n (let [hs (search ps)]\n {:state (assoc st :ps ps) :show (str (count hs) \" homometric\")\n :out [[1 (count hs)] [0 hs]]})))]\n (cond\n (and (#{:bang} value) (:ps st)) (go (:ps st))\n (pulses? value) (if (= (vec value) (:ps st)) {:state st} (go (vec value)))\n :else {})))})\n"
|
|
9
|
+
};
|
package/dist/index.mjs
CHANGED
|
@@ -1,22 +1,40 @@
|
|
|
1
1
|
// Generated by packages/build.mjs
|
|
2
2
|
export default {
|
|
3
3
|
"package": "@kairotic/rhythm",
|
|
4
|
-
"version": "0.
|
|
4
|
+
"version": "0.3.0",
|
|
5
5
|
"api": 1,
|
|
6
6
|
"author": "bonuoq",
|
|
7
7
|
"license": "MPL-2.0",
|
|
8
8
|
"components": [
|
|
9
|
+
{
|
|
10
|
+
"class": "chance",
|
|
11
|
+
"license": "MPL-2.0",
|
|
12
|
+
"doc": "A generator of pulses, as euclid, with chance instead of evenness: each bang draws another rhythm of k onsets among n pulses, sent as pulses (ones and zeros) for a necklace. The draws are the seed's — the same seed, the same rhythms in the same order, for everyone in a room and again from the history; :reset starts its draws again. [:k 5], [:n 16], [:seed 7] (or a map of them) change it and start again; a number is k.",
|
|
13
|
+
"source": ";; chance · k onsets among n pulses, drawn with a seed\n;; Part of @kairotic/rhythm. Written against the Kairotic API (api/…).\n;; A generator of pulses, as euclid is, with chance instead of evenness: each bang draws another rhythm of k\n;; onsets among n pulses. The draws are the seed's: draw i of seed s is always the same rhythm, so the same\n;; seed plays the same game for everyone in a room and again from the history (:reset starts its draws\n;; again). Against euclid's, a necklace's measures say how even or uneven chance came out.\n(let [M 2147483647\n ;; Park–Miller, started from the seed and the number of the draw, a few turns to mix them\n rng (fn [seed i]\n (let [s (volatile! (inc (mod (+ (* 7919 (js/Math.abs (js/Math.round seed))) (* 104729 i) 12345) (dec M))))]\n (dotimes [_ 4] (vreset! s (mod (* @s 16807) M)))\n (fn [] (vreset! s (mod (* @s 16807) M)) (/ (dec @s) (dec M)))))\n ;; k of the n pulses, as a shuffle stopped after k (Fisher–Yates)\n draw (fn [k n seed i]\n (let [r (rng seed i)\n picked (loop [xs (vec (range n)) j 0]\n (if (= j k) (set (subvec xs 0 k))\n (let [m (+ j (js/Math.floor (* (r) (- n j)))) xj (nth xs j) xm (nth xs m)]\n (recur (assoc xs j xm m xj) (inc j)))))]\n (mapv (fn [p] (if (picked p) 1 0)) (range n))))\n params (fn [args over]\n (let [o (merge args over)\n n (api/clamp (js/Math.round (or (:n o) 8)) 1 128)]\n {:n n :k (api/clamp (js/Math.round (or (:k o) 3)) 0 n) :seed (or (:seed o) 1)}))]\n {;; ── about ──\n :class \"chance\"\n :license \"MPL-2.0\"\n :doc \"A generator of pulses, as euclid, with chance instead of evenness: each bang draws another rhythm of k onsets among n pulses, sent as pulses (ones and zeros) for a necklace. The draws are the seed's — the same seed, the same rhythms in the same order, for everyone in a room and again from the history; :reset starts its draws again. [:k 5], [:n 16], [:seed 7] (or a map of them) change it and start again; a number is k.\"\n :usage \"chance [k 3] [n 8] [seed 1]\"\n :io [1 1]\n\n ;; ── arguments ──\n :args [[:k 3] [:n 8] [:seed 1]]\n\n ;; ── logic ──\n :receive (fn [{:keys [value state args]}]\n (let [st (or state {:over {} :i 0})\n again (fn [over] {:state {:over over :i 0} :show (let [p (params args over)] (str (:k p) \"/\" (:n p) \" · seed \" (:seed p)))})]\n (cond\n (#{:bang} value) (let [p (params args (:over st)) i (:i st)]\n {:state (assoc st :i (inc i)) :show (str (:k p) \"/\" (:n p) \" · seed \" (:seed p) \" · draw \" (inc i))\n :out [[0 (draw (:k p) (:n p) (:seed p) i)]]})\n (#{:reset} value) (again (:over st))\n (number? value) (again (assoc (:over st) :k value))\n (and (vector? value) (= 2 (count value)) (#{:k :n :seed} (first value)) (number? (second value)))\n (again (assoc (:over st) (first value) (second value)))\n (map? value) (again (merge (:over st) (select-keys value [:k :n :seed])))\n :else {})))})\n"
|
|
14
|
+
},
|
|
9
15
|
{
|
|
10
16
|
"class": "euclid",
|
|
11
17
|
"license": "MPL-2.0",
|
|
12
|
-
"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
|
|
13
|
-
"source": ";; euclid · a Euclidean rhythm: k onsets spread as evenly as they can be over n pulses\n;; Part of @kairotic/rhythm. 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 [...]}, 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 ({: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"
|
|
18
|
+
"doc": "A Euclidean rhythm (Bjorklund's algorithm, after Toussaint), as pulses: k onsets spread as evenly as they can be over n pulses, from pulse rotation on — euclid 3 8 is the tresillo [1 0 0 1 0 0 1 0], euclid 5 8 the cinquillo, euclid 5 16 a rotation of the bossa nova (euclid 5 16 6 the bossa nova), euclid 7 12 the bembé. A generator with no view: a bang sends the pulses; [:k 5], [:n 16], [:rotation 2] (or a map of them) change them and send them when they are new, a number is k. Pulses are what every rhythm box takes: a necklace after it shows, edits and measures the rhythm, and writes it as a musical tree with pitches (euclid → necklace → tree).",
|
|
19
|
+
"source": ";; euclid · a Euclidean rhythm, as pulses: k onsets spread as evenly as they can be over n pulses\n;; Part of @kairotic/rhythm. 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;; A generator, almost a function: (euclid k n rotation) → pulses, ones and zeros — the common tongue of the\n;; rhythm boxes, as Hz are of pitch. It has no view: a necklace shows, edits, measures and writes as a tree\n;; what it makes (euclid → necklace → tree).\n(let [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 ;; 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 pulses-of (fn [args over]\n (let [o (merge args over)\n n (api/clamp (js/Math.round (or (:n o) 8)) 1 128)\n k (api/clamp (js/Math.round (or (:k o) 3)) 0 n)]\n {:k k :n n :rotation (mod (js/Math.round (or (:rotation o) 0)) n)\n :pulses (rotate (bjorklund k n) (or (:rotation o) 0))}))\n ;; a change: sent when the pulses are new (the same again changes nothing); a bang sends them anyway\n changed (fn [args st over always?]\n (let [r (pulses-of args over)\n shown (str \"E(\" (:k r) \",\" (:n r) \")\" (when (pos? (:rotation r)) (str \" ↻\" (:rotation r))))]\n (if (and (not always?) (= (:pulses r) (:sent st)))\n {:state (assoc st :over over) :show shown}\n {:state (assoc st :over over :sent (:pulses r)) :show shown :out [[0 (:pulses r)]]})))]\n {;; ── about ──\n :class \"euclid\"\n :license \"MPL-2.0\"\n :doc \"A Euclidean rhythm (Bjorklund's algorithm, after Toussaint), as pulses: k onsets spread as evenly as they can be over n pulses, from pulse rotation on — euclid 3 8 is the tresillo [1 0 0 1 0 0 1 0], euclid 5 8 the cinquillo, euclid 5 16 a rotation of the bossa nova (euclid 5 16 6 the bossa nova), euclid 7 12 the bembé. A generator with no view: a bang sends the pulses; [:k 5], [:n 16], [:rotation 2] (or a map of them) change them and send them when they are new, a number is k. Pulses are what every rhythm box takes: a necklace after it shows, edits and measures the rhythm, and writes it as a musical tree with pitches (euclid → necklace → tree).\"\n :usage \"euclid [k 3] [n 8] [rotation 0]\"\n :io [1 1]\n\n ;; ── arguments ──\n :args [[:k 3] [:n 8] [:rotation 0]]\n\n ;; ── logic ──\n :receive (fn [{:keys [value state args]}]\n (let [st (or state {:over {}})\n over (:over st)\n set-over (fn [m] (changed args st (merge over m) false))]\n (cond\n (#{:bang} value) (changed args st over true)\n (number? value) (set-over {:k value})\n (and (vector? value) (= 2 (count value)) (#{:k :n :rotation} (first value)) (number? (second value)))\n (set-over {(first value) (second value)})\n (map? value) (set-over (select-keys value [:k :n :rotation]))\n :else {})))})\n"
|
|
20
|
+
},
|
|
21
|
+
{
|
|
22
|
+
"class": "homometric",
|
|
23
|
+
"license": "MPL-2.0",
|
|
24
|
+
"doc": "The other rhythms with the same interval vector (Toussaint, after crystallography): homometric rhythms hold the same distances between onsets, as many times each, without being the same necklace turned or in a mirror — the two flat rhythms of four onsets in twelve; any half of the pulses of an even cycle and its complement, two drums with the same intervals. Given pulses, it searches every rhythm of as many onsets among as many pulses (when they are at most 7 000: any rhythm of 16 pulses) and sends the others it finds, each from its first onset, as a list of pulses (left: for nth, or one by one to a necklace) and how many there are (right); none, an empty list. A bang searches again.",
|
|
25
|
+
"source": ";; homometric · the other rhythms with the same interval vector\n;; Part of @kairotic/rhythm. Written against the Kairotic API (api/…).\n;; Two rhythms are homometric when they hold the same distances between onsets, as many times each — the\n;; same interval vector, the same \"histogram\" — without being the same necklace turned or seen in a mirror\n;; (Toussaint, after crystallography: Patterson, Rosenblatt and Seymour). The two flat rhythms of four onsets\n;; in twelve are homometric; so is any half of the pulses of an even cycle with its complement, which gives two\n;; drums (high and low congas) the same intervals. Given a rhythm as pulses, it searches every rhythm of as many\n;; onsets among as many pulses (up to 7 000 of them: any rhythm of 16 pulses; a moment for the largest) and sends the others it finds, each from its first onset, as a list of\n;; pulses (for nth, or a necklace one by one), and how many there are.\n(let [onsets-of (fn [ps] (vec (keep-indexed (fn [i x] (when (= 1 x) i)) ps)))\n pulses? (fn [v] (and (sequential? v) (seq v) (every? #{0 1} v)))\n dist (fn [n a b] (let [d (js/Math.abs (- a b))] (min d (- n d))))\n ivec-of (fn [n os] (let [c (frequencies (for [i (range (count os)) j (range (inc i) (count os))] (dist n (nth os i) (nth os j))))]\n (mapv (fn [d] (get c d 0)) (range 1 (inc (quot n 2))))))\n ;; a necklace up to rotation and mirror, as its smallest form starting at 0 (a bracelet)\n bracelet (fn [n os]\n (first (sort (for [f [identity (fn [x] (mod (- n x) n))] r (range n)]\n (vec (sort (map (fn [x] (mod (- (f x) r) n)) os)))))))\n ;; the subsets of 1…n−1 of size m (0 is always an onset: rotations are the same necklace)\n subsets (fn subsets [from n m]\n (cond (zero? m) [[]]\n (> m (- n from)) []\n :else (concat (map (fn [s] (cons from s)) (subsets (inc from) n (dec m))) (subsets (inc from) n m))))\n ;; how many rhythms the search goes through: C(n−1, k−1)\n choose (fn [a b] (reduce (fn [acc i] (/ (* acc (- a i)) (inc i))) 1 (range (min b (- a b)))))\n limit 7000\n search (fn [ps]\n (let [n (count ps) os (onsets-of ps) k (count os) target (ivec-of n os) own (bracelet n os)]\n (if (zero? k) []\n (->> (subsets 1 n (dec k))\n (map (fn [s] (vec (cons 0 s))))\n (filter (fn [o] (= target (ivec-of n o))))\n (map (fn [o] (bracelet n o)))\n distinct\n (remove (fn [b] (= b own)))\n sort\n (mapv (fn [b] (let [on (set b)] (mapv (fn [i] (if (on i) 1 0)) (range n)))))))))]\n {;; ── about ──\n :class \"homometric\"\n :license \"MPL-2.0\"\n :doc \"The other rhythms with the same interval vector (Toussaint, after crystallography): homometric rhythms hold the same distances between onsets, as many times each, without being the same necklace turned or in a mirror — the two flat rhythms of four onsets in twelve; any half of the pulses of an even cycle and its complement, two drums with the same intervals. Given pulses, it searches every rhythm of as many onsets among as many pulses (when they are at most 7 000: any rhythm of 16 pulses) and sends the others it finds, each from its first onset, as a list of pulses (left: for nth, or one by one to a necklace) and how many there are (right); none, an empty list. A bang searches again.\"\n :usage \"homometric\"\n :io [1 2]\n\n ;; ── logic ──\n :receive (fn [{:keys [value state]}]\n (let [st (or state {})\n go (fn [ps] (if (> (choose (dec (count ps)) (max 0 (dec (count (onsets-of ps))))) limit)\n {:state (assoc st :ps ps) :show (str \"too many to search (more than \" limit \" rhythms)\")}\n (let [hs (search ps)]\n {:state (assoc st :ps ps) :show (str (count hs) \" homometric\")\n :out [[1 (count hs)] [0 hs]]})))]\n (cond\n (and (#{:bang} value) (:ps st)) (go (:ps st))\n (pulses? value) (if (= (vec value) (:ps st)) {:state st} (go (vec value)))\n :else {})))})\n"
|
|
14
26
|
},
|
|
15
27
|
{
|
|
16
28
|
"class": "necklace",
|
|
17
29
|
"license": "MPL-2.0",
|
|
18
|
-
"doc": "A cyclic rhythm on the circle and its geometry (Toussaint): k onsets among n pulses around a circle, time clockwise from the top — the same object as a pitch-class set on pcclock. A rhythm arrives as pulses (ones and zeros, as euclid's right outlet sends them), as intervals between onsets ([3 3 2]), as box notation (\"x..x..x.\"), as an :rtm map ({:shares [3 3 2]}, euclid's middle outlet), a tree with an :rtm, or {:onsets [0 3 6] :n 8}; it is drawn as a polygon, with its axes of mirror symmetry. Pressing a pulse (or a number, its index) adds or takes away an onset. :complement swaps onsets and silences, [:rotate 1] starts it a pulse later, [:n 12] makes the circle longer or shorter, :clear empties it, [:bars 4] and [:meter \"3/4\"] as euclid, a bang sends it again. Out, as euclid: a musical tree (left: a bar of n pulses with an :rtm whose shares are the intervals between onsets), the :rtm map alone (1), the pulses (2); and its measures (3): {:n :k :onsets :intervals :ivec — how often each distance occurs —, :evenness — the sum of the chords between all pairs (Block and Douthett) —, :even — that sum against the Euclidean rhythm's, 1 as even as it —, :deep — each distance a different number of times —, :flat — each once —, :axes — of mirror symmetry, in pulses —, :gap — the longest interval —, :oddity — no two onsets halving the cycle —, :euclid — the rotation of E(k,n) it is, or nil}. Its right inlet (cold) takes the pitches the notes take in turn, as euclid's.",
|
|
19
|
-
"source": ";; necklace · a cyclic rhythm on the circle, and its geometry (Toussaint)\n;; Part of @kairotic/rhythm. Written against the Kairotic API (api/…).\n;; A rhythm that repeats is a necklace: k onsets among n pulses around a circle, time clockwise from the\n;; top. Seen so, it is the same object as a pitch-class set on pcclock, and the same geometry measures it\n;; (Toussaint, \"The Geometry of Musical Rhythm\"): its full-interval vector (how often each distance between\n;; onsets occurs), its evenness (the sum of the chords between all pairs of onsets, after Block and Douthett;\n;; arcs are too coarse: the six 4/4 claves would all score the same), whether it is deep (each distance a\n;; different number of times, as the diatonic scale and the bembé), flat (each distance once), its axes of\n;; mirror symmetry, its longest gap, rhythmic oddity (no two onsets halving the cycle), and whether it is a\n;; rotation of the Euclidean rhythm E(k,n). Pressing a pulse adds or takes away an onset: the necklace is\n;; also an editor. What it sends is as euclid's — a musical tree, its :rtm map, its pulses —, so it merges\n;; with pitches the same way (the right inlet, or merge with outlet 1), and its measures go out on the right.\n(let [TAU (* 2 js/Math.PI)\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 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 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 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 r3 (fn [x] (/ (js/Math.round (* 1000 x)) 1000))\n ;; ── what arrives, as pulses (ones and zeros), or nil when it is not a rhythm ──\n whole? (fn [x] (and (number? x) (== x (js/Math.round x))))\n from-shares (fn [sh] (when (and (sequential? sh) (seq sh) (every? (fn [x] (and (whole? x) (not (zero? x)))) sh))\n (vec (mapcat (fn [x] (if (pos? x) (cons 1 (repeat (dec x) 0)) (repeat (- x) 0))) sh))))\n from-onsets (fn [os n] (when (and (whole? n) (pos? n) (sequential? os) (every? whole? os))\n (let [on (set (map (fn [o] (mod o n)) os))] (mapv (fn [i] (if (on i) 1 0)) (range n)))))\n ;; the first :rtm of a tree (as euclid sends it)\n rtm-in (fn rtm-in [t] (when (sequential? t)\n (if (= :rtm (first t)) (second t) (some rtm-in (filter sequential? t)))))\n ;; a list: ones and zeros are pulses; other whole numbers, the intervals between onsets (3 3 2)\n pulses-of-list (fn [v] (when (and (sequential? v) (seq v) (every? whole? v))\n (if (every? #{0 1} v) (vec v) (when (every? pos? v) (from-shares v)))))\n pulses-of (fn [v]\n (cond\n ;; box notation (TUBS): \"x..x..x.\" (x, X or 1 an onset; . - _ or 0 a pulse without one)\n (string? v) (let [cs (remove #{\" \"} (seq v))]\n (when (and (seq cs) (every? #{\"x\" \"X\" \"1\" \".\" \"-\" \"_\" \"0\"} cs))\n (mapv (fn [c] (if (#{\"x\" \"X\" \"1\"} c) 1 0)) cs)))\n (map? v) (cond (contains? v :shares) (from-shares (:shares v))\n (contains? v :pulses) (pulses-of-list (:pulses v))\n (contains? v :onsets) (from-onsets (:onsets v) (:n v)))\n (and (sequential? v) (keyword? (first v))) (some-> (rtm-in v) :shares from-shares)\n :else nil))\n ;; ── its geometry ──\n dist (fn [n a b] (let [d (js/Math.abs (- a b))] (min d (- n d))))\n pairs (fn [os] (for [i (range (count os)) j (range (inc i) (count os))] [(nth os i) (nth os j)]))\n ivec-of (fn [n os] (let [c (frequencies (map (fn [[a b]] (dist n a b)) (pairs os)))]\n (mapv (fn [d] (get c d 0)) (range 1 (inc (quot n 2))))))\n evenness-of (fn [n os] (reduce + 0 (map (fn [[a b]] (* 2 (js/Math.sin (/ (* js/Math.PI (dist n a b)) n)))) (pairs os))))\n ;; the axes of mirror symmetry, in pulses: x → a − x keeps the set; the axis passes through a/2 (and a/2 + n/2)\n axes-of (fn [n os] (let [s (set os)]\n (if (empty? s) []\n (vec (for [a (range n) :when (= s (set (map (fn [x] (mod (- a x) n)) os)))] (/ a 2))))))\n measures (fn [ps]\n (let [n (count ps) os (onsets-of ps) k (count os) iv (ivec-of n os) ev (evenness-of n os)\n e (bjorklund k n) eev (evenness-of n (onsets-of e))\n er (first (filter (fn [r] (= ps (rotate e r))) (range (max n 1))))]\n {:n n :k k :onsets os :intervals (intervals-of ps) :ivec iv\n :evenness (r3 ev) :even (if (pos? eev) (r3 (/ ev eev)) 1)\n :deep (and (>= k 2) (= (count (distinct iv)) (count iv)))\n :flat (and (seq iv) (every? #{1} iv))\n :axes (axes-of n os)\n :gap (if (seq os) (apply max (intervals-of ps)) n)\n :oddity (or (odd? n) (not-any? (fn [[a b]] (= (* 2 (dist n a b)) n)) (pairs os)))\n :euclid er}))\n ;; ── as euclid sends a rhythm: the meter of a bar of n pulses, the pitches, the color over bars ──\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 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 hz->m (fn [x] (when (and (number? x) (pos? x)) (/ (js/Math.round (* 1000 (+ 69 (* 12 (js/Math.log2 (/ x 440)))))) 1000)))\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 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 rhythm (fn [ps st]\n (let [k (count (onsets-of ps)) bars (:bars st) meter (or (:meter st) (meter-of (count ps)))\n rtm (merge {:shares (shares-of ps)} (or (:pm st) {}))\n bar (fn [i] (let [a (color-at rtm (* i k))]\n (if (zero? i) [:measure {:meter meter} [:rtm a]] [:measure [:rtm a]])))]\n {:rtm rtm :tree (into [:voice] (map bar (range bars)))}))\n ;; what goes out (the last first, as Max does): the measures (3), the pulses (2), the :rtm map (1), the tree (0)\n outs (fn [ps st] (let [r (rhythm ps st)] [[3 (measures ps)] [2 ps] [1 (:rtm r)] [0 (:tree r)]]))\n ;; a new state: sent when the rhythm, its bars or its meter are new (the same again changes nothing); a bang anyway\n settle (fn [st st2 always?]\n (let [ps (:pulses st2) key [ps (:bars st2) (:meter st2)]\n show (assoc (measures ps) :pulses ps)]\n (cond (empty? ps) {:state st2}\n (and (not always?) (= key (:sent st))) {:state st2 :show show}\n :else {:state (assoc st2 :sent key) :show show :out (outs ps st2)})))\n polar (fn [cx cy R i n] (let [a (* TAU (/ i n))] [(+ cx (* R (js/Math.sin a))) (- cy (* R (js/Math.cos a)))]))]\n {;; ── about ──\n :class \"necklace\"\n :license \"MPL-2.0\"\n :doc \"A cyclic rhythm on the circle and its geometry (Toussaint): k onsets among n pulses around a circle, time clockwise from the top — the same object as a pitch-class set on pcclock. A rhythm arrives as pulses (ones and zeros, as euclid's right outlet sends them), as intervals between onsets ([3 3 2]), as box notation (\\\"x..x..x.\\\"), as an :rtm map ({:shares [3 3 2]}, euclid's middle outlet), a tree with an :rtm, or {:onsets [0 3 6] :n 8}; it is drawn as a polygon, with its axes of mirror symmetry. Pressing a pulse (or a number, its index) adds or takes away an onset. :complement swaps onsets and silences, [:rotate 1] starts it a pulse later, [:n 12] makes the circle longer or shorter, :clear empties it, [:bars 4] and [:meter \\\"3/4\\\"] as euclid, a bang sends it again. Out, as euclid: a musical tree (left: a bar of n pulses with an :rtm whose shares are the intervals between onsets), the :rtm map alone (1), the pulses (2); and its measures (3): {:n :k :onsets :intervals :ivec — how often each distance occurs —, :evenness — the sum of the chords between all pairs (Block and Douthett) —, :even — that sum against the Euclidean rhythm's, 1 as even as it —, :deep — each distance a different number of times —, :flat — each once —, :axes — of mirror symmetry, in pulses —, :gap — the longest interval —, :oddity — no two onsets halving the cycle —, :euclid — the rotation of E(k,n) it is, or nil}. Its right inlet (cold) takes the pitches the notes take in turn, as euclid's.\"\n :usage \"necklace [n 16] [bars 1] [midi]\"\n :io [2 4]\n :size [200 240]\n\n ;; ── arguments ──\n :args [[:n 16] [:bars 1] [:midi false]]\n\n ;; ── logic ──\n :receive (fn [{:keys [inlet value state args]}]\n (let [st (or state {:pulses (vec (repeat (max 1 (js/Math.round (or (:n args) 16))) 0))\n :bars (api/clamp (js/Math.round (or (:bars args) 1)) 1 64) :meter nil :pm nil})\n ps (:pulses st) n (count ps)\n to (fn [m] (settle st (merge st m) false))\n toggle (fn [i] (let [i (mod (js/Math.round i) n)] (to {:pulses (update ps i (fn [x] (- 1 x)))})))]\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) (settle st st true)\n (#{:clear} value) (to {:pulses (vec (repeat n 0))})\n (#{:complement} value) (to {:pulses (mapv (fn [x] (- 1 x)) ps)})\n (number? value) (toggle value)\n (and (vector? value) (= :pressed (first value)) (number? (second value))) (toggle (second value))\n (and (vector? value) (= :rotate (first value)) (number? (second value))) (to {:pulses (rotate ps (js/Math.round (second value)))})\n (and (vector? value) (= :n (first value)) (number? (second value)))\n (let [m (api/clamp (js/Math.round (second value)) 1 128)]\n (to {:pulses (vec (take m (concat ps (repeat 0))))}))\n (and (vector? value) (= :bars (first value)) (number? (second value))) (to {:bars (api/clamp (js/Math.round (second value)) 1 64)})\n (and (vector? value) (= :meter (first value))) (to {:meter (meter-arg (second value))})\n :else (if-let [p (or (pulses-of-list value) (pulses-of value))]\n (to {:pulses p})\n {})))))\n ;; pressing a pulse adds or takes away an onset (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 [ps (vec (repeat (max 1 (js/Math.round (or (:n args) 16))) 0))] (assoc (measures ps) :pulses ps)))\n n (:n p) ps (:pulses p) os (:onsets p)\n cx (/ w 2) cy (/ (- h 44) 2) R (- (min cx cy) 16)\n r (cond (> n 32) 2.2 (> n 16) 3 :else 4.5)\n flags (remove nil? [(str \"even \" (:even p))\n (let [a (count (:axes p))] (case a 0 \"asymmetric\" 1 \"1 axis\" (str a \" axes\")))\n (when (:deep p) \"deep\") (when (:flat p) \"flat\")\n (when (and (even? n) (:oddity p) (pos? (:k p))) \"oddity\")\n (when (:euclid p) (str \"E(\" (:k p) \",\" n \")\" (when (pos? (:euclid p)) (str \" ↻\" (:euclid p)))))])]\n (concat\n [[:circle {:cx cx :cy cy :r R :stroke :grid}]]\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 ;; the axes of symmetry, across the circle\n (for [a (:axes p)]\n (let [[x1 y1] (polar cx cy (+ R 7) a n) [x2 y2] (polar cx cy (+ R 7) (+ a (/ n 2)) n)]\n [:line {:x1 x1 :y1 y1 :x2 x2 :y2 y2 :stroke :kairos :weight 1 :opacity 0.5}]))\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 29) :anchor :middle :size 10 :fill :ink}\n (str (:k p) \"/\" n \" · \" (if (seq (:intervals p)) (apply str (interpose \"-\" (:intervals p))) \"silence\"))]\n [:text {:x cx :y (- h 16) :anchor :middle :size 9 :fill :soft} (str \"<\" (apply str (interpose \" \" (:ivec p))) \">\")]\n [:text {:x cx :y (- h 3) :anchor :middle :size 9 :fill :soft} (apply str (interpose \" · \" flags))]])))})\n"
|
|
30
|
+
"doc": "A cyclic rhythm on the circle and its geometry (Toussaint): k onsets among n pulses around a circle, time clockwise from the top — the same object as a pitch-class set on pcclock. A rhythm arrives as pulses (ones and zeros, as euclid's right outlet sends them), as intervals between onsets ([3 3 2]), as box notation (\"x..x..x.\"), as an :rtm map ({:shares [3 3 2]}, euclid's middle outlet), a tree with an :rtm, or {:onsets [0 3 6] :n 8}; it is drawn as a polygon, with its axes of mirror symmetry. Pressing a pulse (or a number, its index) adds or takes away an onset. :complement swaps onsets and silences, [:rotate 1] starts it a pulse later, [:n 12] makes the circle longer or shorter, :clear empties it, [:bars 4] and [:meter \"3/4\"] as euclid, a bang sends it again. Out, as euclid: a musical tree (left: a bar of n pulses with an :rtm whose shares are the intervals between onsets), the :rtm map alone (1), the pulses (2); and its measures (3): {:n :k :onsets :intervals :ivec — how often each distance occurs —, :evenness — the sum of the chords between all pairs (Block and Douthett) —, :even — that sum against the Euclidean rhythm's, 1 as even as it —, :deep — each distance a different number of times —, :flat — each once —, :axes — of mirror symmetry, in pulses —, :gap — the longest interval —, :oddity — no two onsets halving the cycle —, :euclid — the rotation of E(k,n) it is, or nil —, :fourier and :phases — its Fourier coefficients f1 … f⌊n/2⌋, magnitudes 0…1 and phases in degrees: |f1| near 0 balanced, |f_k| largest when maximally even —}; with the word fourier the magnitudes are drawn too, a bar each. Its right inlet (cold) takes the pitches the notes take in turn, as euclid's.",
|
|
31
|
+
"source": ";; necklace · a cyclic rhythm on the circle, and its geometry (Toussaint)\n;; Part of @kairotic/rhythm. Written against the Kairotic API (api/…).\n;; A rhythm that repeats is a necklace: k onsets among n pulses around a circle, time clockwise from the\n;; top. Seen so, it is the same object as a pitch-class set on pcclock, and the same geometry measures it\n;; (Toussaint, \"The Geometry of Musical Rhythm\"): its full-interval vector (how often each distance between\n;; onsets occurs), its evenness (the sum of the chords between all pairs of onsets, after Block and Douthett;\n;; arcs are too coarse: the six 4/4 claves would all score the same), whether it is deep (each distance a\n;; different number of times, as the diatonic scale and the bembé), flat (each distance once), its axes of\n;; mirror symmetry, its longest gap, rhythmic oddity (no two onsets halving the cycle), and whether it is a\n;; rotation of the Euclidean rhythm E(k,n) — and its Fourier coefficients (after Amiot and Milne): |f1| near 0\n;; is a balanced rhythm, a maximal |f_k| among the rhythms of k onsets a maximally even one, and the others its\n;; periodicities (in 16 pulses f4 the quarter notes, f3 a three against the four).\n;; It is the rhythm box: generators (euclid) make pulses, the necklace holds them, shows them, is their editor\n;; (pressing a pulse adds or takes away an onset), measures them and writes them as a musical tree, its :rtm\n;; map and its pulses, with the pitches of its right inlet (talea and color).\n(let [TAU (* 2 js/Math.PI)\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 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 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 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 r3 (fn [x] (/ (js/Math.round (* 1000 x)) 1000))\n ;; ── what arrives, as pulses (ones and zeros), or nil when it is not a rhythm ──\n whole? (fn [x] (and (number? x) (== x (js/Math.round x))))\n from-shares (fn [sh] (when (and (sequential? sh) (seq sh) (every? (fn [x] (and (whole? x) (not (zero? x)))) sh))\n (vec (mapcat (fn [x] (if (pos? x) (cons 1 (repeat (dec x) 0)) (repeat (- x) 0))) sh))))\n from-onsets (fn [os n] (when (and (whole? n) (pos? n) (sequential? os) (every? whole? os))\n (let [on (set (map (fn [o] (mod o n)) os))] (mapv (fn [i] (if (on i) 1 0)) (range n)))))\n ;; the first :rtm of a tree (as euclid sends it)\n rtm-in (fn rtm-in [t] (when (sequential? t)\n (if (= :rtm (first t)) (second t) (some rtm-in (filter sequential? t)))))\n ;; a list: ones and zeros are pulses; other whole numbers, the intervals between onsets (3 3 2)\n pulses-of-list (fn [v] (when (and (sequential? v) (seq v) (every? whole? v))\n (if (every? #{0 1} v) (vec v) (when (every? pos? v) (from-shares v)))))\n pulses-of (fn [v]\n (cond\n ;; box notation (TUBS): \"x..x..x.\" (x, X or 1 an onset; . - _ or 0 a pulse without one)\n (string? v) (let [cs (remove #{\" \"} (seq v))]\n (when (and (seq cs) (every? #{\"x\" \"X\" \"1\" \".\" \"-\" \"_\" \"0\"} cs))\n (mapv (fn [c] (if (#{\"x\" \"X\" \"1\"} c) 1 0)) cs)))\n (map? v) (cond (contains? v :shares) (from-shares (:shares v))\n (contains? v :pulses) (pulses-of-list (:pulses v))\n (contains? v :onsets) (from-onsets (:onsets v) (:n v)))\n (and (sequential? v) (keyword? (first v))) (some-> (rtm-in v) :shares from-shares)\n :else nil))\n ;; ── its geometry ──\n dist (fn [n a b] (let [d (js/Math.abs (- a b))] (min d (- n d))))\n pairs (fn [os] (for [i (range (count os)) j (range (inc i) (count os))] [(nth os i) (nth os j)]))\n ivec-of (fn [n os] (let [c (frequencies (map (fn [[a b]] (dist n a b)) (pairs os)))]\n (mapv (fn [d] (get c d 0)) (range 1 (inc (quot n 2))))))\n evenness-of (fn [n os] (reduce + 0 (map (fn [[a b]] (* 2 (js/Math.sin (/ (* js/Math.PI (dist n a b)) n)))) (pairs os))))\n ;; the axes of mirror symmetry, in pulses: x → a − x keeps the set; the axis passes through a/2 (and a/2 + n/2)\n axes-of (fn [n os] (let [s (set os)]\n (if (empty? s) []\n (vec (for [a (range n) :when (= s (set (map (fn [x] (mod (- a x) n)) os)))] (/ a 2))))))\n ;; the Fourier coefficients of the onsets, f1 … f⌊n/2⌋: magnitudes 0…1 (over k) and phases in degrees\n fourier-of (fn [n os]\n (let [k (count os)]\n (vec (for [j (range 1 (inc (quot n 2)))]\n (if (zero? k) [0 0]\n [(/ (reduce + (map (fn [x] (js/Math.cos (/ (* TAU j x) n))) os)) k)\n (- (/ (reduce + (map (fn [x] (js/Math.sin (/ (* TAU j x) n))) os)) k))])))))\n measures (fn [ps]\n (let [n (count ps) os (onsets-of ps) k (count os) iv (ivec-of n os) ev (evenness-of n os)\n e (bjorklund k n) eev (evenness-of n (onsets-of e))\n er (first (filter (fn [r] (= ps (rotate e r))) (range (max n 1))))]\n {:n n :k k :onsets os :intervals (intervals-of ps) :ivec iv\n :evenness (r3 ev) :even (if (pos? eev) (r3 (/ ev eev)) 1)\n :deep (and (>= k 2) (= (count (distinct iv)) (count iv)))\n :flat (and (seq iv) (every? #{1} iv))\n :axes (axes-of n os)\n :gap (if (seq os) (apply max (intervals-of ps)) n)\n :oddity (or (odd? n) (not-any? (fn [[a b]] (= (* 2 (dist n a b)) n)) (pairs os)))\n :euclid er\n :fourier (mapv (fn [[a b]] (r3 (js/Math.hypot a b))) (fourier-of n os))\n :phases (mapv (fn [[a b]] (if (< (js/Math.hypot a b) 1e-9) 0 (r3 (* (/ 180 js/Math.PI) (js/Math.atan2 b a))))) (fourier-of n os))}))\n fourier? (fn [args] (some (fn [a] (= \"fourier\" (if (keyword? a) (name a) (str a)))) (if (map? args) (when (:fourier args) [:fourier]) args)))\n ;; ── as euclid sends a rhythm: the meter of a bar of n pulses, the pitches, the color over bars ──\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 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 hz->m (fn [x] (when (and (number? x) (pos? x)) (/ (js/Math.round (* 1000 (+ 69 (* 12 (js/Math.log2 (/ x 440)))))) 1000)))\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 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 rhythm (fn [ps st]\n (let [k (count (onsets-of ps)) bars (:bars st) meter (or (:meter st) (meter-of (count ps)))\n rtm (merge {:shares (shares-of ps)} (or (:pm st) {}))\n bar (fn [i] (let [a (color-at rtm (* i k))]\n (if (zero? i) [:measure {:meter meter} [:rtm a]] [:measure [:rtm a]])))]\n {:rtm rtm :tree (into [:voice] (map bar (range bars)))}))\n ;; what goes out (the last first, as Max does): the measures (3), the pulses (2), the :rtm map (1), the tree (0)\n outs (fn [ps st] (let [r (rhythm ps st)] [[3 (measures ps)] [2 ps] [1 (:rtm r)] [0 (:tree r)]]))\n ;; a new state: sent when the rhythm, its bars or its meter are new (the same again changes nothing); a bang anyway\n settle (fn [st st2 always?]\n (let [ps (:pulses st2) key [ps (:bars st2) (:meter st2)]\n show (assoc (measures ps) :pulses ps)]\n (cond (empty? ps) {:state st2}\n (and (not always?) (= key (:sent st))) {:state st2 :show show}\n :else {:state (assoc st2 :sent key) :show show :out (outs ps st2)})))\n polar (fn [cx cy R i n] (let [a (* TAU (/ i n))] [(+ cx (* R (js/Math.sin a))) (- cy (* R (js/Math.cos a)))]))]\n {;; ── about ──\n :class \"necklace\"\n :license \"MPL-2.0\"\n :doc \"A cyclic rhythm on the circle and its geometry (Toussaint): k onsets among n pulses around a circle, time clockwise from the top — the same object as a pitch-class set on pcclock. A rhythm arrives as pulses (ones and zeros, as euclid's right outlet sends them), as intervals between onsets ([3 3 2]), as box notation (\\\"x..x..x.\\\"), as an :rtm map ({:shares [3 3 2]}, euclid's middle outlet), a tree with an :rtm, or {:onsets [0 3 6] :n 8}; it is drawn as a polygon, with its axes of mirror symmetry. Pressing a pulse (or a number, its index) adds or takes away an onset. :complement swaps onsets and silences, [:rotate 1] starts it a pulse later, [:n 12] makes the circle longer or shorter, :clear empties it, [:bars 4] and [:meter \\\"3/4\\\"] as euclid, a bang sends it again. Out, as euclid: a musical tree (left: a bar of n pulses with an :rtm whose shares are the intervals between onsets), the :rtm map alone (1), the pulses (2); and its measures (3): {:n :k :onsets :intervals :ivec — how often each distance occurs —, :evenness — the sum of the chords between all pairs (Block and Douthett) —, :even — that sum against the Euclidean rhythm's, 1 as even as it —, :deep — each distance a different number of times —, :flat — each once —, :axes — of mirror symmetry, in pulses —, :gap — the longest interval —, :oddity — no two onsets halving the cycle —, :euclid — the rotation of E(k,n) it is, or nil —, :fourier and :phases — its Fourier coefficients f1 … f⌊n/2⌋, magnitudes 0…1 and phases in degrees: |f1| near 0 balanced, |f_k| largest when maximally even —}; with the word fourier the magnitudes are drawn too, a bar each. Its right inlet (cold) takes the pitches the notes take in turn, as euclid's.\"\n :usage \"necklace [n 16] [bars 1] [midi] [fourier]\"\n :io [2 4]\n :size (fn [box] (if (fourier? (:args box)) [200 296] [200 240]))\n\n ;; ── arguments ──\n :args [[:n 16] [:bars 1] [:midi false] [:fourier false]]\n\n ;; ── logic ──\n :receive (fn [{:keys [inlet value state args]}]\n (let [st (or state {:pulses (vec (repeat (max 1 (js/Math.round (or (:n args) 16))) 0))\n :bars (api/clamp (js/Math.round (or (:bars args) 1)) 1 64) :meter nil :pm nil})\n ps (:pulses st) n (count ps)\n to (fn [m] (settle st (merge st m) false))\n toggle (fn [i] (let [i (mod (js/Math.round i) n)] (to {:pulses (update ps i (fn [x] (- 1 x)))})))]\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) (settle st st true)\n (#{:clear} value) (to {:pulses (vec (repeat n 0))})\n (#{:complement} value) (to {:pulses (mapv (fn [x] (- 1 x)) ps)})\n (number? value) (toggle value)\n (and (vector? value) (= :pressed (first value)) (number? (second value))) (toggle (second value))\n (and (vector? value) (= :rotate (first value)) (number? (second value))) (to {:pulses (rotate ps (js/Math.round (second value)))})\n (and (vector? value) (= :n (first value)) (number? (second value)))\n (let [m (api/clamp (js/Math.round (second value)) 1 128)]\n (to {:pulses (vec (take m (concat ps (repeat 0))))}))\n (and (vector? value) (= :bars (first value)) (number? (second value))) (to {:bars (api/clamp (js/Math.round (second value)) 1 64)})\n (and (vector? value) (= :meter (first value))) (to {:meter (meter-arg (second value))})\n :else (if-let [p (or (pulses-of-list value) (pulses-of value))]\n (to {:pulses p})\n {})))))\n ;; pressing a pulse adds or takes away an onset (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 [ps (vec (repeat (max 1 (js/Math.round (or (:n args) 16))) 0))] (assoc (measures ps) :pulses ps)))\n n (:n p) ps (:pulses p) os (:onsets p)\n fh (if (:fourier args) 60 0)\n cx (/ w 2) cy (/ (- h 44 fh) 2) R (- (min cx cy) 16)\n r (cond (> n 32) 2.2 (> n 16) 3 :else 4.5)\n flags (remove nil? [(str \"even \" (:even p))\n (let [a (count (:axes p))] (case a 0 \"asymmetric\" 1 \"1 axis\" (str a \" axes\")))\n (when (:deep p) \"deep\") (when (:flat p) \"flat\")\n (when (and (even? n) (:oddity p) (pos? (:k p))) \"oddity\")\n (when (:euclid p) (str \"E(\" (:k p) \",\" n \")\" (when (pos? (:euclid p)) (str \" ↻\" (:euclid p)))))])]\n (concat\n [[:circle {:cx cx :cy cy :r R :stroke :grid}]]\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 ;; the axes of symmetry, across the circle\n (for [a (:axes p)]\n (let [[x1 y1] (polar cx cy (+ R 7) a n) [x2 y2] (polar cx cy (+ R 7) (+ a (/ n 2)) n)]\n [:line {:x1 x1 :y1 y1 :x2 x2 :y2 y2 :stroke :kairos :weight 1 :opacity 0.5}]))\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 ;; the Fourier magnitudes, a bar each (f1 … f⌊n/2⌋), above the texts\n (when (:fourier args)\n (let [fs (or (:fourier p) []) m (count fs) bw (if (pos? m) (/ (- w 20) m) 0) base (- h 52)]\n (concat\n [[:line {:x1 10 :y1 base :x2 (- w 10) :y2 base :stroke :grid}]]\n (for [[j f] (map-indexed vector fs)]\n [:rect {:x (+ 10 (* j bw) 1) :y (- base (* 36 f)) :w (max 1 (- bw 2)) :h (* 36 f)\n :fill (if (= (inc j) (:k p)) :kairos :accent) :opacity 0.8}])\n (when (<= m 16)\n (for [j (range m)]\n [:text {:x (+ 10 (* j bw) (/ bw 2)) :y (+ base 9) :anchor :middle :size 7 :fill :soft} (str (inc j))])))))\n [[:text {:x cx :y (- h 29) :anchor :middle :size 10 :fill :ink}\n (str (:k p) \"/\" n \" · \" (if (seq (:intervals p)) (apply str (interpose \"-\" (:intervals p))) \"silence\"))]\n [:text {:x cx :y (- h 16) :anchor :middle :size 9 :fill :soft} (str \"<\" (apply str (interpose \" \" (:ivec p))) \">\")]\n [:text {:x cx :y (- h 3) :anchor :middle :size 9 :fill :soft} (apply str (interpose \" · \" flags))]])))})\n"
|
|
32
|
+
},
|
|
33
|
+
{
|
|
34
|
+
"class": "swap",
|
|
35
|
+
"license": "MPL-2.0",
|
|
36
|
+
"doc": "How far apart two rhythms are (Toussaint's swap distance). Both inlets take pulses of n pulses (euclid's, a necklace's outlet 2): the left one is compared with the right one, the reference (cold). A swap exchanges an onset and the silence beside it; the swap distance is how many turn one rhythm into the other — an onset moved far counts more than one moved near, as the Hamming distance (how many pulses differ) cannot tell. With different numbers of onsets, the directed swap distance (each onset of the shorter rhythm to its own of the other). Out, a map: {:swap — in the bar —, :circular — a swap may cross the end of the bar —, :necklace — the best over every rotation of the reference — and :rotation, the one that gives it, :hamming and :necklace-hamming, :n, :k [onsets of each]}. Rhythms of different lengths are not compared. A bang compares again.",
|
|
37
|
+
"source": ";; swap · how far apart two rhythms are (Toussaint's swap distance)\n;; Part of @kairotic/rhythm. Written against the Kairotic API (api/…).\n;; Two rhythms of n pulses, as pulses. A swap exchanges an onset and the silence beside it, and the swap\n;; distance is how many of them turn one rhythm into the other: an onset moved far counts more than one moved\n;; near, which the Hamming distance (how many pulses differ) cannot tell. With the same number of onsets it\n;; is the sum of |uᵢ − vᵢ| over the onsets in order; with different numbers, the directed swap distance (each\n;; onset of the shorter rhythm goes to its own onset of the other, the least moving in all). Around the circle\n;; a swap may cross the end of the bar; as necklaces, the rhythms are also compared at every rotation (the\n;; one that brings them closest is said). For the futuribles and the agents: is a variation still the same\n;; timeline? Both inlets take pulses (euclid's, a necklace's outlet 2); the left one compares, the right one\n;; is the reference (cold).\n(let [onsets-of (fn [ps] (vec (keep-indexed (fn [i x] (when (= 1 x) i)) ps)))\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 pulses? (fn [v] (and (sequential? v) (seq v) (every? #{0 1} v)))\n cdist (fn [n a b] (let [d (js/Math.abs (- a b))] (min d (- n d))))\n ;; onsets in order, each of the shorter list to its own of the longer one, the least moving in all\n ;; (dynamic programming over both lists: the directed swap distance; with equal lengths, Σ|uᵢ − vᵢ|)\n assign (fn [d us vs]\n (let [[a b] (if (<= (count us) (count vs)) [us vs] [vs us]) p (count a) q (count b)]\n (cond (zero? p) 0\n :else (loop [i 0 row (vec (repeat (inc q) 0))]\n (if (= i p)\n (peek row)\n (recur (inc i)\n (reduce (fn [nr j]\n (conj nr (min (if (> j (inc i)) (peek nr) js/Infinity)\n (+ (nth row (dec j)) (d (nth a i) (nth b (dec j)))))))\n [js/Infinity] (range 1 (inc q)))))))))\n linear (fn [A B] (assign (fn [x y] (js/Math.abs (- x y))) (onsets-of A) (onsets-of B)))\n ;; around the circle: with as many onsets, the best cyclic shift of the pairing; otherwise the best place\n ;; to cut the circle open\n circular (fn [A B]\n (let [n (count A) us (onsets-of A) vs (onsets-of B) k (count us)]\n (cond (or (empty? us) (empty? vs)) (if (= (count us) (count vs)) 0 nil)\n (= k (count vs)) (apply min (for [s (range k)] (reduce + (map (fn [i] (cdist n (nth us i) (nth vs (mod (+ i s) k)))) (range k)))))\n :else (apply min (for [c (range n)]\n (assign (fn [x y] (cdist n x y)) (onsets-of (rotate A c)) (onsets-of (rotate B c))))))))\n hamming (fn [A B] (count (filter false? (map = A B))))\n compare-them (fn [A B]\n (let [n (count A) ka (count (onsets-of A)) kb (count (onsets-of B))\n ;; a rhythm without onsets is not far from another one by swaps: only from silence\n none? (and (or (zero? ka) (zero? kb)) (not= ka kb))\n rs (vec (for [r (range n)] (circular A (rotate B r))))\n best (when-not none? (apply min rs))\n hs (vec (for [r (range n)] (hamming A (rotate B r))))]\n {:n n :k [ka kb]\n :swap (when-not none? (linear A B)) :circular (when-not none? (circular A B))\n :necklace best :rotation (when best (first (keep-indexed (fn [r x] (when (= x best) r)) rs)))\n :hamming (hamming A B) :necklace-hamming (apply min hs)}))]\n {;; ── about ──\n :class \"swap\"\n :license \"MPL-2.0\"\n :doc \"How far apart two rhythms are (Toussaint's swap distance). Both inlets take pulses of n pulses (euclid's, a necklace's outlet 2): the left one is compared with the right one, the reference (cold). A swap exchanges an onset and the silence beside it; the swap distance is how many turn one rhythm into the other — an onset moved far counts more than one moved near, as the Hamming distance (how many pulses differ) cannot tell. With different numbers of onsets, the directed swap distance (each onset of the shorter rhythm to its own of the other). Out, a map: {:swap — in the bar —, :circular — a swap may cross the end of the bar —, :necklace — the best over every rotation of the reference — and :rotation, the one that gives it, :hamming and :necklace-hamming, :n, :k [onsets of each]}. Rhythms of different lengths are not compared. A bang compares again.\"\n :usage \"swap\"\n :io [2 1]\n\n ;; ── logic ──\n :receive (fn [{:keys [inlet value state]}]\n (let [st (or state {})]\n (cond\n (= inlet 1) (if (pulses? value) {:state (assoc st :ref (vec value))} {})\n (and (#{:bang} value) (:a st)) (let [A (:a st) B (:ref st)]\n (if (and B (= (count A) (count B))) {:out [[0 (compare-them A B)]]} {}))\n (pulses? value) (let [A (vec value) B (:ref st)]\n (cond (nil? B) {:state (assoc st :a A) :show \"no reference yet (right inlet)\"}\n (not= (count A) (count B)) {:state (assoc st :a A) :show (str (count A) \" pulses against \" (count B) \": not compared\")}\n :else (let [m (compare-them A B)]\n {:state (assoc st :a A) :show (str \"swap \" (:swap m) \" · necklace \" (:necklace m)) :out [[0 m]]})))\n :else {})))})\n"
|
|
20
38
|
}
|
|
21
39
|
]
|
|
22
40
|
};
|
package/dist/necklace.mjs
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
// Generated by packages/build.mjs from src/necklace.cljs
|
|
2
2
|
export default {
|
|
3
3
|
"class": "necklace",
|
|
4
|
-
"version": "0.
|
|
4
|
+
"version": "0.3.0",
|
|
5
5
|
"author": "bonuoq",
|
|
6
6
|
"license": "MPL-2.0",
|
|
7
|
-
"doc": "A cyclic rhythm on the circle and its geometry (Toussaint): k onsets among n pulses around a circle, time clockwise from the top — the same object as a pitch-class set on pcclock. A rhythm arrives as pulses (ones and zeros, as euclid's right outlet sends them), as intervals between onsets ([3 3 2]), as box notation (\"x..x..x.\"), as an :rtm map ({:shares [3 3 2]}, euclid's middle outlet), a tree with an :rtm, or {:onsets [0 3 6] :n 8}; it is drawn as a polygon, with its axes of mirror symmetry. Pressing a pulse (or a number, its index) adds or takes away an onset. :complement swaps onsets and silences, [:rotate 1] starts it a pulse later, [:n 12] makes the circle longer or shorter, :clear empties it, [:bars 4] and [:meter \"3/4\"] as euclid, a bang sends it again. Out, as euclid: a musical tree (left: a bar of n pulses with an :rtm whose shares are the intervals between onsets), the :rtm map alone (1), the pulses (2); and its measures (3): {:n :k :onsets :intervals :ivec — how often each distance occurs —, :evenness — the sum of the chords between all pairs (Block and Douthett) —, :even — that sum against the Euclidean rhythm's, 1 as even as it —, :deep — each distance a different number of times —, :flat — each once —, :axes — of mirror symmetry, in pulses —, :gap — the longest interval —, :oddity — no two onsets halving the cycle —, :euclid — the rotation of E(k,n) it is, or nil}. Its right inlet (cold) takes the pitches the notes take in turn, as euclid's.",
|
|
8
|
-
"source": ";; necklace · a cyclic rhythm on the circle, and its geometry (Toussaint)\n;; Part of @kairotic/rhythm. Written against the Kairotic API (api/…).\n;; A rhythm that repeats is a necklace: k onsets among n pulses around a circle, time clockwise from the\n;; top. Seen so, it is the same object as a pitch-class set on pcclock, and the same geometry measures it\n;; (Toussaint, \"The Geometry of Musical Rhythm\"): its full-interval vector (how often each distance between\n;; onsets occurs), its evenness (the sum of the chords between all pairs of onsets, after Block and Douthett;\n;; arcs are too coarse: the six 4/4 claves would all score the same), whether it is deep (each distance a\n;; different number of times, as the diatonic scale and the bembé), flat (each distance once), its axes of\n;; mirror symmetry, its longest gap, rhythmic oddity (no two onsets halving the cycle), and whether it is a\n;; rotation of the Euclidean rhythm E(k,n). Pressing a pulse adds or takes away an onset: the necklace is\n;; also an editor. What it sends is as euclid's — a musical tree, its :rtm map, its pulses —, so it merges\n;; with pitches the same way (the right inlet, or merge with outlet 1), and its measures go out on the right.\n(let [TAU (* 2 js/Math.PI)\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 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 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 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 r3 (fn [x] (/ (js/Math.round (* 1000 x)) 1000))\n ;; ── what arrives, as pulses (ones and zeros), or nil when it is not a rhythm ──\n whole? (fn [x] (and (number? x) (== x (js/Math.round x))))\n from-shares (fn [sh] (when (and (sequential? sh) (seq sh) (every? (fn [x] (and (whole? x) (not (zero? x)))) sh))\n (vec (mapcat (fn [x] (if (pos? x) (cons 1 (repeat (dec x) 0)) (repeat (- x) 0))) sh))))\n from-onsets (fn [os n] (when (and (whole? n) (pos? n) (sequential? os) (every? whole? os))\n (let [on (set (map (fn [o] (mod o n)) os))] (mapv (fn [i] (if (on i) 1 0)) (range n)))))\n ;; the first :rtm of a tree (as euclid sends it)\n rtm-in (fn rtm-in [t] (when (sequential? t)\n (if (= :rtm (first t)) (second t) (some rtm-in (filter sequential? t)))))\n ;; a list: ones and zeros are pulses; other whole numbers, the intervals between onsets (3 3 2)\n pulses-of-list (fn [v] (when (and (sequential? v) (seq v) (every? whole? v))\n (if (every? #{0 1} v) (vec v) (when (every? pos? v) (from-shares v)))))\n pulses-of (fn [v]\n (cond\n ;; box notation (TUBS): \"x..x..x.\" (x, X or 1 an onset; . - _ or 0 a pulse without one)\n (string? v) (let [cs (remove #{\" \"} (seq v))]\n (when (and (seq cs) (every? #{\"x\" \"X\" \"1\" \".\" \"-\" \"_\" \"0\"} cs))\n (mapv (fn [c] (if (#{\"x\" \"X\" \"1\"} c) 1 0)) cs)))\n (map? v) (cond (contains? v :shares) (from-shares (:shares v))\n (contains? v :pulses) (pulses-of-list (:pulses v))\n (contains? v :onsets) (from-onsets (:onsets v) (:n v)))\n (and (sequential? v) (keyword? (first v))) (some-> (rtm-in v) :shares from-shares)\n :else nil))\n ;; ── its geometry ──\n dist (fn [n a b] (let [d (js/Math.abs (- a b))] (min d (- n d))))\n pairs (fn [os] (for [i (range (count os)) j (range (inc i) (count os))] [(nth os i) (nth os j)]))\n ivec-of (fn [n os] (let [c (frequencies (map (fn [[a b]] (dist n a b)) (pairs os)))]\n (mapv (fn [d] (get c d 0)) (range 1 (inc (quot n 2))))))\n evenness-of (fn [n os] (reduce + 0 (map (fn [[a b]] (* 2 (js/Math.sin (/ (* js/Math.PI (dist n a b)) n)))) (pairs os))))\n ;; the axes of mirror symmetry, in pulses: x → a − x keeps the set; the axis passes through a/2 (and a/2 + n/2)\n axes-of (fn [n os] (let [s (set os)]\n (if (empty? s) []\n (vec (for [a (range n) :when (= s (set (map (fn [x] (mod (- a x) n)) os)))] (/ a 2))))))\n measures (fn [ps]\n (let [n (count ps) os (onsets-of ps) k (count os) iv (ivec-of n os) ev (evenness-of n os)\n e (bjorklund k n) eev (evenness-of n (onsets-of e))\n er (first (filter (fn [r] (= ps (rotate e r))) (range (max n 1))))]\n {:n n :k k :onsets os :intervals (intervals-of ps) :ivec iv\n :evenness (r3 ev) :even (if (pos? eev) (r3 (/ ev eev)) 1)\n :deep (and (>= k 2) (= (count (distinct iv)) (count iv)))\n :flat (and (seq iv) (every? #{1} iv))\n :axes (axes-of n os)\n :gap (if (seq os) (apply max (intervals-of ps)) n)\n :oddity (or (odd? n) (not-any? (fn [[a b]] (= (* 2 (dist n a b)) n)) (pairs os)))\n :euclid er}))\n ;; ── as euclid sends a rhythm: the meter of a bar of n pulses, the pitches, the color over bars ──\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 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 hz->m (fn [x] (when (and (number? x) (pos? x)) (/ (js/Math.round (* 1000 (+ 69 (* 12 (js/Math.log2 (/ x 440)))))) 1000)))\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 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 rhythm (fn [ps st]\n (let [k (count (onsets-of ps)) bars (:bars st) meter (or (:meter st) (meter-of (count ps)))\n rtm (merge {:shares (shares-of ps)} (or (:pm st) {}))\n bar (fn [i] (let [a (color-at rtm (* i k))]\n (if (zero? i) [:measure {:meter meter} [:rtm a]] [:measure [:rtm a]])))]\n {:rtm rtm :tree (into [:voice] (map bar (range bars)))}))\n ;; what goes out (the last first, as Max does): the measures (3), the pulses (2), the :rtm map (1), the tree (0)\n outs (fn [ps st] (let [r (rhythm ps st)] [[3 (measures ps)] [2 ps] [1 (:rtm r)] [0 (:tree r)]]))\n ;; a new state: sent when the rhythm, its bars or its meter are new (the same again changes nothing); a bang anyway\n settle (fn [st st2 always?]\n (let [ps (:pulses st2) key [ps (:bars st2) (:meter st2)]\n show (assoc (measures ps) :pulses ps)]\n (cond (empty? ps) {:state st2}\n (and (not always?) (= key (:sent st))) {:state st2 :show show}\n :else {:state (assoc st2 :sent key) :show show :out (outs ps st2)})))\n polar (fn [cx cy R i n] (let [a (* TAU (/ i n))] [(+ cx (* R (js/Math.sin a))) (- cy (* R (js/Math.cos a)))]))]\n {;; ── about ──\n :class \"necklace\"\n :license \"MPL-2.0\"\n :doc \"A cyclic rhythm on the circle and its geometry (Toussaint): k onsets among n pulses around a circle, time clockwise from the top — the same object as a pitch-class set on pcclock. A rhythm arrives as pulses (ones and zeros, as euclid's right outlet sends them), as intervals between onsets ([3 3 2]), as box notation (\\\"x..x..x.\\\"), as an :rtm map ({:shares [3 3 2]}, euclid's middle outlet), a tree with an :rtm, or {:onsets [0 3 6] :n 8}; it is drawn as a polygon, with its axes of mirror symmetry. Pressing a pulse (or a number, its index) adds or takes away an onset. :complement swaps onsets and silences, [:rotate 1] starts it a pulse later, [:n 12] makes the circle longer or shorter, :clear empties it, [:bars 4] and [:meter \\\"3/4\\\"] as euclid, a bang sends it again. Out, as euclid: a musical tree (left: a bar of n pulses with an :rtm whose shares are the intervals between onsets), the :rtm map alone (1), the pulses (2); and its measures (3): {:n :k :onsets :intervals :ivec — how often each distance occurs —, :evenness — the sum of the chords between all pairs (Block and Douthett) —, :even — that sum against the Euclidean rhythm's, 1 as even as it —, :deep — each distance a different number of times —, :flat — each once —, :axes — of mirror symmetry, in pulses —, :gap — the longest interval —, :oddity — no two onsets halving the cycle —, :euclid — the rotation of E(k,n) it is, or nil}. Its right inlet (cold) takes the pitches the notes take in turn, as euclid's.\"\n :usage \"necklace [n 16] [bars 1] [midi]\"\n :io [2 4]\n :size [200 240]\n\n ;; ── arguments ──\n :args [[:n 16] [:bars 1] [:midi false]]\n\n ;; ── logic ──\n :receive (fn [{:keys [inlet value state args]}]\n (let [st (or state {:pulses (vec (repeat (max 1 (js/Math.round (or (:n args) 16))) 0))\n :bars (api/clamp (js/Math.round (or (:bars args) 1)) 1 64) :meter nil :pm nil})\n ps (:pulses st) n (count ps)\n to (fn [m] (settle st (merge st m) false))\n toggle (fn [i] (let [i (mod (js/Math.round i) n)] (to {:pulses (update ps i (fn [x] (- 1 x)))})))]\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) (settle st st true)\n (#{:clear} value) (to {:pulses (vec (repeat n 0))})\n (#{:complement} value) (to {:pulses (mapv (fn [x] (- 1 x)) ps)})\n (number? value) (toggle value)\n (and (vector? value) (= :pressed (first value)) (number? (second value))) (toggle (second value))\n (and (vector? value) (= :rotate (first value)) (number? (second value))) (to {:pulses (rotate ps (js/Math.round (second value)))})\n (and (vector? value) (= :n (first value)) (number? (second value)))\n (let [m (api/clamp (js/Math.round (second value)) 1 128)]\n (to {:pulses (vec (take m (concat ps (repeat 0))))}))\n (and (vector? value) (= :bars (first value)) (number? (second value))) (to {:bars (api/clamp (js/Math.round (second value)) 1 64)})\n (and (vector? value) (= :meter (first value))) (to {:meter (meter-arg (second value))})\n :else (if-let [p (or (pulses-of-list value) (pulses-of value))]\n (to {:pulses p})\n {})))))\n ;; pressing a pulse adds or takes away an onset (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 [ps (vec (repeat (max 1 (js/Math.round (or (:n args) 16))) 0))] (assoc (measures ps) :pulses ps)))\n n (:n p) ps (:pulses p) os (:onsets p)\n cx (/ w 2) cy (/ (- h 44) 2) R (- (min cx cy) 16)\n r (cond (> n 32) 2.2 (> n 16) 3 :else 4.5)\n flags (remove nil? [(str \"even \" (:even p))\n (let [a (count (:axes p))] (case a 0 \"asymmetric\" 1 \"1 axis\" (str a \" axes\")))\n (when (:deep p) \"deep\") (when (:flat p) \"flat\")\n (when (and (even? n) (:oddity p) (pos? (:k p))) \"oddity\")\n (when (:euclid p) (str \"E(\" (:k p) \",\" n \")\" (when (pos? (:euclid p)) (str \" ↻\" (:euclid p)))))])]\n (concat\n [[:circle {:cx cx :cy cy :r R :stroke :grid}]]\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 ;; the axes of symmetry, across the circle\n (for [a (:axes p)]\n (let [[x1 y1] (polar cx cy (+ R 7) a n) [x2 y2] (polar cx cy (+ R 7) (+ a (/ n 2)) n)]\n [:line {:x1 x1 :y1 y1 :x2 x2 :y2 y2 :stroke :kairos :weight 1 :opacity 0.5}]))\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 29) :anchor :middle :size 10 :fill :ink}\n (str (:k p) \"/\" n \" · \" (if (seq (:intervals p)) (apply str (interpose \"-\" (:intervals p))) \"silence\"))]\n [:text {:x cx :y (- h 16) :anchor :middle :size 9 :fill :soft} (str \"<\" (apply str (interpose \" \" (:ivec p))) \">\")]\n [:text {:x cx :y (- h 3) :anchor :middle :size 9 :fill :soft} (apply str (interpose \" · \" flags))]])))})\n"
|
|
7
|
+
"doc": "A cyclic rhythm on the circle and its geometry (Toussaint): k onsets among n pulses around a circle, time clockwise from the top — the same object as a pitch-class set on pcclock. A rhythm arrives as pulses (ones and zeros, as euclid's right outlet sends them), as intervals between onsets ([3 3 2]), as box notation (\"x..x..x.\"), as an :rtm map ({:shares [3 3 2]}, euclid's middle outlet), a tree with an :rtm, or {:onsets [0 3 6] :n 8}; it is drawn as a polygon, with its axes of mirror symmetry. Pressing a pulse (or a number, its index) adds or takes away an onset. :complement swaps onsets and silences, [:rotate 1] starts it a pulse later, [:n 12] makes the circle longer or shorter, :clear empties it, [:bars 4] and [:meter \"3/4\"] as euclid, a bang sends it again. Out, as euclid: a musical tree (left: a bar of n pulses with an :rtm whose shares are the intervals between onsets), the :rtm map alone (1), the pulses (2); and its measures (3): {:n :k :onsets :intervals :ivec — how often each distance occurs —, :evenness — the sum of the chords between all pairs (Block and Douthett) —, :even — that sum against the Euclidean rhythm's, 1 as even as it —, :deep — each distance a different number of times —, :flat — each once —, :axes — of mirror symmetry, in pulses —, :gap — the longest interval —, :oddity — no two onsets halving the cycle —, :euclid — the rotation of E(k,n) it is, or nil —, :fourier and :phases — its Fourier coefficients f1 … f⌊n/2⌋, magnitudes 0…1 and phases in degrees: |f1| near 0 balanced, |f_k| largest when maximally even —}; with the word fourier the magnitudes are drawn too, a bar each. Its right inlet (cold) takes the pitches the notes take in turn, as euclid's.",
|
|
8
|
+
"source": ";; necklace · a cyclic rhythm on the circle, and its geometry (Toussaint)\n;; Part of @kairotic/rhythm. Written against the Kairotic API (api/…).\n;; A rhythm that repeats is a necklace: k onsets among n pulses around a circle, time clockwise from the\n;; top. Seen so, it is the same object as a pitch-class set on pcclock, and the same geometry measures it\n;; (Toussaint, \"The Geometry of Musical Rhythm\"): its full-interval vector (how often each distance between\n;; onsets occurs), its evenness (the sum of the chords between all pairs of onsets, after Block and Douthett;\n;; arcs are too coarse: the six 4/4 claves would all score the same), whether it is deep (each distance a\n;; different number of times, as the diatonic scale and the bembé), flat (each distance once), its axes of\n;; mirror symmetry, its longest gap, rhythmic oddity (no two onsets halving the cycle), and whether it is a\n;; rotation of the Euclidean rhythm E(k,n) — and its Fourier coefficients (after Amiot and Milne): |f1| near 0\n;; is a balanced rhythm, a maximal |f_k| among the rhythms of k onsets a maximally even one, and the others its\n;; periodicities (in 16 pulses f4 the quarter notes, f3 a three against the four).\n;; It is the rhythm box: generators (euclid) make pulses, the necklace holds them, shows them, is their editor\n;; (pressing a pulse adds or takes away an onset), measures them and writes them as a musical tree, its :rtm\n;; map and its pulses, with the pitches of its right inlet (talea and color).\n(let [TAU (* 2 js/Math.PI)\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 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 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 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 r3 (fn [x] (/ (js/Math.round (* 1000 x)) 1000))\n ;; ── what arrives, as pulses (ones and zeros), or nil when it is not a rhythm ──\n whole? (fn [x] (and (number? x) (== x (js/Math.round x))))\n from-shares (fn [sh] (when (and (sequential? sh) (seq sh) (every? (fn [x] (and (whole? x) (not (zero? x)))) sh))\n (vec (mapcat (fn [x] (if (pos? x) (cons 1 (repeat (dec x) 0)) (repeat (- x) 0))) sh))))\n from-onsets (fn [os n] (when (and (whole? n) (pos? n) (sequential? os) (every? whole? os))\n (let [on (set (map (fn [o] (mod o n)) os))] (mapv (fn [i] (if (on i) 1 0)) (range n)))))\n ;; the first :rtm of a tree (as euclid sends it)\n rtm-in (fn rtm-in [t] (when (sequential? t)\n (if (= :rtm (first t)) (second t) (some rtm-in (filter sequential? t)))))\n ;; a list: ones and zeros are pulses; other whole numbers, the intervals between onsets (3 3 2)\n pulses-of-list (fn [v] (when (and (sequential? v) (seq v) (every? whole? v))\n (if (every? #{0 1} v) (vec v) (when (every? pos? v) (from-shares v)))))\n pulses-of (fn [v]\n (cond\n ;; box notation (TUBS): \"x..x..x.\" (x, X or 1 an onset; . - _ or 0 a pulse without one)\n (string? v) (let [cs (remove #{\" \"} (seq v))]\n (when (and (seq cs) (every? #{\"x\" \"X\" \"1\" \".\" \"-\" \"_\" \"0\"} cs))\n (mapv (fn [c] (if (#{\"x\" \"X\" \"1\"} c) 1 0)) cs)))\n (map? v) (cond (contains? v :shares) (from-shares (:shares v))\n (contains? v :pulses) (pulses-of-list (:pulses v))\n (contains? v :onsets) (from-onsets (:onsets v) (:n v)))\n (and (sequential? v) (keyword? (first v))) (some-> (rtm-in v) :shares from-shares)\n :else nil))\n ;; ── its geometry ──\n dist (fn [n a b] (let [d (js/Math.abs (- a b))] (min d (- n d))))\n pairs (fn [os] (for [i (range (count os)) j (range (inc i) (count os))] [(nth os i) (nth os j)]))\n ivec-of (fn [n os] (let [c (frequencies (map (fn [[a b]] (dist n a b)) (pairs os)))]\n (mapv (fn [d] (get c d 0)) (range 1 (inc (quot n 2))))))\n evenness-of (fn [n os] (reduce + 0 (map (fn [[a b]] (* 2 (js/Math.sin (/ (* js/Math.PI (dist n a b)) n)))) (pairs os))))\n ;; the axes of mirror symmetry, in pulses: x → a − x keeps the set; the axis passes through a/2 (and a/2 + n/2)\n axes-of (fn [n os] (let [s (set os)]\n (if (empty? s) []\n (vec (for [a (range n) :when (= s (set (map (fn [x] (mod (- a x) n)) os)))] (/ a 2))))))\n ;; the Fourier coefficients of the onsets, f1 … f⌊n/2⌋: magnitudes 0…1 (over k) and phases in degrees\n fourier-of (fn [n os]\n (let [k (count os)]\n (vec (for [j (range 1 (inc (quot n 2)))]\n (if (zero? k) [0 0]\n [(/ (reduce + (map (fn [x] (js/Math.cos (/ (* TAU j x) n))) os)) k)\n (- (/ (reduce + (map (fn [x] (js/Math.sin (/ (* TAU j x) n))) os)) k))])))))\n measures (fn [ps]\n (let [n (count ps) os (onsets-of ps) k (count os) iv (ivec-of n os) ev (evenness-of n os)\n e (bjorklund k n) eev (evenness-of n (onsets-of e))\n er (first (filter (fn [r] (= ps (rotate e r))) (range (max n 1))))]\n {:n n :k k :onsets os :intervals (intervals-of ps) :ivec iv\n :evenness (r3 ev) :even (if (pos? eev) (r3 (/ ev eev)) 1)\n :deep (and (>= k 2) (= (count (distinct iv)) (count iv)))\n :flat (and (seq iv) (every? #{1} iv))\n :axes (axes-of n os)\n :gap (if (seq os) (apply max (intervals-of ps)) n)\n :oddity (or (odd? n) (not-any? (fn [[a b]] (= (* 2 (dist n a b)) n)) (pairs os)))\n :euclid er\n :fourier (mapv (fn [[a b]] (r3 (js/Math.hypot a b))) (fourier-of n os))\n :phases (mapv (fn [[a b]] (if (< (js/Math.hypot a b) 1e-9) 0 (r3 (* (/ 180 js/Math.PI) (js/Math.atan2 b a))))) (fourier-of n os))}))\n fourier? (fn [args] (some (fn [a] (= \"fourier\" (if (keyword? a) (name a) (str a)))) (if (map? args) (when (:fourier args) [:fourier]) args)))\n ;; ── as euclid sends a rhythm: the meter of a bar of n pulses, the pitches, the color over bars ──\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 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 hz->m (fn [x] (when (and (number? x) (pos? x)) (/ (js/Math.round (* 1000 (+ 69 (* 12 (js/Math.log2 (/ x 440)))))) 1000)))\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 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 rhythm (fn [ps st]\n (let [k (count (onsets-of ps)) bars (:bars st) meter (or (:meter st) (meter-of (count ps)))\n rtm (merge {:shares (shares-of ps)} (or (:pm st) {}))\n bar (fn [i] (let [a (color-at rtm (* i k))]\n (if (zero? i) [:measure {:meter meter} [:rtm a]] [:measure [:rtm a]])))]\n {:rtm rtm :tree (into [:voice] (map bar (range bars)))}))\n ;; what goes out (the last first, as Max does): the measures (3), the pulses (2), the :rtm map (1), the tree (0)\n outs (fn [ps st] (let [r (rhythm ps st)] [[3 (measures ps)] [2 ps] [1 (:rtm r)] [0 (:tree r)]]))\n ;; a new state: sent when the rhythm, its bars or its meter are new (the same again changes nothing); a bang anyway\n settle (fn [st st2 always?]\n (let [ps (:pulses st2) key [ps (:bars st2) (:meter st2)]\n show (assoc (measures ps) :pulses ps)]\n (cond (empty? ps) {:state st2}\n (and (not always?) (= key (:sent st))) {:state st2 :show show}\n :else {:state (assoc st2 :sent key) :show show :out (outs ps st2)})))\n polar (fn [cx cy R i n] (let [a (* TAU (/ i n))] [(+ cx (* R (js/Math.sin a))) (- cy (* R (js/Math.cos a)))]))]\n {;; ── about ──\n :class \"necklace\"\n :license \"MPL-2.0\"\n :doc \"A cyclic rhythm on the circle and its geometry (Toussaint): k onsets among n pulses around a circle, time clockwise from the top — the same object as a pitch-class set on pcclock. A rhythm arrives as pulses (ones and zeros, as euclid's right outlet sends them), as intervals between onsets ([3 3 2]), as box notation (\\\"x..x..x.\\\"), as an :rtm map ({:shares [3 3 2]}, euclid's middle outlet), a tree with an :rtm, or {:onsets [0 3 6] :n 8}; it is drawn as a polygon, with its axes of mirror symmetry. Pressing a pulse (or a number, its index) adds or takes away an onset. :complement swaps onsets and silences, [:rotate 1] starts it a pulse later, [:n 12] makes the circle longer or shorter, :clear empties it, [:bars 4] and [:meter \\\"3/4\\\"] as euclid, a bang sends it again. Out, as euclid: a musical tree (left: a bar of n pulses with an :rtm whose shares are the intervals between onsets), the :rtm map alone (1), the pulses (2); and its measures (3): {:n :k :onsets :intervals :ivec — how often each distance occurs —, :evenness — the sum of the chords between all pairs (Block and Douthett) —, :even — that sum against the Euclidean rhythm's, 1 as even as it —, :deep — each distance a different number of times —, :flat — each once —, :axes — of mirror symmetry, in pulses —, :gap — the longest interval —, :oddity — no two onsets halving the cycle —, :euclid — the rotation of E(k,n) it is, or nil —, :fourier and :phases — its Fourier coefficients f1 … f⌊n/2⌋, magnitudes 0…1 and phases in degrees: |f1| near 0 balanced, |f_k| largest when maximally even —}; with the word fourier the magnitudes are drawn too, a bar each. Its right inlet (cold) takes the pitches the notes take in turn, as euclid's.\"\n :usage \"necklace [n 16] [bars 1] [midi] [fourier]\"\n :io [2 4]\n :size (fn [box] (if (fourier? (:args box)) [200 296] [200 240]))\n\n ;; ── arguments ──\n :args [[:n 16] [:bars 1] [:midi false] [:fourier false]]\n\n ;; ── logic ──\n :receive (fn [{:keys [inlet value state args]}]\n (let [st (or state {:pulses (vec (repeat (max 1 (js/Math.round (or (:n args) 16))) 0))\n :bars (api/clamp (js/Math.round (or (:bars args) 1)) 1 64) :meter nil :pm nil})\n ps (:pulses st) n (count ps)\n to (fn [m] (settle st (merge st m) false))\n toggle (fn [i] (let [i (mod (js/Math.round i) n)] (to {:pulses (update ps i (fn [x] (- 1 x)))})))]\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) (settle st st true)\n (#{:clear} value) (to {:pulses (vec (repeat n 0))})\n (#{:complement} value) (to {:pulses (mapv (fn [x] (- 1 x)) ps)})\n (number? value) (toggle value)\n (and (vector? value) (= :pressed (first value)) (number? (second value))) (toggle (second value))\n (and (vector? value) (= :rotate (first value)) (number? (second value))) (to {:pulses (rotate ps (js/Math.round (second value)))})\n (and (vector? value) (= :n (first value)) (number? (second value)))\n (let [m (api/clamp (js/Math.round (second value)) 1 128)]\n (to {:pulses (vec (take m (concat ps (repeat 0))))}))\n (and (vector? value) (= :bars (first value)) (number? (second value))) (to {:bars (api/clamp (js/Math.round (second value)) 1 64)})\n (and (vector? value) (= :meter (first value))) (to {:meter (meter-arg (second value))})\n :else (if-let [p (or (pulses-of-list value) (pulses-of value))]\n (to {:pulses p})\n {})))))\n ;; pressing a pulse adds or takes away an onset (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 [ps (vec (repeat (max 1 (js/Math.round (or (:n args) 16))) 0))] (assoc (measures ps) :pulses ps)))\n n (:n p) ps (:pulses p) os (:onsets p)\n fh (if (:fourier args) 60 0)\n cx (/ w 2) cy (/ (- h 44 fh) 2) R (- (min cx cy) 16)\n r (cond (> n 32) 2.2 (> n 16) 3 :else 4.5)\n flags (remove nil? [(str \"even \" (:even p))\n (let [a (count (:axes p))] (case a 0 \"asymmetric\" 1 \"1 axis\" (str a \" axes\")))\n (when (:deep p) \"deep\") (when (:flat p) \"flat\")\n (when (and (even? n) (:oddity p) (pos? (:k p))) \"oddity\")\n (when (:euclid p) (str \"E(\" (:k p) \",\" n \")\" (when (pos? (:euclid p)) (str \" ↻\" (:euclid p)))))])]\n (concat\n [[:circle {:cx cx :cy cy :r R :stroke :grid}]]\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 ;; the axes of symmetry, across the circle\n (for [a (:axes p)]\n (let [[x1 y1] (polar cx cy (+ R 7) a n) [x2 y2] (polar cx cy (+ R 7) (+ a (/ n 2)) n)]\n [:line {:x1 x1 :y1 y1 :x2 x2 :y2 y2 :stroke :kairos :weight 1 :opacity 0.5}]))\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 ;; the Fourier magnitudes, a bar each (f1 … f⌊n/2⌋), above the texts\n (when (:fourier args)\n (let [fs (or (:fourier p) []) m (count fs) bw (if (pos? m) (/ (- w 20) m) 0) base (- h 52)]\n (concat\n [[:line {:x1 10 :y1 base :x2 (- w 10) :y2 base :stroke :grid}]]\n (for [[j f] (map-indexed vector fs)]\n [:rect {:x (+ 10 (* j bw) 1) :y (- base (* 36 f)) :w (max 1 (- bw 2)) :h (* 36 f)\n :fill (if (= (inc j) (:k p)) :kairos :accent) :opacity 0.8}])\n (when (<= m 16)\n (for [j (range m)]\n [:text {:x (+ 10 (* j bw) (/ bw 2)) :y (+ base 9) :anchor :middle :size 7 :fill :soft} (str (inc j))])))))\n [[:text {:x cx :y (- h 29) :anchor :middle :size 10 :fill :ink}\n (str (:k p) \"/\" n \" · \" (if (seq (:intervals p)) (apply str (interpose \"-\" (:intervals p))) \"silence\"))]\n [:text {:x cx :y (- h 16) :anchor :middle :size 9 :fill :soft} (str \"<\" (apply str (interpose \" \" (:ivec p))) \">\")]\n [:text {:x cx :y (- h 3) :anchor :middle :size 9 :fill :soft} (apply str (interpose \" · \" flags))]])))})\n"
|
|
9
9
|
};
|
package/dist/swap.mjs
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
// Generated by packages/build.mjs from src/swap.cljs
|
|
2
|
+
export default {
|
|
3
|
+
"class": "swap",
|
|
4
|
+
"version": "0.3.0",
|
|
5
|
+
"author": "bonuoq",
|
|
6
|
+
"license": "MPL-2.0",
|
|
7
|
+
"doc": "How far apart two rhythms are (Toussaint's swap distance). Both inlets take pulses of n pulses (euclid's, a necklace's outlet 2): the left one is compared with the right one, the reference (cold). A swap exchanges an onset and the silence beside it; the swap distance is how many turn one rhythm into the other — an onset moved far counts more than one moved near, as the Hamming distance (how many pulses differ) cannot tell. With different numbers of onsets, the directed swap distance (each onset of the shorter rhythm to its own of the other). Out, a map: {:swap — in the bar —, :circular — a swap may cross the end of the bar —, :necklace — the best over every rotation of the reference — and :rotation, the one that gives it, :hamming and :necklace-hamming, :n, :k [onsets of each]}. Rhythms of different lengths are not compared. A bang compares again.",
|
|
8
|
+
"source": ";; swap · how far apart two rhythms are (Toussaint's swap distance)\n;; Part of @kairotic/rhythm. Written against the Kairotic API (api/…).\n;; Two rhythms of n pulses, as pulses. A swap exchanges an onset and the silence beside it, and the swap\n;; distance is how many of them turn one rhythm into the other: an onset moved far counts more than one moved\n;; near, which the Hamming distance (how many pulses differ) cannot tell. With the same number of onsets it\n;; is the sum of |uᵢ − vᵢ| over the onsets in order; with different numbers, the directed swap distance (each\n;; onset of the shorter rhythm goes to its own onset of the other, the least moving in all). Around the circle\n;; a swap may cross the end of the bar; as necklaces, the rhythms are also compared at every rotation (the\n;; one that brings them closest is said). For the futuribles and the agents: is a variation still the same\n;; timeline? Both inlets take pulses (euclid's, a necklace's outlet 2); the left one compares, the right one\n;; is the reference (cold).\n(let [onsets-of (fn [ps] (vec (keep-indexed (fn [i x] (when (= 1 x) i)) ps)))\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 pulses? (fn [v] (and (sequential? v) (seq v) (every? #{0 1} v)))\n cdist (fn [n a b] (let [d (js/Math.abs (- a b))] (min d (- n d))))\n ;; onsets in order, each of the shorter list to its own of the longer one, the least moving in all\n ;; (dynamic programming over both lists: the directed swap distance; with equal lengths, Σ|uᵢ − vᵢ|)\n assign (fn [d us vs]\n (let [[a b] (if (<= (count us) (count vs)) [us vs] [vs us]) p (count a) q (count b)]\n (cond (zero? p) 0\n :else (loop [i 0 row (vec (repeat (inc q) 0))]\n (if (= i p)\n (peek row)\n (recur (inc i)\n (reduce (fn [nr j]\n (conj nr (min (if (> j (inc i)) (peek nr) js/Infinity)\n (+ (nth row (dec j)) (d (nth a i) (nth b (dec j)))))))\n [js/Infinity] (range 1 (inc q)))))))))\n linear (fn [A B] (assign (fn [x y] (js/Math.abs (- x y))) (onsets-of A) (onsets-of B)))\n ;; around the circle: with as many onsets, the best cyclic shift of the pairing; otherwise the best place\n ;; to cut the circle open\n circular (fn [A B]\n (let [n (count A) us (onsets-of A) vs (onsets-of B) k (count us)]\n (cond (or (empty? us) (empty? vs)) (if (= (count us) (count vs)) 0 nil)\n (= k (count vs)) (apply min (for [s (range k)] (reduce + (map (fn [i] (cdist n (nth us i) (nth vs (mod (+ i s) k)))) (range k)))))\n :else (apply min (for [c (range n)]\n (assign (fn [x y] (cdist n x y)) (onsets-of (rotate A c)) (onsets-of (rotate B c))))))))\n hamming (fn [A B] (count (filter false? (map = A B))))\n compare-them (fn [A B]\n (let [n (count A) ka (count (onsets-of A)) kb (count (onsets-of B))\n ;; a rhythm without onsets is not far from another one by swaps: only from silence\n none? (and (or (zero? ka) (zero? kb)) (not= ka kb))\n rs (vec (for [r (range n)] (circular A (rotate B r))))\n best (when-not none? (apply min rs))\n hs (vec (for [r (range n)] (hamming A (rotate B r))))]\n {:n n :k [ka kb]\n :swap (when-not none? (linear A B)) :circular (when-not none? (circular A B))\n :necklace best :rotation (when best (first (keep-indexed (fn [r x] (when (= x best) r)) rs)))\n :hamming (hamming A B) :necklace-hamming (apply min hs)}))]\n {;; ── about ──\n :class \"swap\"\n :license \"MPL-2.0\"\n :doc \"How far apart two rhythms are (Toussaint's swap distance). Both inlets take pulses of n pulses (euclid's, a necklace's outlet 2): the left one is compared with the right one, the reference (cold). A swap exchanges an onset and the silence beside it; the swap distance is how many turn one rhythm into the other — an onset moved far counts more than one moved near, as the Hamming distance (how many pulses differ) cannot tell. With different numbers of onsets, the directed swap distance (each onset of the shorter rhythm to its own of the other). Out, a map: {:swap — in the bar —, :circular — a swap may cross the end of the bar —, :necklace — the best over every rotation of the reference — and :rotation, the one that gives it, :hamming and :necklace-hamming, :n, :k [onsets of each]}. Rhythms of different lengths are not compared. A bang compares again.\"\n :usage \"swap\"\n :io [2 1]\n\n ;; ── logic ──\n :receive (fn [{:keys [inlet value state]}]\n (let [st (or state {})]\n (cond\n (= inlet 1) (if (pulses? value) {:state (assoc st :ref (vec value))} {})\n (and (#{:bang} value) (:a st)) (let [A (:a st) B (:ref st)]\n (if (and B (= (count A) (count B))) {:out [[0 (compare-them A B)]]} {}))\n (pulses? value) (let [A (vec value) B (:ref st)]\n (cond (nil? B) {:state (assoc st :a A) :show \"no reference yet (right inlet)\"}\n (not= (count A) (count B)) {:state (assoc st :a A) :show (str (count A) \" pulses against \" (count B) \": not compared\")}\n :else (let [m (compare-them A B)]\n {:state (assoc st :a A) :show (str \"swap \" (:swap m) \" · necklace \" (:necklace m)) :out [[0 m]]})))\n :else {})))})\n"
|
|
9
|
+
};
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@kairotic/rhythm",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"description": "Kairotic rhythm as geometry (after Toussaint):
|
|
3
|
+
"version": "0.3.0",
|
|
4
|
+
"description": "Kairotic rhythm as geometry (after Toussaint): necklace, the rhythm box (a cyclic rhythm on the circle: drawn, edited, measured — interval vector, evenness, deep, flat, axes of symmetry, oddity, Fourier coefficients — and written as a musical tree whose :rtm merges with any pitches); generators of pulses (euclid, chance, homometric); and swap, how far apart two rhythms are",
|
|
5
5
|
"author": "bonuoq",
|
|
6
6
|
"license": "MPL-2.0",
|
|
7
7
|
"repository": {
|
|
@@ -37,6 +37,9 @@
|
|
|
37
37
|
"toussaint",
|
|
38
38
|
"interval vector",
|
|
39
39
|
"talea",
|
|
40
|
-
"isorhythm"
|
|
40
|
+
"isorhythm",
|
|
41
|
+
"fourier",
|
|
42
|
+
"swap distance",
|
|
43
|
+
"homometric"
|
|
41
44
|
]
|
|
42
45
|
}
|
package/src/chance.cljs
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
;; chance · k onsets among n pulses, drawn with a seed
|
|
2
|
+
;; Part of @kairotic/rhythm. Written against the Kairotic API (api/…).
|
|
3
|
+
;; A generator of pulses, as euclid is, with chance instead of evenness: each bang draws another rhythm of k
|
|
4
|
+
;; onsets among n pulses. The draws are the seed's: draw i of seed s is always the same rhythm, so the same
|
|
5
|
+
;; seed plays the same game for everyone in a room and again from the history (:reset starts its draws
|
|
6
|
+
;; again). Against euclid's, a necklace's measures say how even or uneven chance came out.
|
|
7
|
+
(let [M 2147483647
|
|
8
|
+
;; Park–Miller, started from the seed and the number of the draw, a few turns to mix them
|
|
9
|
+
rng (fn [seed i]
|
|
10
|
+
(let [s (volatile! (inc (mod (+ (* 7919 (js/Math.abs (js/Math.round seed))) (* 104729 i) 12345) (dec M))))]
|
|
11
|
+
(dotimes [_ 4] (vreset! s (mod (* @s 16807) M)))
|
|
12
|
+
(fn [] (vreset! s (mod (* @s 16807) M)) (/ (dec @s) (dec M)))))
|
|
13
|
+
;; k of the n pulses, as a shuffle stopped after k (Fisher–Yates)
|
|
14
|
+
draw (fn [k n seed i]
|
|
15
|
+
(let [r (rng seed i)
|
|
16
|
+
picked (loop [xs (vec (range n)) j 0]
|
|
17
|
+
(if (= j k) (set (subvec xs 0 k))
|
|
18
|
+
(let [m (+ j (js/Math.floor (* (r) (- n j)))) xj (nth xs j) xm (nth xs m)]
|
|
19
|
+
(recur (assoc xs j xm m xj) (inc j)))))]
|
|
20
|
+
(mapv (fn [p] (if (picked p) 1 0)) (range n))))
|
|
21
|
+
params (fn [args over]
|
|
22
|
+
(let [o (merge args over)
|
|
23
|
+
n (api/clamp (js/Math.round (or (:n o) 8)) 1 128)]
|
|
24
|
+
{:n n :k (api/clamp (js/Math.round (or (:k o) 3)) 0 n) :seed (or (:seed o) 1)}))]
|
|
25
|
+
{;; ── about ──
|
|
26
|
+
:class "chance"
|
|
27
|
+
:license "MPL-2.0"
|
|
28
|
+
:doc "A generator of pulses, as euclid, with chance instead of evenness: each bang draws another rhythm of k onsets among n pulses, sent as pulses (ones and zeros) for a necklace. The draws are the seed's — the same seed, the same rhythms in the same order, for everyone in a room and again from the history; :reset starts its draws again. [:k 5], [:n 16], [:seed 7] (or a map of them) change it and start again; a number is k."
|
|
29
|
+
:usage "chance [k 3] [n 8] [seed 1]"
|
|
30
|
+
:io [1 1]
|
|
31
|
+
|
|
32
|
+
;; ── arguments ──
|
|
33
|
+
:args [[:k 3] [:n 8] [:seed 1]]
|
|
34
|
+
|
|
35
|
+
;; ── logic ──
|
|
36
|
+
:receive (fn [{:keys [value state args]}]
|
|
37
|
+
(let [st (or state {:over {} :i 0})
|
|
38
|
+
again (fn [over] {:state {:over over :i 0} :show (let [p (params args over)] (str (:k p) "/" (:n p) " · seed " (:seed p)))})]
|
|
39
|
+
(cond
|
|
40
|
+
(#{:bang} value) (let [p (params args (:over st)) i (:i st)]
|
|
41
|
+
{:state (assoc st :i (inc i)) :show (str (:k p) "/" (:n p) " · seed " (:seed p) " · draw " (inc i))
|
|
42
|
+
:out [[0 (draw (:k p) (:n p) (:seed p) i)]]})
|
|
43
|
+
(#{:reset} value) (again (:over st))
|
|
44
|
+
(number? value) (again (assoc (:over st) :k value))
|
|
45
|
+
(and (vector? value) (= 2 (count value)) (#{:k :n :seed} (first value)) (number? (second value)))
|
|
46
|
+
(again (assoc (:over st) (first value) (second value)))
|
|
47
|
+
(map? value) (again (merge (:over st) (select-keys value [:k :n :seed])))
|
|
48
|
+
:else {})))})
|
package/src/euclid.cljs
CHANGED
|
@@ -1,15 +1,11 @@
|
|
|
1
|
-
;; euclid · a Euclidean rhythm: k onsets spread as evenly as they can be over n pulses
|
|
1
|
+
;; euclid · a Euclidean rhythm, as pulses: k onsets spread as evenly as they can be over n pulses
|
|
2
2
|
;; Part of @kairotic/rhythm. Written against the Kairotic API (api/…).
|
|
3
3
|
;; Bjorklund's algorithm (Toussaint, "The Euclidean algorithm generates traditional musical rhythms", 2005):
|
|
4
4
|
;; 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é.
|
|
5
|
-
;;
|
|
6
|
-
;;
|
|
7
|
-
;;
|
|
8
|
-
|
|
9
|
-
;; talea and color of an isorhythm) into a musical tree: the box does it with what reaches its right inlet,
|
|
10
|
-
;; and its outlet 1 gives the bare :rtm map to merge elsewhere (merge, then vector :rtm %).
|
|
11
|
-
(let [;; Bjorklund: k ones and n − k zeros, the remainder paired again and again (Euclid's algorithm)
|
|
12
|
-
bjorklund (fn [k n]
|
|
5
|
+
;; A generator, almost a function: (euclid k n rotation) → pulses, ones and zeros — the common tongue of the
|
|
6
|
+
;; rhythm boxes, as Hz are of pitch. It has no view: a necklace shows, edits, measures and writes as a tree
|
|
7
|
+
;; what it makes (euclid → necklace → tree).
|
|
8
|
+
(let [bjorklund (fn [k n]
|
|
13
9
|
(cond (<= n 0) []
|
|
14
10
|
(<= k 0) (vec (repeat n 0))
|
|
15
11
|
(>= k n) (vec (repeat n 1))
|
|
@@ -19,136 +15,40 @@
|
|
|
19
15
|
(let [m (min (count a) (count b))]
|
|
20
16
|
(recur (mapv into (subvec a 0 m) (subvec b 0 m))
|
|
21
17
|
(if (> (count a) m) (subvec a m) (subvec b m))))))))
|
|
22
|
-
;;
|
|
18
|
+
;; read from pulse r on: the rhythm in a fixed position against the beat
|
|
23
19
|
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)))))))
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
(cond (zero? n) []
|
|
32
|
-
(empty? os) [(- n)]
|
|
33
|
-
:else (vec (concat (when (pos? (first os)) [(- (first os))])
|
|
34
|
-
(map (fn [a b] (- b a)) os (conj (subvec os 1) n)))))))
|
|
35
|
-
;; the meter of a bar of n pulses, when none is asked: the pulse a written value
|
|
36
|
-
pow2? (fn [x] (and (pos? x) (== x (js/Math.pow 2 (js/Math.round (js/Math.log2 x))))))
|
|
37
|
-
meter-of (fn [n] (cond (and (>= n 4) (pow2? n)) [4 4]
|
|
38
|
-
(and (>= n 12) (zero? (mod n 3)) (pow2? (/ n 3))) [12 8]
|
|
39
|
-
(< n 4) [n 4]
|
|
40
|
-
(<= n 12) [n 8]
|
|
41
|
-
:else [n 16]))
|
|
42
|
-
;; a meter asked for: [3 4], "3/4", "7/8[2+2+3]", or nil (as the pulses say)
|
|
43
|
-
meter-arg (fn [v] (cond (and (sequential? v) (= 2 (count v)) (every? number? v)) (vec v)
|
|
44
|
-
(string? v) v
|
|
45
|
-
(keyword? v) (name v)
|
|
46
|
-
:else nil))
|
|
47
|
-
;; pitches, as theory boxes take them: Hz by default, MIDI with midi; the MIDI notes kept to 3 decimals
|
|
48
|
-
hz->m (fn [x] (when (and (number? x) (pos? x)) (/ (js/Math.round (* 1000 (+ 69 (* 12 (js/Math.log2 (/ x 440)))))) 1000)))
|
|
49
|
-
;; what reaches the right inlet, as the pitches of the :rtm (or nil, to forget them): a map of pitches
|
|
50
|
-
;; ({:pitches …} or {:pitch …}, kept as they are), a pattern ({:note [...]}, MIDI;
|
|
51
|
-
;; nil a rest), a melody string ("c4 e4 g4"), a list of pitches (Hz, as a keyboard sends the keys held;
|
|
52
|
-
;; MIDI with midi), a list of notes or chords of a tree, or one pitch
|
|
53
|
-
pitches-of (fn [midi? v]
|
|
54
|
-
(let [p (fn [x] (if midi? x (hz->m x)))]
|
|
55
|
-
(cond (#{:clear} v) nil
|
|
56
|
-
(map? v) (cond (or (contains? v :pitches) (contains? v :pitch)) (select-keys v [:pitches :pitch])
|
|
57
|
-
(sequential? (:note v)) {:pitches (mapv (fn [x] (if (number? x) x "r")) (:note v))}
|
|
58
|
-
:else :ignore)
|
|
59
|
-
(string? v) {:pitches v}
|
|
60
|
-
(number? v) (if-let [m (p v)] {:pitch m} :ignore)
|
|
61
|
-
(and (sequential? v) (keyword? (first v))) {:pitches [v]}
|
|
62
|
-
(and (sequential? v) (seq v) (every? number? v)) (let [ms (vec (keep p v))] (if (seq ms) {:pitches ms} :ignore))
|
|
63
|
-
(and (sequential? v) (seq v)) {:pitches (vec v)}
|
|
64
|
-
:else :ignore)))
|
|
65
|
-
;; the color goes on over the bars: bar i begins where the notes of the bar before left it
|
|
66
|
-
tokens (fn [ps] (cond (string? ps) (vec (remove #{""} (.split (.trim ps) (js/RegExp. "\\s+"))))
|
|
67
|
-
(sequential? ps) (vec ps)
|
|
68
|
-
:else nil))
|
|
69
|
-
color-at (fn [pm skip]
|
|
70
|
-
(let [ts (tokens (:pitches pm))]
|
|
71
|
-
(if (or (empty? ts) (zero? (mod skip (count ts))))
|
|
72
|
-
pm
|
|
73
|
-
(let [r (mod skip (count ts)) ts2 (vec (concat (subvec ts r) (subvec ts 0 r)))]
|
|
74
|
-
(assoc pm :pitches (if (string? (:pitches pm)) (apply str (interpose " " ts2)) ts2))))))
|
|
75
|
-
;; everything the box knows: its words, changed by messages
|
|
76
|
-
params (fn [args st]
|
|
77
|
-
(let [o (merge args (:over st))
|
|
78
|
-
n (max 1 (js/Math.round (or (:n o) 8)))]
|
|
79
|
-
{:n n :k (api/clamp (js/Math.round (or (:k o) 3)) 0 n) :rotation (mod (js/Math.round (or (:rotation o) 0)) n)
|
|
80
|
-
:bars (api/clamp (js/Math.round (or (:bars o) 1)) 1 64) :meter (or (:meter o) (meter-of n))}))
|
|
81
|
-
;; the rhythm as data: the pulses, its necklace, and the :rtm with the pitches merged
|
|
82
|
-
rhythm (fn [{:keys [k n rotation bars meter]} pm]
|
|
83
|
-
(let [ps (rotate (bjorklund k n) rotation)
|
|
84
|
-
rtm (merge {:shares (shares-of ps)} (or pm {}))
|
|
85
|
-
bar (fn [i] (let [a (color-at rtm (* i k))]
|
|
86
|
-
(if (zero? i) [:measure {:meter meter} [:rtm a]] [:measure [:rtm a]])))]
|
|
87
|
-
{:pulses ps :onsets (onsets-of ps) :intervals (intervals-of ps) :rtm rtm
|
|
88
|
-
:tree (into [:voice] (map bar (range bars)))}))
|
|
89
|
-
shown-of (fn [p r] (merge (select-keys p [:k :n :rotation :bars]) (select-keys r [:pulses :onsets :intervals])))
|
|
90
|
-
;; what goes out: the tree (0), the :rtm map (1), the pulses (2), the last first (as Max does)
|
|
91
|
-
outs (fn [r] [[2 (:pulses r)] [1 (:rtm r)] [0 (:tree r)]])
|
|
92
|
-
;; a change: sent when what it makes is new (the same again changes nothing); a bang sends it anyway
|
|
20
|
+
pulses-of (fn [args over]
|
|
21
|
+
(let [o (merge args over)
|
|
22
|
+
n (api/clamp (js/Math.round (or (:n o) 8)) 1 128)
|
|
23
|
+
k (api/clamp (js/Math.round (or (:k o) 3)) 0 n)]
|
|
24
|
+
{:k k :n n :rotation (mod (js/Math.round (or (:rotation o) 0)) n)
|
|
25
|
+
:pulses (rotate (bjorklund k n) (or (:rotation o) 0))}))
|
|
26
|
+
;; a change: sent when the pulses are new (the same again changes nothing); a bang sends them anyway
|
|
93
27
|
changed (fn [args st over always?]
|
|
94
|
-
(let [
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
{:state (assoc
|
|
98
|
-
|
|
28
|
+
(let [r (pulses-of args over)
|
|
29
|
+
shown (str "E(" (:k r) "," (:n r) ")" (when (pos? (:rotation r)) (str " ↻" (:rotation r))))]
|
|
30
|
+
(if (and (not always?) (= (:pulses r) (:sent st)))
|
|
31
|
+
{:state (assoc st :over over) :show shown}
|
|
32
|
+
{:state (assoc st :over over :sent (:pulses r)) :show shown :out [[0 (:pulses r)]]})))]
|
|
99
33
|
{;; ── about ──
|
|
100
34
|
:class "euclid"
|
|
101
35
|
:license "MPL-2.0"
|
|
102
|
-
: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
|
|
103
|
-
:usage "euclid [k 3] [n 8] [rotation 0]
|
|
104
|
-
:io [
|
|
105
|
-
:size [180 200]
|
|
36
|
+
:doc "A Euclidean rhythm (Bjorklund's algorithm, after Toussaint), as pulses: k onsets spread as evenly as they can be over n pulses, from pulse rotation on — euclid 3 8 is the tresillo [1 0 0 1 0 0 1 0], euclid 5 8 the cinquillo, euclid 5 16 a rotation of the bossa nova (euclid 5 16 6 the bossa nova), euclid 7 12 the bembé. A generator with no view: a bang sends the pulses; [:k 5], [:n 16], [:rotation 2] (or a map of them) change them and send them when they are new, a number is k. Pulses are what every rhythm box takes: a necklace after it shows, edits and measures the rhythm, and writes it as a musical tree with pitches (euclid → necklace → tree)."
|
|
37
|
+
:usage "euclid [k 3] [n 8] [rotation 0]"
|
|
38
|
+
:io [1 1]
|
|
106
39
|
|
|
107
40
|
;; ── arguments ──
|
|
108
|
-
:args [[:k 3] [:n 8] [:rotation 0]
|
|
41
|
+
:args [[:k 3] [:n 8] [:rotation 0]]
|
|
109
42
|
|
|
110
43
|
;; ── logic ──
|
|
111
|
-
:receive (fn [{:keys [
|
|
112
|
-
(let [st (or state {:over {}
|
|
44
|
+
:receive (fn [{:keys [value state args]}]
|
|
45
|
+
(let [st (or state {:over {}})
|
|
113
46
|
over (:over st)
|
|
114
47
|
set-over (fn [m] (changed args st (merge over m) false))]
|
|
115
|
-
(
|
|
116
|
-
(
|
|
117
|
-
|
|
118
|
-
(
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
(let [p (params args st)] (set-over {:rotation (+ (:rotation p) (second value))}))
|
|
123
|
-
(and (vector? value) (= 2 (count value)) (#{:k :n :rotation :bars} (first value)) (number? (second value)))
|
|
124
|
-
(set-over {(first value) (second value)})
|
|
125
|
-
(and (vector? value) (= :meter (first value))) (set-over {:meter (meter-arg (second value))})
|
|
126
|
-
(map? value) (set-over (cond-> (select-keys value [:k :n :rotation :bars])
|
|
127
|
-
(contains? value :meter) (assoc :meter (meter-arg (:meter value)))))
|
|
128
|
-
:else {}))))
|
|
129
|
-
;; pressing a pulse: the rhythm starts there (sent once, on release)
|
|
130
|
-
:gesture (fn [{:keys [up hit]}] (when (and up (number? hit)) [:pressed hit]))
|
|
131
|
-
|
|
132
|
-
;; ── view ──
|
|
133
|
-
:draw (fn [{:keys [shown w h args]}]
|
|
134
|
-
(let [p (or shown (let [n (max 1 (js/Math.round (or (:n args) 8)))
|
|
135
|
-
k (api/clamp (js/Math.round (or (:k args) 3)) 0 n)
|
|
136
|
-
ps (rotate (bjorklund k n) (or (:rotation args) 0))]
|
|
137
|
-
{:k k :n n :pulses ps :onsets (onsets-of ps) :intervals (intervals-of ps)}))
|
|
138
|
-
n (:n p) ps (:pulses p) os (:onsets p)
|
|
139
|
-
cx (/ w 2) cy (/ (- h 30) 2) R (- (min cx cy) 16)
|
|
140
|
-
r (cond (> n 32) 2.2 (> n 16) 3 :else 4.5)]
|
|
141
|
-
(concat
|
|
142
|
-
[[:circle {:cx cx :cy cy :r R :stroke :grid}]]
|
|
143
|
-
;; the start of the bar, at the top
|
|
144
|
-
(let [[x1 y1] (polar cx cy (- R 9) 0 n) [x2 y2] (polar cx cy (+ R 9) 0 n)]
|
|
145
|
-
[[:line {:x1 x1 :y1 y1 :x2 x2 :y2 y2 :stroke :kairos :weight 1.5 :opacity 0.8}]])
|
|
146
|
-
(when (> (count os) 1) [[:path {:points (mapv (fn [i] (polar cx cy R i n)) os) :closed true :stroke :accent :weight 2}]])
|
|
147
|
-
(for [i (range n)]
|
|
148
|
-
(let [[x y] (polar cx cy R i n) on (= 1 (nth ps i 0))]
|
|
149
|
-
[:group {:hit i}
|
|
150
|
-
[[:circle {:cx x :cy y :r (if on (+ r 1.5) r) :fill (if on :accent :bg) :stroke (if on :accent :soft)}]]]))
|
|
151
|
-
[[:text {:x cx :y (- h 15) :anchor :middle :size 10 :fill :ink}
|
|
152
|
-
(str "E(" (:k p) "," n ")" (when (pos? (or (:rotation p) 0)) (str " ↻" (:rotation p))))]
|
|
153
|
-
[:text {:x cx :y (- h 3) :anchor :middle :size 9 :fill :soft}
|
|
154
|
-
(if (seq (:intervals p)) (apply str (interpose "-" (:intervals p))) "silence")]])))})
|
|
48
|
+
(cond
|
|
49
|
+
(#{:bang} value) (changed args st over true)
|
|
50
|
+
(number? value) (set-over {:k value})
|
|
51
|
+
(and (vector? value) (= 2 (count value)) (#{:k :n :rotation} (first value)) (number? (second value)))
|
|
52
|
+
(set-over {(first value) (second value)})
|
|
53
|
+
(map? value) (set-over (select-keys value [:k :n :rotation]))
|
|
54
|
+
:else {})))})
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
;; homometric · the other rhythms with the same interval vector
|
|
2
|
+
;; Part of @kairotic/rhythm. Written against the Kairotic API (api/…).
|
|
3
|
+
;; Two rhythms are homometric when they hold the same distances between onsets, as many times each — the
|
|
4
|
+
;; same interval vector, the same "histogram" — without being the same necklace turned or seen in a mirror
|
|
5
|
+
;; (Toussaint, after crystallography: Patterson, Rosenblatt and Seymour). The two flat rhythms of four onsets
|
|
6
|
+
;; in twelve are homometric; so is any half of the pulses of an even cycle with its complement, which gives two
|
|
7
|
+
;; drums (high and low congas) the same intervals. Given a rhythm as pulses, it searches every rhythm of as many
|
|
8
|
+
;; onsets among as many pulses (up to 7 000 of them: any rhythm of 16 pulses; a moment for the largest) and sends the others it finds, each from its first onset, as a list of
|
|
9
|
+
;; pulses (for nth, or a necklace one by one), and how many there are.
|
|
10
|
+
(let [onsets-of (fn [ps] (vec (keep-indexed (fn [i x] (when (= 1 x) i)) ps)))
|
|
11
|
+
pulses? (fn [v] (and (sequential? v) (seq v) (every? #{0 1} v)))
|
|
12
|
+
dist (fn [n a b] (let [d (js/Math.abs (- a b))] (min d (- n d))))
|
|
13
|
+
ivec-of (fn [n os] (let [c (frequencies (for [i (range (count os)) j (range (inc i) (count os))] (dist n (nth os i) (nth os j))))]
|
|
14
|
+
(mapv (fn [d] (get c d 0)) (range 1 (inc (quot n 2))))))
|
|
15
|
+
;; a necklace up to rotation and mirror, as its smallest form starting at 0 (a bracelet)
|
|
16
|
+
bracelet (fn [n os]
|
|
17
|
+
(first (sort (for [f [identity (fn [x] (mod (- n x) n))] r (range n)]
|
|
18
|
+
(vec (sort (map (fn [x] (mod (- (f x) r) n)) os)))))))
|
|
19
|
+
;; the subsets of 1…n−1 of size m (0 is always an onset: rotations are the same necklace)
|
|
20
|
+
subsets (fn subsets [from n m]
|
|
21
|
+
(cond (zero? m) [[]]
|
|
22
|
+
(> m (- n from)) []
|
|
23
|
+
:else (concat (map (fn [s] (cons from s)) (subsets (inc from) n (dec m))) (subsets (inc from) n m))))
|
|
24
|
+
;; how many rhythms the search goes through: C(n−1, k−1)
|
|
25
|
+
choose (fn [a b] (reduce (fn [acc i] (/ (* acc (- a i)) (inc i))) 1 (range (min b (- a b)))))
|
|
26
|
+
limit 7000
|
|
27
|
+
search (fn [ps]
|
|
28
|
+
(let [n (count ps) os (onsets-of ps) k (count os) target (ivec-of n os) own (bracelet n os)]
|
|
29
|
+
(if (zero? k) []
|
|
30
|
+
(->> (subsets 1 n (dec k))
|
|
31
|
+
(map (fn [s] (vec (cons 0 s))))
|
|
32
|
+
(filter (fn [o] (= target (ivec-of n o))))
|
|
33
|
+
(map (fn [o] (bracelet n o)))
|
|
34
|
+
distinct
|
|
35
|
+
(remove (fn [b] (= b own)))
|
|
36
|
+
sort
|
|
37
|
+
(mapv (fn [b] (let [on (set b)] (mapv (fn [i] (if (on i) 1 0)) (range n)))))))))]
|
|
38
|
+
{;; ── about ──
|
|
39
|
+
:class "homometric"
|
|
40
|
+
:license "MPL-2.0"
|
|
41
|
+
:doc "The other rhythms with the same interval vector (Toussaint, after crystallography): homometric rhythms hold the same distances between onsets, as many times each, without being the same necklace turned or in a mirror — the two flat rhythms of four onsets in twelve; any half of the pulses of an even cycle and its complement, two drums with the same intervals. Given pulses, it searches every rhythm of as many onsets among as many pulses (when they are at most 7 000: any rhythm of 16 pulses) and sends the others it finds, each from its first onset, as a list of pulses (left: for nth, or one by one to a necklace) and how many there are (right); none, an empty list. A bang searches again."
|
|
42
|
+
:usage "homometric"
|
|
43
|
+
:io [1 2]
|
|
44
|
+
|
|
45
|
+
;; ── logic ──
|
|
46
|
+
:receive (fn [{:keys [value state]}]
|
|
47
|
+
(let [st (or state {})
|
|
48
|
+
go (fn [ps] (if (> (choose (dec (count ps)) (max 0 (dec (count (onsets-of ps))))) limit)
|
|
49
|
+
{:state (assoc st :ps ps) :show (str "too many to search (more than " limit " rhythms)")}
|
|
50
|
+
(let [hs (search ps)]
|
|
51
|
+
{:state (assoc st :ps ps) :show (str (count hs) " homometric")
|
|
52
|
+
:out [[1 (count hs)] [0 hs]]})))]
|
|
53
|
+
(cond
|
|
54
|
+
(and (#{:bang} value) (:ps st)) (go (:ps st))
|
|
55
|
+
(pulses? value) (if (= (vec value) (:ps st)) {:state st} (go (vec value)))
|
|
56
|
+
:else {})))})
|
package/src/necklace.cljs
CHANGED
|
@@ -7,9 +7,12 @@
|
|
|
7
7
|
;; arcs are too coarse: the six 4/4 claves would all score the same), whether it is deep (each distance a
|
|
8
8
|
;; different number of times, as the diatonic scale and the bembé), flat (each distance once), its axes of
|
|
9
9
|
;; mirror symmetry, its longest gap, rhythmic oddity (no two onsets halving the cycle), and whether it is a
|
|
10
|
-
;; rotation of the Euclidean rhythm E(k,n)
|
|
11
|
-
;;
|
|
12
|
-
;;
|
|
10
|
+
;; rotation of the Euclidean rhythm E(k,n) — and its Fourier coefficients (after Amiot and Milne): |f1| near 0
|
|
11
|
+
;; is a balanced rhythm, a maximal |f_k| among the rhythms of k onsets a maximally even one, and the others its
|
|
12
|
+
;; periodicities (in 16 pulses f4 the quarter notes, f3 a three against the four).
|
|
13
|
+
;; It is the rhythm box: generators (euclid) make pulses, the necklace holds them, shows them, is their editor
|
|
14
|
+
;; (pressing a pulse adds or takes away an onset), measures them and writes them as a musical tree, its :rtm
|
|
15
|
+
;; map and its pulses, with the pitches of its right inlet (talea and color).
|
|
13
16
|
(let [TAU (* 2 js/Math.PI)
|
|
14
17
|
bjorklund (fn [k n]
|
|
15
18
|
(cond (<= n 0) []
|
|
@@ -64,6 +67,13 @@
|
|
|
64
67
|
axes-of (fn [n os] (let [s (set os)]
|
|
65
68
|
(if (empty? s) []
|
|
66
69
|
(vec (for [a (range n) :when (= s (set (map (fn [x] (mod (- a x) n)) os)))] (/ a 2))))))
|
|
70
|
+
;; the Fourier coefficients of the onsets, f1 … f⌊n/2⌋: magnitudes 0…1 (over k) and phases in degrees
|
|
71
|
+
fourier-of (fn [n os]
|
|
72
|
+
(let [k (count os)]
|
|
73
|
+
(vec (for [j (range 1 (inc (quot n 2)))]
|
|
74
|
+
(if (zero? k) [0 0]
|
|
75
|
+
[(/ (reduce + (map (fn [x] (js/Math.cos (/ (* TAU j x) n))) os)) k)
|
|
76
|
+
(- (/ (reduce + (map (fn [x] (js/Math.sin (/ (* TAU j x) n))) os)) k))])))))
|
|
67
77
|
measures (fn [ps]
|
|
68
78
|
(let [n (count ps) os (onsets-of ps) k (count os) iv (ivec-of n os) ev (evenness-of n os)
|
|
69
79
|
e (bjorklund k n) eev (evenness-of n (onsets-of e))
|
|
@@ -75,7 +85,10 @@
|
|
|
75
85
|
:axes (axes-of n os)
|
|
76
86
|
:gap (if (seq os) (apply max (intervals-of ps)) n)
|
|
77
87
|
:oddity (or (odd? n) (not-any? (fn [[a b]] (= (* 2 (dist n a b)) n)) (pairs os)))
|
|
78
|
-
:euclid er
|
|
88
|
+
:euclid er
|
|
89
|
+
:fourier (mapv (fn [[a b]] (r3 (js/Math.hypot a b))) (fourier-of n os))
|
|
90
|
+
:phases (mapv (fn [[a b]] (if (< (js/Math.hypot a b) 1e-9) 0 (r3 (* (/ 180 js/Math.PI) (js/Math.atan2 b a))))) (fourier-of n os))}))
|
|
91
|
+
fourier? (fn [args] (some (fn [a] (= "fourier" (if (keyword? a) (name a) (str a)))) (if (map? args) (when (:fourier args) [:fourier]) args)))
|
|
79
92
|
;; ── as euclid sends a rhythm: the meter of a bar of n pulses, the pitches, the color over bars ──
|
|
80
93
|
pow2? (fn [x] (and (pos? x) (== x (js/Math.pow 2 (js/Math.round (js/Math.log2 x))))))
|
|
81
94
|
meter-of (fn [n] (cond (and (>= n 4) (pow2? n)) [4 4]
|
|
@@ -128,13 +141,13 @@
|
|
|
128
141
|
{;; ── about ──
|
|
129
142
|
:class "necklace"
|
|
130
143
|
:license "MPL-2.0"
|
|
131
|
-
:doc "A cyclic rhythm on the circle and its geometry (Toussaint): k onsets among n pulses around a circle, time clockwise from the top — the same object as a pitch-class set on pcclock. A rhythm arrives as pulses (ones and zeros, as euclid's right outlet sends them), as intervals between onsets ([3 3 2]), as box notation (\"x..x..x.\"), as an :rtm map ({:shares [3 3 2]}, euclid's middle outlet), a tree with an :rtm, or {:onsets [0 3 6] :n 8}; it is drawn as a polygon, with its axes of mirror symmetry. Pressing a pulse (or a number, its index) adds or takes away an onset. :complement swaps onsets and silences, [:rotate 1] starts it a pulse later, [:n 12] makes the circle longer or shorter, :clear empties it, [:bars 4] and [:meter \"3/4\"] as euclid, a bang sends it again. Out, as euclid: a musical tree (left: a bar of n pulses with an :rtm whose shares are the intervals between onsets), the :rtm map alone (1), the pulses (2); and its measures (3): {:n :k :onsets :intervals :ivec — how often each distance occurs —, :evenness — the sum of the chords between all pairs (Block and Douthett) —, :even — that sum against the Euclidean rhythm's, 1 as even as it —, :deep — each distance a different number of times —, :flat — each once —, :axes — of mirror symmetry, in pulses —, :gap — the longest interval —, :oddity — no two onsets halving the cycle —, :euclid — the rotation of E(k,n) it is, or nil}. Its right inlet (cold) takes the pitches the notes take in turn, as euclid's."
|
|
132
|
-
:usage "necklace [n 16] [bars 1] [midi]"
|
|
144
|
+
:doc "A cyclic rhythm on the circle and its geometry (Toussaint): k onsets among n pulses around a circle, time clockwise from the top — the same object as a pitch-class set on pcclock. A rhythm arrives as pulses (ones and zeros, as euclid's right outlet sends them), as intervals between onsets ([3 3 2]), as box notation (\"x..x..x.\"), as an :rtm map ({:shares [3 3 2]}, euclid's middle outlet), a tree with an :rtm, or {:onsets [0 3 6] :n 8}; it is drawn as a polygon, with its axes of mirror symmetry. Pressing a pulse (or a number, its index) adds or takes away an onset. :complement swaps onsets and silences, [:rotate 1] starts it a pulse later, [:n 12] makes the circle longer or shorter, :clear empties it, [:bars 4] and [:meter \"3/4\"] as euclid, a bang sends it again. Out, as euclid: a musical tree (left: a bar of n pulses with an :rtm whose shares are the intervals between onsets), the :rtm map alone (1), the pulses (2); and its measures (3): {:n :k :onsets :intervals :ivec — how often each distance occurs —, :evenness — the sum of the chords between all pairs (Block and Douthett) —, :even — that sum against the Euclidean rhythm's, 1 as even as it —, :deep — each distance a different number of times —, :flat — each once —, :axes — of mirror symmetry, in pulses —, :gap — the longest interval —, :oddity — no two onsets halving the cycle —, :euclid — the rotation of E(k,n) it is, or nil —, :fourier and :phases — its Fourier coefficients f1 … f⌊n/2⌋, magnitudes 0…1 and phases in degrees: |f1| near 0 balanced, |f_k| largest when maximally even —}; with the word fourier the magnitudes are drawn too, a bar each. Its right inlet (cold) takes the pitches the notes take in turn, as euclid's."
|
|
145
|
+
:usage "necklace [n 16] [bars 1] [midi] [fourier]"
|
|
133
146
|
:io [2 4]
|
|
134
|
-
:size [200 240]
|
|
147
|
+
:size (fn [box] (if (fourier? (:args box)) [200 296] [200 240]))
|
|
135
148
|
|
|
136
149
|
;; ── arguments ──
|
|
137
|
-
:args [[:n 16] [:bars 1] [:midi false]]
|
|
150
|
+
:args [[:n 16] [:bars 1] [:midi false] [:fourier false]]
|
|
138
151
|
|
|
139
152
|
;; ── logic ──
|
|
140
153
|
:receive (fn [{:keys [inlet value state args]}]
|
|
@@ -168,7 +181,8 @@
|
|
|
168
181
|
:draw (fn [{:keys [shown w h args]}]
|
|
169
182
|
(let [p (or shown (let [ps (vec (repeat (max 1 (js/Math.round (or (:n args) 16))) 0))] (assoc (measures ps) :pulses ps)))
|
|
170
183
|
n (:n p) ps (:pulses p) os (:onsets p)
|
|
171
|
-
|
|
184
|
+
fh (if (:fourier args) 60 0)
|
|
185
|
+
cx (/ w 2) cy (/ (- h 44 fh) 2) R (- (min cx cy) 16)
|
|
172
186
|
r (cond (> n 32) 2.2 (> n 16) 3 :else 4.5)
|
|
173
187
|
flags (remove nil? [(str "even " (:even p))
|
|
174
188
|
(let [a (count (:axes p))] (case a 0 "asymmetric" 1 "1 axis" (str a " axes")))
|
|
@@ -188,6 +202,17 @@
|
|
|
188
202
|
(let [[x y] (polar cx cy R i n) on (= 1 (nth ps i 0))]
|
|
189
203
|
[:group {:hit i}
|
|
190
204
|
[[:circle {:cx x :cy y :r (if on (+ r 1.5) r) :fill (if on :accent :bg) :stroke (if on :accent :soft)}]]]))
|
|
205
|
+
;; the Fourier magnitudes, a bar each (f1 … f⌊n/2⌋), above the texts
|
|
206
|
+
(when (:fourier args)
|
|
207
|
+
(let [fs (or (:fourier p) []) m (count fs) bw (if (pos? m) (/ (- w 20) m) 0) base (- h 52)]
|
|
208
|
+
(concat
|
|
209
|
+
[[:line {:x1 10 :y1 base :x2 (- w 10) :y2 base :stroke :grid}]]
|
|
210
|
+
(for [[j f] (map-indexed vector fs)]
|
|
211
|
+
[:rect {:x (+ 10 (* j bw) 1) :y (- base (* 36 f)) :w (max 1 (- bw 2)) :h (* 36 f)
|
|
212
|
+
:fill (if (= (inc j) (:k p)) :kairos :accent) :opacity 0.8}])
|
|
213
|
+
(when (<= m 16)
|
|
214
|
+
(for [j (range m)]
|
|
215
|
+
[:text {:x (+ 10 (* j bw) (/ bw 2)) :y (+ base 9) :anchor :middle :size 7 :fill :soft} (str (inc j))])))))
|
|
191
216
|
[[:text {:x cx :y (- h 29) :anchor :middle :size 10 :fill :ink}
|
|
192
217
|
(str (:k p) "/" n " · " (if (seq (:intervals p)) (apply str (interpose "-" (:intervals p))) "silence"))]
|
|
193
218
|
[:text {:x cx :y (- h 16) :anchor :middle :size 9 :fill :soft} (str "<" (apply str (interpose " " (:ivec p))) ">")]
|
package/src/swap.cljs
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
;; swap · how far apart two rhythms are (Toussaint's swap distance)
|
|
2
|
+
;; Part of @kairotic/rhythm. Written against the Kairotic API (api/…).
|
|
3
|
+
;; Two rhythms of n pulses, as pulses. A swap exchanges an onset and the silence beside it, and the swap
|
|
4
|
+
;; distance is how many of them turn one rhythm into the other: an onset moved far counts more than one moved
|
|
5
|
+
;; near, which the Hamming distance (how many pulses differ) cannot tell. With the same number of onsets it
|
|
6
|
+
;; is the sum of |uᵢ − vᵢ| over the onsets in order; with different numbers, the directed swap distance (each
|
|
7
|
+
;; onset of the shorter rhythm goes to its own onset of the other, the least moving in all). Around the circle
|
|
8
|
+
;; a swap may cross the end of the bar; as necklaces, the rhythms are also compared at every rotation (the
|
|
9
|
+
;; one that brings them closest is said). For the futuribles and the agents: is a variation still the same
|
|
10
|
+
;; timeline? Both inlets take pulses (euclid's, a necklace's outlet 2); the left one compares, the right one
|
|
11
|
+
;; is the reference (cold).
|
|
12
|
+
(let [onsets-of (fn [ps] (vec (keep-indexed (fn [i x] (when (= 1 x) i)) ps)))
|
|
13
|
+
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)))))))
|
|
14
|
+
pulses? (fn [v] (and (sequential? v) (seq v) (every? #{0 1} v)))
|
|
15
|
+
cdist (fn [n a b] (let [d (js/Math.abs (- a b))] (min d (- n d))))
|
|
16
|
+
;; onsets in order, each of the shorter list to its own of the longer one, the least moving in all
|
|
17
|
+
;; (dynamic programming over both lists: the directed swap distance; with equal lengths, Σ|uᵢ − vᵢ|)
|
|
18
|
+
assign (fn [d us vs]
|
|
19
|
+
(let [[a b] (if (<= (count us) (count vs)) [us vs] [vs us]) p (count a) q (count b)]
|
|
20
|
+
(cond (zero? p) 0
|
|
21
|
+
:else (loop [i 0 row (vec (repeat (inc q) 0))]
|
|
22
|
+
(if (= i p)
|
|
23
|
+
(peek row)
|
|
24
|
+
(recur (inc i)
|
|
25
|
+
(reduce (fn [nr j]
|
|
26
|
+
(conj nr (min (if (> j (inc i)) (peek nr) js/Infinity)
|
|
27
|
+
(+ (nth row (dec j)) (d (nth a i) (nth b (dec j)))))))
|
|
28
|
+
[js/Infinity] (range 1 (inc q)))))))))
|
|
29
|
+
linear (fn [A B] (assign (fn [x y] (js/Math.abs (- x y))) (onsets-of A) (onsets-of B)))
|
|
30
|
+
;; around the circle: with as many onsets, the best cyclic shift of the pairing; otherwise the best place
|
|
31
|
+
;; to cut the circle open
|
|
32
|
+
circular (fn [A B]
|
|
33
|
+
(let [n (count A) us (onsets-of A) vs (onsets-of B) k (count us)]
|
|
34
|
+
(cond (or (empty? us) (empty? vs)) (if (= (count us) (count vs)) 0 nil)
|
|
35
|
+
(= k (count vs)) (apply min (for [s (range k)] (reduce + (map (fn [i] (cdist n (nth us i) (nth vs (mod (+ i s) k)))) (range k)))))
|
|
36
|
+
:else (apply min (for [c (range n)]
|
|
37
|
+
(assign (fn [x y] (cdist n x y)) (onsets-of (rotate A c)) (onsets-of (rotate B c))))))))
|
|
38
|
+
hamming (fn [A B] (count (filter false? (map = A B))))
|
|
39
|
+
compare-them (fn [A B]
|
|
40
|
+
(let [n (count A) ka (count (onsets-of A)) kb (count (onsets-of B))
|
|
41
|
+
;; a rhythm without onsets is not far from another one by swaps: only from silence
|
|
42
|
+
none? (and (or (zero? ka) (zero? kb)) (not= ka kb))
|
|
43
|
+
rs (vec (for [r (range n)] (circular A (rotate B r))))
|
|
44
|
+
best (when-not none? (apply min rs))
|
|
45
|
+
hs (vec (for [r (range n)] (hamming A (rotate B r))))]
|
|
46
|
+
{:n n :k [ka kb]
|
|
47
|
+
:swap (when-not none? (linear A B)) :circular (when-not none? (circular A B))
|
|
48
|
+
:necklace best :rotation (when best (first (keep-indexed (fn [r x] (when (= x best) r)) rs)))
|
|
49
|
+
:hamming (hamming A B) :necklace-hamming (apply min hs)}))]
|
|
50
|
+
{;; ── about ──
|
|
51
|
+
:class "swap"
|
|
52
|
+
:license "MPL-2.0"
|
|
53
|
+
:doc "How far apart two rhythms are (Toussaint's swap distance). Both inlets take pulses of n pulses (euclid's, a necklace's outlet 2): the left one is compared with the right one, the reference (cold). A swap exchanges an onset and the silence beside it; the swap distance is how many turn one rhythm into the other — an onset moved far counts more than one moved near, as the Hamming distance (how many pulses differ) cannot tell. With different numbers of onsets, the directed swap distance (each onset of the shorter rhythm to its own of the other). Out, a map: {:swap — in the bar —, :circular — a swap may cross the end of the bar —, :necklace — the best over every rotation of the reference — and :rotation, the one that gives it, :hamming and :necklace-hamming, :n, :k [onsets of each]}. Rhythms of different lengths are not compared. A bang compares again."
|
|
54
|
+
:usage "swap"
|
|
55
|
+
:io [2 1]
|
|
56
|
+
|
|
57
|
+
;; ── logic ──
|
|
58
|
+
:receive (fn [{:keys [inlet value state]}]
|
|
59
|
+
(let [st (or state {})]
|
|
60
|
+
(cond
|
|
61
|
+
(= inlet 1) (if (pulses? value) {:state (assoc st :ref (vec value))} {})
|
|
62
|
+
(and (#{:bang} value) (:a st)) (let [A (:a st) B (:ref st)]
|
|
63
|
+
(if (and B (= (count A) (count B))) {:out [[0 (compare-them A B)]]} {}))
|
|
64
|
+
(pulses? value) (let [A (vec value) B (:ref st)]
|
|
65
|
+
(cond (nil? B) {:state (assoc st :a A) :show "no reference yet (right inlet)"}
|
|
66
|
+
(not= (count A) (count B)) {:state (assoc st :a A) :show (str (count A) " pulses against " (count B) ": not compared")}
|
|
67
|
+
:else (let [m (compare-them A B)]
|
|
68
|
+
{:state (assoc st :a A) :show (str "swap " (:swap m) " · necklace " (:necklace m)) :out [[0 m]]})))
|
|
69
|
+
:else {})))})
|