tune 0.36.0

Explore musical tunings and create synthesizer tuning files for microtonal scales.
Documentation
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
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
//! Find generator chains and keyboard layouts.

use std::cmp::Ordering;
use std::fmt;
use std::fmt::Display;
use std::fmt::Formatter;

use crate::pergen::Accidentals;
use crate::pergen::AccidentalsFormat;
use crate::pergen::AccidentalsOrder;
use crate::pergen::Mos;
use crate::pergen::NoteFormatter;
use crate::pergen::PerGen;
use crate::pitch::Ratio;
use crate::temperament::Val;

/// Find note names and step sizes for a given division of the octave using different genchains.
#[derive(Clone, Debug)]
pub struct IsomorphicLayout {
    genchain: Genchain,
    b_val: bool,
    pergen: PerGen,
    mos: Mos,
    acc_format: AccidentalsFormat,
    formatter: NoteFormatter,
}

impl IsomorphicLayout {
    pub fn find_by_edo(num_steps_per_octave: impl Into<f64>) -> Vec<IsomorphicLayout> {
        Self::find_by_step_size(Ratio::octave().divided_into_equal_steps(num_steps_per_octave))
    }

    pub fn find_by_step_size(step_size: Ratio) -> Vec<IsomorphicLayout> {
        let patent_val = Val::patent(step_size, 5);

        let patent_val_errors: Vec<_> = patent_val
            .errors_in_steps()
            .map(|error| error.abs())
            .collect();
        let evaluate_b_val = patent_val_errors[1] > 1.0 / 3.0; // Ensures b_val error is at most twice as large as patent_val error

        let b_val = evaluate_b_val.then(|| {
            let mut b_val = patent_val.clone();
            b_val.pick_alternative(1);
            b_val
        });

        [
            // Sorted from highest to lowest sharpness within a group
            Genchain::Mavila9,
            Genchain::Meantone7,
            Genchain::Meantone5,
            Genchain::Porcupine8,
            Genchain::Tetracot7,
            Genchain::Hanson7,
        ]
        .into_iter()
        .flat_map(|genchain| {
            genchain.create_layout(&patent_val, false).or_else(|| {
                b_val
                    .as_ref()
                    .and_then(|b_val| genchain.create_layout(b_val, true))
            })
        })
        .collect()
    }

    pub fn genchain(&self) -> Genchain {
        self.genchain
    }

    pub fn b_val(&self) -> bool {
        self.b_val
    }

