Dataset Viewer
Auto-converted to Parquet
txt
stringlengths
202
72.4k
### ---------------------------------------------------- ### -- ABC ### -- Licenses: Artistic-2.0 ### -- Authors: ### -- File: dg-check.raku ### ---------------------------------------------------- use v6; use lib 'lib'; use ABC; my @matches = $*IN.slurp.comb(m/ <ABC::tune> /, :match); my %dg_notes = { 'g' => 1, 'a' => 1, 'b' => 1, 'c' => 1, 'd' => 1, 'e' => 1, '^f' => 1 } for @matches { my %header = header_hash(.<ABC::tune><header>); say %header<T> ~ ":"; my @notes = gather for .<ABC::tune><music><line_of_music> -> $line { for $line<bar> -> $bar { for $bar<element> { when .<broken_rhythm> { take .<broken_rhythm><stem>[0]<note>; take .<broken_rhythm><stem>[1]<note>; } when .<stem> { take .<stem><note>; } } } } my %key_signature = key_signature(%header<K>); my @trouble = @notes.map({apply_key_signature(%key_signature, .<pitch>)}).grep({!%dg_notes{lc($_)}:exists}); say @trouble.perl; }
### ---------------------------------------------------- ### -- ABC ### -- Licenses: Artistic-2.0 ### -- Authors: ### -- File: META6.json ### ---------------------------------------------------- { "perl" : "6.*", "name" : "ABC", "version" : "0.7.2", "auth" : "zef:colomon", "description" : "Toolkit for dealing with ABC music notation", "depends" : [ "File::Temp" ], "license" : "Artistic-2.0", "provides" : { "abc2ly" : "bin/abc2ly", "abc2book" : "bin/abc2book", "abctranspose" : "bin/abctranspose", "abcoctave" : "bin/abcoctave", "abc2tuneindex" : "bin/abc2tuneindex", "ABC::Duration" : "lib/ABC/Duration.rakumod", "ABC::Pitched" : "lib/ABC/Pitched.rakumod", "ABC::Header" : "lib/ABC/Header.rakumod", "ABC::Grammar" : "lib/ABC/Grammar.rakumod", "ABC::Note" : "lib/ABC/Note.rakumod", "ABC::Stem" : "lib/ABC/Stem.rakumod", "ABC::KeyInfo" : "lib/ABC/KeyInfo.rakumod", "ABC::Utils" : "lib/ABC/Utils.rakumod", "ABC::Tune" : "lib/ABC/Tune.rakumod", "ABC::Rest" : "lib/ABC/Rest.rakumod", "ABC::Tuplet" : "lib/ABC/Tuplet.rakumod", "ABC::BrokenRhythm" : "lib/ABC/BrokenRhythm.rakumod", "ABC::Chord" : "lib/ABC/Chord.rakumod", "ABC::LongRest" : "lib/ABC/LongRest.rakumod", "ABC::GraceNotes" : "lib/ABC/GraceNotes.rakumod", "ABC::Context" : "lib/ABC/Context.rakumod", "ABC::Actions" : "lib/ABC/Actions.rakumod", "ABC::ToLilypond" : "lib/ABC/ToLilypond.rakumod" }, "source-type" : "git", "source-url" : "git://github.com/colomon/ABC.git" }
### ---------------------------------------------------- ### -- ABC ### -- Licenses: Artistic-2.0 ### -- Authors: ### -- File: LICENSE ### ---------------------------------------------------- The Artistic License 2.0 Copyright (c) 2000-2006, The Perl Foundation. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble This license establishes the terms under which a given free software Package may be copied, modified, distributed, and/or redistributed. The intent is that the Copyright Holder maintains some artistic control over the development of that Package while still keeping the Package available as open source and free software. You are always permitted to make arrangements wholly outside of this license directly with the Copyright Holder of a given Package. If the terms of this license do not permit the full use that you propose to make of the Package, you should contact the Copyright Holder and seek a different licensing arrangement. Definitions "Copyright Holder" means the individual(s) or organization(s) named in the copyright notice for the entire Package. "Contributor" means any party that has contributed code or other material to the Package, in accordance with the Copyright Holder's procedures. "You" and "your" means any person who would like to copy, distribute, or modify the Package. "Package" means the collection of files distributed by the Copyright Holder, and derivatives of that collection and/or of those files. A given Package may consist of either the Standard Version, or a Modified Version. "Distribute" means providing a copy of the Package or making it accessible to anyone else, or in the case of a company or organization, to others outside of your company or organization. "Distributor Fee" means any fee that you charge for Distributing this Package or providing support for this Package to another party. It does not mean licensing fees. "Standard Version" refers to the Package if it has not been modified, or has been modified only in ways explicitly requested by the Copyright Holder. "Modified Version" means the Package, if it has been changed, and such changes were not explicitly requested by the Copyright Holder. "Original License" means this Artistic License as Distributed with the Standard Version of the Package, in its current version or as it may be modified by The Perl Foundation in the future. "Source" form means the source code, documentation source, and configuration files for the Package. "Compiled" form means the compiled bytecode, object code, binary, or any other form resulting from mechanical transformation or translation of the Source form. Permission for Use and Modification Without Distribution (1) You are permitted to use the Standard Version and create and use Modified Versions for any purpose without restriction, provided that you do not Distribute the Modified Version. Permissions for Redistribution of the Standard Version (2) You may Distribute verbatim copies of the Source form of the Standard Version of this Package in any medium without restriction, either gratis or for a Distributor Fee, provided that you duplicate all of the original copyright notices and associated disclaimers. At your discretion, such verbatim copies may or may not include a Compiled form of the Package. (3) You may apply any bug fixes, portability changes, and other modifications made available from the Copyright Holder. The resulting Package will still be considered the Standard Version, and as such will be subject to the Original License. Distribution of Modified Versions of the Package as Source (4) You may Distribute your Modified Version as Source (either gratis or for a Distributor Fee, and with or without a Compiled form of the Modified Version) provided that you clearly document how it differs from the Standard Version, including, but not limited to, documenting any non-standard features, executables, or modules, and provided that you do at least ONE of the following: (a) make the Modified Version available to the Copyright Holder of the Standard Version, under the Original License, so that the Copyright Holder may include your modifications in the Standard Version. (b) ensure that installation of your Modified Version does not prevent the user installing or running the Standard Version. In addition, the Modified Version must bear a name that is different from the name of the Standard Version. (c) allow anyone who receives a copy of the Modified Version to make the Source form of the Modified Version available to others under (i) the Original License or (ii) a license that permits the licensee to freely copy, modify and redistribute the Modified Version using the same licensing terms that apply to the copy that the licensee received, and requires that the Source form of the Modified Version, and of any works derived from it, be made freely available in that license fees are prohibited but Distributor Fees are allowed. Distribution of Compiled Forms of the Standard Version or Modified Versions without the Source (5) You may Distribute Compiled forms of the Standard Version without the Source, provided that you include complete instructions on how to get the Source of the Standard Version. Such instructions must be valid at the time of your distribution. If these instructions, at any time while you are carrying out such distribution, become invalid, you must provide new instructions on demand or cease further distribution. If you provide valid instructions or cease distribution within thirty days after you become aware that the instructions are invalid, then you do not forfeit any of your rights under this license. (6) You may Distribute a Modified Version in Compiled form without the Source, provided that you comply with Section 4 with respect to the Source of the Modified Version. Aggregating or Linking the Package (7) You may aggregate the Package (either the Standard Version or Modified Version) with other packages and Distribute the resulting aggregation provided that you do not charge a licensing fee for the Package. Distributor Fees are permitted, and licensing fees for other components in the aggregation are permitted. The terms of this license apply to the use and Distribution of the Standard or Modified Versions as included in the aggregation. (8) You are permitted to link Modified and Standard Versions with other works, to embed the Package in a larger work of your own, or to build stand-alone binary or bytecode versions of applications that include the Package, and Distribute the result without restriction, provided the result does not expose a direct interface to the Package. Items That are Not Considered Part of a Modified Version (9) Works (including, but not limited to, modules and scripts) that merely extend or make use of the Package, do not, by themselves, cause the Package to be a Modified Version. In addition, such works are not considered parts of the Package itself, and are not subject to the terms of this license. General Provisions (10) Any use, modification, and distribution of the Standard or Modified Versions is governed by this Artistic License. By using, modifying or distributing the Package, you accept this license. Do not use, modify, or distribute the Package, if you do not accept this license. (11) If your Modified Version has been derived from a Modified Version made by someone other than you, you are nevertheless required to ensure that your Modified Version complies with the requirements of this license. (12) This license does not grant you the right to use any trademark, service mark, tradename, or logo of the Copyright Holder. (13) This license includes the non-exclusive, worldwide, free-of-charge patent license to make, have made, use, offer to sell, sell, import and otherwise transfer the Package with respect to any patent claims licensable by the Copyright Holder that are necessarily infringed by the Package. If you institute patent litigation (including a cross-claim or counterclaim) against any party alleging that the Package constitutes direct or contributory patent infringement, then this Artistic License to you shall terminate on the date that such litigation is filed. (14) Disclaimer of Warranty: THE PACKAGE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS "AS IS' AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES. THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT ARE DISCLAIMED TO THE EXTENT PERMITTED BY YOUR LOCAL LAW. UNLESS REQUIRED BY LAW, NO COPYRIGHT HOLDER OR CONTRIBUTOR WILL BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING IN ANY WAY OUT OF THE USE OF THE PACKAGE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
### ---------------------------------------------------- ### -- ABC ### -- Licenses: Artistic-2.0 ### -- Authors: ### -- File: README.md ### ---------------------------------------------------- # ABC This module is a set of tools for dealing with [ABC music notation](https://abcnotation.com/wiki/abc:standard:v2.1) files in Raku (formerly known as Perl 6). This includes a grammar for most of the notation format (the standard has a lot of twisty corners, and we do not support all of them), Raku data structures for representing them, and some useful utilities. ```raku my $music = q:to<ABC-end>; X:044 T:Elsie Marley B:Robin Williamson, "Fiddle Tunes" (New York 1976) N:"printed by Robert Petrie in 1796 and is N:"described by him as a 'bumpkin'." Z:Nigel Gatherer M:6/8 L:1/8 K:G BAB G2G|G2g gdc|BAB G2G|=F2f fcA| BAB G2G|G2g gdB|c2a B2g|A2=f fcA:| ABC-end my $match = ABC::Grammar.parse($music, :rule<tune>, :actions(ABC::Actions.new)); ok $match, 'tune recognized'; isa-ok $match.ast, ABC::Tune, 'and ABC::Tune created'; ok $match.ast.header.is-valid, "ABC::Tune's header is valid"; is $match.ast.music.elems, 57, '$match.ast.music has 57 elements'; ``` There are several scripts in bin/ built on the library: * abc2ly: converts an ABC file to the Lilypond ly format, then invokes Lilypond on it to create high quality sheet music. If you install ABC using zef you should just be able to say ```abc2ly wedding.abc```to convert ```wedding.abc``` to ```wedding.pdf``` via Lilypond file ```wedding.ly``` NOTE: Lilypond also has an abc2ly script; last time I tried it it produced hideous looking output from Lilypond. If you've got both installed, you will have to make sure the Raku bin of abc2ly appears first in your PATH. * abc2book: Given an ABC file and a simple “book” instructions file (our own format), this makes a book PDF. This uses Lilypond for music formatting, LaTeX for table of contents and index of tunes, and qpdf to stitch the results together into one file. This is still pretty experimental, but has produced one published book, [The Fiddle Music of Newfoundland & Labrador Volume 1, Revised 2020 Edition](https://fmnl1.nltrad.ca) * abctranspose: Simple tool for transposing ABC files. * abcoctave: Simple tool for shifting the octave of ABC files.
### ---------------------------------------------------- ### -- ABC ### -- Licenses: Artistic-2.0 ### -- Authors: ### -- File: playing.raku ### ---------------------------------------------------- use v6; use lib 'lib'; use ABC; my $abc = q«X:64 T:Cuckold Come Out o' the Amrey S:Northumbrian Minstrelsy M:4/4 L:1/8 K:D A/B/c/A/ +trill+c>d e>deg | GG +trill+B>c d/B/A/G/ B/c/d/B/ | A/B/c/A/ c>d e>deg | dB/A/ gB +trill+A2 +trill+e2 :: g>ecg ec e/=f/g/e/ | d/c/B/A/ Gd BG B/c/d/B/ | g/f/e/d/ c/d/e/f/ gc e/f/g/e/ | dB/A/ gB +trill+A2 +trill+e2 :|»; my $match = $abc ~~ m/ <ABC::tune> /; die "Tune not matched\n" unless $match ~~ Match; my @notes = gather for $match<ABC::tune><music><line_of_music> -> $line { for $line<bar> -> $bar { for $bar<element> { when .<broken_rhythm> { take .<broken_rhythm><mnote>[0]; take .<broken_rhythm><mnote>[1]; } when .<mnote> { take .<mnote>; } } } } my %header = header_hash($match<ABC::tune><header>); my %key_signature = key_signature(%header<K>); for @notes { say .<pitch> ~ " => " ~ apply_key_signature(%key_signature, .<pitch>); }
### ---------------------------------------------------- ### -- ABC ### -- Licenses: Artistic-2.0 ### -- Authors: ### -- File: .travis.yml ### ---------------------------------------------------- --- sudo: false language: perl6 perl6: - latest
### ---------------------------------------------------- ### -- ABC ### -- Licenses: Artistic-2.0 ### -- Authors: ### -- File: t/05-actions.rakutest ### ---------------------------------------------------- use v6; use Test; use ABC::Header; use ABC::Tune; use ABC::Grammar; use ABC::Actions; use ABC::Note; use ABC::Stem; use ABC::Rest; use ABC::Tuplet; use ABC::BrokenRhythm; use ABC::Chord; { my $match = ABC::Grammar.parse('F#', :rule<chord>, :actions(ABC::Actions.new)); ok $match, 'chord recognized'; isa-ok $match.ast, ABC::Chord, '$match.ast is an ABC::Chord'; is $match.ast.main-note, "F", "Pitch F"; is $match.ast.main-accidental, "#", "...sharp"; } { my $match = ABC::Grammar.parse('Bbmin/G#', :rule<chord>, :actions(ABC::Actions.new)); ok $match, 'chord recognized'; isa-ok $match.ast, ABC::Chord, '$match.ast is an ABC::Chord'; is $match.ast.main-note, "B", "Pitch B"; is $match.ast.main-accidental, "b", "...flat"; is $match.ast.main-type, "min", "...min"; is $match.ast.bass-note, "G", "over G"; is $match.ast.bass-accidental, "#", "...#"; } { my $match = ABC::Grammar.parse('"F#"', :rule<chord_or_text>, :actions(ABC::Actions.new)); ok $match, 'chord_or_text recognized'; isa-ok $match.ast[0], ABC::Chord, '$match.ast[0] is an ABC::Chord'; is $match.ast[0].main-note, "F", "Pitch F"; is $match.ast[0].main-accidental, "#", "...sharp"; } { my $match = ABC::Grammar.parse('{gf}', :rule<grace_notes>, :actions(ABC::Actions.new)); ok $match, 'grace_notes recognized'; isa-ok $match.ast, ABC::GraceNotes, '$match.ast is an ABC::GraceNotes'; nok $match.ast.acciaccatura, "It's not an acciaccatura"; is $match.ast.notes[0].pitch, "g", "Pitch g found"; is $match.ast.notes[1].pitch, "f", "Pitch g found"; } { my $match = ABC::Grammar.parse('"F#"', :rule<element>, :actions(ABC::Actions.new)); ok $match, 'element recognized'; isa-ok $match.ast, Pair, '$match.ast is a Pair'; is $match.ast.key, "chord_or_text", '$match.ast.key is "chord_or_text"'; is $match.ast.value[0].main-note, "F", "Pitch F"; is $match.ast.value[0].main-accidental, "#", "...sharp"; } { my $match = ABC::Grammar.parse('"^Bb whistle"', :rule<element>, :actions(ABC::Actions.new)); ok $match, 'element recognized'; isa-ok $match.ast, Pair, '$match.ast is a Pair'; is $match.ast.key, "chord_or_text", '$match.ast.key is "chord_or_text"'; isa-ok $match.ast.value[0], Str, "And it's text"; is $match.ast.value[0], "^Bb whistle", '$match.ast.value[0] is ^Bb whistle'; } { my $match = ABC::Grammar.parse("e3", :rule<mnote>, :actions(ABC::Actions.new)); ok $match, 'element recognized'; isa-ok $match.ast, ABC::Note, '$match.ast is an ABC::Note'; is $match.ast.pitch, "e", "Pitch e"; is $match.ast.ticks, 3, "Duration 3 ticks"; } { my $match = ABC::Grammar.parse("e", :rule<mnote>, :actions(ABC::Actions.new)); ok $match, 'element recognized'; isa-ok $match.ast, ABC::Note, '$match.ast is an ABC::Note'; is $match.ast.pitch, "e", "Pitch e"; is $match.ast.ticks, 1, "Duration 1 ticks"; } { my $match = ABC::Grammar.parse("^e,/", :rule<mnote>, :actions(ABC::Actions.new)); ok $match, 'element recognized'; isa-ok $match.ast, ABC::Note, '$match.ast is an ABC::Note'; is $match.ast.pitch, "^e,", "Pitch ^e,"; is $match.ast.ticks, 1/2, "Duration 1/2 ticks"; } { my $match = ABC::Grammar.parse("[a2bc]3", :rule<stem>, :actions(ABC::Actions.new)); ok $match, 'element recognized'; isa-ok $match.ast, ABC::Stem, '$match.ast is an ABC::Stem'; is $match.ast.notes[0], "a2", "Pitch 1 a"; is $match.ast.notes[1], "b", "Pitch 2 b"; is $match.ast.notes[2], "c", "Pitch 3 c"; is $match.ast.ticks, 6, "Duration 6 ticks"; nok $match.ast.is-tie, "Not tied"; } { my $match = ABC::Grammar.parse("[a2bc]/-", :rule<stem>, :actions(ABC::Actions.new)); ok $match, 'element recognized'; isa-ok $match.ast, ABC::Stem, '$match.ast is an ABC::Stem'; is $match.ast.notes[0], "a2", "Pitch 1 a"; is $match.ast.notes[1], "b", "Pitch 2 b"; is $match.ast.notes[2], "c", "Pitch 3 c"; is $match.ast.ticks, 1, "Duration 1 tick"; ok $match.ast.is-tie, "Tied"; } { my $match = ABC::Grammar.parse("z/", :rule<rest>, :actions(ABC::Actions.new)); ok $match, 'rest recognized'; isa-ok $match.ast, ABC::Rest, '$match.ast is an ABC::Rest'; is $match.ast.type, "z", "Rest is z"; is $match.ast.ticks, 1/2, "Duration 1/2 ticks"; } { my $match = ABC::Grammar.parse("F3/2", :rule<mnote>, :actions(ABC::Actions.new)); ok $match, 'element recognized'; isa-ok $match.ast, ABC::Note, '$match.ast is an ABC::Note'; is $match.ast.pitch, "F", "Pitch F"; is $match.ast.ticks, 3/2, "Duration 3/2 ticks"; } { my $match = ABC::Grammar.parse("F2/3", :rule<mnote>, :actions(ABC::Actions.new)); ok $match, 'element recognized'; isa-ok $match.ast, ABC::Note, '$match.ast is an ABC::Note'; is $match.ast.pitch, "F", "Pitch F"; is $match.ast.ticks, 2/3, "Duration 2/3 ticks"; } { my $match = ABC::Grammar.parse("(3abc", :rule<tuplet>, :actions(ABC::Actions.new)); ok $match, 'tuplet recognized'; isa-ok $match.ast, ABC::Tuplet, '$match.ast is an ABC::Tuplet'; is $match.ast.tuple, "3", "It's a triplet"; is $match.ast.ticks, 2, "Duration 2 ticks"; is +$match.ast.notes, 3, "Three internal note"; ok $match.ast.notes[0] ~~ ABC::Stem | ABC::Note, "First internal note is of the correct type"; is $match.ast.notes, "a b c", "Notes are correct"; } { my $match = ABC::Grammar.parse("a>~b", :rule<broken_rhythm>, :actions(ABC::Actions.new)); ok $match, 'broken rhythm recognized'; isa-ok $match.ast, ABC::BrokenRhythm, '$match.ast is an ABC::BrokenRhythm'; is $match.ast.ticks, 2, "total duration is two ticks"; isa-ok $match.ast.effective-stem1, ABC::Note, "effective-stem1 is a note"; is $match.ast.effective-stem1.pitch, "a", "first pitch is a"; is $match.ast.effective-stem1.ticks, 1.5, "first duration is 1 + 1/2"; isa-ok $match.ast.effective-stem2, ABC::Note, "effective-stem2 is a note"; is $match.ast.effective-stem2.pitch, "b", "first pitch is a"; is $match.ast.effective-stem2.ticks, .5, "second duration is 1/2"; } { my $match = ABC::Grammar.parse("a<<<b", :rule<broken_rhythm>, :actions(ABC::Actions.new)); ok $match, 'broken rhythm recognized'; isa-ok $match.ast, ABC::BrokenRhythm, '$match.ast is an ABC::BrokenRhythm'; is $match.ast.ticks, 2, "total duration is two ticks"; isa-ok $match.ast.effective-stem1, ABC::Note, "effective-stem1 is a note"; is $match.ast.effective-stem1.pitch, "a", "first pitch is a"; is $match.ast.effective-stem1.ticks, 1/8, "first duration is 1/8"; isa-ok $match.ast.effective-stem2, ABC::Note, "effective-stem2 is a note"; is $match.ast.effective-stem2.pitch, "b", "first pitch is a"; is $match.ast.effective-stem2.ticks, 15/8, "second duration is 1 + 7/8"; } { my $match = ABC::Grammar.parse("[K:F]", :rule<element>, :actions(ABC::Actions.new)); ok $match, 'inline field recognized'; # isa-ok $match.ast, ABC::BrokenRhythm, '$match.ast is an ABC::BrokenRhythm'; is $match<inline_field><alpha>, "K", "field type is K"; is $match<inline_field><value>, "F", "field value is K"; } { my $match = ABC::Grammar.parse("+fff+", :rule<long_gracing>, :actions(ABC::Actions.new)); ok $match, 'long gracing recognized'; isa-ok $match.ast, Str, '$match.ast is a Str'; is $match.ast, "fff", "gracing is fff"; } { my $match = ABC::Grammar.parse("+fff+", :rule<gracing>, :actions(ABC::Actions.new)); ok $match, 'long gracing recognized'; isa-ok $match.ast, Str, '$match.ast is a Str'; is $match.ast, "fff", "gracing is fff"; } { my $match = ABC::Grammar.parse("~", :rule<gracing>, :actions(ABC::Actions.new)); ok $match, 'gracing recognized'; isa-ok $match.ast, Str, '$match.ast is a Str'; is $match.ast, "~", "gracing is ~"; } { my $match = ABC::Grammar.parse("+fff+", :rule<element>, :actions(ABC::Actions.new)); ok $match, 'long gracing recognized'; is $match.ast.key, "gracing", '$match.ast.key is gracing'; isa-ok $match.ast.value, Str, '$match.ast.value is a Str'; is $match.ast.value, "fff", "gracing is fff"; } { my $music = q«X:64 T:Cuckold Come Out o' the Amrey S:Northumbrian Minstrelsy M:4/4 L:1/8 K:D »; my $match = ABC::Grammar.parse($music, :rule<header>, :actions(ABC::Actions.new)); ok $match, 'tune recognized'; isa-ok $match.ast, ABC::Header, '$match.ast is an ABC::Header'; is $match.ast.get("T").elems, 1, "One T field found"; is $match.ast.get("T")[0].value, "Cuckold Come Out o' the Amrey", "And it's correct"; ok $match.ast.is-valid, "ABC::Header is valid"; } { my $match = ABC::Grammar.parse("e3", :rule<element>, :actions(ABC::Actions.new)); ok $match, 'element recognized'; isa-ok $match.ast, Pair, '$match.ast is a Pair'; is $match.ast.key, "stem", "Stem found"; isa-ok $match.ast.value, ABC::Note, "Value is note"; } { my $match = ABC::Grammar.parse("G2g gdc|", :rule<bar>, :actions(ABC::Actions.new)); ok $match, 'element recognized'; is $match.ast.elems, 7, '$match.ast has seven elements'; is $match.ast[3].key, "stem", "Fourth is stem"; is $match.ast[*-1].key, "barline", "Last is barline"; } { my $match = ABC::Grammar.parse("G2g gdc", :rule<bar>, :actions(ABC::Actions.new)); ok $match, 'element recognized'; is $match.ast.elems, 6, '$match.ast has six elements'; is $match.ast[3].key, "stem", "Fourth is stem"; is $match.ast[*-1].key, "stem", "Last is stem"; } { my $music = q«BAB G2G|G2g gdc|1BAB G2G|2=F2f fcA| BAB G2G|G2g gdB|c2a B2g|A2=f fcA:| »; my $match = ABC::Grammar.parse($music, :rule<music>, :actions(ABC::Actions.new)); ok $match, 'element recognized'; # say $match.ast.perl; is $match.ast.elems, 59, '$match.ast has 59 elements'; # say $match.ast.elems; # say $match.ast[28].WHAT; # say $match.ast[28].perl; is $match.ast[22].key, "nth_repeat", "21st is nth_repeat"; isa-ok $match.ast[22].value, Set, "21st value is a Set"; ok $match.ast[22].value ~~ (set 2), "21st is '2'"; is $match.ast[30].key, "endline", "29th is endline"; is $match.ast[*-1].key, "endline", "Last is endline"; } { my $music = q«BAB G2G|G2g gdc|BAB G2G|=F2f fcA| BAB G2G|G2g gdB|c2a B2g|A2=f fcA:| »; my $match = ABC::Grammar.parse($music, :rule<music>, :actions(ABC::Actions.new)); ok $match, 'element recognized'; # say $match.ast.perl; is $match.ast.elems, 57, '$match.ast has 57 elements'; # say $match.ast.elems; # say $match.ast[28].WHAT; # say $match.ast[28].perl; is $match.ast[28].key, "endline", "29th is endline"; is $match.ast[*-1].key, "endline", "Last is endline"; } { my $music = q:to<ABC-end>; X:044 T:Elsie Marley B:Robin Williamson, "Fiddle Tunes" (New York 1976) N:"printed by Robert Petrie in 1796 and is N:"described by him as a 'bumpkin'." Z:Nigel Gatherer M:6/8 L:1/8 K:G BAB G2G|G2g gdc|BAB G2G|=F2f fcA| BAB G2G|G2g gdB|c2a B2g|A2=f fcA:| ABC-end my $match = ABC::Grammar.parse($music, :rule<tune>, :actions(ABC::Actions.new)); ok $match, 'tune recognized'; isa-ok $match.ast, ABC::Tune, 'and ABC::Tune created'; ok $match.ast.header.is-valid, "ABC::Tune's header is valid"; is $match.ast.music.elems, 57, '$match.ast.music has 57 elements'; } { my $match = ABC::Grammar.parse(slurp("samples.abc"), :rule<tune_file>, :actions(ABC::Actions.new)); ok $match, 'samples.abc is a valid tune file'; # say $match.ast.perl; is @( $match<tune> ).elems, 3, "Three tunes were found"; # is @( $match.ast )[0].elems, 3, "Three tunes were found"; isa-ok @( $match.ast )[0][0], ABC::Tune, "First is an ABC::Tune"; } { my $music = q«X:1 T:Canon in D C:Pachelbel M:2/2 L:1/8 K:D "D" DFAd "A" CEAc|"Bm" B,DFB "F#m" A,CFA|"G" B,DGB "D" A,DFA|"G" B,DGB "A" CEAc| "D" f4 "A" e4|"Bm" d4 "F#m" c4|"G" B4 "D" A4|"G" B4 "A" c4|»; my $match = ABC::Grammar.parse($music, :rule<tune_file>, :actions(ABC::Actions.new)); isa-ok $match, Match, 'Got a match'; ok $match, 'tune_file recognized'; is $match<tune>.elems, 1, 'found one tune'; is $match<tune>[0]<music><line_of_music>.elems, 2, "with two lines of music"; } done-testing;
### ---------------------------------------------------- ### -- ABC ### -- Licenses: Artistic-2.0 ### -- Authors: ### -- File: t/10-utils.rakutest ### ---------------------------------------------------- use v6; use Test; use ABC::Utils; is default-length-from-meter("4/4"), "1/8", "4/4 defaults to eighth note"; is default-length-from-meter("2/2"), "1/8", "2/2 defaults to eighth note"; is default-length-from-meter("3/4"), "1/8", "3/4 defaults to eighth note"; is default-length-from-meter("6/8"), "1/8", "6/8 defaults to eighth note"; is default-length-from-meter("2/4"), "1/16", "2/4 defaults to sixteenth note"; is default-length-from-meter("C"), "1/8", "Common time defaults to eighth note"; is default-length-from-meter("C|"), "1/8", "Cut time defaults to eighth note"; is default-length-from-meter(""), "1/8", "No meter defaults to eighth note"; is default-length-from-meter("none"), "1/8", "No meter defaults to eighth note"; for flat 'A'..'G' X 2..8 -> $note, $octave-number { my ($pitch, $symbol) = from-note-and-number($note, $octave-number); my ($computed-note, $computed-number) = to-note-and-number($pitch, $symbol); is $computed-note, $note, "Note is correct after round trip through note-and-symbol"; is $computed-number, $octave-number, "Octave number is correct after round trip through note-and-symbol"; } my %key; is pitch-to-ordinal(%key, "", "C", ""), 0, "Middle C is correct"; is pitch-to-ordinal(%key, "^", "B", ","), 0, "B-sharp below middle C is correct"; is pitch-to-ordinal(%key, "__", "D", ""), 0, "D-double-flat above middle C is correct"; is pitch-to-ordinal(%key, "", "c", ""), 12, "Third space C is correct"; is pitch-to-ordinal(%key, "^", "B", ""), 12, "Middle line B-sharp is correct"; is pitch-to-ordinal(%key, "__", "d", ""), 12, "Fourth line D-double-flat is correct"; is ordinal-to-pitch(%key, "C", 0), ("", "C", ""), "Middle C translates back okay"; is ordinal-to-pitch(%key, "B", 0), ("^", "B", ","), "B-sharp below middle C translates back okay"; is ordinal-to-pitch(%key, "D", 0), ("__", "D", ""), "D-double-flat above middle C translates back okay"; is ordinal-to-pitch(%key, "C", 12), ("", "c", ""), "Third space C translates back okay"; is ordinal-to-pitch(%key, "B", 12), ("^", "B", ""), "Middle line B-sharp translates back okay"; is ordinal-to-pitch(%key, "D", 12), ("__", "d", ""), "Fourth line D-double-flat translates back okay"; done-testing;
### ---------------------------------------------------- ### -- ABC ### -- Licenses: Artistic-2.0 ### -- Authors: ### -- File: t/08-transpose.rakutest ### ---------------------------------------------------- use v6; use Test; use ABC::Grammar; use ABC::Header; use ABC::Tune; use ABC::Duration; use ABC::Note; use ABC::Rest; use ABC::Tuplet; use ABC::BrokenRhythm; use ABC::Chord; use ABC::LongRest; use ABC::GraceNotes; use ABC::Actions; use ABC::Utils; use ABC::Pitched; use ABC::KeyInfo; sub transpose(Str $test, $pitch-changer) { my $match = ABC::Grammar.parse($test, :rule<element>, :actions(ABC::Actions.new)); if $match { given $match.ast.value { when Positional { $_>>.transpose($pitch-changer); } when ABC::Pitched { $_.transpose($pitch-changer); } die "Don't know how to transpose { $_.WHAT }"; } } } sub up-octave($accidental, $basenote, $octave) { if $octave ~~ /","/ { return ($accidental, $basenote, $/.postmatch); } elsif $octave ~~ /"'"/ || $basenote ~~ /<lower>/ { return ($accidental, $basenote, $octave ~ "'"); } else { return ($accidental, $basenote.lc, $octave); } } is transpose("A", &up-octave), "a", "Octave bump to A yields a"; is transpose("a", &up-octave), "a'", "Octave bump to a yields a'"; is transpose("a''2", &up-octave), "a'''2", "Octave bump to a'' yields a'''"; is transpose("A,-", &up-octave), "A-", "Octave bump to A, yields A"; is transpose("A,,", &up-octave), "A,", "Octave bump to A,, yields A,"; is transpose("[C,Eg]", &up-octave), "[Ceg']", "Octave bump to [C,Eg] yields [Ceg']"; is transpose("[C,Eg]", &up-octave), "[Ceg']", "Octave bump to [C,Eg] yields [Ceg']"; is transpose("(3C,Eg", &up-octave), "(3Ceg'", "Octave bump to (3C,Eg yields (3Ceg'"; is transpose("A<a", &up-octave), "a<a'", "Octave bump to A<a yields a<a'"; is transpose('{Bc}', &up-octave), '{bc\'}', "Octave bump to Bc yields bc'"; is transpose('"Amin/F"', &up-octave), '"Amin/F"', "Octave bump to chord yields no change"; sub pitch2ordinal(%key, $test) { my $match = ABC::Grammar.parse($test, :rule<mnote>, :actions(ABC::Actions.new)); if $match { pitch-to-ordinal(%key, $match.ast.accidental, $match.ast.basenote, $match.ast.octave); } } { my %key = ABC::KeyInfo.new("C").key; is pitch2ordinal(%key, "C"), 0, "C ==> 0"; is pitch2ordinal(%key, "D"), 2, "D ==> 2"; is pitch2ordinal(%key, "E"), 4, "E ==> 4"; is pitch2ordinal(%key, "F"), 5, "F ==> 5"; is pitch2ordinal(%key, "G"), 7, "G ==> 7"; is pitch2ordinal(%key, "A"), 9, "A ==> 9"; is pitch2ordinal(%key, "B"), 11, "B ==> 11"; is pitch2ordinal(%key, "c"), 12, "c ==> 12"; is pitch2ordinal(%key, "=A"), 9, "=A ==> 9"; is pitch2ordinal(%key, "^A"), 10, "^A ==> 10"; is pitch2ordinal(%key, "_A"), 8, "_A ==> 8"; is pitch2ordinal(%key, "^^A"), 11, "^^A ==> 11"; is pitch2ordinal(%key, "__A"), 7, "__A ==> 7"; is pitch2ordinal(%key, "^^G,,,"), -27, "^^G,,, ==> -27"; is pitch2ordinal(%key, "d'''"), 50, "d''' ==> 50"; %key = ABC::KeyInfo.new("Ab").key; is pitch2ordinal(%key, "C"), 0, "C ==> 0"; is pitch2ordinal(%key, "D"), 1, "D ==> 1"; is pitch2ordinal(%key, "E"), 3, "E ==> 3"; is pitch2ordinal(%key, "F"), 5, "F ==> 5"; is pitch2ordinal(%key, "G"), 7, "G ==> 7"; is pitch2ordinal(%key, "A"), 8, "A ==> 8"; is pitch2ordinal(%key, "B"), 10, "B ==> 10"; is pitch2ordinal(%key, "c"), 12, "c ==> 12"; is pitch2ordinal(%key, "=A"), 9, "=A ==> 9"; is pitch2ordinal(%key, "^A"), 10, "^A ==> 10"; is pitch2ordinal(%key, "_A"), 8, "_A ==> 8"; is pitch2ordinal(%key, "^^A"), 11, "^^A ==> 11"; is pitch2ordinal(%key, "__A"), 7, "__A ==> 7"; is pitch2ordinal(%key, "^^G,,,"), -27, "^^G,,, ==> -27"; is pitch2ordinal(%key, "d'''"), 49, "d''' ==> 49"; %key = ABC::KeyInfo.new("C").key; is ordinal-to-pitch(%key, "C", 0), " C ", "0/C => C"; is ordinal-to-pitch(%key, "D", 0), "__ D ", "0/D => __D"; is ordinal-to-pitch(%key, "B", 0), "^ B ,", "0/B => ^B,"; is ordinal-to-pitch(%key, "C", 1), "^ C ", "1/C => ^C"; is ordinal-to-pitch(%key, "D", 1), "_ D ", "1/D => _D"; is ordinal-to-pitch(%key, "B", 1), "^^ B ,", "1/B => ^^B,"; is ordinal-to-pitch(%key, "C", -1), "_ C ", "-1/C => _C"; is ordinal-to-pitch(%key, "B", -1), " B ,", "-1/B => B,"; is ordinal-to-pitch(%key, "C", -12), " C ,", "-12/C => C,"; is ordinal-to-pitch(%key, "D", -12), "__ D ,", "-12/D => __D,"; is ordinal-to-pitch(%key, "B", -12), "^ B ,,", "-12/B => ^B,,"; is ordinal-to-pitch(%key, "C", 11), "_ c ", "11/C => _c"; is ordinal-to-pitch(%key, "B", 11), " B ", "11/B => B"; is ordinal-to-pitch(%key, "C", 12), " c ", "12/C => c"; is ordinal-to-pitch(%key, "D", 12), "__ d ", "12/D => __d"; is ordinal-to-pitch(%key, "B", 12), "^ B ", "12/B => ^B"; is ordinal-to-pitch(%key, "C", 13), "^ c ", "1/C => ^c"; is ordinal-to-pitch(%key, "D", 13), "_ d ", "1/D => _d"; is ordinal-to-pitch(%key, "B", 13), "^^ B ", "1/B => ^^B"; is ordinal-to-pitch(%key, "C", 23), "_ c '", "23/C => _c'"; is ordinal-to-pitch(%key, "B", 23), " b ", "23/B => b"; is ordinal-to-pitch(%key, "C", 24), " c '", "24/C => c'"; is ordinal-to-pitch(%key, "D", 24), "__ d '", "24/D => __d'"; is ordinal-to-pitch(%key, "B", 24), "^ b ", "24/B => ^b"; is ordinal-to-pitch(%key, "C", 25), "^ c '", "25/C => ^c'"; is ordinal-to-pitch(%key, "D", 25), "_ d '", "25/D => _d'"; is ordinal-to-pitch(%key, "B", 25), "^^ b ", "25/B => ^^b"; } sub e-flat-to-d($accidental, $basenote, $octave) { my %e-flat = ABC::KeyInfo.new("Eb").key; my %d = ABC::KeyInfo.new("D").key; my $ordinal = pitch-to-ordinal(%e-flat, $accidental, $basenote, $octave); my $basenote-in-d = $basenote.uc eq "A" ?? "G" !! ($basenote.ord - 1).chr.uc; ordinal-to-pitch(%d, $basenote-in-d, $ordinal - 1); } is transpose("A", &e-flat-to-d), "G", "Eb to D on A yields G"; is transpose("a", &e-flat-to-d), "g", "Eb to D on a yields g"; is transpose("a''2", &e-flat-to-d), "g''2", "Eb to D on a'' yields g''"; is transpose("A,-", &e-flat-to-d), "G,-", "Eb to D on A,- yields G,-"; is transpose("[_EG_B]", &e-flat-to-d), "[DFA]", "Eb to D on [_EG_B] yields [DFA]"; is transpose("[EGB]", &e-flat-to-d), "[DFA]", "Eb to D on [EGB] yields [DFA]"; is transpose("(3C,Eg", &e-flat-to-d), "(3B,,Df", "Eb to D on (3C,Eg yields (3B,,Df"; is transpose("=A<a", &e-flat-to-d), "^G<g", "Eb to D on =A<a yields ^G<g"; is transpose('{Bc}', &e-flat-to-d), '{AB}', "Eb to D on Bc yields AB"; is transpose('"Amin/F"', &e-flat-to-d), '"G#min/E"', "Eb to D on Amin/F yields G#min/E"; is transpose('"Abmin/F"', &e-flat-to-d), '"Gmin/E"', "Eb to D on Abmin/F yields Gmin/E"; class Transposer { has %.key-changes; has $.half-step-shift; has $.pitch-name-shift; has %.current-from; has %.current-to; multi method new(%key-changes, $half-step-shift) { self.bless(:%key-changes, :$half-step-shift); } method set-key($new-key) { %.current-from = ABC::KeyInfo.new($new-key).key; %.current-to = ABC::KeyInfo.new(%.key-changes{$new-key}).key; # $.pitch-name-shift = $new-key. } method postcircumfix:<( )>($accidental, $basenote, $octave) { my $ordinal = pitch-to-ordinal(%.current-from, $accidental, $basenote, $octave); my $basenote-in-new-key = "A".ord + ($basenote.uc.ord - "A".ord + $.pitch-name-shift) % 7; ordinal-to-pitch(%.current-to, $basenote-in-new-key, $ordinal + $.half-step-shift); } } done-testing;
### ---------------------------------------------------- ### -- ABC ### -- Licenses: Artistic-2.0 ### -- Authors: ### -- File: t/02-key.rakutest ### ---------------------------------------------------- use v6; use Test; use ABC::Grammar; use ABC::Utils; use ABC::KeyInfo; { my $key = ABC::KeyInfo.new("D"); is $key.key.elems, 2, "D has two sharps"; is $key.key<F>, "^", "F is sharp"; is $key.key<C>, "^", "C is sharp"; ok !$key.clef.defined || $key.clef eq "treble" , "no clef defined"; is $key.octave-shift, 0, "octave-shift is 0"; } { my $key = ABC::KeyInfo.new("D bass"); is $key.key.elems, 2, "D has two sharps"; is $key.key<F>, "^", "F is sharp"; is $key.key<C>, "^", "C is sharp"; is $key.clef, "bass", "Recognized bass clef"; } { my $key = ABC::KeyInfo.new("Dmix"); is $key.key.elems, 1, "Dmix has one sharp"; is $key.key<F>, "^", "F is sharp"; } { my $key = ABC::KeyInfo.new("Am"); is $key.key.elems, 0, "Am has no sharps or flats"; } { my $key = ABC::KeyInfo.new("Ddor"); is $key.key.elems, 0, "Ddor has no sharps or flats"; } { my $key = ABC::KeyInfo.new("Ador"); is $key.key.elems, 1, "Ador has one sharp"; is $key.key<F>, "^", "F is sharp"; } { my $key = ABC::KeyInfo.new("Amix"); is $key.key.elems, 2, "Amix has two sharps"; is $key.key<F>, "^", "F is sharp"; is $key.key<C>, "^", "C is sharp"; } { my $key = ABC::KeyInfo.new("C#m"); is $key.key.elems, 4, "C#m has four sharps"; is $key.key<F>, "^", "F is sharp"; is $key.key<C>, "^", "C is sharp"; is $key.key<G>, "^", "G is sharp"; is $key.key<D>, "^", "D is sharp"; } { my $key = ABC::KeyInfo.new("C#"); is $key.key.elems, 7, "C# has seven sharps"; is $key.key<F>, "^", "F is sharp"; is $key.key<C>, "^", "C is sharp"; is $key.key<G>, "^", "G is sharp"; is $key.key<D>, "^", "D is sharp"; is $key.key<A>, "^", "A is sharp"; is $key.key<E>, "^", "E is sharp"; is $key.key<B>, "^", "B is sharp"; } { my $key = ABC::KeyInfo.new("C ^f _b"); is $key.key.elems, 2, "C ^f _b has two thingees"; is $key.key<F>, "^", "F is sharp"; is $key.key<B>, "_", "B is flat"; } { my $key = ABC::KeyInfo.new("C#m"); is apply_key_signature($key.key, ABC::Grammar.parse("f", :rule<pitch>)), "^f", "f => ^f"; is apply_key_signature($key.key, ABC::Grammar.parse("C", :rule<pitch>)), "^C", "C => ^C"; is apply_key_signature($key.key, ABC::Grammar.parse("G", :rule<pitch>)), "^G", "G => ^G"; is apply_key_signature($key.key, ABC::Grammar.parse("d", :rule<pitch>)), "^d", "d => ^d"; is apply_key_signature($key.key, ABC::Grammar.parse("_f", :rule<pitch>)), "_f", "_f => _f"; is apply_key_signature($key.key, ABC::Grammar.parse("=C", :rule<pitch>)), "=C", "=C => =C"; is apply_key_signature($key.key, ABC::Grammar.parse("^G", :rule<pitch>)), "^G", "^G => ^G"; is apply_key_signature($key.key, ABC::Grammar.parse("^^d", :rule<pitch>)), "^^d", "^^d => ^^d"; is apply_key_signature($key.key, ABC::Grammar.parse("b'", :rule<pitch>)), "b'", "b' => b'"; } done-testing;
### ---------------------------------------------------- ### -- ABC ### -- Licenses: Artistic-2.0 ### -- Authors: ### -- File: t/06-duration.rakutest ### ---------------------------------------------------- use v6; use Test; use ABC::Duration; is duration-from-parse("2", "3").ticks.perl, (2/3).perl, "2/3 works properly"; ok duration-from-parse("2", "3") ~~ ABC::Duration, "2/3 generates an object which does Duration"; is duration-from-parse(Any, Any).ticks.perl, (1/2).perl, "/ works properly"; ok duration-from-parse(Any, Any) ~~ ABC::Duration, "/ generates an object which does Duration"; is duration-from-parse("1", Any).ticks.perl, (1/2).perl, "1/ works properly"; is duration-from-parse(Any, "2").ticks.perl, (1/2).perl, "/2 works properly"; is duration-from-parse("1").ticks.perl, (1).perl, "1 works properly"; is duration-from-parse(Any).ticks.perl, (1).perl, "'' works properly"; done-testing;
### ---------------------------------------------------- ### -- ABC ### -- Licenses: Artistic-2.0 ### -- Authors: ### -- File: t/04-header.rakutest ### ---------------------------------------------------- use v6; use Test; use ABC::Header; isa-ok ABC::Header.new, ABC::Header, "Can create ABC::Header object"; { my $a = ABC::Header.new; $a.add-line("X", 1); is $a.lines.elems, 1, "One line now present in ABC::Header"; $a.add-line("T", "The Star of Rakudo"); $a.add-line("T", "Michaud's Favorite"); is $a.lines.elems, 3, "Three lines now present in ABC::Header"; is $a.get("T").elems, 2, "Two T lines found"; is $a.get("T")[0].value, "The Star of Rakudo", "First title correct"; is $a.get("T")[1].value, "Michaud's Favorite", "Second title correct"; nok $a.is-valid, "Not valid because its missing a bunch of needed fields"; $a.add-line("M", "2/2"); $a.add-line("L", "1/8"); nok $a.is-valid, "Not valid because its still missing the key signature"; $a.add-line("K", "G"); ok $a.is-valid, "Now valid!"; } { my $a = ABC::Header.new; $a.add-line("X", 1); $a.add-line("T", "The Star of Rakudo"); $a.add-line("T", "Michaud's Favorite"); $a.add-line("M", "2/2"); $a.add-line("K", "G"); $a.add-line("L", "1/8"); nok $a.is-valid, "Not valid, all fields present but K is not the last"; } { my $a = ABC::Header.new; $a.add-line("X", 1); $a.add-line("T", "The Star of Rakudo"); $a.add-line("T", "Michaud's Favorite"); $a.add-line("M", "2/2"); $a.add-line("M", "2/2"); $a.add-line("L", "1/8"); $a.add-line("K", "G"); nok $a.is-valid, "Not valid, too many Ms"; } { my $a = ABC::Header.new; $a.add-line("X", 1); $a.add-line("T", "The Star of Rakudo"); $a.add-line("T", "Michaud's Favorite"); $a.add-line("L", "1/8"); $a.add-line("K", "G"); nok $a.is-valid, "Not valid, too few Ms"; } { my $a = ABC::Header.new; $a.add-line("X", 1); $a.add-line("T", "The Star of Rakudo"); $a.add-line("T", "Michaud's Favorite"); $a.add-line("M", "2/2"); $a.add-line("K", "G"); nok $a.is-valid, "Not valid, too few Ls"; } { my $a = ABC::Header.new; $a.add-line("X", 1); $a.add-line("T", "The Star of Rakudo"); $a.add-line("T", "Michaud's Favorite"); $a.add-line("M", "2/2"); $a.add-line("L", "1/8"); $a.add-line("L", "1/8"); $a.add-line("K", "G"); nok $a.is-valid, "Not valid, too many Ls"; } { my $a = ABC::Header.new; $a.add-line("X", 1); $a.add-line("T", "The Star of Rakudo"); $a.add-line("T", "Michaud's Favorite"); $a.add-line("M", "2/2"); $a.add-line("L", "1/8"); $a.add-line("X", 1); $a.add-line("K", "G"); nok $a.is-valid, "Not valid, too many Xs"; } { my $a = ABC::Header.new; $a.add-line("T", "The Star of Rakudo"); $a.add-line("T", "Michaud's Favorite"); $a.add-line("M", "2/2"); $a.add-line("L", "1/8"); $a.add-line("X", 1); $a.add-line("K", "G"); nok $a.is-valid, "Not valid, X not first"; } { my $a = ABC::Header.new; $a.add-line("X", 1); $a.add-line("T", "The Star of Rakudo"); $a.add-line("T", "Michaud's Favorite"); $a.add-line("M", "2/2"); $a.add-line("L", "1/8"); $a.add-line("K", "G"); $a.add-line("K", "G"); nok $a.is-valid, "Not valid, too many Ks"; } { my $a = ABC::Header.new; $a.add-line("X", 1); $a.add-line("M", "2/2"); $a.add-line("L", "1/8"); $a.add-line("X", 1); $a.add-line("K", "G"); nok $a.is-valid, "Not valid, too few Ts"; } done-testing;
### ---------------------------------------------------- ### -- ABC ### -- Licenses: Artistic-2.0 ### -- Authors: ### -- File: t/07-stringify.rakutest ### ---------------------------------------------------- use v6; use Test; use ABC::Grammar; use ABC::Header; use ABC::Tune; use ABC::Duration; use ABC::Note; use ABC::Rest; use ABC::Tuplet; use ABC::BrokenRhythm; use ABC::Chord; use ABC::LongRest; use ABC::GraceNotes; use ABC::Actions; use ABC::Utils; my @simple-cases = ("a", "B,", "c'''", "^D2-", "_E,,/", "^^f/4", "=G3", "z3", "y/3", "x", "Z10", "[ceg]", "[D3/2d3/2]", "[A,2F2]", "(3abc", "(5A/B/C/D/E/", "a>b", "^c/4<B,,/4", '{cdc}', '{/d}', "(", ")", " ", "\t ", "]"); my @tricky-cases = ('"A"', '"A/B"', '"Am/Bb"', '"^this goes up"', '"_This goes down"', "+trill+", "+accent+", "[2", ".", "~", "[K:Amin]", "[M:3/4]", "[L:1/2]"); for @simple-cases -> $test-case { my $match = ABC::Grammar.parse($test-case, :rule<element>, :actions(ABC::Actions.new)); ok $match, "$test-case parsed"; my $object = $match.ast.value; # say $object.perl; is ~$object, $test-case, "Stringified version matches"; } for |@simple-cases, |@tricky-cases -> $test-case { my $match = ABC::Grammar.parse($test-case, :rule<element>, :actions(ABC::Actions.new)); ok $match, "$test-case parsed"; is element-to-str($match.ast), $test-case, "element-to-str version matches"; } # my @notes = <a b2 c/ d e f g3>.for({ str-to-stem($_) }); # is ABC::Tuplet.new(3, 2, @notes[^2]), "(3::2ab2", "triplet with only two notes"; # is ABC::Tuplet.new(3, 2, @notes[^4]), "(3::4ab2c/d", "triplet with four notes"; # is ABC::Tuplet.new(3, 3, @notes[^4]), "(3:3:4ab2c/d", "triplet with four notes and a weird rhythm"; done-testing;
### ---------------------------------------------------- ### -- ABC ### -- Licenses: Artistic-2.0 ### -- Authors: ### -- File: t/09-context.rakutest ### ---------------------------------------------------- use v6; use Test; use ABC::Context; use ABC::Grammar; use ABC::Actions; { my $context = ABC::Context.new("C", "4/4", "1/8"); my $match = ABC::Grammar.parse("abcdefgab^c_dcd", :rule<bar>, :actions(ABC::Actions.new)); isa-ok $match, Match, 'Got a match'; ok $match, 'bar recognized'; # first run loads up C# and Db for (@($match.ast) Z ("" xx 9, "^", "_", "^", "_").flat).flat -> $note, $desired-accidental { my $accidental = $context.working-accidental($note.value); is $accidental, $desired-accidental; } # second run still has them for (@($match.ast) Z ("", "", "^", "_", "", "", "", "", "", "^", "_", "^", "_")).flat -> $note, $desired-accidental { my $accidental = $context.working-accidental($note.value); is $accidental, $desired-accidental; } $context.bar-line; # and now we've reset to the initial state for (@($match.ast) Z ("" xx 9, "^", "_", "^", "_").flat).flat -> $note, $desired-accidental { my $accidental = $context.working-accidental($note.value); is $accidental, $desired-accidental; } } { my $context = ABC::Context.new("C#", "4/4", "1/8"); my $match = ABC::Grammar.parse("abcdefgab^c_dcd", :rule<bar>, :actions(ABC::Actions.new)); isa-ok $match, Match, 'Got a match'; ok $match, 'bar recognized'; # first run loads up C# and Db for (@($match.ast) Z ("^" xx 9, "^", "_", "^", "_").flat).flat -> $note, $desired-accidental { my $accidental = $context.working-accidental($note.value); is $accidental, $desired-accidental; } # second run still has them for (@($match.ast) Z ("^", "^", "^", "_", "^", "^", "^", "^", "^", "^", "_", "^", "_")).flat -> $note, $desired-accidental { my $accidental = $context.working-accidental($note.value); is $accidental, $desired-accidental; } $context.bar-line; # and now we've reset to the initial state for (@($match.ast) Z ("^" xx 9, "^", "_", "^", "_").flat).flat -> $note, $desired-accidental { my $accidental = $context.working-accidental($note.value); is $accidental, $desired-accidental; } } done-testing;
### ---------------------------------------------------- ### -- ABC ### -- Licenses: Artistic-2.0 ### -- Authors: ### -- File: t/03-file.rakutest ### ---------------------------------------------------- use v6; use Test; use ABC::Grammar; { my $match = ABC::Grammar.parse(slurp("samples.abc"), :rule<tune_file>); ok $match, 'samples.abc is a valid tune file'; is @( $match<tune> ).elems, 3, "Three tunes were found"; my @titles = @( $match<tune> ).flatmap({ @( .<header><header_field> ).grep({ .<header_field_name> eq "T" })[0] }).flatmap({ .<header_field_data> }); is +@titles, 3, "Three titles were found"; is @titles[0], "Cuckold Come Out o' the Amrey", "First is Cuckold"; is @titles[1], "Elsie Marley", "Second is Elsie Marley"; is @titles[2], "Peacock Followed the Hen. JWDM.07", "Third is Peacock"; } done-testing;
### ---------------------------------------------------- ### -- ABC ### -- Licenses: Artistic-2.0 ### -- Authors: ### -- File: t/01-regexes.rakutest ### ---------------------------------------------------- use v6; use Test; use ABC::Grammar; { my $match = ABC::Grammar.parse('"Cmin"', :rule<chord_or_text>); isa-ok $match, Match, 'Got a match'; ok $match, '"Cmin" is a chord'; is $match<chord>, "Cmin", '"Cmin" is chord Cmin'; is $match<chord>[0]<basenote>, "C", '"Cmin" has base note C'; is $match<chord>[0]<chord_type>, "min", '"Cmin" has chord_type "min"'; } { my $match = ABC::Grammar.parse('"1"', :rule<chord_or_text>); isa-ok $match, Match, 'Got a match'; ok $match, '"1" is a chord or text'; is $match<text_expression>, "1", '"1" is text 1'; } { my $match = ABC::Grammar.parse("^A,", :rule<pitch>); isa-ok $match, Match, 'Got a match'; ok $match, '"^A," is a pitch'; is $match<basenote>, "A", '"^A," has base note A'; is $match<octave>, ",", '"^A," has octave ","'; is $match<accidental>, "^", '"^A," has accidental "#"'; } { my $match = ABC::Grammar.parse("_B", :rule<pitch>); isa-ok $match, Match, 'Got a match'; ok $match, '"_B" is a pitch'; is $match<basenote>, "B", '"_B" has base note B'; is $match<octave>, Nil, '"_B" has no octave'; is $match<accidental>, "_", '"_B" has accidental "_"'; } { my $match = ABC::Grammar.parse("C''", :rule<pitch>); isa-ok $match, Match, 'Got a match'; ok $match, '"note" is a pitch'; is $match<basenote>, "C", '"note" has base note C'; is $match<octave>, "''", '"note" has octave two-upticks'; is $match<accidental>, Nil, '"note" has no accidental'; } { my $match = ABC::Grammar.parse("=d,,,", :rule<pitch>); isa-ok $match, Match, 'Got a match'; ok $match, '"=d,,," is a pitch'; is $match<basenote>, "d", '"=d,,," has base note d'; is $match<octave>, ",,,", '"=d,,," has octave ",,,"'; is $match<accidental>, "=", '"=d,,," has accidental "="'; } { my $match = ABC::Grammar.parse("2", :rule<note_length>); isa-ok $match, Match, 'Got a match'; ok $match, '"2" is a note length'; is $match, "2", '"2" has note length 2'; } { my $match = ABC::Grammar.parse("^^e2", :rule<mnote>); isa-ok $match, Match, 'Got a match'; ok $match, '"^^e2" is a note'; is $match<pitch><basenote>, "e", '"^^e2" has base note e'; is $match<pitch><octave>, Nil, '"^^e2" has no octave'; is $match<pitch><accidental>, "^^", '"^^e2" has accidental "^^"'; is $match<note_length>, "2", '"^^e2" has note length 2'; } { my $match = ABC::Grammar.parse("__f'/", :rule<mnote>); isa-ok $match, Match, 'Got a match'; ok $match, '"__f/" is a note'; is $match<pitch><basenote>, "f", '"__f/" has base note f'; is $match<pitch><octave>, "'", '"__f/" has octave tick'; is $match<pitch><accidental>, "__", '"__f/" has accidental "__"'; is $match<note_length>, "/", '"__f/" has note length /'; } { my $match = ABC::Grammar.parse("G,2/3", :rule<mnote>); isa-ok $match, Match, 'Got a match'; ok $match, '"G,2/3" is a note'; is $match<pitch><basenote>, "G", '"G,2/3" has base note G'; is $match<pitch><octave>, ",", '"G,2/3" has octave ","'; is $match<pitch><accidental>, Nil, '"G,2/3" has no accidental'; is $match<note_length>, "2/3", '"G,2/3" has note length 2/3'; } { my $match = ABC::Grammar.parse("z2/3", :rule<rest>); isa-ok $match, Match, 'Got a match'; ok $match, '"z2/3" is a rest'; is $match<rest_type>, "z", '"z2/3" has base rest z'; is $match<note_length>, "2/3", '"z2/3" has note length 2/3'; } { my $match = ABC::Grammar.parse("y/3", :rule<rest>); isa-ok $match, Match, 'Got a match'; ok $match, '"y/3" is a rest'; is $match<rest_type>, "y", '"y/3" has base rest y'; is $match<note_length>, "/3", '"y/3" has note length 2/3'; } { my $match = ABC::Grammar.parse("x", :rule<rest>); isa-ok $match, Match, 'Got a match'; ok $match, '"x" is a rest'; is $match<rest_type>, "x", '"x" has base rest x'; is $match<note_length>, "", '"x" has no note length'; } { my $match = ABC::Grammar.parse("v", :rule<element>); isa-ok $match, Match, 'Got a match'; ok $match, '"v" is an element'; is $match<gracing>, "v", '"v" gracing is v'; } { my $match = ABC::Grammar.parse("T", :rule<element>); isa-ok $match, Match, 'Got a match'; ok $match, '"T" is an element'; is $match<gracing>, "T", '"T" gracing is T'; } { my $match = ABC::Grammar.parse("+trill+", :rule<element>); isa-ok $match, Match, 'Got a match'; ok $match, '"+trill+" is an element'; is $match<gracing>, "+trill+", '"+trill+" gracing is +trill+'; } { my $match = ABC::Grammar.parse("!trill!", :rule<element>); isa-ok $match, Match, 'Got a match'; ok $match, '"!trill!" is an element'; is $match<gracing>, "!trill!", '"!trill!" gracing is !trill!'; } { my $match = ABC::Grammar.parse("~", :rule<element>); isa-ok $match, Match, 'Got a match'; ok $match, '"~" is an element'; is $match<gracing>, "~", '"~" gracing is ~'; } { my $match = ABC::Grammar.parse("z/", :rule<element>); isa-ok $match, Match, 'Got a match'; ok $match, '"z/" is an element'; is $match<rest><rest_type>, "z", '"z/" has base rest z'; is $match<rest><note_length>, "/", '"z/" has length "/"'; } { my $match = ABC::Grammar.parse("(", :rule<element>); isa-ok $match, Match, 'Got a match'; ok $match, '"(" is an element'; is $match<slur_begin>, '(', '"(" is a slur begin'; } { my $match = ABC::Grammar.parse(")", :rule<element>); isa-ok $match, Match, 'Got a match'; ok $match, '")" is an element'; is $match<slur_end>, ')', '")" is a slur end'; } { my $match = ABC::Grammar.parse("_D,5/4", :rule<element>); isa-ok $match, Match, 'Got a match'; ok $match, '"_D,5/4" is an element'; is $match<stem><mnote>[0]<pitch><basenote>, "D", '"_D,5/4" has base note D'; is $match<stem><mnote>[0]<pitch><octave>, ",", '"_D,5/4" has octave ","'; is $match<stem><mnote>[0]<pitch><accidental>, "_", '"_D,5/4" is flat'; is $match<stem><mnote>[0]<note_length>, "5/4", '"_D,5/4" has note length 5/4'; } { my $match = ABC::Grammar.parse("A>^C'", :rule<broken_rhythm>); isa-ok $match, Match, 'Got a match'; ok $match, '"A>^C" is a broken rhythm'; is $match<stem>[0]<mnote>[0]<pitch><basenote>, "A", 'first note is A'; is $match<stem>[0]<mnote>[0]<pitch><octave>, Nil, 'first note has no octave'; is $match<stem>[0]<mnote>[0]<pitch><accidental>, Nil, 'first note has no accidental'; is $match<stem>[0]<mnote>[0]<note_length>, "", 'first note has no length'; is $match<broken_rhythm_bracket>, ">", 'angle is >'; is $match<stem>[1]<mnote>[0]<pitch><basenote>, "C", 'second note is C'; is $match<stem>[1]<mnote>[0]<pitch><octave>, "'", 'second note has octave tick'; is $match<stem>[1]<mnote>[0]<pitch><accidental>, "^", 'second note is sharp'; is $match<stem>[1]<mnote>[0]<note_length>, "", 'second note has no length'; } { my $match = ABC::Grammar.parse("d'+p+<<<+accent+_B", :rule<broken_rhythm>); isa-ok $match, Match, 'Got a match'; ok $match, '"d+p+<<<+accent+_B" is a broken rhythm'; given $match { is .<stem>[0]<mnote>[0]<pitch><basenote>, "d", 'first note is d'; is .<stem>[0]<mnote>[0]<pitch><octave>, "'", 'first note has an octave tick'; is .<stem>[0]<mnote>[0]<pitch><accidental>, Nil, 'first note has no accidental'; is .<stem>[0]<mnote>[0]<note_length>, "", 'first note has no length'; is .<g1>[0], "+p+", 'first gracing is +p+'; is .<broken_rhythm_bracket>, "<<<", 'angle is <<<'; is .<g2>[0], "+accent+", 'second gracing is +accent+'; is .<stem>[1]<mnote>[0]<pitch><basenote>, "B", 'second note is B'; is .<stem>[1]<mnote>[0]<pitch><octave>, Nil, 'second note has no octave'; is .<stem>[1]<mnote>[0]<pitch><accidental>, "_", 'second note is flat'; is .<stem>[1]<mnote>[0]<note_length>, "", 'second note has no length'; } } { my $match = ABC::Grammar.parse("(3abc", :rule<tuplet>); isa-ok $match, Match, 'Got a match'; ok $match, '"(3abc" is a tuplet'; is ~$match, "(3abc", '"(3abc" was the portion matched'; is +@( $match<stem> ), 3, 'Three notes matched'; is $match<stem>[0], "a", 'first note is a'; is $match<stem>[1], "b", 'second note is b'; is $match<stem>[2], "c", 'third note is c'; } { my $match = ABC::Grammar.parse("(3 ab c", :rule<tuplet>); isa-ok $match, Match, 'Got a match'; ok $match, '"(3 ab c" is a tuplet'; is ~$match, "(3 ab c", '"(3 ab c" was the portion matched'; is +@( $match<stem> ), 3, 'Three notes matched'; is $match<stem>[0], "a", 'first note is a'; is $match<stem>[1], "b", 'second note is b'; is $match<stem>[2], "c", 'third note is c'; } { my $match = ABC::Grammar.parse("(5abcde", :rule<tuplet>); isa-ok $match, Match, 'Got a match'; ok $match, '"(5abcde" is a tuplet'; is ~$match, "(5abcde", '"(5abcde" was the portion matched'; is +@( $match<stem> ), 5, 'Three notes matched'; is $match<stem>[0], "a", 'first note is a'; is $match<stem>[1], "b", 'second note is b'; is $match<stem>[2], "c", 'third note is c'; is $match<stem>[3], "d", 'fourth note is d'; is $match<stem>[4], "e", 'fifth note is e'; } { my $match = ABC::Grammar.parse("[a2bc]3", :rule<stem>); isa-ok $match, Match, 'Got a match'; ok $match, '"[a2bc]3" is a stem'; is ~$match, "[a2bc]3", '"[a2bc]3" was the portion matched'; is +@( $match<mnote> ), 3, 'Three notes matched'; is $match<mnote>[0], "a2", 'first note is a2'; is $match<mnote>[1], "b", 'second note is b'; is $match<mnote>[2], "c", 'third note is c'; is $match<note_length>, "3", 'correct duration'; nok ?$match<tie>, 'not tied'; } { my $match = ABC::Grammar.parse("[a2bc]3-", :rule<stem>); isa-ok $match, Match, 'Got a match'; ok $match, '"[a2bc]3-" is a stem'; is ~$match, "[a2bc]3-", '"[a2bc]3-" was the portion matched'; is +@( $match<mnote> ), 3, 'Three notes matched'; is $match<mnote>[0], "a2", 'first note is a2'; is $match<mnote>[1], "b", 'second note is b'; is $match<mnote>[2], "c", 'third note is c'; is $match<note_length>, "3", 'correct duration'; ok ?$match<tie>, 'tied'; } { my $match = ABC::Grammar.parse("[A3 D3 ]", :rule<stem>); isa-ok $match, Match, 'Got a match'; ok $match, '"[A3 D3 ]" is a stem'; is ~$match, "[A3 D3 ]", '"[A3 D3 ]" was the portion matched'; is +@( $match<mnote> ), 2, 'Two notes matched'; is $match<mnote>[0], "A3", 'first note is A3'; is $match<mnote>[1], "D3", 'second note is D3'; nok ?$match<tie>, 'not tied'; } # (3 is the only case that works currently. :( # { # my $match = ABC::Grammar.parse("(2abcd", :rule<tuple>); # isa-ok $match, Match, '"(2ab" is a tuple'; # is ~$match, "(2ab", '"(2ab" was the portion matched'; # is $match<stem>[0], "a", 'first note is a'; # is $match<stem>[1], "b", 'second note is b'; # } for ':|:', '|:', '|', ':|', '::', '|]' { my $match = ABC::Grammar.parse($_, :rule<barline>); isa-ok $match, Match, 'Got a match'; ok $match, "barline $_ recognized"; is $match, $_, "barline $_ is correct"; } { my $match = ABC::Grammar.parse("g>ecgece/f/g/e/|", :rule<bar>); isa-ok $match, Match, 'Got a match'; ok $match, 'bar recognized'; is $match, "g>ecgece/f/g/e/|", "Entire bar was matched"; is $match<element>.flatmap(~*), "g>e c g e c e/ f/ g/ e/", "Each element was matched"; is $match<barline>, "|", "Barline was matched"; } { my $match = ABC::Grammar.parse("g>ecg ec e/f/g/e/ |", :rule<bar>); isa-ok $match, Match, 'Got a match'; ok $match, 'bar recognized'; is $match, "g>ecg ec e/f/g/e/ |", "Entire bar was matched"; is $match<element>.flatmap(~*), "g>e c g e c e/ f/ g/ e/ ", "Each element was matched"; is $match<barline>, "|", "Barline was matched"; } { my $line = "g>ecg ec e/f/g/e/ | d/c/B/A/ Gd BG B/c/d/B/ |"; my $match = ABC::Grammar.parse($line, :rule<line_of_music>); isa-ok $match, Match, 'Got a match'; ok $match, 'line of music recognized'; is $match, $line, "Entire line was matched"; is $match<bar>[0], "g>ecg ec e/f/g/e/ |", "First bar is correct"; is $match<bar>[1], " d/c/B/A/ Gd BG B/c/d/B/ |", "Second bar is correct"; # say $match<ABC::Grammar::line_of_music>.perl; } { my $line = "g>ecg ec e/f/g/e/ |1 d/c/B/A/ Gd BG B/c/d/B/ |"; my $match = ABC::Grammar.parse($line, :rule<line_of_music>); isa-ok $match, Match, 'Got a match'; ok $match, 'line of music recognized'; is $match, $line, "Entire line was matched"; is $match<bar>[0], "g>ecg ec e/f/g/e/ |", "First bar is correct"; is $match<bar>[1], "1 d/c/B/A/ Gd BG B/c/d/B/ |", "Second bar is correct, even with stupid hacky |1 ending marker"; # say $match<ABC::Grammar::line_of_music>.perl; } { my $line = "|A/B/c/A/ c>d e>deg | dB/A/ gB +trill+A2 +trill+e2 ::"; my $match = ABC::Grammar.parse($line, :rule<line_of_music>); isa-ok $match, Match, 'Got a match'; ok $match, 'line of music recognized'; is $match, $line, "Entire line was matched"; is $match<bar>[0], "A/B/c/A/ c>d e>deg |", "First bar is correct"; is $match<bar>[1], " dB/A/ gB +trill+A2 +trill+e2 ::", "Second bar is correct"; is $match<barline>, "|", "Initial barline matched"; # say $match<ABC::Grammar::line_of_music>.perl; } { my $line = 'g>ecg ec e/f/g/e/ |[2-3 d/c/B/A/ {Gd} BG B/c/d/B/ |'; my $match = ABC::Grammar.parse($line, :rule<line_of_music>); isa-ok $match, Match, 'Got a match'; ok $match, 'line of music recognized'; is $match, $line, "Entire line was matched"; is $match<bar>[0], "g>ecg ec e/f/g/e/ |", "First bar is correct"; is $match<bar>[1], '[2-3 d/c/B/A/ {Gd} BG B/c/d/B/ |', "Second bar is correct"; # say $match<ABC::Grammar::line_of_music>.perl; } { my $match = ABC::Grammar.parse("[K:F]", :rule<inline_field>); isa-ok $match, Match, 'Got a match'; ok $match, 'inline field recognized'; is $match, "[K:F]", "Entire string was matched"; is $match<alpha>, "K", "Correct field name found"; is $match<value>, "F", "Correct field value found"; } { my $match = ABC::Grammar.parse("[M:3/4]", :rule<inline_field>); isa-ok $match, Match, 'Got a match'; ok $match, 'inline field recognized'; is $match, "[M:3/4]", "Entire string was matched"; is $match<alpha>, "M", "Correct field name found"; is $match<value>, "3/4", "Correct field value found"; } { my $match = ABC::Grammar.parse(" % this is a comment", :rule<comment_line>); isa-ok $match, Match, 'Got a match'; ok $match, 'comment line recognized'; is $match, " % this is a comment", "Entire string was matched"; } { my $match = ABC::Grammar.parse("% this is a comment", :rule<comment_line>); isa-ok $match, Match, 'Got a match'; ok $match, 'comment line recognized'; is $match, "% this is a comment", "Entire string was matched"; } { my $line = "g>ecg ec e/f/g/e/ | d/c/B/A/ [K:F] Gd BG B/c/d/B/ |"; my $match = ABC::Grammar.parse($line, :rule<line_of_music>); isa-ok $match, Match, 'Got a match'; ok $match, 'line of music recognized'; is $match, $line, "Entire line was matched"; is $match<bar>[0], "g>ecg ec e/f/g/e/ |", "First bar is correct"; is $match<bar>[1], " d/c/B/A/ [K:F] Gd BG B/c/d/B/ |", "Second bar is correct"; ok @( $match<bar>[1]<element> ).grep("[K:F]"), "Key change got recognized"; # say $match<ABC::Grammar::line_of_music>.perl; } { my $line = "g>ecg ec e/f/g/e/ | d/c/B/A/ [M:C] Gd BG B/c/d/B/ |"; my $match = ABC::Grammar.parse($line, :rule<line_of_music>); isa-ok $match, Match, 'Got a match'; ok $match, 'line of music recognized'; is $match, $line, "Entire line was matched"; is $match<bar>[0], "g>ecg ec e/f/g/e/ |", "First bar is correct"; is $match<bar>[1], " d/c/B/A/ [M:C] Gd BG B/c/d/B/ |", "Second bar is correct"; ok @( $match<bar>[1]<element> ).grep("[M:C]"), "Meter change got recognized"; # say $match<ABC::Grammar::line_of_music>.perl; } { my $line = "| [K:F] Gd BG [B/c/d/B/]|"; my $match = ABC::Grammar.parse($line, :rule<line_of_music>); isa-ok $match, Match, 'Got a match'; ok $match, 'line of music recognized'; is $match, $line, "Entire line was matched"; is $match<bar>[0]<element>[1], "[K:F]", "Key signature change is correctly captured"; # is $match<bar>[1], " d/c/B/A/ [K:F] Gd BG B/c/d/B/ |", "Second bar is correct"; } { my $line = 'E2 CE GCEG|c4 B3 ^F|(A2 G2) =F2 D2|C4 {B,C}E2 D>E|[1 (D4 C2) z2:|[2 (D4 C2) z3/2 [G/2D/2]|'; my $match = ABC::Grammar.parse($line, :rule<line_of_music>); isa-ok $match, Match, 'Got a match'; ok $match, 'line of music recognized'; is $match, $line, "Entire line was matched"; is $match<bar>[5]<element>[0], "[2", "nth repeat works"; } { my $music = q«A/B/c/A/ +trill+c>d e>deg | GG +trill+B>c d/B/A/G/ B/c/d/B/ | A/B/c/A/ c>d e>deg | dB/A/ gB +trill+A2 +trill+e2 :: g>ecg ec e/f/g/e/ | d/c/B/A/ Gd BG B/c/d/B/ | g/f/e/d/ c/d/e/f/ gc e/f/g/e/ | dB/A/ gB +trill+A2 +trill+e2 :|»; my $match = ABC::Grammar.parse($music, :rule<music>); isa-ok $match, Match, 'Got a match'; ok $match, 'music recognized'; is $match<line_of_music>.elems, 4, "Four lines matched"; } { my $music = q«% Comment X:64 T:Cuckold Come Out o' the Amrey S:Northumbrian Minstrelsy M:4/4 L:1/8 K:D »; my $match = ABC::Grammar.parse($music, :rule<header>); isa-ok $match, Match, 'Got a match'; ok $match, 'header recognized'; is $match<header_field>.elems, 6, "Six fields matched"; is $match<header_field>.flatmap({ .<header_field_name> }), "X T S M L K", "Got the right field names"; } { my $music = q«X:64 T:Cuckold Come Out o' the Amrey S:Northumbrian Minstrelsy M:4/4 L:1/8 K:D A/B/c/A/ +trill+c>d e>deg | GG +trill+B>c d/B/A/G/ B/c/d/B/ | A/B/c/A/ c>d e>deg | dB/A/ gB +trill+A2 +trill+e2 :: % test comment g>ecg ec e/f/g/e/ | d/c/B/A/ Gd BG B/c/d/B/ | g/f/e/d/ c/d/e/f/ gc e/f/g/e/ | dB/A/ gB +trill+A2 +trill+e2 :| »; my $match = ABC::Grammar.parse($music, :rule<tune>); isa-ok $match, Match, 'Got a match'; ok $match, 'tune recognized'; given $match<header> { is .<header_field>.elems, 6, "Six fields matched"; is .<header_field>.flatmap({ .<header_field_name> }), "X T S M L K", "Got the right field names"; } is $match<music><line_of_music>.elems, 4, "Four lines matched"; } { my $music = q«X:1 T:Are You Coming From The Races? O:from the playing of Frank Maher M:2/4 L:1/8 R:Single K:D DE|:F2 F2|AF ED|E2 EF|ED DE|F2 F2|AF ED|E2 D2| |[1 D2 DE:|[2 D2 dc|:B2 Bc|BA FG|AB AF| AF dc|B2 Bc|BA FA|B2 A2|[1 A2 dc:|[2 A2 X:2 T:Bride's Jig O:from the playing of Frank Maher M:2/4 L:1/8 R:Single K:Edor |:B E2 G|FE D2|E>F GA|Bc BA|B E2 G|FE D2|E>F GE|A2 A2:| |:AB cd|e4|AB cB|BA FA|AB cd|e4|AB cB|A2 A2:| »; my $match = ABC::Grammar.parse($music, :rule<tune_file>); isa-ok $match, Match, 'Got a match'; ok $match, 'tune_file recognized'; is $match<tune>.elems, 2, 'found two tunes'; is $match<tune>[0]<music><line_of_music>.elems, 3; is $match<tune>[1]<music><line_of_music>.elems, 2; } { my $music = q«X:1 T:Are You Coming From The Races? O:from the playing of Frank Maher M:2/4 L:1/8 R:Single K:D DE|:F2 F2|AF ED|E2 EF|ED DE|F2 F2|AF ED|E2 D2| |[1 D2 DE:|[2 D2 dc|:B2 Bc|BA FG|AB AF| AF dc|B2 Bc|BA FA|B2 A2|[1 A2 dc:|[2 A2 X:2 T:Bride's Jig O:from the playing of Frank Maher M:2/4 L:1/8 R:Single K:Edor |:B E2 G|FE D2|E>F GA|Bc BA|B E2 G|FE D2|E>F GE|A2 A2:| |:AB cd|e4|AB cB|BA FA|AB cd|e4|AB cB|A2 A2:|»; my $match = ABC::Grammar.parse($music, :rule<tune_file>); isa-ok $match, Match, 'Got a match'; ok $match, 'tune_file recognized'; is $match<tune>.elems, 2, 'found two tunes'; is $match<tune>[0]<music><line_of_music>.elems, 3; is $match<tune>[1]<music><line_of_music>.elems, 2; } { my $music = q«X:1 T:Canon in D C:Pachelbel M:2/2 L:1/8 K:D "D" DFAd "A" CEAc|"Bm" B,DFB "F#m" A,CFA|"G" B,DGB "D" A,DFA|"G" B,DGB "A" CEAc| "D" f4 "A" e4|"Bm" d4 "F#m" c4|"G" B4 "D" A4|"G" B4 "A" c4| »; my $match = ABC::Grammar.parse($music, :rule<tune_file>); isa-ok $match, Match, 'Got a match'; ok $match, 'tune_file recognized'; is $match<tune>.elems, 1, 'found one tune'; is $match<tune>[0]<music><line_of_music>.elems, 2, "with two lines of music"; } done-testing;
### ---------------------------------------------------- ### -- ABC ### -- Licenses: Artistic-2.0 ### -- Authors: ### -- File: lib/ABC/Utils.rakumod ### ---------------------------------------------------- use v6; use ABC::Grammar; use ABC::Context; use ABC::Note; package ABC::Utils { sub str-to-stem($note) is export { my $match = ABC::Grammar.parse($note, :rule<stem>, :actions(ABC::Actions.new)); $match.ast; } sub element-to-str($element-pair) is export { given $element-pair.key { when "gracing" { given $element-pair.value { when '.' | '~' { $element-pair.value; } '+' ~ $element-pair.value ~ '+'; } } when "inline_field" { '[' ~ $element-pair.value.key ~ ':' ~ $element-pair.value.value ~ ']'; } when "chord_or_text" { $element-pair.value.flatmap({ when Str { '"' ~ $_ ~ '"'; } ~$_; }).join('') ; } when "endline" { "\n"; } when "nth_repeat" { $element-pair.value ~~ Set ?? "[" ~ $element-pair.value.keys.join(",") !! "[" ~ $element-pair.value.perl; } ~$element-pair.value; } } sub apply_key_signature(%key_signature, $pitch) is export { my $resulting_note = ""; if $pitch<accidental> { $resulting_note ~= $pitch<accidental>.Str; } else { if %key_signature{$pitch<basenote>.uc}:exists { $resulting_note ~= %key_signature{$pitch<basenote>.uc}; } } $resulting_note ~= $pitch<basenote>.Str; $resulting_note ~= $pitch<octave>.Str if $pitch<octave>; return $resulting_note; } sub is-a-power-of-two($n) is export { if $n ~~ Rat { is-a-power-of-two($n.numerator) && is-a-power-of-two($n.denominator); } else { !($n +& ($n - 1)); } } my %notename-to-ordinal = ( C => 0, D => 2, E => 4, F => 5, G => 7, A => 9, B => 11, c => 12, d => 14, e => 16, f => 17, g => 19, a => 21, b => 23 ); sub to-note-and-number($basenote, $octave-symbol) is export { my $octave = $basenote ~~ /<[A..G]>/ ?? 5 !! 6; for $octave-symbol.comb { when "," { $octave-- } when "'" { $octave++ } } ($basenote.uc, $octave); } sub from-note-and-number($basenote, $octave-number) is export { if $octave-number <= 5 { ($basenote.uc, "," x (5 - $octave-number)); } else { ($basenote.lc, "'" x ($octave-number - 6)) } } sub pitch-to-ordinal(%key, $accidental, $basenote, $octave) is export { my $ord = %notename-to-ordinal{$basenote}; given $accidental || %key{$basenote.uc} || "" { when /^ "^"+ $/ { $ord += $_.chars; } when /^ "_"+ $/ { $ord -= $_.chars; } } given $octave { when /^ "'"+ $/ { $ord += $_.chars * 12} when /^ ","+ $/ { $ord -= $_.chars * 12} when "" { } die "Unable to recognize octave $octave"; } $ord; } sub ordinal-to-pitch(%key, $basenote, $ordinal, $keep-accidental = False) is export { my $octave = 0; my $working-ordinal = %notename-to-ordinal{$basenote.uc}; while $ordinal + 5 < $working-ordinal { $working-ordinal -= 12; $octave -= 1; } while $working-ordinal + 5 < $ordinal { $working-ordinal += 12; $octave += 1; } my $key-accidental = %key{$basenote.uc} || "="; my $working-accidental; given $ordinal - $working-ordinal { when -2 { $working-accidental = "__"; } when -1 { $working-accidental = "_"; } when 0 { $working-accidental = "="; } when 1 { $working-accidental = "^"; } when 2 { $working-accidental = "^^"; } die "Too far away from note: $ordinal vs $working-ordinal"; } if !$keep-accidental && ($key-accidental eq $working-accidental) { $working-accidental = ""; } if $octave > 0 { ($working-accidental, $basenote.lc, "'" x ($octave - 1)); } else { ($working-accidental, $basenote.uc, "," x -$octave); } } sub stream-of-notes($tune) is export { my $key = $tune.header.get-first-value("K"); my $meter = $tune.header.get-first-value("M"); my $length = $tune.header.get-first-value("L") // "1/8"; my $context = ABC::Context.new($key, $meter, $length); my @elements = $tune.music; my $repeat-position = 0; my $repeat-context = ABC::Context.new($context); my $repeat-count = 1; my $in-nth-repeat = False; my $i = 0; gather while ($i < @elements) { given @elements[$i].key { when "stem" { my $stem = @elements[$i].value; take ABC::Note.new($context.working-accidental($stem), $stem.basenote, $stem.octave, $stem, $stem.is-tie); } when "tuplet" { my $tuplet = @elements[$i].value; for $tuplet.notes -> $note { take ABC::Note.new($context.working-accidental($note), $note.basenote, $note.octave, ABC::Duration.new(:ticks(2 / $tuplet.tuple * $note.ticks)), $note.is-tie); } } when "broken_rhythm" { my $br = @elements[$i].value; for ($br.effective-stem1, $br.effective-stem2) -> $stem { take ABC::Note.new($context.working-accidental($stem), $stem.basenote, $stem.octave, $stem, $stem.is-tie); } } when "nth_repeat" { $in-nth-repeat = True; if $repeat-count !(elem) @elements[$i].value { # this is an ending for some other repeat, skip it $i++ while ($i < @elements && !(@elements[$i].key eq "barline" && @elements[$i].value eq ":|" | ":|:")); } } when "end_nth_repeat" { $in-nth-repeat = False; } when "barline" { given @elements[$i].value { when ":|" | ":|:" { if $in-nth-repeat || $repeat-count == 1 { $context = ABC::Context.new($repeat-context); $i = $repeat-position; $repeat-count++; } else { # treat :| as :|: because it is sometimes used as such by mistake $repeat-context = ABC::Context.new($context); $repeat-position = $i; $repeat-count = 1; } $in-nth-repeat = False; } when "|:" { $repeat-context = ABC::Context.new($context); $repeat-position = $i; $repeat-count = 1; $in-nth-repeat = False; } } $context.bar-line; } when "chord_or_text" { } when "spacing" { } when "endline" { } take @elements[$i].key; } $i++; } } sub default-length-from-meter($meter) is export { if $meter ~~ m{(\d+ '/' \d+)} { $0.Rat < 3/4 ?? "1/16" !! "1/8"; } else { "1/8"; } } }
### ---------------------------------------------------- ### -- ABC ### -- Licenses: Artistic-2.0 ### -- Authors: ### -- File: lib/ABC/Note.rakumod ### ---------------------------------------------------- use v6; use ABC::Duration; use ABC::Pitched; class ABC::Note does ABC::Duration does ABC::Pitched { has $.accidental; has $.basenote; has $.octave; has $.is-tie; method new($accidental, $basenote, $octave, ABC::Duration $duration, $is-tie) { self.bless(:$accidental, :$basenote, :$octave, :ticks($duration.ticks), :$is-tie); } method pitch() { $.accidental ~ $.basenote ~ $.octave; } method Str() { $.pitch ~ self.duration-to-str ~ ($.is-tie ?? "-" !! ""); } method perl() { "ABC::Note.new({ $.accidental.perl }, { $.basenote.perl }, { $.octave.perl }, { $.ticks.perl }, { $.is-tie.perl })"; } method transpose($pitch-changer) { my ($new-accidental, $new-basenote, $new-octave) = $pitch-changer($.accidental, $.basenote, $.octave); ABC::Note.new($new-accidental, $new-basenote, $new-octave, self, $.is-tie); } }
### ---------------------------------------------------- ### -- ABC ### -- Licenses: Artistic-2.0 ### -- Authors: ### -- File: lib/ABC/Chord.rakumod ### ---------------------------------------------------- use v6; use ABC::Pitched; class ABC::Chord does ABC::Pitched { has $.main-note; has $.main-accidental; has $.main-type; has $.bass-note; has $.bass-accidental; method new($main-note, $main-accidental, $main-type, $bass-note, $bass-accidental) { self.bless(:$main-note, :$main-accidental, :$main-type, :$bass-note, :$bass-accidental); } method Str() { '"' ~ $.main-note ~ $.main-accidental ~ $.main-type ~ ($.bass-note ?? '/' ~ $.bass-note ~ $.bass-accidental !! "") ~ '"'; } method perl() { "ABC::Chord.new({ $.main-note.perl }, { $.main-accidental.perl }, { $.main-type.perl }, { $.bass-note.perl }, { $.bass-accidental.perl })"; } method transpose($pitch-changer) { sub change-chord($note, $accidental) { my $note-accidental; given $accidental { when '#' { $note-accidental = '^' } when 'b' { $note-accidental = '_' } $note-accidental = '='; } my ($new-accidental, $new-note, $new-octave) = $pitch-changer($note-accidental, $note, ""); given $new-accidental { when '^' { $new-accidental = '#' } when '_' { $new-accidental = 'b' } when '=' { $new-accidental = '' } when '' { $new-accidental = '' } die "Unable to handle $new-accidental in a chord name"; } ($new-note.uc, $new-accidental); } my ($main-note, $main-accidental) = change-chord($.main-note, $.main-accidental); my ($bass-note, $bass-accidental) = change-chord($.bass-note, $.bass-accidental); ABC::Chord.new($main-note, $main-accidental, $.main-type, $bass-note, $bass-accidental); } }
### ---------------------------------------------------- ### -- ABC ### -- Licenses: Artistic-2.0 ### -- Authors: ### -- File: lib/ABC/Header.rakumod ### ---------------------------------------------------- use v6; class ABC::Header { has @.lines; # array of Pairs representing each line of the ABC header method add-line($name, $data) { self.lines.push($name => $data); } method set-key($new-key) { my $found = False; self.lines = self.lines.grep(*.key ne "K"); # remove old key signatures self.lines.push("K" => $new-key); } method get($name) { self.lines.grep({ .key eq $name }); } method get-first-value($name) { my $pair = self.lines.first({ .key eq $name }); $pair ?? $pair.value !! Any; } method is-valid() { self.lines.elems > 1 && self.lines[0].key eq "X" && self.get("T").elems > 0 && self.get("M").elems == 1 && self.get("L").elems == 1 && self.get("X").elems == 1 && self.get("K").elems == 1 && self.lines[*-1].key eq "K"; } }
### ---------------------------------------------------- ### -- ABC ### -- Licenses: Artistic-2.0 ### -- Authors: ### -- File: lib/ABC/GraceNotes.rakumod ### ---------------------------------------------------- use v6; use ABC::Pitched; class ABC::GraceNotes does ABC::Pitched { has $.acciaccatura; has @.notes; method new($acciaccatura, @notes) { die "GraceNotes must have at least one note" if +@notes == 0; self.bless(:$acciaccatura, :@notes); } method Str() { '{' ~ ($.acciaccatura ?? '/' !! '') ~ @.notes.join('') ~ '}'; } method transpose($pitch-changer) { ABC::GraceNotes.new($.acciaccatura, @.notes>>.transpose($pitch-changer)); } }
### ---------------------------------------------------- ### -- ABC ### -- Licenses: Artistic-2.0 ### -- Authors: ### -- File: lib/ABC/Grammar.rakumod ### ---------------------------------------------------- use v6; # use Grammar::Tracer; # Originally based on https://web.archive.org/web/20120201072612/http://www.norbeck.nu/abc/bnf/abc20bnf.htm grammar ABC::Grammar { regex comment { \h* '%' \N* $$ } regex comment_line { ^^ <comment> } token header_field_name { \w } token header_field_data { <-[ % \v ]>* } token header_field { ^^ <header_field_name> ':' \h* <header_field_data> <comment>? $$ } token header { [[<header_field> | <comment_line>] \v+]+ } token basenote { <[a..g]+[A..G]> } token octave { "'"+ | ","+ } token accidental { '^^' | '^' | '__' | '_' | '=' } token pitch { <accidental>? <basenote> <octave>? } token tie { '-' } token number { <digit>+ } token note_length_denominator { '/' <bottom=number>? } token note_length { <top=number>? <note_length_denominator>? } token mnote { <pitch> <note_length> <tie>? } token stem { <mnote> | [ '[' \h* [<mnote> \h* ]+ ']' <note_length> <tie>? ] } token rest_type { <[x..z]> } token rest { <rest_type> <note_length> } token multi_measure_rest { 'Z' <number>? } token slur_begin { '(' } token slur_end { ')' } token grace_note { <pitch> <note_length> } # as mnote, but without tie token grace_note_stem { <grace_note> | [ '[' <grace_note>+ ']' ] } token acciaccatura { '/' } token grace_notes { '{' <acciaccatura>? <grace_note_stem>+ '}' } token long_gracing_text { [<alpha> | '.' | ')' | '(']+ } token long_gracing { ['+' <long_gracing_text> '+'] | ['!' <long_gracing_text> '!'] } token gracing { '.' | '~' | '!+!' | '!>!' | <[ H .. Y ]> | <[ h .. w ]> | <long_gracing> } token spacing { \h+ } token broken_rhythm_bracket { ['<'+ | '>'+] } token b_elem { <gracing> | <grace_notes> | <slur_begin> | <slur_end> } token broken_rhythm { <stem> <g1=b_elem>* <broken_rhythm_bracket> <g2=b_elem>* <stem> } token t_elem { <gracing> | <grace_notes> | <broken_rhythm> | <slur_begin> | <slur_end> } # token tuplet { '('(<digit>+) {} [<t_elem>* <stem>] ** { +$0 } <slur_end>? } # If the previous line fails, you can use the next rule to get the most common cases # next block makes the most common cases work # token tuplet { '(' (<digit>+) {} (<t_elem>* <stem>)*? <?{ say $1.perl; say $0.perl; $1.elems == $0 }> <slur_end>? } token tuplet { ['(2' \h* [\h* <t_elem>* <stem>] ** 2 <slur_end>? ] | ['(3' \h* [\h* <t_elem>* <stem>] ** 3 <slur_end>? ] | ['(4' \h* [\h* <t_elem>* <stem>] ** 4 <slur_end>? ] | ['(5' \h* [\h* <t_elem>* <stem>] ** 5 <slur_end>? ] } token nth_repeat_num { <digit>+ [[',' | '-'] <digit>+]* } token nth_repeat_text { '"' .*? '"' } token nth_repeat { ['[' [ <nth_repeat_num> | <nth_repeat_text> ]] | [<?after '|'> <nth_repeat_num>] } token end_nth_repeat { ']' } regex inline_field { '[' <alpha> ':' $<value>=[.*?] ']' } token chord_accidental { '#' | 'b' | '=' } token chord_type { [ <alpha> | <digit> | '+' | '-' ]+ } token chord_newline { '\n' | ';' } token chord { <mainnote=basenote> <mainaccidental=chord_accidental>? <maintype=chord_type>? [ '/' <bassnote=basenote> <bass_accidental=chord_accidental>? ]? <non_quote>* } token non_quote { <-["]> } token text_expression { [ '^' | '<' | '>' | '_' | '@' ]? <non_quote>+ } token chord_or_text { '"' [ <chord> | <text_expression> ] [ <chord_newline> [ <chord> | <text_expression> ] ]* '"' } token element { <broken_rhythm> | <stem> | <rest> | <tuplet> | <slur_begin> | <slur_end> | <multi_measure_rest> | <gracing> | <grace_notes> | <nth_repeat> | <end_nth_repeat> | <spacing> | <inline_field> | <chord_or_text> } token barline { '||' | '|]' | '[|' | ':|:' | '|:' | '|' | ':|' | '::' | '||:' | '&' } token bar { <element>+ <barline>? } token line_of_music { <barline>? <bar>+ '\\'? <comment>? $$ } token interior_header_field_name { < K M L w P > } token interior_header_field_data { <-[ % \v ]>* } token interior_header_field { ^^ <interior_header_field_name> ':' \h* <interior_header_field_data> <comment>? $$ } token music { [[<line_of_music> | <interior_header_field> | <comment_line> ] \s*]+ } token tune { <header> <music> } token tune_file { \s* [<tune> \s*]+ } token clef { [ ["clef=" [<clef-note> | <clef-name>]] | <clef-name>] <clef-line>? ["+8" | "-8"]? [\h+ "octave=" <clef-octave>]? [\h+ <clef-middle>]? } token clef-note { "G" | "C" | "F" | "P" } token clef-name { "treble" | "alto" | "tenor" | "baritone" | "bass" | "mezzo" | "soprano" | "perc" | "none" } token clef-line { <[1..5]> } token clef-octave { ['+' | '-']? \d+ } token clef-middle { "middle=" <basenote> <octave> } token key { [ [<key-def> [\h+ <clef>]?] | <clef> | "HP" | "Hp" ] \h* } token key-def { <basenote> <chord_accidental>? [\h* <mode>]? [\h+ <global-accidental>]* } token mode { <minor> | <major> | <lydian> | <ionian> | <mixolydian> | <dorian> | <aeolian> | <phrygian> | <locrian> } token minor { "m" ["in" ["o" ["r"]?]?]? } # m, min, mino, minor - all modes are case insensitive token major { "maj" ["o" ["r"]?]? } token lydian { "lyd" ["i" ["a" ["n"]?]?]? } # major with sharp 4th token ionian { "ion" ["i" ["a" ["n"]?]?]? } # =major token mixolydian { "mix" ["o" ["l" ["y" ["d" ["i" ["a" ["n"]?]?]?]?]?]?]? } # major with flat 7th token dorian { "dor" ["i" ["a" ["n"]?]?]? } # minor with sharp 6th token aeolian { "aeo" ["l" ["i" ["a" ["n"]?]?]?]? } # =minor token phrygian { "phr" ["y" ["g" ["i" ["a" ["n"]?]?]?]?]? } # minor with flat 2nd token locrian { "loc" ["r" ["i" ["a" ["n"]?]?]?]? } # minor with flat 2nd and 5th token global-accidental { <accidental> <basenote> } # e.g. ^f =c _b } sub header_hash($header_match) #OK { gather for $header_match<header_field> { take $_.<header_field_name>.Str => $_.<header_field_data>.Str; } }
### ---------------------------------------------------- ### -- ABC ### -- Licenses: Artistic-2.0 ### -- Authors: ### -- File: lib/ABC/Duration.rakumod ### ---------------------------------------------------- use v6; role ABC::Duration { has $.ticks; multi sub duration-from-parse($top) is export { #OK ABC::Duration.new(:ticks(($top ?? +~$top !! 1).Int)); } multi sub duration-from-parse($top, $bottom) is export { #OK # $*ERR.say: :$top.perl; # $*ERR.say: :$bottom.perl; ABC::Duration.new(:ticks(($top ?? +~$top !! 1).Int / ($bottom ?? +~$bottom !! 2).Int)); } method duration-to-str() { given $.ticks { when 1 { ""; } when 1/2 { "/"; } when Int { .Str; } when Rat { if $_.denominator == 1 { ~$_.numerator; } elsif $_.numerator == 1 { "/" ~ $_.denominator; } else { $_.numerator ~ "/" ~ $_.denominator; } } die "Duration must be Int or Rat, but it's { .WHAT }"; } } }
### ---------------------------------------------------- ### -- ABC ### -- Licenses: Artistic-2.0 ### -- Authors: ### -- File: lib/ABC/Context.rakumod ### ---------------------------------------------------- use ABC::KeyInfo; class ABC::Context { has $.key-name; has $.key-info; has $.meter; has $.length; has %.accidentals; multi method new($key-name, $meter, $length, :$current-key-info) { self.bless(:$key-name, :key-info(ABC::KeyInfo.new($key-name, :$current-key-info)), :$meter, :$length); } multi method new(ABC::Context $other) { self.bless(:key-name($other.key-name), :key-info(ABC::KeyInfo.new($other.key-name)), :meter($other.meter), :length($other.length)); } method bar-line () { %.accidentals = (); } method working-accidental($abc-pitch) { if $abc-pitch.accidental { %.accidentals{$abc-pitch.basenote.uc} = $abc-pitch.accidental; } %.accidentals{$abc-pitch.basenote.uc} || ($.key-info.key{$abc-pitch.basenote.uc} // ""); } }
### ---------------------------------------------------- ### -- ABC ### -- Licenses: Artistic-2.0 ### -- Authors: ### -- File: lib/ABC/ToLilypond.rakumod ### ---------------------------------------------------- use v6; use ABC::Header; use ABC::Tune; use ABC::Grammar; use ABC::Actions; use ABC::Duration; #OK use ABC::Note; use ABC::LongRest; use ABC::Utils; use ABC::KeyInfo; use ABC::Context; my $use-ABC-line-breaks = True; # false will use Lilypond's judgment my %accidental-map = ( '' => "", '=' => "", '^' => "is", '^^' => "isis", '_' => "es", '__' => "eses" ); my %octave-map = ( -3 => ",,", -2 => ",", -1 => "", 0 => "'", 1 => "''", 2 => "'''" ); my %unrecognized_gracings; my %substitutes; my %title-skips; my $spacing-comment = ''; # '%{ spacing %}'; sub start-lilypond($out, $paper-size) is export { $out.say: '\\version "2.19.83"'; $out.say: "#(set-default-paper-size \"{$paper-size}\")"; $out.say: '#(define-bar-line ".|:-|." "|." ".|:" ".|")'; } sub sanitize-quotation-marks($string, :$escape-number-sign?) is export { my $s = $string; $s.=subst(/^^ '"' (\S)/, {"“$0"}, :global); $s.=subst(/<?after \s> '"' (\S)/, {"“$0"}, :global); $s.=subst(/'"'/, "”", :global); $s.=subst(/"'s" $/, {"’s"}, :global); $s.=subst(/"'s" <?before \s>/, {"’s"}, :global); $s.=subst(/<!wb>"'"(\S)/, {"‘$0"}, :global); $s.=subst(/"'"/, "’", :global); $s.=subst(/ "#" /, "#", :global) if $escape-number-sign; my @subs = %substitutes.keys; $s.=subst(/ (@subs) /, { %substitutes{$0} }, :global); $s; } class LilypondContext { has ABC::Context $.context; method new($key-name, $meter, $length, :$current-key-info) { self.bless(context => ABC::Context.new($key-name, $meter, $length, :$current-key-info)); } method bar-line { $.context.bar-line; } method get-Lilypond-pitch(ABC::Note $abc-pitch) { my $real-accidental = $.context.working-accidental($abc-pitch); my $octave = +($abc-pitch.basenote ~~ 'a'..'z') + $.context.key-info.octave-shift; given $abc-pitch.octave { when !*.defined { } # skip if no additional octave info when /\,/ { $octave -= $abc-pitch.octave.chars } when /\'/ { $octave += $abc-pitch.octave.chars } } $abc-pitch.basenote.lc ~ %accidental-map{$real-accidental} ~ %octave-map{$octave}; } method get-Lilypond-duration(ABC::Duration $abc-duration) { my $ticks = $abc-duration.ticks.Rat * $.context.length; my $dots = ""; given $ticks.numerator { when 3 { $dots = "."; $ticks *= 2/3; } when 7 { $dots = ".."; $ticks *= 4/7; } } die "Don't know how to handle duration { $abc-duration.ticks }" unless is-a-power-of-two($ticks); die "Don't know how to handle duration { $abc-duration.ticks }" if $ticks > 4; if $ticks == 4 { "\\longa" ~ $dots; } elsif $ticks == 2 { "\\breve" ~ $dots; } else { $ticks.denominator ~ $dots; } } method meter-to-string() { given $.context.meter { when "none" { "" } when "C" { "\\time 4/4" } when "C|" { "\\time 2/2" } when "3/4" { "\\time 3/4 \\set Timing.beamExceptions = #'()"} when "6/4" { "\\time 6/4 \\set Timing.beatStructure = 2,2,2"} "\\time { $.context.meter } "; } } method ticks-in-measure() { given $.context.meter { when "C" | "C|" { 1 / $.context.length; } when "none" { Inf } $.context.meter / $.context.length; } } method get-Lilypond-measure-length() { given $.context.meter.trim { when "C" | "C|" | "4/4" { "1" } when "3/4" | 6/8 { "2." } when "2/4" { "2" } } } method key-to-string() { my $sf = $.context.key-info.key.flatmap({ "{.key}{.value}" }).sort.Str.lc; my $major-key-name; given $sf { when "" { $major-key-name = "c"; } when "f^" { $major-key-name = "g"; } when "c^ f^" { $major-key-name = "d"; } when "c^ f^ g^" { $major-key-name = "a"; } when "c^ d^ f^ g^" { $major-key-name = "e"; } when "a^ c^ d^ f^ g^" { $major-key-name = "b"; } when "a^ c^ d^ e^ f^ g^" { $major-key-name = "fis"; } when "a^ b^ c^ d^ e^ f^ g^" { $major-key-name = "cis"; } when "b_" { $major-key-name = "f"; } when "b_ e_" { $major-key-name = "bes"; } when "a_ b_ e_" { $major-key-name = "ees"; } when "a_ b_ d_ e_" { $major-key-name = "aes"; } when "a_ b_ d_ e_ g_" { $major-key-name = "des"; } when "a_ b_ c_ d_ e_ g_" { $major-key-name = "ges"; } when "a_ b_ c_ d_ e_ f_ g_" { $major-key-name = "ces"; } } "\\key $major-key-name \\major\n"; } method clef-to-string() { my $lilypond-clef = "treble"; given $.context.key-info.clef { when not .defined { } when "treble" | "alto" | "tenor" | "bass" { $lilypond-clef = ~$.context.key-info.clef; } } "\\clef $lilypond-clef"; } } sub get-field-if-there($header, $field) { my @things = $header.get($field)>>.value; ?@things ?? @things[0] !! ""; } class TuneConvertor { has $.context; has $.log; method new($key, $meter, $length, $log) { self.bless(:context(LilypondContext.new($key, $meter, $length)), :$log); } # MUST: this is context dependent too method Duration($element) { $element.value ~~ ABC::Duration ?? $element.value.ticks !! 0; } method StemPitchToLilypond($stem) { given $stem { when ABC::Note { $.context.get-Lilypond-pitch($stem) } when ABC::Stem { "<" ~ $stem.notes.map({ $.context.get-Lilypond-pitch($_) ~ ($_.is-tie ?? '~' !! '') }).join(' ') ~ ">" } die "Unrecognized alleged stem: " ~ $stem.perl; } } method StemToLilypond($stem, $suffix = "") { " " ~ self.StemPitchToLilypond($stem) ~ $.context.get-Lilypond-duration($stem) ~ ($stem.is-tie ?? '~' !! '') ~ $suffix ~ " "; } method WrapBar($lilypond-bar, $duration, :$might-be-parital?) { my $ticks-in-measure = $.context.ticks-in-measure; my $result = ""; if $ticks-in-measure == Inf { $result ~= "\\cadenzaOn "; my @chunks = $lilypond-bar.split($spacing-comment); for @chunks -> $chunk { if $chunk !~~ /"["/ && $chunk.comb(/\d+/).grep(* > 4) > 1 { $result ~= $chunk.subst(/<?after \S> \s/, { "[ " }) ~ "]"; } else { $result ~= $chunk; } } $result ~= " \\cadenzaOff"; } else { if $might-be-parital && $duration % $ticks-in-measure != 0 { my $note-length = 1 / $.context.context.length; my $count = $duration % $ticks-in-measure; if $count ~~ Rat { die "Strange partial measure found: $lilypond-bar" unless is-a-power-of-two($count.denominator); while $count.denominator > 1 { $note-length *= 2; # makes twice as short $count *= 2; # makes twice as long } } $result = "\\partial { $note-length }*{ $count } "; } $result ~= $lilypond-bar; } $result; } sub token-is-space($token) { # this probably needs to get smarter about barline so $token.key eq "spacing" | "endline" | "barline" | "end_nth_repeat" | "inline_field"; } method SectionToLilypond(@elements, $out, :$first-bar-might-need-partial?, :$next-section-is-repeated?) { my $first-bar = True; my $notes = ""; my $lilypond = ""; my $duration = 0; my $chord-duration = 0; my $suffix = ""; my $in-slur = False; for @elements.kv -> $i, $element { $duration += self.Duration($element); $chord-duration += self.Duration($element); given $element.key { when "stem" { $lilypond ~= self.StemToLilypond($element.value, $suffix); $suffix = ""; } when "rest" { $lilypond ~= " r{ $.context.get-Lilypond-duration($element.value) }$suffix "; $suffix = ""; } when "tuplet" { given $element.value.tuple { when 2 { $lilypond ~= " \\times 3/2 \{"; } when 3 { $lilypond ~= " \\times 2/3 \{"; } when 4 { $lilypond ~= " \\times 3/4 \{"; } $lilypond ~= " \\times 2/{ $element.value.tuple } \{"; } $lilypond ~= self.StemToLilypond($element.value.notes[0], "["); for 1..($element.value.notes - 2) -> $i { $lilypond ~= self.StemToLilypond($element.value.notes[$i]); } $lilypond ~= self.StemToLilypond($element.value.notes[*-1], "]"); $lilypond ~= " } "; $suffix = ""; } when "broken_rhythm" { $lilypond ~= self.StemToLilypond($element.value.effective-stem1, $suffix); # MUST: handle interior graciings $lilypond ~= self.StemToLilypond($element.value.effective-stem2); $suffix = ""; } when "gracing" { given $element.value { when "~" { $suffix ~= "\\turn"; } when "." { $suffix ~= "\\staccato"; } when "T" { $suffix ~= "\\trill"; } when "P" { $suffix ~= "\\prall"; } when "L" { $suffix ~= "\\accent"; } when "!>!" { $suffix ~= "\\accent"; } when "+" { $suffix ~= "-+"; } when "!+!" { $suffix ~= "-+"; } when "segno" { $lilypond ~= '\\mark \\markup { \\musicglyph #"scripts.segno" }'; } when "coda" { $lilypond ~= '\\mark \\markup { \\musicglyph #"scripts.coda" }'; } when "D.C." { $lilypond ~= '\\mark "D.C."'; } when "D.S." { $lilypond ~= '\\mark "D.S."'; } # when "D.C." { $suffix ~= '^\\markup { \\bold " D.C." } '; } # when "D.S." { $suffix ~= '^\\markup { \\bold " D.S." } '; } when "fine" { $suffix ~= '^\\markup { \\center-align { Fine } } '; } when "breath" { $lilypond ~= '\\breathe'; } when "crescendo(" | "<(" { $suffix ~= "\\<"; } when "crescendo)" | "<)" { $suffix ~= "\\!"; } when "diminuendo(" | ">(" { $suffix ~= "\\>"; } when "diminuendo)" | ">)" { $suffix ~= "\\!"; } when /^p+$/ | "mp" | "mf" | /^f+$/ | "fermata" | "accent" | "trill" | "sfz" | "marcato" { $suffix ~= "\\" ~ $element.value; } when "tenuto" { $suffix ~= "--"; } $*ERR.say: "Unrecognized gracing: " ~ $element.value.perl; %unrecognized_gracings{~$element.value} = 1; } } when "barline" { $notes ~= self.WrapBar($lilypond, $duration, :might-be-parital($first-bar && $first-bar-might-need-partial)); $first-bar = False; my $need-special = $next-section-is-repeated; if $need-special && $i + 1 < @elements && @elements[$i+1..*-1].grep({ !token-is-space($_) }) { $need-special = False; } given $element.value { when "||" { $notes ~= $need-special ?? ' \\bar ".|:-||"' !! ' \\bar "||"'; } when "|]" { $notes ~= $need-special ?? ' \\bar ".|:-|."' !! ' \\bar "|."'; } default { # $notes ~= ' \\bar "|"'; # this should be automatic -- except when this is wrong!! } } $notes ~= "\n"; $lilypond = ""; $duration = 0; $.context.bar-line; } when "inline_field" { given $element.value.key { when "K" { $!context = LilypondContext.new($element.value.value, $!context.context.meter, $!context.context.length, :current-key-info($!context.context.key-info)); $lilypond ~= $!context.key-to-string; $lilypond ~= $!context.clef-to-string; } when "M" { $!context = LilypondContext.new($!context.context.key-name, $element.value.value, $!context.context.length); $lilypond ~= $!context.meter-to-string; } when "L" { $!context = LilypondContext.new($!context.context.key-name, $!context.context.meter, $element.value.value); } } } when "slur_begin" { $suffix ~= "("; $in-slur = True; } when "slur_end" { $lilypond .= subst(/(\s+)$/, { ")$_" }) if $in-slur; $*ERR.say: "Warning: End-slur found without begin-slur" unless $in-slur; $in-slur = False; } when "multi_measure_rest" { $lilypond ~= "\\compressFullBarRests R" ~ $!context.get-Lilypond-measure-length ~ "*" ~ $element.value.measures_rest ~ " "; } when "chord_or_text" { for @($element.value) -> $chord_or_text { if $chord_or_text ~~ ABC::Chord { $suffix ~= '^' ~ $chord_or_text ~ " "; } else { given $element.value { when /^ '^'(.*)/ { $suffix ~= '^"' ~ $0 ~ '" ' } } } } } when "grace_notes" { $*ERR.say: "Unused suffix in grace note code: $suffix" if $suffix; $lilypond ~= $element.value.acciaccatura ?? "\\acciaccatura \{" !! "\\grace \{"; if $element.value.notes == 1 { $lilypond ~= self.StemToLilypond($element.value.notes[0], ""); } else { $lilypond ~= self.StemToLilypond($element.value.notes[0], "["); for 1..^($element.value.notes - 1) { $lilypond ~= self.StemToLilypond($element.value.notes[$_], ""); } $lilypond ~= self.StemToLilypond($element.value.notes[*-1], "]"); } $lilypond ~= " \} "; $suffix = ""; } when "spacing" { $lilypond ~= $spacing-comment } when "endline" { $lilypond ~= "\\break \\noPageBreak" if $use-ABC-line-breaks; } # .say; } } $out.say: "\{"; $notes ~= self.WrapBar($lilypond, $duration, :might-be-parital($first-bar && $first-bar-might-need-partial)); $first-bar = False; $out.say: $notes; $out.say: " \}"; } method BodyToLilypond(@elements, $out, :$prefix?) { $out.say: "\{"; $out.say: $prefix if $prefix; # if tune contains M: none sections, turn off barnumber display if @elements.grep({ $_.key eq "inline_field" && $_.value.key eq "M" && $_.value.value eq "none" }) { $out.say: "\\override Score.BarNumber.break-visibility = ##(#f #f #f)"; } $out.print: $.context.key-to-string; $out.say: "\\accidentalStyle modern-cautionary"; $out.print: $.context.clef-to-string; $out.print: $.context.meter-to-string; sub element-to-marker($element) { given $element.key { when "nth_repeat" { $element.value; } when "barline" { if $element.value ne "|" { $element.value; } else { ""; } } default { ""; } } } my $outer-self = self; class SectionInfo { has $.start-index; has $.end-index; method is-ending { @elements[self.start-index].key eq "nth_repeat"; } method is-space { @elements[self.start-index..self.end-index].grep({ token-is-space($_) }) == @elements[self.start-index..self.end-index] } method starts-with-repeat { so element-to-marker(@elements[self.start-index]) eq "|:" | "::" | ":|:"; } method ends-with-repeat { so element-to-marker(@elements[self.end-index]) eq ":|" | "::" | ":|:"; } method total-duration { [+] (self.start-index..self.end-index).map(-> $i { $outer-self.Duration(@elements[$i])}); } method first-bar-duration { my $i = self.starts-with-repeat ?? self.start-index + 1 !! self.start-index; my $duration = 0; while $i < +@elements { last if @elements[$i].key eq "barline"; $duration += $outer-self.Duration(@elements[$i++]); } $duration; } } sub sections-to-lilypond(@sections, :$next-section-is-repeated?, :$first-bar-might-need-partial?) { my $start = @sections[0].start-index; $.log.say: "start = $start, +elements = { +@elements }"; ++$start if @elements[$start].key eq "barline"; $.log.say: "outputing $start to {@sections[*-1].end-index} { $next-section-is-repeated ?? 'Next section repeated' !! '' }"; self.SectionToLilypond(@elements[$start .. @sections[*-1].end-index], $out, :$next-section-is-repeated, :$first-bar-might-need-partial); } my $start-of-section = 0; my @sections; for @elements.kv -> $i, $element { next if $i == $start-of-section; given element-to-marker($element) { when /\d/ { @sections.push(SectionInfo.new(start-index => $start-of-section, end-index => $i-1)); $start-of-section = $i; } when '|:' { @sections.push(SectionInfo.new(start-index => $start-of-section, end-index => $i-1)); $start-of-section = $i; } when '::' | ':|:' { @sections.push(SectionInfo.new(start-index => $start-of-section, end-index => $i)); $start-of-section = $i; } when '|]' | '||' | ':|' { @sections.push(SectionInfo.new(start-index => $start-of-section, end-index => $i)); $start-of-section = $i+1; } } } @sections.push(SectionInfo.new(start-index => $start-of-section, end-index => @elements - 1)); write-sections(@sections); sub write-section($section) { $.log.say: "{$section.start-index} => {$section.end-index}" ~ " {@elements[$section.start-index]} / {@elements[$section.end-index]}" ~ " {$section.is-space ?? "SPACING" !! ""}"; } sub write-sections(@sections) { for @sections -> $section { write-section($section); } } sub output-sections(@sections, :$next-section-is-repeated?, :$first-bar-might-need-partial?) { $.log.say: "******************************** start cluster of sections"; write-sections(@sections); return unless @sections; my @endings; for @sections.kv -> $i, $section { @endings.push($i) if $section.is-ending; } if @endings { my $volta-count = 2; # SHOULD: use endings to figure out right volta count $out.print: "\\repeat volta $volta-count "; sections-to-lilypond(@sections[0..^@endings[0]], :$next-section-is-repeated, :$first-bar-might-need-partial); $out.say: "\\alternative \{"; for @endings.rotor(2=>-1) -> ($a, $b) { $.log.say: "ending is $a => $b"; sections-to-lilypond(@sections[$a..^$b], :$next-section-is-repeated); } sections-to-lilypond(@sections[@endings[*-1]..(*-1)], :$next-section-is-repeated); $out.say: "\}"; } elsif @sections.grep(*.ends-with-repeat) { $out.print: "\\repeat volta 2 "; sections-to-lilypond(@sections, :$next-section-is-repeated, :$first-bar-might-need-partial); } else { sections-to-lilypond(@sections, :$next-section-is-repeated, :$first-bar-might-need-partial); } } my $first-bar-might-need-partial = @sections && 0 < @sections[0].first-bar-duration < $.context.ticks-in-measure; if $first-bar-might-need-partial && +@sections > 1 { if @sections[0].total-duration + @sections[1].first-bar-duration == $.context.ticks-in-measure { $first-bar-might-need-partial = False; } } # delete empty sections from the end of the tune while @sections && @sections[*-1].is-space { @sections.pop; } my $in-endings = False; my @section-cluster; for @sections -> $section { if $in-endings { if $section.is-ending || $section.is-space { @section-cluster.push($section); } else { output-sections(@section-cluster, :next-section-is-repeated($section.starts-with-repeat), :$first-bar-might-need-partial); $first-bar-might-need-partial = False; @section-cluster = (); @section-cluster.push($section); $in-endings = False; } } else { if @section-cluster && $section.starts-with-repeat { # output everything up to the current section output-sections(@section-cluster, :next-section-is-repeated(True), :$first-bar-might-need-partial); $first-bar-might-need-partial = False; @section-cluster = (); } @section-cluster.push($section); } if !$in-endings { if $section.is-ending { $in-endings = True; } else { if $section.ends-with-repeat { output-sections(@section-cluster, :next-section-is-repeated(True), :$first-bar-might-need-partial); $first-bar-might-need-partial = False; @section-cluster = (); } } } } if @section-cluster { output-sections(@section-cluster, :$first-bar-might-need-partial); $first-bar-might-need-partial = False; } $out.say: "\}"; } } sub TuneBodyToLilypondStream($tune, $out, :$prefix?, :$log?) is export { my $key = $tune.header.get-first-value("K"); my $meter = $tune.header.get-first-value("M"); my $length = $tune.header.get-first-value("L") // default-length-from-meter($meter); my $convertor = TuneConvertor.new($key, $meter, $length, $log // (open :w, $*SPEC.devnull)); $convertor.BodyToLilypond($tune.music, $out, :$prefix); } sub HeaderToLilypond(ABC::Header $header, $out, :$title?, :$subtitle?) is export { $out.say: "\\header \{"; my $working-title = $title // $header.get-first-value("T") // "Unworking-titled"; my @skips = %title-skips.keys; $working-title.=subst(/ (@skips) /, "", :global); $working-title = sanitize-quotation-marks($working-title); $out.say: " title = \" $working-title \""; my $composer = sanitize-quotation-marks(get-field-if-there($header, "C")); my $origin = sanitize-quotation-marks(get-field-if-there($header, "O")); if $origin { if $origin ~~ m:i/^for/ { $out.say: qq/ dedication = "$origin"/; } else { if $composer { $composer ~= " ($origin)"; } else { $composer = $origin; } } } $out.say: qq/ composer = "{ sanitize-quotation-marks($composer) }"/ if $composer; if $subtitle { $out.say: " subtitle = " ~ '"' ~ $subtitle ~ '"'; } else { $out.say: " subtitle = ##f"; } $out.say: "}"; } sub tune-to-score($tune, $out, $log, @notes = $tune.header.get("N").map(*.value), :$subtitle?) is export { $*ERR.say: "Working on { $tune.header.get-first-value("T") // $tune.header.get-first-value("X") }"; $log.say: "Working on { $tune.header.get-first-value("T") // $tune.header.get-first-value("X") }"; $out.say: "\\score \{"; TuneBodyToLilypondStream($tune, $out, :$log); HeaderToLilypond($tune.header, $out, :$subtitle); $out.say: "}\n\n"; if @notes { for @notes -> $note { next if $note ~~ / ^ \s* $ /; $out.say: q:to/END/; \noPageBreak \markup \fill-line { \center-column \wordwrap-lines { END $out.say: " " ~ sanitize-quotation-marks($note, :escape-number-sign); $out.say: q:to/END/; } } END } } else { # This was to allow breaks between tunes even if the tune # ended with a linebreak and didn't have a note. Now # trying to just avoid ending on a linebreak! # $out.say: q:to/END/; # \markup \fill-line { } # END } } sub GetUnrecognizedGracings() is export { %unrecognized_gracings } sub add-substitute($look-for, $replace-with) is export { %substitutes{$look-for} = $replace-with; } sub add-title-skip($look-for) is export { %title-skips{$look-for} = 1; }
### ---------------------------------------------------- ### -- ABC ### -- Licenses: Artistic-2.0 ### -- Authors: ### -- File: lib/ABC/KeyInfo.rakumod ### ---------------------------------------------------- use v6; use ABC::Grammar; #SHOULD: rename parcel to list? sub parcel-first-if-needed($a) { $a ~~ List ?? $a[0] !! $a; } class ABC::KeyInfo { has %.key; has $.clef; has $.octave-shift; has $.basenote; method new($key-field, :$current-key-info) { # say "K: $key-field"; my $match = ABC::Grammar.parse($key-field, :rule<key>); # say :$match.perl; die "Illegal key signature $key-field\n" unless $match; my %key-info; my $clef-info = "treble"; my $octave-shift = 0; if $current-key-info { %key-info = $current-key-info.key; $clef-info = $current-key-info.clef; $octave-shift = $current-key-info.octave-shift; } if $match<key-def> { %key-info = (); my %keys = ( 'C' => 0, 'G' => 1, 'D' => 2, 'A' => 3, 'E' => 4, 'B' => 5, 'F' => -1, ); # say $match<key-def>.perl; # my $lookup = $match<key-def><basenote>.uc; # say :$lookup.perl; my $sharps = %keys{$match<key-def><basenote>.uc}; if $match<key-def><chord_accidental> { given ~$match<key-def><chord_accidental> { when "#" { $sharps += 7; } when "b" { $sharps -= 7; } } } if $match<key-def><mode> { given parcel-first-if-needed($match<key-def><mode>) { when so .<major> { } when so .<ionian> { } when so .<mixolydian> { $sharps -= 1; } when so .<dorian> { $sharps -= 2; } when so .<minor> { $sharps -= 3; } when so .<aeolian> { $sharps -= 3; } when so .<phrygian> { $sharps -= 4; } when so .<locrian> { $sharps -= 5; } when so .<lydian> { $sharps += 1; } default { die "Unknown mode $_ requested"; } } } my @sharp_notes = <F C G D A E B>; given $sharps { when 1..7 { for ^$sharps -> $i { %key-info{@sharp_notes[$i]} = "^"; } } when -7..-1 { for ^(-$sharps) -> $i { %key-info{@sharp_notes[6-$i]} = "_"; } } } if $match<key-def><global-accidental> { for $match<key-def><global-accidental>.list -> $ga { %key-info{$ga<basenote>.uc} = ~$ga<accidental>; } } } if $match<clef> { my $clef = parcel-first-if-needed($match<clef>); $clef-info = ~($clef<clef-name> // $clef<clef-note>); if $match<clef><clef-octave> { $octave-shift = $match<clef><clef-octave>.Int; } else { $octave-shift = 0; } } self.bless(:key(%key-info), :clef($clef-info), :octave-shift($octave-shift) :basenote($match<key-def><basenote>.uc)); } method scale-names is export { ($.basenote .. "G", "A".."G").flat[^7]; } }
### ---------------------------------------------------- ### -- ABC ### -- Licenses: Artistic-2.0 ### -- Authors: ### -- File: lib/ABC/Rest.rakumod ### ---------------------------------------------------- use v6; use ABC::Duration; class ABC::Rest does ABC::Duration { has $.type; method new($type, ABC::Duration $duration) { self.bless(:$type, :ticks($duration.ticks)); } method Str() { $.type ~ self.duration-to-str; } }
### ---------------------------------------------------- ### -- ABC ### -- Licenses: Artistic-2.0 ### -- Authors: ### -- File: lib/ABC/Actions.rakumod ### ---------------------------------------------------- use v6; use ABC::Header; use ABC::Tune; use ABC::Duration; use ABC::Note; use ABC::Rest; use ABC::Tuplet; use ABC::BrokenRhythm; use ABC::Chord; use ABC::LongRest; use ABC::GraceNotes; class ABC::Actions { has $.current-tune = ""; method header_field($/) { if $<header_field_name> eq "T" { $*ERR.say: "Parsing " ~ $<header_field_data>; $!current-tune = $<header_field_data> ~ "\n"; } make ~$<header_field_name> => ~$<header_field_data>; } method interior_header_field($/) { make ~$<interior_header_field_name> => ~$<interior_header_field_data>; } method header($/) { my $header = ABC::Header.new; for @( $<header_field> ) -> $field { $header.add-line($field.ast.key, $field.ast.value); } make $header; } method note_length($/) { if $<note_length_denominator> { if $<note_length_denominator> ~~ List { make duration-from-parse($<top>, $<note_length_denominator>[0]<bottom>); } else { make duration-from-parse($<top>, $<note_length_denominator><bottom>); } } else { make duration-from-parse($<top>); } } method mnote($/) { make ABC::Note.new(~($<pitch><accidental> // ""), ~$<pitch><basenote>, ~($<pitch><octave> // ""), $<note_length>.ast, ?$<tie>); } method stem($/) { if @( $<mnote> ) == 1 { make $<mnote>[0].ast; } else { make ABC::Stem.new(@( $<mnote> )>>.ast, $<note_length>.ast, ?$<tie>); } } method rest($/) { make ABC::Rest.new(~$<rest_type>, $<note_length>.ast); } method multi_measure_rest($/) { make ABC::LongRest.new(~($<number> // 1)); } method tuplet($/) { make ABC::Tuplet.new(+@( $<stem> ), @( $<stem> )>>.ast); } method nth_repeat_num($/) { my @nums = $/.subst("-", "..").EVAL; make @nums.Set; } method nth_repeat($/) { make ($<nth_repeat_num> // $<nth_repeat_text>).ast; } method broken_rhythm($/) { make ABC::BrokenRhythm.new($<stem>[0].ast, ~$<g1>, ~$<broken_rhythm_bracket>, ~$<g2>, $<stem>[1].ast); } method grace_note($/) { make ABC::Note.new(~($<pitch><accidental> // ""), ~$<pitch><basenote>, ~($<pitch><octave> // ""), $<note_length>.ast, False); } method grace_note_stem($/) { if @( $<grace_note> ) == 1 { make $<grace_note>[0].ast; } else { make ABC::Stem.new(@( $<grace_note> )>>.ast); } } method grace_notes($/) { make ABC::GraceNotes.new(?$<acciaccatura>, @( $<grace_note_stem> )>>.ast); } method inline_field($/) { make ~$/<alpha> => ~$/<value>; } method long_gracing($/) { make ~$/<long_gracing_text>; } method gracing($/) { make $/<long_gracing> ?? $/<long_gracing>.ast !! ~$/; } method slur_begin($/) { make ~$/; } method slur_end($/) { make ~$/; } method chord($/) { # say "hello?"; # say $/<chord_accidental>[0].WHAT; # say $/<chord_accidental>[0].perl; make ABC::Chord.new(~$/<mainnote>, ~($/<mainaccidental> // ""), ~($/<maintype> // ""), ~($/<bassnote> // ""), ~($/<bass_accidental> // "")); } method chord_or_text($/) { my @chords = $/<chord>.flatmap({ $_.ast }); my @texts = $/<text_expression>.flatmap({ ~$_ }); make (@chords, @texts).flat.list; } method element($/) { my $type; for <broken_rhythm stem rest slur_begin slur_end multi_measure_rest gracing grace_notes nth_repeat end_nth_repeat spacing tuplet inline_field chord_or_text> { $type = $_ if $/{$_}; } # say $type ~ " => " ~ $/{$type}.ast.WHAT; my $ast = $type => ~$/{$type}; # say :$ast.perl; # say $/{$type}.ast.perl; # say $/{$type}.ast.WHAT; if $/{$type}.ast ~~ ABC::Duration | ABC::LongRest | ABC::GraceNotes | Pair | Str | List | Set { $ast = $type => $/{$type}.ast; } make $ast; } method barline($/) { make "barline" => ~$/; } method bar($/) { $!current-tune ~= ~$/; my @bar = @( $<element> )».ast; if $<barline> { @bar.push($<barline>.ast); } make @bar; } method line_of_music($/) { my @line; if $<barline> { @line.push($<barline>.ast); } my @bars = @( $<bar> )>>.ast; for @bars -> $bar { for $bar.list { @line.push($_); } } @line.push("endline" => ""); $!current-tune ~= "\n"; make @line; } method music($/) { my @music; # $*ERR.say: "Started music action"; for @( $/.caps ) { # $*ERR.say: ~$_.key ~ " => " ~ ~$_.value; when *.key eq "line_of_music" { for $_.value.ast { @music.push($_); } } when *.key eq "interior_header_field" { @music.push("inline_field" => $_.value.ast); } } # state $count = 0; # die if ++$count == 10; make @music; } method tune($/) { make ABC::Tune.new($<header>.ast, $<music>.ast); } method tune_file($/) { make @( $<tune> )>>.ast; } }
### ---------------------------------------------------- ### -- ABC ### -- Licenses: Artistic-2.0 ### -- Authors: ### -- File: lib/ABC/Pitched.rakumod ### ---------------------------------------------------- use v6; role ABC::Pitched { method transpose($pitch-changer) { ... } }
### ---------------------------------------------------- ### -- ABC ### -- Licenses: Artistic-2.0 ### -- Authors: ### -- File: lib/ABC/BrokenRhythm.rakumod ### ---------------------------------------------------- use v6; use ABC::Duration; use ABC::Pitched; use ABC::Note; use ABC::Stem; class ABC::BrokenRhythm does ABC::Duration does ABC::Pitched { has $.stem1; has $.gracing1; has $.broken-rhythm; has $.gracing2; has $.stem2; method new($stem1, $gracing1, $broken-rhythm, $gracing2, $stem2) { self.bless(:$stem1, :$gracing1, :$broken-rhythm, :$gracing2, :$stem2, :ticks($stem1.ticks + $stem2.ticks)); } method broken-factor() { 1 / 2 ** $.broken-rhythm.chars.Int; } method broken-direction-forward() { $.broken-rhythm ~~ /\>/; } sub new-rhythm($note, $ticks) { given $note { when ABC::Note { ABC::Note.new($note.accidental, $note.basenote, $note.octave, ABC::Duration.new(:$ticks), $note.is-tie); } when ABC::Stem { ABC::Stem.new($note.notes.map({ new-rhythm($_, $ticks); })); } } } method effective-stem1() { new-rhythm($.stem1, self.broken-direction-forward ?? $.stem1.ticks * (2 - self.broken-factor) !! $.stem1.ticks * self.broken-factor); } method effective-stem2() { new-rhythm($.stem2, self.broken-direction-forward ?? $.stem2.ticks * self.broken-factor !! $.stem2.ticks * (2 - self.broken-factor)); } method Str() { # Handle gracings here, too $.stem1 ~ $.broken-rhythm ~ $.stem2; } method transpose($pitch-changer) { ABC::BrokenRhythm.new($.stem1.transpose($pitch-changer), $.gracing1, $.broken-rhythm, $.gracing2, $.stem2.transpose($pitch-changer)); } }
### ---------------------------------------------------- ### -- ABC ### -- Licenses: Artistic-2.0 ### -- Authors: ### -- File: lib/ABC/Tuplet.rakumod ### ---------------------------------------------------- use v6; use ABC::Duration; use ABC::Pitched; class ABC::Tuplet does ABC::Duration does ABC::Pitched { has $.p; has $.q; has @.notes; multi method new($p, @notes) { self.new($p, default-q($p), @notes); } multi method new($p, $q, @notes) { die "Tuplet must have at least one note" if +@notes == 0; self.bless(:$p, :$q, :@notes, :ticks($q/$p * [+] @notes>>.ticks)); } sub default-q($p) { given $p { when 3 | 6 { 2; } when 2 | 4 | 8 { 3; } default { 2; } # really need to know the time signature for this! } } method Str() { my $q = $.q != default-q($.p) ?? $.q !! ""; my $r = @.notes != $.p ?? [email protected] !! ""; if $q eq "" && $r eq "" { "(" ~ $.p ~ @.notes.join(""); } else { "(" ~ $.p ~ ":" ~ $q ~ ":" ~ $r ~ @.notes.join(""); } } method transpose($pitch-changer) { ABC::Tuplet.new($.tuple, @.notes>>.transpose($pitch-changer)); } method tuple() { $.p; } # for backwards compatibility, probably needs to go in the long run }
### ---------------------------------------------------- ### -- ABC ### -- Licenses: Artistic-2.0 ### -- Authors: ### -- File: lib/ABC/Tune.rakumod ### ---------------------------------------------------- use v6; use ABC::Header; use ABC::Pitched; class ABC::Tune { has $.header; has @.music; multi method new(ABC::Header $header, @music) { self.bless(:$header, :@music); } method transpose(Int $steps-up) { sub transpose-element($element) { $element.key => ($element.value ~~ ABC::Pitched) ?? $element.transpose($steps-up) !! $element.value; } ABC::Tune.new($.header, @.music.map({ transpose-element($_); })); } }
### ---------------------------------------------------- ### -- ABC ### -- Licenses: Artistic-2.0 ### -- Authors: ### -- File: lib/ABC/LongRest.rakumod ### ---------------------------------------------------- use v6; class ABC::LongRest { has $.measures_rest; method new($measures_rest) { self.bless(:measures_rest(+$measures_rest)); } method Str() { "Z" ~ $.measures_rest; } }
### ---------------------------------------------------- ### -- ABC ### -- Licenses: Artistic-2.0 ### -- Authors: ### -- File: lib/ABC/Stem.rakumod ### ---------------------------------------------------- use v6; use ABC::Duration; use ABC::Pitched; class ABC::Stem does ABC::Duration does ABC::Pitched { has @.notes; has $.is-tie; method new(@notes, ABC::Duration $duration, $is-tie) { die "Stem must have at least one note" if +@notes == 0; self.bless(:@notes, :ticks(@notes>>.ticks.max * $duration.ticks), :$is-tie); } method Str() { "[" ~ @.notes.join("") ~ "]" ~ ($.is-tie ?? "-" !! ""); } method transpose($pitch-changer) { ABC::Stem.new(@.notes>>.transpose($pitch-changer), self, $.is-tie); } }
### ---------------------------------------------------- ### -- ADT ### -- Licenses: ### -- Authors: ### -- File: META6.json ### ---------------------------------------------------- { "perl" : "6.*", "name" : "ADT", "version" : "0.5", "description" : "Algebraic Data Types inspired by Haskell.", "depends" : [ ], "source-url" : "git://github.com/timo/ADT.git", "author" : "Timo Paulssen", "provides": { "ADT": "lib/ADT.pm6" } }
### ---------------------------------------------------- ### -- ADT ### -- Licenses: ### -- Authors: ### -- File: README.md ### ---------------------------------------------------- Algebraic Data Types ==================== This module implements algebraic data types inspired by the Haskell syntax. See below for limitations of the current implementation. Here's a code example for you: use ADT; # define the algebraic data type my $adt = q{Tree = Branch Tree left, Tree right | Leaf Str storage}; my %res = create_adt($adt); # capture the Tree class my \Tree = %res<Tree>; # create a tree using named parameters my $t = Tree.new-branch( :left(Tree.new-branch( :left(Tree.new-leaf(:storage(1))), :right(Tree.new-leaf(:storage(2))))), :right(Tree.new-leaf(:storage(3)))); # pretty-print the tree say $t.gist; # create a tree using positional arguments my $t2 = Tree.new-branch( Tree.new-branch( Tree.new-leaf(1), Tree.new-leaf(2)), Tree.new-leaf(3)); say $t2.gist; # capture the subtypes to pattern-match in a given block. my \Branch = %res<Branch>; my \Leaf = %res<Leaf>; # map over a whole tree changing all storages. sub treemap($t, *&code) { given $t { when Branch { return Tree.new-branch(treemap($t.left, &code), treemap($t.right, &code)) } when Leaf { return Tree.new-leaf(code($t.storage)) } } } # multiply every leaf node by 10 say treemap($t2, * * 10).gist; Limitations ----------- ### Compile-time availability Since rakudo doesn't yet allow the EXPORT sub of a package to return a hash of things to export, the ADT cannot be used to define multi subs, because the symbols are not available at compile time. When EXPORT works, code like this will be possible: use ADT "data Tree = Branch Tree left, Tree right | Leaf Str storage"; multi sub treemap(Branch $t, *&c) { ... } multi sub treemap(Leaf $l, *&c) { ... } ### Compile-time checks One of the neat features of ADT is that the compiler can ensure, that the program is prepared to deal with every defined case (Branch or Leaf, Just or Nothing, ...). A macro can probably be devised to implement such a compile-time check. ### "is parsed" macros When Rakudo gets support for "is parsed" macros, definitons of ADT can move from the "use" line into the mainline of the code, so that they look tidyer and the programmer can put comments nearby etc.
### ---------------------------------------------------- ### -- ADT ### -- Licenses: ### -- Authors: ### -- File: .travis.yml ### ---------------------------------------------------- language: perl6 perl6: - latest install: - rakudobrew build zef - zef install .
### ---------------------------------------------------- ### -- ADT ### -- Licenses: ### -- Authors: ### -- File: t/01-tree.t ### ---------------------------------------------------- use Test; use ADT; plan 7; { my %res = create_adt("Tree = Branch Tree left, Tree right | Leaf Str storage"); my \Tree = %res<Tree>; my $in-out = 'Tree.new-branch(left => Tree.new-branch(left => Tree.new-leaf(storage => 1), right => Tree.new-leaf(storage => 2)), right => Tree.new-leaf(storage => 3))'; my $t = Tree.new-branch(left => Tree.new-branch(left => Tree.new-leaf(storage => 1), right => Tree.new-leaf(storage => 2)), right => Tree.new-leaf(storage => 3)); is $t.gist, $in-out, "evaling a construction gists out exactly the same again."; is $t.perl, $in-out, "evaling a construction perls out exactly the same again."; my $t2 = Tree.new-branch( Tree.new-branch( Tree.new-leaf(1), Tree.new-leaf(2)), Tree.new-leaf(3)); is $t2.gist, $in-out, "positional args for constructors work, too"; my \Branch = %res<Branch>; my \Leaf = %res<Leaf>; sub treemap($t, *&code) { given $t { when Branch { return Tree.new-branch(treemap($t.left, &code), treemap($t.right, &code)) } when Leaf { return Tree.new-leaf(code($t.storage)) } } } $t2 = treemap($t2, * * 10); my $counter; treemap($t2, { $counter += $^val; $^val }); is $counter, 60, "example treemaps work"; ok $t ~~ Tree, "smartmatch against container class"; ok $t ~~ Branch, "smartmatch against one constructor"; ok $t.right ~~ Leaf, "smartmatch against another constructor"; }
### ---------------------------------------------------- ### -- ADT ### -- Licenses: ### -- Authors: ### -- File: t/04-whitespace.t ### ---------------------------------------------------- use Test; use ADT; plan 5; { dies-ok { create_adt("arghlebarghle") }, "sanity"; ok create_adt(q:to/TREE/), "simple multiline"; Tree = Branch Tree left, Tree right | Leaf Str storage TREE ok create_adt(q:to/TREE/), "| on the first line, too"; Tree = | Branch Tree left, Tree right | Leaf Str storage TREE ok create_adt(q:to/TREE/), "newline after comma"; Tree = | Branch Tree left, Tree right | Leaf Str storage TREE ok create_adt(q:to/TREE/), "trailing comma"; Tree = | Branch Tree left, Tree right, | Leaf Str storage, TREE }
### ---------------------------------------------------- ### -- ADT ### -- Licenses: ### -- Authors: ### -- File: t/03-positional.t ### ---------------------------------------------------- use Test; use ADT; plan 8; { my %res = create_adt("Positionals = One Str one1 | Two Str a, Str b | Three Str x, Str y, Str z | Five Str f1, Str f2, Str f3, Str f4, Str f5 | Eight Str e1, Str e2, Str e3, Str e4, Str e5, Str e6, Str e7, Str e8"); my \Positionals = %res<Positionals>; my \One = %res<One>; my \Two = %res<Two>; my \Three = %res<Three>; my \Five = %res<Five>; my \Eight = %res<Eight>; my $one = Positionals.new-one: <black>; ok $one ~~ One, "positional constructors"; my $two = Positionals.new-one: <then>; ok $two ~~ One; my $three = Positionals.new-two: <white are>; ok $three ~~ Two; my $four = Positionals.new-three: <all I see>; ok $four ~~ Three; my $five = Positionals.new-five: <in my in fan cy>; ok $five ~~ Five; my $six = Positionals.new-eight: <red and yel low then came to be>; ok $six ~~ Eight; my $seven = Positionals.new-five: <rea ching out to me>; ok $seven ~~ Five; my $eight = Positionals.new-three: <lets me see>; ok $eight ~~ Three; }
### ---------------------------------------------------- ### -- ADT ### -- Licenses: ### -- Authors: ### -- File: t/02-EXPORT.t ### ---------------------------------------------------- use Test; eval-lives-ok q{ use ADT "Tree = Branch Tree left, Tree right | Leaf Str storage"; my $a = Tree.new-leaf("Hello"); }, "single ADT from EXPORT"; eval-lives-ok q{ use ADT "Maybe = Just Str data | Nothing"; my $a = Maybe.new-just("Hello"); }, "single ADT from EXPORT number 2"; eval-lives-ok q{ use ADT "Maybe = Just Str data | Nothing", "Tree = Branch Tree left, Tree right | Leaf Str storage"; my $a = Maybe.new-just("Hello"); my $b = Tree.new-leaf("Goodbye"); }, "two ADTs from EXPORT"; done-testing;
### ---------------------------------------------------- ### -- AI::FANN ### -- Licenses: Artistic-2.0 ### -- Authors: Jonathan Scott Duff <[email protected]>, José Joaquín Atria <[email protected]> ### -- File: META6.json ### ---------------------------------------------------- { "auth": "zef:jjatria", "authors": [ "Jonathan Scott Duff <[email protected]>", "José Joaquín Atria <[email protected]>" ], "depends": { "build": { "requires": [ "fann:from<native>" ] }, "test": { "requires": [ "File::Temp", "Test" ] } }, "description": "Raku binding to the Fast Artificial Neural Network library", "license": "Artistic-2.0", "name": "AI::FANN", "perl": "6.d", "provides": { "AI::FANN": "lib/AI/FANN.rakumod", "AI::FANN::Raw": "lib/AI/FANN/Raw.rakumod", "AI::FANN::Raw::Base": "lib/AI/FANN/Raw/Base.rakumod", "AI::FANN::Raw::Cascade": "lib/AI/FANN/Raw/Cascade.rakumod", "AI::FANN::Raw::Creation": "lib/AI/FANN/Raw/Creation.rakumod", "AI::FANN::Raw::Error": "lib/AI/FANN/Raw/Error.rakumod", "AI::FANN::Raw::IO": "lib/AI/FANN/Raw/IO.rakumod", "AI::FANN::Raw::Training": "lib/AI/FANN/Raw/Training.rakumod" }, "source-type": "git", "source-url": "https://github.com/jjatria/AI-FANN.git", "support": { "bugtracker": "https://github.com/jjatria/AI-FANN/issues", "source": "https://github.com/jjatria/AI-FANN.git" }, "tags": [ "AI", "Neural Network" ], "version": "0.2.0" }
### ---------------------------------------------------- ### -- AI::FANN ### -- Licenses: Artistic-2.0 ### -- Authors: Jonathan Scott Duff <[email protected]>, José Joaquín Atria <[email protected]> ### -- File: README.md ### ---------------------------------------------------- ### -- Chunk 1 of 2 # NAME AI::FANN # SYNOPSIS ``` raku # See below for details on export tags use AI::FANN :enum; # Hidden # Input | Output # \ | / given AI::FANN.new: layers => [ 2, 3, 1 ] { LEAVE .?destroy; # Make sure to clean up after yourself # A sample data set for solving the XOR problem my $data = AI::FANN::TrainData.new: pairs => [ [ -1, -1 ] => [ -1 ], [ -1, 1 ] => [ 1 ], [ 1, -1 ] => [ 1 ], [ 1, 1 ] => [ -1 ], ]; LEAVE $data.?destroy; .activation-function: FANN_SIGMOID_SYMMETRIC; # Train for up to 500,000 epochs # or until the MSE is less than 0.001 # with no reports to STDOUT .train: $data, desired-error => 0.001, max-epochs => 500_000, epochs-between-reports => 0; say .run: [ 1, -1 ]; } # OUTPUT: # (0.9508717060089111) ``` # DESCRIPTION This distribution provides native bindings for the Fast Artificial Neural Network library (FANN). The aim of the library is to be easy to use, which makes it a good entry point and suitable for working on machine learning prototypes. Creating networks, training them, and running them on input data can be done without much knowledge of the internals of ANNs, although the ANNs created will still be powerful and effective. Users with more experience and desiring more control will also find methods to parameterize most of the aspects of the ANNs, allowing for the creation of specialized and highly optimal ANNs. ## Installation The bindings for Raku make use of the system version of FANN. Please refer to your platform's instructions on how to install the library, or follow the instructions for [compiling from source](https://github.com/libfann/fann#to-install). ## Error handling The default behaviour for libfann is to print errors to standard error. In order to give the user more control over how to handle these errors, AI::FANN will raise exceptions whenever an error is encountered. When possible, these will be raised before an actual call to libfann is ever made. When this is not possible, errors raised by libfann will be wrapped into exceptions of type X::AI::FANN. When capturing these, a string version of the error will be available in its `message` method, while its `code` method will return the error as a member of the [AI::FANN::Error](#aifannerror) enum. # METHODS The methods described below include readers, mutators, and methods that operate on the internal state of the network in more complex ways. Some methods, like [num-input](#num-input) are only for reading the internal state of the network, and will always return the value that was requested. Other methods, like [activation-function](#activation-function) will act as both readers and mutators depending on the arguments that are passed. When acting as readers, named parameters may be used to specify the scope of the reading. Some of these may be mandatory. When acting as mutators, the new value should be passed as one or more positional arguments, with any named parameters specifying the possible scope of the mutation. All mutators always return the calling object, to allow for chaining. These will be marked in the signatures as `returns self`. Most other methods, like [reset-error](#reset-error) or [train](#train), will also return the calling object, and may take named parameters. Some methods have different return values, like [test](#test) or [save](#save) that reflect the result of the operation. In all cases, the signature should specify the return value. The sections below follow roughly the same structure as that used in the documentation of [libfann](http://libfann.github.io/fann/docs). Whenever possible, the underlying method that is being called will be indicated next to the method signatures. Please refer to the libfann documentation for additional details. ## Creation and Execution ### new ``` raku # fann_create_shortcut # fann_create_sparse # fann_create_standard multi method new ( :@layers, Num() :$connection-rate, Bool() :$shortcut, ) returns AI::FANN # fann_create_from_file multi method new ( IO() :$path, ) returns AI::FANN ``` Creates a new AI::FANN neural network. The constructor can be called in one of two ways. If the `path` parameter is set, it will be coerced to a [IO::Path] and the network will be created based on the contents of that file (see [save](#save) for how this file can be created). Alternatively, a list of integers can be passed as the `layers` parameter to specify the number of neurons in each layer, with the input layer being the first in the list, the output layer being the last in the list, and any remaining ones describing hidden layers. By default, this will create a fully connected backpropagation neural network. There will be a bias neuron in each layer (except the output layer), and this bias neuron will be connected to all neurons in the next layer. When running the network, the bias nodes always emits 1. To create a neural network that is not fully connected, a `connection-rate` parameter can be set to a number between 0 and 1, where 0 is a network with no connections, and 1 is a fully connected network. If the `shortcut` flag is set, the resulting network will be fully connected, and it will have connections between neurons in non-contiguous layers. A fully connected network with shortcut connections is a network where all neurons are connected to all neurons in later layers, including direct connections from the input layer to the output layer. The `connection-rate` and `shortcut` parameters are not compatible, and using both is an error. ### run ``` raku # fann_run multi method run ( CArray[num32] $input ) returns CArray[num32] multi method run ( *@input ) returns List ``` Run the input through the neural network, returning an array of outputs. The output array will have one value per neuron in the output layer. The type of the return value depends on the type of the input. If the input is provided as a [CArray[num32]][CArray] object, it will be used as-is and the return value will be of the same type. This is the fastest way to call this method. If the input is passed as a [List] or [Array], it will be internally converted to its C representation, and the return value will be a [List] object. ### bit-fail ``` raku # fann_get_bit_fail method bit-fail returns Int ``` Returns the number of fail bits, or the number of output neurons which differ more than the bit fail limit (see [bit-fail-limit](#bit-fail-limit)). The bits are counted in all of the training data, so this number can be higher than the number of training data. This value is reset by [reset-error](#reset-error) and updated by all the same functions which also update the mean square error (eg. [test](#test)). ### connection-rate ``` raku # fann_get_connection_rate method connection-rate returns Num ``` Get the connection rate used when the network was created. ### num-input ``` raku # fann_get_num_input method num-input returns Int ``` Get the number of input neurons. ### num-layers ``` raku # fann_get_num_layers method num-layers returns Int ``` Get the number of layers in the network. ### num-output ``` raku # fann_get_num_output method num-output returns Int ``` Get the number of output neurons. ### total-connections ``` raku # fann_get_total_connection method total-connections returns Int ``` Get the total number of connections in the entire network. ### total-neurons ``` raku # fann_get_total_neurons method total-neurons returns Int ``` Get the total number of neurons in the entire network. This number includes the bias neurons, so a 2-4-2 network has 2+4+2 neurons, plus 2 bias neurons (one for each layer except the output one) for a total of 10. ### network-type ``` raku # fann_get_network_type method network-type returns AI::FANN::NetType ``` Get the type of neural network it was created as. ### layer-array ``` raku # fann_get_layer_array method layer-array returns List ``` Get the number of neurons in each layer in the network. Bias is not included so the layers match the ones used in the constructor. ### bias-array ``` raku # fann_get_bias_array method bias-array returns List ``` Get the number of bias in each layer in the network. ### connection-array ``` raku # fann_get_connection_array method connection-array returns List ``` Get the connections in the network as a [List] of AI::FANN::Connection. These objects encapsulate a connection between two neurons. They hold a number identifying the source and target neurons, which can be read with the `from-neuron` and `to-neuron` methods respectively; and the weight of the connection, which can be read with the `weight` method. The `weight` method returns a writable container, which means that a new value can be set by using it on the left side of an assignment. Connection objects thus modified can then be passed to the [weights](#weights) method described below to update the connections of the network. ### weights ``` raku multi method weights () returns List # fann_set_weight multi method weights ( Num() $weight, Int() :$from! where * >= 0, Int() :$to! where * >= 0, ) returns self multi method weights ( *@connections where { .all ~~ AI::FANN::Connection }, ) returns self ``` Called with no arguments, returns the list of all connection weights as a [List] of [Num]. The weights will be in the same order as the connections returned by [connection-array](#connection-array). This method can also be used as a setter if called with either a weight as a positional argument and the numbers identifying the source and target neurons as the `:from` and `:to` named parameters respectively. Alternatively, one or more AI::FANN::Connection objects (such as those returned by [connection-array](#connection-array) can be passed as positional arguments, in which case the weight in each connection will be used as the new value. See the documentation of that method for details. Using this method as a setter returns the calling ANN, to allow for chaining. ### randomize-weights ``` raku # fann_randomize_weights method randomize-weights ( Range:D $range, ) returns self ``` Give each connection a random weight between the endpoints of the specified [Range] object. From the beginning the weights are random between -0.1 and 0.1. This method is an alias for [randomise-weights](#randomise-weights). ### randomise-weights ``` raku # fann_randomize_weights method randomise-weights ( Range:D $range, ) returns self ``` Give each connection a random weight between the endpoints of the specified [Range] object. From the beginning the weights are random between -0.1 and 0.1. This method is an alias for [randomize-weights](#randomize-weights). ### init-weights ``` raku # fann_init_weights method init-weights ( AI::FANN::TrainData:D $data, ) returns self ``` Initialize the weights using Widrow + Nguyen’s algorithm. This function behaves similarly to [randomize-weights](#randomize-weights). It will use the algorithm developed by Derrick Nguyen and Bernard Widrow to set the weights in such a way as to speed up training. This technique is not always successful, and in some cases can be less efficient than a purely random initialization. The algorithm requires access to the range of the input data (ie, largest and smallest input), and therefore requires an AI::FANN::TrainData as its only positional argument. This should be the same data set used to train the network. ### print-connections ``` raku # fann_print_connections method print-connections returns self ``` Will print the connections of the network in a compact matrix, for easy viewing of its internals. As an example, this is the output from a small (2 2 1) network trained on the xor problem: Layer / Neuron 012345 L 1 / N 3 BBa... L 1 / N 4 BBA... L 1 / N 5 ...... L 2 / N 6 ...BBA L 2 / N 7 ...... This network has five real neurons and two bias neurons. This gives a total of seven neurons named from 0 to 6. The connections between these neurons can be seen in the matrix. A period (".") indicates there is no connection, while a character tells how strong the connection is on a scale from a-z. The two real neurons in the hidden layer (neuron 3 and 4 in layer 1) have connections from the three neurons in the previous layer as is visible in the first two lines. The output neuron (6) has connections from the three neurons in the hidden layer 3 - 5, as shown in the fourth line. To simplify the matrix output, neurons are not visible as neurons that connections can come from, and input and bias neurons are not visible as neurons that connections can go to. ### print-parameters ``` raku # fann_print_parameters method print-parameters returns self ``` Prints all of the parameters and options of the network. ### clone ``` raku # fann_copy method clone returns AI::FANN ``` Returns an exact copy of the calling AI::FANN object. ### destroy ``` raku # fann_destroy method destroy returns Nil ``` Destroy the internal representation of this network. It's a good idea to make sure to call this for every object that has been created. ## File Input / Output ### save ``` raku # fann_save method save ( IO() $path ) returns Bool ``` Save the entire network to a configuration file. The configuration file contains all information about the neural network and can be passed as the `path` parameter to the constructor to create an exact copy of the network and all of the associated parameters. The only parameters that are not saved are the callback, error log, and user data, since they cannot safely be ported to a different location. Note that temporary parameters generated during training, like the mean square error, are also not saved. ## Training The methods in this section support fixed topology training. When using this method of training, the size and topology of the ANN is determined in advance and the training alters the weights in order to minimize the difference between the desired output values and the actual output values. For evolving topology training, see the [Cascade Training](#cascade-training) section below. ### train ``` raku multi method train ( @input, @output, ) returns self # fann_train multi method train ( CArray[num32] $input, CArray[num32] $output, ) returns self # fann_train_epoch # fann_train_on_data multi method train ( AI::FANN::TrainData:D $data, Int() :$max-epochs, Int() :$epochs-between-reports, Num() :$desired-error, ) returns self # fann_train_epoch # fann_train_on_file multi method train ( IO() $path, Int() :$max-epochs, Int() :$epochs-between-reports, Num() :$desired-error, ) returns self ``` This method is used to train the neural network. The first two candidates train a single iteration using the specified set of inputs and desired outputs in the `input` and `output` parameters. Inputs and outputs can be passed as [CArray[num32]][CArray] objects, or as arrays of numeric values, which will be converted internally to their C representation. Since only one pattern is presented, training done this way is always incremental training (`FANN_TRAIN_INCREMENTAL` in the [AI::FANN::Train](#aifanntrain) enum). The last two candidates train instead on an entire dataset. The first one takes a mandatory AI::FANN::TrainData object, while the second takes instead a filename that will be used to generate a training dataset internally. Both of these candidates will default to running a single iteration or "epoch". They can instead be used to train for a period of time by specifying the maximum number of iterations, the target error, and the number of iterations between reports. See [callback](#callback) for the code that gets executed to generate this report. In both cases, the training uses the algorithm set with [training-algorithm](#training-algorithm), and the parameters set for these training algorithms (see [Training Algorithm Parameters](#training-algorithm-parameters) below). ### test ``` raku multi method test ( @input, @output, ) returns List # fann_test multi method test ( CArray[num32] $input, CArray[num32] $output, ) returns CArray[num32] multi method test ( AI::FANN::TrainData $data, ) returns Num multi method train ( IO() $path, ) returns Num ``` Test the network with a set of inputs and desired outputs. This operation updates the mean square error, but does not change the network in any way. Inputs and outputs can be passed as CArray[num32] objects, or as arrays of numeric values, which will be converted internally to their C representation. These candidates return the same as the equivalent invokations of [run](#run). Two more calling patterns are offered as shortcuts. A AI::FANN::TrainData object can be passed as the `data` parameter, in which case the network will be tested with all the input and output data it contains. Alternatively, the `path` parameter can be set to a value that can be coerced to a [IO::Path] object. In this case, an AI::FANN::TrainData will be internally read from the contents of this file and used as above. These candidates return the updated mean square error for the network. ### callback ``` raku multi method callback ( :$delete where :so, ) returns self # fann_set_callback method callback ( &callback where { .cando: \( AI::FANN $fann, AI::FANN::TrainData $data, uint32 $max-epochs, uint32 $epochs-between-reports, num32 $desired-error, uint32 $epoch, ); } ) returns self ``` If called with a [Callable] as the first positional argument, this method will set that as the training callback. If called with a single `:delete` argument that evaluates to [True], any previously set callback will be cleared, and the default callback will be restored. The default callback function simply prints out some status information. The callback will be called during training if using a AI::FANN::TrainData object either directly (with the `:data` argument to [train](#train)) or indirectly (with the `:path` argument to the same method). It will be called once during the first epoch, and again every time the epoch is divisible by the value provided in the `:epochs-between-reports` argument to [train](#train). The callback will be called with the AI::FANN object being trained, the AI::FANN::TrainData object that is being used for training, as well as the maximum number of allowed training epochs, the number of epochs between reports, and the target error for training that were set when training started as positional arguments. Additionally, the current epoch will also be passed as the final argument to the callback. The callback can interrupt the training by returning [False] or a value that, when coerced into an [Int] evaluates to -1. ### activation-function ``` raku # fann_get_activation_function multi method activation-function ( Int :$layer!, Int :$neuron!, ) returns AI::FANN::ActivationFunc # fann_set_activation_function # fann_set_activation_function_layer multi method activation-function ( AI::FANN::ActivationFunc $function, Int :$layer!, Int :$neuron, ) returns self # fann_set_activation_function_hidden # fann_set_activation_function_output multi method activation-function ( AI::FANN::ActivationFunc $function, Bool() :$hidden, Bool() :$output, ) returns self ``` If called with no positional arguments, this method returns the activation function for the neuron number and layer specified in the `:neuron` and `:layer` parameters respectively, counting the input layer as layer 0. It is not possible to get activation functions for the neurons in the input layer: trying to do so is an error. If called with a member of the [AI::FANN::ActivationFunc](#aifannactivationfunc) enum as the first positional argument, then this function will instead _set_ this as the activation function for the specified layer and neuron, and return the calling AI::FANN object. When used as a setter, specifying the layer is always required. This can be done with the `:layer` parameter, as described above, or with the `:hidden` or `:output` flags. The `:hidden` flag will set the activation function for all neurons in _all_ hidden layers, while the `:output` flag will do so only for those in the output layer. When setting the activation function using the `:layer` parameter, the `:neuron` parameter is optional. If none is set, all neurons in the specified layer will be modified. ### activation-steepness ``` raku # fann_get_activation_steepness multi method activation-steepness ( Int :$layer!, Int :$neuron!, ) returns Num # fann_set_activation_steepness # fann_set_activation_steepness_layer multi method activation-steepness ( Num() $steepness, Int :$layer!, Int :$neuron, ) returns self # fann_set_activation_steepness_hidden # fann_set_activation_steepness_output multi method activation-steepness ( Num() $steepness, Bool() :$hidden, Bool() :$output, ) returns self ``` If called with no positional arguments, this method returns the activation steepness for the neuron number and layer specified in the `:neuron` and `:layer` parameters respectively, counting the input layer as layer 0. It is not possible to get activation functions for the neurons in the input layer: trying to do so is an error. If called with a positional argument, it will be coerced to a [Num] and this function will instead _set_ this as the activation steepness for the specified layer and neuron and return the calling AI::FANN object. When used as a setter, specifying the layer is always required. This can be done with the `:layer` parameter, as described above, or with the `:hidden` or `output` flags. The `:hidden` flag will set the activation function for all neurons in _all_ hidden layers, while the `output` flag will do so only for those in the output layer. When setting the activation steepness using the `:layer` parameter, the `:neuron` parameter is optional. If none is set, all neurons in the specified layer will be modified. ### training-algorithm ``` raku # fann_get_training_algorithm multi method training-algorithm returns AI::FANN::Train # fann_set_training_algorithm multi method training-algorithm ( AI::FANN::Train $algorithm, ) returns self ``` If called with no positional arguments, this method returns the training algorithm as per the [AI::FANN::Train](#aifanntrain) enum. The training algorithm is used eg. when running [train](#train) or [cascade-train](#cascade-train) with a AI::FANN::TrainData object. If a member of that enum is passed as the first positional argument, this method instead sets that as the new training algorithm and returns it. Note that only `FANN_TRAIN_RPROP` and `FANN_TRAIN_QUICKPROP` are allowed during cascade training. The default training algorithm is `FANN_TRAIN_RPROP`. ### train-error-function ``` raku # fann_get_train_error_function multi method train-error-function returns AI::FANN::ErrorFunc # fann_set_train_error_function multi method train-error-function ( AI::FANN::ErrorFunc $function, ) returns self ``` If called with no positional arguments, this method returns the error function used during training as per the [AI::FANN::ErrorFunc](#aifannerrorfunc) enum. If a member of that enum is passed as the first positional argument, this method instead sets that as the new training error function and returns it. The default training error function if `FANN_ERRORFUNC_TANH`. ### train-stop-function ``` raku # fann_get_train_stop_function multi method train-stop-function returns AI::FANN::StopFunc # fann_set_train_stop_function multi method train-stop-function ( AI::FANN::StopFunc $function, ) returns self ``` If called with no positional arguments, this method returns the stop function used during training as per the [AI::FANN::StopFunc](#aifannstopfunc) enum. If a member of that enum is passed as the first positional argument, this method instead sets that as the new training stop function and returns it. The default training stop function if `FANN_STOPFUNC_MSE`. ### bit-fail-limit ``` raku # fann_get_bit_fail_limit multi method bit-fail-limit returns Num # fann_set_bit_fail_limit multi method bit-fail-limit ( Num() $limit, ) returns self ``` If called with no positional arguments, this method returns the bit fail limit used during training. If called with a positional argument, it will be coerced to a [Num] and set as the new limit. The bit fail limit is used during training when the stop function is set to `FANN_STOPFUNC_BIT` (see [train-stop-function](#train-stop-function)). The limit is the maximum accepted difference between the desired output and the actual output during training. Each output that diverges more than this limit is counted as an error bit. This difference is divided by two when dealing with symmetric activation functions, so that symmetric and asymmetric activation functions can use the same limit. The default bit fail limit is 0.35. ### learning-rate ``` raku multi method learning-rate returns Num multi method learning-rate ( Num() $rate, ) returns self ``` If called with no positional arguments, this method returns the learning rate used during training. If called with a positional argument, it will be coerced to a [Num] and set as the new learning rate. The learning rate is used to determine how aggressive training should be for some of the training algorithms (`FANN_TRAIN_INCREMENTAL`, `FANN_TRAIN_BATCH`, `FANN_TRAIN_QUICKPROP`). Do however note that it is not used in `FANN_TRAIN_RPROP`. The default learning rate is 0.7. ### learning-momentum ``` raku multi method learning-momentum returns Num multi method learning-momentum ( Num() $momentum, ) returns self ``` If called with no positional arguments, this method returns the learning momentum used during training. If called with a positional argument, it will be coerced to a [Num] and set as the new learning momentum. The learning momentum can be used to speed up `FANN_TRAIN_INCREMENTAL` training. Too high a momentum will however not benefit training. Setting the momentum to 0 will be the same as not using the momentum parameter. The recommended value of this parameter is between 0 and 1. The default momentum is 0. ### scale ``` raku # fann_scale_train multi method scale ( AI::FANN::TrainData:D $data, ) returns self # fann_scale_input # fann_scale_output multi method scale ( CArray[num32] :$input, CArray[num32] :$output, ) returns self # fann_scale_input # fann_scale_output multi method scale ( :@input, :@output, ) returns self ``` This method will scale a set of inputs and outputs according to the scaling parameters set in this network (see [scaling](#scaling) for how these are calculated and set). If called with an AI::FANN::TrainData object, the scaling will apply to its input and output data. Alternatively, the `:input` and `:output` named parameters can be set to either [CArray[num32]][CArray] or to [Array] objects with the data to scale, which will be modified in-place according to the scaling parameters calculated for inputs and outputs respectively. See [descale](#descale) for a way to reverse this manipulation. Calling this method before setting scaling parameters (with [scaling](#scaling)) is an error. Calling this method after clearing the scaling parameters is not. ### descale ``` raku # fann_descale_train multi method descale ( AI::FANN::TrainData:D $data, ) returns self # fann_descale_input # fann_descale_output multi method descale ( CArray[num32] :$input, CArray[num32] :$output, ) returns self # fann_descale_input # fann_descale_output multi method descale ( :@input, :@output, ) returns self ``` This method will reverse the scaling performed by [scale](#scale). If called with an AI::FANN::TrainData object, the descaling will apply to its input and output data. Alternatively, the `:input` and `:output` named parameters can be set to either [CArray[num32]][CArray] or to [Array] objects with the data to descale, which will be modified in-place according to the scaling parameters calculated for inputs and outputs respectively. Calling this method before setting scaling parameters (with [scaling](#scaling)) is an error. Calling this method after clearing the scaling parameters is not. ### scaling ``` raku # fann_set_scaling_params # fann_set_input_scaling_params # fann_set_output_scaling_params multi method scaling ( AI::FANN::TrainData:D $data, Range :$output, Range :$input, ) returns self # fann_clear_scaling_params multi method scaling ( :$delete! where :so, ) returns self ``` Takes an AI::FANN::TrainData object that will be used to calculate the scaling parameters as a positional parameter, and [Range] objects representing the desired range for input and output values in the `:input` and `:output` named parameters respectively. At least one of these must be specified. The scaling parameters set by this method can be cleared with the `:delete` flag. This will reset them a default value of -1..1. ### reset-error ``` raku # fann_reset_MSE method reset-error returns self ``` Resets the mean square error from the network, and the number of bits that fail. ### mean-square-error ``` raku # fann_get_MSE method mean-square-error returns Num ``` Reads the mean square error from the network. This value is calculated during training or testing (see [train](#train) and [test](#test) above), and can therefore sometimes be a bit off if the weights have been changed since the last calculation of the value. ## Training Algorithm Parameters These methods control the parameters used for specific training algorithms. ### quickprop-decay ``` raku multi method quickprop-decay returns Num multi method quickprop-decay ( Num() $value where * <= 0, ) returns self ``` The decay is a small negative valued number which is the factor that the weights should become smaller in each iteration during quickprop training. This is used to make sure that the weights do not become too high during training. If called with no positional arguments, this method returns the current decay value. If called with a positional argument, it will be coerced to a [Num] and set as the new decay. The default decay is -0.0001. ### quickprop-mu ``` raku multi method quickprop-mu returns Num multi method quickprop-mu ( Num() $value, ) returns self ``` The mu factor is used to increase and decrease the step-size during quickprop training. The mu factor should always be above 1, since it would otherwise decrease the step-size when it was supposed to increase it. If called with no positional arguments, this method returns the current mu factor. If called with a positional argument, it will be coerced to a [Num] and set as the new mu factor. The default mu factor is 1.75. ### rprop-increase ``` raku multi method rprop-increase returns Num multi method rprop-increase ( Num() $value where * > 1, ) returns self ``` The increase factor is a value larger than 1, which is used to increase the step-size during RPROP training. If called with no positional arguments, this method returns the current increase factor. If called with a positional argument, it will be coerced to a [Num] and set as the new increase factor. The default increase factor is 1.2. ### rprop-decrease ``` raku multi method rprop-decrease returns Num multi method rprop-decrease ( Num() $value where * < 1, ) returns self ``` The increase factor is a value larger than 1, which is used to decrease the step-size during RPROP training. If called with no positional arguments, this method returns the current decrease factor. If called with a positional argument, it will be coerced to a [Num] and set as the new decrease factor. The default increase factor is 0.5. ### rprop-delta-range ``` raku multi method rprop-delta-range returns Range multi method rprop-delta-range ( Range $value where { not .infinite }, ) returns self ``` The delta range determines the minimum and maximum allowed values for the step-size used during RPROP training. If called with no positional arguments, this method returns the current delta range. If called with a [Range] as a positional argument, it will be set as the new delta range. The default delta range is 0..50. ### rprop-delta-zero ``` raku multi method rprop-delta-zero returns Num multi method rprop-delta-zero ( Num() $value where * > 0, ) returns self ``` The delta zero is a positive number determining the initial step size used during RPROP training. If called with no positional arguments, this method returns the current initial step size. If called with a positional argument, it will be coerced to a [Num] and set as the new initial step size. The default delta zero is 0.1. ### sarprop-weight-decay-shift ``` raku multi method sarprop-weight-decay-shift returns Num multi method sarprop-weight-decay-shift ( Num() $value, ) returns self ``` If called with no positional arguments, this method returns the current weight decay shift used during SARPROP training.
End of preview. Expand in Data Studio

Raku Projects from GitHub

About the Dataset

This dataset is a large proportion of the Raku projects currently available on GitHub.

License

Where possible, the licenses have been extracted from the META6.json files in the repository and appended to the header of each section.

Unfortunately, some projects included in this dataset do not clearly specify a license.

Format

The dataset is formatted for continued pre-training.

Chunks are split at a seq_len of 8192 based on the Qwen 3 tokenizer.

Goals

This dataset is part of a larger collection designed to teach LLMs to write a niche programming language. In this case, Raku (perl 6).

Downloads last month
100