Skip to content

pitch

Diapason

Tuning reference.

Parameters:

Name Type Description Default
reference_midi_number int

The reference pitch MIDI number

69
reference_hertz float

The frequency of the reference pitch in Hertz

440.0
Source code in staff/pitch.py
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
@dataclass(frozen=True)
class Diapason:
    """Tuning reference.

    Args:
        reference_midi_number: The reference pitch MIDI number
        reference_hertz: The frequency of the reference pitch in Hertz
    """

    reference_midi_number: int = 69
    reference_hertz: float = 440.0

    def __post_init__(self):
        if (self.reference_midi_number < 0) or (self.reference_midi_number > 127):
            raise ValueError(f"invalid MIDI note number `{self.reference_midi_number}`")

        if self.reference_hertz <= 0:
            raise ValueError(f"invalid Hertz value `{self.reference_hertz}`")

Frequency

Frequency representation.

Parameters:

Name Type Description Default
hertz float

The frequency in Hertz (cycles-per-second)

required

Implements total_ordering against Frequency.

Implements the following operations:

- `__add__` against `Frequency`
- `__sub__` against `Frequency`
- `__mul__` against `int` and `float`
- `__rmul__` against `int` and `float`
- `__truediv__` against `int` and `float`
- `__floor_div__` against `int` and `float`
- `__round__`

Implements total ordering.

Examples:

Converting to a MIDIPitch:

>>> Frequency(hertz=440).to_midi()
MIDIPitch(number=69, bend=MIDIBend(bend=0, bend_range=200))
>>> Frequency(hertz=450).to_midi()
MIDIPitch(number=69, bend=MIDIBend(bend=1594, bend_range=200))

The distance between two Frequency instances (exponential) in Cents (linear):

>>> Frequency(880).cents_distance(Frequency(440))
Cents(cents=-1200.0)
>>> round(Frequency(440).cents_distance(Frequency(660)), 2)
Cents(cents=701.96)

Adding Cents (linear) to Frequency (exponential):

>>> Frequency(40).plus_cents(Cents(2400))
Frequency(hertz=160.0)
>>> round(Frequency(40).plus_cents(Cents(2401)), 2)
Frequency(hertz=160.09)

Frequency arithmetic is simple:

>>> Frequency(hertz=440) + Frequency(hertz=220)
Frequency(hertz=660)
>>> Frequency(hertz=660) - Frequency(hertz=220)
Frequency(hertz=440)
>>> Frequency(hertz=440) * 2
Frequency(hertz=880)
>>> Frequency(hertz=440) / 2
Frequency(hertz=220.0)
>>> round(Frequency(hertz=261.6255653005986), 2)
Frequency(hertz=261.63)

As is comparison:

