Skip to content

Utility Functions

from amads.core.utils import *

dir_to_collection

dir_to_collection(filenames: list[str])

Converts a list of music filenames to a dictionary where keys are filenames and values are corresponding Score objects.

Parameters:

  • filenames (list(str)) –

    List of filenames to process.

Returns:

  • dict

    A dictionary mapping filenames to Score objects.

Source code in amads/core/utils.py
 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
def dir_to_collection(filenames: list[str]):
    """
    Converts a list of music filenames to a dictionary where keys
    are filenames and values are corresponding Score objects.

    Parameters
    ----------
    filenames : list(str)
        List of filenames to process.

    Returns
    -------
    dict
        A dictionary mapping filenames to Score objects.
    """
    scores = {}

    for file in filenames:
        if any(file.endswith(ext) for ext in valid_score_extensions):
            try:
                score = read_score(file)
                scores[file] = score
            except Exception as e:
                print(f"Error processing file {file}: {e}")
        else:
            print(f"Unsupported file format: {file}")

    return scores

hz_to_key_num

hz_to_key_num(
    hertz: Union[float, list[float]], do_round: bool = True
) -> Union[float, list[float]]

Converts a frequency in Hertz to the corresponding MIDI key number.

Parameters:

  • hertz (Union(float, list(float))) –

    The frequency or list of frequencies in Hertz.

  • do_round (bool, default: True ) –

    Perform rounding to the nearest integer key_num.

Returns:

  • Union(float, list(float))

    The corresponding MIDI key number(s).

Examples:

>>> hz_to_key_num(440.0)
69
>>> hz_to_key_num(260.0, False)
59.89209719404554
>>> hz_to_key_num([440, 260], True)
[69, 60]
Source code in amads/core/utils.py
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
def hz_to_key_num(
    hertz: Union[float, list[float]], do_round: bool = True
) -> Union[float, list[float]]:
    """
    Converts a frequency in Hertz to the corresponding MIDI key number.

    Parameters
    ----------
    hertz : Union(float, list(float))
        The frequency or list of frequencies in Hertz.

    do_round : bool
        Perform rounding to the nearest integer key_num.

    Returns
    -------
    Union(float, list(float))
        The corresponding MIDI key number(s).

    Examples
    --------
    >>> hz_to_key_num(440.0)
    69
    >>> hz_to_key_num(260.0, False)
    59.89209719404554
    >>> hz_to_key_num([440, 260], True)
    [69, 60]
    """

    if isinstance(hertz, list):
        return [_hz_to_key_num_single(hz, do_round) for hz in hertz]
    else:
        return _hz_to_key_num_single(hertz, do_round)

key_num_to_hz

key_num_to_hz(
    key_num: Union[float, Pitch, list[Union[float, Pitch]]],
) -> Union[float, list[float]]

Converts a Pitch object or MIDI key number to the corresponding frequency in Hertz.

Parameters:

  • key_num (Union(Pitch, float, list(Union(Pitch, float)))) –

    The Pitch object(s) or MIDI key number(s).

Returns:

  • Union(float, list(float))

    The corresponding frequency in Hertz.

Examples:

>>> key_num_to_hz(69)
440.0
>>> key_num_to_hz([Pitch("A5"), 60])
[880.0, 261.6255653005986]
Source code in amads/core/utils.py
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
def key_num_to_hz(
    key_num: Union[float, Pitch, list[Union[float, Pitch]]]
) -> Union[float, list[float]]:
    """
    Converts a Pitch object or MIDI key number to the corresponding
    frequency in Hertz.

    Parameters
    ----------
    key_num : Union(Pitch, float, list(Union(Pitch, float)))
        The Pitch object(s) or MIDI key number(s).

    Returns
    -------
    Union(float, list(float))
        The corresponding frequency in Hertz.

    Examples
    --------
    >>> key_num_to_hz(69)
    440.0
    >>> key_num_to_hz([Pitch("A5"), 60])
    [880.0, 261.6255653005986]
    """

    def key_num_to_hz_single(k):
        if isinstance(k, Pitch):
            key_num = k.key_num
        else:
            key_num = k
        return 440.0 * 2 ** ((key_num - 69) / 12)

    if isinstance(key_num, list):
        return [key_num_to_hz_single(k) for k in key_num]
    else:
        return key_num_to_hz_single(key_num)