    pub fn wart(&self) -> &'static str {
        if self.b_val { "b" } else { "" }
    }

    pub fn pergen(&self) -> &PerGen {
        &self.pergen
    }

    pub fn mos(&self) -> Mos {
        self.mos
    }

    pub fn get_scale_name(&self) -> &'static str {
        match (self.genchain, self.mos.sharpness().cmp(&0)) {
            (_, Ordering::Equal) => "equalized",
            (Genchain::Mavila9, Ordering::Greater) => "armotonic",
            (Genchain::Mavila9, Ordering::Less) => "balzano",
            (Genchain::Meantone7, Ordering::Greater) => "diatonic",
            (Genchain::Meantone7, Ordering::Less) => "antidiatonic",
            (Genchain::Meantone5, Ordering::Greater) => "antipentic",
            (Genchain::Meantone5, Ordering::Less) => "pentic",
            (Genchain::Porcupine8, Ordering::Greater) => "pine",
            (Genchain::Porcupine8, Ordering::Less) => "antipine",
            (Genchain::Tetracot7, Ordering::Greater) => "archeotonic",
            (Genchain::Tetracot7, Ordering::Less) => "onyx",
            (Genchain::Hanson7, Ordering::Greater) => "smitonic",
            (Genchain::Hanson7, Ordering::Less) => "mosh",
        }
    }

    /// Obtains the note name for the given degree of the current layout.
    ///
    /// # Examples
    ///
    /// ```
    /// # use tune::layout::IsomorphicLayout;
    /// let positive_sharpness = &IsomorphicLayout::find_by_edo(31)[0];
    ///
    /// assert_eq!(positive_sharpness.get_note_name(0), "D");
    /// assert_eq!(positive_sharpness.get_note_name(1), "Ebb");
    /// assert_eq!(positive_sharpness.get_note_name(18), "A");
    /// assert_eq!(positive_sharpness.get_note_name(25), "B#");
    ///
    /// let negative_sharpness = &IsomorphicLayout::find_by_edo(16)[1];
    ///
    /// assert_eq!(negative_sharpness.get_note_name(0), "D");
    /// assert_eq!(negative_sharpness.get_note_name(1), "D+/E-");
    /// assert_eq!(negative_sharpness.get_note_name(9), "A");
    /// assert_eq!(negative_sharpness.get_note_name(12), "B+");
    /// ```
    pub fn get_note_name(&self, index: u16) -> String {
        self.formatter.format(&self.get_accidentals(index))
    }

    pub fn get_accidentals(&self, index: u16) -> Accidentals {
        self.pergen.get_accidentals(&self.acc_format, index)
    }

    /// Generates an automatic color schema for the given layout.
    ///
    /// This function is a wrapper around [`Mos::get_layers`] with the following quality-of-life enhancements:
    ///
    /// - The returned color layer is typed as a [`Layer`].
    /// - The values are returned in stepwise instead of genchain order.
    /// - Multi-cyclic and equalized MOSes are handled.
    /// - The origin of the layout's genchain is considered.
    ///
    /// # Return Value
    ///
    /// The color schema is returned as a [`Vec`] of [`Layer`]s in stepwise order.
    /// It is the caller's responsibility to map the returned values to their target colors.
    ///
    /// # Examples
    ///
    /// ```
    /// # use tune::layout::IsomorphicLayout;
    /// # use tune::layout::Layer;
    /// let (n, s, f, e) = (Layer::Natural, Layer::Sharp, Layer::Flat, Layer::Enharmonic);
    ///
    /// // Color layers of 17-EDO:
    /// // This example illustrates the regular case where
    /// // - n represents the natural layer
    /// // - s(0)/f(0) represent full-sharp/flat layers
    /// assert_eq!(
    ///     IsomorphicLayout::find_by_edo(17)[0].get_layers(),
    ///     &[
    ///         n,    // D
    ///         f(0), // Eb
    ///         s(0), // D#
    ///         n,    // E
    ///         n,    // F
    ///         f(0), // Gb
    ///         s(0), // F#
    ///         n,    // G
    ///         f(0), // Ab
    ///         s(0), // G#
    ///         n,    // A
    ///         f(0), // Bb
    ///         s(0), // A#
    ///         n,    // B
    ///         n,    // C
    ///         f(0), // Db
    ///         s(0), // C#
    ///     ]
    /// );
    ///
    /// // Color layers of 24-EDO:
    /// // Since 24-EDO contains 2 genchains, s(0)/f(0) represent half-sharp/flat layers and
    /// // e(1) represents the layer that can be classified as both full-sharp or full-flat.
    /// assert_eq!(
    ///     IsomorphicLayout::find_by_edo(24)[0].get_layers(),
    ///     &[
    ///         n,    // D
    ///         s(0), // D^
    ///         e(1), // D#/Eb
    ///         f(0), // Ev
    ///         n,    // E
    ///         s(0), // E^
    ///         n,    // F
    ///         s(0), // F^
    ///         e(1), // F#/Gb
    ///         f(0), // Gv
    ///         n,    // G
    ///         s(0), // G^
    ///         e(1), // G#/Ab
    ///         f(0), // Av
    ///         n,    // A
    ///         s(0), // A^
    ///         e(1), // A#/Bb
    ///         f(0), // Bv
    ///         n,    // B
    ///         s(0), // B^
    ///         n,    // C
    ///         s(0), // C^
    ///         e(1), // C#/Db
    ///         f(0), // Dv
    ///     ]
    /// );
    ///
    /// // Color layers of 14-EDO:
    /// // Equalized MOSes do not render naturally as staircase patterns.
    /// // To still receive visual cues, alternating sub-layers are added.
    /// // This doubles the amount of layers being used as well as the period.
    /// // The first cycle contains the layers n-e(1)-n-e(1)-...
    /// // The second cycle contains the layers s(0)-f(0)-s(0)-f(0)-...
    /// assert_eq!(
    ///     IsomorphicLayout::find_by_edo(14)[0].get_layers(),
    ///     &[
    ///         n,    // D
    ///         s(0), // D*
    ///         n,    // E
    ///         s(0), // E*
    ///         e(1), // F
    ///         f(0), // F*
    ///         e(1), // G
    ///         f(0), // G*
    ///         e(1), // A
    ///         f(0), // A*
    ///         e(1), // B
    ///         f(0), // B*
    ///         n,    // C
    ///         s(0), // C*
    ///         n,    // D
    ///         s(0), // D*
    ///         n,    // E
    ///         s(0), // E*
    ///         e(1), // F
    ///         f(0), // F*
    ///         e(1), // G
    ///         f(0), // G*
    ///         e(1), // A
    ///         f(0), // A*
    ///         e(1), // B
    ///         f(0), // B*
    ///         n,    // C
    ///         s(0), // C*
    ///     ]
    /// );
    /// ```
    pub fn get_layers(&self) -> Vec<Layer> {
        if self.mos.sharpness() == 0 {
            // Equalized MOSes do not render as staircase patterns but as straight lines.
            // To still receive visual cues, an alternating color schema is rendered instead.
            return self.get_sharp0_layers();
        }

        let layers = self.mos.get_layers();

        let num_layers =
            layers.last().map(|&index| index + 1).unwrap_or_default() * self.pergen.num_cycles();

        (0..self.pergen.period())
            .map(|index| {
                let generation = self.pergen().get_generation(index);
                let genchain_degree = (usize::from(generation.degree)
                    + usize::from(self.acc_format.genchain_origin))
                    % layers.len();
                let layer_index = layers[genchain_degree] * self.pergen.num_cycles()
                    + generation.cycle.unwrap_or_default();

                layer_index_to_semantic_layer(layer_index, num_layers)
            })
            .collect()
    }

    /// Creates a color schema with alternating layers based on the given MOS structure.
    ///
    /// This is done in scale degree space, not generator space.
    fn get_sharp0_layers(&self) -> Vec<Layer> {
        let num_cycles = u32::from(self.pergen.num_cycles());
        let num_secondary_steps = u32::from(self.mos.num_secondary_steps());

        let genchain_offset = u32::from(self.pergen().generator())
            * u32::from(self.acc_format.genchain_origin)
            / num_cycles;
        let genchain_offset_parity =
            (genchain_offset * num_secondary_steps / self.mos.num_steps()).is_multiple_of(2);

        // Double the period s.t. consecutive periods are still alternating in layer index.
        (0..(u32::from(self.pergen.period()) * 2))
            .map(|index| {
                let scale_degree = index / num_cycles + genchain_offset;
                let scale_degree_parity =
                    (scale_degree * num_secondary_steps / self.mos.num_steps()).is_multiple_of(2);

                let cycle = u16::try_from(index % num_cycles).unwrap();
                let layer_index = cycle
                    + u16::from(genchain_offset_parity ^ scale_degree_parity)
                        * self.pergen.num_cycles();

                layer_index_to_semantic_layer(layer_index, self.pergen.num_cycles() * 2)
            })
            .collect()
    }
}