>>> Frequency(220) > Frequency(110)
True
Source code in staff/pitch.py
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 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
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
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
146
147
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
@total_ordering
@dataclass(frozen=True)
class Frequency:
    """Frequency representation.

    Args:
        hertz: The frequency in Hertz (cycles-per-second)

    Implements `total_ordering` against `Frequency`.

    Implements the following operations:

        - `__add__` against `Frequency`
        - `__sub__` against `Frequency`
        - `__mul__` against `int` and `float`
        - `__rmul__` against `int` and `float`
        - `__truediv__` against `int` and `float`
        - `__floor_div__` against `int` and `float`
        - `__round__`

    Implements total ordering.

    Examples:
        Converting to a `MIDIPitch`:

        >>> Frequency(hertz=440).to_midi()
        MIDIPitch(number=69, bend=MIDIBend(bend=0, bend_range=200))

        >>> Frequency(hertz=450).to_midi()
        MIDIPitch(number=69, bend=MIDIBend(bend=1594, bend_range=200))

        The distance between two `Frequency` instances (exponential) in `Cents`
        (linear):

        >>> Frequency(880).cents_distance(Frequency(440))
        Cents(cents=-1200.0)

        >>> round(Frequency(440).cents_distance(Frequency(660)), 2)
        Cents(cents=701.96)

        Adding `Cents` (linear) to `Frequency` (exponential):

        >>> Frequency(40).plus_cents(Cents(2400))
        Frequency(hertz=160.0)

        >>> round(Frequency(40).plus_cents(Cents(2401)), 2)
        Frequency(hertz=160.09)

        `Frequency` arithmetic is simple:

        >>> Frequency(hertz=440) + Frequency(hertz=220)
        Frequency(hertz=660)

        >>> Frequency(hertz=660) - Frequency(hertz=220)
        Frequency(hertz=440)

        >>> Frequency(hertz=440) * 2
        Frequency(hertz=880)

        >>> Frequency(hertz=440) / 2
        Frequency(hertz=220.0)

        >>> round(Frequency(hertz=261.6255653005986), 2)
        Frequency(hertz=261.63)

        As is comparison:

        >>> Frequency(220) > Frequency(110)
        True
    """

    hertz: float

    def __post_init__(self):
        if self.hertz <= 0:
            raise ValueError(f"hertz must be greater than 0. Got {self.hertz}")

    def to_midi(
        self,
        midi_bend_range: int = 200,
        diapason: Diapason = Diapason(),
        octave_divs: int = 12,
    ) -> MIDIPitch:
        """Frequency to MIDIPitch conversion."""
        midi_float = (
            octave_divs * log2(self.hertz / diapason.reference_hertz)
            + diapason.reference_midi_number
        )
        try:
            bend = Cents(100 * divmod(midi_float, int(midi_float))[1]).to_midi_bend(
                bend_range=midi_bend_range
            )
        except ZeroDivisionError:
            # MIDI note 0
            bend = Cents(100 * midi_float).to_midi_bend(bend_range=midi_bend_range)
        return MIDIPitch(
            number=floor(midi_float),
            bend=bend,
            diapason=diapason,
            octave_divs=octave_divs,
        )

    def cents_distance(self, other: Frequency) -> Cents:
        """Cents distance between two frequencies."""
        if not isinstance(other, Frequency):
            raise TypeError("other must be an instance of Frequency.")
        return Cents((1200 * log2(other.hertz / self.hertz)))

    def plus_cents(self, cents: Cents) -> Frequency:
        """Frequency cents distance away."""
        if not isinstance(cents, Cents):
            raise TypeError("cents must be an instance of Cents.")
        return Frequency(hertz=self.hertz * 2 ** (cents.proportion_of_octave))

    def __gt__(self, other: Frequency) -> bool:
        if not isinstance(other, Frequency):
            raise TypeError(f"cannot compare Frequency with type '{type(other)}'")
        return self.hertz > other.hertz

    def _operate(
        self,
        other: Union[int, float],
        oper: Callable,
    ) -> Frequency:
        return Frequency(hertz=oper(self.hertz, other))

    def __add__(self, other: Frequency) -> Frequency:
        if not isinstance(other, Frequency):
            raise TypeError(
                f"unsupported operand type(s) for +: 'Frequency' and '{type(other)}'"
            )
        return Frequency(self.hertz + other.hertz)

    def __sub__(self, other: Frequency) -> Frequency:
        if not isinstance(other, Frequency):
            raise TypeError(
                f"unsupported operand type(s) for -: 'Frequency' and '{type(other)}'"
            )
        return Frequency(self.hertz - other.hertz)

    def __mul__(self, other: Union[int, float]) -> Frequency:
        return self._operate(other, operator.mul)

    def __rmul__(self, other: Union[int, float]) -> Frequency:
        return self._operate(other, operator.mul)

    def __truediv__(self, other: Union[int, float]) -> Frequency:
        return self._operate(other, operator.truediv)

    def __floordiv__(self, other: Union[int, float]) -> Frequency:
        return self._operate(other, operator.floordiv)

    def __round__(self, ndigits: int) -> Frequency:
        return Frequency(hertz=round(self.hertz, ndigits))

cents_distance(other)

Cents distance between two frequencies.

Source code in staff/pitch.py
134
135
136
137
138
def cents_distance(self, other: Frequency) -> Cents:
    """Cents distance between two frequencies."""
    if not isinstance(other, Frequency):
        raise TypeError("other must be an instance of Frequency.")
    return Cents((1200 * log2(other.hertz / self.hertz)))

