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
use std::collections::BTreeMap;

use sim_lib_pitch_serial::{
    RowForm, RowPartition, analyze_combinatoriality_partition, analyze_interlocking_partitions,
};

use crate::{
    EventPlacement, RowInstanceId, SerialEventId, SimultaneousGroupId, StructuralLicense, VoiceId,
};

use super::core::{
    PlanBuilder, SerialDeployError, SerialDeployer, SerialDeployerInner, require_row,
    require_voices, structural_event,
};

/// Complete horizontal statement deployment for one row.
#[derive(Clone)]
pub struct HorizontalStatementSpec {
    /// Source row to present.
    pub row_id: RowInstanceId,
    /// Stable event id for the emitted statement.
    pub event_id: SerialEventId,
    /// Voice receiving the statement.
    pub voice: VoiceId,
    /// Human-facing structural rationale.
    pub rationale: String,
    /// Structural reading that licenses the statement.
    pub license: StructuralLicense,
}

impl HorizontalStatementSpec {
    pub(crate) fn apply(
        &self,
        rows: &BTreeMap<RowInstanceId, RowForm>,
        builder: &mut PlanBuilder,
    ) -> Result<(), SerialDeployError> {
        require_row("complete-horizontal-statement", rows, &self.row_id)?;
        builder.add_event(
            "complete-horizontal-statement",
            structural_event(
                self.event_id.clone(),
                &(0..12).map(|ordinal| ordinal as u8).collect::<Vec<_>>(),
                self.row_id.clone(),
                self.voice.clone(),
                self.rationale.clone(),
                self.license.clone(),
                EventPlacement::independent(),
            ),
        )
    }
}

/// Creates one complete horizontal row statement deployer.
pub fn complete_horizontal_statement(
    row_id: RowInstanceId,
    event_id: SerialEventId,
    voice: VoiceId,
    rationale: impl Into<String>,
    license: StructuralLicense,
) -> SerialDeployer {
    SerialDeployer {
        inner: SerialDeployerInner::Horizontal(HorizontalStatementSpec {
            row_id,
            event_id,
            voice,
            rationale: rationale.into(),
            license,
        }),
    }
}

/// Sequential motivic partition deployment over one row.
#[derive(Clone)]
pub struct MotivicPartitionSpec {
    /// Source row to partition.
    pub row_id: RowInstanceId,
    /// Validated partition to emit.
    pub partition: RowPartition,
    /// One voice per partition block.
    pub voices: Vec<VoiceId>,
    /// Stable event id prefix.
    pub event_prefix: String,
    /// Human-facing structural rationale.
    pub rationale: String,
    /// Structural reading that licenses the partition.
    pub license: StructuralLicense,
}

impl MotivicPartitionSpec {
    pub(crate) fn apply(
        &self,
        rows: &BTreeMap<RowInstanceId, RowForm>,
        builder: &mut PlanBuilder,
    ) -> Result<(), SerialDeployError> {
        require_row("motivic-partition", rows, &self.row_id)?;
        require_voices(
            "motivic-partition",
            self.partition.block_count(),
            self.voices.len(),
        )?;
        let mut previous = None::<SerialEventId>;
        for (index, (block, voice)) in self.partition.blocks().iter().zip(&self.voices).enumerate()
        {
            let event_id = SerialEventId::new(format!("{}/block-{}", self.event_prefix, index))
                .map_err(|error| SerialDeployError::Plan(error.to_string()))?;
            builder.add_event(
                "motivic-partition",
                structural_event(
                    event_id.clone(),
                    block.ordinals(),
                    self.row_id.clone(),
                    voice.clone(),
                    self.rationale.clone(),
                    self.license.clone(),
                    EventPlacement::independent(),
                ),
            )?;
            if let Some(previous_id) = previous.as_ref() {
                builder.add_precedence(previous_id, &event_id);
            }
            previous = Some(event_id);
        }
        Ok(())
    }
}

/// Creates one sequential motivic partition deployer.
pub fn motivic_partition(
    row_id: RowInstanceId,
    partition: RowPartition,
    voices: Vec<VoiceId>,
    event_prefix: impl Into<String>,
    rationale: impl Into<String>,
    license: StructuralLicense,
) -> SerialDeployer {
    SerialDeployer {
        inner: SerialDeployerInner::Motivic(MotivicPartitionSpec {
            row_id,
            partition,
            voices,
            event_prefix: event_prefix.into(),
            rationale: rationale.into(),
            license,
        }),
    }
}

