sim-lib-music-serial 0.1.0

Immutable serial plans with stable row and event identity, explicit provenance, and validated partial temporal order.
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
//! Ranked extraction of serial-row hypotheses from exact music attacks.

use std::collections::{BTreeMap, BTreeSet};

use sim_lib_discrete_search::{
    NeverInterrupt, SearchControl, SearchInterrupt, SearchOrder, SearchProblem, SearchRun,
    SearchStatus, SearchStep, solve,
};
use sim_lib_music_core::{
    AmbiguousConversionPolicy, AtomRef, Music, MusicObject, Note, ObjectId, Score, ScoreForm,
    ScoreFormKind, Staff, StaffNote, StaffVoice, Time, convert_score,
};
use sim_lib_pitch_serial::{RowClassAlias, RowLabelConvention, ToneRow, analyze_row_class};
use thiserror::Error;

use crate::{
    ExtractionEvidence, ExtractionOutcome, RankedSerialHypothesis, SerialAliasEvidence,
    SerialObservation, SerialObservationBlock, SerialReadingOrder, SerialStableRank,
    SerialTimeSpan,
};

/// Request policy for serial-row extraction.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct SerialExtractionRequest {
    /// Generic bounded-search control reused from the discrete owner.
    pub search: SearchControl,
    /// Convention used when rendering alias labels.
    pub label_convention: RowLabelConvention,
}

impl Default for SerialExtractionRequest {
    fn default() -> Self {
        Self {
            search: SearchControl::default()
                .with_order(SearchOrder::DepthFirst)
                .with_max_results(128),
            label_convention: RowLabelConvention::FirstLastPitch,
        }
    }
}

/// Auxiliary services for extraction.
#[derive(Default)]
pub struct SerialExtractionServices<'a> {
    /// Optional external interrupt source checked by the generic search loop.
    pub interrupt: Option<&'a dyn SearchInterrupt>,
}

/// Failure while extracting serial-row hypotheses.
#[derive(Debug, Error)]
pub enum SerialExtractionError {
    /// Existing score conversion rejected the source.
    #[error("serial extraction score conversion failed: {0}")]
    ScoreConversion(String),
    /// The exact window owner rejected the source staff.
    #[error("serial extraction window construction failed: {0}")]
    WindowConstruction(String),
    /// A score-form conversion or derived identity was invalid.
    #[error("serial extraction identity failure: {0}")]
    Identity(String),
}

#[derive(Clone, Debug, PartialEq, Eq)]
struct AttackCandidate {
    voice_id: ObjectId,
    note_id: ObjectId,
    event_id: ObjectId,
    midi: u8,
    onset: Time,
    release: Time,
}

#[derive(Clone, Debug, PartialEq, Eq)]
struct AttackGroup {
    span: SerialTimeSpan,
    notes: Vec<AttackCandidate>,
}

#[derive(Clone, Debug, PartialEq, Eq)]
struct ChosenBlock {
    span: SerialTimeSpan,
    order: SerialReadingOrder,
    notes: Vec<AttackCandidate>,
}

#[derive(Clone, Debug, PartialEq, Eq)]
struct ExtractionState {
    next_group: usize,
    blocks: Vec<ChosenBlock>,
}

#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
struct BlockChoice {
    group_index: usize,
    order: SerialReadingOrder,
    event_key: String,
}

struct ExtractionProblem {
    groups: Vec<AttackGroup>,
}

impl SearchProblem for ExtractionProblem {
    type State = ExtractionState;
    type Choice = BlockChoice;
    type Output = RankedSerialHypothesis;

    fn initial_state(&self) -> Self::State {
        ExtractionState {
            next_group: 0,
            blocks: Vec::new(),
        }
    }

    fn expand(&self, state: &Self::State, out: &mut Vec<Self::Choice>) {
        if state.next_group >= self.groups.len() {
            return;
        }
        let group = &self.groups[state.next_group];
        for order in candidate_orders(group.notes.len()) {
            let sorted = sorted_candidates(&group.notes, order);
            out.push(BlockChoice {
                group_index: state.next_group,
                order,
                event_key: stable_event_key(&sorted),
            });
        }
    }

    fn apply(&self, state: &Self::State, choice: &Self::Choice) -> SearchStep<Self::State> {
        let group = &self.groups[choice.group_index];
        let mut blocks = state.blocks.clone();
        blocks.push(ChosenBlock {
            span: group.span.clone(),
            order: choice.order,
            notes: sorted_candidates(&group.notes, choice.order),
        });
        SearchStep::Continue(ExtractionState {
            next_group: state.next_group + 1,
            blocks,
        })
    }