plus_cents(cents)

Frequency cents distance away.

Source code in staff/pitch.py
140
141
142
143
144
def plus_cents(self, cents: Cents) -> Frequency:
    """Frequency cents distance away."""
    if not isinstance(cents, Cents):
        raise TypeError("cents must be an instance of Cents.")
    return Frequency(hertz=self.hertz * 2 ** (cents.proportion_of_octave))

to_midi(midi_bend_range=200, diapason=Diapason(), octave_divs=12)

Frequency to MIDIPitch conversion.

Source code in staff/pitch.py
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
def to_midi(
    self,
    midi_bend_range: int = 200,
    diapason: Diapason = Diapason(),
    octave_divs: int = 12,
) -> MIDIPitch:
    """Frequency to MIDIPitch conversion."""
    midi_float = (
        octave_divs * log2(self.hertz / diapason.reference_hertz)
        + diapason.reference_midi_number
    )
    try:
        bend = Cents(100 * divmod(midi_float, int(midi_float))[1]).to_midi_bend(
            bend_range=midi_bend_range
        )
    except ZeroDivisionError:
        # MIDI note 0
        bend = Cents(100 * midi_float).to_midi_bend(bend_range=midi_bend_range)
    return MIDIPitch(
        number=floor(midi_float),
        bend=bend,
        diapason=diapason,
        octave_divs=octave_divs,
    )

Cents

Cents representation.

Parameters:

Name Type Description Default
cents float

The cents value. There are 1200 cents per octave.

required

Implements the following operations:

- `__add__` against `Cents`
- `__sub__` against `Cents`
- `__mul__` against `int` and `float`
- `__rmul__` against `int` and `float`
- `__truediv__` against `int` and `float` (though the result is rounded
    to the **closest** int)
- `__floor_div__` against `int` and `float`

Implements total ordering.

Examples:

Cents as a proportion of the octave:

>>> Cents(600).proportion_of_octave
0.5

Cents can be converted to MIDIBend:

>>> Cents(1.96).to_midi_bend()
MIDIBend(bend=80, bend_range=200)
>>> Cents(-15.64).to_midi_bend()
MIDIBend(bend=-641, bend_range=200)

Cents arithmetic is simple:

>>> Cents(100) + Cents(500)
Cents(cents=600)
>>> Cents(600) - Cents(100)
Cents(cents=500)
>>> Cents(600) * 2
Cents(cents=1200)
>>> Cents(1200) / 2
Cents(cents=600)
>>> round(Cents(1.96), 0)
Cents(cents=2.0)

As is comparison:

>>> Cents(600) > Cents(100)
True
Source code in staff/pitch.py
188
189
190
191
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
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
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
@total_ordering
@dataclass(frozen=True)
class Cents:
    """Cents representation.

    Args:
        cents: The cents value. There are 1200 cents per octave.

    Implements the following operations:

        - `__add__` against `Cents`
        - `__sub__` against `Cents`
        - `__mul__` against `int` and `float`
        - `__rmul__` against `int` and `float`
        - `__truediv__` against `int` and `float` (though the result is rounded
            to the **closest** int)
        - `__floor_div__` against `int` and `float`

    Implements total ordering.

    Examples:
        `Cents` as a proportion of the octave:

        >>> Cents(600).proportion_of_octave
        0.5

        `Cents` can be converted to `MIDIBend`:

        >>> Cents(1.96).to_midi_bend()
        MIDIBend(bend=80, bend_range=200)

        >>> Cents(-15.64).to_midi_bend()
        MIDIBend(bend=-641, bend_range=200)

        `Cents` arithmetic is simple:

        >>> Cents(100) + Cents(500)
        Cents(cents=600)

        >>> Cents(600) - Cents(100)
        Cents(cents=500)

        >>> Cents(600) * 2
        Cents(cents=1200)

        >>> Cents(1200) / 2
        Cents(cents=600)

        >>> round(Cents(1.96), 0)
        Cents(cents=2.0)

        As is comparison:
        >>> Cents(600) > Cents(100)
        True
    """

    cents: float

    @property
    def proportion_of_octave(self) -> float:
        """Ratio of these cents against a standard 1200 cent octave.

        Returns:
            The proportion (ratio) of these cents against the 1200 cent octave
        """
        return self.cents / 1200.0

    def to_midi_bend(self, bend_range: int = 200) -> MIDIBend:
        """MIDI bend value required to achieve these cents.

        Args:
            bend_range: The set pitch-bend range

        Returns:
            The MIDIBend equivalent of these cents
        """
        return MIDIBend(
            bend=round((8192 / bend_range) * self.cents),
            bend_range=bend_range,
        )

    def __gt__(self, other: Cents) -> bool:
        if not isinstance(other, Cents):
            raise TypeError(f"cannot compare Cents with type '{type(other)}'")
        return self.cents > other.cents

    def _operate(
        self,
        other: Union[int, float],
        oper: Callable,
    ) -> Cents:
        if not isinstance(other, (int, float)):
            raise TypeError(
                f"unsupported operand type(s) for {oper.__name__}: "
                f"'Cents' and '{type(other)}'"
            )
        return Cents(cents=round(oper(self.cents, other)))

    def __add__(self, other: Cents) -> Cents:
        if not isinstance(other, Cents):
            raise TypeError(
                f"unsupported operand type(s) for +: 'Cents' and '{type(other)}'"
            )
        return Cents(self.cents + other.cents)

    def __sub__(self, other: Cents) -> Cents:
        if not isinstance(other, Cents):
            raise TypeError(
                f"unsupported operand type(s) for -: 'Cents' and '{type(other)}'"
            )
        return Cents(self.cents - other.cents)

    def __mul__(self, other: Union[int, float]) -> Cents:
        return self._operate(other, operator.mul)

    def __rmul__(self, other: Union[int, float]) -> Cents:
        return self._operate(other, operator.mul)

    def __truediv__(self, other: Union[int, float]) -> Cents:
        return self._operate(other, operator.truediv)

    def __floordiv__(self, other: Union[int, float]) -> Cents:
        return self._operate(other, operator.floordiv)

    def __round__(self, ndigits: Optional[int] = None) -> Cents:
        return Cents(cents=round(self.cents, ndigits))

proportion_of_octave: float property

Ratio of these cents against a standard 1200 cent octave.

Returns:

Type Description
float

The proportion (ratio) of these cents against the 1200 cent octave

to_midi_bend(bend_range=200)

MIDI bend value required to achieve these cents.

Parameters:

Name Type Description Default
bend_range int

The set pitch-bend range

200

Returns:

Type Description
MIDIBend

The MIDIBend equivalent of these cents

Source code in staff/pitch.py
255
256
257
258
259
260
261
262
263
264
265
266
267
def to_midi_bend(self, bend_range: int = 200) -> MIDIBend:
    """MIDI bend value required to achieve these cents.

    Args:
        bend_range: The set pitch-bend range

    Returns:
        The MIDIBend equivalent of these cents
    """
    return MIDIBend(
        bend=round((8192 / bend_range) * self.cents),
        bend_range=bend_range,
    )

MIDIPitch

MIDI pitch representation which includes pitch-bend.

Parameters:

Name Type Description Default
number int

MIDI note number.

required
bend MIDIBend

MIDI pitch-wheel bend.

MIDIBend(bend=0, bend_range=200)
diapason Diapason

Tuning reference.

Diapason()
octave_divs int

Equal divisions of the octave. Typically 12.

field(default=12, compare=False)

Implements total ordering.

Examples:

MIDIPitches can be initialized using a string:

>>> MIDIPitch.from_string("c4")
MIDIPitch(number=60, bend=MIDIBend(bend=0, bend_range=200))
>>> MIDIPitch.from_string("c#4")
MIDIPitch(number=61, bend=MIDIBend(bend=0, bend_range=200))
>>> MIDIPitch.from_string("db4")
MIDIPitch(number=61, bend=MIDIBend(bend=0, bend_range=200))

or a number:

>>> MIDIPitch(60)
MIDIPitch(number=60, bend=MIDIBend(bend=0, bend_range=200))

They can be converted to Frequency:

>>> round(MIDIPitch(60).frequency, 2)
Frequency(hertz=261.63)