/// Chordal vertical-block deployment over one row.
#[derive(Clone)]
pub struct VerticalBlocksSpec {
    /// Source row to partition.
    pub row_id: RowInstanceId,
    /// Validated partition supplying vertical blocks.
    pub partition: RowPartition,
    /// Block indices that should sound as chordal events.
    pub selected_blocks: Vec<usize>,
    /// Voice receiving the chordal material.
    pub voice: VoiceId,
    /// Stable event id prefix.
    pub event_prefix: String,
    /// Human-facing structural rationale.
    pub rationale: String,
    /// Structural reading that licenses the vertical reading.
    pub license: StructuralLicense,
}

impl VerticalBlocksSpec {
    pub(crate) fn apply(
        &self,
        rows: &BTreeMap<RowInstanceId, RowForm>,
        builder: &mut PlanBuilder,
    ) -> Result<(), SerialDeployError> {
        require_row("vertical-blocks", rows, &self.row_id)?;
        let mut previous = None::<SerialEventId>;
        for (position, block_index) in self.selected_blocks.iter().copied().enumerate() {
            let block = self
                .partition
                .blocks()
                .get(block_index)
                .expect("validated block index selected by caller");
            let event_id =
                SerialEventId::new(format!("{}/vertical-{}", self.event_prefix, position))
                    .map_err(|error| SerialDeployError::Plan(error.to_string()))?;
            builder.add_event(
                "vertical-blocks",
                structural_event(
                    event_id.clone(),
                    block.ordinals(),
                    self.row_id.clone(),
                    self.voice.clone(),
                    self.rationale.clone(),
                    self.license.clone(),
                    EventPlacement::independent(),
                ),
            )?;
            if let Some(previous_id) = previous.as_ref() {
                builder.add_precedence(previous_id, &event_id);
            }
            previous = Some(event_id);
        }
        Ok(())
    }
}

/// Creates one chordal vertical-block deployer.
pub fn verticalize_selected_blocks(spec: VerticalBlocksSpec) -> SerialDeployer {
    SerialDeployer {
        inner: SerialDeployerInner::Vertical(spec),
    }
}

/// Interlocking partition deployment over one row.
#[derive(Clone)]
pub struct InterlockingPartitionSpec {
    /// Source row to partition.
    pub row_id: RowInstanceId,
    /// Primary partition to emit.
    pub partition: RowPartition,
    /// Counter-partition used as the interlocking witness.
    pub counter_partition: RowPartition,
    /// One voice per emitted block.
    pub voices: Vec<VoiceId>,
    /// Stable event id prefix.
    pub event_prefix: String,
    /// Human-facing structural rationale.
    pub rationale: String,
    /// Structural reading that licenses the interlocking reading.
    pub license: StructuralLicense,
}

impl InterlockingPartitionSpec {
    pub(crate) fn apply(
        &self,
        rows: &BTreeMap<RowInstanceId, RowForm>,
        builder: &mut PlanBuilder,
    ) -> Result<(), SerialDeployError> {
        require_row("interlocking-partition", rows, &self.row_id)?;
        require_voices(
            "interlocking-partition",
            self.partition.block_count(),
            self.voices.len(),
        )?;
        let report = analyze_interlocking_partitions(&self.partition, &self.counter_partition);
        if !report.is_interlocking {
            return Err(SerialDeployError::NotInterlocking {
                deployer: "interlocking-partition".to_owned(),
            });
        }
        let mut previous = None::<SerialEventId>;
        for (index, (block, voice)) in self.partition.blocks().iter().zip(&self.voices).enumerate()
        {
            let event_id = SerialEventId::new(format!("{}/exchange-{}", self.event_prefix, index))
                .map_err(|error| SerialDeployError::Plan(error.to_string()))?;
            builder.add_event(
                "interlocking-partition",
                structural_event(
                    event_id.clone(),
                    block.ordinals(),
                    self.row_id.clone(),
                    voice.clone(),
                    format!("{}; interlocking witness", self.rationale),
                    self.license.clone(),
                    EventPlacement::independent(),
                ),
            )?;
            if let Some(previous_id) = previous.as_ref() {
                builder.add_precedence(previous_id, &event_id);
            }
            previous = Some(event_id);
        }
        Ok(())
    }
}

/// Creates one interlocking partition deployer.
pub fn interlocking_partition(spec: InterlockingPartitionSpec) -> SerialDeployer {
    SerialDeployer {
        inner: SerialDeployerInner::Interlocking(spec),
    }
}