fn layer_index_to_semantic_layer(layer_index: u16, num_layers: u16) -> Layer {
    if layer_index == 0 {
        Layer::Natural
    } else if layer_index < num_layers.div_ceil(2) {
        Layer::Sharp(layer_index - 1)
    } else if Some(layer_index) == exact_div(num_layers, 2) {
        Layer::Enharmonic(layer_index - 1)
    } else if layer_index < num_layers {
        Layer::Flat(num_layers - layer_index - 1)
    } else {
        panic!("layer_index {layer_index} is out of bounds for num_layers {num_layers}")
    }
}

/// A descriptor for a consecutive genchain segment after decomposing a MOS into its color layers.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Layer {
    /// Layer containing the natural notes.
    Natural,
    /// Layer at the given level containing sharp notes.
    Sharp(u16),
    /// Layer at the given level containing flat notes.
    Flat(u16),
    /// Layer at the given level containing notes with ambiguous accidental.
    Enharmonic(u16),
}

/// Genchain used to derive note names, colors and step sizes for a given tuning.
///
/// The name is to be understood as a representative for an entire family of temperaments that share the same genchain.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub enum Genchain {
    /// Similar to [`Genchain::Meantone7`] but with 9 natural notes instead of 7.
    ///
    /// This genchain can be used when rather flat versions of 3/2 are involved and [`Genchain::Meantone7`] would result in a MOS with negative sharpness.
    ///
    /// The generated notes are [ &hellip; φb, β, F, C, G, D, A, E, B, φ, β#, &hellip; ].

    /// Due to the additional notes, the conventional relationships between interval names and just ratios no longer apply.
    /// For instance, a Mavila\[9\] major third will sound similar to a Meantone\[7\] minor third and a Mavila\[9\] minor fourth will sound similar to a Meantone\[7\] major third.
    Mavila9,

    /// Octave-reduced genchain treating four fifths (3/2) to be equal to one major third.
    ///
    /// The major third can be divided into two equal parts which form the *primary steps* of the resulting MOS.
    ///
    /// The notes are generated via the genchain of fifths [ &hellip; Bb F C G D A E B F# &hellip; ].
    /// This results in standard music notation with G at one fifth above C and D at two fifths == 1/2 major third == 1 primary step above C.
    ///
    /// This genchain is compatible with other chain-of-fifth-based temperaments like Mavila and Superpyth.
    Meantone7,

    /// Similar to [`Genchain::Meantone7`] but with 5 natural notes instead of 7.
    ///
    /// This genchain can be used when rather sharp versions of 3/2 are involved and [`Genchain::Meantone7`] would not result in a MOS.
    ///
    /// The generated notes are [ &hellip; Eb C G D A E C# &hellip; ].
    Meantone5,

    /// Octave-reduced genchain treating three seconds to be equal to one major fourth (4/3).
    ///
    /// The second acts as a *primary step* and as the generator with generated notes being [ &hellip; Hb A B C D E F G H A# &hellip; ].
    ///
    /// Unlike in meantone, the intervals E-F and F-G have the same size of one primary step while G-A is different which has some important consequences.
    /// For instance, a Porcupine\[8\] major third will sound similar to a Meantone\[7\] minor third and a Porcupine\[8\] minor fourth will sound similar to a Meantone\[7\] major third.
    Porcupine8,

    /// Similar to [`Genchain::Porcupine8`] but with 7 natural notes instead of 8 and with four seconds treated as being equal to one major fifth (3/2).
    ///
    /// This genchain can be used when rather sharp versions of 4/3 are involved and [`Genchain::Porcupine8`] would not result in a MOS.
    ///
    /// The generated notes are [ &hellip; Gb A B C D E F G A# &hellip; ].
    Tetracot7,

    /// Octave-reduced genchain treating six minor thirds to be equal to one major twelfth (3/1).
    ///
    /// The third is split into a major and minor second, corresponding to the *primary step* and *secondary step* sizes.
    ///
    /// The sixth is used to generate the notes [ &hellip; Eb C A F D B G E C# &hellip; ].
    Hanson7,
}