A Diapason can be used to set tuning:

>>> diapason = Diapason(reference_midi_number=69, reference_hertz=438)
>>> pitch = MIDIPitch(60, diapason=diapason)
>>> round(pitch.frequency, 2)
Frequency(hertz=260.44)

Octave divisions other than 12 can be used, changing the MIDI note key mapping:

>>> round(MIDIPitch(60, octave_divs=24).frequency, 2)
Frequency(hertz=339.29)

Given a pitch that isn't twelve-tone equal-temperament, a MIDIBend will be applied (note that Frequency.to_midi returns a MIDIPitch):

>>> Frequency(100).to_midi().bend
MIDIBend(bend=1433, bend_range=200)

They can be compared:

>>> MIDIPitch.from_string("c#4") == MIDIPitch.from_string("db4")
True
Source code in staff/pitch.py
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
@total_ordering
@dataclass(frozen=True, repr=False)
class MIDIPitch:
    """MIDI pitch representation which includes pitch-bend.

    Args:
        number: MIDI note number.
        bend: MIDI pitch-wheel bend.
        diapason: Tuning reference.
        octave_divs: Equal divisions of the octave. Typically 12.

    Implements total ordering.

    Examples:
        `MIDIPitches` can be initialized using a string:

        >>> MIDIPitch.from_string("c4")
        MIDIPitch(number=60, bend=MIDIBend(bend=0, bend_range=200))

        >>> MIDIPitch.from_string("c#4")
        MIDIPitch(number=61, bend=MIDIBend(bend=0, bend_range=200))

        >>> MIDIPitch.from_string("db4")
        MIDIPitch(number=61, bend=MIDIBend(bend=0, bend_range=200))

        or a number:

        >>> MIDIPitch(60)
        MIDIPitch(number=60, bend=MIDIBend(bend=0, bend_range=200))

        They can be converted to `Frequency`:

        >>> round(MIDIPitch(60).frequency, 2)
        Frequency(hertz=261.63)

        A `Diapason` can be used to set tuning:

        >>> diapason = Diapason(reference_midi_number=69, reference_hertz=438)
        >>> pitch = MIDIPitch(60, diapason=diapason)
        >>> round(pitch.frequency, 2)
        Frequency(hertz=260.44)

        Octave divisions other than 12 can be used, changing the MIDI note key
        mapping:

        >>> round(MIDIPitch(60, octave_divs=24).frequency, 2)
        Frequency(hertz=339.29)

        Given a pitch that isn't twelve-tone equal-temperament, a `MIDIBend`
        will be applied (note that `Frequency.to_midi` returns a `MIDIPitch`):

        >>> Frequency(100).to_midi().bend
        MIDIBend(bend=1433, bend_range=200)

        They can be compared:

        >>> MIDIPitch.from_string("c#4") == MIDIPitch.from_string("db4")
        True
    """

    number: int
    bend: MIDIBend = MIDIBend(bend=0, bend_range=200)
    diapason: Diapason = Diapason()
    octave_divs: int = field(default=12, compare=False)

    def __post_init__(self):
        if (self.number < 0) or (self.number > 127):
            raise ValueError(f"number must be between 0 and 127. Got {self.number}")

    def __repr__(self):
        return f"MIDIPitch(number={self.number}, bend={self.bend})"

    def __hash__(self) -> int:
        return hash(self.number_precise)

    @property
    def number_precise(self) -> float:
        """The MIDI number with the bend as the fractional part of a float.

        Returns:
            The precise MIDI number including the bend.

        Examples:
            >>> MIDIPitch(60, bend=MIDIBend(100, bend_range=200)).number_precise
            60.5
        """
        return self.number + (self.bend.bend / self.bend.bend_range)

    @property
    def frequency(self) -> Frequency:
        """Convert MIDIPitch to Frequency.

        Returns:
            The MIDIPitch frequency
        """
        fhz = Frequency(
            2
            ** ((self.number - self.diapason.reference_midi_number) / self.octave_divs)
            * self.diapason.reference_hertz
        )
        if self.bend == MIDIBend(bend=0):
            return fhz
        cents = self.bend.cents
        return fhz.plus_cents(cents=cents)

    @property
    def pitch_class(self) -> int:
        """The approximate pitch class of the pitch.

        Note:
            This is more utility than function. It uses the integer MIDI number
            not the precise number that includes the pitch bend.

        Returns:
            The pitch class of the pitch.
        """
        return self.number % self.octave_divs

    @property
    def pitch_class_precise(self) -> MIDIPitch:
        """The lowest octave equivalent of the precise pitch.

        Note:
            This is recommended for microtonal pitches.

        Returns:
            The `MIDIPitch` which is the lowest octave equivalent.
        """
        lower_bound = MIDIPitch(0).frequency.hertz
        frequency = self.frequency.hertz
        candidate = frequency / 2.0
        if candidate < lower_bound:
            return Frequency(hertz=frequency).to_midi(
                midi_bend_range=self.bend.bend_range,
                diapason=self.diapason,
                octave_divs=self.octave_divs,
            )
        while candidate >= lower_bound:
            frequency = candidate
            candidate = frequency / 2.0
        return Frequency(hertz=frequency).to_midi(
            midi_bend_range=self.bend.bend_range,
            diapason=self.diapason,
            octave_divs=self.octave_divs,
        )

    @classmethod
    def from_string(cls, pitch: str, c4_number: int = 60) -> MIDIPitch:
        """Create a MIDIPitch from a string representations.

        Pitch strings are written as a combination of the pitch note class letter,
        a maximum of one accidental, and an integer representing the octave.
        Sharps are represented by the '#' symbols and flats by 'b'.

        Args:
            pitch: The pitch in string representation.
            c4_number: The MIDI number representing C4.

        Raises:
            ValueError: if an invalid pitch string is given.
        """
        if not isinstance(pitch, str):
            raise TypeError("pitch must be expressed as a 'str'")
        if not isinstance(c4_number, int):
            raise TypeError("c4_number must be expressed as a 'int'")

        pitches = [
            ["b#", "c"],
            ["c#", "db"],
            ["d"],
            ["d#", "eb"],
            ["e", "fb"],
            ["f", "e#"],
            ["f#", "gb"],
            ["g"],
            ["g#", "ab"],
            ["a"],
            ["a#", "bb"],
            ["b", "cb"],
        ]
        pitch = pitch.strip().lower()
        idx = 1
        while pitch[-idx].isnumeric():
            idx += 1
        idx -= 1
        if pitch[-(idx + 1)] == "-":
            idx += 1
        octave = int(pitch[-idx:])
        pitch_class = pitch[:-idx]
        found = False
        pc_number = 0
        for idx, enharmonics in enumerate(pitches):
            if pitch_class in enharmonics:
                pc_number = idx
                found = True
                break
        if not found:
            raise ValueError(f"invalid pitch string : {pitch}")
        if pitch_class == "b#":
            octave += 1
        elif pitch_class == "cb":
            octave -= 1
        return MIDIPitch((c4_number + pc_number) + (octave - 4) * 12)

    def octave_up(self) -> MIDIPitch:
        return Frequency(self.frequency.hertz * 2).to_midi(
            midi_bend_range=self.bend.bend_range,
            diapason=self.diapason,
            octave_divs=self.octave_divs,
        )

    def octave_down(self) -> MIDIPitch:
        return Frequency(self.frequency.hertz / 2).to_midi(
            midi_bend_range=self.bend.bend_range,
            diapason=self.diapason,
            octave_divs=self.octave_divs,
        )

    def __gt__(self, other: MIDIPitch) -> bool:
        if not isinstance(other, MIDIPitch):
            raise TypeError(f"cannot compare MIDIPitch with type '{type(other)}'")
        return self.frequency > other.frequency