/// Melody/accompaniment distribution deployment over one row.
#[derive(Clone)]
pub struct MelodyAccompanimentSpec {
    /// Source row to partition.
    pub row_id: RowInstanceId,
    /// Validated partition supplying blocks.
    pub partition: RowPartition,
    /// Lead melody voice.
    pub melody_voice: VoiceId,
    /// Accompaniment voice.
    pub accompaniment_voice: VoiceId,
    /// Stable event id prefix.
    pub event_prefix: String,
    /// Human-facing structural rationale.
    pub rationale: String,
    /// Structural reading that licenses the split.
    pub license: StructuralLicense,
}

impl MelodyAccompanimentSpec {
    pub(crate) fn apply(
        &self,
        rows: &BTreeMap<RowInstanceId, RowForm>,
        builder: &mut PlanBuilder,
    ) -> Result<(), SerialDeployError> {
        require_row("melody-accompaniment", rows, &self.row_id)?;
        let mut previous = None::<SerialEventId>;
        for (index, block) in self.partition.blocks().iter().enumerate() {
            let melody_id = SerialEventId::new(format!("{}/melody-{}", self.event_prefix, index))
                .map_err(|error| SerialDeployError::Plan(error.to_string()))?;
            builder.add_event(
                "melody-accompaniment",
                structural_event(
                    melody_id.clone(),
                    &[block.ordinals()[0]],
                    self.row_id.clone(),
                    self.melody_voice.clone(),
                    self.rationale.clone(),
                    self.license.clone(),
                    EventPlacement::independent(),
                ),
            )?;
            if let Some(previous_id) = previous.as_ref() {
                builder.add_precedence(previous_id, &melody_id);
            }
            previous = Some(melody_id.clone());
            if block.ordinals().len() > 1 {
                let accompaniment_id =
                    SerialEventId::new(format!("{}/accompaniment-{}", self.event_prefix, index))
                        .map_err(|error| SerialDeployError::Plan(error.to_string()))?;
                builder.add_event(
                    "melody-accompaniment",
                    structural_event(
                        accompaniment_id.clone(),
                        &block.ordinals()[1..],
                        self.row_id.clone(),
                        self.accompaniment_voice.clone(),
                        format!("{}; accompaniment residue", self.rationale),
                        self.license.clone(),
                        EventPlacement::independent(),
                    ),
                )?;
                builder.add_precedence(&melody_id, &accompaniment_id);
                previous = Some(accompaniment_id);
            }
        }
        Ok(())
    }
}

/// Creates one melody/accompaniment deployer.
pub fn melody_accompaniment_distribution(spec: MelodyAccompanimentSpec) -> SerialDeployer {
    SerialDeployer {
        inner: SerialDeployerInner::MelodyAccompaniment(spec),
    }
}

/// Aggregate-rotation deployment over one row.
#[derive(Clone)]
pub struct AggregateRotationSpec {
    /// Source row to rotate.
    pub row_id: RowInstanceId,
    /// Rotation offset in row ordinals.
    pub rotation: usize,
    /// Block lengths after rotation.
    pub block_lengths: Vec<usize>,
    /// One voice per rotated block.
    pub voices: Vec<VoiceId>,
    /// Stable event id prefix.
    pub event_prefix: String,
    /// Human-facing structural rationale.
    pub rationale: String,
    /// Structural reading that licenses the rotation.
    pub license: StructuralLicense,
}

impl AggregateRotationSpec {
    pub(crate) fn apply(
        &self,
        rows: &BTreeMap<RowInstanceId, RowForm>,
        builder: &mut PlanBuilder,
    ) -> Result<(), SerialDeployError> {
        require_row("aggregate-rotation", rows, &self.row_id)?;
        require_voices(
            "aggregate-rotation",
            self.block_lengths.len(),
            self.voices.len(),
        )?;
        let total: usize = self.block_lengths.iter().sum();
        if total != 12 {
            return Err(SerialDeployError::InvalidRotationCoverage(total));
        }
        let ordinals = (0..12)
            .map(|offset| ((self.rotation + offset) % 12) as u8)
            .collect::<Vec<_>>();
        let mut start = 0usize;
        let mut previous = None::<SerialEventId>;
        for (index, (len, voice)) in self
            .block_lengths
            .iter()
            .copied()
            .zip(&self.voices)
            .enumerate()
        {
            let event_id = SerialEventId::new(format!("{}/rotation-{}", self.event_prefix, index))
                .map_err(|error| SerialDeployError::Plan(error.to_string()))?;
            builder.add_event(
                "aggregate-rotation",
                structural_event(
                    event_id.clone(),
                    &ordinals[start..start + len],
                    self.row_id.clone(),
                    voice.clone(),
                    self.rationale.clone(),
                    self.license.clone(),
                    EventPlacement::independent(),
                ),
            )?;
            if let Some(previous_id) = previous.as_ref() {
                builder.add_precedence(previous_id, &event_id);
            }
            previous = Some(event_id);
            start += len;
        }
        Ok(())
    }
}

