/// 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) -> 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 { 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 { use std::collections::HashSet; let factor = calculate_factor(sequence); // Collect unique outer values let unique_outers: HashSet = sequence.values() .iter() .map(|value| value.outer) .collect(); // Multiply each by the factor and include 0 let mut rungs: Vec = 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 { use std::collections::HashMap; let factor = calculate_factor(sequence); // Group values by outer let mut groups: HashMap> = 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(¬es) }