frequency: Frequency property

Convert MIDIPitch to Frequency.

Returns:

Type Description
Frequency

The MIDIPitch frequency

number_precise: float property

The MIDI number with the bend as the fractional part of a float.

Returns:

Type Description
float

The precise MIDI number including the bend.

Examples:

>>> MIDIPitch(60, bend=MIDIBend(100, bend_range=200)).number_precise
60.5

pitch_class: int property

The approximate pitch class of the pitch.

Note

This is more utility than function. It uses the integer MIDI number not the precise number that includes the pitch bend.

Returns:

Type Description
int

The pitch class of the pitch.

pitch_class_precise: MIDIPitch property

The lowest octave equivalent of the precise pitch.

Note

This is recommended for microtonal pitches.

Returns:

Type Description
MIDIPitch

The MIDIPitch which is the lowest octave equivalent.

from_string(pitch, c4_number=60) classmethod

Create a MIDIPitch from a string representations.

Pitch strings are written as a combination of the pitch note class letter, a maximum of one accidental, and an integer representing the octave. Sharps are represented by the '#' symbols and flats by 'b'.

Parameters:

Name Type Description Default
pitch str

The pitch in string representation.

required
c4_number int

The MIDI number representing C4.

60

Raises:

Type Description
ValueError

if an invalid pitch string is given.

