summaryrefslogtreecommitdiff
path: root/morphology-img/src/note.rs
blob: e3f44efddb8e19e3d2f744b7888357dbce02bf92 (plain)
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
/// Represents a LilyPond absolute pitch name (e.g., "c'", "bes,", "fis")
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LilyPondPitch(String);

impl LilyPondPitch {
    pub fn new(s: impl Into<String>) -> Self {
        Self(s.into())
    }

    pub fn as_str(&self) -> &str {
        &self.0
    }
}

/// Converts an integer to a LilyPond absolute pitch name.
///
/// The mapping uses B (integer 0) as the reference pitch in the middle octave.
/// Positive integers represent diatonic steps upward, negative integers downward.
///
/// # Diatonic Scale
/// - 0 → b (reference)
/// - 1 → c' (next octave)
/// - -1 → a (same octave)
/// - 7 → b' (one octave up)
/// - -7 → b, (one octave down)
///
/// # Algorithm
/// The diatonic scale is C, D, E, F, G, A, B (7 notes).
/// B is at index 6, corresponding to n=0.
/// We adjust the input by 6 to convert to C-based indexing,
/// then use modular arithmetic to find the pitch class and octave.
pub fn integer_to_pitch_name(n: i32) -> LilyPondPitch {
    const PITCH_NAMES: [&str; 7] = ["c", "d", "e", "f", "g", "a", "b"];

    // B is at index 6, corresponds to n=0
    // Adjust to C-based indexing
    let adjusted = n + 6;

    // Calculate pitch class (0-6) and octave
    // rem_euclid and div_euclid handle negative numbers correctly
    let pitch_index = adjusted.rem_euclid(7) as usize;
    let octave = adjusted.div_euclid(7);

    // Get base pitch name
    let pitch_name = PITCH_NAMES[pitch_index];

    // Add octave markers
    let octave_marker = if octave > 0 {
        "'".repeat(octave as usize)
    } else if octave < 0 {
        ",".repeat((-octave) as usize)
    } else {
        String::new()
    };

    LilyPondPitch::new(format!("{}{}", pitch_name, octave_marker))
}

/// Represents a complete LilyPond note with duration (e.g., "c'4")
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LilyPondNote(String);

impl LilyPondNote {
    pub fn new(pitch: LilyPondPitch, duration: Duration) -> Self {
        Self(format!("{}{}", pitch.as_str(), duration.as_str()))
    }

    pub fn as_str(&self) -> &str {
        &self.0
    }
}

/// Represents a note duration in LilyPond (e.g., "4", "8", "2")
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Duration(u8);

impl Duration {
    pub const QUARTER: Duration = Duration(4);

    pub fn new(value: u8) -> Self {
        Self(value)
    }

    pub fn as_str(&self) -> String {
        self.0.to_string()
    }
}

/// Calculates the staff scaling factor for a sequence based on its inner values.
///
/// The factor is computed as: max(abs(inner values)) + 3
///
/// # Arguments
/// - `sequence`: The meta-affine sequence
///
/// # Returns
/// The factor value to use for pitch calculations
fn calculate_factor(sequence: &morphology::Sequence) -> i32 {
    let max_abs_inner = sequence.values()
        .iter()
        .map(|value| value.inner.abs())
        .max()
        .unwrap_or(0);

    max_abs_inner + 3
}

/// Converts a meta-affine sequence to a vector of LilyPond notes.
///
/// All notes are assigned quarter note duration internally.
/// In future iterations, duration may be derived from additional meta-affine structures.
///
/// Transformation steps:
/// 1. Convert (outer, inner) pairs to integers: pitch = (outer * factor) + inner
///    where factor = max(abs(inner values)) + 3
/// 2. Convert integers to pitch names using integer_to_pitch_name
/// 3. Append quarter note duration to create notes
///
/// # Arguments
/// - `sequence`: The meta-affine sequence to convert
pub fn sequence_to_notes(sequence: &morphology::Sequence) -> Vec<LilyPondNote> {
    let duration = Duration::QUARTER;
    let factor = calculate_factor(sequence);

    sequence.values()
        .iter()
        .map(|value| {
            let pitch_int = (value.outer * factor) + value.inner;
            let pitch = integer_to_pitch_name(pitch_int);
            LilyPondNote::new(pitch, duration)
        })
        .collect()
}