impl Genchain {
    fn create_layout(self, val: &Val, b_val: bool) -> Option<IsomorphicLayout> {
        let pergen = self.get_pergen(val)?;
        let spec = self.get_parameters();

        let mos = pergen.get_moses().find(|mos| {
            usize::from(mos.num_primary_steps()) + usize::from(mos.num_secondary_steps())
                == spec.genchain.len()
        })?;

        let (sharp_sign, flat_sign, order) = if mos.primary_step() >= mos.secondary_step() {
            ('#', 'b', AccidentalsOrder::SharpFlat)
        } else {
            ('-', '+', AccidentalsOrder::FlatSharp)
        };

        Some(IsomorphicLayout {
            genchain: self,
            b_val,
            pergen,
            mos,
            acc_format: AccidentalsFormat {
                num_symbols: u16::try_from(mos.num_steps()).ok()?,
                genchain_origin: spec.genchain_origin,
            },
            formatter: NoteFormatter {
                note_names: spec.genchain.into(),
                sharp_sign,
                flat_sign,
                cycle_sign: '*',
                order,
            },
        })
    }

    fn get_pergen(&self, val: &Val) -> Option<PerGen> {
        let values = val.values();
        let octave = values[0];
        let tritave = values[1];

        Some(match self {
            Genchain::Mavila9 | Genchain::Meantone7 | Genchain::Meantone5 => {
                let fifth = tritave.checked_sub(octave)?;
                PerGen::new(octave, fifth)
            }
            Genchain::Porcupine8 => {
                let third_fourth = exact_div(octave.checked_mul(2)?.checked_sub(tritave)?, 3)?;
                PerGen::new(octave, third_fourth)
            }
            Genchain::Tetracot7 => {
                let quarter_fifth = exact_div(tritave.checked_sub(octave)?, 4)?;
                PerGen::new(octave, quarter_fifth)
            }
            Genchain::Hanson7 => {
                let sixth_twelfth = exact_div(tritave, 6)?;
                let bright_generator = octave.checked_sub(sixth_twelfth)?;
                PerGen::new(octave, bright_generator)
            }
        })
    }