Source code in staff/pitch.py
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
@classmethod
def from_string(cls, pitch: str, c4_number: int = 60) -> MIDIPitch:
    """Create a MIDIPitch from a string representations.

    Pitch strings are written as a combination of the pitch note class letter,
    a maximum of one accidental, and an integer representing the octave.
    Sharps are represented by the '#' symbols and flats by 'b'.

    Args:
        pitch: The pitch in string representation.
        c4_number: The MIDI number representing C4.

    Raises:
        ValueError: if an invalid pitch string is given.
    """
    if not isinstance(pitch, str):
        raise TypeError("pitch must be expressed as a 'str'")
    if not isinstance(c4_number, int):
        raise TypeError("c4_number must be expressed as a 'int'")

    pitches = [
        ["b#", "c"],
        ["c#", "db"],
        ["d"],
        ["d#", "eb"],
        ["e", "fb"],
        ["f", "e#"],
        ["f#", "gb"],
        ["g"],
        ["g#", "ab"],
        ["a"],
        ["a#", "bb"],
        ["b", "cb"],
    ]
    pitch = pitch.strip().lower()
    idx = 1
    while pitch[-idx].isnumeric():
        idx += 1
    idx -= 1
    if pitch[-(idx + 1)] == "-":
        idx += 1
    octave = int(pitch[-idx:])
    pitch_class = pitch[:-idx]
    found = False
    pc_number = 0
    for idx, enharmonics in enumerate(pitches):
        if pitch_class in enharmonics:
            pc_number = idx
            found = True
            break
    if not found:
        raise ValueError(f"invalid pitch string : {pitch}")
    if pitch_class == "b#":
        octave += 1
    elif pitch_class == "cb":
        octave -= 1
    return MIDIPitch((c4_number + pc_number) + (octave - 4) * 12)

MIDIBend

MIDI bend value with bend wheel range.

Parameters:

Name Type Description Default
bend int

MIDI pitch bend value (in range -8192, 8192)

0
bend_range int

MIDI bend wheel range in cents. Typically 200 (2 semitones), but with some MPE instruments and controllers the bend range is set to 2400 (24 semitones).

200
Source code in staff/pitch.py
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
@dataclass(frozen=True)
class MIDIBend:
    """MIDI bend value with bend wheel range.

    Args:
        bend: MIDI pitch bend value (in range -8192, 8192)
        bend_range: MIDI bend wheel range in cents. Typically 200 (2 semitones),
            but with some MPE instruments and controllers the bend range is set
            to 2400 (24 semitones).
    """

    bend: int = 0
    bend_range: int = 200

    def __post_init__(self):
        if (self.bend < -8192) or (self.bend > 8192):
            raise ValueError(f"bend must be between -8192 and 8192. Got {self.bend}")

        if self.bend_range <= 0:
            raise ValueError(
                f"bend_range must be greater than 0. Got {self.bend_range}"
            )

    @property
    def cents(self) -> Cents:
        """Get this MIDI bend value as cents.

        Returns:
            The MIDIBend as cents
        """
        return Cents((self.bend / 8192) * self.bend_range)

cents: Cents property

Get this MIDI bend value as cents.

Returns:

Type Description
Cents

The MIDIBend as cents