gabriel / muse public
retrograde.py python
107 lines 4.1 KB
Raw
sha256:61100cca63d948098d334e1b600d8fea514568a1c26ef357bf8b6380fbd8a217 chore(timeline): remove unused RationalRate import in entity.py Human minor ⚠ breaking 8 days ago
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 import argparse
21 import logging
22 import pathlib
23 import sys
24
25 from muse.core.errors import ExitCode
26 from muse.core.validation import contain_path
27 from muse.core.repo import require_repo
28 from muse.plugins.midi._query import NoteInfo, load_track_from_workdir, notes_to_midi_bytes
29 from muse.plugins.midi.midi_diff import _pitch_name
30
31 logger = logging.getLogger(__name__)
32
33 def register(subparsers: "argparse._SubParsersAction[argparse.ArgumentParser]") -> None:
34 """Register the retrograde subcommand."""
35 parser = subparsers.add_parser("retrograde", help="Reverse the pitch order of all notes (retrograde transformation).", description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
36 parser.add_argument("track", metavar="TRACK", help="Workspace-relative path to a .mid file.")
37 parser.add_argument("--dry-run", "-n", action="store_true", help="Preview without writing.")
38 parser.set_defaults(func=run)
39
40 def run(args: argparse.Namespace) -> None:
41 """Reverse the pitch order of all notes (retrograde transformation).
42
43 ``muse retrograde`` maps note positions: the note that was at tick T from
44 the end is placed at tick T from the start, so the last note plays first.
45 Durations and velocities are preserved; only pitch and position are swapped.
46
47 This is a foundational operation in serial/twelve-tone composition and is
48 impossible to describe meaningfully in Git's binary-blob model.
49 """
50 track: str = args.track
51 dry_run: bool = args.dry_run
52
53 root = require_repo()
54 result = load_track_from_workdir(root, track)
55 if result is None:
56 print(f"❌ Track '{track}' not found or not a valid MIDI file.", file=sys.stderr)
57 raise SystemExit(ExitCode.USER_ERROR)
58
59 notes, tpb = result
60 if not notes:
61 print(f" (track '{track}' contains no notes — nothing to retrograde)")
62 return
63
64 # Sort by start time to get the temporal order, then reverse pitches.
65 by_time = sorted(notes, key=lambda n: n.start_tick)
66 reversed_pitches = [n.pitch for n in reversed(by_time)]
67
68 total_ticks = max(n.start_tick + n.duration_ticks for n in notes)
69 retro: list[NoteInfo] = [
70 NoteInfo(
71 pitch=reversed_pitches[i],
72 velocity=by_time[i].velocity,
73 start_tick=by_time[i].start_tick,
74 duration_ticks=by_time[i].duration_ticks,
75 channel=by_time[i].channel,
76 ticks_per_beat=by_time[i].ticks_per_beat,
77 )
78 for i in range(len(by_time))
79 ]
80
81 span_beats = total_ticks / max(tpb, 1)
82 first_orig = _pitch_name(by_time[0].pitch)
83 first_retro = _pitch_name(retro[0].pitch)
84
85 if dry_run:
86 print(f"\n[dry-run] Would retrograde {track}")
87 print(f" Notes: {len(notes)}")
88 print(f" Was: first note = {first_orig}")
89 print(f" Would: first note = {first_retro}")
90 print(f" Span: {span_beats:.2f} beats (unchanged)")
91 print(" No changes written (--dry-run).")
92 return
93
94 midi_bytes = notes_to_midi_bytes(retro, tpb)
95 workdir = root
96 try:
97 work_path = contain_path(workdir, track)
98 except ValueError as exc:
99 print(f"❌ Invalid track path: {exc}")
100 raise SystemExit(ExitCode.USER_ERROR)
101 work_path.parent.mkdir(parents=True, exist_ok=True)
102 work_path.write_bytes(midi_bytes)
103
104 print(f"\n✅ Retrograded {track}")
105 print(f" {len(retro)} notes reversed ({first_orig} → was last, now first)")
106 print(f" Duration preserved · original span: {span_beats:.2f} beats")
107 print(" Run `muse status` to review, then `muse commit`")
File History 1 commit
sha256:61100cca63d948098d334e1b600d8fea514568a1c26ef357bf8b6380fbd8a217 chore(timeline): remove unused RationalRate import in entity.py Human minor 8 days ago