Skip to content

sorting_lists

Utilities for standardizing, extracting, and ordering pitch and interval strings. These are used internally throughout main_objs.py to keep note names and ngram tuples in a consistent, sortable form.

sort_pitch_values sorts against a reference ordering passed as its order parameter. The module defines these options:

  • pitch_order (default): full chromatic gamut across octaves 2-6, e.g. 'C2', 'C#2', 'D-2', ... 'C6'.
  • recta_order: the same range restricted to musica recta pitches, omitting a handful of chromatic alterations found in pitch_order (e.g. 'C2', 'G-2', 'A#2').
  • pitch_class_order: pitch classes without octave, plus 'Rest', e.g. 'C', 'C#', 'D-', ... 'B#', 'Rest'.
  • pitch_class_order_no_rests: pitch_class_order with 'Rest' removed.
  • pitch_class_order_with_rests: alias for pitch_class_order, kept for symmetry with pitch_class_order_no_rests.

standardize_note

standardize_note(note)
Source code in crim_intervals/sorting_lists.py
150
151
152
153
154
155
def standardize_note(note):
    if pd.isna(note):
        return note
    if '-' in str(note):
        return str(note).replace('-', 'b')
    return str(note)

extract_letter

extract_letter(value, include_rests=True)

Extract pitch class from a note string.

Returns 'Rest' for rest tokens (if include_rests=True), None for rest tokens (if include_rests=False), or the pitch class letter+accidental for pitched notes.

Source code in crim_intervals/sorting_lists.py
158
159
160
161
162
163
164
165
166
167
168
169
170
171
def extract_letter(value, include_rests=True):
    """Extract pitch class from a note string.

    Returns 'Rest' for rest tokens (if include_rests=True),
    None for rest tokens (if include_rests=False),
    or the pitch class letter+accidental for pitched notes.
    """
    if pd.isna(value):
        return None
    s = str(value).strip()
    if s.lower() in REST_TOKENS:
        return 'Rest' if include_rests else None
    # Strip octave digit(s) from end to get pitch class
    return s.rstrip('0123456789')

tuple_to_list

tuple_to_list(value, separator=None, cast=None)

Convert tuple-like values to a Python list.

cast, if given, is applied to each element (e.g. cast=int to parse a string of the form "1, -2, 1, -2" into [1, -2, 1, -2]).

Source code in crim_intervals/sorting_lists.py
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
def tuple_to_list(value, separator=None, cast=None):
    """Convert tuple-like values to a Python list.

    `cast`, if given, is applied to each element (e.g. `cast=int` to parse a
    string of the form "1, -2, 1, -2" into `[1, -2, 1, -2]`).
    """
    if value is None:
        return []
    if isinstance(value, pd.Series):
        value = value.tolist()
    if isinstance(value, (list, tuple, set)):
        result = [item for item in value]
    elif isinstance(value, str):
        if separator is None:
            stripped = value.strip()
            if stripped.startswith('(') and stripped.endswith(')'):
                stripped = stripped[1:-1]
            if not stripped:
                return []
            result = [item.strip() for item in stripped.split(',') if item.strip()]
        else:
            result = [item.strip() for item in value.split(separator) if item.strip()]
    else:
        result = [value]
    if cast is not None:
        result = [cast(item) for item in result]
    return result

tuple_to_string

tuple_to_string(value, separator=', ')

Convert tuple-like values to a delimited string.

Source code in crim_intervals/sorting_lists.py
203
204
205
206
207
208
209
210
211
212
213
def tuple_to_string(value, separator=', '):
    """Convert tuple-like values to a delimited string."""
    if value is None:
        return ''
    if isinstance(value, pd.Series):
        value = value.tolist()
    if isinstance(value, str):
        return value
    if isinstance(value, (list, tuple, set)):
        return separator.join(str(item) for item in value)
    return str(value)

sort_pitch_values

sort_pitch_values(values, order=None, include_rests=True)

Return a list of pitch values sorted according to a supplied order.

Parameters:

Name Type Description Default
values list, tuple, set, pandas.Series, or scalar

The pitch values to sort.

required
order list

The reference ordering to sort values against. Defaults to pitch_order if not passed. Available options defined in this module:

  • pitch_order (default): full chromatic gamut across octaves 2-6, e.g. 'C2', 'C#2', 'D-2', ... 'C6'.
  • recta_order: the same range restricted to musica recta pitches, omitting a handful of chromatic alterations found in pitch_order (e.g. 'C2', 'G-2', 'A#2').
  • pitch_class_order: pitch classes without octave, plus 'Rest', e.g. 'C', 'C#', 'D-', ... 'B#', 'Rest'.
  • pitch_class_order_no_rests: pitch_class_order with 'Rest' removed.
  • pitch_class_order_with_rests: alias for pitch_class_order, kept for symmetry with pitch_class_order_no_rests.
None
include_rests bool, optional (default True)

Whether rest tokens ('Rest', 'r', '-', etc.) sort in place (True) or are pushed after all pitched values (False).

True

Returns:

Type Description
list

values sorted according to order, with NaNs dropped.

Source code in crim_intervals/sorting_lists.py
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
def sort_pitch_values(values, order=None, include_rests=True):
    """
    Return a list of pitch values sorted according to a supplied order.

    Parameters
    ----------
    values : list, tuple, set, pandas.Series, or scalar
        The pitch values to sort.
    order : list, optional
        The reference ordering to sort `values` against. Defaults to
        `pitch_order` if not passed. Available options defined in this
        module:

        - `pitch_order` (default): full chromatic gamut across octaves 2-6,
          e.g. 'C2', 'C#2', 'D-2', ... 'C6'.
        - `recta_order`: the same range restricted to musica recta pitches,
          omitting a handful of chromatic alterations found in `pitch_order`
          (e.g. 'C2', 'G-2', 'A#2').
        - `pitch_class_order`: pitch classes without octave, plus 'Rest',
          e.g. 'C', 'C#', 'D-', ... 'B#', 'Rest'.
        - `pitch_class_order_no_rests`: `pitch_class_order` with 'Rest'
          removed.
        - `pitch_class_order_with_rests`: alias for `pitch_class_order`,
          kept for symmetry with `pitch_class_order_no_rests`.
    include_rests : bool, optional (default True)
        Whether rest tokens ('Rest', 'r', '-', etc.) sort in place (True) or
        are pushed after all pitched values (False).

    Returns
    -------
    list
        `values` sorted according to `order`, with NaNs dropped.
    """
    if values is None:
        return []
    if isinstance(values, (pd.Series, pd.Index, np.ndarray)):
        values = list(values)
    elif isinstance(values, str):
        values = [values]
    elif not isinstance(values, (list, tuple, set)):
        values = [values]

    if order is None:
        order = pitch_order
    order_lookup = {item: index for index, item in enumerate(order)}

    def _sort_key(value):
        if pd.isna(value):
            return (1, len(order_lookup), '')
        text = str(value).strip()
        if not text:
            return (1, len(order_lookup), '')
        if text.lower() in {'r', 'rest', '-', ''}:
            if include_rests:
                return (0, order_lookup.get('Rest', len(order_lookup)), 'Rest')
            return (1, len(order_lookup), 'Rest')
        if text in order_lookup:
            return (0, order_lookup[text], text)
        if text.replace('-', 'b') in order_lookup:
            return (0, order_lookup[text.replace('-', 'b')], text)
        return (1, len(order_lookup), text)

    return [value for value in sorted(values, key=_sort_key) if not pd.isna(value)]