    fn finish(&self, state: &Self::State) -> Option<Self::Output> {
        (state.next_group == self.groups.len()).then(|| hypothesis_from_blocks(&state.blocks))
    }

    fn score_state(&self, state: &Self::State) -> i64 {
        -(state.blocks.len() as i64)
    }

    fn output_score(&self, output: &Self::Output) -> Option<i64> {
        Some(
            output.stable_rank.omissions as i64 * 1_000_000
                + output.stable_rank.duplicates_before_completion as i64 * 10_000
                + output.stable_rank.order_errors as i64 * 100
                + *output.stable_rank.occupied_span.numer(),
        )
    }
}

/// Extracts ranked serial-row hypotheses from a musical score.
pub fn extract_serial_hypotheses(
    score: &Score,
    request: &SerialExtractionRequest,
    services: &SerialExtractionServices<'_>,
) -> Result<ExtractionOutcome, SerialExtractionError> {
    let staff = canonical_staff(score)?;
    let groups = attack_groups(&staff)?;
    let source_summary = vec![
        format!("voices={}", staff.voices.len()),
        format!("attack-groups={}", groups.len()),
        format!(
            "attacks={}",
            groups.iter().map(|group| group.notes.len()).sum::<usize>()
        ),
    ];
    let interrupt = services
        .interrupt
        .map_or(&NeverInterrupt as &dyn SearchInterrupt, |interrupt| {
            interrupt
        });
    let run = solve(
        &ExtractionProblem { groups },
        request.search.clone(),
        interrupt,
    );
    let receipt = run.receipt.clone();
    let ranked = dedupe_and_rank(run, request.label_convention);
    let evidence = ExtractionEvidence {
        search: receipt,
        source_summary,
    };
    match evidence.search.status {
        SearchStatus::Partial => Ok(ExtractionOutcome::BudgetExhausted { ranked, evidence }),
        SearchStatus::Cancelled | SearchStatus::Infeasible | SearchStatus::Complete => {
            if ranked.len() <= 1 {
                let hypothesis = ranked.first().cloned().unwrap_or_else(empty_hypothesis);
                Ok(ExtractionOutcome::Complete {
                    hypothesis: Box::new(hypothesis),
                    ranked,
                    evidence,
                })
            } else {
                Ok(ExtractionOutcome::Ambiguous { ranked, evidence })
            }
        }
    }
}

fn canonical_staff(score: &Score) -> Result<Staff, SerialExtractionError> {
    if let Some(form) = score_form(&score.body) {
        let report = convert_score(
            &form,
            ScoreFormKind::Staff,
            AmbiguousConversionPolicy::Reject,
        )
        .map_err(|error| SerialExtractionError::ScoreConversion(error.to_string()))?;
        let ScoreForm::Staff(staff) = report.value else {
            unreachable!("staff conversion must return a staff");
        };
        Ok(staff)
    } else {
        flattened_staff(score)
    }
}

fn attack_groups(staff: &Staff) -> Result<Vec<AttackGroup>, SerialExtractionError> {
    let duration = staff.duration();
    if duration == Time::from_integer(0) {
        return Ok(Vec::new());
    }
    let notes = staff
        .notes()
        .map(|note| {
            let midi = note.note.pitch.to_midi().ok_or_else(|| {
                SerialExtractionError::WindowConstruction(format!(
                    "non-MIDI pitch in event {}",
                    note.event_id
                ))
            })?;
            Ok(AttackCandidate {
                voice_id: note.voice_id.clone(),
                note_id: note.note_id.clone(),
                event_id: note.event_id.clone(),
                midi,
                onset: note.onset,
                release: note.end(),
            })
        })
        .collect::<Result<Vec<_>, SerialExtractionError>>()?;
    let mut boundaries = vec![Time::from_integer(0), duration];
    for note in &notes {
        boundaries.push(note.onset);
        boundaries.push(note.release);
    }
    boundaries.sort();
    boundaries.dedup();
    Ok(boundaries
        .windows(2)
        .filter_map(|pair| {
            let span = SerialTimeSpan::new(pair[0], pair[1]);
            let attacks = notes
                .iter()
                .filter(|note| note.onset == span.start)
                .cloned()
                .collect::<Vec<_>>();
            (!attacks.is_empty()).then_some(AttackGroup {
                span,
                notes: attacks,
            })
        })
        .collect())
}