key_num_to_name

key_num_to_name(n, detail='nameoctave')

Converts key numbers to key names (text).

Parameters:

  • n (Union(int, list(int))) –

    The key numbers.

  • detail (Optional(str), default: 'nameoctave' ) –

    'nameonly' for just the note name (e.g., 'C#'), 'nameoctave' for note name with octave (e.g., 'C#4') (default).

Returns:

  • Union(str, list(str))

    The corresponding key names.

Examples:

>>> key_num_to_name(61)
'C#4'
>>> key_num_to_name(61, detail="nameonly")
'C#'
Source code in amads/core/utils.py
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
def key_num_to_name(n, detail="nameoctave"):
    """
    Converts key numbers to key names (text).

    Parameters
    ----------
    n : Union(int, list(int))
        The key numbers.
    detail : Optional(str)
        `'nameonly'` for just the note name (e.g., `'C#'`),
        `'nameoctave'` for note name with octave (e.g., `'C#4'`) (default).

    Returns
    -------
    Union(str, list(str))
        The corresponding key names.

    Examples
    --------
    >>> key_num_to_name(61)
    'C#4'

    >>> key_num_to_name(61, detail="nameonly")
    'C#'
    """

    def key_num_to_name_single(k):
        pitch = Pitch(k)
        if detail == "nameonly":
            # Handles sharps, flats, and naturals correctly
            return pitch.name
        elif detail == "nameoctave":
            return pitch.name_with_octave  # Includes note name and octave
        else:
            raise ValueError(
                "Invalid detail option. Use 'nameonly' or " "'nameoctave'."
            )

    if isinstance(n, list):
        return [key_num_to_name_single(k) for k in n]
    else:
        return key_num_to_name_single(n)

sign

sign(x: float) -> int

Get the sign of a numeric value as -1, 0, or +1.

Returns:

  • int

    -1 if x < 0, 0 if x == 0, 1 if x > 0

Examples:

>>> sign(-15)
-1
>>> sign(-1)
-1
>>> sign(-0.5)
-1
>>> sign(-0)
0
>>> sign(+0)
0
>>> sign(+0.5)
1
>>> sign(15.2)
1
>>> sign(None) is None
True
Source code in amads/core/utils.py
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
def sign(x: float) -> int:
    """
    Get the sign of a numeric value as -1, 0, or +1.

    Returns
    ----------
    int
        -1 if `x` < 0, 0 if `x` == 0, 1 if `x` > 0

    Examples
    --------
    >>> sign(-15)
    -1

    >>> sign(-1)
    -1

    >>> sign(-0.5)
    -1

    >>> sign(-0)
    0

    >>> sign(+0)
    0

    >>> sign(+0.5)
    1

    >>> sign(15.2)
    1

    >>> sign(None) is None
    True
    """
    if x is None:
        return None  # type: ignore
    else:
        return bool(x > 0) - bool(x < 0)

float_range

float_range(
    start: float, end: Optional[float], step: float
) -> Iterator[float]

Generate a range of floats.

Similar to Python's built-in range() function but supports floating point numbers. If end is None, generates an infinite sequence.

Parameters:

  • start (float) –

    The starting value of the range

  • end (float or None) –

    The end value of the range (exclusive). If None, generates an infinite sequence

  • step (float) –

    The increment between values

Yields:

  • float

    The next value in the sequence

Source code in amads/core/utils.py
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
def float_range(
    start: float, end: Optional[float], step: float
) -> Iterator[float]:
    """Generate a range of floats.

    Similar to Python's built-in range() function but supports floating
    point numbers. If end is None, generates an infinite sequence.

    Parameters
    ----------
    start : float
        The starting value of the range
    end : float or None
        The end value of the range (exclusive). If None, generates an
        infinite sequence
    step : float
        The increment between values

    Yields
    ------
    float
        The next value in the sequence
    """
    curr = start
    while end is None or curr < end:
        yield curr
        curr += step