    fn get_parameters(self) -> GenchainParameters {
        match self {
            Genchain::Mavila9 => GenchainParameters {
                genchain: &['β', 'F', 'C', 'G', 'D', 'A', 'E', 'B', 'φ'],
                genchain_origin: 4,
            },
            Genchain::Meantone7 => GenchainParameters {
                genchain: &['F', 'C', 'G', 'D', 'A', 'E', 'B'],
                genchain_origin: 3,
            },
            Genchain::Meantone5 => GenchainParameters {
                genchain: &['C', 'G', 'D', 'A', 'E'],
                genchain_origin: 2,
            },
            Genchain::Porcupine8 => GenchainParameters {
                genchain: &['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'],
                genchain_origin: 3,
            },
            Genchain::Tetracot7 => GenchainParameters {
                genchain: &['A', 'B', 'C', 'D', 'E', 'F', 'G'],
                genchain_origin: 3,
            },
            Genchain::Hanson7 => GenchainParameters {
                genchain: &['C', 'A', 'F', 'D', 'B', 'G', 'E'],
                genchain_origin: 3,
            },
        }
    }
}

fn exact_div(numer: u16, denom: u16) -> Option<u16> {
    numer.is_multiple_of(denom).then_some(numer / denom)
}

impl Display for Genchain {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        let display_name = match self {
            Genchain::Mavila9 => "Mavila[9]",
            Genchain::Meantone7 => "Meantone[7]",
            Genchain::Meantone5 => "Meantone[5]",
            Genchain::Porcupine8 => "Porcupine[8]",
            Genchain::Tetracot7 => "Tetracot[7]",
            Genchain::Hanson7 => "Hanson[7]",
        };
        write!(f, "{display_name}")
    }
}

struct GenchainParameters {
    genchain: &'static [char],
    genchain_origin: u16,
}

#[cfg(test)]
mod tests {
    use std::fmt::Write;