fn hypothesis_from_blocks(blocks: &[ChosenBlock]) -> RankedSerialHypothesis {
    let mut seen = BTreeMap::<u8, usize>::new();
    let mut row_classes = Vec::new();
    let mut duplicates_before_completion = 0usize;
    let mut order_errors = 0usize;
    let mut observations = Vec::new();
    let mut all_event_ids = Vec::new();
    for block in blocks {
        let mut block_observations = Vec::new();
        for note in &block.notes {
            let class = note.midi % 12;
            let ordinal = if let Some(&ordinal) = seen.get(&class) {
                if row_classes.len() < 12 {
                    duplicates_before_completion += 1;
                } else {
                    order_errors += 1;
                }
                ordinal
            } else {
                let ordinal = row_classes.len();
                seen.insert(class, ordinal);
                row_classes.push(class);
                ordinal
            };
            block_observations.push(SerialObservation {
                voice_id: note.voice_id.clone(),
                note_id: note.note_id.clone(),
                event_id: note.event_id.clone(),
                ordinal,
                span: block.span.clone(),
            });
            all_event_ids.push(note.event_id.to_string());
        }
        observations.push(SerialObservationBlock {
            span: block.span.clone(),
            order: block.order,
            observations: block_observations,
        });
    }

    let omissions = 12usize.saturating_sub(row_classes.len());
    let row = tone_row_from_classes(&row_classes);
    let row_report = analyze_row_class(&row);
    let aliases = alias_evidence(
        &row_report.aliases,
        &row,
        RowLabelConvention::FirstLastPitch,
    );
    let start = blocks
        .first()
        .map(|block| block.span.start)
        .unwrap_or_else(|| Time::from_integer(0));
    let end = blocks
        .iter()
        .flat_map(|block| block.notes.iter().map(|note| note.release))
        .max()
        .unwrap_or(start);
    let span = SerialTimeSpan::new(start, end);
    let stable_key = all_event_ids.join("|");
    let stable_rank = SerialStableRank {
        omissions,
        duplicates_before_completion,
        order_errors,
        occupied_span: span.duration(),
        stable_key,
    };
    RankedSerialHypothesis {
        stable_rank,
        row,
        blocks: observations,
        duplicates_before_completion,
        order_errors,
        omissions,
        span,
        aliases,
    }
}

fn alias_evidence(
    aliases: &[RowClassAlias],
    row: &ToneRow,
    convention: RowLabelConvention,
) -> Vec<SerialAliasEvidence> {
    aliases
        .iter()
        .copied()
        .map(|alias| {
            let label = row.apply(alias.operation).label(convention).to_string();
            SerialAliasEvidence { alias, label }
        })
        .collect()
}

fn dedupe_and_rank(
    run: SearchRun<RankedSerialHypothesis>,
    convention: RowLabelConvention,
) -> Vec<RankedSerialHypothesis> {
    let mut by_key = BTreeMap::<String, RankedSerialHypothesis>::new();
    for mut hypothesis in run.outputs {
        hypothesis.aliases = alias_evidence(
            &analyze_row_class(&hypothesis.row).aliases,
            &hypothesis.row,
            convention,
        );
        let key = format!(
            "{:?}|{:?}|{:?}",
            hypothesis.row.classes(),
            hypothesis.stable_rank,
            hypothesis
                .blocks
                .iter()
                .map(|block| block.order.as_str())
                .collect::<Vec<_>>()
        );
        by_key.entry(key).or_insert(hypothesis);
    }
    let mut ranked = by_key.into_values().collect::<Vec<_>>();
    ranked.sort_by(|left, right| {
        left.stable_rank
            .cmp(&right.stable_rank)
            .then_with(|| left.aliases.len().cmp(&right.aliases.len()))
    });
    ranked
}

fn candidate_orders(group_len: usize) -> Vec<SerialReadingOrder> {
    let mut orders = BTreeSet::from([
        SerialReadingOrder::WindowOrder,
        SerialReadingOrder::PitchAscending,
        SerialReadingOrder::PitchDescending,
        SerialReadingOrder::VoiceAscending,
        SerialReadingOrder::VoiceDescending,
    ]);
    if group_len <= 1 {
        orders.retain(|order| *order == SerialReadingOrder::WindowOrder);
    }
    orders.into_iter().collect()
}

fn sorted_candidates(notes: &[AttackCandidate], order: SerialReadingOrder) -> Vec<AttackCandidate> {
    let mut sorted = notes.to_vec();
    match order {
        SerialReadingOrder::WindowOrder => {}
        SerialReadingOrder::PitchAscending => sorted.sort_by(|left, right| {
            left.midi
                .cmp(&right.midi)
                .then_with(|| left.voice_id.cmp(&right.voice_id))
                .then_with(|| left.event_id.cmp(&right.event_id))
        }),
        SerialReadingOrder::PitchDescending => sorted.sort_by(|left, right| {
            right
                .midi
                .cmp(&left.midi)
                .then_with(|| left.voice_id.cmp(&right.voice_id))
                .then_with(|| left.event_id.cmp(&right.event_id))
        }),
        SerialReadingOrder::VoiceAscending => sorted.sort_by(|left, right| {
            left.voice_id
                .cmp(&right.voice_id)
                .then_with(|| left.midi.cmp(&right.midi))
                .then_with(|| left.event_id.cmp(&right.event_id))
        }),
        SerialReadingOrder::VoiceDescending => sorted.sort_by(|left, right| {
            right
                .voice_id
                .cmp(&left.voice_id)
                .then_with(|| left.midi.cmp(&right.midi))
                .then_with(|| left.event_id.cmp(&right.event_id))
        }),
    }
    sorted
}