/// Converts a meta-affine sequence to staff line positions (rungs).
///
/// This function computes the staff line positions based on the unique outer
/// values in the sequence, scaled by the same factor used for pitch calculation.
///
/// # Algorithm
/// 1. Collect all unique outer values from the sequence
/// 2. Multiply each by the factor (max(abs(inner values)) + 3)
/// 3. Always include 0 in the result
/// 4. Return as a sorted vector
///
/// # Arguments
/// - `sequence`: The meta-affine sequence to analyze
///
/// # Returns
/// A sorted vector of staff line positions
///
/// # Examples
/// ```
/// use morphology::{Sequence, Value};
/// use morphology_img::note::sequence_to_staff;
///
/// let seq = Sequence::new(vec![
///     Value::new(1, 0),
///     Value::new(-1, -1),
///     Value::new(-1, -2),
///     Value::new(-1, 0),
///     Value::new(0, 0),
/// ]);
///
/// // Outer values: [1, -1, -1, -1, 0] -> unique: [1, -1, 0]
/// // max_abs_inner = 2, factor = 5
/// // Rungs: [5, -5, 0] -> sorted: [-5, 0, 5]
/// let staff = sequence_to_staff(&seq);
/// assert_eq!(staff, vec![-5, 0, 5]);
/// ```
pub fn sequence_to_staff(sequence: &morphology::Sequence) -> Vec<i32> {
    use std::collections::HashSet;

    let factor = calculate_factor(sequence);

    // Collect unique outer values
    let unique_outers: HashSet<i32> = sequence.values()
        .iter()
        .map(|value| value.outer)
        .collect();

    // Multiply each by the factor and include 0
    let mut rungs: Vec<i32> = unique_outers
        .into_iter()
        .map(|outer| outer * factor)
        .collect();

    // Sort the rungs
    rungs.sort();

    rungs
}

/// Converts an integer vector to a LilyPond Scheme list string.
///
/// # Arguments
/// - `values`: Vector of integers
///
/// # Returns
/// A string representing a Scheme list, e.g., "#'(-5 0 5)"
///
/// # Examples
/// ```
/// use morphology_img::note::vector_to_scheme;
///
/// let values = vec![-5, 0, 5];
/// assert_eq!(vector_to_scheme(&values), "#'(-5 0 5)");
/// ```
pub fn vector_to_scheme(values: &[i32]) -> String {
    use itertools::Itertools;

    format!("#'({})", values.iter().map(|v| v.to_string()).join(" "))
}

/// Converts a meta-affine sequence to ledger line positions.
///
/// This function computes ledger line positions based on even inner values
/// in each subset of values grouped by outer value.
///
/// # Algorithm
/// For each subset of values with the same outer value:
/// 1. Find min and max inner values in the subset
/// 2. For all even integers in the range [min_inner, max_inner]:
///    - Include (outer * factor) + n in the ledger positions
///
/// # Arguments
/// - `sequence`: The meta-affine sequence to analyze
///
/// # Returns
/// A sorted vector of ledger line positions
///
/// # Examples
/// ```
/// use morphology::{Sequence, Value};
/// use morphology_img::note::sequence_to_ledgers;
///
/// let seq = Sequence::new(vec![
///     Value::new(1, 0),
///     Value::new(-1, -1),
///     Value::new(-1, -2),
///     Value::new(-1, 0),
///     Value::new(0, 0),
/// ]);
///
/// // Subsets by outer:
/// // outer=1: inner=[0], range [0,0], even: 0 -> ledger: (1*5)+0 = 5
/// // outer=-1: inner=[-1,-2,0], range [-2,0], even: -2,0 -> ledgers: -7, -5
/// // outer=0: inner=[0], range [0,0], even: 0 -> ledger: (0*5)+0 = 0
/// let ledgers = sequence_to_ledgers(&seq);
/// assert_eq!(ledgers, vec![-7, -5, 0, 5]);
/// ```
pub fn sequence_to_ledgers(sequence: &morphology::Sequence) -> Vec<i32> {
    use std::collections::HashMap;

    let factor = calculate_factor(sequence);

    // Group values by outer
    let mut groups: HashMap<i32, Vec<i32>> = HashMap::new();
    for value in sequence.values() {
        groups.entry(value.outer)
            .or_insert_with(Vec::new)
            .push(value.inner);
    }

    let mut ledgers = Vec::new();

    // Process each group
    for (outer, inners) in groups {
        let min_inner = *inners.iter().min().unwrap();
        let max_inner = *inners.iter().max().unwrap();

        // Find all even integers in [min_inner, max_inner]
        for n in min_inner..=max_inner {
            if n % 2 == 0 {
                ledgers.push((outer * factor) + n);
            }
        }
    }

    // Sort and deduplicate
    ledgers.sort();
    ledgers.dedup();

    ledgers
}

/// Converts a vector of LilyPond notes into a space-separated string.
///
/// This function creates the LilyPond markup string that will be substituted
/// into the template .ly file.
pub fn notes_to_markup(notes: &[LilyPondNote]) -> String {
    use itertools::Itertools;

    notes.iter()
        .map(|n| n.as_str())
        .join(" ")
}

/// Converts a meta-affine sequence directly to LilyPond markup string.
///
/// This is the main public API for converting sequences to LilyPond markup.
/// It combines sequence_to_notes and notes_to_markup into a single operation.
///
/// # Arguments
/// - `sequence`: The meta-affine sequence to convert
///
/// # Returns
/// A space-separated string of LilyPond notes ready for template substitution
///
/// # Examples
/// ```
/// use morphology::{Sequence, Value};
/// use morphology_img::sequence_to_markup;
///
/// let seq = Sequence::new(vec![
///     Value::new(1, 0),
///     Value::new(-1, 1),
///     Value::new(-1, 0),
///     Value::new(0, 0),
/// ]);
///
/// let markup = sequence_to_markup(&seq);
/// assert_eq!(markup, "f'4 f4 e4 b4");
/// ```
pub fn sequence_to_markup(sequence: &morphology::Sequence) -> String {
    let notes = sequence_to_notes(sequence);
    notes_to_markup(&notes)
}