API Reference
Here you can find the API reference for the kernpy
package. The reference contains a detailed description of the kernpy
API. The reference describes how the methods work and which parameters can be used.
Find the basics of the kernpy
package in the Tutorial.
kernpy
=====
Python Humdrum kern and mens utilities package.
Execute the following command to run kernpy as a module:
python -m kernpy --help
python -m kernpy <command> <options>
Intervals = {-2: 'dd1', -1: 'd1', 0: 'P1', 1: 'A1', 2: 'AA1', 3: 'dd2', 4: 'd2', 5: 'm2', 6: 'M2', 7: 'A2', 8: 'AA2', 9: 'dd3', 10: 'd3', 11: 'm3', 12: 'M3', 13: 'A3', 14: 'AA3', 15: 'dd4', 16: 'd4', 17: 'P4', 18: 'A4', 19: 'AA4', 21: 'dd5', 22: 'd5', 23: 'P5', 24: 'A5', 25: 'AA5', 26: 'dd6', 27: 'd6', 28: 'm6', 29: 'M6', 30: 'A6', 31: 'AA6', 32: 'dd7', 33: 'd7', 34: 'm7', 35: 'M7', 36: 'A7', 37: 'AA7', 40: 'octave'}
module-attribute
Base-40 interval classes (d=diminished, m=minor, M=major, P=perfect, A=augmented)
AbstractToken
Bases: ABC
An abstract base class representing a token.
This class serves as a blueprint for creating various types of tokens, which are categorized based on their TokenCategory.
Attributes:
Name | Type | Description |
---|---|---|
encoding |
str
|
The original representation of the token. |
category |
TokenCategory
|
The category of the token. |
hidden |
bool
|
A flag indicating whether the token is hidden. Defaults to False. |
Source code in kernpy/core/tokens.py
1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 |
|
__eq__(other)
Compare two tokens.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
other |
AbstractToken
|
The other token to compare. |
required |
Returns (bool): True if the tokens are equal, False otherwise.
Source code in kernpy/core/tokens.py
1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 |
|
__hash__()
Returns the hash of the token.
Returns (int): The hash of the token.
Source code in kernpy/core/tokens.py
1462 1463 1464 1465 1466 1467 1468 |
|
__init__(encoding, category)
AbstractToken constructor
Parameters:
Name | Type | Description | Default |
---|---|---|---|
encoding |
str
|
The original representation of the token. |
required |
category |
TokenCategory
|
The category of the token. |
required |
Source code in kernpy/core/tokens.py
1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 |
|
__ne__(other)
Compare two tokens.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
other |
AbstractToken
|
The other token to compare. |
required |
Returns (bool): True if the tokens are different, False otherwise.
Source code in kernpy/core/tokens.py
1452 1453 1454 1455 1456 1457 1458 1459 1460 |
|
__str__()
Returns the string representation of the token.
Returns (str): The string representation of the token without processing.
Source code in kernpy/core/tokens.py
1432 1433 1434 1435 1436 1437 1438 |
|
export(**kwargs)
abstractmethod
Exports the token.
Other Parameters:
Name | Type | Description |
---|---|---|
filter_categories |
Optional[Callable[[TokenCategory], bool]]
|
A function that takes a TokenCategory and returns a boolean indicating whether the token should be included in the export. If provided, only tokens for which the function returns True will be exported. Defaults to None. If None, all tokens will be exported. |
Returns:
Name | Type | Description |
---|---|---|
str |
str
|
The encoded token representation, potentially filtered if a filter_categories function is provided. |
Examples:
>>> token = AbstractToken('*clefF4', TokenCategory.SIGNATURES)
>>> token.export()
'*clefF4'
>>> token.export(filter_categories=lambda cat: cat in {TokenCategory.SIGNATURES, TokenCategory.SIGNATURES.DURATION})
'*clefF4'
Source code in kernpy/core/tokens.py
1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 |
|
AgnosticPitch
Represents a pitch in a generic way, independent of the notation system used.
Source code in kernpy/core/pitch_models.py
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 |
|
__init__(name, octave)
Initialize the AgnosticPitch object.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
name |
str
|
The name of the pitch (e.g., 'C', 'D#', 'Bb'). |
required |
octave |
int
|
The octave of the pitch (e.g., 4 for middle C). |
required |
Source code in kernpy/core/pitch_models.py
85 86 87 88 89 90 91 92 93 94 |
|
BasicSpineImporter
Bases: SpineImporter
Source code in kernpy/core/basic_spine_importer.py
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 36 37 38 39 40 41 42 43 44 45 46 |
|
__init__(verbose=False)
KernSpineImporter constructor.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
verbose |
Optional[bool]
|
Level of verbosity for error messages. |
False
|
Source code in kernpy/core/basic_spine_importer.py
12 13 14 15 16 17 18 19 |
|
BekernTokenizer
Bases: Tokenizer
BekernTokenizer converts a Token into a bekern (Basic Extended **kern) string representation. This format use a '@' separator for the main tokens but discards all the decorations tokens.
Source code in kernpy/core/tokenizers.py
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 |
|
__init__(*, token_categories)
Create a new BekernTokenizer
Parameters:
Name | Type | Description | Default |
---|---|---|---|
token_categories |
Set[TokenCategory]
|
List of categories to be tokenized. If None will raise an exception. |
required |
Source code in kernpy/core/tokenizers.py
153 154 155 156 157 158 159 160 |
|
tokenize(token)
Tokenize a token into a bekern string representation. Args: token (Token): Token to be tokenized.
Returns (str): bekern string representation.
Examples:
>>> token.encoding
'2@.@bb@-·_·L'
>>> BekernTokenizer().tokenize(token)
'2@.@bb@-'
Source code in kernpy/core/tokenizers.py
162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 |
|
BkernTokenizer
Bases: Tokenizer
BkernTokenizer converts a Token into a bkern (Basic kern) string representation. This format use the main tokens but not the decorations tokens. This format is a lightweight version of the classic Humdrum kern format.
Source code in kernpy/core/tokenizers.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 |
|
__init__(*, token_categories)
Create a new BkernTokenizer
Parameters:
Name | Type | Description | Default |
---|---|---|---|
token_categories |
Set[TokenCategory]
|
List of categories to be tokenized. If None will raise an exception. |
required |
Source code in kernpy/core/tokenizers.py
195 196 197 198 199 200 201 202 |
|
tokenize(token)
Tokenize a token into a bkern string representation. Args: token (Token): Token to be tokenized.
Returns (str): bkern string representation.
Examples:
>>> token.encoding
'2@.@bb@-·_·L'
>>> BkernTokenizer().tokenize(token)
'2.bb-'
Source code in kernpy/core/tokenizers.py
205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 |
|
C1Clef
Bases: Clef
Source code in kernpy/core/gkern.py
391 392 393 394 395 396 397 398 399 400 401 402 |
|
__init__()
Initializes the C Clef object.
Source code in kernpy/core/gkern.py
392 393 394 395 396 |
|
bottom_line()
Returns the pitch of the bottom line of the staff.
Source code in kernpy/core/gkern.py
398 399 400 401 402 |
|
C2Clef
Bases: Clef
Source code in kernpy/core/gkern.py
404 405 406 407 408 409 410 411 412 413 414 415 |
|
__init__()
Initializes the C Clef object.
Source code in kernpy/core/gkern.py
405 406 407 408 409 |
|
bottom_line()
Returns the pitch of the bottom line of the staff.
Source code in kernpy/core/gkern.py
411 412 413 414 415 |
|
C3Clef
Bases: Clef
Source code in kernpy/core/gkern.py
418 419 420 421 422 423 424 425 426 427 428 429 |
|
__init__()
Initializes the C Clef object.
Source code in kernpy/core/gkern.py
419 420 421 422 423 |
|
bottom_line()
Returns the pitch of the bottom line of the staff.
Source code in kernpy/core/gkern.py
425 426 427 428 429 |
|
C4Clef
Bases: Clef
Source code in kernpy/core/gkern.py
431 432 433 434 435 436 437 438 439 440 441 442 |
|
__init__()
Initializes the C Clef object.
Source code in kernpy/core/gkern.py
432 433 434 435 436 |
|
bottom_line()
Returns the pitch of the bottom line of the staff.
Source code in kernpy/core/gkern.py
438 439 440 441 442 |
|
Clef
Bases: ABC
Abstract class representing a clef.
Source code in kernpy/core/gkern.py
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 314 315 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 347 348 349 |
|
__init__(diatonic_pitch, on_line)
Initializes the Clef object. Args: diatonic_pitch (DiatonicPitch): The diatonic pitch of the clef (e.g., 'C', 'G', 'F'). This value is used as a decorator. on_line (int): The line number on which the clef is placed (1 for bottom line, 2 for 1st line from bottom, etc.). This value is used as a decorator.
Source code in kernpy/core/gkern.py
290 291 292 293 294 295 296 297 298 |
|
__str__()
Returns:
Name | Type | Description |
---|---|---|
str |
str
|
The string representation of the clef. |
Source code in kernpy/core/gkern.py
319 320 321 322 323 324 |
|
bottom_line()
abstractmethod
Returns the pitch of the bottom line of the staff.
Source code in kernpy/core/gkern.py
300 301 302 303 304 305 |
|
name()
Returns the name of the clef.
Source code in kernpy/core/gkern.py
307 308 309 310 311 |
|
reference_point()
Returns the reference point for the clef.
Source code in kernpy/core/gkern.py
313 314 315 316 317 |
|
ClefFactory
Source code in kernpy/core/gkern.py
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 |
|
create_clef(encoding)
classmethod
Creates a Clef object based on the given token.
Clefs are encoded in interpretation tokens that start with a single * followed by the string clef and then the shape and line position of the clef. For example, a treble clef is clefG2, with G meaning a G-clef, and 2 meaning that the clef is centered on the second line up from the bottom of the staff. The bass clef is clefF4 since it is an F-clef on the fourth line of the staff. A vocal tenor clef is represented by clefGv2, where the v means the music should be played an octave lower than the regular clef’s sounding pitches. Try creating a vocal tenor clef in the above interactive example. The v operator also works on the other clefs (but these sorts of clefs are very rare). Another rare clef is clefG^2 which is the opposite of *clefGv2, where the music is written an octave lower than actually sounding pitch for the normal form of the clef. You can also try to create exotic two-octave clefs by doubling the ^^ and vv markers.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
encoding |
str
|
The encoding of the clef token. |
required |
Returns:
Source code in kernpy/core/gkern.py
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 |
|
ComplexToken
Bases: Token
, ABC
Abstract ComplexToken class. This abstract class ensures that the subclasses implement the export method using the 'filter_categories' parameter to filter the subtokens.
Passing the argument 'filter_categories' by **kwargs don't break the compatibility with parent classes.
Here we're trying to get the Liskov substitution principle done...
Source code in kernpy/core/tokens.py
1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 |
|
__init__(encoding, category)
Constructor for the ComplexToken
Parameters:
Name | Type | Description | Default |
---|---|---|---|
encoding |
str
|
The original representation of the token. |
required |
category |
TokenCategory)
|
The category of the token. |
required |
Source code in kernpy/core/tokens.py
1717 1718 1719 1720 1721 1722 1723 1724 1725 |
|
export(**kwargs)
abstractmethod
Exports the token.
Other Parameters:
Name | Type | Description |
---|---|---|
filter_categories |
Optional[Callable[[TokenCategory], bool]]
|
A function that takes a TokenCategory and returns a boolean indicating whether the token should be included in the export. If provided, only tokens for which the function returns True will be exported. Defaults to None. If None, all tokens will be exported. |
Returns (str): The exported token.
Source code in kernpy/core/tokens.py
1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 |
|
CompoundToken
Bases: ComplexToken
Source code in kernpy/core/tokens.py
1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 |
|
__init__(encoding, category, subtokens)
Parameters:
Name | Type | Description | Default |
---|---|---|---|
encoding |
str
|
The complete unprocessed encoding |
required |
category |
TokenCategory
|
The token category, one of 'TokenCategory' |
required |
subtokens |
List[Subtoken]
|
The individual elements of the token. Also of type 'TokenCategory' but in the hierarchy they must be children of the current token. |
required |
Source code in kernpy/core/tokens.py
1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 |
|
export(**kwargs)
Exports the token.
Other Parameters:
Name | Type | Description |
---|---|---|
filter_categories |
Optional[Callable[[TokenCategory], bool]]
|
A function that takes a TokenCategory and returns a boolean indicating whether the token should be included in the export. If provided, only tokens for which the function returns True will be exported. Defaults to None. If None, all tokens will be exported. |
Returns (str): The exported token.
Source code in kernpy/core/tokens.py
1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 |
|
Document
Document class.
This class store the score content using an agnostic tree structure.
Attributes:
Name | Type | Description |
---|---|---|
tree |
MultistageTree
|
The tree structure of the document where all the nodes are stored. Each stage of the tree corresponds to a row in the Humdrum **kern file encoding. |
measure_start_tree_stages |
List[List[Node]]
|
The list of nodes that corresponds to the measures. Empty list by default. The index of the list is starting from 1. Rows after removing empty lines and line comments |
page_bounding_boxes |
Dict[int, BoundingBoxMeasures]
|
The dictionary of page bounding boxes. - key: page number - value: BoundingBoxMeasures object |
header_stage |
int
|
The index of the stage that contains the headers. None by default. |
Source code in kernpy/core/document.py
338 339 340 341 342 343 344 345 346 347 348 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 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 |
|
__init__(tree)
Constructor for Document class.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
tree |
MultistageTree
|
The tree structure of the document where all the nodes are stored. |
required |
Source code in kernpy/core/document.py
356 357 358 359 360 361 362 363 364 365 366 |
|
__iter__()
Get the indexes to export all the document.
Returns: An iterator with the indexes to export the document.
Source code in kernpy/core/document.py
882 883 884 885 886 887 888 |
|
__next__()
Get the next index to export the document.
Returns: The next index to export the document.
Source code in kernpy/core/document.py
890 891 892 893 894 895 896 |
|
add(other, *, check_core_spines_only=False)
Concatenate one document to the current document: Modify the current object!
Parameters:
Name | Type | Description | Default |
---|---|---|---|
other |
'Document'
|
The document to concatenate. |
required |
check_core_spines_only |
Optional[bool]
|
If True, only the core spines (kern and mens) are checked. If False, all spines are checked. |
False
|
Returns ('Document'): The current document (self) with the other document concatenated.
Source code in kernpy/core/document.py
638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 |
|
append_spines(spines)
Append the spines directly to current document tree.
Args:
spines(list): A list of spines to append.
Returns: None
Examples:
>>> import kernpy as kp
>>> doc, _ = kp.read('score.krn')
>>> spines = [
>>> '4e 4f 4g 4a
4b 4c 4d 4e = = = = ', >>> '4c 4d 4e 4f 4g 4a 4b 4c = = = = ', >>> ] >>> doc.append_spines(spines) None
Source code in kernpy/core/document.py
612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 |
|
clone()
Create a deep copy of the Document instance.
Returns: A new instance of Document with the tree copied.
Source code in kernpy/core/document.py
598 599 600 601 602 603 604 605 606 607 608 609 610 |
|
frequencies(token_categories=None)
Frequency of tokens in the document.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
token_categories |
Optional[Sequence[TokenCategory]]
|
If None, all tokens are considered. |
None
|
Returns (Dict): A dictionary with the category and the number of occurrences of each token.
Source code in kernpy/core/document.py
701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 |
|
get_all_tokens(filter_by_categories=None)
Parameters:
Name | Type | Description | Default |
---|---|---|---|
filter_by_categories |
Optional[Sequence[TokenCategory]]
|
A list of categories to filter the tokens. If None, all tokens are returned. |
None
|
Returns:
Type | Description |
---|---|
List[AbstractToken]
|
List[AbstractToken] - A list of all tokens. |
Examples:
>>> tokens = document.get_all_tokens()
>>> Document.tokens_to_encodings(tokens)
>>> [type(t) for t in tokens]
[<class 'kernpy.core.token.Token'>, <class 'kernpy.core.token.Token'>, <class 'kernpy.core.token.Token'>]
Source code in kernpy/core/document.py
500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 |
|
get_all_tokens_encodings(filter_by_categories=None)
Parameters:
Name | Type | Description | Default |
---|---|---|---|
filter_by_categories |
Optional[Sequence[TokenCategory]]
|
A list of categories to filter the tokens. If None, all tokens are returned. |
None
|
Returns:
Type | Description |
---|---|
List[str]
|
list[str] - A list of all token encodings. |
Examples:
>>> tokens = document.get_all_tokens_encodings()
>>> Document.tokens_to_encodings(tokens)
['!!!COM: Coltrane', '!!!voices: 1', '!!!OPR: Blue Train']
Source code in kernpy/core/document.py
519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 |
|
get_first_measure()
Get the index of the first measure of the document.
Returns: (Int) The index of the first measure of the document.
Raises: Exception - If the document has no measures.
Examples:
>>> import kernpy as kp
>>> document, err = kp.read('score.krn')
>>> document.get_first_measure()
1
Source code in kernpy/core/document.py
399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 |
|
get_header_nodes()
Get the header nodes of the current document.
Returns: List[HeaderToken]: A list with the header nodes of the current document.
Source code in kernpy/core/document.py
680 681 682 683 684 685 686 |
|
get_header_stage()
Get the Node list of the header stage.
Returns: (Union[List[Node], List[List[Node]]]) The Node list of the header stage.
Raises: Exception - If the document has no header stage.
Source code in kernpy/core/document.py
370 371 372 373 374 375 376 377 378 379 380 381 |
|
get_leaves()
Get the leaves of the tree.
Returns: (List[Node]) The leaves of the tree.
Source code in kernpy/core/document.py
383 384 385 386 387 388 389 |
|
get_metacomments(KeyComment=None, clear=False)
Get all metacomments in the document
Parameters:
Name | Type | Description | Default |
---|---|---|---|
KeyComment |
Optional[str]
|
Filter by a specific metacomment key: e.g. Use 'COM' to get only comments starting with '!!!COM: '. If None, all metacomments are returned. |
None
|
clear |
bool
|
If True, the metacomment key is removed from the comment. E.g. '!!!COM: Coltrane' -> 'Coltrane'. If False, the metacomment key is kept. E.g. '!!!COM: Coltrane' -> '!!!COM: Coltrane'. The clear functionality is equivalent to the following code:
Other formats are not supported. |
False
|
Returns: A list of metacomments.
Examples:
>>> document.get_metacomments()
['!!!COM: Coltrane', '!!!voices: 1', '!!!OPR: Blue Train']
>>> document.get_metacomments(KeyComment='COM')
['!!!COM: Coltrane']
>>> document.get_metacomments(KeyComment='COM', clear=True)
['Coltrane']
>>> document.get_metacomments(KeyComment='non_existing_key')
[]
Source code in kernpy/core/document.py
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 |
|
get_spine_count()
Get the number of spines in the document.
Returns (int): The number of spines in the document.
Source code in kernpy/core/document.py
391 392 393 394 395 396 397 |
|
get_spine_ids()
Get the indexes of the current document.
Returns List[int]: A list with the indexes of the current document.
Examples:
>>> document.get_all_spine_indexes()
[0, 1, 2, 3, 4]
Source code in kernpy/core/document.py
688 689 690 691 692 693 694 695 696 697 698 699 |
|
get_unique_token_encodings(filter_by_categories=None)
Get unique token encodings.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
filter_by_categories |
Optional[Sequence[TokenCategory]]
|
A list of categories to filter the tokens. If None, all tokens are returned. |
None
|
Returns: List[str] - A list of unique token encodings.
Source code in kernpy/core/document.py
558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 |
|
get_unique_tokens(filter_by_categories=None)
Get unique tokens.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
filter_by_categories |
Optional[Sequence[TokenCategory]]
|
A list of categories to filter the tokens. If None, all tokens are returned. |
None
|
Returns:
Type | Description |
---|---|
List[AbstractToken]
|
List[AbstractToken] - A list of unique tokens. |
Source code in kernpy/core/document.py
539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 |
|
get_voices(clean=False)
Get the voices of the document.
Args clean (bool): Remove the first '!' from the voice name.
Returns: A list of voices.
Examples:
>>> document.get_voices()
['!sax', '!piano', '!bass']
>>> document.get_voices(clean=True)
['sax', 'piano', 'bass']
>>> document.get_voices(clean=False)
['!sax', '!piano', '!bass']
Source code in kernpy/core/document.py
574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 |
|
match(a, b, *, check_core_spines_only=False)
classmethod
Match two documents. Two documents match if they have the same spine structure.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
a |
Document
|
The first document. |
required |
b |
Document
|
The second document. |
required |
check_core_spines_only |
Optional[bool]
|
If True, only the core spines (kern and mens) are checked. If False, all spines are checked. |
False
|
Returns: True if the documents match, False otherwise.
Examples:
Source code in kernpy/core/document.py
786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 |
|
measures_count()
Get the index of the last measure of the document.
Returns: (Int) The index of the last measure of the document.
Raises: Exception - If the document has no measures.
Examples:
>>> document, _ = kernpy.read('score.krn')
>>> document.measures_count()
10
>>> for i in range(document.get_first_measure(), document.measures_count() + 1):
>>> options = kernpy.ExportOptions(from_measure=i, to_measure=i+4)
Source code in kernpy/core/document.py
418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 |
|
split()
Split the current document into a list of documents, one for each kern spine. Each resulting document will contain one kern spine along with all non-kern spines.
Returns:
Type | Description |
---|---|
List['Document']
|
List['Document']: A list of documents, where each document contains one **kern spine |
List['Document']
|
and all non-kern spines from the original document. |
Examples:
>>> document.split()
[<Document: score.krn>, <Document: score.krn>, <Document: score.krn>]
Source code in kernpy/core/document.py
725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 |
|
to_concat(first_doc, second_doc, deep_copy=True)
classmethod
Concatenate two documents.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
first_doc |
Document
|
The first document. |
required |
second_doc |
Document
|
The second document. |
required |
deep_copy |
bool
|
If True, the documents are deep copied. If False, the documents are shallow copied. |
True
|
Returns: A new instance of Document with the documents concatenated.
Source code in kernpy/core/document.py
768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 |
|
to_transposed(interval, direction=Direction.UP.value)
Create a new document with the transposed notes without modifying the original document.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
interval |
str
|
The name of the interval to transpose. It can be 'P4', 'P5', 'M2', etc. Check the kp.AVAILABLE_INTERVALS for the available intervals. |
required |
direction |
str
|
The direction to transpose. It can be 'up' or 'down'. |
UP.value
|
Returns:
Source code in kernpy/core/document.py
809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 |
|
tokens_to_encodings(tokens)
classmethod
Get the encodings of a list of tokens.
The method is equivalent to the following code
tokens = kp.get_all_tokens() [token.encoding for token in tokens if token.encoding is not None]
Parameters:
Name | Type | Description | Default |
---|---|---|---|
tokens |
Sequence[AbstractToken]
|
list - A list of tokens. |
required |
Returns: List[str] - A list of token encodings.
Examples:
>>> tokens = document.get_all_tokens()
>>> Document.tokens_to_encodings(tokens)
['!!!COM: Coltrane', '!!!voices: 1', '!!!OPR: Blue Train']
Source code in kernpy/core/document.py
478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 |
|
Duration
Bases: ABC
Represents the duration of a note or a rest.
The duration is represented using the Humdrum Kern format. The duration is a number that represents the number of units of the duration.
The duration of a whole note is 1, half note is 2, quarter note is 4, eighth note is 8, etc.
The duration of a note is represented by a number. The duration of a rest is also represented by a number.
This class do not limit the duration ranges.
In the following example, the duration is represented by the number '2'.
**kern
*clefG2
2c // whole note
4c // half note
8c // quarter note
16c // eighth note
*-
Source code in kernpy/core/tokens.py
970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 |
|
DurationClassical
Bases: Duration
Represents the duration in classical notation of a note or a rest.
Source code in kernpy/core/tokens.py
1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 |
|
__eq__(other)
Compare two durations.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
other |
DurationClassical
|
The other duration to compare |
required |
Returns (bool): True if the durations are equal, False otherwise
Examples:
>>> duration = DurationClassical(2)
>>> duration2 = DurationClassical(2)
>>> duration == duration2
True
>>> duration = DurationClassical(2)
>>> duration2 = DurationClassical(4)
>>> duration == duration2
False
Source code in kernpy/core/tokens.py
1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 |
|
__ge__(other)
Compare two durations.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
other |
DurationClassical
|
The other duration to compare |
required |
Returns (bool): True if this duration is higher or equal than the other, False otherwise
Examples:
>>> duration = DurationClassical(2)
>>> duration2 = DurationClassical(4)
>>> duration >= duration2
False
>>> duration = DurationClassical(4)
>>> duration2 = DurationClassical(2)
>>> duration >= duration2
True
>>> duration = DurationClassical(4)
>>> duration2 = DurationClassical(4)
>>> duration >= duration2
True
Source code in kernpy/core/tokens.py
1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 |
|
__gt__(other)
Compare two durations.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
other |
'DurationClassical'
|
The other duration to compare |
required |
Returns (bool): True if this duration is higher than the other, False otherwise
Examples:
>>> duration = DurationClassical(2)
>>> duration2 = DurationClassical(4)
>>> duration > duration2
False
>>> duration = DurationClassical(4)
>>> duration2 = DurationClassical(2)
>>> duration > duration2
True
>>> duration = DurationClassical(4)
>>> duration2 = DurationClassical(4)
>>> duration > duration2
False
Source code in kernpy/core/tokens.py
1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 |
|
__init__(duration)
Create a new Duration object.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
duration |
str
|
duration representation in Humdrum Kern format |
required |
Examples:
>>> duration = DurationClassical(2)
True
>>> duration = DurationClassical(4)
True
>>> duration = DurationClassical(32)
True
>>> duration = DurationClassical(1)
True
>>> duration = DurationClassical(0)
False
>>> duration = DurationClassical(-2)
False
>>> duration = DurationClassical(3)
False
>>> duration = DurationClassical(7)
False
Source code in kernpy/core/tokens.py
1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 |
|
__le__(other)
Compare two durations.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
other |
DurationClassical
|
The other duration to compare |
required |
Returns:
Type | Description |
---|---|
bool
|
True if this duration is lower or equal than the other, False otherwise |
Examples:
>>> duration = DurationClassical(2)
>>> duration2 = DurationClassical(4)
>>> duration <= duration2
True
>>> duration = DurationClassical(4)
>>> duration2 = DurationClassical(2)
>>> duration <= duration2
False
>>> duration = DurationClassical(4)
>>> duration2 = DurationClassical(4)
>>> duration <= duration2
True
Source code in kernpy/core/tokens.py
1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 |
|
__lt__(other)
Compare two durations.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
other |
DurationClassical
|
The other duration to compare |
required |
Returns (bool): True if this duration is lower than the other, False otherwise
Examples:
>>> duration = DurationClassical(2)
>>> duration2 = DurationClassical(4)
>>> duration < duration2
True
>>> duration = DurationClassical(4)
>>> duration2 = DurationClassical(2)
>>> duration < duration2
False
>>> duration = DurationClassical(4)
>>> duration2 = DurationClassical(4)
>>> duration < duration2
False
Source code in kernpy/core/tokens.py
1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 |
|
__ne__(other)
Compare two durations.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
other |
DurationClassical
|
The other duration to compare |
required |
Returns (bool): True if the durations are different, False otherwise
Examples:
>>> duration = DurationClassical(2)
>>> duration2 = DurationClassical(2)
>>> duration != duration2
False
>>> duration = DurationClassical(2)
>>> duration2 = DurationClassical(4)
>>> duration != duration2
True
Source code in kernpy/core/tokens.py
1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 |
|
modify(ratio)
Modify the duration of a note or a rest of the current object.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
ratio |
int
|
The factor to modify the duration. The factor must be greater than 0. |
required |
Returns (DurationClassical): The new duration object with the modified duration.
Examples:
>>> duration = DurationClassical(2)
>>> new_duration = duration.modify(2)
>>> new_duration.duration
4
>>> duration = DurationClassical(2)
>>> new_duration = duration.modify(0)
Traceback (most recent call last):
...
ValueError: Invalid factor provided: 0. The factor must be greater than 0.
>>> duration = DurationClassical(2)
>>> new_duration = duration.modify(-2)
Traceback (most recent call last):
...
ValueError: Invalid factor provided: -2. The factor must be greater than 0.
Source code in kernpy/core/tokens.py
1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 |
|
DurationMensural
Bases: Duration
Represents the duration in mensural notation of a note or a rest.
Source code in kernpy/core/tokens.py
1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 |
|
DynSpineImporter
Bases: SpineImporter
Source code in kernpy/core/dyn_importer.py
11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
|
__init__(verbose=False)
KernSpineImporter constructor.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
verbose |
Optional[bool]
|
Level of verbosity for error messages. |
False
|
Source code in kernpy/core/dyn_importer.py
12 13 14 15 16 17 18 19 |
|
DynamSpineImporter
Bases: SpineImporter
Source code in kernpy/core/dynam_spine_importer.py
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 36 37 38 39 40 41 42 43 44 |
|
__init__(verbose=False)
KernSpineImporter constructor.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
verbose |
Optional[bool]
|
Level of verbosity for error messages. |
False
|
Source code in kernpy/core/dynam_spine_importer.py
11 12 13 14 15 16 17 18 |
|
EkernTokenizer
Bases: Tokenizer
EkernTokenizer converts a Token into an eKern (Extended **kern) string representation. This format use a '@' separator for the main tokens and a '·' separator for the decorations tokens.
Source code in kernpy/core/tokenizers.py
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 |
|
__init__(*, token_categories)
Create a new EkernTokenizer
Parameters:
Name | Type | Description | Default |
---|---|---|---|
token_categories |
List[TokenCategory]
|
List of categories to be tokenized. If None will raise an exception. |
required |
Source code in kernpy/core/tokenizers.py
120 121 122 123 124 125 126 127 |
|
tokenize(token)
Tokenize a token into an eKern string representation. Args: token (Token): Token to be tokenized.
Returns (str): eKern string representation.
Examples:
>>> token.encoding
'2@.@bb@-·_·L'
>>> EkernTokenizer().tokenize(token)
'2@.@bb@-·_·L'
Source code in kernpy/core/tokenizers.py
129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 |
|
Encoding
Bases: Enum
Options for exporting a kern file.
Example
import kernpy as kp
Load a file
doc, _ = kp.load('path/to/file.krn')
Save the file using the specified encoding
exported_content = kp.dumps(encoding=kp.Encoding.normalizedKern)
Source code in kernpy/core/tokenizers.py
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 36 37 38 39 40 41 42 43 44 45 |
|
prefix()
Get the prefix of the kern type.
Returns (str): Prefix of the kern type.
Source code in kernpy/core/tokenizers.py
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
|
ExportOptions
ExportOptions
class.
Store the options to export a **kern file.
Source code in kernpy/core/exporter.py
15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 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 |
|
__eq__(other)
Compare two ExportOptions objects.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
other |
'ExportOptions'
|
The other ExportOptions object to compare. |
required |
Returns (bool): True if the objects are equal, False otherwise.
Examples:
>>> options1 = ExportOptions(spine_types=['**kern'], token_categories=BEKERN_CATEGORIES)
>>> options2 = ExportOptions(spine_types=['**kern'], token_categories=BEKERN_CATEGORIES)
>>> options1 == options2
True
>>> options3 = ExportOptions(spine_types=['**kern', '**harm'], token_categories=BEKERN_CATEGORIES)
>>> options1 == options3
False
Source code in kernpy/core/exporter.py
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 |
|
__init__(spine_types=None, token_categories=None, from_measure=None, to_measure=None, kern_type=Encoding.normalizedKern, instruments=None, show_measure_numbers=False, spine_ids=None)
Create a new ExportOptions object.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
spine_types |
Iterable
|
kern, mens, etc... |
None
|
token_categories |
Iterable
|
TokenCategory |
None
|
from_measure |
int
|
The measure to start exporting. When None, the exporter will start from the beginning of the file. The first measure is 1 |
None
|
to_measure |
int
|
The measure to end exporting. When None, the exporter will end at the end of the file. |
None
|
kern_type |
Encoding
|
The type of the kern file to export. |
normalizedKern
|
instruments |
Iterable
|
The instruments to export. When None, all the instruments will be exported. |
None
|
show_measure_numbers |
Bool
|
Show the measure numbers in the exported file. |
False
|
spine_ids |
Iterable
|
The ids of the spines to export. When None, all the spines will be exported. Spines ids start from 0 and they are increased by 1. |
None
|
Example
import kernpy
Create the importer and read the file
hi = Importer() document = hi.import_file('file.krn') exporter = Exporter()
Export the file with the specified options
options = ExportOptions(spine_types=['**kern'], token_categories=BEKERN_CATEGORIES) exported_data = exporter.export_string(document, options)
Export only the lyrics
options = ExportOptions(spine_types=['**kern'], token_categories=[TokenCategory.LYRICS]) exported_data = exporter.export_string(document, options)
Export the comments
options = ExportOptions(spine_types=['**kern'], token_categories=[TokenCategory.LINE_COMMENTS, TokenCategory.FIELD_COMMENTS]) exported_data = exporter.export_string(document, options)
Export using the eKern version
options = ExportOptions(spine_types=['**kern'], token_categories=BEKERN_CATEGORIES, kern_type=Encoding.eKern) exported_data = exporter.export_string(document, options)
Source code in kernpy/core/exporter.py
22 23 24 25 26 27 28 29 30 31 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 |
|
__ne__(other)
Compare two ExportOptions objects.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
other |
ExportOptions
|
The other ExportOptions object to compare. |
required |
Returns (bool): True if the objects are not equal, False otherwise.
Examples:
>>> options1 = ExportOptions(spine_types=['**kern'], token_categories=BEKERN_CATEGORIES)
>>> options2 = ExportOptions(spine_types=['**kern'], token_categories=BEKERN_CATEGORIES)
>>> options1 != options2
False
>>> options3 = ExportOptions(spine_types=['**kern', '**harm'], token_categories=BEKERN_CATEGORIES)
>>> options1 != options3
True
Source code in kernpy/core/exporter.py
109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 |
|
Exporter
Source code in kernpy/core/exporter.py
183 184 185 186 187 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 314 315 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 347 348 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 |
|
append_row(document, node, options, row)
Append a row to the row list if the node accomplishes the requirements. Args: document (Document): The document with the spines. node (Node): The node to append. options (ExportOptions): The export options to filter the token. row (list): The row to append.
Returns (bool): True if the row was appended. False if the row was not appended.
Source code in kernpy/core/exporter.py
311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 |
|
compute_header_type(node)
Compute the header type of the node.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
node |
Node
|
The node to compute. |
required |
Returns (Optional[Token]): The header type Node
object. None if the current node is the header.
Source code in kernpy/core/exporter.py
284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 |
|
export_options_validator(document, options)
classmethod
Validate the export options. Raise an exception if the options are invalid.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
document |
Document
|
|
required |
options |
ExportOptions
|
|
required |
Returns: None
Example
export_options_validator(document, options) ValueError: option from_measure must be >=0 but -1 was found. export_options_validator(document, options2) None
Source code in kernpy/core/exporter.py
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 |
|
get_spine_types(document, spine_types=None)
Get the spine types from the document.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
document |
Document
|
The document with the spines. |
required |
spine_types |
list
|
The spine types to export. If None, all the spine types will be exported. |
None
|
Returns: A list with the spine types.
Examples:
>>> exporter = Exporter()
>>> exporter.get_spine_types(document)
['**kern', '**kern', '**kern', '**kern', '**root', '**harm']
>>> exporter.get_spine_types(document, None)
['**kern', '**kern', '**kern', '**kern', '**root', '**harm']
>>> exporter.get_spine_types(document, ['**kern'])
['**kern', '**kern', '**kern', '**kern']
>>> exporter.get_spine_types(document, ['**kern', '**root'])
['**kern', '**kern', '**kern', '**kern', '**root']
>>> exporter.get_spine_types(document, ['**kern', '**root', '**harm'])
['**kern', '**kern', '**kern', '**kern', '**root', '**harm']
>>> exporter.get_spine_types(document, [])
[]
Source code in kernpy/core/exporter.py
336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 |
|
F3Clef
Bases: Clef
Source code in kernpy/core/gkern.py
365 366 367 368 369 370 371 372 373 374 375 376 |
|
__init__()
Initializes the F Clef object.
Source code in kernpy/core/gkern.py
366 367 368 369 370 |
|
bottom_line()
Returns the pitch of the bottom line of the staff.
Source code in kernpy/core/gkern.py
372 373 374 375 376 |
|
F4Clef
Bases: Clef
Source code in kernpy/core/gkern.py
378 379 380 381 382 383 384 385 386 387 388 389 |
|
__init__()
Initializes the F Clef object.
Source code in kernpy/core/gkern.py
379 380 381 382 383 |
|
bottom_line()
Returns the pitch of the bottom line of the staff.
Source code in kernpy/core/gkern.py
385 386 387 388 389 |
|
FingSpineImporter
Bases: SpineImporter
Source code in kernpy/core/fing_spine_importer.py
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 36 37 38 39 40 41 42 43 44 45 |
|
__init__(verbose=False)
KernSpineImporter constructor.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
verbose |
Optional[bool]
|
Level of verbosity for error messages. |
False
|
Source code in kernpy/core/fing_spine_importer.py
11 12 13 14 15 16 17 18 |
|
GClef
Bases: Clef
Source code in kernpy/core/gkern.py
352 353 354 355 356 357 358 359 360 361 362 363 |
|
__init__()
Initializes the G Clef object.
Source code in kernpy/core/gkern.py
353 354 355 356 357 |
|
bottom_line()
Returns the pitch of the bottom line of the staff.
Source code in kernpy/core/gkern.py
359 360 361 362 363 |
|
GraphvizExporter
Source code in kernpy/core/graphviz_exporter.py
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 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 |
|
export_to_dot(tree, filename=None)
Export the given MultistageTree to DOT format.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
tree |
MultistageTree
|
The tree to export. |
required |
filename |
Path or None
|
The output file path. If None, prints to stdout. |
None
|
Source code in kernpy/core/graphviz_exporter.py
22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 |
|
HarmSpineImporter
Bases: SpineImporter
Source code in kernpy/core/harm_spine_importer.py
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 36 37 38 39 40 41 42 43 44 |
|
__init__(verbose=False)
KernSpineImporter constructor.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
verbose |
Optional[bool]
|
Level of verbosity for error messages. |
False
|
Source code in kernpy/core/harm_spine_importer.py
11 12 13 14 15 16 17 18 |
|
HeaderToken
Bases: SimpleToken
HeaderTokens class.
Source code in kernpy/core/tokens.py
1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 |
|
__init__(encoding, spine_id)
Constructor for the HeaderToken class.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
encoding |
str
|
The original representation of the token. |
required |
spine_id |
int
|
The spine id of the token. The spine id is used to identify the token in the score. The spine_id starts from 0 and increases by 1 for each new spine like the following example: kern kern kern dyn **text 0 1 2 3 4 |
required |
Source code in kernpy/core/tokens.py
1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 |
|
HeaderTokenGenerator
HeaderTokenGenerator class.
This class is used to translate the HeaderTokens to the specific encoding format.
Source code in kernpy/core/exporter.py
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 |
|
new(*, token, type)
classmethod
Create a new HeaderTokenGenerator object. Only accepts stardized Humdrum **kern encodings.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
token |
HeaderToken
|
The HeaderToken to be translated. |
required |
type |
Encoding
|
The encoding to be used. |
required |
Examples:
>>> header = HeaderToken('**kern', 0)
>>> header.encoding
'**kern'
>>> new_header = HeaderTokenGenerator.new(token=header, type=Encoding.eKern)
>>> new_header.encoding
'**ekern'
Source code in kernpy/core/exporter.py
158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 |
|
HumdrumPitchImporter
Bases: PitchImporter
Represents the pitch in the Humdrum Kern format.
The name is represented using the International Standard Organization (ISO) name notation. The first line below the staff is the C4 in G clef. The above C is C5, the below C is C3, etc.
The Humdrum Kern format uses the following name representation: 'c' = C4 'cc' = C5 'ccc' = C6 'cccc' = C7
'C' = C3 'CC' = C2 'CCC' = C1
This class do not limit the name ranges.
In the following example, the name is represented by the letter 'c'. The name of 'c' is C4, 'cc' is C5, 'ccc' is C6.
**kern
*clefG2
2c // C4
2cc // C5
2ccc // C6
2C // C3
2CC // C2
2CCC // C1
*-
Source code in kernpy/core/pitch_models.py
186 187 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 |
|
Importer
Importer class.
Use this class to import the content from a file or a string to a Document
object.
Source code in kernpy/core/importer.py
16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 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 186 187 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 |
|
__init__()
Create an instance of the importer.
Raises:
Exception: If the importer content is not a valid **kern file.
Examples:
# Create the importer
>>> importer = Importer()
# Import the content from a file
>>> document = importer.import_file('file.krn')
# Import the content from a string
>>> document = importer.import_string("**kern
clefF4 c4 4d 4e 4f -")
Source code in kernpy/core/importer.py
22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 |
|
get_error_messages()
Get the error messages of the importer.
Returns: str - The error messages split by a new line character.
Examples:
Create the importer and read the file
>>> importer = Importer()
>>> importer.import_file(Path('file.krn'))
>>> print(importer.get_error_messages())
'Error: Invalid token in row 1'
Source code in kernpy/core/importer.py
198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 |
|
has_errors()
Check if the importer has any errors.
Returns: bool - True if the importer has errors, False otherwise.
Examples:
Create the importer and read the file
>>> importer = Importer()
>>> importer.import_file(Path('file.krn')) # file.krn has an error
>>> print(importer.has_errors())
True
>>> importer.import_file(Path('file2.krn')) # file2.krn has no errors
>>> print(importer.has_errors())
False
Source code in kernpy/core/importer.py
217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 |
|
import_file(file_path)
Import the content from the importer to the file. Args: file_path: The path to the file.
Returns:
Type | Description |
---|---|
Document
|
Document - The document with the imported content. |
Examples:
Create the importer and read the file
>>> importer = Importer()
>>> importer.import_file('file.krn')
Source code in kernpy/core/importer.py
156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 |
|
import_string(text)
Import the content from the content of the score in string format.
Args:
text: The content of the score in string format.
Returns:
Document - The document with the imported content.
Examples:
# Create the importer and read the file
>>> importer = Importer()
>>> importer.import_string("**kern
clefF4 c4 4d 4e 4f -") # Read the content from a file >>> with open('file.krn', 'r', newline='', encoding='utf-8', errors='ignore') as f: # We encourage you to use these open file options >>> content = f.read() >>> importer.import_string(content) >>> document = importer.import_string(content)
Source code in kernpy/core/importer.py
174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 |
|
KernSpineImporter
Bases: SpineImporter
Source code in kernpy/core/kern_spine_importer.py
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 |
|
__init__(verbose=False)
KernSpineImporter constructor.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
verbose |
Optional[bool]
|
Level of verbosity for error messages. |
False
|
Source code in kernpy/core/kern_spine_importer.py
41 42 43 44 45 46 47 48 |
|
KernTokenizer
Bases: Tokenizer
KernTokenizer converts a Token into a normalized kern string representation.
Source code in kernpy/core/tokenizers.py
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 |
|
__init__(*, token_categories)
Create a new KernTokenizer.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
token_categories |
Set[TokenCategory]
|
List of categories to be tokenized. If None will raise an exception. |
required |
Source code in kernpy/core/tokenizers.py
86 87 88 89 90 91 92 93 |
|
tokenize(token)
Tokenize a token into a normalized kern string representation. This format is the classic Humdrum **kern representation.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
token |
Token
|
Token to be tokenized. |
required |
Returns (str): Normalized kern string representation. This is the classic Humdrum **kern representation.
Examples:
>>> token.encoding
'2@.@bb@-·_·L'
>>> KernTokenizer().tokenize(token)
'2.bb-_L'
Source code in kernpy/core/tokenizers.py
95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 |
|
MensSpineImporter
Bases: SpineImporter
Source code in kernpy/core/mens_spine_importer.py
9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
|
__init__(verbose=False)
MensSpineImporter constructor.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
verbose |
Optional[bool]
|
Level of verbosity for error messages. |
False
|
Source code in kernpy/core/mens_spine_importer.py
10 11 12 13 14 15 16 17 |
|
MxhmSpineImporter
Bases: SpineImporter
Source code in kernpy/core/mhxm_spine_importer.py
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 36 37 38 39 40 41 42 43 44 |
|
__init__(verbose=False)
KernSpineImporter constructor.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
verbose |
Optional[bool]
|
Level of verbosity for error messages. |
False
|
Source code in kernpy/core/mhxm_spine_importer.py
11 12 13 14 15 16 17 18 |
|
NoteRestToken
Bases: ComplexToken
NoteRestToken class.
Attributes:
Name | Type | Description |
---|---|---|
pitch_duration_subtokens |
list
|
The subtokens for the pitch and duration |
decoration_subtokens |
list
|
The subtokens for the decorations |
Source code in kernpy/core/tokens.py
1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 |
|
__init__(encoding, pitch_duration_subtokens, decoration_subtokens)
NoteRestToken constructor.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
encoding |
str
|
The complete unprocessed encoding |
required |
pitch_duration_subtokens |
List[Subtoken])y
|
The subtokens for the pitch and duration |
required |
decoration_subtokens |
List[Subtoken]
|
The subtokens for the decorations. Individual elements of the token, of type Subtoken |
required |
Source code in kernpy/core/tokens.py
1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 |
|
export(**kwargs)
Exports the token.
Other Parameters:
Name | Type | Description |
---|---|---|
filter_categories |
Optional[Callable[[TokenCategory], bool]]
|
A function that takes a TokenCategory and returns a boolean indicating whether the token should be included in the export. If provided, only tokens for which the function returns True will be exported. Defaults to None. If None, all tokens will be exported. |
Returns (str): The exported token.
Source code in kernpy/core/tokens.py
1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 |
|
PitchPositionReferenceSystem
Source code in kernpy/core/gkern.py
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 |
|
__init__(base_pitch)
Initializes the PitchPositionReferenceSystem object. Args: base_pitch (AgnosticPitch): The AgnosticPitch in the first line of the Staff. The AgnosticPitch object that serves as the reference point for the system.
Source code in kernpy/core/gkern.py
221 222 223 224 225 226 227 228 |
|
compute_position(pitch)
Computes the position in staff for the given pitch. Args: pitch (AgnosticPitch): The AgnosticPitch object to compute the position for. Returns: PositionInStaff: The PositionInStaff object representing the computed position.
Source code in kernpy/core/gkern.py
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 |
|
PitchRest
Represents a name or a rest in a note.
The name is represented using the International Standard Organization (ISO) name notation. The first line below the staff is the C4 in G clef. The above C is C5, the below C is C3, etc.
The Humdrum Kern format uses the following name representation: 'c' = C4 'cc' = C5 'ccc' = C6 'cccc' = C7
'C' = C3 'CC' = C2 'CCC' = C1
The rests are represented by the letter 'r'. The rests do not have name.
This class do not limit the name ranges.
In the following example, the name is represented by the letter 'c'. The name of 'c' is C4, 'cc' is C5, 'ccc' is C6.
**kern
*clefG2
2c // C4
2cc // C5
2ccc // C6
2C // C3
2CC // C2
2CCC // C1
*-
Source code in kernpy/core/tokens.py
598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 |
|
__eq__(other)
Compare two pitches and rests.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
other |
PitchRest
|
The other name to compare |
required |
Returns (bool): True if the pitches are equal, False otherwise
Examples:
>>> pitch_rest = PitchRest('c')
>>> pitch_rest2 = PitchRest('c')
>>> pitch_rest == pitch_rest2
True
>>> pitch_rest = PitchRest('c')
>>> pitch_rest2 = PitchRest('ccc')
>>> pitch_rest == pitch_rest2
False
>>> pitch_rest = PitchRest('c')
>>> pitch_rest2 = PitchRest('r')
>>> pitch_rest == pitch_rest2
False
>>> pitch_rest = PitchRest('r')
>>> pitch_rest2 = PitchRest('r')
>>> pitch_rest == pitch_rest2
True
Source code in kernpy/core/tokens.py
730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 |
|
__ge__(other)
Compare two pitches. If any of the PitchRest is a rest, the comparison raise an exception. Args: other (PitchRest): The other name to compare
Returns (bool): True if this name is higher or equal than the other, False otherwise
Examples:
>>> pitch_rest = PitchRest('c')
>>> pitch_rest2 = PitchRest('d')
>>> pitch_rest >= pitch_rest2
False
>>> pitch_rest = PitchRest('c')
>>> pitch_rest2 = PitchRest('c')
>>> pitch_rest >= pitch_rest2
True
>>> pitch_rest = PitchRest('c')
>>> pitch_rest2 = PitchRest('b')
>>> pitch_rest >= pitch_rest2
True
>>> pitch_rest = PitchRest('r')
>>> pitch_rest2 = PitchRest('c')
>>> pitch_rest >= pitch_rest2
Traceback (most recent call last):
...
ValueError: ...
>>> pitch_rest = PitchRest('r')
>>> pitch_rest2 = PitchRest('r')
>>> pitch_rest >= pitch_rest2
Traceback (most recent call last):
...
ValueError: ...
Source code in kernpy/core/tokens.py
893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 |
|
__gt__(other)
Compare two pitches.
If any of the pitches is a rest, the comparison raise an exception.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
other |
PitchRest
|
The other name to compare |
required |
Returns (bool): True if this name is higher than the other, False otherwise
Examples:
>>> pitch_rest = PitchRest('c')
>>> pitch_rest2 = PitchRest('d')
>>> pitch_rest > pitch_rest2
False
>>> pitch_rest = PitchRest('c')
>>> pitch_rest2 = PitchRest('c')
>>> pitch_rest > pitch_rest2
False
>>> pitch_rest = PitchRest('c')
>>> pitch_rest2 = PitchRest('b')
>>> pitch_rest > pitch_rest2
True
>>> pitch_rest = PitchRest('r')
>>> pitch_rest2 = PitchRest('c')
>>> pitch_rest > pitch_rest2
Traceback (most recent call last):
...
ValueError: ...
>>> pitch_rest = PitchRest('r')
>>> pitch_rest2 = PitchRest('r')
>>> pitch_rest > pitch_rest2
Traceback (most recent call last):
ValueError: ...
Source code in kernpy/core/tokens.py
796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 |
|
__init__(raw_pitch)
Create a new PitchRest object.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
raw_pitch |
str
|
name representation in Humdrum Kern format |
required |
Examples:
>>> pitch_rest = PitchRest('c')
>>> pitch_rest = PitchRest('r')
>>> pitch_rest = PitchRest('DDD')
Source code in kernpy/core/tokens.py
641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 |
|
__le__(other)
Compare two pitches. If any of the PitchRest is a rest, the comparison raise an exception. Args: other (PitchRest): The other name to compare
Returns (bool): True if this name is lower or equal than the other, False otherwise
Examples:
>>> pitch_rest = PitchRest('c')
>>> pitch_rest2 = PitchRest('d')
>>> pitch_rest <= pitch_rest2
True
>>> pitch_rest = PitchRest('c')
>>> pitch_rest2 = PitchRest('c')
>>> pitch_rest <= pitch_rest2
True
>>> pitch_rest = PitchRest('c')
>>> pitch_rest2 = PitchRest('b')
>>> pitch_rest <= pitch_rest2
False
>>> pitch_rest = PitchRest('r')
>>> pitch_rest2 = PitchRest('c')
>>> pitch_rest <= pitch_rest2
Traceback (most recent call last):
...
ValueError: ...
>>> pitch_rest = PitchRest('r')
>>> pitch_rest2 = PitchRest('r')
>>> pitch_rest <= pitch_rest2
Traceback (most recent call last):
...
ValueError: ...
Source code in kernpy/core/tokens.py
932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 |
|
__lt__(other)
Compare two pitches.
If any of the pitches is a rest, the comparison raise an exception.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
other |
'PitchRest'
|
The other name to compare |
required |
Returns:
Type | Description |
---|---|
bool
|
True if this name is lower than the other, False otherwise |
Examples:
>>> pitch_rest = PitchRest('c')
>>> pitch_rest2 = PitchRest('d')
>>> pitch_rest < pitch_rest2
True
>>> pitch_rest = PitchRest('c')
>>> pitch_rest2 = PitchRest('c')
>>> pitch_rest < pitch_rest2
False
>>> pitch_rest = PitchRest('c')
>>> pitch_rest2 = PitchRest('b')
>>> pitch_rest < pitch_rest2
False
>>> pitch_rest = PitchRest('r')
>>> pitch_rest2 = PitchRest('c')
>>> pitch_rest < pitch_rest2
Traceback (most recent call last):
...
ValueError: ...
>>> pitch_rest = PitchRest('r')
>>> pitch_rest2 = PitchRest('r')
>>> pitch_rest < pitch_rest2
Traceback (most recent call last):
...
ValueError: ...
Source code in kernpy/core/tokens.py
844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 |
|
__ne__(other)
Compare two pitches and rests. Args: other (PitchRest): The other name to compare
Returns (bool): True if the pitches are different, False otherwise
Examples:
>>> pitch_rest = PitchRest('c')
>>> pitch_rest2 = PitchRest('c')
>>> pitch_rest != pitch_rest2
False
>>> pitch_rest = PitchRest('c')
>>> pitch_rest2 = PitchRest('ccc')
>>> pitch_rest != pitch_rest2
True
>>> pitch_rest = PitchRest('c')
>>> pitch_rest2 = PitchRest('r')
>>> pitch_rest != pitch_rest2
True
>>> pitch_rest = PitchRest('r')
>>> pitch_rest2 = PitchRest('r')
>>> pitch_rest != pitch_rest2
False
Source code in kernpy/core/tokens.py
767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 |
|
is_rest()
Check if the name is a rest.
Returns:
Name | Type | Description |
---|---|---|
bool |
bool
|
True if the name is a rest, False otherwise. |
Examples:
>>> pitch_rest = PitchRest('c')
>>> pitch_rest.is_rest()
False
>>> pitch_rest = PitchRest('r')
>>> pitch_rest.is_rest()
True
Source code in kernpy/core/tokens.py
677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 |
|
pitch_comparator(pitch_a, pitch_b)
staticmethod
Compare two pitches of the same octave.
The lower name is 'a'. So 'a' < 'b' < 'c' < 'd' < 'e' < 'f' < 'g'
Parameters:
Name | Type | Description | Default |
---|---|---|---|
pitch_a |
str
|
One name of 'abcdefg' |
required |
pitch_b |
str
|
Another name of 'abcdefg' |
required |
Returns:
Type | Description |
---|---|
int
|
-1 if pitch1 is lower than pitch2 |
int
|
0 if pitch1 is equal to pitch2 |
int
|
1 if pitch1 is higher than pitch2 |
Examples:
>>> PitchRest.pitch_comparator('c', 'c')
0
>>> PitchRest.pitch_comparator('c', 'd')
-1
>>> PitchRest.pitch_comparator('d', 'c')
1
Source code in kernpy/core/tokens.py
694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 |
|
PositionInStaff
Source code in kernpy/core/gkern.py
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 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 |
|
__eq__(other)
Compares two PositionInStaff objects.
Source code in kernpy/core/gkern.py
180 181 182 183 184 185 186 |
|
__hash__()
Returns the hash of the PositionInStaff object.
Source code in kernpy/core/gkern.py
194 195 196 197 198 |
|
__init__(line_space)
Initializes the PositionInStaff object.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
line_space |
int
|
0 for bottom line, -1 for space under bottom line, 1 for space above bottom line. Increments by 1 for each line or space. |
required |
Source code in kernpy/core/gkern.py
59 60 61 62 63 64 65 66 67 68 |
|
__lt__(other)
Compares two PositionInStaff objects.
Source code in kernpy/core/gkern.py
200 201 202 203 204 205 206 |
|
__ne__(other)
Compares two PositionInStaff objects.
Source code in kernpy/core/gkern.py
188 189 190 191 192 |
|
__repr__()
Returns the string representation of the PositionInStaff object.
Source code in kernpy/core/gkern.py
174 175 176 177 178 |
|
__str__()
Returns the string representation of the position in staff.
Source code in kernpy/core/gkern.py
165 166 167 168 169 170 171 172 |
|
from_encoded(encoded)
classmethod
Creates a PositionInStaff object from an encoded string.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
encoded |
str
|
The encoded string. |
required |
Returns:
Name | Type | Description |
---|---|---|
PositionInStaff |
PositionInStaff
|
The PositionInStaff object. |
Source code in kernpy/core/gkern.py
96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 |
|
from_line(line)
classmethod
Creates a PositionInStaff object from a line number.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
line |
int
|
The line number. line 1 is bottom line, 2 is the 1st line from bottom, 0 is the bottom ledger line |
required |
Returns:
Name | Type | Description |
---|---|---|
PositionInStaff |
PositionInStaff
|
The PositionInStaff object. 0 for the bottom line, 2 for the 1st line from bottom, -1 for the bottom ledger line, etc. |
Source code in kernpy/core/gkern.py
70 71 72 73 74 75 76 77 78 79 80 81 |
|
from_space(space)
classmethod
Creates a PositionInStaff object from a space number.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
space |
int
|
The space number. space 1 is bottom space, 2 |
required |
Returns:
Name | Type | Description |
---|---|---|
PositionInStaff |
PositionInStaff
|
The PositionInStaff object. |
Source code in kernpy/core/gkern.py
83 84 85 86 87 88 89 90 91 92 93 94 |
|
is_line()
Returns True if the position is a line, False otherwise. If is not a line, it is a space, and vice versa.
Source code in kernpy/core/gkern.py
133 134 135 136 137 |
|
line()
Returns the line number of the position in staff.
Source code in kernpy/core/gkern.py
119 120 121 122 123 |
|
move(line_space_difference)
Returns a new PositionInStaff object with the position moved by the given number of lines or spaces.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
line_space_difference |
int
|
The number of lines or spaces to move. |
required |
Returns:
Name | Type | Description |
---|---|---|
PositionInStaff |
PositionInStaff
|
The new PositionInStaff object. |
Source code in kernpy/core/gkern.py
139 140 141 142 143 144 145 146 147 148 149 |
|
position_above()
Returns the position above the current position.
Source code in kernpy/core/gkern.py
157 158 159 160 161 |
|
position_below()
Returns the position below the current position.
Source code in kernpy/core/gkern.py
151 152 153 154 155 |
|
space()
Returns the space number of the position in staff.
Source code in kernpy/core/gkern.py
126 127 128 129 130 |
|
RootSpineImporter
Bases: SpineImporter
Source code in kernpy/core/root_spine_importer.py
37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 |
|
__init__(verbose=False)
KernSpineImporter constructor.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
verbose |
Optional[bool]
|
Level of verbosity for error messages. |
False
|
Source code in kernpy/core/root_spine_importer.py
38 39 40 41 42 43 44 45 |
|
SimpleToken
Bases: Token
SimpleToken class.
Source code in kernpy/core/tokens.py
1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 |
|
export(**kwargs)
Exports the token.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
**kwargs |
'filter_categories' (Optional[Callable[[TokenCategory], bool]]): It is ignored in this class. |
{}
|
Returns (str): The encoded token representation.
Source code in kernpy/core/tokens.py
1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 |
|
SpineOperationToken
Bases: SimpleToken
SpineOperationToken class.
This token represents different operations in the Humdrum kern encoding.
These are the available operations:
- *-
: spine-path terminator.
- *
: null interpretation.
- *+
: add spines.
- *^
: split spines.
- *x
: exchange spines.
Attributes:
Name | Type | Description |
---|---|---|
cancelled_at_stage |
int
|
The stage at which the operation was cancelled. Defaults to None. |
Source code in kernpy/core/tokens.py
1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 |
|
is_cancelled_at(stage)
Checks if the operation was cancelled at the given stage.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
stage |
int
|
The stage at which the operation was cancelled. |
required |
Returns:
Name | Type | Description |
---|---|---|
bool |
bool
|
True if the operation was cancelled at the given stage, False otherwise. |
Source code in kernpy/core/tokens.py
1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 |
|
StoreCache
A simple cache that stores the result of a callback function
Source code in kernpy/util/store_cache.py
1 2 3 4 5 6 7 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 |
|
__init__()
Constructor
Source code in kernpy/util/store_cache.py
5 6 7 8 9 |
|
request(callback, request)
Request a value from the cache. If the value is not in the cache, it will be calculated by the callback function Args: callback (function): The callback function that will be called to calculate the value request (any): The request that will be passed to the callback function
Returns (any): The value that was requested
Examples:
>>> def add_five(x):
... return x + 5
>>> store_cache = StoreCache()
>>> store_cache.request(callback, 5) # Call the callback function
10
>>> store_cache.request(callback, 5) # Return the value from the cache, without calling the callback function
10
Source code in kernpy/util/store_cache.py
11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
|
Subtoken
Subtoken class. Thhe subtokens are the smallest units of categories. ComplexToken objects are composed of subtokens.
Attributes:
Name | Type | Description |
---|---|---|
encoding |
The complete unprocessed encoding |
|
category |
The subtoken category, one of SubTokenCategory |
Source code in kernpy/core/tokens.py
1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 |
|
__eq__(other)
Compare two subtokens.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
other |
Subtoken
|
The other subtoken to compare. |
required |
Returns (bool): True if the subtokens are equal, False otherwise.
Source code in kernpy/core/tokens.py
1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 |
|
__hash__()
Returns the hash of the subtoken.
Returns (int): The hash of the subtoken.
Source code in kernpy/core/tokens.py
1376 1377 1378 1379 1380 1381 1382 |
|
__init__(encoding, category)
Subtoken constructor
Parameters:
Name | Type | Description | Default |
---|---|---|---|
encoding |
str
|
The complete unprocessed encoding |
required |
category |
TokenCategory
|
The subtoken category. It should be a child of the main 'TokenCategory' in the hierarchy. |
required |
Source code in kernpy/core/tokens.py
1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 |
|
__ne__(other)
Compare two subtokens.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
other |
Subtoken
|
The other subtoken to compare. |
required |
Returns (bool): True if the subtokens are different, False otherwise.
Source code in kernpy/core/tokens.py
1366 1367 1368 1369 1370 1371 1372 1373 1374 |
|
__str__()
Returns the string representation of the subtoken.
Returns (str): The string representation of the subtoken.
Source code in kernpy/core/tokens.py
1346 1347 1348 1349 1350 1351 1352 |
|
TextSpineImporter
Bases: SpineImporter
Source code in kernpy/core/text_spine_importer.py
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 36 37 38 39 40 41 42 43 44 45 46 |
|
__init__(verbose=False)
KernSpineImporter constructor.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
verbose |
Optional[bool]
|
Level of verbosity for error messages. |
False
|
Source code in kernpy/core/text_spine_importer.py
12 13 14 15 16 17 18 19 |
|
Token
Bases: AbstractToken
, ABC
Abstract Token class.
Source code in kernpy/core/tokens.py
1471 1472 1473 1474 1475 1476 1477 |
|
TokenCategory
Bases: Enum
Options for the category of a token.
This is used to determine what kind of token should be exported.
The categories are sorted the specific order they are compared to sorthem. But hierarchical order must be defined in other data structures.
Source code in kernpy/core/tokens.py
23 24 25 26 27 28 29 30 31 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 186 187 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 |
|
__lt__(other)
Compare two TokenCategory. Args: other (TokenCategory): The other category to compare.
Returns (bool): True if this category is lower than the other, False otherwise.
Examples:
>>> TokenCategory.STRUCTURAL < TokenCategory.CORE
True
>>> TokenCategory.STRUCTURAL < TokenCategory.STRUCTURAL
False
>>> TokenCategory.CORE < TokenCategory.STRUCTURAL
False
>>> sorted([TokenCategory.STRUCTURAL, TokenCategory.CORE])
[TokenCategory.STRUCTURAL, TokenCategory.CORE]
Source code in kernpy/core/tokens.py
69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 |
|
__str__()
Get the string representation of the category.
Returns (str): The string representation of the category.
Source code in kernpy/core/tokens.py
230 231 232 233 234 235 236 |
|
children(target)
classmethod
Get the children of the target category.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
target |
TokenCategory
|
The target category. |
required |
Returns (List[TokenCategory]): The list of child categories of the target category.
Source code in kernpy/core/tokens.py
160 161 162 163 164 165 166 167 168 169 170 |
|
is_child(*, child, parent)
classmethod
Check if the child category is a child of the parent category.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
child |
TokenCategory
|
The child category. |
required |
parent |
TokenCategory
|
The parent category. |
required |
Returns (bool): True if the child category is a child of the parent category, False otherwise.
Source code in kernpy/core/tokens.py
147 148 149 150 151 152 153 154 155 156 157 158 |
|
leaves(target)
classmethod
Get the leaves of the subtree of the target category.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
target |
TokenCategory
|
The target category. |
required |
Returns (List[TokenCategory]): The list of leaf categories of the target category.
Source code in kernpy/core/tokens.py
187 188 189 190 191 192 193 194 195 196 197 |
|
match(target, *, include=None, exclude=None)
classmethod
Check if the target category matches the include and exclude sets.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
target |
TokenCategory
|
The target category. |
required |
include |
Optional[Set[TokenCategory]]
|
The set of categories to include. Defaults to None. If None, all categories are included. |
None
|
exclude |
Optional[Set[TokenCategory]]
|
The set of categories to exclude. Defaults to None. If None, no categories are excluded. |
None
|
Returns (bool): True if the target category matches the include and exclude sets, False otherwise.
Source code in kernpy/core/tokens.py
211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 |
|
nodes(target)
classmethod
Get the nodes of the subtree of the target category.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
target |
TokenCategory
|
The target category. |
required |
Returns (List[TokenCategory]): The list of node categories of the target category.
Source code in kernpy/core/tokens.py
199 200 201 202 203 204 205 206 207 208 209 |
|
tree()
classmethod
Return a string representation of the category hierarchy Returns (str): The string representation of the category hierarchy
Examples:
>>> import kernpy as kp
>>> print(kp.TokenCategory.tree())
.
├── TokenCategory.STRUCTURAL
├── TokenCategory.CORE
│ ├── TokenCategory.NOTE_REST
│ │ ├── TokenCategory.DURATION
│ │ ├── TokenCategory.NOTE
│ │ │ ├── TokenCategory.PITCH
│ │ │ └── TokenCategory.DECORATION
│ │ └── TokenCategory.REST
│ ├── TokenCategory.CHORD
│ └── TokenCategory.EMPTY
├── TokenCategory.SIGNATURES
│ ├── TokenCategory.CLEF
│ ├── TokenCategory.TIME_SIGNATURE
│ ├── TokenCategory.METER_SYMBOL
│ └── TokenCategory.KEY_SIGNATURE
├── TokenCategory.ENGRAVED_SYMBOLS
├── TokenCategory.OTHER_CONTEXTUAL
├── TokenCategory.BARLINES
├── TokenCategory.COMMENTS
│ ├── TokenCategory.FIELD_COMMENTS
│ └── TokenCategory.LINE_COMMENTS
├── TokenCategory.DYNAMICS
├── TokenCategory.HARMONY
├── TokenCategory.FINGERING
├── TokenCategory.LYRICS
├── TokenCategory.INSTRUMENTS
├── TokenCategory.BOUNDING_BOXES
└── TokenCategory.OTHER
Source code in kernpy/core/tokens.py
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 |
|
valid(*, include=None, exclude=None)
classmethod
Get the valid categories based on the include and exclude sets.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
include |
Optional[Set[TokenCategory]]
|
The set of categories to include. Defaults to None. If None, all categories are included. |
None
|
exclude |
Optional[Set[TokenCategory]]
|
The set of categories to exclude. Defaults to None. If None, no categories are excluded. |
None
|
Returns (Set[TokenCategory]): The list of valid categories based on the include and exclude sets.
Source code in kernpy/core/tokens.py
172 173 174 175 176 177 178 179 180 181 182 183 184 185 |
|
TokenCategoryHierarchyMapper
Mapping of the TokenCategory hierarchy.
This class is used to define the hierarchy of the TokenCategory. Useful related methods are provided.
Source code in kernpy/core/tokens.py
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 314 315 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 347 348 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 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 |
|
all()
classmethod
Get all categories in the hierarchy.
Returns:
Type | Description |
---|---|
Set[TokenCategory]
|
Set[TokenCategory]: The set of all categories in the hierarchy. |
Source code in kernpy/core/tokens.py
539 540 541 542 543 544 545 546 547 |
|
children(parent)
classmethod
Get the direct children of the parent category.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
parent |
TokenCategory
|
The parent category. |
required |
Returns:
Type | Description |
---|---|
Set[TokenCategory]
|
Set[TokenCategory]: The list of children categories of the parent category. |
Source code in kernpy/core/tokens.py
359 360 361 362 363 364 365 366 367 368 369 370 |
|
is_child(parent, child)
classmethod
Recursively check if child
is in the subtree of parent
. If parent
is the same as child
, return True.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
parent |
TokenCategory
|
The parent category. |
required |
child |
TokenCategory
|
The category to check. |
required |
Returns:
Name | Type | Description |
---|---|---|
bool |
bool
|
True if |
Source code in kernpy/core/tokens.py
343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 |
|
leaves(target)
classmethod
Get the leaves of the subtree of the target category.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
target |
TokenCategory
|
The target category. |
required |
Returns (List[TokenCategory]): The list of leaf categories of the target category.
Source code in kernpy/core/tokens.py
444 445 446 447 448 449 450 451 452 453 454 455 |
|
match(category, *, include=None, exclude=None)
classmethod
Check if the category matches the include and exclude sets. If include is None, all categories are included. If exclude is None, no categories are excluded.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
category |
TokenCategory
|
The category to check. |
required |
include |
Optional[Set[TokenCategory]]
|
The set of categories to include. Defaults to None. If None, all categories are included. |
None
|
exclude |
Optional[Set[TokenCategory]]
|
The set of categories to exclude. Defaults to None. If None, no categories are excluded. |
None
|
Returns (bool): True if the category matches the include and exclude sets, False otherwise.
Examples:
>>> TokenCategoryHierarchyMapper.match(TokenCategory.NOTE, include={TokenCategory.NOTE_REST})
True
>>> TokenCategoryHierarchyMapper.match(TokenCategory.NOTE, include={TokenCategory.NOTE_REST}, exclude={TokenCategory.REST})
True
>>> TokenCategoryHierarchyMapper.match(TokenCategory.NOTE, include={TokenCategory.NOTE_REST}, exclude={TokenCategory.NOTE})
False
>>> TokenCategoryHierarchyMapper.match(TokenCategory.NOTE, include={TokenCategory.CORE}, exclude={TokenCategory.DURATION})
True
>>> TokenCategoryHierarchyMapper.match(TokenCategory.DURATION, include={TokenCategory.CORE}, exclude={TokenCategory.DURATION})
False
Source code in kernpy/core/tokens.py
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 |
|
nodes(parent)
classmethod
Get the all nodes of the subtree of the parent category.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
parent |
TokenCategory
|
The parent category. |
required |
Returns:
Type | Description |
---|---|
Set[TokenCategory]
|
List[TokenCategory]: The list of nodes of the subtree of the parent category. |
Source code in kernpy/core/tokens.py
396 397 398 399 400 401 402 403 404 405 406 407 408 |
|
tree()
classmethod
Return a string representation of the category hierarchy, formatted similar to the output of the Unix 'tree' command.
Example output
. ├── STRUCTURAL ├── CORE │ ├── NOTE_REST │ │ ├── DURATION │ │ ├── NOTE │ │ │ ├── PITCH │ │ │ └── DECORATION │ │ └── REST │ ├── CHORD │ └── EMPTY ├── SIGNATURES │ ├── CLEF │ ├── TIME_SIGNATURE │ ├── METER_SYMBOL │ └── KEY_SIGNATURE ├── ENGRAVED_SYMBOLS ├── OTHER_CONTEXTUAL ├── BARLINES ├── COMMENTS │ ├── FIELD_COMMENTS │ └── LINE_COMMENTS ├── DYNAMICS ├── HARMONY ...
Source code in kernpy/core/tokens.py
549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 |
|
valid(include=None, exclude=None)
classmethod
Get the valid categories based on the include and exclude sets.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
include |
Optional[Set[TokenCategory]]
|
The set of categories to include. Defaults to None. If None, all categories are included. |
None
|
exclude |
Optional[Set[TokenCategory]]
|
The set of categories to exclude. Defaults to None. If None, no categories are excluded. |
None
|
Returns (Set[TokenCategory]): The list of valid categories based on the include and exclude sets.
Source code in kernpy/core/tokens.py
410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 |
|
Tokenizer
Bases: ABC
Tokenizer interface. All tokenizers must implement this interface.
Tokenizers are responsible for converting a token into a string representation.
Source code in kernpy/core/tokenizers.py
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 |
|
__init__(*, token_categories)
Create a new Tokenizer.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
token_categories |
Set[TokenCategory]
|
List of categories to be tokenized. If None, an exception will be raised. |
required |
Source code in kernpy/core/tokenizers.py
54 55 56 57 58 59 60 61 62 63 64 65 |
|
tokenize(token)
abstractmethod
Tokenize a token into a string representation.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
token |
Token
|
Token to be tokenized. |
required |
Returns (str): Tokenized string representation.
Source code in kernpy/core/tokenizers.py
68 69 70 71 72 73 74 75 76 77 78 79 |
|
agnostic_distance(first_pitch, second_pitch)
Calculate the distance in semitones between two pitches.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
first_pitch |
AgnosticPitch
|
The first pitch to compare. |
required |
second_pitch |
AgnosticPitch
|
The second pitch to compare. |
required |
Returns:
Name | Type | Description |
---|---|---|
int |
int
|
The distance in semitones between the two pitches. |
Examples:
>>> agnostic_distance(AgnosticPitch('C4'), AgnosticPitch('E4'))
4
>>> agnostic_distance(AgnosticPitch('C4'), AgnosticPitch('B3'))
-1
Source code in kernpy/core/transposer.py
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 |
|
concat(contents, *, separator='\n')
Concatenate multiple **kern fragments into a single Document object. All the fragments should be presented in order. Each fragment does not need to be a complete **kern file.
Warnings:
Processing a large number of files in a row may take some time.
This method performs as many `kp.read` operations as there are fragments to concatenate.
Args:
contents (Sequence[str]): List of **kern strings
separator (Optional[str]): Separator string to separate the **kern fragments. Default is '
' (newline).
Returns (Tuple[Document, List[Tuple[int, int]]]): Document object and and a List of Pairs (Tuple[int, int]) representing the measure fragment indexes of the concatenated document.
Examples:
>>> import kernpy as kp
>>> contents = ['**kern
4e 4f 4g - ', '4a 4b 4c - = ', '4d 4e 4f *- '] >>> document, indexes = kp.concat(contents) >>> indexes [(0, 3), (3, 6), (6, 9)] >>> document, indexes = kp.concat(contents, separator=' ') >>> indexes [(0, 3), (3, 6), (6, 9)] >>> document, indexes = kp.concat(contents, separator='') >>> indexes [(0, 3), (3, 6), (6, 9)] >>> for start, end in indexes: >>> print(kp.dumps(document, from_measure=start, to_measure=end)))
Source code in kernpy/io/public.py
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 |
|
create(content, strict=False)
Create a Document object from a string encoded in Humdrum **kern format.
Args:
content: String encoded in Humdrum **kern format
strict: If True, raise an error if the **kern file has any errors. Otherwise, return a list of errors.
Returns (Document, list): Document object and list of error messages. Empty list if no errors.
Examples:
>>> import kernpy as kp
>>> document, errors = kp.create('**kern
4e 4f 4g - ') >>> if len(errors) > 0: >>> print(errors) ['Error: Invalid kern spine: 1', 'Error: Invalid *kern spine: 2']
Source code in kernpy/core/generic.py
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 |
|
distance(first_encoding, second_encoding, *, first_format=NotationEncoding.HUMDRUM.value, second_format=NotationEncoding.HUMDRUM.value)
Calculate the distance in semitones between two pitches.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
first_encoding |
str
|
The first pitch to compare. |
required |
second_encoding |
str
|
The second pitch to compare. |
required |
first_format |
str
|
The encoding format of the first pitch. Default is HUMDRUM. |
HUMDRUM.value
|
second_format |
str
|
The encoding format of the second pitch. Default is HUMDRUM. |
HUMDRUM.value
|
Returns:
Name | Type | Description |
---|---|---|
int |
int
|
The distance in semitones between the two pitches. |
Examples:
>>> distance('C4', 'E4')
4
>>> distance('C4', 'B3')
-1
Source code in kernpy/core/transposer.py
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 |
|
download_polish_scores(input_directory, output_directory, remove_empty_directories=True, kern_spines_filter=2, exporter_kern_type='ekern')
Process the files in the input_directory and save the results in the output_directory. http requests are made to download the images.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
input_directory |
str
|
directory where the input files are found |
required |
output_directory |
str
|
directory where the output files are saved |
required |
remove_empty_directories |
Optional[bool]
|
remove empty directories when finish processing the files |
True
|
kern_spines_filter |
Optional[int]
|
Only process files with the number of **kern spines specified. Use it to export 2-voice files. Default is 2. Use None to process all files. |
2
|
exporter_kern_type |
Optional[str]
|
the type of kern exporter. It can be 'krn' or 'ekrn' |
'ekern'
|
Returns:
Type | Description |
---|---|
None
|
None |
Examples:
>>> main('/kern_files', '/output_ekern')
None
>>> main('/kern_files', '/output_ekern', remove_empty_directories=False)
None
>>> main('/kern_files', '/output_ekern', kern_spines_filter=2, remove_empty_directories=False)
None
>>> main('/kern_files', '/output_ekern', kern_spines_filter=None, remove_empty_directories=False)
None
>>> main('/kern_files', '/output_ekern', exporter_kern_type='krn', remove_empty_directories=True)
None
>>> main('/kern_files', '/output_ekern', exporter_kern_type='ekrn', remove_empty_directories=True, kern_spines_filter=2)
None
Source code in kernpy/polish_scores/download_polish_dataset.py
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 314 315 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 347 348 349 350 351 |
|
dump(document, fp, *, spine_types=None, include=None, exclude=None, from_measure=None, to_measure=None, encoding=None, instruments=None, show_measure_numbers=None, spine_ids=None)
Parameters:
Name | Type | Description | Default |
---|---|---|---|
document |
Document
|
The Document object to write to the file. |
required |
fp |
Union[str, Path]
|
The file path to write the Document object. |
required |
spine_types |
Iterable
|
kern, mens, etc... |
None
|
include |
Iterable
|
The token categories to include in the exported file. When None, all the token categories will be exported. |
None
|
exclude |
Iterable
|
The token categories to exclude from the exported file. When None, no token categories will be excluded. |
None
|
from_measure |
int
|
The measure to start exporting. When None, the exporter will start from the beginning of the file. The first measure is 1 |
None
|
to_measure |
int
|
The measure to end exporting. When None, the exporter will end at the end of the file. |
None
|
encoding |
Encoding
|
The type of the **kern file to export. |
None
|
instruments |
Iterable
|
The instruments to export. If None, all the instruments will be exported. |
None
|
show_measure_numbers |
Bool
|
Show the measure numbers in the exported file. |
None
|
spine_ids |
Iterable
|
The ids of the spines to export. When None, all the spines will be exported. Spines ids start from 0, and they are increased by 1 for each spine to the right. |
None
|
Returns (None): None
Raises:
Type | Description |
---|---|
ValueError
|
If the document could not be exported. |
Examples:
>>> import kernpy as kp
>>> document, errors = kp.load('BWV565.krn')
>>> kp.dump(document, 'BWV565_normalized.krn')
None
>>> # File 'BWV565_normalized.krn' will be created with the normalized **kern representation.
Source code in kernpy/io/public.py
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 |
|
dumps(document, *, spine_types=None, include=None, exclude=None, from_measure=None, to_measure=None, encoding=None, instruments=None, show_measure_numbers=None, spine_ids=None)
Args:
document (Document): The Document object to write to the file.
fp (Union[str, Path]): The file path to write the Document object.
spine_types (Iterable): **kern, **mens, etc...
include (Iterable): The token categories to include in the exported file. When None, all the token categories will be exported.
exclude (Iterable): The token categories to exclude from the exported file. When None, no token categories will be excluded.
from_measure (int): The measure to start exporting. When None, the exporter will start from the beginning of the file. The first measure is 1
to_measure (int): The measure to end exporting. When None, the exporter will end at the end of the file.
encoding (Encoding): The type of the **kern file to export.
instruments (Iterable): The instruments to export. If None, all the instruments will be exported.
show_measure_numbers (Bool): Show the measure numbers in the exported file.
spine_ids (Iterable): The ids of the spines to export. When None, all the spines will be exported. Spines ids start from 0, and they are increased by 1 for each spine to the right.
Returns (None): None
Raises:
ValueError: If the document could not be exported.
Examples:
>>> import kernpy as kp
>>> document, errors = kp.load('score.krn')
>>> kp.dumps(document)
'**kern
clefG2 =1 4c 4d 4e 4f -'
Source code in kernpy/io/public.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 190 191 192 193 194 195 196 197 198 199 200 201 202 203 |
|
ekern_to_krn(input_file, output_file)
Convert one .ekrn file to .krn file.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
input_file |
str
|
Filepath to the input **ekern |
required |
output_file |
str
|
Filepath to the output **kern |
required |
Returns: None
Example
Convert .ekrn to .krn
ekern_to_krn('path/to/file.ekrn', 'path/to/file.krn')
Convert a list of .ekrn files to .krn files
ekrn_files = your_modue.get_files()
# Use the wrapper to avoid stopping the process if an error occurs
def ekern_to_krn_wrapper(ekern_file, kern_file):
try:
ekern_to_krn(ekrn_files, output_folder)
except Exception as e:
print(f'Error:{e}')
# Convert all the files
for ekern_file in ekrn_files:
output_file = ekern_file.replace('.ekrn', '.krn')
ekern_to_krn_wrapper(ekern_file, output_file)
Source code in kernpy/core/exporter.py
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 |
|
export(document, options)
Export a Document object to a string.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
document |
Document
|
Document object to export |
required |
options |
ExportOptions
|
Export options |
required |
Returns: Exported string
Examples:
>>> import kernpy as kp
>>> document, errors = kp.read('path/to/file.krn')
>>> options = kp.ExportOptions()
>>> content = kp.export(document, options)
Source code in kernpy/core/generic.py
312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 |
|
get_kern_from_ekern(ekern_content)
Read the content of a ekern file and return the kern content.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
ekern_content |
str
|
The content of the **ekern file. |
required |
Returns: The content of the **kern file.
Example
# Read **ekern file
ekern_file = 'path/to/file.ekrn'
with open(ekern_file, 'r') as file:
ekern_content = file.read()
# Get **kern content
kern_content = get_kern_from_ekern(ekern_content)
with open('path/to/file.krn', 'w') as file:
file.write(kern_content)
Source code in kernpy/core/exporter.py
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 |
|
get_spine_types(document, spine_types=None)
Get the spines of a Document object.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
document |
Document
|
Document object to get spines from |
required |
spine_types |
Optional[Sequence[str]]
|
List of spine types to get. If None, all spines are returned. |
None
|
Returns (List[str]): List of spines
Examples:
>>> import kernpy as kp
>>> document, _ = kp.read('path/to/file.krn')
>>> kp.get_spine_types(document)
['**kern', '**kern', '**kern', '**kern', '**root', '**harm']
>>> kp.get_spine_types(document, None)
['**kern', '**kern', '**kern', '**kern', '**root', '**harm']
>>> kp.get_spine_types(document, ['**kern'])
['**kern', '**kern', '**kern', '**kern']
>>> kp.get_spine_types(document, ['**kern', '**root'])
['**kern', '**kern', '**kern', '**kern', '**root']
>>> kp.get_spine_types(document, ['**kern', '**root', '**harm'])
['**kern', '**kern', '**kern', '**kern', '**root', '**harm']
>>> kp.get_spine_types(document, [])
[]
Source code in kernpy/core/generic.py
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 |
|
graph(document, fp)
Create a graph representation of a Document object using Graphviz. Save the graph as a .dot file or indicate the output file path or stream. If the output file path is None, the function will return the graphviz content as a string to the standard output.
Use the Graphviz software to convert the .dot file to an image.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
document |
Document
|
The Document object to export as a graphviz file. |
required |
fp |
Optional[Union[str, Path]]
|
The file path to write the graphviz file. If None, the function will return the graphviz content as a string to the standard output. |
required |
Returns (None): None
Examples:
>>> import kernpy as kp
>>> document, errors = kp.load('score.krn')
>>> kp.graph(document, 'score.dot')
None
>>> # File 'score.dot' will be created with the graphviz representation of the Document object.
>>> kp.graph(document, None)
'digraph G { ... }'
Source code in kernpy/io/public.py
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 |
|
kern_to_ekern(input_file, output_file)
Convert one .krn file to .ekrn file
Parameters:
Name | Type | Description | Default |
---|---|---|---|
input_file |
str
|
Filepath to the input **kern |
required |
output_file |
str
|
Filepath to the output **ekern |
required |
Returns:
Type | Description |
---|---|
None
|
None |
Example
Convert .krn to .ekrn
kern_to_ekern('path/to/file.krn', 'path/to/file.ekrn')
Convert a list of .krn files to .ekrn files
krn_files = your_module.get_files()
# Use the wrapper to avoid stopping the process if an error occurs
def kern_to_ekern_wrapper(krn_file, ekern_file):
try:
kern_to_ekern(krn_file, ekern_file)
except Exception as e:
print(f'Error:{e}')
# Convert all the files
for krn_file in krn_files:
output_file = krn_file.replace('.krn', '.ekrn')
kern_to_ekern_wrapper(krn_file, output_file)
Source code in kernpy/core/exporter.py
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 |
|
load(fp, *, raise_on_errors=False, **kwargs)
Load a Document object from a Humdrum **kern file-like object.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
fp |
Union[str, Path]
|
A path-like object representing a **kern file. |
required |
raise_on_errors |
Optional[bool]
|
If True, raise an exception if any grammar error is detected during parsing. |
False
|
Returns ((Document, List[str])): A tuple containing the Document object and a list of messages representing grammar errors detected during parsing. If the list is empty, the parsing did not detect any errors.
Raises:
Type | Description |
---|---|
ValueError
|
If the Humdrum **kern representation could not be parsed. |
Examples:
>>> import kernpy as kp
>>> document, errors = kp.load('BWV565.krn')
>>> if len(errors) > 0:
>>> print(f"Grammar didn't recognize the following errors: {errors}")
['Error: Invalid **kern spine: 1', 'Error: Invalid **kern spine: 2']
>>> # Anyway, we can use the Document
>>> print(document)
>>> else:
>>> print(document)
<kernpy.core.document.Document object at 0x7f8b3b7b3d90>
Source code in kernpy/io/public.py
20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 |
|
loads(s, *, raise_on_errors=False, **kwargs)
Load a Document object from a string encoded in Humdrum **kern.
Args:
s (str): A string containing a **kern file.
raise_on_errors (Optional[bool], optional): If True, raise an exception if any grammar error is detected during parsing.
Returns ((Document, List[str])): A tuple containing the Document object and a list of messages representing grammar errors detected during parsing. If the list is empty, the parsing did not detect any errors.
Raises:
ValueError: If the Humdrum **kern representation could not be parsed.
Examples:
>>> import kernpy as kp
>>> document, errors = kp.loads('**kern
clefG2
=1
4c
4d
4e
4f
')
>>> if len(errors) > 0:
>>> print(f"Grammar didn't recognize the following errors: {errors}")
['Error: Invalid *kern spine: 1']
>>> # Anyway, we can use the Document
>>> print(document)
>>> else:
>>> print(document)
Source code in kernpy/io/public.py
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 |
|
merge(contents, *, raise_on_errors=False)
Merge multiple **kern fragments into a single **kern string. All the fragments should be presented in order. Each fragment does not need to be a complete **kern file.
Warnings:
Processing a large number of files in a row may take some time.
This method performs as many `kp.read` operations as there are fragments to concatenate.
Args:
contents (Sequence[str]): List of **kern strings
raise_on_errors (Optional[bool], optional): If True, raise an exception if any grammar error is detected during parsing.
Returns (Tuple[Document, List[Tuple[int, int]]]): Document object and and a List of Pairs (Tuple[int, int]) representing the measure fragment indexes of the concatenated document.
Examples:
>>> import kernpy as kp
>>> contents = ['**kern
4e 4f 4g - -', 'kern 4a 4b 4c - = -', 'kern 4d 4e 4f - -'] >>> document, indexes = kp.concat(contents) >>> indexes [(0, 3), (3, 6), (6, 9)] >>> document, indexes = kp.concat(contents, separator=' ') >>> indexes [(0, 3), (3, 6), (6, 9)] >>> document, indexes = kp.concat(contents, separator='') >>> indexes [(0, 3), (3, 6), (6, 9)] >>> for start, end in indexes: >>> print(kp.dumps(document, from_measure=start, to_measure=end)))
Source code in kernpy/io/public.py
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 314 315 |
|
read(path, strict=False)
Read a Humdrum **kern file.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
path |
Union[str, Path]
|
File path to read |
required |
strict |
Optional[bool]
|
If True, raise an error if the **kern file has any errors. Otherwise, return a list of errors. |
False
|
Returns (Document, List[str]): Document object and list of error messages. Empty list if no errors.
Examples:
>>> import kernpy as kp
>>> document, _ = kp.read('path/to/file.krn')
>>> document, errors = kp.read('path/to/file.krn')
>>> if len(errors) > 0:
>>> print(errors)
['Error: Invalid **kern spine: 1', 'Error: Invalid **kern spine: 2']
Source code in kernpy/core/generic.py
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 |
|
spine_types(document, headers=None)
Get the spines of a Document object.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
document |
Document
|
Document object to get spines from |
required |
headers |
Optional[Sequence[str]]
|
List of spine types to get. If None, all spines are returned. Using a header will return all the spines of that type. |
None
|
Returns (List[str]): List of spines
Examples:
>>> import kernpy as kp
>>> document, _ = kp.read('path/to/file.krn')
>>> kp.spine_types(document)
['**kern', '**kern', '**kern', '**kern', '**root', '**harm']
>>> kp.spine_types(document, None)
['**kern', '**kern', '**kern', '**kern', '**root', '**harm']
>>> kp.spine_types(document, headers=None)
['**kern', '**kern', '**kern', '**kern', '**root', '**harm']
>>> kp.spine_types(document, headers=['**kern'])
['**kern', '**kern', '**kern', '**kern']
>>> kp.spine_types(document, headers=['**kern', '**root'])
['**kern', '**kern', '**kern', '**kern', '**root']
>>> kp.spine_types(document, headers=['**kern', '**root', '**harm'])
['**kern', '**kern', '**kern', '**kern', '**root', '**harm']
>>> kp.spine_types(document, headers=[])
[]
Source code in kernpy/io/public.py
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 347 348 349 350 351 352 353 |
|
store(document, path, options)
Store a Document object to a file.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
document |
Document
|
Document object to store |
required |
path |
Union[str, Path]
|
File path to store |
required |
options |
ExportOptions
|
Export options |
required |
Returns: None
Examples:
>>> import kernpy as kp
>>> document, errors = kp.read('path/to/file.krn')
>>> options = kp.ExportOptions()
>>> kp.store(document, 'path/to/store.krn', options)
Source code in kernpy/core/generic.py
338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 |
|
store_graph(document, path)
Create a graph representation of a Document object using Graphviz. Save the graph to a file.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
document |
Document
|
Document object to create graph from |
required |
path |
str
|
File path to save the graph |
required |
Returns (None): None
Examples:
>>> import kernpy as kp
>>> document, errors = kp.read('path/to/file.krn')
>>> kp.store_graph(document, 'path/to/graph.dot')
Source code in kernpy/core/generic.py
368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 |
|
transpose(input_encoding, interval, input_format=NotationEncoding.HUMDRUM.value, output_format=NotationEncoding.HUMDRUM.value, direction=Direction.UP.value)
Transpose a pitch by a given interval.
The pitch must be in the American notation.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
input_encoding |
str
|
The pitch to transpose. |
required |
interval |
int
|
The interval to transpose the pitch. |
required |
input_format |
str
|
The encoding format of the pitch. Default is HUMDRUM. |
HUMDRUM.value
|
output_format |
str
|
The encoding format of the transposed pitch. Default is HUMDRUM. |
HUMDRUM.value
|
direction |
str
|
The direction of the transposition.'UP' or 'DOWN' Default is 'UP'. |
UP.value
|
Returns:
Name | Type | Description |
---|---|---|
str |
str
|
The transposed pitch. |
Examples:
>>> transpose('ccc', IntervalsByName['P4'], input_format='kern', output_format='kern')
'fff'
>>> transpose('ccc', IntervalsByName['P4'], input_format=NotationEncoding.HUMDRUM.value)
'fff'
>>> transpose('ccc', IntervalsByName['P4'], input_format='kern', direction='down')
'gg'
>>> transpose('ccc', IntervalsByName['P4'], input_format='kern', direction=Direction.DOWN.value)
'gg'
>>> transpose('ccc#', IntervalsByName['P4'])
'fff#'
>>> transpose('G4', IntervalsByName['m3'], input_format='american')
'Bb4'
>>> transpose('G4', IntervalsByName['m3'], input_format=NotationEncoding.AMERICAN.value)
'Bb4'
>>> transpose('C3', IntervalsByName['P4'], input_format='american', direction='down')
'G2'
Source code in kernpy/core/transposer.py
185 186 187 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 |
|
transpose_agnostic_to_encoding(agnostic_pitch, interval, output_format=NotationEncoding.HUMDRUM.value, direction=Direction.UP.value)
Transpose an AgnosticPitch by a given interval.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
agnostic_pitch |
AgnosticPitch
|
The pitch to transpose. |
required |
interval |
int
|
The interval to transpose the pitch. |
required |
output_format |
Optional[str]
|
The encoding format of the transposed pitch. Default is HUMDRUM. |
HUMDRUM.value
|
direction |
Optional[str]
|
The direction of the transposition.'UP' or 'DOWN' Default is 'UP'. |
UP.value
|
Returns (str): str: The transposed pitch.
Examples:
>>> transpose_agnostic_to_encoding(AgnosticPitch('C', 4), IntervalsByName['P4'])
'F4'
>>> transpose_agnostic_to_encoding(AgnosticPitch('C', 4), IntervalsByName['P4'], direction='down')
'G3'
>>> transpose_agnostic_to_encoding(AgnosticPitch('C#', 4), IntervalsByName['P4'])
'F#4'
>>> transpose_agnostic_to_encoding(AgnosticPitch('G', 4), IntervalsByName['m3'], direction='down')
'Bb4'
Source code in kernpy/core/transposer.py
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 |
|
transpose_agnostics(input_pitch, interval, direction=Direction.UP.value)
Transpose an AgnosticPitch by a given interval.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
input_pitch |
AgnosticPitch
|
The pitch to transpose. |
required |
interval |
int
|
The interval to transpose the pitch. |
required |
direction |
str
|
The direction of the transposition. 'UP' or 'DOWN'. Default is 'UP'. |
UP.value
|
Returns
AgnosticPitch: The transposed pitch.
Examples:
>>> transpose_agnostics(AgnosticPitch('C', 4), IntervalsByName['P4'])
AgnosticPitch('F', 4)
>>> transpose_agnostics(AgnosticPitch('C', 4), IntervalsByName['P4'], direction='down')
AgnosticPitch('G', 3)
>>> transpose_agnostics(AgnosticPitch('C#', 4), IntervalsByName['P4'])
AgnosticPitch('F#', 4)
>>> transpose_agnostics(AgnosticPitch('G', 4), IntervalsByName['m3'], direction='down')
AgnosticPitch('Bb', 4)
Source code in kernpy/core/transposer.py
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 |
|
transpose_encoding_to_agnostic(input_encoding, interval, input_format=NotationEncoding.HUMDRUM.value, direction=Direction.UP.value)
Transpose a pitch by a given interval.
The pitch must be in the American notation.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
input_encoding |
str
|
The pitch to transpose. |
required |
interval |
int
|
The interval to transpose the pitch. |
required |
input_format |
str
|
The encoding format of the pitch. Default is HUMDRUM. |
HUMDRUM.value
|
direction |
str
|
The direction of the transposition.'UP' or 'DOWN' Default is 'UP'. |
UP.value
|
Returns:
Name | Type | Description |
---|---|---|
AgnosticPitch |
AgnosticPitch
|
The transposed pitch. |
Examples:
>>> transpose_encoding_to_agnostic('ccc', IntervalsByName['P4'], input_format='kern')
AgnosticPitch('fff', 4)
>>> transpose_encoding_to_agnostic('ccc', IntervalsByName['P4'], input_format=NotationEncoding.HUMDRUM.value)
AgnosticPitch('fff', 4)
>>> transpose_encoding_to_agnostic('ccc', IntervalsByName['P4'], input_format='kern', direction='down')
AgnosticPitch('gg', 3)
>>> transpose_encoding_to_agnostic('ccc#', IntervalsByName['P4'])
AgnosticPitch('fff#', 4)
>>> transpose_encoding_to_agnostic('G4', IntervalsByName['m3'], input_format='american')
AgnosticPitch('Bb4', 4)
>>> transpose_encoding_to_agnostic('C3', IntervalsByName['P4'], input_format='american', direction='down')
AgnosticPitch('G2', 2)
Source code in kernpy/core/transposer.py
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 |
|
Modules
kernpy.core
=====
This module contains the core functionality of the kernpy
package.
Intervals = {-2: 'dd1', -1: 'd1', 0: 'P1', 1: 'A1', 2: 'AA1', 3: 'dd2', 4: 'd2', 5: 'm2', 6: 'M2', 7: 'A2', 8: 'AA2', 9: 'dd3', 10: 'd3', 11: 'm3', 12: 'M3', 13: 'A3', 14: 'AA3', 15: 'dd4', 16: 'd4', 17: 'P4', 18: 'A4', 19: 'AA4', 21: 'dd5', 22: 'd5', 23: 'P5', 24: 'A5', 25: 'AA5', 26: 'dd6', 27: 'd6', 28: 'm6', 29: 'M6', 30: 'A6', 31: 'AA6', 32: 'dd7', 33: 'd7', 34: 'm7', 35: 'M7', 36: 'A7', 37: 'AA7', 40: 'octave'}
module-attribute
Base-40 interval classes (d=diminished, m=minor, M=major, P=perfect, A=augmented)
AbstractToken
Bases: ABC
An abstract base class representing a token.
This class serves as a blueprint for creating various types of tokens, which are categorized based on their TokenCategory.
Attributes:
Name | Type | Description |
---|---|---|
encoding |
str
|
The original representation of the token. |
category |
TokenCategory
|
The category of the token. |
hidden |
bool
|
A flag indicating whether the token is hidden. Defaults to False. |
Source code in kernpy/core/tokens.py
1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 |
|
__eq__(other)
Compare two tokens.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
other |
AbstractToken
|
The other token to compare. |
required |
Returns (bool): True if the tokens are equal, False otherwise.
Source code in kernpy/core/tokens.py
1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 |
|
__hash__()
Returns the hash of the token.
Returns (int): The hash of the token.
Source code in kernpy/core/tokens.py
1462 1463 1464 1465 1466 1467 1468 |
|
__init__(encoding, category)
AbstractToken constructor
Parameters:
Name | Type | Description | Default |
---|---|---|---|
encoding |
str
|
The original representation of the token. |
required |
category |
TokenCategory
|
The category of the token. |
required |
Source code in kernpy/core/tokens.py
1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 |
|
__ne__(other)
Compare two tokens.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
other |
AbstractToken
|
The other token to compare. |
required |
Returns (bool): True if the tokens are different, False otherwise.
Source code in kernpy/core/tokens.py
1452 1453 1454 1455 1456 1457 1458 1459 1460 |
|
__str__()
Returns the string representation of the token.
Returns (str): The string representation of the token without processing.
Source code in kernpy/core/tokens.py
1432 1433 1434 1435 1436 1437 1438 |
|
export(**kwargs)
abstractmethod
Exports the token.
Other Parameters:
Name | Type | Description |
---|---|---|
filter_categories |
Optional[Callable[[TokenCategory], bool]]
|
A function that takes a TokenCategory and returns a boolean indicating whether the token should be included in the export. If provided, only tokens for which the function returns True will be exported. Defaults to None. If None, all tokens will be exported. |
Returns:
Name | Type | Description |
---|---|---|
str |
str
|
The encoded token representation, potentially filtered if a filter_categories function is provided. |
Examples:
>>> token = AbstractToken('*clefF4', TokenCategory.SIGNATURES)
>>> token.export()
'*clefF4'
>>> token.export(filter_categories=lambda cat: cat in {TokenCategory.SIGNATURES, TokenCategory.SIGNATURES.DURATION})
'*clefF4'
Source code in kernpy/core/tokens.py
1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 |
|
AgnosticPitch
Represents a pitch in a generic way, independent of the notation system used.
Source code in kernpy/core/pitch_models.py
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 |
|
__init__(name, octave)
Initialize the AgnosticPitch object.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
name |
str
|
The name of the pitch (e.g., 'C', 'D#', 'Bb'). |
required |
octave |
int
|
The octave of the pitch (e.g., 4 for middle C). |
required |
Source code in kernpy/core/pitch_models.py
85 86 87 88 89 90 91 92 93 94 |
|
Alteration
Bases: Enum
Enum for the alteration of a pitch.
Source code in kernpy/core/gkern.py
35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 |
|
BarToken
Bases: SimpleToken
BarToken class.
Source code in kernpy/core/tokens.py
1645 1646 1647 1648 1649 1650 1651 |
|
BasicSpineImporter
Bases: SpineImporter
Source code in kernpy/core/basic_spine_importer.py
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 36 37 38 39 40 41 42 43 44 45 46 |
|
__init__(verbose=False)
KernSpineImporter constructor.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
verbose |
Optional[bool]
|
Level of verbosity for error messages. |
False
|
Source code in kernpy/core/basic_spine_importer.py
12 13 14 15 16 17 18 19 |
|
BekernTokenizer
Bases: Tokenizer
BekernTokenizer converts a Token into a bekern (Basic Extended **kern) string representation. This format use a '@' separator for the main tokens but discards all the decorations tokens.
Source code in kernpy/core/tokenizers.py
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 |
|
__init__(*, token_categories)
Create a new BekernTokenizer
Parameters:
Name | Type | Description | Default |
---|---|---|---|
token_categories |
Set[TokenCategory]
|
List of categories to be tokenized. If None will raise an exception. |
required |
Source code in kernpy/core/tokenizers.py
153 154 155 156 157 158 159 160 |
|
tokenize(token)
Tokenize a token into a bekern string representation. Args: token (Token): Token to be tokenized.
Returns (str): bekern string representation.
Examples:
>>> token.encoding
'2@.@bb@-·_·L'
>>> BekernTokenizer().tokenize(token)
'2@.@bb@-'
Source code in kernpy/core/tokenizers.py
162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 |
|
BkernTokenizer
Bases: Tokenizer
BkernTokenizer converts a Token into a bkern (Basic kern) string representation. This format use the main tokens but not the decorations tokens. This format is a lightweight version of the classic Humdrum kern format.
Source code in kernpy/core/tokenizers.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 |
|
__init__(*, token_categories)
Create a new BkernTokenizer
Parameters:
Name | Type | Description | Default |
---|---|---|---|
token_categories |
Set[TokenCategory]
|
List of categories to be tokenized. If None will raise an exception. |
required |
Source code in kernpy/core/tokenizers.py
195 196 197 198 199 200 201 202 |
|
tokenize(token)
Tokenize a token into a bkern string representation. Args: token (Token): Token to be tokenized.
Returns (str): bkern string representation.
Examples:
>>> token.encoding
'2@.@bb@-·_·L'
>>> BkernTokenizer().tokenize(token)
'2.bb-'
Source code in kernpy/core/tokenizers.py
205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 |
|
BoundingBox
BoundingBox class.
It contains the coordinates of the score bounding box. Useful for full-page tasks.
Attributes:
Name | Type | Description |
---|---|---|
from_x |
int
|
The x coordinate of the top left corner |
from_y |
int
|
The y coordinate of the top left corner |
to_x |
int
|
The x coordinate of the bottom right corner |
to_y |
int
|
The y coordinate of the bottom right corner |
Source code in kernpy/core/tokens.py
1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 |
|
__init__(x, y, w, h)
BoundingBox constructor.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
x |
int
|
The x coordinate of the top left corner |
required |
y |
int
|
The y coordinate of the top left corner |
required |
w |
int
|
The width |
required |
h |
int
|
The height |
required |
Source code in kernpy/core/tokens.py
1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 |
|
__str__()
Returns a string representation of the bounding box
Returns (str): The string representation of the bounding box
Source code in kernpy/core/tokens.py
1950 1951 1952 1953 1954 1955 1956 |
|
extend(bounding_box)
Extends the bounding box. Modify the current object.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
bounding_box |
BoundingBox
|
The bounding box to extend |
required |
Returns:
Type | Description |
---|---|
None
|
None |
Source code in kernpy/core/tokens.py
1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 |
|
h()
Returns the height of the box
Returns:
Name | Type | Description |
---|---|---|
int |
int
|
The height of the box |
return self.to_y - self.from_y
Source code in kernpy/core/tokens.py
1925 1926 1927 1928 1929 1930 1931 1932 1933 |
|
w()
Returns the width of the box
Returns:
Name | Type | Description |
---|---|---|
int |
int
|
The width of the box |
Source code in kernpy/core/tokens.py
1916 1917 1918 1919 1920 1921 1922 1923 |
|
xywh()
Returns a string representation of the bounding box.
Returns:
Name | Type | Description |
---|---|---|
str |
str
|
The string representation of the bounding box |
Source code in kernpy/core/tokens.py
1958 1959 1960 1961 1962 1963 1964 1965 |
|
BoundingBoxMeasures
BoundingBoxMeasures class.
Source code in kernpy/core/document.py
224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 |
|
__init__(bounding_box, from_measure, to_measure)
Create an instance of BoundingBoxMeasures.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
bounding_box |
The bounding box object of the node. |
required | |
from_measure |
int
|
The first measure of the score in the BoundingBoxMeasures object. |
required |
to_measure |
int
|
The last measure of the score in the BoundingBoxMeasures object. |
required |
Source code in kernpy/core/document.py
229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 |
|
BoundingBoxToken
Bases: Token
BoundingBoxToken class.
It contains the coordinates of the score bounding box. Useful for full-page tasks.
Attributes:
Name | Type | Description |
---|---|---|
encoding |
str
|
The complete unprocessed encoding |
page_number |
int
|
The page number |
bounding_box |
BoundingBox
|
The bounding box |
Source code in kernpy/core/tokens.py
1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 |
|
__init__(encoding, page_number, bounding_box)
BoundingBoxToken constructor.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
encoding |
str
|
The complete unprocessed encoding |
required |
page_number |
int
|
The page number |
required |
bounding_box |
BoundingBox
|
The bounding box |
required |
Source code in kernpy/core/tokens.py
1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 |
|
C1Clef
Bases: Clef
Source code in kernpy/core/gkern.py
391 392 393 394 395 396 397 398 399 400 401 402 |
|
__init__()
Initializes the C Clef object.
Source code in kernpy/core/gkern.py
392 393 394 395 396 |
|
bottom_line()
Returns the pitch of the bottom line of the staff.
Source code in kernpy/core/gkern.py
398 399 400 401 402 |
|
C2Clef
Bases: Clef
Source code in kernpy/core/gkern.py
404 405 406 407 408 409 410 411 412 413 414 415 |
|
__init__()
Initializes the C Clef object.
Source code in kernpy/core/gkern.py
405 406 407 408 409 |
|
bottom_line()
Returns the pitch of the bottom line of the staff.
Source code in kernpy/core/gkern.py
411 412 413 414 415 |
|
C3Clef
Bases: Clef
Source code in kernpy/core/gkern.py
418 419 420 421 422 423 424 425 426 427 428 429 |
|
__init__()
Initializes the C Clef object.
Source code in kernpy/core/gkern.py
419 420 421 422 423 |
|
bottom_line()
Returns the pitch of the bottom line of the staff.
Source code in kernpy/core/gkern.py
425 426 427 428 429 |
|
C4Clef
Bases: Clef
Source code in kernpy/core/gkern.py
431 432 433 434 435 436 437 438 439 440 441 442 |
|
__init__()
Initializes the C Clef object.
Source code in kernpy/core/gkern.py
432 433 434 435 436 |
|
bottom_line()
Returns the pitch of the bottom line of the staff.
Source code in kernpy/core/gkern.py
438 439 440 441 442 |
|
ChordToken
Bases: SimpleToken
ChordToken class.
It contains a list of compound tokens
Source code in kernpy/core/tokens.py
1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 |
|
__init__(encoding, category, notes_tokens)
ChordToken constructor.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
encoding |
str
|
The complete unprocessed encoding |
required |
category |
TokenCategory
|
The token category, one of TokenCategory |
required |
notes_tokens |
Sequence[Token]
|
The subtokens for the notes. Individual elements of the token, of type token |
required |
Source code in kernpy/core/tokens.py
1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 |
|
Clef
Bases: ABC
Abstract class representing a clef.
Source code in kernpy/core/gkern.py
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 314 315 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 347 348 349 |
|
__init__(diatonic_pitch, on_line)
Initializes the Clef object. Args: diatonic_pitch (DiatonicPitch): The diatonic pitch of the clef (e.g., 'C', 'G', 'F'). This value is used as a decorator. on_line (int): The line number on which the clef is placed (1 for bottom line, 2 for 1st line from bottom, etc.). This value is used as a decorator.
Source code in kernpy/core/gkern.py
290 291 292 293 294 295 296 297 298 |
|
__str__()
Returns:
Name | Type | Description |
---|---|---|
str |
str
|
The string representation of the clef. |
Source code in kernpy/core/gkern.py
319 320 321 322 323 324 |
|
bottom_line()
abstractmethod
Returns the pitch of the bottom line of the staff.
Source code in kernpy/core/gkern.py
300 301 302 303 304 305 |
|
name()
Returns the name of the clef.
Source code in kernpy/core/gkern.py
307 308 309 310 311 |
|
reference_point()
Returns the reference point for the clef.
Source code in kernpy/core/gkern.py
313 314 315 316 317 |
|
ClefFactory
Source code in kernpy/core/gkern.py
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 |
|
create_clef(encoding)
classmethod
Creates a Clef object based on the given token.
Clefs are encoded in interpretation tokens that start with a single * followed by the string clef and then the shape and line position of the clef. For example, a treble clef is clefG2, with G meaning a G-clef, and 2 meaning that the clef is centered on the second line up from the bottom of the staff. The bass clef is clefF4 since it is an F-clef on the fourth line of the staff. A vocal tenor clef is represented by clefGv2, where the v means the music should be played an octave lower than the regular clef’s sounding pitches. Try creating a vocal tenor clef in the above interactive example. The v operator also works on the other clefs (but these sorts of clefs are very rare). Another rare clef is clefG^2 which is the opposite of *clefGv2, where the music is written an octave lower than actually sounding pitch for the normal form of the clef. You can also try to create exotic two-octave clefs by doubling the ^^ and vv markers.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
encoding |
str
|
The encoding of the clef token. |
required |
Returns:
Source code in kernpy/core/gkern.py
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 |
|
ClefToken
Bases: SignatureToken
ClefToken class.
Source code in kernpy/core/tokens.py
1663 1664 1665 1666 1667 1668 1669 |
|
ComplexToken
Bases: Token
, ABC
Abstract ComplexToken class. This abstract class ensures that the subclasses implement the export method using the 'filter_categories' parameter to filter the subtokens.
Passing the argument 'filter_categories' by **kwargs don't break the compatibility with parent classes.
Here we're trying to get the Liskov substitution principle done...
Source code in kernpy/core/tokens.py
1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 |
|
__init__(encoding, category)
Constructor for the ComplexToken
Parameters:
Name | Type | Description | Default |
---|---|---|---|
encoding |
str
|
The original representation of the token. |
required |
category |
TokenCategory)
|
The category of the token. |
required |
Source code in kernpy/core/tokens.py
1717 1718 1719 1720 1721 1722 1723 1724 1725 |
|
export(**kwargs)
abstractmethod
Exports the token.
Other Parameters:
Name | Type | Description |
---|---|---|
filter_categories |
Optional[Callable[[TokenCategory], bool]]
|
A function that takes a TokenCategory and returns a boolean indicating whether the token should be included in the export. If provided, only tokens for which the function returns True will be exported. Defaults to None. If None, all tokens will be exported. |
Returns (str): The exported token.
Source code in kernpy/core/tokens.py
1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 |
|
CompoundToken
Bases: ComplexToken
Source code in kernpy/core/tokens.py
1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 |
|
__init__(encoding, category, subtokens)
Parameters:
Name | Type | Description | Default |
---|---|---|---|
encoding |
str
|
The complete unprocessed encoding |
required |
category |
TokenCategory
|
The token category, one of 'TokenCategory' |
required |
subtokens |
List[Subtoken]
|
The individual elements of the token. Also of type 'TokenCategory' but in the hierarchy they must be children of the current token. |
required |
Source code in kernpy/core/tokens.py
1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 |
|
export(**kwargs)
Exports the token.
Other Parameters:
Name | Type | Description |
---|---|---|
filter_categories |
Optional[Callable[[TokenCategory], bool]]
|
A function that takes a TokenCategory and returns a boolean indicating whether the token should be included in the export. If provided, only tokens for which the function returns True will be exported. Defaults to None. If None, all tokens will be exported. |
Returns (str): The exported token.
Source code in kernpy/core/tokens.py
1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 |
|
Document
Document class.
This class store the score content using an agnostic tree structure.
Attributes:
Name | Type | Description |
---|---|---|
tree |
MultistageTree
|
The tree structure of the document where all the nodes are stored. Each stage of the tree corresponds to a row in the Humdrum **kern file encoding. |
measure_start_tree_stages |
List[List[Node]]
|
The list of nodes that corresponds to the measures. Empty list by default. The index of the list is starting from 1. Rows after removing empty lines and line comments |
page_bounding_boxes |
Dict[int, BoundingBoxMeasures]
|
The dictionary of page bounding boxes. - key: page number - value: BoundingBoxMeasures object |
header_stage |
int
|
The index of the stage that contains the headers. None by default. |
Source code in kernpy/core/document.py
338 339 340 341 342 343 344 345 346 347 348 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 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 |
|
__init__(tree)
Constructor for Document class.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
tree |
MultistageTree
|
The tree structure of the document where all the nodes are stored. |
required |
Source code in kernpy/core/document.py
356 357 358 359 360 361 362 363 364 365 366 |
|
__iter__()
Get the indexes to export all the document.
Returns: An iterator with the indexes to export the document.
Source code in kernpy/core/document.py
882 883 884 885 886 887 888 |
|
__next__()
Get the next index to export the document.
Returns: The next index to export the document.
Source code in kernpy/core/document.py
890 891 892 893 894 895 896 |
|
add(other, *, check_core_spines_only=False)
Concatenate one document to the current document: Modify the current object!
Parameters:
Name | Type | Description | Default |
---|---|---|---|
other |
'Document'
|
The document to concatenate. |
required |
check_core_spines_only |
Optional[bool]
|
If True, only the core spines (kern and mens) are checked. If False, all spines are checked. |
False
|
Returns ('Document'): The current document (self) with the other document concatenated.
Source code in kernpy/core/document.py
638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 |
|
append_spines(spines)
Append the spines directly to current document tree.
Args:
spines(list): A list of spines to append.
Returns: None
Examples:
>>> import kernpy as kp
>>> doc, _ = kp.read('score.krn')
>>> spines = [
>>> '4e 4f 4g 4a
4b 4c 4d 4e = = = = ', >>> '4c 4d 4e 4f 4g 4a 4b 4c = = = = ', >>> ] >>> doc.append_spines(spines) None
Source code in kernpy/core/document.py
612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 |
|
clone()
Create a deep copy of the Document instance.
Returns: A new instance of Document with the tree copied.
Source code in kernpy/core/document.py
598 599 600 601 602 603 604 605 606 607 608 609 610 |
|
frequencies(token_categories=None)
Frequency of tokens in the document.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
token_categories |
Optional[Sequence[TokenCategory]]
|
If None, all tokens are considered. |
None
|
Returns (Dict): A dictionary with the category and the number of occurrences of each token.
Source code in kernpy/core/document.py
701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 |
|
get_all_tokens(filter_by_categories=None)
Parameters:
Name | Type | Description | Default |
---|---|---|---|
filter_by_categories |
Optional[Sequence[TokenCategory]]
|
A list of categories to filter the tokens. If None, all tokens are returned. |
None
|
Returns:
Type | Description |
---|---|
List[AbstractToken]
|
List[AbstractToken] - A list of all tokens. |
Examples:
>>> tokens = document.get_all_tokens()
>>> Document.tokens_to_encodings(tokens)
>>> [type(t) for t in tokens]
[<class 'kernpy.core.token.Token'>, <class 'kernpy.core.token.Token'>, <class 'kernpy.core.token.Token'>]
Source code in kernpy/core/document.py
500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 |
|
get_all_tokens_encodings(filter_by_categories=None)
Parameters:
Name | Type | Description | Default |
---|---|---|---|
filter_by_categories |
Optional[Sequence[TokenCategory]]
|
A list of categories to filter the tokens. If None, all tokens are returned. |
None
|
Returns:
Type | Description |
---|---|
List[str]
|
list[str] - A list of all token encodings. |
Examples:
>>> tokens = document.get_all_tokens_encodings()
>>> Document.tokens_to_encodings(tokens)
['!!!COM: Coltrane', '!!!voices: 1', '!!!OPR: Blue Train']
Source code in kernpy/core/document.py
519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 |
|
get_first_measure()
Get the index of the first measure of the document.
Returns: (Int) The index of the first measure of the document.
Raises: Exception - If the document has no measures.
Examples:
>>> import kernpy as kp
>>> document, err = kp.read('score.krn')
>>> document.get_first_measure()
1
Source code in kernpy/core/document.py
399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 |
|
get_header_nodes()
Get the header nodes of the current document.
Returns: List[HeaderToken]: A list with the header nodes of the current document.
Source code in kernpy/core/document.py
680 681 682 683 684 685 686 |
|
get_header_stage()
Get the Node list of the header stage.
Returns: (Union[List[Node], List[List[Node]]]) The Node list of the header stage.
Raises: Exception - If the document has no header stage.
Source code in kernpy/core/document.py
370 371 372 373 374 375 376 377 378 379 380 381 |
|
get_leaves()
Get the leaves of the tree.
Returns: (List[Node]) The leaves of the tree.
Source code in kernpy/core/document.py
383 384 385 386 387 388 389 |
|
get_metacomments(KeyComment=None, clear=False)
Get all metacomments in the document
Parameters:
Name | Type | Description | Default |
---|---|---|---|
KeyComment |
Optional[str]
|
Filter by a specific metacomment key: e.g. Use 'COM' to get only comments starting with '!!!COM: '. If None, all metacomments are returned. |
None
|
clear |
bool
|
If True, the metacomment key is removed from the comment. E.g. '!!!COM: Coltrane' -> 'Coltrane'. If False, the metacomment key is kept. E.g. '!!!COM: Coltrane' -> '!!!COM: Coltrane'. The clear functionality is equivalent to the following code:
Other formats are not supported. |
False
|
Returns: A list of metacomments.
Examples:
>>> document.get_metacomments()
['!!!COM: Coltrane', '!!!voices: 1', '!!!OPR: Blue Train']
>>> document.get_metacomments(KeyComment='COM')
['!!!COM: Coltrane']
>>> document.get_metacomments(KeyComment='COM', clear=True)
['Coltrane']
>>> document.get_metacomments(KeyComment='non_existing_key')
[]
Source code in kernpy/core/document.py
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 |
|
get_spine_count()
Get the number of spines in the document.
Returns (int): The number of spines in the document.
Source code in kernpy/core/document.py
391 392 393 394 395 396 397 |
|
get_spine_ids()
Get the indexes of the current document.
Returns List[int]: A list with the indexes of the current document.
Examples:
>>> document.get_all_spine_indexes()
[0, 1, 2, 3, 4]
Source code in kernpy/core/document.py
688 689 690 691 692 693 694 695 696 697 698 699 |
|
get_unique_token_encodings(filter_by_categories=None)
Get unique token encodings.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
filter_by_categories |
Optional[Sequence[TokenCategory]]
|
A list of categories to filter the tokens. If None, all tokens are returned. |
None
|
Returns: List[str] - A list of unique token encodings.
Source code in kernpy/core/document.py
558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 |
|
get_unique_tokens(filter_by_categories=None)
Get unique tokens.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
filter_by_categories |
Optional[Sequence[TokenCategory]]
|
A list of categories to filter the tokens. If None, all tokens are returned. |
None
|
Returns:
Type | Description |
---|---|
List[AbstractToken]
|
List[AbstractToken] - A list of unique tokens. |
Source code in kernpy/core/document.py
539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 |
|
get_voices(clean=False)
Get the voices of the document.
Args clean (bool): Remove the first '!' from the voice name.
Returns: A list of voices.
Examples:
>>> document.get_voices()
['!sax', '!piano', '!bass']
>>> document.get_voices(clean=True)
['sax', 'piano', 'bass']
>>> document.get_voices(clean=False)
['!sax', '!piano', '!bass']
Source code in kernpy/core/document.py
574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 |
|
match(a, b, *, check_core_spines_only=False)
classmethod
Match two documents. Two documents match if they have the same spine structure.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
a |
Document
|
The first document. |
required |
b |
Document
|
The second document. |
required |
check_core_spines_only |
Optional[bool]
|
If True, only the core spines (kern and mens) are checked. If False, all spines are checked. |
False
|
Returns: True if the documents match, False otherwise.
Examples:
Source code in kernpy/core/document.py
786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 |
|
measures_count()
Get the index of the last measure of the document.
Returns: (Int) The index of the last measure of the document.
Raises: Exception - If the document has no measures.
Examples:
>>> document, _ = kernpy.read('score.krn')
>>> document.measures_count()
10
>>> for i in range(document.get_first_measure(), document.measures_count() + 1):
>>> options = kernpy.ExportOptions(from_measure=i, to_measure=i+4)
Source code in kernpy/core/document.py
418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 |
|
split()
Split the current document into a list of documents, one for each kern spine. Each resulting document will contain one kern spine along with all non-kern spines.
Returns:
Type | Description |
---|---|
List['Document']
|
List['Document']: A list of documents, where each document contains one **kern spine |
List['Document']
|
and all non-kern spines from the original document. |
Examples:
>>> document.split()
[<Document: score.krn>, <Document: score.krn>, <Document: score.krn>]
Source code in kernpy/core/document.py
725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 |
|
to_concat(first_doc, second_doc, deep_copy=True)
classmethod
Concatenate two documents.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
first_doc |
Document
|
The first document. |
required |
second_doc |
Document
|
The second document. |
required |
deep_copy |
bool
|
If True, the documents are deep copied. If False, the documents are shallow copied. |
True
|
Returns: A new instance of Document with the documents concatenated.
Source code in kernpy/core/document.py
768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 |
|
to_transposed(interval, direction=Direction.UP.value)
Create a new document with the transposed notes without modifying the original document.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
interval |
str
|
The name of the interval to transpose. It can be 'P4', 'P5', 'M2', etc. Check the kp.AVAILABLE_INTERVALS for the available intervals. |
required |
direction |
str
|
The direction to transpose. It can be 'up' or 'down'. |
UP.value
|
Returns:
Source code in kernpy/core/document.py
809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 |
|
tokens_to_encodings(tokens)
classmethod
Get the encodings of a list of tokens.
The method is equivalent to the following code
tokens = kp.get_all_tokens() [token.encoding for token in tokens if token.encoding is not None]
Parameters:
Name | Type | Description | Default |
---|---|---|---|
tokens |
Sequence[AbstractToken]
|
list - A list of tokens. |
required |
Returns: List[str] - A list of token encodings.
Examples:
>>> tokens = document.get_all_tokens()
>>> Document.tokens_to_encodings(tokens)
['!!!COM: Coltrane', '!!!voices: 1', '!!!OPR: Blue Train']
Source code in kernpy/core/document.py
478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 |
|
Duration
Bases: ABC
Represents the duration of a note or a rest.
The duration is represented using the Humdrum Kern format. The duration is a number that represents the number of units of the duration.
The duration of a whole note is 1, half note is 2, quarter note is 4, eighth note is 8, etc.
The duration of a note is represented by a number. The duration of a rest is also represented by a number.
This class do not limit the duration ranges.
In the following example, the duration is represented by the number '2'.
**kern
*clefG2
2c // whole note
4c // half note
8c // quarter note
16c // eighth note
*-
Source code in kernpy/core/tokens.py
970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 |
|
DurationClassical
Bases: Duration
Represents the duration in classical notation of a note or a rest.
Source code in kernpy/core/tokens.py
1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 |
|
__eq__(other)
Compare two durations.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
other |
DurationClassical
|
The other duration to compare |
required |
Returns (bool): True if the durations are equal, False otherwise
Examples:
>>> duration = DurationClassical(2)
>>> duration2 = DurationClassical(2)
>>> duration == duration2
True
>>> duration = DurationClassical(2)
>>> duration2 = DurationClassical(4)
>>> duration == duration2
False
Source code in kernpy/core/tokens.py
1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 |
|
__ge__(other)
Compare two durations.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
other |
DurationClassical
|
The other duration to compare |
required |
Returns (bool): True if this duration is higher or equal than the other, False otherwise
Examples:
>>> duration = DurationClassical(2)
>>> duration2 = DurationClassical(4)
>>> duration >= duration2
False
>>> duration = DurationClassical(4)
>>> duration2 = DurationClassical(2)
>>> duration >= duration2
True
>>> duration = DurationClassical(4)
>>> duration2 = DurationClassical(4)
>>> duration >= duration2
True
Source code in kernpy/core/tokens.py
1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 |
|
__gt__(other)
Compare two durations.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
other |
'DurationClassical'
|
The other duration to compare |
required |
Returns (bool): True if this duration is higher than the other, False otherwise
Examples:
>>> duration = DurationClassical(2)
>>> duration2 = DurationClassical(4)
>>> duration > duration2
False
>>> duration = DurationClassical(4)
>>> duration2 = DurationClassical(2)
>>> duration > duration2
True
>>> duration = DurationClassical(4)
>>> duration2 = DurationClassical(4)
>>> duration > duration2
False
Source code in kernpy/core/tokens.py
1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 |
|
__init__(duration)
Create a new Duration object.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
duration |
str
|
duration representation in Humdrum Kern format |
required |
Examples:
>>> duration = DurationClassical(2)
True
>>> duration = DurationClassical(4)
True
>>> duration = DurationClassical(32)
True
>>> duration = DurationClassical(1)
True
>>> duration = DurationClassical(0)
False
>>> duration = DurationClassical(-2)
False
>>> duration = DurationClassical(3)
False
>>> duration = DurationClassical(7)
False
Source code in kernpy/core/tokens.py
1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 |
|
__le__(other)
Compare two durations.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
other |
DurationClassical
|
The other duration to compare |
required |
Returns:
Type | Description |
---|---|
bool
|
True if this duration is lower or equal than the other, False otherwise |
Examples:
>>> duration = DurationClassical(2)
>>> duration2 = DurationClassical(4)
>>> duration <= duration2
True
>>> duration = DurationClassical(4)
>>> duration2 = DurationClassical(2)
>>> duration <= duration2
False
>>> duration = DurationClassical(4)
>>> duration2 = DurationClassical(4)
>>> duration <= duration2
True
Source code in kernpy/core/tokens.py
1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 |
|
__lt__(other)
Compare two durations.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
other |
DurationClassical
|
The other duration to compare |
required |
Returns (bool): True if this duration is lower than the other, False otherwise
Examples:
>>> duration = DurationClassical(2)
>>> duration2 = DurationClassical(4)
>>> duration < duration2
True
>>> duration = DurationClassical(4)
>>> duration2 = DurationClassical(2)
>>> duration < duration2
False
>>> duration = DurationClassical(4)
>>> duration2 = DurationClassical(4)
>>> duration < duration2
False
Source code in kernpy/core/tokens.py
1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 |
|
__ne__(other)
Compare two durations.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
other |
DurationClassical
|
The other duration to compare |
required |
Returns (bool): True if the durations are different, False otherwise
Examples:
>>> duration = DurationClassical(2)
>>> duration2 = DurationClassical(2)
>>> duration != duration2
False
>>> duration = DurationClassical(2)
>>> duration2 = DurationClassical(4)
>>> duration != duration2
True
Source code in kernpy/core/tokens.py
1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 |
|
modify(ratio)
Modify the duration of a note or a rest of the current object.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
ratio |
int
|
The factor to modify the duration. The factor must be greater than 0. |
required |
Returns (DurationClassical): The new duration object with the modified duration.
Examples:
>>> duration = DurationClassical(2)
>>> new_duration = duration.modify(2)
>>> new_duration.duration
4
>>> duration = DurationClassical(2)
>>> new_duration = duration.modify(0)
Traceback (most recent call last):
...
ValueError: Invalid factor provided: 0. The factor must be greater than 0.
>>> duration = DurationClassical(2)
>>> new_duration = duration.modify(-2)
Traceback (most recent call last):
...
ValueError: Invalid factor provided: -2. The factor must be greater than 0.
Source code in kernpy/core/tokens.py
1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 |
|
DurationMensural
Bases: Duration
Represents the duration in mensural notation of a note or a rest.
Source code in kernpy/core/tokens.py
1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 |
|
DynSpineImporter
Bases: SpineImporter
Source code in kernpy/core/dyn_importer.py
11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
|
__init__(verbose=False)
KernSpineImporter constructor.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
verbose |
Optional[bool]
|
Level of verbosity for error messages. |
False
|
Source code in kernpy/core/dyn_importer.py
12 13 14 15 16 17 18 19 |
|
DynamSpineImporter
Bases: SpineImporter
Source code in kernpy/core/dynam_spine_importer.py
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 36 37 38 39 40 41 42 43 44 |
|
__init__(verbose=False)
KernSpineImporter constructor.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
verbose |
Optional[bool]
|
Level of verbosity for error messages. |
False
|
Source code in kernpy/core/dynam_spine_importer.py
11 12 13 14 15 16 17 18 |
|
EkernTokenizer
Bases: Tokenizer
EkernTokenizer converts a Token into an eKern (Extended **kern) string representation. This format use a '@' separator for the main tokens and a '·' separator for the decorations tokens.
Source code in kernpy/core/tokenizers.py
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 |
|
__init__(*, token_categories)
Create a new EkernTokenizer
Parameters:
Name | Type | Description | Default |
---|---|---|---|
token_categories |
List[TokenCategory]
|
List of categories to be tokenized. If None will raise an exception. |
required |
Source code in kernpy/core/tokenizers.py
120 121 122 123 124 125 126 127 |
|
tokenize(token)
Tokenize a token into an eKern string representation. Args: token (Token): Token to be tokenized.
Returns (str): eKern string representation.
Examples:
>>> token.encoding
'2@.@bb@-·_·L'
>>> EkernTokenizer().tokenize(token)
'2@.@bb@-·_·L'
Source code in kernpy/core/tokenizers.py
129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 |
|
Encoding
Bases: Enum
Options for exporting a kern file.
Example
import kernpy as kp
Load a file
doc, _ = kp.load('path/to/file.krn')
Save the file using the specified encoding
exported_content = kp.dumps(encoding=kp.Encoding.normalizedKern)
Source code in kernpy/core/tokenizers.py
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 36 37 38 39 40 41 42 43 44 45 |
|
prefix()
Get the prefix of the kern type.
Returns (str): Prefix of the kern type.
Source code in kernpy/core/tokenizers.py
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
|
ErrorListener
Bases: ConsoleErrorListener
Source code in kernpy/core/error_listener.py
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 |
|
__init__(*, verbose=False)
ErrorListener constructor.
Args:
verbose (bool): If True, the error messages will be printed to the console using the ConsoleErrorListener
interface.
Source code in kernpy/core/error_listener.py
27 28 29 30 31 32 33 34 35 36 |
|
ErrorToken
Bases: SimpleToken
Used to wrap tokens that have not been parsed.
Source code in kernpy/core/tokens.py
1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 |
|
__init__(encoding, line, error)
ErrorToken constructor
Parameters:
Name | Type | Description | Default |
---|---|---|---|
encoding |
str
|
The original representation of the token. |
required |
line |
int
|
The line number of the token in the score. |
required |
error |
str
|
The error message thrown by the parser. |
required |
Source code in kernpy/core/tokens.py
1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 |
|
__str__()
Information about the error token.
Returns (str) The information about the error token.
Source code in kernpy/core/tokens.py
1532 1533 1534 1535 1536 1537 1538 |
|
export(**kwargs)
Exports the error token.
Returns (str): A string representation of the error token.
Source code in kernpy/core/tokens.py
1523 1524 1525 1526 1527 1528 1529 1530 |
|
ExportOptions
ExportOptions
class.
Store the options to export a **kern file.
Source code in kernpy/core/exporter.py
15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 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 |
|
__eq__(other)
Compare two ExportOptions objects.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
other |
'ExportOptions'
|
The other ExportOptions object to compare. |
required |
Returns (bool): True if the objects are equal, False otherwise.
Examples:
>>> options1 = ExportOptions(spine_types=['**kern'], token_categories=BEKERN_CATEGORIES)
>>> options2 = ExportOptions(spine_types=['**kern'], token_categories=BEKERN_CATEGORIES)
>>> options1 == options2
True
>>> options3 = ExportOptions(spine_types=['**kern', '**harm'], token_categories=BEKERN_CATEGORIES)
>>> options1 == options3
False
Source code in kernpy/core/exporter.py
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 |
|
__init__(spine_types=None, token_categories=None, from_measure=None, to_measure=None, kern_type=Encoding.normalizedKern, instruments=None, show_measure_numbers=False, spine_ids=None)
Create a new ExportOptions object.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
spine_types |
Iterable
|
kern, mens, etc... |
None
|
token_categories |
Iterable
|
TokenCategory |
None
|
from_measure |
int
|
The measure to start exporting. When None, the exporter will start from the beginning of the file. The first measure is 1 |
None
|
to_measure |
int
|
The measure to end exporting. When None, the exporter will end at the end of the file. |
None
|
kern_type |
Encoding
|
The type of the kern file to export. |
normalizedKern
|
instruments |
Iterable
|
The instruments to export. When None, all the instruments will be exported. |
None
|
show_measure_numbers |
Bool
|
Show the measure numbers in the exported file. |
False
|
spine_ids |
Iterable
|
The ids of the spines to export. When None, all the spines will be exported. Spines ids start from 0 and they are increased by 1. |
None
|
Example
import kernpy
Create the importer and read the file
hi = Importer() document = hi.import_file('file.krn') exporter = Exporter()
Export the file with the specified options
options = ExportOptions(spine_types=['**kern'], token_categories=BEKERN_CATEGORIES) exported_data = exporter.export_string(document, options)
Export only the lyrics
options = ExportOptions(spine_types=['**kern'], token_categories=[TokenCategory.LYRICS]) exported_data = exporter.export_string(document, options)
Export the comments
options = ExportOptions(spine_types=['**kern'], token_categories=[TokenCategory.LINE_COMMENTS, TokenCategory.FIELD_COMMENTS]) exported_data = exporter.export_string(document, options)
Export using the eKern version
options = ExportOptions(spine_types=['**kern'], token_categories=BEKERN_CATEGORIES, kern_type=Encoding.eKern) exported_data = exporter.export_string(document, options)
Source code in kernpy/core/exporter.py
22 23 24 25 26 27 28 29 30 31 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 |
|
__ne__(other)
Compare two ExportOptions objects.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
other |
ExportOptions
|
The other ExportOptions object to compare. |
required |
Returns (bool): True if the objects are not equal, False otherwise.
Examples:
>>> options1 = ExportOptions(spine_types=['**kern'], token_categories=BEKERN_CATEGORIES)
>>> options2 = ExportOptions(spine_types=['**kern'], token_categories=BEKERN_CATEGORIES)
>>> options1 != options2
False
>>> options3 = ExportOptions(spine_types=['**kern', '**harm'], token_categories=BEKERN_CATEGORIES)
>>> options1 != options3
True
Source code in kernpy/core/exporter.py
109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 |
|
Exporter
Source code in kernpy/core/exporter.py
183 184 185 186 187 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 314 315 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 347 348 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 |
|
append_row(document, node, options, row)
Append a row to the row list if the node accomplishes the requirements. Args: document (Document): The document with the spines. node (Node): The node to append. options (ExportOptions): The export options to filter the token. row (list): The row to append.
Returns (bool): True if the row was appended. False if the row was not appended.
Source code in kernpy/core/exporter.py
311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 |
|
compute_header_type(node)
Compute the header type of the node.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
node |
Node
|
The node to compute. |
required |
Returns (Optional[Token]): The header type Node
object. None if the current node is the header.
Source code in kernpy/core/exporter.py
284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 |
|
export_options_validator(document, options)
classmethod
Validate the export options. Raise an exception if the options are invalid.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
document |
Document
|
|
required |
options |
ExportOptions
|
|
required |
Returns: None
Example
export_options_validator(document, options) ValueError: option from_measure must be >=0 but -1 was found. export_options_validator(document, options2) None
Source code in kernpy/core/exporter.py
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 |
|
get_spine_types(document, spine_types=None)
Get the spine types from the document.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
document |
Document
|
The document with the spines. |
required |
spine_types |
list
|
The spine types to export. If None, all the spine types will be exported. |
None
|
Returns: A list with the spine types.
Examples:
>>> exporter = Exporter()
>>> exporter.get_spine_types(document)
['**kern', '**kern', '**kern', '**kern', '**root', '**harm']
>>> exporter.get_spine_types(document, None)
['**kern', '**kern', '**kern', '**kern', '**root', '**harm']
>>> exporter.get_spine_types(document, ['**kern'])
['**kern', '**kern', '**kern', '**kern']
>>> exporter.get_spine_types(document, ['**kern', '**root'])
['**kern', '**kern', '**kern', '**kern', '**root']
>>> exporter.get_spine_types(document, ['**kern', '**root', '**harm'])
['**kern', '**kern', '**kern', '**kern', '**root', '**harm']
>>> exporter.get_spine_types(document, [])
[]
Source code in kernpy/core/exporter.py
336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 |
|
F3Clef
Bases: Clef
Source code in kernpy/core/gkern.py
365 366 367 368 369 370 371 372 373 374 375 376 |
|
__init__()
Initializes the F Clef object.
Source code in kernpy/core/gkern.py
366 367 368 369 370 |
|
bottom_line()
Returns the pitch of the bottom line of the staff.
Source code in kernpy/core/gkern.py
372 373 374 375 376 |
|
F4Clef
Bases: Clef
Source code in kernpy/core/gkern.py
378 379 380 381 382 383 384 385 386 387 388 389 |
|
__init__()
Initializes the F Clef object.
Source code in kernpy/core/gkern.py
379 380 381 382 383 |
|
bottom_line()
Returns the pitch of the bottom line of the staff.
Source code in kernpy/core/gkern.py
385 386 387 388 389 |
|
FieldCommentToken
Bases: SimpleToken
FieldCommentToken class stores the metacomments of the score.
Usually these are comments starting with !!!
.
Source code in kernpy/core/tokens.py
1575 1576 1577 1578 1579 1580 1581 1582 1583 |
|
FingSpineImporter
Bases: SpineImporter
Source code in kernpy/core/fing_spine_importer.py
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 36 37 38 39 40 41 42 43 44 45 |
|
__init__(verbose=False)
KernSpineImporter constructor.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
verbose |
Optional[bool]
|
Level of verbosity for error messages. |
False
|
Source code in kernpy/core/fing_spine_importer.py
11 12 13 14 15 16 17 18 |
|
GClef
Bases: Clef
Source code in kernpy/core/gkern.py
352 353 354 355 356 357 358 359 360 361 362 363 |
|
__init__()
Initializes the G Clef object.
Source code in kernpy/core/gkern.py
353 354 355 356 357 |
|
bottom_line()
Returns the pitch of the bottom line of the staff.
Source code in kernpy/core/gkern.py
359 360 361 362 363 |
|
GKernExporter
Source code in kernpy/core/gkern.py
508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 |
|
agnostic_position(staff, pitch)
Returns the agnostic position in staff for the given pitch.
Source code in kernpy/core/gkern.py
519 520 521 522 523 |
|
export(staff, pitch)
Exports the given pitch to a graphic **kern encoding.
Source code in kernpy/core/gkern.py
512 513 514 515 516 517 |
|
Generic
Generic class.
This class provides support to the public API for KernPy.
The main functions implementation are provided here.
Source code in kernpy/core/generic.py
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 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 186 187 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 |
|
concat(contents, separator=None)
classmethod
Parameters:
Name | Type | Description | Default |
---|---|---|---|
contents |
Sequence[str]
|
|
required |
separator |
Optional[str]
|
|
None
|
Returns:
Source code in kernpy/core/generic.py
182 183 184 185 186 187 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 |
|
create(content, strict=False)
classmethod
Parameters:
Name | Type | Description | Default |
---|---|---|---|
content |
str
|
|
required |
strict |
Optional[bool]
|
|
False
|
Returns:
Source code in kernpy/core/generic.py
50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 |
|
export(document, options)
classmethod
Parameters:
Name | Type | Description | Default |
---|---|---|---|
document |
Document
|
|
required |
options |
ExportOptions
|
|
required |
Returns:
Source code in kernpy/core/generic.py
74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 |
|
get_spine_types(document, spine_types=None)
classmethod
Parameters:
Name | Type | Description | Default |
---|---|---|---|
document |
Document
|
|
required |
spine_types |
Optional[Sequence[str]]
|
|
None
|
Returns:
Source code in kernpy/core/generic.py
128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 |
|
merge(contents, strict=False)
classmethod
Parameters:
Name | Type | Description | Default |
---|---|---|---|
contents |
Sequence[str]
|
|
required |
strict |
Optional[bool]
|
|
False
|
Returns:
Source code in kernpy/core/generic.py
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 |
|
parse_options_to_ExportOptions(**kwargs)
classmethod
Parameters:
Name | Type | Description | Default |
---|---|---|---|
**kwargs |
Any
|
|
{}
|
Returns:
Source code in kernpy/core/generic.py
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 |
|
read(path, strict=False)
classmethod
Parameters:
Name | Type | Description | Default |
---|---|---|---|
path |
Path
|
|
required |
strict |
Optional[bool]
|
|
False
|
Returns:
Source code in kernpy/core/generic.py
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 |
|
store(document, path, options)
classmethod
Parameters:
Name | Type | Description | Default |
---|---|---|---|
document |
Document
|
|
required |
path |
Path
|
|
required |
options |
ExportOptions
|
|
required |
Returns:
Source code in kernpy/core/generic.py
92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 |
|
store_graph(document, path)
classmethod
Parameters:
Name | Type | Description | Default |
---|---|---|---|
document |
Document
|
|
required |
path |
Path
|
|
required |
Returns:
Source code in kernpy/core/generic.py
111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 |
|
GraphvizExporter
Source code in kernpy/core/graphviz_exporter.py
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 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 |
|
export_to_dot(tree, filename=None)
Export the given MultistageTree to DOT format.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
tree |
MultistageTree
|
The tree to export. |
required |
filename |
Path or None
|
The output file path. If None, prints to stdout. |
None
|
Source code in kernpy/core/graphviz_exporter.py
22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 |
|
HarmSpineImporter
Bases: SpineImporter
Source code in kernpy/core/harm_spine_importer.py
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 36 37 38 39 40 41 42 43 44 |
|
__init__(verbose=False)
KernSpineImporter constructor.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
verbose |
Optional[bool]
|
Level of verbosity for error messages. |
False
|
Source code in kernpy/core/harm_spine_importer.py
11 12 13 14 15 16 17 18 |
|
HeaderToken
Bases: SimpleToken
HeaderTokens class.
Source code in kernpy/core/tokens.py
1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 |
|
__init__(encoding, spine_id)
Constructor for the HeaderToken class.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
encoding |
str
|
The original representation of the token. |
required |
spine_id |
int
|
The spine id of the token. The spine id is used to identify the token in the score. The spine_id starts from 0 and increases by 1 for each new spine like the following example: kern kern kern dyn **text 0 1 2 3 4 |
required |
Source code in kernpy/core/tokens.py
1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 |
|
HeaderTokenGenerator
HeaderTokenGenerator class.
This class is used to translate the HeaderTokens to the specific encoding format.
Source code in kernpy/core/exporter.py
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 |
|
new(*, token, type)
classmethod
Create a new HeaderTokenGenerator object. Only accepts stardized Humdrum **kern encodings.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
token |
HeaderToken
|
The HeaderToken to be translated. |
required |
type |
Encoding
|
The encoding to be used. |
required |
Examples:
>>> header = HeaderToken('**kern', 0)
>>> header.encoding
'**kern'
>>> new_header = HeaderTokenGenerator.new(token=header, type=Encoding.eKern)
>>> new_header.encoding
'**ekern'
Source code in kernpy/core/exporter.py
158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 |
|
HumdrumPitchImporter
Bases: PitchImporter
Represents the pitch in the Humdrum Kern format.
The name is represented using the International Standard Organization (ISO) name notation. The first line below the staff is the C4 in G clef. The above C is C5, the below C is C3, etc.
The Humdrum Kern format uses the following name representation: 'c' = C4 'cc' = C5 'ccc' = C6 'cccc' = C7
'C' = C3 'CC' = C2 'CCC' = C1
This class do not limit the name ranges.
In the following example, the name is represented by the letter 'c'. The name of 'c' is C4, 'cc' is C5, 'ccc' is C6.
**kern
*clefG2
2c // C4
2cc // C5
2ccc // C6
2C // C3
2CC // C2
2CCC // C1
*-
Source code in kernpy/core/pitch_models.py
186 187 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 |
|
Importer
Importer class.
Use this class to import the content from a file or a string to a Document
object.
Source code in kernpy/core/importer.py
16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 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 186 187 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 |
|
__init__()
Create an instance of the importer.
Raises:
Exception: If the importer content is not a valid **kern file.
Examples:
# Create the importer
>>> importer = Importer()
# Import the content from a file
>>> document = importer.import_file('file.krn')
# Import the content from a string
>>> document = importer.import_string("**kern
clefF4 c4 4d 4e 4f -")
Source code in kernpy/core/importer.py
22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 |
|
get_error_messages()
Get the error messages of the importer.
Returns: str - The error messages split by a new line character.
Examples:
Create the importer and read the file
>>> importer = Importer()
>>> importer.import_file(Path('file.krn'))
>>> print(importer.get_error_messages())
'Error: Invalid token in row 1'
Source code in kernpy/core/importer.py
198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 |
|
has_errors()
Check if the importer has any errors.
Returns: bool - True if the importer has errors, False otherwise.
Examples:
Create the importer and read the file
>>> importer = Importer()
>>> importer.import_file(Path('file.krn')) # file.krn has an error
>>> print(importer.has_errors())
True
>>> importer.import_file(Path('file2.krn')) # file2.krn has no errors
>>> print(importer.has_errors())
False
Source code in kernpy/core/importer.py
217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 |
|
import_file(file_path)
Import the content from the importer to the file. Args: file_path: The path to the file.
Returns:
Type | Description |
---|---|
Document
|
Document - The document with the imported content. |
Examples:
Create the importer and read the file
>>> importer = Importer()
>>> importer.import_file('file.krn')
Source code in kernpy/core/importer.py
156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 |
|
import_string(text)
Import the content from the content of the score in string format.
Args:
text: The content of the score in string format.
Returns:
Document - The document with the imported content.
Examples:
# Create the importer and read the file
>>> importer = Importer()
>>> importer.import_string("**kern
clefF4 c4 4d 4e 4f -") # Read the content from a file >>> with open('file.krn', 'r', newline='', encoding='utf-8', errors='ignore') as f: # We encourage you to use these open file options >>> content = f.read() >>> importer.import_string(content) >>> document = importer.import_string(content)
Source code in kernpy/core/importer.py
174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 |
|
InstrumentToken
Bases: SimpleToken
InstrumentToken class stores the instruments of the score.
These tokens usually look like *I"Organo
.
Source code in kernpy/core/tokens.py
1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 |
|
__init__(encoding)
Constructor for the InstrumentToken
Parameters:
Name | Type | Description | Default |
---|---|---|---|
encoding |
str
|
|
required |
Source code in kernpy/core/tokens.py
1565 1566 1567 1568 1569 1570 1571 1572 |
|
KernSpineImporter
Bases: SpineImporter
Source code in kernpy/core/kern_spine_importer.py
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 |
|
__init__(verbose=False)
KernSpineImporter constructor.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
verbose |
Optional[bool]
|
Level of verbosity for error messages. |
False
|
Source code in kernpy/core/kern_spine_importer.py
41 42 43 44 45 46 47 48 |
|
KernTokenizer
Bases: Tokenizer
KernTokenizer converts a Token into a normalized kern string representation.
Source code in kernpy/core/tokenizers.py
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 |
|
__init__(*, token_categories)
Create a new KernTokenizer.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
token_categories |
Set[TokenCategory]
|
List of categories to be tokenized. If None will raise an exception. |
required |
Source code in kernpy/core/tokenizers.py
86 87 88 89 90 91 92 93 |
|
tokenize(token)
Tokenize a token into a normalized kern string representation. This format is the classic Humdrum **kern representation.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
token |
Token
|
Token to be tokenized. |
required |
Returns (str): Normalized kern string representation. This is the classic Humdrum **kern representation.
Examples:
>>> token.encoding
'2@.@bb@-·_·L'
>>> KernTokenizer().tokenize(token)
'2.bb-_L'
Source code in kernpy/core/tokenizers.py
95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 |
|
KeySignatureToken
Bases: SignatureToken
KeySignatureToken class.
Source code in kernpy/core/tokens.py
1690 1691 1692 1693 1694 1695 1696 |
|
KeyToken
Bases: SignatureToken
KeyToken class.
Source code in kernpy/core/tokens.py
1699 1700 1701 1702 1703 1704 1705 |
|
MHXMToken
Bases: Token
MHXMToken class.
Source code in kernpy/core/tokens.py
2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 |
|
MensSpineImporter
Bases: SpineImporter
Source code in kernpy/core/mens_spine_importer.py
9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
|
__init__(verbose=False)
MensSpineImporter constructor.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
verbose |
Optional[bool]
|
Level of verbosity for error messages. |
False
|
Source code in kernpy/core/mens_spine_importer.py
10 11 12 13 14 15 16 17 |
|
MetacommentToken
Bases: SimpleToken
MetacommentToken class stores the metacomments of the score.
Usually these are comments starting with !!
.
Source code in kernpy/core/tokens.py
1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 |
|
__init__(encoding)
Constructor for the MetacommentToken class.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
encoding |
str
|
The original representation of the token. |
required |
Source code in kernpy/core/tokens.py
1548 1549 1550 1551 1552 1553 1554 1555 |
|
MeterSymbolToken
Bases: SignatureToken
MeterSymbolToken class.
Source code in kernpy/core/tokens.py
1681 1682 1683 1684 1685 1686 1687 |
|
MultistageTree
MultistageTree class.
Source code in kernpy/core/document.py
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 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 |
|
__deepcopy__(memo)
Create a deep copy of the MultistageTree object.
Source code in kernpy/core/document.py
322 323 324 325 326 327 328 329 330 331 332 333 334 335 |
|
__init__()
Constructor for MultistageTree class.
Create an empty Node object to serve as the root, and start the stages list by placing this root node inside a new list.
Source code in kernpy/core/document.py
253 254 255 256 257 258 259 260 261 262 263 |
|
add_node(stage, parent, token, last_spine_operator_node, previous_signature_nodes, header_node=None)
Add a new node to the tree. Args: stage (int): parent (Node): token (Optional[AbstractToken]): last_spine_operator_node (Optional[Node]): previous_signature_nodes (Optional[SignatureNodes]): header_node (Optional[Node]):
Returns: Node - The added node object.
Source code in kernpy/core/document.py
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 |
|
dfs(visit_method)
Depth-first search (DFS)
Parameters:
Name | Type | Description | Default |
---|---|---|---|
visit_method |
TreeTraversalInterface
|
The tree traversal interface. |
required |
Returns: None
Source code in kernpy/core/document.py
298 299 300 301 302 303 304 305 306 307 308 |
|
dfs_iterative(visit_method)
Depth-first search (DFS). Iterative version.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
visit_method |
TreeTraversalInterface
|
The tree traversal interface. |
required |
Returns: None
Source code in kernpy/core/document.py
310 311 312 313 314 315 316 317 318 319 320 |
|
MxhmSpineImporter
Bases: SpineImporter
Source code in kernpy/core/mhxm_spine_importer.py
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 36 37 38 39 40 41 42 43 44 |
|
__init__(verbose=False)
KernSpineImporter constructor.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
verbose |
Optional[bool]
|
Level of verbosity for error messages. |
False
|
Source code in kernpy/core/mhxm_spine_importer.py
11 12 13 14 15 16 17 18 |
|
Node
Node class.
This class represents a node in a tree.
The Node
class is responsible for storing the main information of the **kern file.
Attributes:
Name | Type | Description |
---|---|---|
id(int) |
The unique id of the node. |
|
token(Optional[AbstractToken]) |
The specific token of the node. The token can be a |
|
parent(Optional['Node']) |
A reference to the parent |
|
children(List['Node']) |
A list of the children |
|
stage(int) |
The stage of the node in the tree. The stage is similar to a row in the **kern file. |
|
last_spine_operator_node(Optional['Node']) |
The last spine operator node. |
|
last_signature_nodes(Optional[SignatureNodes]) |
A reference to the last |
|
header_node(Optional['Node']) |
The header node. |
Source code in kernpy/core/document.py
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 186 187 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 |
|
__eq__(other)
Compare two nodes.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
other |
The other node to compare. |
required |
Returns: True if the nodes are equal, False otherwise.
Source code in kernpy/core/document.py
182 183 184 185 186 187 188 189 190 191 192 193 194 |
|
__hash__()
Get the hash of the node.
Returns: The hash of the node.
Source code in kernpy/core/document.py
207 208 209 210 211 212 213 |
|
__init__(stage, token, parent, last_spine_operator_node, last_signature_nodes, header_node)
Create an instance of Node.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
stage |
int
|
The stage of the node in the tree. The stage is similar to a row in the **kern file. |
required |
token |
Optional[AbstractToken]
|
The specific token of the node. The token can be a |
required |
parent |
Optional['Node']
|
A reference to the parent |
required |
last_spine_operator_node |
Optional['Node']
|
The last spine operator node. |
required |
last_signature_nodes |
Optional[SignatureNodes]
|
A reference to the last |
required |
header_node |
Optional['Node']
|
The header node. |
required |
Source code in kernpy/core/document.py
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 |
|
__ne__(other)
Compare two nodes.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
other |
The other node to compare. |
required |
Returns: True if the nodes are not equal, False otherwise.
Source code in kernpy/core/document.py
196 197 198 199 200 201 202 203 204 205 |
|
__str__()
Get the string representation of the node.
Returns: The string representation of the node.
Source code in kernpy/core/document.py
215 216 217 218 219 220 221 |
|
count_nodes_by_stage()
Count the number of nodes in each stage of the tree.
Examples:
>>> node = Node(0, None, None, None, None, None)
>>> ...
>>> node.count_nodes_by_stage()
[2, 2, 2, 2, 3, 3, 3, 2]
Returns:
Type | Description |
---|---|
List[int]
|
List[int]: A list with the number of nodes in each stage of the tree. |
Source code in kernpy/core/document.py
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 |
|
dfs(tree_traversal)
Depth-first search (DFS)
Parameters:
Name | Type | Description | Default |
---|---|---|---|
tree_traversal |
TreeTraversalInterface
|
The tree traversal interface. Object used to visit the nodes of the tree. |
required |
Source code in kernpy/core/document.py
155 156 157 158 159 160 161 162 163 164 165 |
|
dfs_iterative(tree_traversal)
Depth-first search (DFS). Iterative version.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
tree_traversal |
TreeTraversalInterface
|
The tree traversal interface. Object used to visit the nodes of the tree. |
required |
Returns: None
Source code in kernpy/core/document.py
167 168 169 170 171 172 173 174 175 176 177 178 179 180 |
|
NoteRestToken
Bases: ComplexToken
NoteRestToken class.
Attributes:
Name | Type | Description |
---|---|---|
pitch_duration_subtokens |
list
|
The subtokens for the pitch and duration |
decoration_subtokens |
list
|
The subtokens for the decorations |
Source code in kernpy/core/tokens.py
1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 |
|
__init__(encoding, pitch_duration_subtokens, decoration_subtokens)
NoteRestToken constructor.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
encoding |
str
|
The complete unprocessed encoding |
required |
pitch_duration_subtokens |
List[Subtoken])y
|
The subtokens for the pitch and duration |
required |
decoration_subtokens |
List[Subtoken]
|
The subtokens for the decorations. Individual elements of the token, of type Subtoken |
required |
Source code in kernpy/core/tokens.py
1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 |
|
export(**kwargs)
Exports the token.
Other Parameters:
Name | Type | Description |
---|---|---|
filter_categories |
Optional[Callable[[TokenCategory], bool]]
|
A function that takes a TokenCategory and returns a boolean indicating whether the token should be included in the export. If provided, only tokens for which the function returns True will be exported. Defaults to None. If None, all tokens will be exported. |
Returns (str): The exported token.
Source code in kernpy/core/tokens.py
1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 |
|
PitchPositionReferenceSystem
Source code in kernpy/core/gkern.py
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 |
|
__init__(base_pitch)
Initializes the PitchPositionReferenceSystem object. Args: base_pitch (AgnosticPitch): The AgnosticPitch in the first line of the Staff. The AgnosticPitch object that serves as the reference point for the system.
Source code in kernpy/core/gkern.py
221 222 223 224 225 226 227 228 |
|
compute_position(pitch)
Computes the position in staff for the given pitch. Args: pitch (AgnosticPitch): The AgnosticPitch object to compute the position for. Returns: PositionInStaff: The PositionInStaff object representing the computed position.
Source code in kernpy/core/gkern.py
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 |
|
PitchRest
Represents a name or a rest in a note.
The name is represented using the International Standard Organization (ISO) name notation. The first line below the staff is the C4 in G clef. The above C is C5, the below C is C3, etc.
The Humdrum Kern format uses the following name representation: 'c' = C4 'cc' = C5 'ccc' = C6 'cccc' = C7
'C' = C3 'CC' = C2 'CCC' = C1
The rests are represented by the letter 'r'. The rests do not have name.
This class do not limit the name ranges.
In the following example, the name is represented by the letter 'c'. The name of 'c' is C4, 'cc' is C5, 'ccc' is C6.
**kern
*clefG2
2c // C4
2cc // C5
2ccc // C6
2C // C3
2CC // C2
2CCC // C1
*-
Source code in kernpy/core/tokens.py
598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 |
|
__eq__(other)
Compare two pitches and rests.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
other |
PitchRest
|
The other name to compare |
required |
Returns (bool): True if the pitches are equal, False otherwise
Examples:
>>> pitch_rest = PitchRest('c')
>>> pitch_rest2 = PitchRest('c')
>>> pitch_rest == pitch_rest2
True
>>> pitch_rest = PitchRest('c')
>>> pitch_rest2 = PitchRest('ccc')
>>> pitch_rest == pitch_rest2
False
>>> pitch_rest = PitchRest('c')
>>> pitch_rest2 = PitchRest('r')
>>> pitch_rest == pitch_rest2
False
>>> pitch_rest = PitchRest('r')
>>> pitch_rest2 = PitchRest('r')
>>> pitch_rest == pitch_rest2
True
Source code in kernpy/core/tokens.py
730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 |
|
__ge__(other)
Compare two pitches. If any of the PitchRest is a rest, the comparison raise an exception. Args: other (PitchRest): The other name to compare
Returns (bool): True if this name is higher or equal than the other, False otherwise
Examples:
>>> pitch_rest = PitchRest('c')
>>> pitch_rest2 = PitchRest('d')
>>> pitch_rest >= pitch_rest2
False
>>> pitch_rest = PitchRest('c')
>>> pitch_rest2 = PitchRest('c')
>>> pitch_rest >= pitch_rest2
True
>>> pitch_rest = PitchRest('c')
>>> pitch_rest2 = PitchRest('b')
>>> pitch_rest >= pitch_rest2
True
>>> pitch_rest = PitchRest('r')
>>> pitch_rest2 = PitchRest('c')
>>> pitch_rest >= pitch_rest2
Traceback (most recent call last):
...
ValueError: ...
>>> pitch_rest = PitchRest('r')
>>> pitch_rest2 = PitchRest('r')
>>> pitch_rest >= pitch_rest2
Traceback (most recent call last):
...
ValueError: ...
Source code in kernpy/core/tokens.py
893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 |
|
__gt__(other)
Compare two pitches.
If any of the pitches is a rest, the comparison raise an exception.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
other |
PitchRest
|
The other name to compare |
required |
Returns (bool): True if this name is higher than the other, False otherwise
Examples:
>>> pitch_rest = PitchRest('c')
>>> pitch_rest2 = PitchRest('d')
>>> pitch_rest > pitch_rest2
False
>>> pitch_rest = PitchRest('c')
>>> pitch_rest2 = PitchRest('c')
>>> pitch_rest > pitch_rest2
False
>>> pitch_rest = PitchRest('c')
>>> pitch_rest2 = PitchRest('b')
>>> pitch_rest > pitch_rest2
True
>>> pitch_rest = PitchRest('r')
>>> pitch_rest2 = PitchRest('c')
>>> pitch_rest > pitch_rest2
Traceback (most recent call last):
...
ValueError: ...
>>> pitch_rest = PitchRest('r')
>>> pitch_rest2 = PitchRest('r')
>>> pitch_rest > pitch_rest2
Traceback (most recent call last):
ValueError: ...
Source code in kernpy/core/tokens.py
796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 |
|
__init__(raw_pitch)
Create a new PitchRest object.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
raw_pitch |
str
|
name representation in Humdrum Kern format |
required |
Examples:
>>> pitch_rest = PitchRest('c')
>>> pitch_rest = PitchRest('r')
>>> pitch_rest = PitchRest('DDD')
Source code in kernpy/core/tokens.py
641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 |
|
__le__(other)
Compare two pitches. If any of the PitchRest is a rest, the comparison raise an exception. Args: other (PitchRest): The other name to compare
Returns (bool): True if this name is lower or equal than the other, False otherwise
Examples:
>>> pitch_rest = PitchRest('c')
>>> pitch_rest2 = PitchRest('d')
>>> pitch_rest <= pitch_rest2
True
>>> pitch_rest = PitchRest('c')
>>> pitch_rest2 = PitchRest('c')
>>> pitch_rest <= pitch_rest2
True
>>> pitch_rest = PitchRest('c')
>>> pitch_rest2 = PitchRest('b')
>>> pitch_rest <= pitch_rest2
False
>>> pitch_rest = PitchRest('r')
>>> pitch_rest2 = PitchRest('c')
>>> pitch_rest <= pitch_rest2
Traceback (most recent call last):
...
ValueError: ...
>>> pitch_rest = PitchRest('r')
>>> pitch_rest2 = PitchRest('r')
>>> pitch_rest <= pitch_rest2
Traceback (most recent call last):
...
ValueError: ...
Source code in kernpy/core/tokens.py
932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 |
|
__lt__(other)
Compare two pitches.
If any of the pitches is a rest, the comparison raise an exception.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
other |
'PitchRest'
|
The other name to compare |
required |
Returns:
Type | Description |
---|---|
bool
|
True if this name is lower than the other, False otherwise |
Examples:
>>> pitch_rest = PitchRest('c')
>>> pitch_rest2 = PitchRest('d')
>>> pitch_rest < pitch_rest2
True
>>> pitch_rest = PitchRest('c')
>>> pitch_rest2 = PitchRest('c')
>>> pitch_rest < pitch_rest2
False
>>> pitch_rest = PitchRest('c')
>>> pitch_rest2 = PitchRest('b')
>>> pitch_rest < pitch_rest2
False
>>> pitch_rest = PitchRest('r')
>>> pitch_rest2 = PitchRest('c')
>>> pitch_rest < pitch_rest2
Traceback (most recent call last):
...
ValueError: ...
>>> pitch_rest = PitchRest('r')
>>> pitch_rest2 = PitchRest('r')
>>> pitch_rest < pitch_rest2
Traceback (most recent call last):
...
ValueError: ...
Source code in kernpy/core/tokens.py
844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 |
|
__ne__(other)
Compare two pitches and rests. Args: other (PitchRest): The other name to compare
Returns (bool): True if the pitches are different, False otherwise
Examples:
>>> pitch_rest = PitchRest('c')
>>> pitch_rest2 = PitchRest('c')
>>> pitch_rest != pitch_rest2
False
>>> pitch_rest = PitchRest('c')
>>> pitch_rest2 = PitchRest('ccc')
>>> pitch_rest != pitch_rest2
True
>>> pitch_rest = PitchRest('c')
>>> pitch_rest2 = PitchRest('r')
>>> pitch_rest != pitch_rest2
True
>>> pitch_rest = PitchRest('r')
>>> pitch_rest2 = PitchRest('r')
>>> pitch_rest != pitch_rest2
False
Source code in kernpy/core/tokens.py
767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 |
|
is_rest()
Check if the name is a rest.
Returns:
Name | Type | Description |
---|---|---|
bool |
bool
|
True if the name is a rest, False otherwise. |
Examples:
>>> pitch_rest = PitchRest('c')
>>> pitch_rest.is_rest()
False
>>> pitch_rest = PitchRest('r')
>>> pitch_rest.is_rest()
True
Source code in kernpy/core/tokens.py
677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 |
|
pitch_comparator(pitch_a, pitch_b)
staticmethod
Compare two pitches of the same octave.
The lower name is 'a'. So 'a' < 'b' < 'c' < 'd' < 'e' < 'f' < 'g'
Parameters:
Name | Type | Description | Default |
---|---|---|---|
pitch_a |
str
|
One name of 'abcdefg' |
required |
pitch_b |
str
|
Another name of 'abcdefg' |
required |
Returns:
Type | Description |
---|---|
int
|
-1 if pitch1 is lower than pitch2 |
int
|
0 if pitch1 is equal to pitch2 |
int
|
1 if pitch1 is higher than pitch2 |
Examples:
>>> PitchRest.pitch_comparator('c', 'c')
0
>>> PitchRest.pitch_comparator('c', 'd')
-1
>>> PitchRest.pitch_comparator('d', 'c')
1
Source code in kernpy/core/tokens.py
694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 |
|
PositionInStaff
Source code in kernpy/core/gkern.py
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 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 |
|
__eq__(other)
Compares two PositionInStaff objects.
Source code in kernpy/core/gkern.py
180 181 182 183 184 185 186 |
|
__hash__()
Returns the hash of the PositionInStaff object.
Source code in kernpy/core/gkern.py
194 195 196 197 198 |
|
__init__(line_space)
Initializes the PositionInStaff object.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
line_space |
int
|
0 for bottom line, -1 for space under bottom line, 1 for space above bottom line. Increments by 1 for each line or space. |
required |
Source code in kernpy/core/gkern.py
59 60 61 62 63 64 65 66 67 68 |
|
__lt__(other)
Compares two PositionInStaff objects.
Source code in kernpy/core/gkern.py
200 201 202 203 204 205 206 |
|
__ne__(other)
Compares two PositionInStaff objects.
Source code in kernpy/core/gkern.py
188 189 190 191 192 |
|
__repr__()
Returns the string representation of the PositionInStaff object.
Source code in kernpy/core/gkern.py
174 175 176 177 178 |
|
__str__()
Returns the string representation of the position in staff.
Source code in kernpy/core/gkern.py
165 166 167 168 169 170 171 172 |
|
from_encoded(encoded)
classmethod
Creates a PositionInStaff object from an encoded string.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
encoded |
str
|
The encoded string. |
required |
Returns:
Name | Type | Description |
---|---|---|
PositionInStaff |
PositionInStaff
|
The PositionInStaff object. |
Source code in kernpy/core/gkern.py
96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 |
|
from_line(line)
classmethod
Creates a PositionInStaff object from a line number.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
line |
int
|
The line number. line 1 is bottom line, 2 is the 1st line from bottom, 0 is the bottom ledger line |
required |
Returns:
Name | Type | Description |
---|---|---|
PositionInStaff |
PositionInStaff
|
The PositionInStaff object. 0 for the bottom line, 2 for the 1st line from bottom, -1 for the bottom ledger line, etc. |
Source code in kernpy/core/gkern.py
70 71 72 73 74 75 76 77 78 79 80 81 |
|
from_space(space)
classmethod
Creates a PositionInStaff object from a space number.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
space |
int
|
The space number. space 1 is bottom space, 2 |
required |
Returns:
Name | Type | Description |
---|---|---|
PositionInStaff |
PositionInStaff
|
The PositionInStaff object. |
Source code in kernpy/core/gkern.py
83 84 85 86 87 88 89 90 91 92 93 94 |
|
is_line()
Returns True if the position is a line, False otherwise. If is not a line, it is a space, and vice versa.
Source code in kernpy/core/gkern.py
133 134 135 136 137 |
|
line()
Returns the line number of the position in staff.
Source code in kernpy/core/gkern.py
119 120 121 122 123 |
|
move(line_space_difference)
Returns a new PositionInStaff object with the position moved by the given number of lines or spaces.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
line_space_difference |
int
|
The number of lines or spaces to move. |
required |
Returns:
Name | Type | Description |
---|---|---|
PositionInStaff |
PositionInStaff
|
The new PositionInStaff object. |
Source code in kernpy/core/gkern.py
139 140 141 142 143 144 145 146 147 148 149 |
|
position_above()
Returns the position above the current position.
Source code in kernpy/core/gkern.py
157 158 159 160 161 |
|
position_below()
Returns the position below the current position.
Source code in kernpy/core/gkern.py
151 152 153 154 155 |
|
space()
Returns the space number of the position in staff.
Source code in kernpy/core/gkern.py
126 127 128 129 130 |
|
RootSpineImporter
Bases: SpineImporter
Source code in kernpy/core/root_spine_importer.py
37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 |
|
__init__(verbose=False)
KernSpineImporter constructor.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
verbose |
Optional[bool]
|
Level of verbosity for error messages. |
False
|
Source code in kernpy/core/root_spine_importer.py
38 39 40 41 42 43 44 45 |
|
SignatureNodes
SignatureNodes class.
This class is used to store the last signature nodes of a tree. It is used to keep track of the last signature nodes.
Attributes: nodes (dict): A dictionary that stores the last signature nodes. This way, we can add several tokens without repetitions. - The key is the signature descendant token class (KeyToken, MeterSymbolToken, etc...) - The value = node
Source code in kernpy/core/document.py
18 19 20 21 22 23 24 25 26 27 28 29 30 31 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 |
|
__init__()
Create an instance of SignatureNodes. Initialize the nodes as an empty dictionary.
Examples:
>>> signature_nodes = SignatureNodes()
>>> signature_nodes.nodes
{}
Source code in kernpy/core/document.py
31 32 33 34 35 36 37 38 39 40 |
|
clone()
Create a deep copy of the SignatureNodes instance. Returns: A new instance of SignatureNodes with nodes copied.
TODO: This method is equivalent to the following code:
from copy import deepcopy
signature_nodes_to_copy = SignatureNodes()
...
result = deepcopy(signature_nodes_to_copy)
It should be tested.
Source code in kernpy/core/document.py
42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 |
|
SignatureToken
Bases: SimpleToken
SignatureToken class for all signature tokens. It will be overridden by more specific classes.
Source code in kernpy/core/tokens.py
1654 1655 1656 1657 1658 1659 1660 |
|
SimpleToken
Bases: Token
SimpleToken class.
Source code in kernpy/core/tokens.py
1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 |
|
export(**kwargs)
Exports the token.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
**kwargs |
'filter_categories' (Optional[Callable[[TokenCategory], bool]]): It is ignored in this class. |
{}
|
Returns (str): The encoded token representation.
Source code in kernpy/core/tokens.py
1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 |
|
SpineImporter
Bases: ABC
Source code in kernpy/core/spine_importer.py
16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
|
__init__(verbose=False)
SpineImporter constructor. This class is an abstract base class for importing all kinds of spines.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
verbose |
Optional[bool]
|
Level of verbosity for error messages. |
False
|
Source code in kernpy/core/spine_importer.py
17 18 19 20 21 22 23 24 25 26 |
|
SpineOperationToken
Bases: SimpleToken
SpineOperationToken class.
This token represents different operations in the Humdrum kern encoding.
These are the available operations:
- *-
: spine-path terminator.
- *
: null interpretation.
- *+
: add spines.
- *^
: split spines.
- *x
: exchange spines.
Attributes:
Name | Type | Description |
---|---|---|
cancelled_at_stage |
int
|
The stage at which the operation was cancelled. Defaults to None. |
Source code in kernpy/core/tokens.py
1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 |
|
is_cancelled_at(stage)
Checks if the operation was cancelled at the given stage.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
stage |
int
|
The stage at which the operation was cancelled. |
required |
Returns:
Name | Type | Description |
---|---|---|
bool |
bool
|
True if the operation was cancelled at the given stage, False otherwise. |
Source code in kernpy/core/tokens.py
1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 |
|
Staff
Source code in kernpy/core/gkern.py
499 500 501 502 503 504 |
|
position_in_staff(*, clef, pitch)
Returns the position in staff for the given clef and pitch.
Source code in kernpy/core/gkern.py
500 501 502 503 504 |
|
Subtoken
Subtoken class. Thhe subtokens are the smallest units of categories. ComplexToken objects are composed of subtokens.
Attributes:
Name | Type | Description |
---|---|---|
encoding |
The complete unprocessed encoding |
|
category |
The subtoken category, one of SubTokenCategory |
Source code in kernpy/core/tokens.py
1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 |
|
__eq__(other)
Compare two subtokens.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
other |
Subtoken
|
The other subtoken to compare. |
required |
Returns (bool): True if the subtokens are equal, False otherwise.
Source code in kernpy/core/tokens.py
1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 |
|
__hash__()
Returns the hash of the subtoken.
Returns (int): The hash of the subtoken.
Source code in kernpy/core/tokens.py
1376 1377 1378 1379 1380 1381 1382 |
|
__init__(encoding, category)
Subtoken constructor
Parameters:
Name | Type | Description | Default |
---|---|---|---|
encoding |
str
|
The complete unprocessed encoding |
required |
category |
TokenCategory
|
The subtoken category. It should be a child of the main 'TokenCategory' in the hierarchy. |
required |
Source code in kernpy/core/tokens.py
1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 |
|
__ne__(other)
Compare two subtokens.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
other |
Subtoken
|
The other subtoken to compare. |
required |
Returns (bool): True if the subtokens are different, False otherwise.
Source code in kernpy/core/tokens.py
1366 1367 1368 1369 1370 1371 1372 1373 1374 |
|
__str__()
Returns the string representation of the subtoken.
Returns (str): The string representation of the subtoken.
Source code in kernpy/core/tokens.py
1346 1347 1348 1349 1350 1351 1352 |
|
TextSpineImporter
Bases: SpineImporter
Source code in kernpy/core/text_spine_importer.py
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 36 37 38 39 40 41 42 43 44 45 46 |
|
__init__(verbose=False)
KernSpineImporter constructor.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
verbose |
Optional[bool]
|
Level of verbosity for error messages. |
False
|
Source code in kernpy/core/text_spine_importer.py
12 13 14 15 16 17 18 19 |
|
TimeSignatureToken
Bases: SignatureToken
TimeSignatureToken class.
Source code in kernpy/core/tokens.py
1672 1673 1674 1675 1676 1677 1678 |
|
Token
Bases: AbstractToken
, ABC
Abstract Token class.
Source code in kernpy/core/tokens.py
1471 1472 1473 1474 1475 1476 1477 |
|
TokenCategory
Bases: Enum
Options for the category of a token.
This is used to determine what kind of token should be exported.
The categories are sorted the specific order they are compared to sorthem. But hierarchical order must be defined in other data structures.
Source code in kernpy/core/tokens.py
23 24 25 26 27 28 29 30 31 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 186 187 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 |
|
__lt__(other)
Compare two TokenCategory. Args: other (TokenCategory): The other category to compare.
Returns (bool): True if this category is lower than the other, False otherwise.
Examples:
>>> TokenCategory.STRUCTURAL < TokenCategory.CORE
True
>>> TokenCategory.STRUCTURAL < TokenCategory.STRUCTURAL
False
>>> TokenCategory.CORE < TokenCategory.STRUCTURAL
False
>>> sorted([TokenCategory.STRUCTURAL, TokenCategory.CORE])
[TokenCategory.STRUCTURAL, TokenCategory.CORE]
Source code in kernpy/core/tokens.py
69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 |
|
__str__()
Get the string representation of the category.
Returns (str): The string representation of the category.
Source code in kernpy/core/tokens.py
230 231 232 233 234 235 236 |
|
children(target)
classmethod
Get the children of the target category.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
target |
TokenCategory
|
The target category. |
required |
Returns (List[TokenCategory]): The list of child categories of the target category.
Source code in kernpy/core/tokens.py
160 161 162 163 164 165 166 167 168 169 170 |
|
is_child(*, child, parent)
classmethod
Check if the child category is a child of the parent category.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
child |
TokenCategory
|
The child category. |
required |
parent |
TokenCategory
|
The parent category. |
required |
Returns (bool): True if the child category is a child of the parent category, False otherwise.
Source code in kernpy/core/tokens.py
147 148 149 150 151 152 153 154 155 156 157 158 |
|
leaves(target)
classmethod
Get the leaves of the subtree of the target category.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
target |
TokenCategory
|
The target category. |
required |
Returns (List[TokenCategory]): The list of leaf categories of the target category.
Source code in kernpy/core/tokens.py
187 188 189 190 191 192 193 194 195 196 197 |
|
match(target, *, include=None, exclude=None)
classmethod
Check if the target category matches the include and exclude sets.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
target |
TokenCategory
|
The target category. |
required |
include |
Optional[Set[TokenCategory]]
|
The set of categories to include. Defaults to None. If None, all categories are included. |
None
|
exclude |
Optional[Set[TokenCategory]]
|
The set of categories to exclude. Defaults to None. If None, no categories are excluded. |
None
|
Returns (bool): True if the target category matches the include and exclude sets, False otherwise.
Source code in kernpy/core/tokens.py
211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 |
|
nodes(target)
classmethod
Get the nodes of the subtree of the target category.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
target |
TokenCategory
|
The target category. |
required |
Returns (List[TokenCategory]): The list of node categories of the target category.
Source code in kernpy/core/tokens.py
199 200 201 202 203 204 205 206 207 208 209 |
|
tree()
classmethod
Return a string representation of the category hierarchy Returns (str): The string representation of the category hierarchy
Examples:
>>> import kernpy as kp
>>> print(kp.TokenCategory.tree())
.
├── TokenCategory.STRUCTURAL
├── TokenCategory.CORE
│ ├── TokenCategory.NOTE_REST
│ │ ├── TokenCategory.DURATION
│ │ ├── TokenCategory.NOTE
│ │ │ ├── TokenCategory.PITCH
│ │ │ └── TokenCategory.DECORATION
│ │ └── TokenCategory.REST
│ ├── TokenCategory.CHORD
│ └── TokenCategory.EMPTY
├── TokenCategory.SIGNATURES
│ ├── TokenCategory.CLEF
│ ├── TokenCategory.TIME_SIGNATURE
│ ├── TokenCategory.METER_SYMBOL
│ └── TokenCategory.KEY_SIGNATURE
├── TokenCategory.ENGRAVED_SYMBOLS
├── TokenCategory.OTHER_CONTEXTUAL
├── TokenCategory.BARLINES
├── TokenCategory.COMMENTS
│ ├── TokenCategory.FIELD_COMMENTS
│ └── TokenCategory.LINE_COMMENTS
├── TokenCategory.DYNAMICS
├── TokenCategory.HARMONY
├── TokenCategory.FINGERING
├── TokenCategory.LYRICS
├── TokenCategory.INSTRUMENTS
├── TokenCategory.BOUNDING_BOXES
└── TokenCategory.OTHER
Source code in kernpy/core/tokens.py
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 |
|
valid(*, include=None, exclude=None)
classmethod
Get the valid categories based on the include and exclude sets.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
include |
Optional[Set[TokenCategory]]
|
The set of categories to include. Defaults to None. If None, all categories are included. |
None
|
exclude |
Optional[Set[TokenCategory]]
|
The set of categories to exclude. Defaults to None. If None, no categories are excluded. |
None
|
Returns (Set[TokenCategory]): The list of valid categories based on the include and exclude sets.
Source code in kernpy/core/tokens.py
172 173 174 175 176 177 178 179 180 181 182 183 184 185 |
|
TokenCategoryHierarchyMapper
Mapping of the TokenCategory hierarchy.
This class is used to define the hierarchy of the TokenCategory. Useful related methods are provided.
Source code in kernpy/core/tokens.py
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 314 315 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 347 348 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 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 |
|
all()
classmethod
Get all categories in the hierarchy.
Returns:
Type | Description |
---|---|
Set[TokenCategory]
|
Set[TokenCategory]: The set of all categories in the hierarchy. |
Source code in kernpy/core/tokens.py
539 540 541 542 543 544 545 546 547 |
|
children(parent)
classmethod
Get the direct children of the parent category.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
parent |
TokenCategory
|
The parent category. |
required |
Returns:
Type | Description |
---|---|
Set[TokenCategory]
|
Set[TokenCategory]: The list of children categories of the parent category. |
Source code in kernpy/core/tokens.py
359 360 361 362 363 364 365 366 367 368 369 370 |
|
is_child(parent, child)
classmethod
Recursively check if child
is in the subtree of parent
. If parent
is the same as child
, return True.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
parent |
TokenCategory
|
The parent category. |
required |
child |
TokenCategory
|
The category to check. |
required |
Returns:
Name | Type | Description |
---|---|---|
bool |
bool
|
True if |
Source code in kernpy/core/tokens.py
343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 |
|
leaves(target)
classmethod
Get the leaves of the subtree of the target category.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
target |
TokenCategory
|
The target category. |
required |
Returns (List[TokenCategory]): The list of leaf categories of the target category.
Source code in kernpy/core/tokens.py
444 445 446 447 448 449 450 451 452 453 454 455 |
|
match(category, *, include=None, exclude=None)
classmethod
Check if the category matches the include and exclude sets. If include is None, all categories are included. If exclude is None, no categories are excluded.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
category |
TokenCategory
|
The category to check. |
required |
include |
Optional[Set[TokenCategory]]
|
The set of categories to include. Defaults to None. If None, all categories are included. |
None
|
exclude |
Optional[Set[TokenCategory]]
|
The set of categories to exclude. Defaults to None. If None, no categories are excluded. |
None
|
Returns (bool): True if the category matches the include and exclude sets, False otherwise.
Examples:
>>> TokenCategoryHierarchyMapper.match(TokenCategory.NOTE, include={TokenCategory.NOTE_REST})
True
>>> TokenCategoryHierarchyMapper.match(TokenCategory.NOTE, include={TokenCategory.NOTE_REST}, exclude={TokenCategory.REST})
True
>>> TokenCategoryHierarchyMapper.match(TokenCategory.NOTE, include={TokenCategory.NOTE_REST}, exclude={TokenCategory.NOTE})
False
>>> TokenCategoryHierarchyMapper.match(TokenCategory.NOTE, include={TokenCategory.CORE}, exclude={TokenCategory.DURATION})
True
>>> TokenCategoryHierarchyMapper.match(TokenCategory.DURATION, include={TokenCategory.CORE}, exclude={TokenCategory.DURATION})
False
Source code in kernpy/core/tokens.py
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 |
|
nodes(parent)
classmethod
Get the all nodes of the subtree of the parent category.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
parent |
TokenCategory
|
The parent category. |
required |
Returns:
Type | Description |
---|---|
Set[TokenCategory]
|
List[TokenCategory]: The list of nodes of the subtree of the parent category. |
Source code in kernpy/core/tokens.py
396 397 398 399 400 401 402 403 404 405 406 407 408 |
|
tree()
classmethod
Return a string representation of the category hierarchy, formatted similar to the output of the Unix 'tree' command.
Example output
. ├── STRUCTURAL ├── CORE │ ├── NOTE_REST │ │ ├── DURATION │ │ ├── NOTE │ │ │ ├── PITCH │ │ │ └── DECORATION │ │ └── REST │ ├── CHORD │ └── EMPTY ├── SIGNATURES │ ├── CLEF │ ├── TIME_SIGNATURE │ ├── METER_SYMBOL │ └── KEY_SIGNATURE ├── ENGRAVED_SYMBOLS ├── OTHER_CONTEXTUAL ├── BARLINES ├── COMMENTS │ ├── FIELD_COMMENTS │ └── LINE_COMMENTS ├── DYNAMICS ├── HARMONY ...
Source code in kernpy/core/tokens.py
549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 |
|
valid(include=None, exclude=None)
classmethod
Get the valid categories based on the include and exclude sets.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
include |
Optional[Set[TokenCategory]]
|
The set of categories to include. Defaults to None. If None, all categories are included. |
None
|
exclude |
Optional[Set[TokenCategory]]
|
The set of categories to exclude. Defaults to None. If None, no categories are excluded. |
None
|
Returns (Set[TokenCategory]): The list of valid categories based on the include and exclude sets.
Source code in kernpy/core/tokens.py
410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 |
|
Tokenizer
Bases: ABC
Tokenizer interface. All tokenizers must implement this interface.
Tokenizers are responsible for converting a token into a string representation.
Source code in kernpy/core/tokenizers.py
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 |
|
__init__(*, token_categories)
Create a new Tokenizer.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
token_categories |
Set[TokenCategory]
|
List of categories to be tokenized. If None, an exception will be raised. |
required |
Source code in kernpy/core/tokenizers.py
54 55 56 57 58 59 60 61 62 63 64 65 |
|
tokenize(token)
abstractmethod
Tokenize a token into a string representation.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
token |
Token
|
Token to be tokenized. |
required |
Returns (str): Tokenized string representation.
Source code in kernpy/core/tokenizers.py
68 69 70 71 72 73 74 75 76 77 78 79 |
|
TokensTraversal
Bases: TreeTraversalInterface
Source code in kernpy/core/document.py
909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 |
|
__init__(non_repeated, filter_by_categories)
Create an instance of TokensTraversal
.
Args:
non_repeated: If True, only unique tokens are returned. If False, all tokens are returned.
filter_by_categories: A list of categories to filter the tokens. If None, all tokens are returned.
Source code in kernpy/core/document.py
910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 |
|
TraversalFactory
Source code in kernpy/core/document.py
936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 |
|
create(traversal_type, non_repeated, filter_by_categories)
classmethod
Create an instance of TreeTraversalInterface
based on the traversal_type
.
Args:
non_repeated:
filter_by_categories:
traversal_type: The type of traversal to use. Possible values are:
- "metacomments"
- "tokens"
Returns: An instance of TreeTraversalInterface
.
Source code in kernpy/core/document.py
941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 |
|
TreeTraversalInterface
Bases: ABC
TreeTraversalInterface class.
This class is used to traverse the tree. The TreeTraversalInterface
class is responsible for implementing
the visit
method.
Source code in kernpy/core/document.py
62 63 64 65 66 67 68 69 70 71 72 |
|
agnostic_distance(first_pitch, second_pitch)
Calculate the distance in semitones between two pitches.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
first_pitch |
AgnosticPitch
|
The first pitch to compare. |
required |
second_pitch |
AgnosticPitch
|
The second pitch to compare. |
required |
Returns:
Name | Type | Description |
---|---|---|
int |
int
|
The distance in semitones between the two pitches. |
Examples:
>>> agnostic_distance(AgnosticPitch('C4'), AgnosticPitch('E4'))
4
>>> agnostic_distance(AgnosticPitch('C4'), AgnosticPitch('B3'))
-1
Source code in kernpy/core/transposer.py
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 |
|
create(content, strict=False)
Create a Document object from a string encoded in Humdrum **kern format.
Args:
content: String encoded in Humdrum **kern format
strict: If True, raise an error if the **kern file has any errors. Otherwise, return a list of errors.
Returns (Document, list): Document object and list of error messages. Empty list if no errors.
Examples:
>>> import kernpy as kp
>>> document, errors = kp.create('**kern
4e 4f 4g - ') >>> if len(errors) > 0: >>> print(errors) ['Error: Invalid kern spine: 1', 'Error: Invalid *kern spine: 2']
Source code in kernpy/core/generic.py
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 |
|
deprecated(reason)
Decorator to mark a function or class as deprecated.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
reason |
str
|
The reason why the function/class is deprecated. |
required |
Example
@deprecated("Use new_function instead.") def old_function(): pass
Source code in kernpy/util/helpers.py
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
|
distance(first_encoding, second_encoding, *, first_format=NotationEncoding.HUMDRUM.value, second_format=NotationEncoding.HUMDRUM.value)
Calculate the distance in semitones between two pitches.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
first_encoding |
str
|
The first pitch to compare. |
required |
second_encoding |
str
|
The second pitch to compare. |
required |
first_format |
str
|
The encoding format of the first pitch. Default is HUMDRUM. |
HUMDRUM.value
|
second_format |
str
|
The encoding format of the second pitch. Default is HUMDRUM. |
HUMDRUM.value
|
Returns:
Name | Type | Description |
---|---|---|
int |
int
|
The distance in semitones between the two pitches. |
Examples:
>>> distance('C4', 'E4')
4
>>> distance('C4', 'B3')
-1
Source code in kernpy/core/transposer.py
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 |
|
ekern_to_krn(input_file, output_file)
Convert one .ekrn file to .krn file.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
input_file |
str
|
Filepath to the input **ekern |
required |
output_file |
str
|
Filepath to the output **kern |
required |
Returns: None
Example
Convert .ekrn to .krn
ekern_to_krn('path/to/file.ekrn', 'path/to/file.krn')
Convert a list of .ekrn files to .krn files
ekrn_files = your_modue.get_files()
# Use the wrapper to avoid stopping the process if an error occurs
def ekern_to_krn_wrapper(ekern_file, kern_file):
try:
ekern_to_krn(ekrn_files, output_folder)
except Exception as e:
print(f'Error:{e}')
# Convert all the files
for ekern_file in ekrn_files:
output_file = ekern_file.replace('.ekrn', '.krn')
ekern_to_krn_wrapper(ekern_file, output_file)
Source code in kernpy/core/exporter.py
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 |
|
export(document, options)
Export a Document object to a string.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
document |
Document
|
Document object to export |
required |
options |
ExportOptions
|
Export options |
required |
Returns: Exported string
Examples:
>>> import kernpy as kp
>>> document, errors = kp.read('path/to/file.krn')
>>> options = kp.ExportOptions()
>>> content = kp.export(document, options)
Source code in kernpy/core/generic.py
312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 |
|
get_kern_from_ekern(ekern_content)
Read the content of a ekern file and return the kern content.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
ekern_content |
str
|
The content of the **ekern file. |
required |
Returns: The content of the **kern file.
Example
# Read **ekern file
ekern_file = 'path/to/file.ekrn'
with open(ekern_file, 'r') as file:
ekern_content = file.read()
# Get **kern content
kern_content = get_kern_from_ekern(ekern_content)
with open('path/to/file.krn', 'w') as file:
file.write(kern_content)
Source code in kernpy/core/exporter.py
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 |
|
get_spine_types(document, spine_types=None)
Get the spines of a Document object.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
document |
Document
|
Document object to get spines from |
required |
spine_types |
Optional[Sequence[str]]
|
List of spine types to get. If None, all spines are returned. |
None
|
Returns (List[str]): List of spines
Examples:
>>> import kernpy as kp
>>> document, _ = kp.read('path/to/file.krn')
>>> kp.get_spine_types(document)
['**kern', '**kern', '**kern', '**kern', '**root', '**harm']
>>> kp.get_spine_types(document, None)
['**kern', '**kern', '**kern', '**kern', '**root', '**harm']
>>> kp.get_spine_types(document, ['**kern'])
['**kern', '**kern', '**kern', '**kern']
>>> kp.get_spine_types(document, ['**kern', '**root'])
['**kern', '**kern', '**kern', '**kern', '**root']
>>> kp.get_spine_types(document, ['**kern', '**root', '**harm'])
['**kern', '**kern', '**kern', '**kern', '**root', '**harm']
>>> kp.get_spine_types(document, [])
[]
Source code in kernpy/core/generic.py
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 |
|
kern_to_ekern(input_file, output_file)
Convert one .krn file to .ekrn file
Parameters:
Name | Type | Description | Default |
---|---|---|---|
input_file |
str
|
Filepath to the input **kern |
required |
output_file |
str
|
Filepath to the output **ekern |
required |
Returns:
Type | Description |
---|---|
None
|
None |
Example
Convert .krn to .ekrn
kern_to_ekern('path/to/file.krn', 'path/to/file.ekrn')
Convert a list of .krn files to .ekrn files
krn_files = your_module.get_files()
# Use the wrapper to avoid stopping the process if an error occurs
def kern_to_ekern_wrapper(krn_file, ekern_file):
try:
kern_to_ekern(krn_file, ekern_file)
except Exception as e:
print(f'Error:{e}')
# Convert all the files
for krn_file in krn_files:
output_file = krn_file.replace('.krn', '.ekrn')
kern_to_ekern_wrapper(krn_file, output_file)
Source code in kernpy/core/exporter.py
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 |
|
read(path, strict=False)
Read a Humdrum **kern file.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
path |
Union[str, Path]
|
File path to read |
required |
strict |
Optional[bool]
|
If True, raise an error if the **kern file has any errors. Otherwise, return a list of errors. |
False
|
Returns (Document, List[str]): Document object and list of error messages. Empty list if no errors.
Examples:
>>> import kernpy as kp
>>> document, _ = kp.read('path/to/file.krn')
>>> document, errors = kp.read('path/to/file.krn')
>>> if len(errors) > 0:
>>> print(errors)
['Error: Invalid **kern spine: 1', 'Error: Invalid **kern spine: 2']
Source code in kernpy/core/generic.py
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 |
|
store(document, path, options)
Store a Document object to a file.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
document |
Document
|
Document object to store |
required |
path |
Union[str, Path]
|
File path to store |
required |
options |
ExportOptions
|
Export options |
required |
Returns: None
Examples:
>>> import kernpy as kp
>>> document, errors = kp.read('path/to/file.krn')
>>> options = kp.ExportOptions()
>>> kp.store(document, 'path/to/store.krn', options)
Source code in kernpy/core/generic.py
338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 |
|
store_graph(document, path)
Create a graph representation of a Document object using Graphviz. Save the graph to a file.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
document |
Document
|
Document object to create graph from |
required |
path |
str
|
File path to save the graph |
required |
Returns (None): None
Examples:
>>> import kernpy as kp
>>> document, errors = kp.read('path/to/file.krn')
>>> kp.store_graph(document, 'path/to/graph.dot')
Source code in kernpy/core/generic.py
368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 |
|
transpose(input_encoding, interval, input_format=NotationEncoding.HUMDRUM.value, output_format=NotationEncoding.HUMDRUM.value, direction=Direction.UP.value)
Transpose a pitch by a given interval.
The pitch must be in the American notation.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
input_encoding |
str
|
The pitch to transpose. |
required |
interval |
int
|
The interval to transpose the pitch. |
required |
input_format |
str
|
The encoding format of the pitch. Default is HUMDRUM. |
HUMDRUM.value
|
output_format |
str
|
The encoding format of the transposed pitch. Default is HUMDRUM. |
HUMDRUM.value
|
direction |
str
|
The direction of the transposition.'UP' or 'DOWN' Default is 'UP'. |
UP.value
|
Returns:
Name | Type | Description |
---|---|---|
str |
str
|
The transposed pitch. |
Examples:
>>> transpose('ccc', IntervalsByName['P4'], input_format='kern', output_format='kern')
'fff'
>>> transpose('ccc', IntervalsByName['P4'], input_format=NotationEncoding.HUMDRUM.value)
'fff'
>>> transpose('ccc', IntervalsByName['P4'], input_format='kern', direction='down')
'gg'
>>> transpose('ccc', IntervalsByName['P4'], input_format='kern', direction=Direction.DOWN.value)
'gg'
>>> transpose('ccc#', IntervalsByName['P4'])
'fff#'
>>> transpose('G4', IntervalsByName['m3'], input_format='american')
'Bb4'
>>> transpose('G4', IntervalsByName['m3'], input_format=NotationEncoding.AMERICAN.value)
'Bb4'
>>> transpose('C3', IntervalsByName['P4'], input_format='american', direction='down')
'G2'
Source code in kernpy/core/transposer.py
185 186 187 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 |
|
transpose_agnostic_to_encoding(agnostic_pitch, interval, output_format=NotationEncoding.HUMDRUM.value, direction=Direction.UP.value)
Transpose an AgnosticPitch by a given interval.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
agnostic_pitch |
AgnosticPitch
|
The pitch to transpose. |
required |
interval |
int
|
The interval to transpose the pitch. |
required |
output_format |
Optional[str]
|
The encoding format of the transposed pitch. Default is HUMDRUM. |
HUMDRUM.value
|
direction |
Optional[str]
|
The direction of the transposition.'UP' or 'DOWN' Default is 'UP'. |
UP.value
|
Returns (str): str: The transposed pitch.
Examples:
>>> transpose_agnostic_to_encoding(AgnosticPitch('C', 4), IntervalsByName['P4'])
'F4'
>>> transpose_agnostic_to_encoding(AgnosticPitch('C', 4), IntervalsByName['P4'], direction='down')
'G3'
>>> transpose_agnostic_to_encoding(AgnosticPitch('C#', 4), IntervalsByName['P4'])
'F#4'
>>> transpose_agnostic_to_encoding(AgnosticPitch('G', 4), IntervalsByName['m3'], direction='down')
'Bb4'
Source code in kernpy/core/transposer.py
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 |
|
transpose_agnostics(input_pitch, interval, direction=Direction.UP.value)
Transpose an AgnosticPitch by a given interval.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
input_pitch |
AgnosticPitch
|
The pitch to transpose. |
required |
interval |
int
|
The interval to transpose the pitch. |
required |
direction |
str
|
The direction of the transposition. 'UP' or 'DOWN'. Default is 'UP'. |
UP.value
|
Returns
AgnosticPitch: The transposed pitch.
Examples:
>>> transpose_agnostics(AgnosticPitch('C', 4), IntervalsByName['P4'])
AgnosticPitch('F', 4)
>>> transpose_agnostics(AgnosticPitch('C', 4), IntervalsByName['P4'], direction='down')
AgnosticPitch('G', 3)
>>> transpose_agnostics(AgnosticPitch('C#', 4), IntervalsByName['P4'])
AgnosticPitch('F#', 4)
>>> transpose_agnostics(AgnosticPitch('G', 4), IntervalsByName['m3'], direction='down')
AgnosticPitch('Bb', 4)
Source code in kernpy/core/transposer.py
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 |
|
transpose_encoding_to_agnostic(input_encoding, interval, input_format=NotationEncoding.HUMDRUM.value, direction=Direction.UP.value)
Transpose a pitch by a given interval.
The pitch must be in the American notation.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
input_encoding |
str
|
The pitch to transpose. |
required |
interval |
int
|
The interval to transpose the pitch. |
required |
input_format |
str
|
The encoding format of the pitch. Default is HUMDRUM. |
HUMDRUM.value
|
direction |
str
|
The direction of the transposition.'UP' or 'DOWN' Default is 'UP'. |
UP.value
|
Returns:
Name | Type | Description |
---|---|---|
AgnosticPitch |
AgnosticPitch
|
The transposed pitch. |
Examples:
>>> transpose_encoding_to_agnostic('ccc', IntervalsByName['P4'], input_format='kern')
AgnosticPitch('fff', 4)
>>> transpose_encoding_to_agnostic('ccc', IntervalsByName['P4'], input_format=NotationEncoding.HUMDRUM.value)
AgnosticPitch('fff', 4)
>>> transpose_encoding_to_agnostic('ccc', IntervalsByName['P4'], input_format='kern', direction='down')
AgnosticPitch('gg', 3)
>>> transpose_encoding_to_agnostic('ccc#', IntervalsByName['P4'])
AgnosticPitch('fff#', 4)
>>> transpose_encoding_to_agnostic('G4', IntervalsByName['m3'], input_format='american')
AgnosticPitch('Bb4', 4)
>>> transpose_encoding_to_agnostic('C3', IntervalsByName['P4'], input_format='american', direction='down')
AgnosticPitch('G2', 2)
Source code in kernpy/core/transposer.py
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 |
|
kernpy.util
=====
This module contains utility functions for the kernpy package.
StoreCache
A simple cache that stores the result of a callback function
Source code in kernpy/util/store_cache.py
1 2 3 4 5 6 7 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 |
|
__init__()
Constructor
Source code in kernpy/util/store_cache.py
5 6 7 8 9 |
|
request(callback, request)
Request a value from the cache. If the value is not in the cache, it will be calculated by the callback function Args: callback (function): The callback function that will be called to calculate the value request (any): The request that will be passed to the callback function
Returns (any): The value that was requested
Examples:
>>> def add_five(x):
... return x + 5
>>> store_cache = StoreCache()
>>> store_cache.request(callback, 5) # Call the callback function
10
>>> store_cache.request(callback, 5) # Return the value from the cache, without calling the callback function
10
Source code in kernpy/util/store_cache.py
11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
|