1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
//! Rule-based algorithmic composition using L-systems and cellular automata.
//!
//! # L-systems
//! An [`LSystemComposer`] expands a string axiom through production rules and
//! then interprets characters as pitch offsets (in semitones) to produce a
//! sequence of [`Note`]s.
//!
//! # Cellular automata
//! A [`MusicalCellularAutomaton`] evolves a 1-D binary state with Wolfram
//! Rule 30 or Rule 110, then maps each row of the evolution to simultaneous
//! notes (active cells → pitches from a supplied [`crate::microtonal::TuningTable`]).
#![allow(dead_code)]
use std::collections::HashMap;
// ── Note (local) ──────────────────────────────────────────────────────────────
/// A single musical note produced by the algorithmic engine.
#[derive(Debug, Clone, PartialEq)]
pub struct Note {
/// Fundamental frequency in Hz.
pub pitch_hz: f64,
/// Duration in seconds.
pub duration_secs: f64,
/// MIDI-style velocity (0–127).
pub velocity: u8,
}
// ── MusicalLSystem ────────────────────────────────────────────────────────────
/// An L-system configured for musical use.
///
/// Each character in the produced string that appears in `variables` is
/// interpreted as a pitch offset (semitones) relative to `root_hz`.
#[derive(Debug, Clone)]
pub struct MusicalLSystem {
/// Starting string for the rewriting system.
pub axiom: String,
/// Production rules: each char maps to a replacement string.
pub rules: HashMap<char, String>,
/// Pitch semantics: char → offset in semitones from root.
pub variables: HashMap<char, f64>,
}
// ── LSystemComposer ──────────────────────────────────────────────────────────
/// Expands and interprets L-systems into [`Note`] sequences.
pub struct LSystemComposer;
impl LSystemComposer {
// ── Expansion ─────────────────────────────────────────────────────────────
/// Expand `axiom` by applying `rules` for `steps` iterations.
pub fn iterate(axiom: &str, rules: &HashMap<char, String>, steps: u32) -> String {
let mut current = axiom.to_string();
for _ in 0..steps {
let mut next = String::with_capacity(current.len() * 2);
for ch in current.chars() {
if let Some(replacement) = rules.get(&ch) {
next.push_str(replacement);
} else {
next.push(ch);
}
}
current = next;
}
current
}
// ── Note generation ───────────────────────────────────────────────────────
/// Convert an expanded L-system string into a sequence of [`Note`]s.
///
/// Only characters present in `variables` generate notes; others are
/// treated as articulation/structural markers and skipped.
///
/// The frequency for an offset of `n` semitones is
/// `root_hz × 2^(n / 12)`.
pub fn to_notes(
s: &str,
variables: &HashMap<char, f64>,
root_hz: f64,
base_duration: f64,
) -> Vec<Note> {
s.chars()
.filter_map(|ch| {
variables.get(&ch).map(|&semitones| {
let pitch_hz = root_hz * 2.0_f64.powf(semitones / 12.0);
Note {
pitch_hz,
duration_secs: base_duration,
velocity: 80,
}
})
})
.collect()
}
// ── Built-in definitions ──────────────────────────────────────────────────
/// Sierpinski-triangle melody L-system definition.
///
/// Produces a fractal, self-similar melodic pattern when interpreted with
/// the included variable map.
pub fn sierpinski_melody() -> MusicalLSystem {
let mut rules = HashMap::new();
rules.insert('A', "B-A-B".to_string());
rules.insert('B', "A+B+A".to_string());
let mut variables = HashMap::new();
variables.insert('A', 0.0); // root
variables.insert('B', 7.0); // perfect fifth
MusicalLSystem {
axiom: "A".to_string(),
rules,
variables,
}
}
/// Dragon-curve melody L-system definition.
///
/// The dragon curve grammar yields a winding melodic line when pitch
/// offsets are assigned to its characters.
pub fn dragon_curve_melody() -> MusicalLSystem {
let mut rules = HashMap::new();
rules.insert('X', "X+YF+".to_string());
rules.insert('Y', "-FX-Y".to_string());
let mut variables = HashMap::new();
variables.insert('F', 0.0); // root (forward step = play note)
variables.insert('X', 4.0); // major third
variables.insert('Y', 7.0); // perfect fifth
MusicalLSystem {
axiom: "FX".to_string(),
rules,
variables,
}
}
}
// ── MusicalCellularAutomaton ──────────────────────────────────────────────────
/// 1-D binary cellular automata with musical output interpretation.
pub struct MusicalCellularAutomaton;
impl MusicalCellularAutomaton {
// ── Rule 30 ───────────────────────────────────────────────────────────────
/// Apply one step of Wolfram Rule 30 to `state`.
///
/// Boundary conditions are periodic (toroidal).
pub fn rule_30(state: &[bool]) -> Vec<bool> {
Self::apply_rule(state, 30)
}
// ── Rule 110 ──────────────────────────────────────────────────────────────
/// Apply one step of Wolfram Rule 110 to `state`.
pub fn rule_110(state: &[bool]) -> Vec<bool> {
Self::apply_rule(state, 110)
}
// ── Evolve ────────────────────────────────────────────────────────────────
/// Evolve `state` for `steps` generations using the supplied rule function.
///
/// Returns all generations including the initial state.
pub fn evolve(
state: &[bool],
rule_fn: fn(&[bool]) -> Vec<bool>,
steps: usize,
) -> Vec<Vec<bool>> {
let mut history = Vec::with_capacity(steps + 1);
history.push(state.to_vec());
for i in 0..steps {
let next = rule_fn(&history[i]);
history.push(next);
}
history
}
// ── CA to notes ───────────────────────────────────────────────────────────
/// Map a CA evolution to a sequence of [`Note`]s.
///
/// Each row of `evolution` is a time step. Active cells (`true`) are
/// sounded simultaneously; inactive cells are silent. Pitches are drawn
/// from `pitches_hz` by wrapping the cell index into the pitch table.
///
/// Returns one [`Note`] per active cell across all time steps.
pub fn ca_to_notes(
evolution: &[Vec<bool>],
pitches_hz: &[f64],
duration: f64,
) -> Vec<Note> {
if pitches_hz.is_empty() {
return Vec::new();
}
let mut notes = Vec::new();
for row in evolution {
for (col, &active) in row.iter().enumerate() {
if active {
let pitch = pitches_hz[col % pitches_hz.len()];
notes.push(Note {
pitch_hz: pitch,
duration_secs: duration,
velocity: 90,
});
}
}
}
notes
}
// ── Internal ─────────────────────────────────────────────────────────────
/// Generic Wolfram elementary CA step for the given rule number (0–255).
fn apply_rule(state: &[bool], rule: u8) -> Vec<bool> {
let n = state.len();
if n == 0 {
return Vec::new();
}
(0..n)
.map(|i| {
let left = if i == 0 { state[n - 1] } else { state[i - 1] };
let center = state[i];
let right = if i == n - 1 { state[0] } else { state[i + 1] };
let pattern = ((left as u8) << 2) | ((center as u8) << 1) | (right as u8);
(rule >> pattern) & 1 == 1
})
.collect()
}
}
// ── Tests ─────────────────────────────────────────────────────────────────────
#[cfg(test)]
mod tests {
use super::*;
// ── L-system tests ────────────────────────────────────────────────────────
#[test]
fn test_iterate_zero_steps() {
let rules = HashMap::new();
let result = LSystemComposer::iterate("AB", &rules, 0);
assert_eq!(result, "AB");
}
#[test]
fn test_iterate_no_matching_rule() {
let rules = HashMap::new();
let result = LSystemComposer::iterate("XYZ", &rules, 3);
assert_eq!(result, "XYZ");
}
#[test]
fn test_iterate_algae() {
// Classic Lindenmayer algae: A→AB, B→A.
let mut rules = HashMap::new();
rules.insert('A', "AB".to_string());
rules.insert('B', "A".to_string());
let result = LSystemComposer::iterate("A", &rules, 4);
// Step 0: A, 1: AB, 2: ABA, 3: ABAAB, 4: ABAABABA
assert_eq!(result, "ABAABABA");
}
#[test]
fn test_to_notes_maps_variables() {
let mut variables = HashMap::new();
variables.insert('A', 0.0);
variables.insert('B', 7.0);
let notes = LSystemComposer::to_notes("ABA", &variables, 440.0, 0.5);
assert_eq!(notes.len(), 3);
assert!((notes[0].pitch_hz - 440.0).abs() < 1e-6);
// 7 semitones up from 440 = 440 * 2^(7/12) ≈ 659.26 Hz
assert!((notes[1].pitch_hz - 659.255).abs() < 1.0);
assert!((notes[2].pitch_hz - 440.0).abs() < 1e-6);
}
#[test]
fn test_to_notes_ignores_non_variables() {
let mut variables = HashMap::new();
variables.insert('F', 0.0);
let notes = LSystemComposer::to_notes("F+F-F", &variables, 440.0, 1.0);
// Only 'F' chars generate notes.
assert_eq!(notes.len(), 3);
}
#[test]
fn test_sierpinski_melody_definition() {
let sys = LSystemComposer::sierpinski_melody();
assert!(!sys.axiom.is_empty());
assert!(!sys.rules.is_empty());
let expanded = LSystemComposer::iterate(&sys.axiom, &sys.rules, 3);
let notes = LSystemComposer::to_notes(&expanded, &sys.variables, 440.0, 0.25);
assert!(!notes.is_empty());
}
#[test]
fn test_dragon_curve_melody_definition() {
let sys = LSystemComposer::dragon_curve_melody();
let expanded = LSystemComposer::iterate(&sys.axiom, &sys.rules, 3);
let notes = LSystemComposer::to_notes(&expanded, &sys.variables, 440.0, 0.25);
assert!(!notes.is_empty());
}
// ── CA tests ─────────────────────────────────────────────────────────────
#[test]
fn test_rule_30_single_cell() {
// Start with a single active cell in the center.
let mut state = vec![false; 7];
state[3] = true;
let next = MusicalCellularAutomaton::rule_30(&state);
assert_eq!(next.len(), 7);
// After one step the pattern should have changed.
assert_ne!(next, state);
}
#[test]
fn test_rule_110_length_preserved() {
let state = vec![false, true, false, true, true, false];
let next = MusicalCellularAutomaton::rule_110(&state);
assert_eq!(next.len(), state.len());
}
#[test]
fn test_evolve_step_count() {
let state = vec![false; 8];
let evolution = MusicalCellularAutomaton::evolve(
&state,
MusicalCellularAutomaton::rule_30,
5,
);
// Initial + 5 steps = 6 rows.
assert_eq!(evolution.len(), 6);
}
#[test]
fn test_ca_to_notes_active_cells() {
// Row with 3 active cells.
let evolution = vec![vec![true, false, true, true]];
let pitches = vec![220.0, 330.0, 440.0, 550.0];
let notes = MusicalCellularAutomaton::ca_to_notes(&evolution, &pitches, 0.5);
assert_eq!(notes.len(), 3); // cells 0, 2, 3 are active
}
#[test]
fn test_ca_to_notes_empty_pitches() {
let evolution = vec![vec![true, false, true]];
let notes = MusicalCellularAutomaton::ca_to_notes(&evolution, &[], 0.5);
assert!(notes.is_empty());
}
#[test]
fn test_ca_to_notes_pitch_wrapping() {
// More cells than pitches → wrap.
let evolution = vec![vec![true, true, true]];
let pitches = vec![440.0]; // only one pitch
let notes = MusicalCellularAutomaton::ca_to_notes(&evolution, &pitches, 0.5);
assert_eq!(notes.len(), 3);
for n in ¬es {
assert!((n.pitch_hz - 440.0).abs() < 1e-6);
}
}
#[test]
fn test_rule_30_all_false() {
let state = vec![false; 8];
let next = MusicalCellularAutomaton::rule_30(&state);
// All false input → rule 30 pattern 000 = bit 0 = 0 → all false.
assert!(next.iter().all(|&b| !b));
}
#[test]
fn test_note_duration_preserved() {
let mut variables = HashMap::new();
variables.insert('A', 0.0);
let notes = LSystemComposer::to_notes("A", &variables, 440.0, 1.23);
assert!((notes[0].duration_secs - 1.23).abs() < 1e-9);
}
}