retrograde.py
python
| 1 | """muse retrograde — reverse the note order of a MIDI track. |
| 2 | |
| 3 | Plays the melody backward: the last note becomes the first. A classical |
| 4 | transformation used in canon, fugue, and serial music. Agents composing |
| 5 | palindromic or mirror structures can apply this automatically. |
| 6 | |
| 7 | Usage:: |
| 8 | |
| 9 | muse retrograde tracks/melody.mid |
| 10 | muse retrograde tracks/melody.mid --dry-run |
| 11 | |
| 12 | Output:: |
| 13 | |
| 14 | ✅ Retrograded tracks/melody.mid |
| 15 | 23 notes reversed (C4 → was last, now first) |
| 16 | Duration preserved · original span: 8.0 beats |
| 17 | Run `muse status` to review, then `muse commit` |
| 18 | """ |
| 19 | |
| 20 | from __future__ import annotations |
| 21 | |
| 22 | import logging |
| 23 | import pathlib |
| 24 | |
| 25 | import typer |
| 26 | |
| 27 | from muse.core.errors import ExitCode |
| 28 | from muse.core.validation import contain_path |
| 29 | from muse.core.repo import require_repo |
| 30 | from muse.plugins.midi._query import NoteInfo, load_track_from_workdir, notes_to_midi_bytes |
| 31 | from muse.plugins.midi.midi_diff import _pitch_name |
| 32 | |
| 33 | logger = logging.getLogger(__name__) |
| 34 | app = typer.Typer() |
| 35 | |
| 36 | |
| 37 | @app.callback(invoke_without_command=True) |
| 38 | def retrograde( |
| 39 | ctx: typer.Context, |
| 40 | track: str = typer.Argument(..., metavar="TRACK", help="Workspace-relative path to a .mid file."), |
| 41 | dry_run: bool = typer.Option(False, "--dry-run", "-n", help="Preview without writing."), |
| 42 | ) -> None: |
| 43 | """Reverse the pitch order of all notes (retrograde transformation). |
| 44 | |
| 45 | ``muse retrograde`` maps note positions: the note that was at tick T from |
| 46 | the end is placed at tick T from the start, so the last note plays first. |
| 47 | Durations and velocities are preserved; only pitch and position are swapped. |
| 48 | |
| 49 | This is a foundational operation in serial/twelve-tone composition and is |
| 50 | impossible to describe meaningfully in Git's binary-blob model. |
| 51 | """ |
| 52 | root = require_repo() |
| 53 | result = load_track_from_workdir(root, track) |
| 54 | if result is None: |
| 55 | typer.echo(f"❌ Track '{track}' not found or not a valid MIDI file.", err=True) |
| 56 | raise typer.Exit(code=ExitCode.USER_ERROR) |
| 57 | |
| 58 | notes, tpb = result |
| 59 | if not notes: |
| 60 | typer.echo(f" (track '{track}' contains no notes — nothing to retrograde)") |
| 61 | return |
| 62 | |
| 63 | # Sort by start time to get the temporal order, then reverse pitches. |
| 64 | by_time = sorted(notes, key=lambda n: n.start_tick) |
| 65 | reversed_pitches = [n.pitch for n in reversed(by_time)] |
| 66 | |
| 67 | total_ticks = max(n.start_tick + n.duration_ticks for n in notes) |
| 68 | retro: list[NoteInfo] = [ |
| 69 | NoteInfo( |
| 70 | pitch=reversed_pitches[i], |
| 71 | velocity=by_time[i].velocity, |
| 72 | start_tick=by_time[i].start_tick, |
| 73 | duration_ticks=by_time[i].duration_ticks, |
| 74 | channel=by_time[i].channel, |
| 75 | ticks_per_beat=by_time[i].ticks_per_beat, |
| 76 | ) |
| 77 | for i in range(len(by_time)) |
| 78 | ] |
| 79 | |
| 80 | span_beats = total_ticks / max(tpb, 1) |
| 81 | first_orig = _pitch_name(by_time[0].pitch) |
| 82 | first_retro = _pitch_name(retro[0].pitch) |
| 83 | |
| 84 | if dry_run: |
| 85 | typer.echo(f"\n[dry-run] Would retrograde {track}") |
| 86 | typer.echo(f" Notes: {len(notes)}") |
| 87 | typer.echo(f" Was: first note = {first_orig}") |
| 88 | typer.echo(f" Would: first note = {first_retro}") |
| 89 | typer.echo(f" Span: {span_beats:.2f} beats (unchanged)") |
| 90 | typer.echo(" No changes written (--dry-run).") |
| 91 | return |
| 92 | |
| 93 | midi_bytes = notes_to_midi_bytes(retro, tpb) |
| 94 | workdir = root |
| 95 | try: |
| 96 | work_path = contain_path(workdir, track) |
| 97 | except ValueError as exc: |
| 98 | typer.echo(f"❌ Invalid track path: {exc}") |
| 99 | raise typer.Exit(code=ExitCode.USER_ERROR) |
| 100 | work_path.parent.mkdir(parents=True, exist_ok=True) |
| 101 | work_path.write_bytes(midi_bytes) |
| 102 | |
| 103 | typer.echo(f"\n✅ Retrograded {track}") |
| 104 | typer.echo(f" {len(retro)} notes reversed ({first_orig} → was last, now first)") |
| 105 | typer.echo(f" Duration preserved · original span: {span_beats:.2f} beats") |
| 106 | typer.echo(" Run `muse status` to review, then `muse commit`") |