    use super::*;
    use crate::math;

    #[test]
    fn edo_notes_1_to_99() {
        let mut output = String::new();

        for num_steps_per_octave in 1u16..100 {
            print_notes(&mut output, num_steps_per_octave).unwrap();
        }

        std::fs::write("edo-notes-1-to-99.txt", &output).unwrap();
        assert_eq!(output, include_str!("../edo-notes-1-to-99.txt"));
    }

    fn print_notes(output: &mut String, num_steps_per_octave: u16) -> Result<(), fmt::Error> {
        for layout in IsomorphicLayout::find_by_edo(num_steps_per_octave) {
            print_edo_headline(output, num_steps_per_octave, &layout)?;

            for index in 0..num_steps_per_octave {
                writeln!(output, "{} - {}", index, layout.get_note_name(index))?;
            }
        }

        Ok(())
    }

    #[test]
    fn edo_keyboards_1_to_99() {
        let mut output = String::new();

        for num_steps_per_octave in 1..100 {
            print_keyboards(&mut output, num_steps_per_octave).unwrap();
        }

        std::fs::write("edo-keyboards-1-to-99.txt", &output).unwrap();
        assert_eq!(output, include_str!("../edo-keyboards-1-to-99.txt"));
    }

    fn print_keyboards(output: &mut String, num_steps_per_octave: u16) -> Result<(), fmt::Error> {
        for layout in IsomorphicLayout::find_by_edo(num_steps_per_octave) {
            print_edo_headline(output, num_steps_per_octave, &layout)?;

            let mos = layout.mos().coprime();

            for y in -5i16..=5 {
                for x in 0..10 {
                    write!(
                        output,
                        "{:>4}",
                        mos.get_key(x, y)
                            .rem_euclid(i32::from(num_steps_per_octave)),
                    )?;
                }
                writeln!(output)?;
            }
        }

        Ok(())
    }

    #[test]
    fn edo_colors_1_to_99() {
        let mut output = String::new();

        for num_steps_per_octave in 1..100 {
            print_colors(&mut output, num_steps_per_octave).unwrap();
        }

        std::fs::write("edo-colors-1-to-99.txt", &output).unwrap();
        assert_eq!(output, include_str!("../edo-colors-1-to-99.txt"));
    }

    fn print_colors(output: &mut String, num_steps_per_octave: u16) -> Result<(), fmt::Error> {
        for layout in IsomorphicLayout::find_by_edo(num_steps_per_octave) {
            print_edo_headline(output, num_steps_per_octave, &layout)?;

            let layers = layout.get_layers();
            let mos = layout.mos().coprime();

            for y in -5i16..=5 {
                for x in 0..10 {
                    write!(
                        output,
                        "{:>4}",
                        format_layer(
                            &layers[usize::from(math::i32_rem_u(
                                mos.get_key(x, y),
                                num_steps_per_octave
                            ))]
                        ),
                    )?;
                }
                writeln!(output)?;
            }
        }

        Ok(())
    }

    fn print_edo_headline(
        output: &mut String,
        num_steps_per_octave: u16,
        layout: &IsomorphicLayout,
    ) -> Result<(), fmt::Error> {
        writeln!(
            output,
            "---- {}{}-EDO ({}) ----",
            num_steps_per_octave,
            layout.wart(),
            layout.genchain()
        )?;

        writeln!(
            output,
            "primary_step={}, secondary_step={}, sharpness={}, num_cycles={}",
            layout.mos().primary_step(),
            layout.mos().secondary_step(),
            layout.mos().sharpness(),
            layout.pergen().num_cycles(),
        )
    }

    fn format_layer(layer: &Layer) -> String {
        match layer {
            Layer::Natural => "nat".to_owned(),
            Layer::Sharp(index) => format!("sh{index}"),
            Layer::Flat(index) => format!("fl{index}"),
            Layer::Enharmonic(index) => format!("en{index}"),
        }
    }
}