/// Creates one aggregate-rotation deployer.
#[allow(clippy::missing_const_for_fn)]
pub fn aggregate_rotation(spec: AggregateRotationSpec) -> SerialDeployer {
    SerialDeployer {
        inner: SerialDeployerInner::AggregateRotation(spec),
    }
}

/// Simultaneous multi-form deployment aligned by contiguous blocks.
#[derive(Clone)]
pub struct SimultaneousFormsSpec {
    /// Row ids to align simultaneously.
    pub row_ids: Vec<RowInstanceId>,
    /// One voice per row form.
    pub voices: Vec<VoiceId>,
    /// Supported contiguous block size.
    pub block_size: usize,
    /// Stable event id prefix.
    pub event_prefix: String,
    /// Human-facing structural rationale.
    pub rationale: String,
    /// Structural reading that licenses the simultaneity.
    pub license: StructuralLicense,
}

impl SimultaneousFormsSpec {
    pub(crate) fn apply(
        &self,
        rows: &BTreeMap<RowInstanceId, RowForm>,
        builder: &mut PlanBuilder,
    ) -> Result<(), SerialDeployError> {
        require_voices("simultaneous-forms", self.row_ids.len(), self.voices.len())?;
        for row_id in &self.row_ids {
            require_row("simultaneous-forms", rows, row_id)?;
        }
        let source_id = self.row_ids.first().expect("at least one row");
        let source_row = rows.get(source_id).expect("validated row").row().clone();
        for partner_id in self.row_ids.iter().skip(1) {
            let partner = rows.get(partner_id).expect("validated row");
            let witness = analyze_combinatoriality_partition(
                &source_row,
                partner.operation(),
                self.block_size,
            )
            .map_err(|error| SerialDeployError::Partition(error.to_string()))?;
            let Some(partner_witness) = witness else {
                return Err(SerialDeployError::NotCombinatorial {
                    source_row_id: source_id.clone(),
                    partner_row_id: partner_id.clone(),
                    block_size: self.block_size,
                });
            };
            if partner_witness.operation != partner.operation() {
                return Err(SerialDeployError::NotCombinatorial {
                    source_row_id: source_id.clone(),
                    partner_row_id: partner_id.clone(),
                    block_size: self.block_size,
                });
            }
        }
        let block_count = 12 / self.block_size;
        let mut previous_group = Vec::<SerialEventId>::new();
        for block_index in 0..block_count {
            let group =
                SimultaneousGroupId::new(format!("{}/simul-{}", self.event_prefix, block_index))
                    .map_err(|error| SerialDeployError::Plan(error.to_string()))?;
            let mut current_group = Vec::new();
            for (row_id, voice) in self.row_ids.iter().zip(&self.voices) {
                let event_id = SerialEventId::new(format!(
                    "{}/form-{}/block-{}",
                    self.event_prefix,
                    row_id.as_str().replace('/', "_"),
                    block_index
                ))
                .map_err(|error| SerialDeployError::Plan(error.to_string()))?;
                let start = block_index * self.block_size;
                let ordinals = (start..start + self.block_size)
                    .map(|ordinal| ordinal as u8)
                    .collect::<Vec<_>>();
                builder.add_event(
                    "simultaneous-forms",
                    structural_event(
                        event_id.clone(),
                        &ordinals,
                        row_id.clone(),
                        voice.clone(),
                        self.rationale.clone(),
                        self.license.clone(),
                        EventPlacement::simultaneous(group.clone()),
                    ),
                )?;
                current_group.push(event_id);
            }
            for previous_id in &previous_group {
                for current_id in &current_group {
                    builder.add_precedence(previous_id, current_id);
                }
            }
            previous_group = current_group;
        }
        Ok(())
    }
}

/// Creates one simultaneous-forms deployer.
pub fn simultaneous_forms(spec: SimultaneousFormsSpec) -> SerialDeployer {
    SerialDeployer {
        inner: SerialDeployerInner::SimultaneousForms(spec),
    }
}