Skip to content

Commit 3b93734

Browse files
authored
MIDI-175: Support empty MidiPiece trims (#13)
* Support empty trims * fix tests
1 parent 4111759 commit 3b93734

File tree

2 files changed

+14
-6
lines changed

2 files changed

+14
-6
lines changed

fortepyan/midi/structures.py

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -113,6 +113,12 @@ def time_shift(self, shift_s: float) -> "MidiPiece":
113113
new_piece.df.end += shift_s
114114
return new_piece
115115

116+
@classmethod
117+
def empty(cls) -> "MidiPiece":
118+
df = pd.DataFrame(columns=["start", "duration", "velocity", "pitch"])
119+
piece = cls(df=df)
120+
return piece
121+
116122
def trim(
117123
self,
118124
start: float,
@@ -122,7 +128,7 @@ def trim(
122128

123129
idx = np.where(ids)[0]
124130
if len(idx) == 0:
125-
raise IndexError("No notes found in the specified range.")
131+
return MidiPiece.empty()
126132

127133
start_idx = idx[0]
128134
finish_idx = idx[-1] + 1

tests/midi/test_structures.py

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -87,14 +87,16 @@ def test_midi_piece_duration_calculation(sample_df):
8787

8888

8989
def test_trim_out_of_bounds(sample_midi_piece):
90-
with pytest.raises(IndexError):
91-
_ = sample_midi_piece.trim(5.5, 8) # Out of bounds, should raise an error
90+
# Out of bounds, should return empty piece
91+
piece = sample_midi_piece.trim(5.5, 8)
92+
assert piece.df.empty
9293

9394

9495
def test_trim_with_invalid_range(sample_midi_piece):
95-
# Assuming the behavior is to raise an error with invalid range
96-
with pytest.raises(IndexError):
97-
_ = sample_midi_piece.trim(4, 2) # Invalid range, start is greater than finish
96+
# Invalid range, start is greater than finish
97+
# Should return empty piece
98+
piece = sample_midi_piece.trim(4, 2)
99+
assert piece.df.empty
98100

99101

100102
def test_to_midi(sample_midi_piece):

0 commit comments

Comments
 (0)