fn stable_event_key(notes: &[AttackCandidate]) -> String {
    notes
        .iter()
        .map(|note| note.event_id.to_string())
        .collect::<Vec<_>>()
        .join("|")
}

fn tone_row_from_classes(classes: &[u8]) -> ToneRow {
    use sim_lib_music_core::PitchClass;

    let mut ordered = classes
        .iter()
        .copied()
        .map(|value| PitchClass::new(value).expect("pitch class"))
        .collect::<Vec<_>>();
    for value in 0..12u8 {
        if !classes.contains(&value) {
            ordered.push(PitchClass::new(value).expect("pitch class"));
        }
    }
    let classes = std::array::from_fn(|index| ordered[index]);
    ToneRow::try_from_classes(classes).expect("padded class order is exhaustive")
}

fn empty_hypothesis() -> RankedSerialHypothesis {
    let row = tone_row_from_classes(&[]);
    RankedSerialHypothesis {
        stable_rank: SerialStableRank {
            omissions: 12,
            duplicates_before_completion: 0,
            order_errors: 0,
            occupied_span: Time::from_integer(0),
            stable_key: "empty".to_owned(),
        },
        row,
        blocks: Vec::new(),
        duplicates_before_completion: 0,
        order_errors: 0,
        omissions: 12,
        span: SerialTimeSpan::new(Time::from_integer(0), Time::from_integer(0)),
        aliases: Vec::new(),
    }
}

fn score_form(music: &Music) -> Option<ScoreForm> {
    match music {
        Music::Chord(value) => Some(ScoreForm::Chord(value.clone())),
        Music::Melody(value) => Some(ScoreForm::Melody(value.clone())),
        Music::Progression(value) => Some(ScoreForm::Progression(value.clone())),
        Music::Counterpoint(value) => Some(ScoreForm::Counterpoint(value.clone())),
        Music::PianoRoll(value) => Some(ScoreForm::PianoRoll(value.clone())),
        Music::Note(_)
        | Music::Rest(_)
        | Music::Par(_)
        | Music::Seq(_)
        | Music::Arranger(_)
        | Music::MidiTrack(_)
        | Music::MidiFile(_) => None,
    }
}

fn flattened_staff(score: &Score) -> Result<Staff, SerialExtractionError> {
    let duration = score.body.duration();
    let mut atoms = Vec::new();
    score.body.voices(Time::from_integer(0), &mut atoms);
    let mut voices = BTreeMap::<u8, StaffVoice>::new();
    for (index, atom) in atoms.into_iter().enumerate() {
        let AtomRef::Note(note) = atom.atom else {
            continue;
        };
        push_derived_note(&mut voices, duration, index, atom.onset, note)?;
    }
    if voices.is_empty() {
        let voice_id = object_id("score/voice/silence")?;
        voices.insert(
            0,
            StaffVoice {
                id: voice_id,
                name: "Silence".to_owned(),
                duration,
                notes: Vec::new(),
            },
        );
    }
    Staff::new(voices.into_values().collect())
        .map_err(|error| SerialExtractionError::ScoreConversion(error.to_string()))
}

fn push_derived_note(
    voices: &mut BTreeMap<u8, StaffVoice>,
    duration: Time,
    index: usize,
    onset: Time,
    note: Note,
) -> Result<(), SerialExtractionError> {
    let channel = note.channel.0;
    let voice_id = object_id(format!("score/voice/channel-{channel}"))?;
    let entry = voices.entry(channel).or_insert_with(|| StaffVoice {
        id: voice_id.clone(),
        name: format!("Derived channel {channel}"),
        duration,
        notes: Vec::new(),
    });
    entry.notes.push(StaffNote {
        voice_id,
        note_id: object_id(format!("score/note/{index}"))?,
        event_id: object_id(format!("score/event/{index}"))?,
        onset,
        note,
    });
    Ok(())
}

fn object_id(value: impl Into<String>) -> Result<ObjectId, SerialExtractionError> {
    ObjectId::new(value).map_err(|error| SerialExtractionError::Identity(error.to_string()))
}