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. |
### ----------------------------------------------------
### -- AI::FANN
### -- Licenses: Artistic-2.0
### -- Authors: Jonathan Scott Duff <[email protected]>, José Joaquín Atria <[email protected]>
### -- File: README.md
### ----------------------------------------------------
### -- Chunk 2 of 2
If called with a positional
argument, it will be coerced to a [Num] and set as the new weight decay shift.
The default value is -6.644.
### sarprop-error-threshold
``` raku
multi method sarprop-error-threshold returns Num
multi method sarprop-error-threshold (
Num() $value,
) returns self
```
If called with no positional arguments, this method returns the current error
threshold factor used during SARPROP training. If called with a positional
argument, it will be coerced to a [Num] and set as the new error threshold
factor.
The default value is 0.1.
### sarprop-step-error-shift
``` raku
multi method sarprop-step-error-shift returns Num
multi method sarprop-step-error-shift (
Num() $value,
) returns self
```
If called with no positional arguments, this method returns the current step
error shift used during SARPROP training. If called with a positional
argument, it will be coerced to a [Num] and set as the new step error shift.
The default value is 1.385.
### sarprop-temperature
``` raku
multi method sarprop-temperature returns Num
multi method sarprop-temperature (
Num() $value,
) returns self
```
If called with no positional arguments, this method returns the current decay
shift used during SARPROP training. If called with a positional argument, it
will be coerced to a [Num] and set as the new decay shift.
The default value is 0.015.
## Cascade Training
Cascade training differs from ordinary training in that it starts with an
empty neural network and then adds neurons one by one, while it trains the
neural network. The main benefit of this approach is that you do not have to
guess the number of hidden layers and neurons prior to training, but cascade
training has also proved better at solving some problems.
The basic idea of cascade training is that a number of candidate neurons are
trained separate from the real network, then the most promising of these
candidate neurons is inserted into the neural network. Then the output
connections are trained and new candidate neurons are prepared. The candidate
neurons are created as shortcut connected neurons in a new hidden layer, which
means that the final neural network will consist of a number of hidden layers
with one shortcut connected neuron in each.
For methods supporting ordinary, or fixed topology training, see the
[Training](#training) section above.
### cascade-train
``` raku
# fann_cascadetrain_on_data
multi method cascade-train (
AI::FANN::TrainData:D $data,
Int() :$max-neurons!,
Int() :$neurons-between-reports!,
Num() :$desired-error!,
) returns self
# fann_cascadetrain_on_file
multi method cascade-train (
IO() $path,
Int() :$max-neurons!,
Int() :$neurons-between-reports!,
Num() :$desired-error!,
) returns self
```
Trains the network on an entire dataset for a period of time using the
Cascade2 training algorithm. The dataset can be passed as an
AI::FANN::TrainData object in the `data` parameter. Alternatively, if
the `path` is set, it will be coerced to an [IO::Path] object and the
training data will be read from there instead.
This algorithm adds neurons to the neural network while training, which means
that it needs to start with an ANN without any hidden layers. The neural
network should also use shortcut connections, so the `shortcut` flag should
be used when invoking [new](#new), like this
``` raku
my $ann = AI::FANN.new: :shortcut,
layers => [ $data.num-input, $data.num-output ];
```
### cascade-num-candidates
``` raku
# fann_get_cascade_num_candidates
multi method cascade-num-candidates returns Int
```
Returns the number of candidates used during training.
The number of candidates is calculated by multiplying the value returned by
[cascade-activation-functions-count](#cascade-activation-functions-count),
[cascade-activation-steepnesses-count](#cascade-activation-steepnesses-count),
and [cascade-num-candidate-groups](#cascade-num-candidate-groups).
The actual candidates is defined by the
[cascade-activation-functions](#cascade-activation-functions) and
[cascade-activation-steepnesses](#cascade-activation-steepnesses) arrays.
These arrays define the activation functions and activation steepnesses used
for the candidate neurons. If there are 2 activation functions in the
activation function array and 3 steepnesses in the steepness array, then there
will be 2x3=6 different candidates which will be trained. These 6 different
candidates can be copied into several candidate groups, where the only
difference between these groups is the initial weights. If the number of
groups is set to 2, then the number of candidate neurons will be 2x3x2=12.
The number of candidate groups can be set with
[cascade-num-candidate-groups](#cascade-num-candidate-groups).
The default number of candidates is 6x4x2 = 48
### cascade-num-candidate-groups
``` raku
# fann_get_cascade_num_candidate_groups
multi method cascade-num-candidate-groups returns Int
# fann_set_cascade_num_candidate_groups
multi method cascade-num-candidate-groups ( Int $groups ) returns self
```
If called with no positional arguments, this method returns the number of
candidate groups used during training. If called with an Int as a positional
argument, it will be set as the new value.
The number of candidate groups is the number of groups of identical candidates
which will be used during training.
This number can be used to have more candidates without having to define new
parameters for the candidates.
See [cascade-num-candidates](#cascade-num-candidates) for a description of
which candidate neurons will be generated by this parameter.
The default number of candidate groups is 2
### cascade-candidate-limit
``` raku
# fann_get_cascade_candidate_limit
multi method cascade-candidate-limit returns Num
# fann_set_cascade_candidate_limit
multi method cascade-candidate-limit ( Num() $value ) returns self
```
The candidate limit is a limit for how much the candidate neuron may be
trained. It limits the proportion between the MSE and candidate score. Set
this to a lower value to avoid overfitting and to a higher if overfitting is
not a problem.
If called with no positional arguments, this method returns the current
candidate limit. If called with a positional argument, it will be coerced
to a [Num] and set as the new candidate limit.
The default candidate limit is 1000.
### cascade-weight-multiplier
``` raku
# fann_get_cascade_weight_multiplier
multi method cascade-weight-multiplier returns Num
# fann_set_cascade_weight_multiplier
multi method cascade-weight-multiplier ( Num() $value ) returns self
```
The weight multiplier is a parameter which is used to multiply the weights
from the candidate neuron before adding the neuron to the neural network.
This parameter is usually between 0 and 1, and is used to make the training a
bit less aggressive.
If called with no positional arguments, this method returns the current
weight multiplier. If called with a positional argument, it will be coerced
to a [Num] and set as the new weight multiplier.
The default weight multiplier is 0.4
### cascade-output-change-fraction
``` raku
# fann_get_cascade_output_change_fraction
multi method cascade-output-change-fraction returns Num
# fann_set_cascade_output_change_fraction
multi method cascade-output-change-fraction ( Num() $value ) returns self
```
The cascade output change fraction is a number between 0 and 1 determining how
large a fraction the [mean-square-error](#mean-square-error) should change
within [cascade-output-stagnation-epochs](#cascade-output-stagnation-epochs)
during training of the output connections, in order for the training not to
stagnate. If the training stagnates, the training of the output connections
will be ended and new candidates will be prepared.
If the MSE does not change by a fraction of the value returned by this method
during a period of
[cascade-output-stagnation-epochs](#cascade-output-stagnation-epochs), the
training of the output connections is stopped because the training has stagnated.
If the cascade output change fraction is low, the output connections will be
trained more and if the fraction is high they will be trained less.
If called with no positional arguments, this method returns the current
output change fraction. If called with a positional argument, it will be
coerced to a [Num] and set as the new fraction.
The default cascade output change fraction is 0.01, which is equivalent to a
1% change in MSE.
### cascade-candidate-change-fraction
``` raku
# fann_get_cascade_candidate_change_fraction
multi method cascade-candidate-change-fraction returns Num
# fann_set_cascade_candidate_change_fraction
multi method cascade-candidate-change-fraction ( Num() $value ) returns self
```
The cascade candidate change fraction is a number between 0 and 1 determining
how large a fraction the [mean-square-error](#mean-square-error) should change
within [cascade-output-stagnation-epochs](#cascade-output-stagnation-epochs)
during training of the candidate neurons, in order for the training not to
stagnate. If the training stagnates, the training of candidate neurons will be
ended and the best candidate will be selected.
If the MSE does not change by a fraction of the value returned by this method
during a period of
[cascade-candidate-stagnation-epochs](#cascade-candidate-stagnation-epochs), the
training of the candidate neurons is stopped because the training has stagnated.
If the cascade candidate change fraction is low, the candidate neurons will be
trained more and if the fraction is high they will be trained less.
If called with no positional arguments, this method returns the current
candidate change fraction. If called with a positional argument, it will be
coerced to a [Num] and set as the new fraction.
The default cascade candidate change fraction is 0.01, which is equivalent to a
1% change in MSE.
### cascade-candidate-stagnation-epochs
``` raku
# fann_get_cascade_candidate_stagnation_epochs
multi method cascade-candidate-stagnation-epochs returns Num
# fann_set_cascade_candidate_stagnation_epochs
multi method cascade-candidate-stagnation-epochs ( Num() $value ) returns self
```
The number of cascade candidate stagnation epochs determines the number of
epochs training is allowed to continue without changing the MSE by a fraction
of [cascade-candidate-change-fraction](#cascade-candidate-change-fraction).
If called with no positional arguments, this method returns the current
candidate stagnation epochs. If called with a positional argument, it will be
coerced to a [Num] and set as the new candidate stagnation epochs.
The default number of cascade candidate stagnation epochs is 12.
### cascade-output-stagnation-epochs
``` raku
# fann_get_cascade_output_stagnation_epochs
multi method cascade-output-stagnation-epochs returns Num
# fann_set_cascade_output_stagnation_epochs
multi method cascade-output-stagnation-epochs ( Num() $value ) returns self
```
The number of cascade output stagnation epochs determines the number of epochs
training is allowed to continue without changing the MSE by a fraction of
[cascade-output-change-fraction](#cascade-output-change-fraction).
If called with no positional arguments, this method returns the current
output stagnation epochs. If called with a positional argument, it will be
coerced to a [Num] and set as the new output stagnation epochs.
The default number of cascade output stagnation epochs is 12.
### cascade-activation-steepnesses-count
``` raku
# fann_get_cascade_activation_steepnesses_count
multi method cascade-activation_steepnesses_count returns Int
```
Returns the number of activation steepnesses in the list returned by
[cascade-activation-functions](#cascade-activation-functions).
The default number of activation steepnesses is 4.
### cascade-candidate-epochs
``` raku
# fann_get_cascade_min_cand_epochs
# fann_get_cascade_max_cand_epochs
multi method cascade-candidate-epochs returns Range
# fann_set_cascade_min_cand_epochs
# fann_set_cascade_max_cand_epochs
multi method cascade-candidate-epochs (
Range $value where { not .infinite },
) returns self
multi method cascade-candidate-epochs (
Int :$min,
Int :$max,
) returns self
```
The candidate epochs determines the minimum and maximum number of epochs the
input connections to the candidates may be trained before adding a new
candidate neuron.
If called with no positional arguments, this method returns the current
candidate epoch range. If called with a [Range] as a positional argument, it will
be set as the new candidate epoch range. This method can also be called with
a value for the minimum or maximum end of the range as the `:min` and `:max`
named parameters respectively.
The default candidate epoch range is 50..150
### cascade-output-epochs
``` raku
# fann_get_cascade_min_out_epochs
# fann_get_cascade_max_out_epochs
multi method cascade-output-epochs returns Range
# fann_set_cascade_min_out_epochs
# fann_set_cascade_max_out_epochs
multi method cascade-output-epochs (
Range $value where { not .infinite },
) returns self
multi method cascade-output-epochs (
Int :$min,
Int :$max,
) returns self
```
The output epochs determines the minimum and maximum number of epochs the
output connections may be trained after adding a new candidate neuron.
If called with no positional arguments, this method returns the current
output epoch range. If called with a [Range] as a positional argument, it will
be set as the new output epoch range. This method can also be called with
a value for the minimum or maximum end of the range as the `:min` and `:max`
named parameters respectively.
The default output epoch range is 50..150
### cascade-activation-steepnesses
``` raku
# fann_get_cascade_activation_steepnesses
multi method cascade-activation-steepnesses returns List
# fann_set_cascade_activation_steepnesses
multi method cascade-activation-steepnesses (
CArray[num32] $steepnesses,
) returns self
multi method cascade-activation-steepnesses (
*@steepnesses,
) returns self
```
If called with no positional arguments, this method returns the array of
activation steepnesses used by the candidates. See
[cascade-num-candidates](#cascade-num-candidates) for a description of which
candidate neurons will be generated by this array.
If called with a [CArray[num32]][CArray] object as the first positional
argument, this method will instead use that as the new value. Alternatively,
the values that would be in that array can be passed as positional arguments
and they'll be internally converted to a C representation to use instead.
In either case, the new array must be just as long as defined by the count
(see [cascade-activation-steepnesses-count](#cascade-activation-steepnesses-count)).
The default activation steepnesses are [ 0.25, 0.50, 0.75, 1.00 ].
### cascade-activation-functions
``` raku
# fann_get_cascade_activation_functions
multi method cascade-activation-functions returns List
# fann_set_cascade_activation_functions
multi method cascade-activation-functions (
CArray[num32] $functions,
) returns self
multi method cascade-activation-functions (
*@functions,
) returns self
```
If called with no positional arguments, this method returns the array of
activation functions used by the candidates. See
[cascade-num-candidates](#cascade-num-candidates) for a description of which
candidate neurons will be generated by this array.
If called with a [CArray[num32]][CArray] object as the first positional
argument, this method will instead use that as the new value. Alternatively,
the values that would be in that array can be passed as positional arguments
and they'll be internally converted to a C representation to use instead.
In either case, the new array must be just as long as defined by the count
(see [cascade-activation-functions-count](#cascade-activation-functions-count)).
The default activation functions are [ `FANN_SIGMOID`,
`FANN_SIGMOID_SYMMETRIC`, `FANN_GAUSSIAN`, `FANN_GAUSSIAN_SYMMETRIC`,
`FANN_ELLIOT`, `FANN_ELLIOT_SYMMETRIC`, `FANN_SIN_SYMMETRIC`,
`FANN_COS_SYMMETRIC`, `FANN_SIN`, `FANN_COS` ].
# EXPORT TAGS
AI::FANN exports nothing by default. However, the following enums are
available and can be exported using the `:enum` tag to export *all* enums, or
the `:error` tag to export only the [AI::FANN::Error](#aifannerror) enum.
## AI::FANN::NetType
* FANN_NETTYPE_LAYER
* FANN_NETTYPE_SHORTCUT
## AI::FANN::ActivationFunc
The activation functions used for the neurons during training. The activation
functions can either be defined for a group of neurons by calling
[activation-function](#activation-function) with the `:hidden` or `:output`
parameters or it can be defined for a single neuron or layer with the `:layer`
and `:neuron` parameters.
The functions are described with functions where
* `x` is the input to the activation function
* `y` is the output
* `s` is the steepness
* `d` is the derivation.
The steepness of an activation function is defined in the same way by calling
[activation-steepness](#activation-steepness).
See the documentation for those functions for details.
* FANN_LINEAR
Linear activation function.
-∞ < y < ∞
y = x⋅s
d = s
* FANN_THRESHOLD
Threshold activation function. Cannot be used during training.
y = 0 if x < 0
y = 1 if x ≥ 0
* FANN_THRESHOLD_SYMMETRIC
Symmetric threshold activation function. Cannot be used during training.
y = -1 if x < 0
y = 1 if x ≥ 0
* FANN_SIGMOID
Sigmoid activation function. This function is very commonly used.
0 < y < 1
y = 1 / ( 1 + exp( -2⋅s⋅x ) ) - 1
d = 2⋅s⋅y⋅( 1 - y² )
* FANN_SIGMOID_STEPWISE
Stepwise linear approximation to sigmoid. Faster than sigmoid, but a
little less precise.
* FANN_SIGMOID_SYMMETRIC
Symmetric sigmoid activation function, also known as "tanh". This function
is very commonly used.
-1 < y < 1
y = tanh(s⋅x) = 2 / ( 1 + exp( -2⋅s⋅x ) ) - 1
d = s⋅( 1 - y² )
* FANN_SIGMOID_SYMMETRIC_STEPWISE
Stepwise linear approximation to symmetric sigmoid. Faster than symmetric
sigmoid, but a little less precise.
* FANN_GAUSSIAN
Gaussian activation function.
0 < y < 1
y = 0 when x = -∞
y = 1 when x = 0
y = 0 when x = ∞
y = exp( -x⋅s⋅x⋅s )
d = -2⋅x⋅s⋅y⋅s
* FANN_GAUSSIAN_SYMMETRIC
Symmetric Gaussian activation function.
-1 < y < 1
y = -1 when x = -∞
y = 1 when x = 0
y = -1 when x = ∞
y = exp( -x⋅s⋅x⋅s )⋅2 - 1
d = -2⋅x⋅s⋅y⋅s
* FANN_GAUSSIAN_STEPWISE
Not yet implemented.
* FANN_ELLIOT
Fast (sigmoid like) activation function defined by David Elliott.
0 < y < 1
y = x⋅s / 2 / ( 1 + |x⋅s| ) + 0.5
d = s / ( 2 ⋅ ( 1 + |x⋅s| )² )
* FANN_ELLIOT_SYMMETRIC
Fast (symmetric sigmoid like) activation function defined by David Elliott.
-1 < y < 1
y = x⋅s / ( 1 + |x⋅s| )
d = s / ( 1 + |x⋅s| )²
* FANN_LINEAR_PIECE
Bounded linear activation function.
0 ≤ y ≤ 1
y = x⋅s
d = s
* FANN_LINEAR_PIECE_SYMMETRIC
Bounded linear activation function.
-1 ≤ y ≤ 1
y = x⋅s
d = s
* FANN_SIN_SYMMETRIC
Periodical sinus activation function.
-1 ≤ y ≤ 1
y = sin( x⋅s )
d = s⋅cos( x⋅s )
* FANN_COS_SYMMETRIC
Periodical cosinus activation function.
-1 ≤ y ≤ 1
y = cos( x⋅s )
d = s⋅-sin( x⋅s )
* FANN_SIN
Periodical sinus activation function.
0 ≤ y ≤ 1
y = sin( x⋅s ) / 2 + 0.5
d = s⋅cos( x⋅s ) / 2
* FANN_COS
Periodical cosinus activation function.
0 ≤ y ≤ 1
y = cos( x⋅s ) / 2 + 0.5
d = s⋅-sin( x⋅s ) / 2
## AI::FANN::Train
The training algorithms used when training on AI::FANN::TrainData with
functions like [train](#train) with the `:path` or `:data` arguments. The
incremental training alters the weights after each time it is presented an
input pattern, while batch only alters the weights once after it has been
presented to all the patterns.
* FANN_TRAIN_INCREMENTAL
Standard backpropagation algorithm, where the weights are updated after
each training pattern. This means that the weights are updated many
times during a single epoch. For this reason some problems will train very
fast with this algorithm, while other more advanced problems will not
train very well.
* FANN_TRAIN_BATCH
Standard backpropagation algorithm, where the weights are updated after
calculating the mean square error for the whole training set. This means
that the weights are only updated once during an epoch. For this reason
some problems will train slower with this algorithm. But since the mean
square error is calculated more correctly than in incremental training,
some problems will reach better solutions with this algorithm.
* FANN_TRAIN_RPROP
A more advanced batch training algorithm which achieves good results for
many problems. The RPROP training algorithm is adaptive, and does
therefore not use the value set with [learning-rate](#learning-rate).
Some other parameters can however be set to change the way the RPROP
algorithm works, but it is only recommended for users with insight in how
the RPROP training algorithm works. The RPROP training algorithm is
described by [Riedmiller and Braun (1993)](#references), but the actual
learning algorithm used here is the iRPROP- training algorithm which is
described by [Igel and Hüsken (2000)](#references) which is a variant of
the standard RPROP training algorithm.
* FANN_TRAIN_QUICKPROP
A more advanced batch training algorithm which achieves good results
for many problems. The quickprop training algorithm uses the
[learning-rate](#learning-rate) parameter along with other more
advanced parameters, but it is only recommended to change these advanced
parameters, for users with insight in how the quickprop training
algorithm works. The quickprop training algorithm is described by
[Fahlman (1988)](#references).
* FANN_TRAIN_SARPROP
This is the same algorithm described in
[Nicholas and Tamas (1998)](#references).
## AI::FANN::ErrorFunc
Error function used during training.
* FANN_ERRORFUNC_LINEAR
Standard linear error function.
* FANN_ERRORFUNC_TANH
Tanh error function, usually better but can require a lower learning
rate. This error function aggressively targets outputs that differ much
from the desired, while not targeting outputs that only differ a little
that much. This activation function is not recommended for cascade
training and incremental training.
## AI::FANN::StopFunc
Stop criteria used during training.
* FANN_STOPFUNC_MSE
Stop criterion is Mean Square Error (MSE) value.
* FANN_STOPFUNC_BIT
Stop criterion is number of bits that fail. The number of bits means 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.
## AI::FANN::Error
Used to define error events on AI::FANN and AI::FANN::TrainData objects.
* FANN_E_NO_ERROR
No error.
* FANN_E_CANT_OPEN_CONFIG_R
Unable to open configuration file for reading.
* FANN_E_CANT_OPEN_CONFIG_W
Unable to open configuration file for writing.
* FANN_E_WRONG_CONFIG_VERSION
Wrong version of configuration file.
* FANN_E_CANT_READ_CONFIG
Error reading info from configuration file.
* FANN_E_CANT_READ_NEURON
Error reading neuron info from configuration file.
* FANN_E_CANT_READ_CONNECTIONS
Error reading connections from configuration file.
* FANN_E_WRONG_NUM_CONNECTIONS
Number of connections not equal to the number expected.
* FANN_E_CANT_OPEN_TD_W
Unable to open train data file for writing.
* FANN_E_CANT_OPEN_TD_R
Unable to open train data file for reading.
* FANN_E_CANT_READ_TD
Error reading training data from file.
* FANN_E_CANT_ALLOCATE_MEM
Unable to allocate memory.
* FANN_E_CANT_TRAIN_ACTIVATION
Unable to train with the selected activation function.
* FANN_E_CANT_USE_ACTIVATION
Unable to use the selected activation function.
* FANN_E_TRAIN_DATA_MISMATCH
Irreconcilable differences between two AI::FANN::TrainData objects.
* FANN_E_CANT_USE_TRAIN_ALG
Unable to use the selected training algorithm.
* FANN_E_TRAIN_DATA_SUBSET
Trying to take subset which is not within the training set.
* FANN_E_INDEX_OUT_OF_BOUND
Index is out of bound.
* FANN_E_SCALE_NOT_PRESENT
Scaling parameters not present.
* FANN_E_INPUT_NO_MATCH
The number of input neurons in the ANN and data don’t match.
* FANN_E_OUTPUT_NO_MATCH
The number of output neurons in the ANN and data don’t match.
# REFERENCES
* Fahlman, S.E. (1988). "Faster-Learning Variations on Back-Propagation: An
Empirical Study" in I<Proceedings of the 1988 Connectionist Models Summer
School>, Morgan Kaufmann.
* Igel, C., Hüsken, M. (2000) "Improving the Rprop Learning Algorithm" in
_Proceedings of the Second International ICSC Symposium on Neural
Computation (NC 2000)_, pp. 115—121. ICSC Academic Press.
* Nicholas, K.T., Tamas, D.G. (1998) "Simulated Annealing and Weight Decay in
Adaptive Learning: The SARPROP Algorithm". IEEE Transactions on Neural
Networks 9(4), pp. 662—668
* Riedmiller, M., Braun, H. (1993). "A Direct Adaptive Method for Faster
Backpropagation Leaning: the RPROP Algorithm" in _IEEE International
Conference on Neural Networks_, pp. 586—591, IEEE.
# COPYRIGHT AND LICENSE
Copyright 2021 José Joaquín Atria
This library is free software; you can redistribute it and/or modify it under
the Artistic License 2.0.
[Array]: https://docs.raku.org/type/Array
[CArray]: https://docs.raku.org/language/nativecall#Arrays
[Callable]: https://docs.raku.org/type/Callable
[False]: https://docs.raku.org/type/Bool
[IO::Path]: https://docs.raku.org/type/IO::Path
[Int]: https://docs.raku.org/type/Int
[List]: https://docs.raku.org/type/List
[Num]: https://docs.raku.org/type/Num
[Range]: https://docs.raku.org/type/Range
[SARPROP]: http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.47.8197&rep=rep1&type=pdf
[True]: https://docs.raku.org/type/Bool
|
### ----------------------------------------------------
### -- AI::FANN
### -- Licenses: Artistic-2.0
### -- Authors: Jonathan Scott Duff <[email protected]>, José Joaquín Atria <[email protected]>
### -- File: dist.ini
### ----------------------------------------------------
name = AI-FANN
[ReadmeFromPod]
enable = false
[RegenerateMeta]
enable = false
[PruneFiles]
match = ^ 'xt/'
match = ^ '.git'
match = ^ 'dist.ini' $
[UploadToZef]
|
### ----------------------------------------------------
### -- AI::FANN
### -- Licenses: Artistic-2.0
### -- Authors: Jonathan Scott Duff <[email protected]>, José Joaquín Atria <[email protected]>
### -- File: t/imports.t
### ----------------------------------------------------
#!/usr/bin/env raku
use Test;
is-deeply do {
my @before = MY::.keys;
my @after = do { use AI::FANN; MY::.keys };
@after (-) @before;
}, < AI >.Set, 'Plain use only modifies AI namespace';
is-deeply do {
my @before = MY::.keys;
my @after = do { use AI::FANN::Raw; MY::.keys };
@after (-) @before;
}, «
&fann_cascadetrain_on_data
&fann_cascadetrain_on_file
&fann_clear_scaling_params
&fann_copy
&fann_create_from_file
&fann_create_shortcut
&fann_create_shortcut_array
&fann_create_sparse
&fann_create_sparse_array
&fann_create_standard
&fann_create_standard_array
&fann_create_train
&fann_create_train_from_callback
&fann_descale_input
&fann_descale_output
&fann_descale_train
&fann_destroy
&fann_destroy_train
&fann_duplicate_train_data
&fann_get_MSE
&fann_get_activation_function
&fann_get_activation_steepness
&fann_get_bias_array
&fann_get_bit_fail
&fann_get_bit_fail_limit
&fann_get_cascade_activation_functions
&fann_get_cascade_activation_functions_count
&fann_get_cascade_activation_steepnesses
&fann_get_cascade_activation_steepnesses_count
&fann_get_cascade_candidate_change_fraction
&fann_get_cascade_candidate_limit
&fann_get_cascade_candidate_stagnation_epochs
&fann_get_cascade_max_cand_epochs
&fann_get_cascade_max_out_epochs
&fann_get_cascade_min_cand_epochs
&fann_get_cascade_min_out_epochs
&fann_get_cascade_num_candidate_groups
&fann_get_cascade_num_candidates
&fann_get_cascade_output_change_fraction
&fann_get_cascade_output_stagnation_epochs
&fann_get_cascade_weight_multiplier
&fann_get_connection_array
&fann_get_connection_rate
&fann_get_errno
&fann_get_errstr
&fann_get_layer_array
&fann_get_learning_momentum
&fann_get_learning_rate
&fann_get_network_type
&fann_get_num_input
&fann_get_num_layers
&fann_get_num_output
&fann_get_quickprop_decay
&fann_get_quickprop_mu
&fann_get_rprop_decrease_factor
&fann_get_rprop_delta_max
&fann_get_rprop_delta_min
&fann_get_rprop_delta_zero
&fann_get_rprop_increase_factor
&fann_get_sarprop_step_error_shift
&fann_get_sarprop_step_error_threshold_factor
&fann_get_sarprop_temperature
&fann_get_sarprop_weight_decay_shift
&fann_get_total_connections
&fann_get_total_neurons
&fann_get_train_error_function
&fann_get_train_stop_function
&fann_get_training_algorithm
&fann_get_user_data
&fann_init_weights
&fann_length_train_data
&fann_merge_train_data
&fann_num_input_train_data
&fann_num_output_train_data
&fann_print_connections
&fann_print_error
&fann_print_parameters
&fann_randomize_weights
&fann_read_train_from_file
&fann_reset_MSE
&fann_reset_errno
&fann_reset_errstr
&fann_run
&fann_save
&fann_save_train
&fann_save_train_to_fixed
&fann_scale_input
&fann_scale_input_train_data
&fann_scale_output
&fann_scale_output_train_data
&fann_scale_train
&fann_scale_train_data
&fann_set_activation_function
&fann_set_activation_function_hidden
&fann_set_activation_function_layer
&fann_set_activation_function_output
&fann_set_activation_steepness
&fann_set_activation_steepness_hidden
&fann_set_activation_steepness_layer
&fann_set_activation_steepness_output
&fann_set_bit_fail_limit
&fann_set_callback
&fann_set_cascade_activation_functions
&fann_set_cascade_activation_steepnesses
&fann_set_cascade_candidate_change_fraction
&fann_set_cascade_candidate_limit
&fann_set_cascade_candidate_stagnation_epochs
&fann_set_cascade_max_cand_epochs
&fann_set_cascade_max_out_epochs
&fann_set_cascade_min_cand_epochs
&fann_set_cascade_min_out_epochs
&fann_set_cascade_num_candidate_groups
&fann_set_cascade_output_change_fraction
&fann_set_cascade_output_stagnation_epochs
&fann_set_cascade_weight_multiplier
&fann_set_error_log
&fann_set_input_scaling_params
&fann_set_learning_momentum
&fann_set_learning_rate
&fann_set_output_scaling_params
&fann_set_quickprop_decay
&fann_set_quickprop_mu
&fann_set_rprop_decrease_factor
&fann_set_rprop_delta_max
&fann_set_rprop_delta_min
&fann_set_rprop_delta_zero
&fann_set_rprop_increase_factor
&fann_set_sarprop_step_error_shift
&fann_set_sarprop_step_error_threshold_factor
&fann_set_sarprop_temperature
&fann_set_sarprop_weight_decay_shift
&fann_set_scaling_params
&fann_set_train_error_function
&fann_set_train_stop_function
&fann_set_training_algorithm
&fann_set_user_data
&fann_set_weight
&fann_set_weight_array
&fann_shuffle_train_data
&fann_subset_train_data
&fann_test
&fann_test_data
&fann_train
&fann_train_epoch
&fann_train_on_data
&fann_train_on_file
fann
fann_activationfunc_enum
fann_connection
fann_errno_enum
fann_error
fann_errorfunc_enum
fann_nettype_enum
fann_stopfunc_enum
fann_train_data
fann_train_enum
fann_type
float
».Set, 'Raw exports';
my %imports = (
enum => <
FANN_COS_SYMMETRIC
FANN_ELLIOT
FANN_ELLIOT_SYMMETRIC
FANN_ERRORFUNC_LINEAR
FANN_ERRORFUNC_TANH
FANN_E_CANT_ALLOCATE_MEM
FANN_E_CANT_OPEN_CONFIG_R
FANN_E_CANT_OPEN_CONFIG_W
FANN_E_CANT_OPEN_TD_R
FANN_E_CANT_OPEN_TD_W
FANN_E_CANT_READ_CONFIG
FANN_E_CANT_READ_CONNECTIONS
FANN_E_CANT_READ_NEURON
FANN_E_CANT_READ_TD
FANN_E_CANT_TRAIN_ACTIVATION
FANN_E_CANT_USE_ACTIVATION
FANN_E_CANT_USE_TRAIN_ALG
FANN_E_INDEX_OUT_OF_BOUND
FANN_E_INPUT_NO_MATCH
FANN_E_NO_ERROR
FANN_E_OUTPUT_NO_MATCH
FANN_E_SCALE_NOT_PRESENT
FANN_E_TRAIN_DATA_MISMATCH
FANN_E_TRAIN_DATA_SUBSET
FANN_E_WRONG_CONFIG_VERSION
FANN_E_WRONG_NUM_CONNECTIONS
FANN_GAUSSIAN
FANN_GAUSSIAN_STEPWISE
FANN_GAUSSIAN_SYMMETRIC
FANN_LINEAR
FANN_LINEAR_PIECE
FANN_LINEAR_PIECE_SYMMETRIC
FANN_NETTYPE_LAYER
FANN_NETTYPE_SHORTCUT
FANN_SIGMOID
FANN_SIGMOID_STEPWISE
FANN_SIGMOID_SYMMETRIC
FANN_SIGMOID_SYMMETRIC_STEPWISE
FANN_SIN FANN_COS
FANN_SIN_SYMMETRIC
FANN_STOPFUNC_BIT
FANN_STOPFUNC_MSE
FANN_THRESHOLD
FANN_THRESHOLD_SYMMETRIC
FANN_TRAIN_BATCH
FANN_TRAIN_INCREMENTAL
FANN_TRAIN_QUICKPROP
FANN_TRAIN_RPROP
FANN_TRAIN_SARPROP
>,
error => <
FANN_E_CANT_ALLOCATE_MEM
FANN_E_CANT_OPEN_CONFIG_R
FANN_E_CANT_OPEN_CONFIG_W
FANN_E_CANT_OPEN_TD_R
FANN_E_CANT_OPEN_TD_W
FANN_E_CANT_READ_CONFIG
FANN_E_CANT_READ_CONNECTIONS
FANN_E_CANT_READ_NEURON
FANN_E_CANT_READ_TD
FANN_E_CANT_TRAIN_ACTIVATION
FANN_E_CANT_USE_ACTIVATION
FANN_E_CANT_USE_TRAIN_ALG
FANN_E_INDEX_OUT_OF_BOUND
FANN_E_INPUT_NO_MATCH
FANN_E_NO_ERROR
FANN_E_OUTPUT_NO_MATCH
FANN_E_SCALE_NOT_PRESENT
FANN_E_TRAIN_DATA_MISMATCH
FANN_E_TRAIN_DATA_SUBSET
FANN_E_WRONG_CONFIG_VERSION
FANN_E_WRONG_NUM_CONNECTIONS
>,
);
for %imports.kv -> $tag, $expected {
is-deeply do { EVAL "use AI::FANN :{ $tag }; MY::.keys.grep(/ 'FANN_' /).Set" },
$expected.Set, "Importing :{ $tag } imports correct names";
}
done-testing;
|
### ----------------------------------------------------
### -- AI::FANN
### -- Licenses: Artistic-2.0
### -- Authors: Jonathan Scott Duff <[email protected]>, José Joaquín Atria <[email protected]>
### -- File: t/errors.t
### ----------------------------------------------------
#!/usr/bin/env raku
use Test;
use AI::FANN :error;
my $ann = AI::FANN.new: layers => [ 2, 3, 1 ];
END $ann.destroy;
subtest 'new' => sub {
throws-like { AI::FANN.new: path => 'missing' },
X::AdHoc, message => "Cannot read from file: 'missing'";
}
subtest 'save' => sub {
throws-like {
AI::FANN.new( layers => [ 1, 1 ] ).save:
$*HOME.parent.child('forbidden') # Hopefully...
}, X::AI::FANN, code => FANN_E_CANT_OPEN_CONFIG_W;
}
subtest 'activation-function' => sub {
throws-like { $ann.activation-function: layer => -1, neuron => 1 },
X::OutOfRange, what => 'Layer index', range => '1 2';
throws-like { $ann.activation-function: layer => 0, neuron => 1 },
X::OutOfRange, what => 'Layer index', range => '1 2';
throws-like { $ann.activation-function: layer => 4, neuron => 1 },
X::OutOfRange, what => 'Layer index', range => '1 2';
throws-like { $ann.activation-function: layer => 1, neuron => 4 },
X::OutOfRange, what => 'Neuron index', range => '0 1 2 3';
throws-like { $ann.activation-function: layer => 1, neuron => -1 },
X::OutOfRange, what => 'Neuron index', range => '0 1 2 3';
throws-like { $ann.activation-function: 42, :hidden },
X::AdHoc, message => 'Invalid activation function: must be a value in AI::FANN::ActivationFunc';
lives-ok { $ann.activation-function: 5, :hidden },
'Accepts plain numeric values';
}
subtest 'activation-steepness' => sub {
throws-like { $ann.activation-steepness: layer => -1, neuron => 1 },
X::OutOfRange, what => 'Layer index', range => '1 2';
throws-like { $ann.activation-steepness: layer => 0, neuron => 1 },
X::OutOfRange, what => 'Layer index', range => '1 2';
throws-like { $ann.activation-steepness: layer => 4, neuron => 1 },
X::OutOfRange, what => 'Layer index', range => '1 2';
throws-like { $ann.activation-steepness: layer => 1, neuron => 4 },
X::OutOfRange, what => 'Neuron index', range => '0 1 2 3';
throws-like { $ann.activation-steepness: layer => 1, neuron => -1 },
X::OutOfRange, what => 'Neuron index', range => '0 1 2 3';
lives-ok { $ann.activation-steepness: 5, :hidden },
'Accepts plain numeric values';
}
subtest 'training-algorithm' => {
throws-like { $ann.training-algorithm: 42 },
X::AdHoc, message => 'Invalid training algorithm: must be a value in AI::FANN::Train';
}
subtest 'train-error-function' => {
throws-like { $ann.train-error-function: 42 },
X::AdHoc, message => 'Invalid error function: must be a value in AI::FANN::ErrorFunc';
}
subtest 'train-stop-function' => {
throws-like { $ann.train-stop-function: 42 },
X::AdHoc, message => 'Invalid stop function: must be a value in AI::FANN::StopFunc';
}
subtest 'train' => {
throws-like {
$ann.train: 'missing',
max-epochs => 1,
epochs-between-reports => 1,
desired-error => 1;
}, X::AdHoc, message => "Cannot read from file: 'missing'";
}
subtest 'cascade-train' => {
throws-like {
$ann.cascade-train: 'missing',
max-neurons => 1,
neurons-between-reports => 1,
desired-error => 1;
}, X::AdHoc, message => "Cannot read from file: 'missing'";
}
subtest 'test' => {
throws-like { $ann.test: 'missing' },
X::AdHoc, message => "Cannot read from file: 'missing'";
}
done-testing;
|
### ----------------------------------------------------
### -- AI::FANN
### -- Licenses: Artistic-2.0
### -- Authors: Jonathan Scott Duff <[email protected]>, José Joaquín Atria <[email protected]>
### -- File: t/train-data.t
### ----------------------------------------------------
#!/usr/bin/env raku
use Test;
use AI::FANN :error;
subtest 'Create ' => {
ok $_ = AI::FANN::TrainData.new(
pairs => [
[ 0, 0 ] => [ 0 ],
[ 0, 255 ] => [ 255 ],
[ 255, 0 ] => [ 255 ],
[ 255, 255 ] => [ 0 ],
],
), 'Create from pairs';
LEAVE .?destroy;
is .num-input, 2, 'Num input';
is .num-output, 1, 'Num output';
is .num-data, 4, 'Num data';
is .input[2][0,1], [ 255, 0 ], 'Can set input data';
is .output[0,1]».[0], [ 0, 255 ], 'Can set output data';
is .scale( -1..1, :input ), $_, 'Scale returns self';
is .input[2][0,1]».round, [ 1, -1 ], 'Can scale input data';
is .output[0,1]».[0]».round, [ 0, 255 ], 'Output is unchanged';
is .scale( -10..10, :output ), $_, 'Scale returns self';
is .input[2][0,1]».round, [ 1, -1 ], 'Input is unchanged';
is .output[0,1]».[0]».round, [ -10, 10 ], 'Can scale output data';
is .scale( ^256 ), $_, 'Scale returns self';
is .input[2][0,1]».round, [ 255, 0 ], 'Can scale input data';
is .output[0,1]».[0]».round, [ 0, 255 ], 'Can scale output data';
is .shuffle, $_, 'Shuffle returns self';
}
subtest 'Create from pairs' => {
ok $_ = AI::FANN::TrainData.new(
pairs => [
[ -1, -1 ] => [ -1 ],
[ -1, 1 ] => [ 1 ],
[ 1, -1 ] => [ 1 ],
[ 1, 1 ] => [ -1 ],
],
), 'Create from pairs';
LEAVE .?destroy;
is .num-input, 2, 'Num input';
is .num-output, 1, 'Num output';
is .num-data, 4, 'Num data';
subtest ':pairs must be Pairs' => {
throws-like
{ AI::FANN::TrainData.new: pairs => [ 0, 1 ] },
X::AdHoc, message => 'Values in :pairs must be Pair objects';
}
subtest 'Inputs must be consistent' => {
throws-like
{ AI::FANN::TrainData.new: pairs => [ [ 0, 1 ] => 1, 1 => 2 ] },
X::AdHoc, message => 'Number of inputs must be consistent';
}
subtest 'Outputs must be consistent' => {
throws-like
{ AI::FANN::TrainData.new: pairs => [ 1 => [1], 1 => [1, 2] ] },
X::AdHoc, message => 'Number of outputs must be consistent';
}
subtest 'Inputs must not be empty' => {
throws-like
{ AI::FANN::TrainData.new: pairs => [ [] => [1] ] },
X::AdHoc, message => 'Data must have at least one input';
}
subtest 'Outputs must not be empty' => {
throws-like
{ AI::FANN::TrainData.new: pairs => [ [1] => [] ] },
X::AdHoc, message => 'Data must have at least one output';
}
}
subtest 'Subset and merge' => {
my $a = AI::FANN::TrainData.new: pairs => [
[ -1, -1 ] => [ -1 ],
[ -1, 1 ] => [ 1 ],
[ 1, -1 ] => [ 1 ],
[ 1, 1 ] => [ -1 ],
];
LEAVE $a.?destroy;
is $a.num-data, 4, 'Original data length';
my $b = $a.subset: 0, 1;
is $b.num-data, 1, 'Can subset from start';
LEAVE $b.?destroy;
my $c = $a.subset: 1, 3;
is $c.num-data, 3, 'Can subset from middle';
LEAVE $c.?destroy;
given AI::FANN::TrainData.new: data => [ $b, $c ] {
is .num-data, 4, 'Can combine subsets';
.?destroy;
}
given $a.clone {
is .num-data, 4, 'Can clone data set';
.?destroy;
}
subtest 'Input data must match when merging' => {
my $a = AI::FANN::TrainData.new: pairs => [ [1 ] => [1] ];
my $b = AI::FANN::TrainData.new: pairs => [ [1, 1] => [1] ];
throws-like { AI::FANN::TrainData.new: data => [ $a, $b ] },
X::AI::FANN, code => FANN_E_TRAIN_DATA_MISMATCH;
}
subtest 'Output data must match when merging' => {
my $a = AI::FANN::TrainData.new: pairs => [ [1 ] => [1] ];
my $b = AI::FANN::TrainData.new: pairs => [ [1] => [1, 1] ];
throws-like { AI::FANN::TrainData.new: data => [ $a, $b ] },
X::AI::FANN, code => FANN_E_TRAIN_DATA_MISMATCH;
}
subtest 'Subset position must be positive' => {
throws-like { $a.subset: -1, 2 },
X::OutOfRange, what => 'Subset position', range => '0 1 2 3';
}
subtest 'Subset position must be within data' => {
throws-like { $a.subset: 4, 2 },
X::OutOfRange, what => 'Subset position', range => '0 1 2 3';
}
subtest 'Subset length depends on pos' => {
throws-like { $a.subset: 0, 5 },
X::OutOfRange, what => 'Subset length', range => '1 2 3 4';
throws-like { $a.subset: 2, 3 },
X::OutOfRange, what => 'Subset length', range => '1 2';
}
}
subtest 'File I/O' => {
use File::Temp;
ok my $src = AI::FANN::TrainData.new: pairs => [
[ 1, 2 ] => [ 2, 3, 4 ],
[ 1, 2 ] => [ 2, 3, 4 ],
];
LEAVE $src.?destroy;
my ( $path, $handle ) = tempfile;
is $src.save($path), $src, 'Can save with Str';
is $src.save($path.IO), $src, 'Can save with IO::Path';
given AI::FANN::TrainData.new: :$path {
ok .defined, 'Can read from Str';
is .num-input, $src.num-input, 'Read data is equivalent';
LEAVE .?destroy;
}
given AI::FANN::TrainData.new: path => $path.IO {
ok .defined, 'Can read from IO::Path';
LEAVE .?destroy;
}
subtest 'File must be writable to save' => {
throws-like { $src.save: $*HOME.parent.child('forbidden') },
X::AI::FANN, code => FANN_E_CANT_OPEN_TD_W;
}
subtest 'File must be readable to read' => {
my ($dir) = tempdir;
throws-like { AI::FANN::TrainData.new: path => $dir.IO.child('missing.net') },
X::AdHoc, message => /'Cannot read from file: '/;
}
}
done-testing;
|
### ----------------------------------------------------
### -- AI::FANN
### -- Licenses: Artistic-2.0
### -- Authors: Jonathan Scott Duff <[email protected]>, José Joaquín Atria <[email protected]>
### -- File: t/creation.t
### ----------------------------------------------------
#!/usr/bin/env raku
use Test;
use AI::FANN :enum;
# Input Hidden Output
# \ / | \ /
my @layers = 2, 3, 5, 3, 1;
sub test ( $o, $checks ) {
for $checks.kv -> $name, $want {
my $have = $o."$name"();
if $have ~~ Positional {
is-deeply $have, $want, $name;
}
else {
is $have, $want, $name;
}
}
}
todo 'Weight modification is flaky'; # FIXME
subtest 'Weights with connection' => {
my $nn = AI::FANN.new: layers => [ 1, 1 ];
LEAVE $nn.?destroy;
my @connections = $nn.connection-array;
for @connections.kv -> $i, $c {
$c.weight = $i.Num;
}
is $nn.weights(@connections), $nn, 'weights with list returns self';
is $nn.weights, ( 0e0, 1e0 ), 'Can set weights with connections';
@connections[0].weight = 42e0;
is $nn.weights(@connections[0]), $nn, 'weights with connection returns self';
is $nn.weights, ( 42e0, 1e0 ), 'Can set weights with connections';
is $nn.weights(
32,
from => @connections[0].from-neuron,
to => @connections[0].to-neuron,
).weights, ( 32e0, 1e0 ), 'Can set weights with values'
}
subtest 'Standard' => {
ok my $nn = AI::FANN.new( :@layers ), 'new';
LEAVE $nn.destroy;
$nn.&test: {
bias-array => @layers.List,
bit-fail => 0,
connection-rate => 1,
layer-array => @layers.List,
network-type => FANN_NETTYPE_LAYER,
num-input => @layers.head,
num-layers => @layers.elems,
num-output => @layers.tail,
total-connections => 51,
total-neurons => @layers.sum + @layers - 1,
};
is-deeply $nn.connection-array.map(*.^name),
[ 'AI::FANN::Connection' xx $nn.total-connections ].List,
'connection-array';
subtest 'activation-function' => {
my &get-hidden = { .activation-function: neuron => 0, layer => 1 };
my &get-output = { .activation-function: neuron => 0, layer => @layers.elems - 1 };
is $nn.&get-hidden, FANN_SIGMOID_STEPWISE, 'getter';
is $nn.activation-function( FANN_SIGMOID, :hidden ).&get-hidden, FANN_SIGMOID, 'hidden setter';
is $nn.activation-function( FANN_GAUSSIAN, :output ).&get-output, FANN_GAUSSIAN, 'output setter';
is $nn.activation-function( FANN_ELLIOT, layer => 1 ).&get-hidden, FANN_ELLIOT, 'layer setter';
ok $nn.activation-function( FANN_THRESHOLD, layer => 1, neuron => 0 );
is $nn.&get-hidden, FANN_THRESHOLD, 'setter';
is $nn.activation-function( neuron => 2, layer => 1 ),
FANN_ELLIOT, 'other neurons remain untouched';
}
subtest 'activation-steepness' => {
my &get-hidden = { .activation-steepness( :0neuron, :1layer ).round: 0.1 };
my &get-output = { .activation-steepness( :0neuron, layer => @layers.elems - 1 ).round: 0.1 };
is $nn.&get-hidden, 0.5, 'getter';
is $nn.activation-steepness( 0.3, :hidden ).&get-hidden, 0.3, 'hidden setter';
is $nn.activation-steepness( 0.7, :output ).&get-output, 0.7, 'output setter';
is $nn.activation-steepness( 0.2, :1layer ).&get-hidden, 0.2, 'layer setter';
ok $nn.activation-steepness( 0.1, layer => 1, neuron => 0 );
is $nn.&get-hidden, 0.1, 'setter';
is $nn.activation-steepness( :2neuron, :1layer ).round(0.1),
0.2, 'other neurons remain untouched';
}
subtest 'training-algorithm' => {
is $nn.training-algorithm, FANN_TRAIN_RPROP, 'getter';
is $nn.training-algorithm(FANN_TRAIN_INCREMENTAL)
.training-algorithm, FANN_TRAIN_INCREMENTAL, 'setter';
is $nn.training-algorithm(1)
.training-algorithm, FANN_TRAIN_BATCH, 'setter with Int';
}
subtest 'train-error-function' => {
is $nn.train-error-function, FANN_ERRORFUNC_TANH, 'getter';
is $nn.train-error-function(FANN_ERRORFUNC_LINEAR)
.train-error-function, FANN_ERRORFUNC_LINEAR, 'setter';
is $nn.train-error-function(0)
.train-error-function, FANN_ERRORFUNC_LINEAR, 'setter';
}
subtest 'train-stop-function' => {
is $nn.train-stop-function, FANN_STOPFUNC_MSE, 'getter';
is $nn.train-stop-function(FANN_STOPFUNC_BIT)
.train-stop-function, FANN_STOPFUNC_BIT, 'setter';
is $nn.train-stop-function(0)
.train-stop-function, FANN_STOPFUNC_MSE, 'setter';
}
subtest 'bit-fail-limit' => {
is $nn.bit-fail-limit.round(0.01), 0.35, 'getter';
is $nn.bit-fail-limit(1.5).bit-fail-limit, 1.5, 'setter';
}
subtest 'learning-rate' => {
is $nn.learning-rate.round(0.1), 0.7, 'getter';
is $nn.learning-rate(1).learning-rate, 1, 'setter';
}
subtest 'learning-momentum' => {
is $nn.learning-momentum, 0, 'getter';
is $nn.learning-momentum(1).learning-momentum, 1, 'setter';
}
given $nn.weights {
is .min.round(0.1), -0.1, 'Minimum weight ~-0.1';
is .max.round(0.1), 0.1, 'Maximum weight ~+0.1';
}
is $nn.randomise-weights(1..2), $nn, 'randomise-weights returns self';
is $nn.randomize-weights(1..2), $nn, 'randomize-weights returns self';
given $nn.weights {
is .min.round(1), 1, 'Scaled minimum weight';
is .max.round(1), 2, 'Scaled maximum weight';
}
given AI::FANN::TrainData.new: pairs => [ 0 => 1 ] {
is $nn.init-weights($_), $nn, 'init-weights returns self';
.?destroy;
}
with $nn.clone {
is .num-input, $nn.num-input, 'Can clone network';
.?destroy;
}
}
subtest 'Sparse' => {
my $connection-rate = 0.75;
ok $_ = AI::FANN.new( :@layers, :$connection-rate ), 'new';
LEAVE .?destroy;
.&test: {
bias-array => @layers.List,
bit-fail => 0,
connection-rate => $connection-rate,
layer-array => @layers.List,
network-type => FANN_NETTYPE_LAYER,
num-input => @layers.head,
num-layers => @layers.elems,
num-output => @layers.tail,
total-connections => 42,
total-neurons => @layers.sum + @layers - 1,
};
is-deeply .connection-array.map(*.^name),
[ 'AI::FANN::Connection' xx .total-connections ].List,
'connection-array';
}
subtest 'Shortcut' => {
ok $_ = AI::FANN.new( :@layers, :shortcut ), 'new';
LEAVE .?destroy;
.&test: {
bias-array => @layers.List,
bit-fail => 0,
connection-rate => 1,
layer-array => @layers.List,
network-type => FANN_NETTYPE_SHORTCUT,
num-input => @layers.head,
num-layers => @layers.elems,
num-output => @layers.tail,
total-connections => 86,
total-neurons => 15,
};
is-deeply .connection-array.map(*.^name),
[ 'AI::FANN::Connection' xx .total-connections ].List,
'connection-array';
}
subtest 'File I/O' => {
use File::Temp;
ok my $src = AI::FANN.new: layers => [ 2, 3, 1 ];
LEAVE $src.?destroy;
my ( $path, $handle ) = tempfile;
is $src.save($path), $src, 'Can save with Str';
is $src.save($path.IO), $src, 'Can save with IO::Path';
given AI::FANN.new: :$path {
ok .defined, 'Can read from Str';
is .num-input, $src.num-input, 'Read data is equivalent';
LEAVE .?destroy;
}
given AI::FANN.new: path => $path.IO {
ok .defined, 'Can read from IO::Path';
LEAVE .?destroy;
}
subtest 'File must be writable to save' => {
throws-like { $src.save: $*HOME.parent.child('forbidden') },
X::AI::FANN, code => FANN_E_CANT_OPEN_CONFIG_W;
}
subtest 'File must be readable to read' => {
my ($dir) = tempdir;
throws-like { AI::FANN::TrainData.new: path => $dir.IO.child('missing.net') },
X::AdHoc, message => /'Cannot read from file: '/;
}
}
done-testing;
|
### ----------------------------------------------------
### -- AI::FANN
### -- Licenses: Artistic-2.0
### -- Authors: Jonathan Scott Duff <[email protected]>, José Joaquín Atria <[email protected]>
### -- File: t/training.t
### ----------------------------------------------------
#!/usr/bin/env raku
use Test;
use AI::FANN :enum;
my $nn = AI::FANN.new: layers => [ 2, 3, 1 ];
LEAVE $nn.?destroy;
my $data = AI::FANN::TrainData.new: pairs => [
[ -1, -1 ] => [ -1 ],
[ -1, 1 ] => [ 1 ],
[ 1, -1 ] => [ 1 ],
[ 1, 1 ] => [ -1 ],
];
LEAVE $data.?destroy;
my @epochs;
my $callback = sub (
$fann,
$data,
Int $max-epochs,
Int $epochs-between-reports,
Num $desired-error,
Int $epoch,
--> Int
) {
@epochs.push: $epoch;
return $epoch >= 8 ?? -1 !! 1; # Stop at epoch 8
}
is $nn.callback($callback), $nn, 'callback returns self';
my $train = $nn.train: $data,
desired-error => 0.001,
max-epochs => 500_000,
epochs-between-reports => 2;
is $train, $nn, 'train returns self';
is @epochs, [ 1, 2, 4, 6, 8 ],
'Callback ran every 2 epochs and could be stopped';
is $nn.callback(:delete), $nn, 'Clearing a callback returns self';
throws-like { $nn.callback }, X::AdHoc, message => /'The callback method'/;
subtest 'Scaling' => {
my $bad = AI::FANN::TrainData.new: pairs => [ 1 => 0 ];
LEAVE $bad.?destroy;
my $input = 0..1;
my $output = -2..-1;
throws-like { $nn.scale: $data },
X::AI::FANN, code => FANN_E_SCALE_NOT_PRESENT,
'Scale needs scaling factor';
throws-like { $nn.descale: $data },
X::AI::FANN, code => FANN_E_SCALE_NOT_PRESENT,
'Descale needs scaling factor';
is $nn.scaling( $data, :$input, :$output ), $nn, 'Scaling returns self';
is $nn.scaling( $data, :$input ), $nn, 'Scaling with only input returns self';
is $nn.scaling( $data, :$output ), $nn, 'Scaling with only output returns self';
is $nn.scale($data), $nn, 'Scale returns self';
is $data.input[1][^$data.num-input], ( 0, 1 ), 'Scaled input data';
is $data.output[0,1]».[0], ( -2, -1 ), 'Scaled output data';
is $nn.descale($data), $nn, 'Descale returns self';
is $data.input[1][^$data.num-input], ( -1, 1 ), 'Descaled input data';
is $data.output[0,1]».[0], ( -1, 1 ), 'Descaled output data';
use NativeCall;
given CArray[num32].new: ( -1, 1 )».Num -> $input {
is $nn.scale(:$input), $nn, 'Scaling CArray input returns self';
is $input[0, 1], ( 0, 1 )».Num, 'Scaled CArray input';
is $nn.descale(:$input), $nn, 'Descaling CArray input returns self';
is $input[0, 1], ( -1, 1 )».Num, 'Descaled CArray input';
}
given CArray[num32].new: -1.Num -> $output {
is $nn.scale(:$output), $nn, 'Scaling CArray output returns self';
is $output[0], -2.Num, 'Scaled CArray output';
is $nn.descale(:$output), $nn, 'Descaling CArray output returns self';
is $output[0], -1.Num, 'Descaled CArray output';
}
given [ -1, 1 ] -> @input {
is $nn.scale(:@input), $nn, 'Scaling array input returns self';
is @input, ( 0, 1 ), 'Scaled array input';
is $nn.descale(:@input), $nn, 'Descaling array input returns self';
is @input, ( -1, 1 ), 'Descaled array input';
}
given [ -1 ] -> @output {
is $nn.scale(:@output), $nn, 'Scaling array output returns self';
is @output, ( -2 ), 'Scaled array output';
is $nn.descale(:@output), $nn, 'Descaling array output returns self';
is @output, ( -1 ), 'Descaled array output';
}
is $nn.scaling(:delete), $nn, 'Clearing scaling returns self';
throws-like { $nn.scaling( $bad, :$input, :$output ) },
X::AI::FANN, code => FANN_E_TRAIN_DATA_MISMATCH,
'Scaling needs matching dataset';
}
done-testing;
|
### ----------------------------------------------------
### -- AI::FANN
### -- Licenses: Artistic-2.0
### -- Authors: Jonathan Scott Duff <[email protected]>, José Joaquín Atria <[email protected]>
### -- File: lib/AI/FANN.rakumod
### ----------------------------------------------------
### -- Chunk 1 of 2
use AI::FANN::Raw;
package AI::FANN {
our enum NetType is export(:enum) «
FANN_NETTYPE_LAYER
FANN_NETTYPE_SHORTCUT
»;
our enum ActivationFunc is export(:enum) «
FANN_LINEAR
FANN_THRESHOLD
FANN_THRESHOLD_SYMMETRIC
FANN_SIGMOID
FANN_SIGMOID_STEPWISE
FANN_SIGMOID_SYMMETRIC
FANN_SIGMOID_SYMMETRIC_STEPWISE
FANN_GAUSSIAN
FANN_GAUSSIAN_SYMMETRIC
FANN_GAUSSIAN_STEPWISE
FANN_ELLIOT
FANN_ELLIOT_SYMMETRIC
FANN_LINEAR_PIECE
FANN_LINEAR_PIECE_SYMMETRIC
FANN_SIN_SYMMETRIC
FANN_COS_SYMMETRIC
FANN_SIN FANN_COS
»;
our enum Train is export(:enum) «
FANN_TRAIN_INCREMENTAL
FANN_TRAIN_BATCH
FANN_TRAIN_RPROP
FANN_TRAIN_QUICKPROP
FANN_TRAIN_SARPROP
»;
our enum ErrorFunc is export(:enum) «
FANN_ERRORFUNC_LINEAR
FANN_ERRORFUNC_TANH
»;
our enum StopFunc is export(:enum) «
FANN_STOPFUNC_MSE
FANN_STOPFUNC_BIT
»;
our enum Error is export(:enum, :error) «
FANN_E_NO_ERROR
FANN_E_CANT_OPEN_CONFIG_R
FANN_E_CANT_OPEN_CONFIG_W
FANN_E_WRONG_CONFIG_VERSION
FANN_E_CANT_READ_CONFIG
FANN_E_CANT_READ_NEURON
FANN_E_CANT_READ_CONNECTIONS
FANN_E_WRONG_NUM_CONNECTIONS
FANN_E_CANT_OPEN_TD_W
FANN_E_CANT_OPEN_TD_R
FANN_E_CANT_READ_TD
FANN_E_CANT_ALLOCATE_MEM
FANN_E_CANT_TRAIN_ACTIVATION
FANN_E_CANT_USE_ACTIVATION
FANN_E_TRAIN_DATA_MISMATCH
FANN_E_CANT_USE_TRAIN_ALG
FANN_E_TRAIN_DATA_SUBSET
FANN_E_INDEX_OUT_OF_BOUND
FANN_E_SCALE_NOT_PRESENT
FANN_E_INPUT_NO_MATCH
FANN_E_OUTPUT_NO_MATCH
»;
}
class X::AI::FANN is Exception {
has AI::FANN::Error $.code;
has Str $.message;
}
my subset MaybeError where * ~~ Nil | X::AI::FANN;
my sub error ( fann_error $e ) {
LEAVE {
fann_reset_errstr($e);
fann_reset_errno($e);
}
$e.errno == 0 ?? Nil !! X::AI::FANN.new(
code => AI::FANN::Error.^enum_from_value($e.errno),
message => $e.errstr.chomp.subst( /\.$/, '', :nth(*) ),
);
}
class AI::FANN {
use NativeCall;
# Disable printing error directly to STDERR
fann_set_error_log( fann_error, Pointer );
# See https://stackoverflow.com/a/43554058/807650
my role StructArray[Mu:U \T where .REPR eq 'CStruct'] does Positional[T] {
has $.bytes;
has $.elems;
method new(UInt \n) {
self.bless(bytes => buf8.allocate(n * nativesizeof T), elems => n);
}
method AT-POS(UInt \i where ^$!elems) {
nativecast(T, Pointer.new(nativecast(Pointer, $!bytes) + i * nativesizeof T));
}
method pointer {
nativecast(Pointer[T], $!bytes);
}
}
has fann $!fann;
has $!layers; # Used for error reporting
class Connection is repr('CStruct') {
has uint32 $.from-neuron;
has uint32 $.to-neuron;
has fann_type $.weight is rw;
}
class TrainData {
trusts AI::FANN;
has fann_train_data $!data
handles < num-data num-input num-output input output >;
method !data { $!data }
multi method BUILD (
Int :$num-data!,
Int :$num-input!,
Int :$num-output!,
:&callback
) {
$!data = &callback
?? fann_create_train_from_callback( $num-data, $num-input, $num-output, &callback )
!! fann_create_train( $num-data, $num-input, $num-output );
}
multi method BUILD ( IO() :$path! ) {
die "Cannot read from file: '$path'" unless $path.r;
$!data = fann_read_train_from_file( "$path" )
or die 'Unable to create train data';
}
multi method BUILD ( :@pairs! ) {
my ( $inputs, $outputs );
for @pairs.kv -> $i, $_ {
die 'Values in :pairs must be Pair objects' unless $_ ~~ Pair;
my @have = .key.List;
my @want = .value.List;
die 'Data must have at least one input' unless @have.elems;
die 'Data must have at least one output' unless @want.elems;
if $i == 0 {
$inputs = @have.elems;
$outputs = @want.elems;
$!data = fann_create_train(
@pairs.elems,
$inputs,
$outputs,
) or die 'Unable to create train data';
}
else {
die 'Number of inputs must be consistent' if $inputs != @have.elems;
die 'Number of outputs must be consistent' if $outputs != @want.elems;
}
$!data.input[ $i][ ^$inputs ] = |@have».Num;
$!data.output[$i][ ^$outputs ] = |@want».Num;
}
}
multi method BUILD ( :@data! where { .all ~~ TrainData:D } ) {
$!data = @data.reduce: -> $a, $b {
LEAVE $a!error.throw;
fann_merge_train_data(
$a!AI::FANN::TrainData::data,
$b!AI::FANN::TrainData::data,
);
}
}
multi method BUILD ( fann_train_data :$data! ) {
$!data = $data;
}
method !error ( --> MaybeError ) { $!data.error.&error }
method subset ( Int $pos, Int $length --> TrainData ) {
X::OutOfRange.new(
what => 'Subset position',
got => $pos,
range => ^$.num-data,
).throw if $pos !~~ ^$.num-data;
X::OutOfRange.new(
what => 'Subset length',
got => $length,
range => 1..( $.num-data - $pos ),
).throw if $length !~~ 1..( $.num-data - $pos );
self.new: data => fann_subset_train_data( $!data, $pos, $length );
}
method clone ( --> TrainData ) {
my $data = fann_duplicate_train_data($!data)
// die 'Unable to create train data';
self.new: :$data;
}
method scale (
Range:D $range,
Bool() :$input,
Bool() :$output,
) {
die 'Cannot use an infinite range to set scale' if $range.infinite;
if $input || $output {
fann_scale_input_train_data( $!data, |$range.minmax».Num ) if $input;
fann_scale_output_train_data( $!data, |$range.minmax».Num ) if $output;
}
else {
fann_scale_train_data( $!data, |$range.minmax».Num );
}
self;
}
method save ( IO() $path --> ::?CLASS:D ) {
LEAVE self!error.throw;
fann_save_train($!data, "$path");
self;
}
method shuffle ( --> ::?CLASS:D ) {
fann_shuffle_train_data($!data);
self;
}
method destroy ( --> Nil ) {
fann_destroy_train($!data) if $!data;
$!data = Nil;
}
}
multi method BUILD ( IO() :$path! ) {
die "Cannot read from file: '$path'" unless $path.r;
$!fann = fann_create_from_file("$path")
// die 'Unable to create network';
}
multi method BUILD (
:@layers!,
Bool() :$shortcut,
Num() :connection-rate($rate),
) {
die 'The :shortcut and :connection-rate parameters are not compatible'
if $rate.defined && $shortcut;
my $layers = CArray[uint32].new: |@layers;
my $n = @layers.elems;
$!layers = @layers;
$!fann = $shortcut ?? fann_create_shortcut_array( $n, $layers )
!! $rate.defined ?? fann_create_sparse_array( $rate, $n, $layers )
!! fann_create_standard_array( $n, $layers );
die 'Unable to create network' unless $!fann;
}
multi method BUILD ( fann:D :$fann! ) {
$!fann = $fann;
}
method !error ( --> MaybeError ) { $!fann.error.&error }
# no error
method connection-rate ( --> Num ) { fann_get_connection_rate($!fann) }
method num-input ( --> Int ) { fann_get_num_input($!fann) }
method num-layers ( --> Int ) { fann_get_num_layers($!fann) }
method num-output ( --> Int ) { fann_get_num_output($!fann) }
method total-connections ( --> Int ) { fann_get_total_connections($!fann) }
method total-neurons ( --> Int ) { fann_get_total_neurons($!fann) }
method bit-fail ( --> Int ) { fann_get_bit_fail($!fann) }
method network-type ( --> AI::FANN::NetType ) {
AI::FANN::NetType.^enum_from_value: fann_get_network_type($!fann);
}
multi method weights ( --> List() ) { $.connection-array».weight }
multi method weights (
Num() $weight,
Int() :$from! where * >= 0,
Int() :$to! where * >= 0,
--> ::?CLASS:D
) {
fann_set_weight( $!fann, $from, $to, $weight );
self;
}
multi method weights (
*@connections where { .all ~~ AI::FANN::Connection },
--> ::?CLASS:D
) {
for @connections -> $c {
fann_set_weight( $!fann, $c.from-neuron, $c.to-neuron, $c.weight )
}
self;
}
method randomise-weights ( |c --> ::?CLASS:D ) { $.randomize-weights: |c } # We love our British users
method randomize-weights ( Range:D $range --> ::?CLASS:D ) { # no error
die 'Cannot use an infinite range to randomize weights' if $range.infinite;
fann_randomize_weights($!fann, |$range.minmax».Num);
self;
}
method init-weights ( AI::FANN::TrainData:D $data --> ::?CLASS:D ) {
fann_init_weights( $!fann, $data!AI::FANN::TrainData::data );
self;
}
method layer-array ( --> List ) { # no error
my $out = CArray[uint32].allocate($.num-layers);
fann_get_layer_array($!fann, $out);
$out.list;
}
method bias-array ( --> List ) { # no error
my $out = CArray[uint32].allocate($.num-layers);
fann_get_layer_array($!fann, $out);
$out.list;
}
method connection-array ( --> List ) { # no error
my $out = StructArray[AI::FANN::Connection].new($.total-connections);
fann_get_connection_array($!fann, $out.pointer);
[ $out[ ^$out.elems ] ];
}
method print-connections ( --> ::?CLASS:D ) {
LEAVE self!error.throw; # FANN_E_CANT_ALLOCATE_MEM ...
fann_print_connections($!fann);
self;
}
method print-parameters ( --> ::?CLASS:D ) { # no error
fann_print_parameters($!fann);
self;
}
multi method callback () {
die 'The callback method can only be used to set the callback, or clear it with :delete';
}
multi method callback ( :$delete! where :so --> ::?CLASS:D ) { # no error
fann_set_callback( $!fann, Code );
self;
}
multi method callback ( &cb --> AI::FANN ) { # no error
die 'Unsupported callback: it must be able to accept '
~ :( AI::FANN, AI::FANN::TrainData, uint32, uint32, num32, uint32 ).raku
unless &cb.cando: \( AI::FANN, AI::FANN::TrainData, uint32, uint32, num32, uint32 );
fann_set_callback( $!fann, sub ( $fann, $data, |c ) {
given cb( AI::FANN.new(:$fann), AI::FANN::TrainData.new(:$data), |c ) {
return .so ?? 0 !! -1 when Bool;
return .Int;
}
});
self;
}
multi method run ( CArray[fann_type] $input --> CArray[fann_type] ) {
LEAVE self!error.throw;
fann_run( $!fann, $input )
}
multi method run ( *@input --> List() ) {
LEAVE self!error.throw;
.[ ^$.num-output ]
with fann_run( $!fann, CArray[fann_type].new: |@input».Num )
}
method clone ( --> ::?CLASS:D ) {
LEAVE self!error.throw; # FANN_E_CANT_ALLOCATE_MEM ...
self.new: fann => fann_copy($!fann);
}
multi method scale ( TrainData:D $data --> ::?CLASS:D ) {
LEAVE self!error.throw;
fann_scale_train( $!fann, $data!AI::FANN::TrainData::data );
self;
}
multi method descale ( TrainData:D $data --> ::?CLASS:D ) {
LEAVE self!error.throw;
fann_descale_train( $!fann, $data!AI::FANN::TrainData::data );
self;
}
multi method scale (
CArray[fann_type] :$input,
CArray[fann_type] :$output,
--> ::?CLASS:D
) {
LEAVE self!error.throw;
die 'Must specify input or output data to scale' unless $input || $output;
fann_scale_input( $!fann, $input ) if $input;
fann_scale_output( $!fann, $output ) if $output;
self;
}
multi method descale (
CArray[fann_type] :$input,
CArray[fann_type] :$output,
--> ::?CLASS:D
) {
LEAVE self!error.throw;
die 'Must specify input or output data to descale' unless $input || $output;
fann_descale_input( $!fann, $input ) if $input;
fann_descale_output( $!fann, $output ) if $output;
self;
}
multi method scale (
:@input,
:@output,
--> ::?CLASS:D
) {
LEAVE self!error.throw;
die 'Must specify input or output data to scale' unless @input || @output;
if @input {
my $data = CArray[fann_type].new: |@input».Num;
fann_scale_input( $!fann, $data );
@input[*] = |$data.list;
}
if @output {
my $data = CArray[fann_type].new: |@output».Num;
fann_scale_output( $!fann, $data );
@output[*] = $data.list;
}
self;
}
multi method descale (
:@input,
:@output,
--> ::?CLASS:D
) {
LEAVE self!error.throw;
die 'Must specify input or output data to descale' unless @input || @output;
if @input {
my $data = CArray[fann_type].new: |@input».Num;
fann_descale_input( $!fann, $data );
@input[*] = |$data.list;
}
if @output {
my $data = CArray[fann_type].new: |@output».Num;
fann_descale_output( $!fann, $data );
@output[*] = $data.list;
}
self;
}
multi method scaling (
TrainData:D $train,
Range :$output,
Range :$input,
--> ::?CLASS:D
) {
LEAVE self!error.throw;
die 'Must specify input or output scaling parameters'
unless $input || $output;
die 'Cannot use an infinite range to set input scaling parameters'
if $input && $input.infinite;
die 'Cannot use an infinite range to set output scaling parameters'
if $output && $output.infinite;
my $ret = 0;
$ret = fann_set_input_scaling_params( $!fann, $train!AI::FANN::TrainData::data, |$input.minmax».Num ) if $input && $ret == 0;
$ret = fann_set_output_scaling_params( $!fann, $train!AI::FANN::TrainData::data, |$output.minmax».Num ) if $output && $ret == 0;
self;
}
multi method scaling ( :$delete! where :so --> ::?CLASS:D ) {
LEAVE self!error.throw;
fann_clear_scaling_params( $!fann );
self;
}
method save ( IO() $path --> ::?CLASS:D ) {
LEAVE self!error.throw;
fann_save($!fann, "$path");
self;
}
method reset-error ( --> ::?CLASS:D ) { fann_reset_MSE($!fann); self } # no error
method mean-square-error ( --> Num ) { fann_get_MSE($!fann) } # no error
proto method activation-function ( :$layer, :$neuron, | ) {
$!layers //= $.layer-array;
X::OutOfRange.new(
what => 'Layer index',
got => $layer,
range => 1..^$!layers.elems,
).throw if $layer.defined && $layer !~~ 1..^$!layers.elems;
if $neuron.defined {
die "Cannot set :neuron without setting :layer" unless $layer.defined;
X::OutOfRange.new(
what => 'Neuron index',
got => $neuron,
range => 0..$!layers[$layer],
).throw unless $neuron ~~ 0..$!layers[$layer];
}
{*}
}
multi method activation-function ( # no error
Int :$layer!,
Int :$neuron!,
--> AI::FANN::ActivationFunc
) {
AI::FANN::ActivationFunc.^enum_from_value:
fann_get_activation_function( $!fann, $layer, $neuron );
}
multi method activation-function ( # no error
AI::FANN::ActivationFunc $function!,
Int:D :$layer!,
Int :$neuron,
--> ::?CLASS:D
) {
$neuron.defined
?? fann_set_activation_function( $!fann, $function, $layer, $neuron )
!! fann_set_activation_function_layer( $!fann, $function, $layer );
self;
}
multi method activation-function ( # no error
AI::FANN::ActivationFunc $function!,
Bool() :$hidden is copy,
Bool() :$output is copy,
--> ::?CLASS:D
) {
$hidden = $output = True unless $hidden || $output;
fann_set_activation_function_hidden( $!fann, $function ) if $hidden;
fann_set_activation_function_output( $!fann, $function ) if $output;
self;
}
multi method activation-function ( $other, |c ) { # no error
my $value = AI::FANN::ActivationFunc.^enum_from_value($other)
// die "Invalid activation function: must be a value in AI::FANN::ActivationFunc";
nextwith( $value, |c );
}
proto method activation-steepness ( :$layer, :$neuron, | ) {
$!layers //= $.layer-array;
X::OutOfRange.new(
what => 'Layer index',
got => $layer,
range => 1..^$!layers.elems,
).throw if $layer.defined && $layer !~~ 1..^$!layers.elems;
if $neuron.defined {
die "Cannot set :neuron without setting :layer" unless $layer.defined;
X::OutOfRange.new(
what => 'Neuron index',
got => $neuron,
range => 0..$!layers[$layer],
).throw unless $neuron ~~ 0..$!layers[$layer];
}
{*}
}
multi method activation-steepness ( # no error
Int :$layer!,
Int :$neuron!,
--> Num
) {
fann_get_activation_steepness( $!fann, $layer, $neuron );
}
multi method activation-steepness ( # no error
Num() $value!,
Int:D :$layer!,
Int :$neuron,
--> ::?CLASS:D
) {
$neuron.defined
?? fann_set_activation_steepness( $!fann, $value, $layer, $neuron )
!! fann_set_activation_steepness_layer( $!fann, $value, $layer );
self;
}
multi method activation-steepness ( # no error
Num() $value!,
Bool() :$hidden is copy,
Bool() :$output is copy,
--> ::?CLASS:D
) {
$hidden = $output = True unless $hidden || $output;
fann_set_activation_steepness_hidden( $!fann, $value ) if $hidden;
fann_set_activation_steepness_output( $!fann, $value ) if $output;
self;
}
multi method training-algorithm ( --> AI::FANN::Train ) { # no error
AI::FANN::Train.^enum_from_value: fann_get_training_algorithm($!fann);
}
multi method training-algorithm ( # no error
AI::FANN::Train $algorithm,
--> ::?CLASS:D
) {
fann_set_training_algorithm( $!fann, $algorithm );
self;
}
multi method training-algorithm ( $other, |c --> ::?CLASS:D ) { # no error
my $value = AI::FANN::Train.^enum_from_value($other)
// die "Invalid training algorithm: must be a value in AI::FANN::Train";
$.training-algorithm: $value, |c;
}
multi method train-error-function ( --> AI::FANN::ErrorFunc ) { # no error
AI::FANN::ErrorFunc.^enum_from_value: fann_get_train_error_function($!fann);
}
multi method train-error-function ( # no error
AI::FANN::ErrorFunc $function,
--> ::?CLASS:D
) {
fann_set_train_error_function( $!fann, $function );
self;
}
multi method train-error-function ( $other, |c --> ::?CLASS:D ) { # no error
my $value = AI::FANN::ErrorFunc.^enum_from_value($other)
// die "Invalid error function: must be a value in AI::FANN::ErrorFunc";
$.train-error-function: $value, |c;
}
multi method train-stop-function ( --> AI::FANN::StopFunc ) { # no error
AI::FANN::StopFunc.^enum_from_value: fann_get_train_stop_function($!fann);
}
multi method train-stop-function ( # no error
AI::FANN::StopFunc $function,
--> ::?CLASS:D
) {
fann_set_train_stop_function( $!fann, $function );
self;
}
multi method train-stop-function ( $other, |c --> ::?CLASS:D ) { # no error
my $value = AI::FANN::StopFunc.^enum_from_value($other)
// die "Invalid stop function: must be a value in AI::FANN::StopFunc";
$.train-stop-function: $value, |c;
}
# no error
multi method bit-fail-limit ( --> Num ) { fann_get_bit_fail_limit($!fann) }
multi method bit-fail-limit ( Num() $value --> ::?CLASS:D ) {
fann_set_bit_fail_limit( $!fann, $value );
self;
}
# no error
multi method learning-rate ( --> Num ) { fann_get_learning_rate($!fann) }
multi method learning-rate ( Num() $value --> ::?CLASS:D ) {
fann_set_learning_rate( $!fann, $value );
self;
}
# no error
multi method learning-momentum ( --> Num ) { fann_get_learning_momentum($!fann) }
multi method learning-momentum ( Num() $value --> ::?CLASS:D ) {
fann_set_learning_momentum( $!fann, $value );
self;
}
# no error
multi method quickprop-decay ( --> Num ) { fann_get_quickprop_decay($!fann) }
multi method quickprop-decay ( Num() $value --> ::?CLASS:D ) {
die "The decay value must be less than or equal to 0; got instead $value" if $value > 0;
fann_set_quickprop_decay( $!fann, $value );
self;
}
# no error
multi method quickprop-mu ( --> Num ) { fann_get_quickprop_mu($!fann) }
multi method quickprop-mu ( Num() $value --> ::?CLASS:D ) {
fann_set_quickprop_mu( $!fann, $value );
self;
}
# no error
multi method quickprop-mu ( --> Num ) { fann_get_quickprop_mu($!fann) }
multi method quickprop-mu ( Num() $value --> ::?CLASS:D ) {
fann_set_quickprop_mu( $!fann, $value );
self;
}
# no error
multi method rprop-increase ( --> Num ) { fann_get_rprop_increase_factor($!fann) }
multi method rprop-increase ( Num() $value --> ::?CLASS:D ) {
die "The RPROP increase value must be greater than 1; got instead $value" if $value <= 1;
fann_set_rprop_increase_factor( $!fann, $value );
self;
}
# no error
multi method rprop-decrease ( --> Num ) { fann_get_rprop_decrease_factor($!fann) }
multi method rprop-decrease ( Num() $value --> ::?CLASS:D ) {
die "The RPROP increase value must be smaller than 1; got instead $value" if $value >= 1;
fann_set_rprop_decrease_factor( $!fann, $value );
self;
}
# no error
multi method rprop-delta-range ( --> Range ) {
fann_get_rprop_delta_min($!fann) .. fann_get_rprop_delta_max($!fann)
}
multi method rprop-delta-range ( Range:D $value --> ::?CLASS:D ) {
die 'Cannot use an infinite range to set scale' if $value.infinite;
fann_set_rprop_delta_min( $!fann, $value.min );
self;
}
# no error
multi method rprop-delta-zero ( --> Range ) { fann_get_rprop_delta_zero($!fann) }
multi method rprop-delta-zero ( Num() $value --> ::?CLASS:D ) {
die "The delta zero must be greater than 0; got instead $value" if $value <= 0;
fann_set_rprop_delta_zero( $!fann, $value );
self;
}
# no error
multi method sarprop-weight-decay-shift ( --> Range ) { fann_get_sarprop_weight_decay_shift($!fann) }
multi method sarprop-weight-decay-shift ( Num() $value --> ::?CLASS:D ) {
fann_set_sarprop_weight_decay_shift( $!fann, $value );
self;
}
# no error
multi method sarprop-step-error-threshold ( --> Range ) { fann_get_sarprop_step_error_threshold_factor($!fann) }
multi method sarprop-step-error-threshold ( Num() $value --> ::?CLASS:D ) {
fann_set_sarprop_step_error_threshold_factor( $!fann, $value );
self;
}
# no error
multi method sarprop-step-error-shift ( --> Range ) { fann_get_sarprop_step_error_shift($!fann) }
multi method sarprop-step-error-shift ( Num() $value --> ::?CLASS:D ) {
fann_set_sarprop_step_error_shift( $!fann, $value );
self;
}
# no error
multi method sarprop-temperature ( --> Range ) { fann_get_sarprop_temperature($!fann) }
multi method sarprop-temperature ( Num() $value --> ::?CLASS:D ) {
fann_set_sarprop_temperature( $!fann, $value );
self;
}
multi method train ( @input, @output --> ::?CLASS:D ) {
LEAVE self!error.throw; # FANN_E_CANT_ALLOCATE_MEM FANN_E_CANT_TRAIN_ACTIVATION ...
fann_train( $!fann,
CArray[fann_type].new(|@input».Num),
CArray[fann_type].new(|@output».Num),
);
self;
}
multi method train (
CArray[fann_type] $input,
CArray[fann_type] $output,
--> ::?CLASS:D
) {
LEAVE self!error.throw; # FANN_E_CANT_ALLOCATE_MEM FANN_E_CANT_TRAIN_ACTIVATION ...
fann_train( $!fann, $input, $output );
self;
}
multi method train ( TrainData:D $data --> ::?CLASS:D ) {
LEAVE self!error.throw; # FANN_E_CANT_ALLOCATE_MEM FANN_E_CANT_TRAIN_ACTIVATION ...
fann_train_epoch( $!fann, $data!AI::FANN::TrainData::data );
self;
}
multi method train ( IO() $path --> ::?CLASS:D ) {
my $data = AI::FANN::TrainData.new: :$path;
LEAVE $data.?destroy;
$.train: $data;
}
multi method train (
TrainData:D $data,
Int() :$max-epochs where *.defined,
Int() :$epochs-between-reports where *.defined,
Num() :$desired-error where *.defined,
--> ::?CLASS:D
) {
LEAVE self!error.throw; # FANN_E_CANT_ALLOCATE_MEM FANN_E_CANT_TRAIN_ACTIVATION ...
fann_train_on_data(
$!fann,
$data!AI::FANN::TrainData::data,
$max-epochs,
$epochs-between-reports,
$desired-error,
);
self;
}
multi method train (
IO() $path,
Int() :$max-epochs where *.defined,
Int() :$epochs-between-reports where *.defined,
Num() :$desired-error where *.defined,
--> ::?CLASS:D
) {
LEAVE self!error.throw; # FANN_E_CANT_ALLOCATE_MEM FANN_E_CANT_TRAIN_ACTIVATION ...
die "Cannot read from file: '$path'" unless $path.r;
fann_train_on_file(
$!fann,
"$path",
$max-epochs,
$epochs-between-reports,
$desired-error,
);
self;
}
multi method train (
Int() :$max-epochs,
Int() :$epochs-between-reports,
Num() :$desired-error,
|c
) {
die 'You must specify none or all three of :max-epochs, :epochs-between-reports, and :desired-error'
if ( $max-epochs, $epochs-between-reports, $desired-error ).grep(*.defined) != 3;
nextsame;
}
multi method test ( @input, @output --> List() ) {
LEAVE self!error.throw; # FANN_E_CANT_USE_ACTIVATION ...
fann_test( $!fann,
CArray[fann_type].new(|@input».Num),
CArray[fann_type].new(|@output».Num),
).[ ^$.num-output ]
}
multi method test (
CArray[fann_type] $input,
CArray[fann_type] $output,
--> CArray[fann_type]
) {
LEAVE self!error.throw; # FANN_E_CANT_USE_ACTIVATION ...
fann_test( $!fann, $input, $output );
}
multi method test ( TrainData:D $data --> Num ) {
LEAVE self!error.throw; # FANN_E_CANT_USE_ACTIVATION ...
fann_test_data( $!fann, $data!AI::FANN::TrainData::data );
}
multi method test ( IO() $path --> Num ) {
my $data = AI::FANN::TrainData.new: :$path;
LEAVE $data.?destroy;
$.test: $data;
}
# Cascade methods
multi method cascade-train (
TrainData:D $data,
Int() :$max-neurons!,
Int() :$neurons-between-reports!,
Num() :$desired-error!,
--> ::?CLASS:D
) {
LEAVE self!error.throw; # FANN_E_CANT_ALLOCATE_MEM FANN_E_CANT_TRAIN_ACTIVATION ...
fann_cascadetrain_on_data(
$!fann,
$data!AI::FANN::TrainData::data,
$max-neurons,
$neurons-between-reports,
$desired-error,
);
self;
}
multi method cascade-train (
IO() $path,
Int() :$max-neurons!,
Int() :$neurons-between-reports!,
Num() :$desired-error!,
--> ::?CLASS:D
) {
LEAVE self!error.throw; # FANN_E_CANT_ALLOC |
### ----------------------------------------------------
### -- AI::FANN
### -- Licenses: Artistic-2.0
### -- Authors: Jonathan Scott Duff <[email protected]>, José Joaquín Atria <[email protected]>
### -- File: lib/AI/FANN.rakumod
### ----------------------------------------------------
### -- Chunk 2 of 2
ATE_MEM FANN_E_CANT_TRAIN_ACTIVATION ...
die "Cannot read from file: '$path'" unless $path.r;
fann_cascadetrain_on_file(
$!fann,
"$path",
$max-neurons,
$neurons-between-reports,
$desired-error,
);
self;
}
# no error
method cascade-num-candidates ( --> Int ) { fann_get_cascade_num_candidates($!fann) }
# no error
multi method cascade-candidate-limit ( --> Num ) { fann_get_cascade_candidate_limit($!fann) }
multi method cascade-candidate-limit ( Num() $value --> ::?CLASS:D ) {
fann_set_cascade_candidate_limit( $!fann, $value );
self;
}
# no error
multi method cascade-weight-multiplier ( --> Num ) { fann_get_cascade_weight_multiplier($!fann) }
multi method cascade-weight-multiplier ( Num() $value --> ::?CLASS:D ) {
fann_set_cascade_weight_multiplier( $!fann, $value );
self;
}
# no error
multi method cascade-output-change-fraction ( --> Num ) { fann_get_cascade_output_change_fraction($!fann) }
multi method cascade-output-change-fraction ( Num() $value --> ::?CLASS:D ) {
fann_set_cascade_output_change_fraction( $!fann, $value );
self;
}
# no error
multi method cascade-candidate-change-fraction ( --> Num ) { fann_get_cascade_candidate_change_fraction($!fann) }
multi method cascade-candidate-change-fraction ( Num() $value --> ::?CLASS:D ) {
fann_set_cascade_candidate_change_fraction( $!fann, $value );
self;
}
# no error
multi method cascade-num-candidate-groups ( --> Int ) { fann_get_cascade_num_candidate_groups($!fann) }
multi method cascade-num-candidate-groups ( Int:D $value --> ::?CLASS:D ) {
fann_set_cascade_num_candidate_groups( $!fann, $value );
self;
}
# no error
multi method cascade-candidate-stagnation-epochs ( --> Int ) { fann_get_cascade_candidate_stagnation_epochs($!fann) }
multi method cascade-candidate-stagnation-epochs ( Int:D $value --> ::?CLASS:D ) {
fann_set_cascade_candidate_stagnation_epochs( $!fann, $value );
self;
}
# no error
multi method cascade-output-stagnation-epochs ( --> Int ) { fann_get_cascade_output_stagnation_epochs($!fann) }
multi method cascade-output-stagnation-epochs ( Int:D $value --> ::?CLASS:D ) {
fann_set_cascade_output_stagnation_epochs( $!fann, $value );
self;
}
# no error
multi method cascade-activation-steepnesses-count ( --> Int ) { fann_get_cascade_activation_steepnesses_count($!fann) }
multi method cascade-candidate-epochs ( --> Range ) {
fann_get_cascade_max_cand_epochs($!fann) .. fann_get_cascade_min_cand_epochs($!fann);
}
multi method cascade-candidate-epochs (
Range $value,
--> ::?CLASS:D
) {
die 'Cannot use an infinite range to set cascade candidate epochs' if $value.infinite;
fann_set_cascade_max_cand_epochs($!fann, $value.min.Int);
fann_set_cascade_min_cand_epochs($!fann, $value.max.Int);
self;
}
multi method cascade-candidate-epochs (
Int :$min,
Int :$max,
--> ::?CLASS:D
) {
fann_set_cascade_min_cand_epochs($!fann, $min) if $min.defined;
fann_set_cascade_max_cand_epochs($!fann, $max) if $max.defined;
self;
}
multi method cascade-output-epochs ( --> Range ) {
fann_get_cascade_max_out_epochs($!fann) .. fann_get_cascade_min_out_epochs($!fann);
}
multi method cascade-output-epochs (
Range $value,
--> ::?CLASS:D
) {
die 'Cannot use an infinite range to set cascade output epochs' if $value.infinite;
fann_set_cascade_max_out_epochs($!fann, $value.min.Int);
fann_set_cascade_min_out_epochs($!fann, $value.max.Int);
self;
}
multi method cascade-output-epochs (
Int :$min,
Int :$max,
--> ::?CLASS:D
) {
fann_set_cascade_min_out_epochs($!fann, $min) if $min.defined;
fann_set_cascade_max_out_epochs($!fann, $max) if $max.defined;
self;
}
multi method cascade-activation-steepnesses ( --> List() ) {
.[ ^$.cascade-activation-steepnesses-count ]
with fann_get_cascade_activation_steepnesses($!fann)
}
multi method cascade-activation-steepnesses (
CArray[fann_type] $steepnesses,
--> ::?CLASS:D
) {
LEAVE self!error.throw; # FANN_E_CANT_ALLOCATE_MEM
fann_set_cascade_activation_steepnesses(
$!fann, $steepnesses, $steepnesses.elems );
self;
}
multi method cascade-activation-steepnesses (
*@steepnesses,
--> ::?CLASS:D
) {
LEAVE self!error.throw; # FANN_E_CANT_ALLOCATE_MEM
fann_set_cascade_activation_steepnesses(
$!fann,
CArray[fann_type].new(|@steepnesses».Num),
@steepnesses.elems
);
self;
}
multi method cascade-activation-functions ( --> List() ) { # no error
.[ ^$.cascade-activation-functions-count ]
with fann_get_cascade_activation_functions($!fann)
}
multi method cascade-activation-functions (
CArray[fann_activationfunc_enum] $functions,
--> ::?CLASS:D
) {
LEAVE self!error.throw; # FANN_E_CANT_ALLOCATE_MEM
fann_set_cascade_activation_functions(
$!fann, $functions, $functions.elems );
self;
}
multi method cascade-activation-functions (
*@functions,
--> ::?CLASS:D
) {
LEAVE self!error.throw; # FANN_E_CANT_ALLOCATE_MEM
fann_set_cascade_activation_functions(
$!fann,
CArray[fann_activationfunc_enum].new(|@functions».Int),
@functions.elems
);
self;
}
method destroy ( --> Nil ) {
fann_destroy($!fann) if $!fann;
$!fann = Nil;
}
}
|
### ----------------------------------------------------
### -- AI::FANN
### -- Licenses: Artistic-2.0
### -- Authors: Jonathan Scott Duff <[email protected]>, José Joaquín Atria <[email protected]>
### -- File: lib/AI/FANN/Raw.rakumod
### ----------------------------------------------------
use AI::FANN::Raw::Base;
use AI::FANN::Raw::Creation;
use AI::FANN::Raw::Training;
use AI::FANN::Raw::Cascade;
use AI::FANN::Raw::Error;
use AI::FANN::Raw::IO;
sub EXPORT {
return Map.new(
%(AI::FANN::Raw::Base::EXPORT::DEFAULT::),
%(AI::FANN::Raw::Creation::EXPORT::DEFAULT::),
%(AI::FANN::Raw::Training::EXPORT::DEFAULT::),
%(AI::FANN::Raw::Cascade::EXPORT::DEFAULT::),
%(AI::FANN::Raw::Error::EXPORT::DEFAULT::),
%(AI::FANN::Raw::IO::EXPORT::DEFAULT::),
);
}
|
### ----------------------------------------------------
### -- AI::FANN
### -- Licenses: Artistic-2.0
### -- Authors: Jonathan Scott Duff <[email protected]>, José Joaquín Atria <[email protected]>
### -- File: lib/AI/FANN/Raw/Base.rakumod
### ----------------------------------------------------
unit module AI::FANN::Raw::Base;
use NativeCall;
constant float is export = num32;
constant fann_type is export = num32;
constant fann_activationfunc_enum is export = int32;
constant fann_errorfunc_enum is export = int32;
constant fann_stopfunc_enum is export = int32;
constant fann_nettype_enum is export = int32;
constant fann_errno_enum is export = int32;
constant fann_train_enum is export = int32;
class fann_connection is repr('CPointer') is export {*}
class fann_error is repr('CStruct') is export {
has int32 $.errno;
has Pointer $!error-log;
has Str $.errstr;
}
class fann is repr('CStruct') is export {
has int32 $.errno;
has Pointer $!error-log;
has Str $.errstr;
method error { nativecast( fann_error, self ) }
}
class fann_train_data is repr('CStruct') is export {
has int32 $.errno;
has Pointer $!error-log;
has Str $.errstr;
has uint32 $.num-data;
has uint32 $.num-input;
has uint32 $.num-output;
has CArray[CArray[fann_type]] $.input;
has CArray[CArray[fann_type]] $.output;
method error { nativecast( fann_error, self ) }
}
|
### ----------------------------------------------------
### -- AI::FANN
### -- Licenses: Artistic-2.0
### -- Authors: Jonathan Scott Duff <[email protected]>, José Joaquín Atria <[email protected]>
### -- File: lib/AI/FANN/Raw/Training.rakumod
### ----------------------------------------------------
unit module AI::FANN::Raw::Training;
use NativeCall;
use AI::FANN::Raw::Base;
my constant LIB = 'fann';
## http://leenissen.dk/fann/html/files/fann_train-h.html
## FANN Training
sub fann_train(fann, CArray[fann_type], CArray[fann_type]) is export is native(LIB) {*}
sub fann_test(fann, CArray[fann_type], CArray[fann_type]) returns CArray[fann_type] is export is native(LIB) {*}
sub fann_get_MSE(fann) returns float is export is native(LIB) {*}
sub fann_get_bit_fail(fann) returns uint32 is export is native(LIB) {*}
sub fann_reset_MSE(fann) is export is native(LIB) {*}
sub fann_train_on_data(fann, fann_train_data, uint32, uint32, float) is export is native(LIB) {*}
sub fann_train_on_file(fann, Str, uint32, uint32, float) is export is native(LIB) {*}
sub fann_train_epoch(fann, fann_train_data) returns float is export is native(LIB) {*}
sub fann_test_data(fann, fann_train_data) returns float is export is native(LIB) {*}
## Training Data Manipulation
sub fann_read_train_from_file(Str) returns fann_train_data is export is native(LIB) {*}
sub fann_create_train(uint32, uint32, uint32) returns fann_train_data is export is native(LIB) {*}
sub fann_create_train_from_callback(uint32, uint32, uint32, & ( uint32, uint32, uint32, CArray[fann_type], CArray[fann_type] ) ) returns fann_train_data is export is native(LIB) {*}
sub fann_destroy_train(fann_train_data) is export is native(LIB) {*}
sub fann_shuffle_train_data(fann_train_data) is export is native(LIB) {*}
sub fann_scale_train(fann,fann_train_data) is export is native(LIB) {*}
sub fann_descale_train(fann,fann_train_data) is export is native(LIB) {*}
sub fann_set_input_scaling_params(fann, fann_train_data, float, float) returns int32 is export is native(LIB) {*}
sub fann_set_output_scaling_params(fann, fann_train_data, float, float) returns int32 is export is native(LIB) {*}
sub fann_set_scaling_params(fann, fann_train_data, float, float, float, float) returns int32 is export is native(LIB) {*}
sub fann_clear_scaling_params(fann) returns int32 is export is native(LIB) {*}
sub fann_scale_input(fann, CArray[fann_type] ) is export is native(LIB) {*}
sub fann_scale_output(fann, CArray[fann_type] ) is export is native(LIB) {*}
sub fann_descale_input(fann, CArray[fann_type] ) is export is native(LIB) {*}
sub fann_descale_output(fann, CArray[fann_type] ) is export is native(LIB) {*}
sub fann_get_training_algorithm(fann) returns fann_train_enum is export is native(LIB) {*}
sub fann_set_training_algorithm(fann, fann_train_enum) is export is native(LIB) {*}
sub fann_get_learning_rate(fann) returns float is export is native(LIB) {*}
sub fann_set_learning_rate(fann, float) is export is native(LIB) {*}
sub fann_get_learning_momentum(fann) returns float is export is native(LIB) {*}
sub fann_set_learning_momentum(fann, float) is export is native(LIB) {*}
sub fann_get_activation_function(fann, int32, int32) returns fann_activationfunc_enum is export is native(LIB) {*}
sub fann_set_activation_function(fann, fann_activationfunc_enum, int32, int32) returns fann_activationfunc_enum is export is native(LIB) {*}
sub fann_set_activation_function_layer(fann, fann_activationfunc_enum, int32) is export is native(LIB) {*}
sub fann_set_activation_function_hidden(fann, fann_activationfunc_enum) is export is native(LIB) {*}
sub fann_set_activation_function_output(fann, fann_activationfunc_enum) is export is native(LIB) {*}
sub fann_get_activation_steepness(fann, int32, int32) returns fann_type is export is native(LIB) {*}
sub fann_set_activation_steepness(fann, fann_type, int32, int32) is export is native(LIB) {*}
sub fann_set_activation_steepness_layer(fann, fann_type, int32) is export is native(LIB) {*}
sub fann_set_activation_steepness_hidden(fann, fann_type) is export is native(LIB) {*}
sub fann_set_activation_steepness_output(fann, fann_type) is export is native(LIB) {*}
sub fann_get_train_error_function(fann) returns fann_errorfunc_enum is export is native(LIB) {*}
sub fann_set_train_error_function(fann, fann_errorfunc_enum) is export is native(LIB) {*}
sub fann_get_train_stop_function(fann) returns fann_stopfunc_enum is export is native(LIB) {*}
sub fann_set_train_stop_function(fann, fann_stopfunc_enum) is export is native(LIB) {*}
sub fann_get_bit_fail_limit(fann) returns fann_type is export is native(LIB) {*}
sub fann_set_bit_fail_limit(fann, fann_type) is export is native(LIB) {*}
sub fann_set_callback(fann, & ( fann, fann_train_data, uint32, uint32, num32, uint32 --> int ) ) is export is native(LIB) {*}
sub fann_get_quickprop_decay(fann) returns float is export is native(LIB) {*}
sub fann_set_quickprop_decay(fann, float) is export is native(LIB) {*}
sub fann_get_quickprop_mu(fann) returns float is export is native(LIB) {*}
sub fann_set_quickprop_mu(fann, float) is export is native(LIB) {*}
sub fann_get_rprop_increase_factor(fann) returns float is export is native(LIB) {*}
sub fann_set_rprop_increase_factor(fann, float) is export is native(LIB) {*}
sub fann_get_rprop_decrease_factor(fann) returns float is export is native(LIB) {*}
sub fann_set_rprop_decrease_factor(fann, float) is export is native(LIB) {*}
sub fann_get_rprop_delta_min(fann) returns float is export is native(LIB) {*}
sub fann_set_rprop_delta_min(fann, float) is export is native(LIB) {*}
sub fann_get_rprop_delta_max(fann) returns float is export is native(LIB) {*}
sub fann_set_rprop_delta_max(fann, float) is export is native(LIB) {*}
sub fann_get_rprop_delta_zero(fann) returns float is export is native(LIB) {*}
sub fann_set_rprop_delta_zero(fann, float) is export is native(LIB) {*}
sub fann_get_sarprop_weight_decay_shift(fann) returns float is export is native(LIB) {*}
sub fann_set_sarprop_weight_decay_shift(fann, float) is export is native(LIB) {*}
sub fann_get_sarprop_step_error_threshold_factor(fann) returns float is export is native(LIB) {*}
sub fann_set_sarprop_step_error_threshold_factor(fann, float) is export is native(LIB) {*}
sub fann_get_sarprop_step_error_shift(fann) returns float is export is native(LIB) {*}
sub fann_set_sarprop_step_error_shift(fann, float) is export is native(LIB) {*}
sub fann_get_sarprop_temperature(fann) returns float is export is native(LIB) {*}
sub fann_set_sarprop_temperature(fann, float) is export is native(LIB) {*}
# Training data methods
sub fann_scale_input_train_data(fann_train_data, fann_type, fann_type) is export is native(LIB) {*}
sub fann_scale_output_train_data(fann_train_data, fann_type, fann_type) is export is native(LIB) {*}
sub fann_scale_train_data(fann_train_data, fann_type, fann_type) is export is native(LIB) {*}
sub fann_merge_train_data(fann_train_data, fann_train_data) returns fann_train_data is export is native(LIB) {*}
sub fann_duplicate_train_data(fann_train_data) returns fann_train_data is export is native(LIB) {*}
sub fann_subset_train_data(fann_train_data, uint32, uint32) returns fann_train_data is export is native(LIB) {*}
sub fann_length_train_data(fann_train_data) returns uint32 is export is native(LIB) {*}
sub fann_num_input_train_data(fann_train_data) returns uint32 is export is native(LIB) {*}
sub fann_num_output_train_data(fann_train_data) returns uint32 is export is native(LIB) {*}
sub fann_save_train(fann_train_data, Str) returns uint32 is export is native(LIB) {*}
sub fann_save_train_to_fixed(fann_train_data, Str, uint32) returns uint32 is export is native(LIB) {*}
|
### ----------------------------------------------------
### -- AI::FANN
### -- Licenses: Artistic-2.0
### -- Authors: Jonathan Scott Duff <[email protected]>, José Joaquín Atria <[email protected]>
### -- File: lib/AI/FANN/Raw/Cascade.rakumod
### ----------------------------------------------------
unit module AI::FANN::Raw::Cascade;
use NativeCall;
use AI::FANN::Raw::Base;
my constant LIB = 'fann';
sub fann_cascadetrain_on_data(fann, fann_train_data, uint32, uint32, float) is export is native(LIB) {*}
sub fann_cascadetrain_on_file(fann, Str, uint32, uint32, float) is export is native(LIB) {*}
sub fann_get_cascade_output_change_fraction(fann) returns float is export is native(LIB) {*}
sub fann_set_cascade_output_change_fraction(fann, float) is export is native(LIB) {*}
sub fann_get_cascade_output_stagnation_epochs(fann) returns uint32 is export is native(LIB) {*}
sub fann_set_cascade_output_stagnation_epochs(fann, uint32) is export is native(LIB) {*}
sub fann_get_cascade_candidate_change_fraction(fann) returns float is export is native(LIB) {*}
sub fann_set_cascade_candidate_change_fraction(fann, float) is export is native(LIB) {*}
sub fann_get_cascade_candidate_stagnation_epochs(fann) returns uint32 is export is native(LIB) {*}
sub fann_set_cascade_candidate_stagnation_epochs(fann, uint32) is export is native(LIB) {*}
sub fann_get_cascade_weight_multiplier(fann) returns fann_type is export is native(LIB) {*}
sub fann_set_cascade_weight_multiplier(fann, fann_type) is export is native(LIB) {*}
sub fann_get_cascade_candidate_limit(fann) returns fann_type is export is native(LIB) {*}
sub fann_set_cascade_candidate_limit(fann, fann_type) is export is native(LIB) {*}
sub fann_get_cascade_max_out_epochs(fann) returns uint32 is export is native(LIB) {*}
sub fann_set_cascade_max_out_epochs(fann, uint32) is export is native(LIB) {*}
sub fann_get_cascade_min_out_epochs(fann) returns uint32 is export is native(LIB) {*}
sub fann_set_cascade_min_out_epochs(fann, uint32) is export is native(LIB) {*}
sub fann_get_cascade_max_cand_epochs(fann) returns uint32 is export is native(LIB) {*}
sub fann_set_cascade_max_cand_epochs(fann, uint32) is export is native(LIB) {*}
sub fann_get_cascade_min_cand_epochs(fann) returns uint32 is export is native(LIB) {*}
sub fann_set_cascade_min_cand_epochs(fann, uint32) is export is native(LIB) {*}
sub fann_get_cascade_num_candidates(fann) returns uint32 is export is native(LIB) {*}
sub fann_get_cascade_activation_functions(fann) returns fann_activationfunc_enum is export is native(LIB) {*}
sub fann_set_cascade_activation_functions(fann, CArray[fann_activationfunc_enum], uint32) is export is native(LIB) {*}
sub fann_get_cascade_activation_steepnesses(fann) returns CArray[fann_type] is export is native(LIB) {*}
sub fann_set_cascade_activation_steepnesses(fann, CArray[fann_type], uint32) is export is native(LIB) {*}
sub fann_get_cascade_activation_functions_count(fann) returns uint32 is export is native(LIB) {*}
sub fann_get_cascade_activation_steepnesses_count(fann) returns uint32 is export is native(LIB) {*}
sub fann_get_cascade_num_candidate_groups(fann) returns uint32 is export is native(LIB) {*}
sub fann_set_cascade_num_candidate_groups(fann, uint32) is export is native(LIB) {*}
|
### ----------------------------------------------------
### -- AI::FANN
### -- Licenses: Artistic-2.0
### -- Authors: Jonathan Scott Duff <[email protected]>, José Joaquín Atria <[email protected]>
### -- File: lib/AI/FANN/Raw/Error.rakumod
### ----------------------------------------------------
unit module AI::FANN::Raw::Error;
use NativeCall;
use AI::FANN::Raw::Base;
my constant LIB = 'fann';
sub fann_set_error_log(fann_error, Pointer) is export is native(LIB) {*}
sub fann_get_errno(fann_error) returns fann_errno_enum is export is native(LIB) {*}
sub fann_reset_errno(fann_error) is export is native(LIB) {*}
sub fann_reset_errstr(fann_error) is export is native(LIB) {*}
sub fann_get_errstr(fann_error) returns Str is export is native(LIB) {*}
sub fann_print_error(fann_error) is export is native(LIB) {*}
|
### ----------------------------------------------------
### -- AI::FANN
### -- Licenses: Artistic-2.0
### -- Authors: Jonathan Scott Duff <[email protected]>, José Joaquín Atria <[email protected]>
### -- File: lib/AI/FANN/Raw/Creation.rakumod
### ----------------------------------------------------
unit module AI::FANN::Raw::Creation;
use NativeCall;
use AI::FANN::Raw::Base;
## http://leenissen.dk/fann/html/files/fann-h.html
## FANN Creation/Execution
my constant LIB = 'fann';
sub fann_create_standard_array(uint32, CArray[uint32]) returns fann is export is native(LIB) {*}
sub fann_create_sparse_array(float, uint32, CArray[uint32]) returns fann is export is native(LIB) {*}
sub fann_create_shortcut_array(uint32, CArray[uint32]) returns fann is export is native(LIB) {*}
sub fann_create_standard(uint32 $num_layers, *@neurons) is export {
my CArray[uint32] $layers .= new(|@neurons);
return fann_create_standard_array($num_layers, $layers);
}
sub fann_create_sparse(float $connection_rate, uint32 $num_layers, *@neurons) returns fann is export {
my CArray[uint32] $layers = CArray[uint32].new(@neurons);
return fann_create_sparse_array($connection_rate, $num_layers, $layers);
}
sub fann_create_shortcut(uint32 $num_layers, *@neurons) returns fann is export {
my CArray[uint32] $layers = CArray[uint32].new(@neurons);
return fann_create_shortcut_array($num_layers, $layers);
}
sub fann_destroy(fann) is export is native(LIB) {*}
sub fann_copy(fann) returns fann is export is native(LIB) {*}
sub fann_run(fann, CArray[float]) returns CArray[fann_type] is export is native(LIB) {*}
sub fann_randomize_weights(fann, float, float) is export is native(LIB) {*}
sub fann_init_weights(fann, fann_train_data) is export is native(LIB) {*}
sub fann_print_connections(fann) is export is native(LIB) {*}
sub fann_print_parameters(fann) is export is native(LIB) {*}
sub fann_get_num_input(fann) returns uint32 is export is native(LIB) {*}
sub fann_get_num_output(fann) returns uint32 is export is native(LIB) {*}
sub fann_get_total_neurons(fann) returns uint32 is export is native(LIB) {*}
sub fann_get_total_connections(fann) returns uint32 is export is native(LIB) {*}
sub fann_get_network_type(fann) returns uint32 is export is native(LIB) {*}
sub fann_get_connection_rate(fann) returns float is export is native(LIB) {*}
sub fann_get_num_layers(fann) returns uint32 is export is native(LIB) {*}
sub fann_get_layer_array(fann, CArray[uint32]) is export is native(LIB) {*}
sub fann_get_bias_array(fann, CArray[uint32]) is export is native(LIB) {*}
sub fann_get_connection_array(fann, Pointer) is export is native(LIB) {*}
sub fann_set_weight_array(fann, CArray[fann_connection], uint32) is export is native(LIB) {*}
sub fann_set_weight(fann, uint32, uint32, float) is export is native(LIB) {*}
sub fann_set_user_data(fann, Pointer) is export is native(LIB) {*}
sub fann_get_user_data(fann) returns Pointer[void] is export is native(LIB) {*}
|
### ----------------------------------------------------
### -- AI::FANN
### -- Licenses: Artistic-2.0
### -- Authors: Jonathan Scott Duff <[email protected]>, José Joaquín Atria <[email protected]>
### -- File: lib/AI/FANN/Raw/IO.rakumod
### ----------------------------------------------------
unit module AI::FANN::Raw::IO;
use NativeCall;
use AI::FANN::Raw::Base;
my constant LIB = 'fann';
sub fann_create_from_file(Str) returns fann is export is native(LIB) {*}
sub fann_save(fann, Str) returns int32 is export is native(LIB) {*}
|
### ----------------------------------------------------
### -- AI::Gator
### -- Licenses: MIT
### -- Authors: Brian Duggan
### -- File: META6.json
### ----------------------------------------------------
{
"name" : "AI::Gator",
"authors" : [
"Brian Duggan"
],
"provides" : {
"AI::Gator" : "lib/AI/Gator.rakumod",
"AI::Gator::Session" : "lib/AI/Gator/Session.rakumod",
"AI::Gator::ToolBuilder" : "lib/AI/Gator/ToolBuilder.rakumod",
"AI::Gator::Tools" : "lib/AI/Gator/Tools.rakumod",
"ai-gator" : "bin/ai-gator"
},
"build-depends" : [ ],
"depends" : [
"Log::Async:ver<0.0.13>", "HTTP::Tiny", "Prompt", "JSON::Fast", "Terminal::ANSI", "Terminal::UI",
"Readline"
],
"description" : "Ailigator: your AI Generic Assistant with a Tool-Oriented REPL",
"tags" : [
"ai"
],
"license" : "MIT",
"raku" : "6.*",
"version" : "0.0.4",
"auth" : "zef:bduggan",
"source-url" : "git://github.com/bduggan/raku-ai-gator.git"
}
|
### ----------------------------------------------------
### -- AI::Gator
### -- Licenses: MIT
### -- Authors: Brian Duggan
### -- File: LICENSE
### ----------------------------------------------------
MIT License
Copyright (c) 2025 Brian Duggan
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
|
### ----------------------------------------------------
### -- AI::Gator
### -- Licenses: MIT
### -- Authors: Brian Duggan
### -- File: README.md
### ----------------------------------------------------
[](https://github.com/bduggan/raku-ai-gator/actions/workflows/linux.yml)
[](https://github.com/bduggan/raku-ai-gator/actions/workflows/macos.yml)
NAME
====
AI::Gator - Ailigator -- your AI Generic Assistant with a Tool-Oriented REPL
<img src="https://github.com/user-attachments/assets/0e71fb98-e149-483a-8654-300316e413e8" alt="ailigator" width="300">
SYNOPSIS
========
Put this into $HOME/ai-gator/tools/weather.raku:
#| Get real time weather for a given city
our sub get_weather(
Str :$city! #= The city to get the weather for
) {
"The weather in $city is sunny.";
}
Then start the AI Gator REPL:
$ ai-gator
You: Is it raining in Toledo?
[tool] get_weather city Toledo
[tool] get_weather done
Gator: No, it is not raining in Toledo. The weather is sunny.
You: What about Philadelphia or San Francisco?
[tool] get_weather city Philadelphia
[tool] get_weather done
[tool] get_weather city San Francisco
[tool] get_weather done
Gator: It is sunny in both Philadelphia and San Francisco.
For other options, run:
$ ai-gator -h
This module can also be used programmatically:
use AI::Gator;
my AI::Gator $gator = AI::Gator::Gemini.new: model => 'gemini-2.0-flash';
my AI::Gator::Session $session = AI::Gator::Session::Gemini.new;
$session.add-message: "Hello, Gator!";
react whenever $gator.chat($session) -> $chunk {
print $chunk;
}
# Hello! How can I help you today?
To use tools programmatically, here is an example:
use AI::Gator;
#| Get real time weather for a given city
sub get_weather(
Str :$city! #= The city to get the weather for
) {
"The weather in $city is sunny.";
}
my AI::Gator $gator = AI::Gator::Gemini.new:
model => 'gemini-2.0-flash',
:quiet,
tools => @( &get_weather, );
my AI::Gator::Session $session = AI::Gator::Session::Gemini.new;
$session.add-message: "Hello ailigator!";
react whenever $gator.chat($session) { .print }
# Hello! How can I help you today? 🐊
my $tool-promise = start $gator.tool-builder($session);
$session.add-message: "What is the weather in Paris?";
react whenever $gator.chat($session) { .print }
await $tool-promise;
$gator.do-tool-calls: $session;
react whenever $gator.chat($session) { .print }
# The weather in Paris is sunny.
DESCRIPTION
===========
AI::Gator is an AI assistant oriented towards using tools and a REPL interface.
Features:
- streaming responses
- tool definitions in Raku
- tool calls
- session storage
- Gemini and OpenAI support
- REPL interface with history
Tools are defined as Raku functions and converted into an OpenAI or Gemini specification using declarator pod and other native Raku features.
All sessions are stored in the sessions/ directory, and the REPL stores the history in a .history file, readline-style.
COMMAND LINE OPTIONS
====================
`ai-gator resume-last` will resume the last session, if it exists.
`ai-gator resume session-id` will resume the specified session.
`ai-gator sessions` will list all sessions.
Also in the REPL:
`\history` will show user + assistant commands
`\history all` will show all commands, including tool calls
`\history mine` will show just the user commands
`\inspect` will enter an interactive ui that shows all previous prompts and responses
CONFIGURATION
=============
Set AI_GATOR_HOME to ai-gator's home (by default $HOME/ai-gator).
In this directory, the following files and directories are used:
- config.toml: configuration file
- tools/: directory with files containing tools
- sessions/: directory with session files (created by the REPL)
- .history: file with readline history (also created by the REPL)
CONFIGURATION FILE
==================
Sample configuration to use Gemini:
model = "gemini-2.0-flash"
adapter = 'Gemini'
Sample configuration to use OpenAI:
model = "gpt-4o"
base-uri = "https://api.openai.com/v1"
ENVIRONMENT
===========
- AI_GATOR_HOME: home directory for AI::Gator (default: $HOME/ai-gator)
- GEMINI_API_KEY: API key for Gemini (if using Gemini)
- OPENAI_API_KEY: API key for OpenAI (if using OpenAI)
NOTES
=====
This is all pretty rough and experimental. Expect the api to change. Patches welcome!
AUTHOR
======
Brian Duggan
|
### ----------------------------------------------------
### -- AI::Gator
### -- Licenses: MIT
### -- Authors: Brian Duggan
### -- File: t/01-session.rakutest
### ----------------------------------------------------
#!/usr/bin/env raku
use Test;
use AI::Gator::Session;
use JSON::Fast;
use Log::Async;
logger.untapped-ok = True;
plan 7;
subtest 'Basic Session Creation' => {
plan 4;
my $session = AI::Gator::Session.new;
isa-ok $session, AI::Gator::Session, 'Session created successfully';
is $session.messages.elems, 0, 'Session starts with no messages';
is $session.tool-calls.elems, 0, 'Session starts with no tool calls';
is $session.last-finish-reason, '', 'Session starts with empty finish reason';
}
subtest 'Message Management' => {
plan 6;
my $session = AI::Gator::Session.new;
# Test basic message addition
$session.add-message('Hello, world!');
is $session.messages.elems, 1, 'Message added successfully';
is $session.messages[0]<role>, 'user', 'Default role is user';
is $session.messages[0]<content>, 'Hello, world!', 'Content stored correctly';
# Test message with custom role
$session.add-message('Hello back!', :role<assistant>);
is $session.messages.elems, 2, 'Second message added';
is $session.messages[1]<role>, 'assistant', 'Custom role set correctly';
# Test message with additional args
$session.add-message(:role<system>, :custom-arg<value>);
is $session.messages[2]<custom-arg>, 'value', 'Additional args preserved';
}
subtest 'Tool Call Management' => {
plan 5;
my $session = AI::Gator::Session.new;
# Add a tool call
my %tool-call = name => 'test_function', arguments => '{"param": "value"}', id => 'call_123';
$session.add-tool-call(%tool-call);
is $session.tool-calls.elems, 1, 'Tool call added';
ok $session.has-pending-tool-calls, 'Has pending tool calls';
is $session.tool-calls[0]<name>, 'test_function', 'Tool call name preserved';
# Clear tool calls
$session.clear-tool-calls;
is $session.tool-calls.elems, 0, 'Tool calls cleared';
nok $session.has-pending-tool-calls, 'No pending tool calls after clear';
}
subtest 'with-message Method' => {
plan 3;
my $session = AI::Gator::Session.new;
$session.add-message('First message');
my @messages = $session.with-message('Temporary message');
is @messages.elems, 2, 'with-message returns original + new message';
is @messages[1]<content>, 'Temporary message', 'New message content correct';
is $session.messages.elems, 1, 'Original session unchanged';
}
subtest 'Session File Handling' => {
plan 3;
# Test with custom session directory
my $temp-dir = $*TMPDIR.child('test-gator-sessions');
my $session = AI::Gator::Session.new(:session-dir($temp-dir));
isa-ok $session.session-dir, IO::Path, 'Session directory is IO::Path';
isa-ok $session.session-file, IO::Path, 'Session file is IO::Path';
ok $session.session-file.dirname.contains('test-gator-sessions'), 'Session file in correct directory';
# Cleanup
$temp-dir.rmdir if $temp-dir.d;
}
subtest 'Session Saving' => {
plan 5;
my $temp-dir = $*TMPDIR.child('test-gator-save');
mkdir $temp-dir unless $temp-dir.d;
my $session-file = $temp-dir.child('test-session.json');
my $session = AI::Gator::Session.new(:$session-file);
$session.add-message('Test message');
lives-ok { $session.save(:summary('Test summary')) }, 'Session saves without error';
ok $session-file.e, 'Session file created';
# Verify content
if $session-file.e {
my $content = from-json($session-file.slurp);
is $content<messages>.elems, 1, 'Message saved correctly';
is $content<summary>, 'Test summary', 'Summary saved correctly';
ok $content<timestamp>, 'Timestamp saved';
# Cleanup
$session-file.unlink;
}
$temp-dir.rmdir if $temp-dir.d;
}
subtest 'Gemini Session Tests' => {
plan 4;
my $session = AI::Gator::Session::Gemini.new;
isa-ok $session, AI::Gator::Session::Gemini, 'Gemini session created';
# Test Gemini-specific message format
$session.add-message('Hello Gemini');
is $session.messages[0]<parts>[0]<text>, 'Hello Gemini', 'Gemini message format correct';
ok $session.messages[0]<parts>, 'Parts array exists';
# Test with-message for Gemini
my @messages = $session.with-message('Test message');
is @messages[*-1]<parts>[0]<text>, 'Test message', 'Gemini with-message format correct';
}
done-testing;
|
### ----------------------------------------------------
### -- AI::Gator
### -- Licenses: MIT
### -- Authors: Brian Duggan
### -- File: t/03-integration.rakutest
### ----------------------------------------------------
#!/usr/bin/env raku
use Test;
use AI::Gator;
use AI::Gator::Session;
use JSON::Fast;
use Log::Async;
logger.untapped-ok = True;
plan 6;
# Mock HTTP client for integration testing
class IntegrationMockHTTP {
has @.call-log;
has %.stream-responses;
method post($url, *%args) {
@!call-log.push: %( type => 'post', :$url, |%args );
# Simulate different API responses based on URL
if $url.contains('chat/completions') {
return %(
success => True,
content => to-json(%(
choices => [%(
message => %(
content => 'This is a test response from the AI.'
)
)]
)).encode
);
}
return %( success => True, content => '{"status": "ok"}'.encode );
}
method post-stream($url, *%args) {
@!call-log.push: %( type => 'stream', :$url, |%args );
# Return a supply that emits SSE-formatted data
return supply {
emit 'data: {"choices":[{"delta":{"content":"Hello"}}]}'.encode;
emit "\n".encode;
emit 'data: {"choices":[{"delta":{"content":" world"}}]}'.encode;
emit "\n".encode;
emit 'data: {"choices":[{"finish_reason":"stop"}]}'.encode;
emit "\n".encode;
emit 'data: [DONE]'.encode;
emit "\n".encode;
}
}
}
subtest 'Complete Conversation Flow' => {
plan 4;
my $mock-http = IntegrationMockHTTP.new;
my $gator = AI::Gator.new(:model<gpt-3.5-turbo>, :ua($mock-http));
my $session = AI::Gator::Session.new;
# Add initial message
$session.add-message('Hello, AI!');
# Test chat-once (non-streaming)
my $response = $gator.chat-once($session);
is $response, 'This is a test response from the AI.', 'Non-streaming chat works';
# Verify the HTTP call was made correctly
is $mock-http.call-log.elems, 1, 'One HTTP call made';
is $mock-http.call-log[0]<type>, 'post', 'Call was a POST request';
ok $mock-http.call-log[0]<url>.contains('chat/completions'), 'Called chat completions endpoint';
}
subtest 'Tool Integration Workflow' => {
plan 6;
my $tool-called = False;
my $tool-args;
my @tools = ( %(
spec => %(
function => %(
name => 'calculator',
description => 'Performs basic math operations',
parameters => %(
type => 'object',
properties => %(
operation => %( type => 'string' ),
a => %( type => 'number' ),
b => %( type => 'number' )
)
)
)
),
func => sub (:$operation, :$a, :$b) {
$tool-called = True;
$tool-args = %( :$operation, :$a, :$b );
given $operation {
when 'add' { $a + $b }
when 'multiply' { $a * $b }
default { 'Unknown operation' }
}
}
), );
my $gator = AI::Gator.new(:model<test>, :@tools);
my $session = AI::Gator::Session.new;
# Simulate receiving a tool call
$session.add-tool-call(%(
id => 'call_abc123',
name => 'calculator',
arguments => to-json(%( operation => 'add', a => 5, b => 3 ))
));
# Capture output
my $captured-output = '';
$gator.^find_method('output').wrap: -> $self, $text { $captured-output ~= $text };
# Execute tool calls
$gator.do-tool-calls($session);
ok $tool-called, 'Tool function was called';
is $tool-args<operation>, 'add', 'Tool received correct operation';
is $tool-args<a>, 5, 'Tool received correct first argument';
is $tool-args<b>, 3, 'Tool received correct second argument';
# Check that messages were added to session
is $session.messages.elems, 2, 'Two messages added (tool call + response)';
is $session.messages[1]<role>, 'tool', 'Second message is tool response';
}
subtest 'Session Persistence Integration' => {
plan 4;
my $temp-dir = $*TMPDIR.child('integration-test-sessions');
mkdir $temp-dir unless $temp-dir.d;
# Create session with conversation
my $session = AI::Gator::Session.new(:session-dir($temp-dir));
$session.add-message('What is the weather?');
$session.add-message('It is sunny today.', :role<assistant>);
# Save session
$session.save(:summary('Weather inquiry'));
ok $session.session-file.e, 'Session file was created';
# Load and verify session content
my $saved-data = from-json($session.session-file.slurp);
is $saved-data<messages>.elems, 2, 'Both messages saved';
is $saved-data<summary>, 'Weather inquiry', 'Summary saved correctly';
ok $saved-data<timestamp>, 'Timestamp recorded';
# Cleanup
$session.session-file.unlink if $session.session-file.e;
$temp-dir.rmdir if $temp-dir.d;
}
subtest 'Gemini Integration Differences' => {
plan 5;
%*ENV<GEMINI_API_KEY> = 'test-gemini-key';
my $gemini = AI::Gator::Gemini.new(:model<gemini-pro>);
my $session = AI::Gator::Session::Gemini.new;
# Test message format differences
$session.add-message('Hello Gemini');
is $session.messages[0]<role>, 'user', 'Gemini session uses correct role';
ok $session.messages[0]<parts>, 'Gemini message has parts structure';
is $session.messages[0]<parts>[0]<text>, 'Hello Gemini', 'Text content in parts';
# Test tool call format
my %tool-call = name => 'test_tool', args => %( param => 'value' );
$gemini.add-tool-call-message($session, %tool-call);
is $session.messages[1]<role>, 'model', 'Gemini tool call uses model role';
ok $session.messages[1]<parts>[0]<functionCall>, 'Function call structure present';
}
subtest 'Streaming Response Integration' => {
plan 3;
my $mock-http = IntegrationMockHTTP.new;
my $gator = AI::Gator.new(:model<test>, :ua($mock-http));
my $session = AI::Gator::Session.new;
$session.add-message('Stream test');
# Test streaming supply creation
my $stream = $gator.chat-stream($session);
isa-ok $stream, Supply, 'Chat stream returns Supply';
# Test that stream processing works
my $byte-stream = supply { emit "test data\n".encode };
my $processed = $gator.process-byte-stream($byte-stream, $session);
isa-ok $processed, Supply, 'Byte stream processing returns Supply';
# Verify streaming endpoint was called
react whenever $stream { last }
is $mock-http.call-log.elems, 1, 'Streaming endpoint called';
}
subtest 'Memory and State Management' => {
plan 4;
my $gator = AI::Gator.new(:model<test>);
my $session = AI::Gator::Session.new;
# Test that session maintains state across operations
$session.add-message('First message');
$session.add-message('Second message', :role<assistant>);
# Test finish reason tracking
$session.last-finish-reason = 'stop';
is $session.last-finish-reason, 'stop', 'Finish reason tracked correctly';
# Test tool call state management
$session.add-tool-call(%( id => 'call_1', name => 'test', arguments => '{}' ));
ok $session.has-pending-tool-calls, 'Pending tool calls tracked';
$session.clear-tool-calls;
nok $session.has-pending-tool-calls, 'Tool calls cleared correctly';
# Test message count persistence
is $session.messages.elems, 2, 'Message count maintained throughout operations';
}
done-testing;
|
### ----------------------------------------------------
### -- AI::Gator
### -- Licenses: MIT
### -- Authors: Brian Duggan
### -- File: t/02-gator.rakutest
### ----------------------------------------------------
#!/usr/bin/env raku
use Test;
use AI::Gator;
use AI::Gator::Session;
use JSON::Fast;
use Log::Async;
logger.untapped-ok = True;
plan 14;
# Mock HTTP::Tiny for testing
class MockHTTPTiny {
has %.responses;
has @.requests;
method post($url, *%args) {
@!requests.push: %( :$url, |%args );
return %.responses{$url} // %( success => True, content => '{"test": "response"}'.encode );
}
}
subtest 'Basic Gator Creation' => {
plan 4;
my $gator = AI::Gator.new(:model<gpt-3.5-turbo>);
isa-ok $gator, AI::Gator, 'Gator created successfully';
is $gator.model, 'gpt-3.5-turbo', 'Model set correctly';
is $gator.base-uri, 'https://api.openai.com/v1', 'Base URI set to OpenAI';
isa-ok $gator.toolbox, Supplier, 'Toolbox is a Supplier';
}
subtest 'Tool Management' => {
plan 4;
my @tools = [
%{
spec => %{
function => %{
name => 'test_tool',
description => 'A test tool'
}
},
func => sub { 'tool result' }
},
];
my $gator = AI::Gator.new(:model<test>, :@tools);
is $gator.tools.elems, 1, 'Tool added to gator';
is $gator.tool-funcs.keys.elems, 1, 'Tool function registered';
ok $gator.tool-funcs<test_tool>, 'Tool function accessible by name';
is $gator.tool-funcs<test_tool>(), 'tool result', 'Tool function works correctly';
}
subtest 'HTTP POST Method' => {
plan 3;
my $mock-ua = MockHTTPTiny.new;
$mock-ua.responses<test-url> = %( success => True, content => '{"result": "success"}'.encode );
my $gator = AI::Gator.new(:model<test>, :ua($mock-ua));
my $result = $gator.post('test-url', %( test => 'data' ));
is $result, '{"result": "success"}', 'POST returns correct content';
is $mock-ua.requests.elems, 1, 'One request made';
is $mock-ua.requests[0]<url>, 'test-url', 'Correct URL called';
}
subtest 'HTTP POST Error Handling' => {
plan 1;
my $mock-ua = MockHTTPTiny.new;
$mock-ua.responses<error-url> = %( success => False, status => 404, reason => 'Not Found', content => 'Not found'.encode );
my $gator = AI::Gator.new(:model<test>, :ua($mock-ua));
throws-like { $gator.post('error-url', %()) }, Exception, 'POST throws on HTTP error';
}
subtest 'Chat Once Method' => {
plan 2;
my $mock-ua = MockHTTPTiny.new;
my $response = %{
choices => [
%{ message => %{ content => 'Hello, I am an AI assistant.' } }
]
};
$mock-ua.responses<https://api.openai.com/v1/chat/completions> = %(
success => True,
content => to-json($response).encode
);
my $gator = AI::Gator.new(:model<gpt-3.5-turbo>, :ua($mock-ua));
my $session = AI::Gator::Session.new;
$session.add-message('Hello');
my $result = $gator.chat-once($session);
is $result, 'Hello, I am an AI assistant.', 'Chat-once returns correct content';
is $mock-ua.requests.elems, 1, 'One request made to OpenAI';
}
subtest 'Session Message Addition' => {
plan 5;
my $gator = AI::Gator.new(:model<test>);
my $session = AI::Gator::Session.new;
# Test tool call message addition
my %call = id => 'call_123', name => 'test_function', arguments => '{"param": "value"}';
$gator.add-tool-call-message($session, %call);
is $session.messages.elems, 1, 'Tool call message added';
is $session.messages[0]<role>, 'assistant', 'Tool call message has assistant role';
ok $session.messages[0]<tool_calls>, 'Tool calls array exists';
is $session.messages[0]<tool_calls>[0]<id>, 'call_123', 'Tool call ID preserved';
# Test tool response addition
$gator.add-tool-response($session, :tool_call_id<call_123>, :tool-response<result>, :name<test_function>);
is $session.messages.elems, 2, 'Tool response message added';
}
subtest 'Tool Call Execution' => {
plan 4;
my @tools = [
%{
spec => %{
function => %{
name => 'add_numbers',
description => 'Adds two numbers'
}
},
func => sub ($a, $b) { $a + $b }
}
];
my $gator = AI::Gator.new(:model<test>, :@tools);
my $session = AI::Gator::Session.new;
# Simulate a tool call
$session.add-tool-call(%( id => 'call_123', name => 'add_numbers', arguments => '{"a": 5, "b": 3}' ));
# Capture output
my $output-captured = '';
my $original-output = $gator.can('output')[0];
$gator.^find_method('output').wrap: -> $self, $text { $output-captured ~= $text };
$gator.do-tool-calls($session);
is $session.messages.elems, 2, 'Tool call and response messages added';
ok $output-captured.contains('add_numbers'), 'Tool name appears in output';
ok $output-captured.contains('done'), 'Completion message appears in output';
nok $session.has-pending-tool-calls, 'Tool calls cleared after execution';
}
subtest 'Tool Call Error Handling' => {
plan 2;
my @tools = [
%{
spec => %{
function => %{
name => 'failing_tool',
description => 'A tool that fails'
}
},
func => sub { die 'Tool failed!' }
}
];
my $gator = AI::Gator.new(:model<test>, :@tools);
my $session = AI::Gator::Session.new;
$session.add-tool-call(%( id => 'call_123', name => 'failing_tool', arguments => '{}' ));
# Capture output to suppress it during test
my $output-captured = '';
$gator.^find_method('output').wrap: -> $self, $text { $output-captured ~= $text };
lives-ok { $gator.do-tool-calls($session) }, 'Tool call failure handled gracefully';
# Check that error response was added
my $tool-response-msg = $session.messages.grep({ .<role> eq 'tool' })[0];
ok $tool-response-msg<content>.starts-with('Error:'), 'Error message recorded in tool response';
}
subtest 'Gemini Gator Creation' => {
plan 3;
%*ENV<GEMINI_API_KEY> = 'test-key';
my $gemini = AI::Gator::Gemini.new(:model<gemini-pro>);
isa-ok $gemini, AI::Gator::Gemini, 'Gemini gator created';
ok $gemini.base-uri.contains('googleapis.com'), 'Gemini base URI set correctly';
is $gemini.key, 'test-key', 'API key from environment';
}
subtest 'Gemini Tool Call Message Format' => {
plan 3;
my $gemini = AI::Gator::Gemini.new(:model<test>);
my $session = AI::Gator::Session::Gemini.new;
my %call = name => 'test_function', args => %( param => 'value' );
$gemini.add-tool-call-message($session, %call);
is $session.messages.elems, 1, 'Gemini tool call message added';
is $session.messages[0]<role>, 'model', 'Gemini uses model role for tool calls';
ok $session.messages[0]<parts>[0]<functionCall>, 'Function call structure present';
}
subtest 'Gemini Tool Response Format' => {
plan 3;
my $gemini = AI::Gator::Gemini.new(:model<test>);
my $session = AI::Gator::Session::Gemini.new;
$gemini.add-tool-response($session, :tool_call_id<call_123>, :tool-response<result>, :name<test_function>);
is $session.messages.elems, 1, 'Gemini tool response message added';
is $session.messages[0]<role>, 'function', 'Gemini uses function role for responses';
ok $session.messages[0]<parts>[0]<functionResponse>, 'Function response structure present';
}
subtest 'Summarize Method' => {
plan 1;
my $mock-ua = MockHTTPTiny.new;
my $response = %{
choices => [
%{ message => %{ content => 'Brief conversation summary' } }
]
};
$mock-ua.responses<https://api.openai.com/v1/chat/completions> = %(
success => True,
content => to-json($response).encode
);
my $gator = AI::Gator.new(:model<test>, :ua($mock-ua));
my $session = AI::Gator::Session.new;
# Note: summarize calls chat-once internally, so we test the method exists and doesn't crash
lives-ok { $gator.summarize($session) }, 'Summarize method executes without error';
}
subtest 'Stream Processing' => {
plan 2;
my $gator = AI::Gator.new(:model<test>);
# Test byte stream processing
my $test-supply = supply {
emit "data: chunk1\n".encode;
emit "data: chunk2\n".encode;
done;
}
my $session = AI::Gator::Session.new;
isa-ok $gator.process-byte-stream($test-supply, $session), Supply, 'process-byte-stream returns Supply';
# Test post-stream method signature
my $mock-ua = MockHTTPTiny.new;
$gator = AI::Gator.new(:model<test>, :ua($mock-ua));
isa-ok $gator.post-stream('test-url', %()), Supply, 'post-stream returns Supply';
}
subtest 'Tool Builder Method' => {
plan 1;
my $gator = AI::Gator.new(:model<test>);
my $session = AI::Gator::Session.new;
# Test that tool-builder method exists and can be called
lives-ok { start $gator.tool-builder($session) }, 'Tool builder method executes';
}
done-testing;
|
### ----------------------------------------------------
### -- AI::Gator
### -- Licenses: MIT
### -- Authors: Brian Duggan
### -- File: t/00-load.rakutest
### ----------------------------------------------------
#!raku
use Test;
plan 1;
use-ok 'AI::Gator';
|
### ----------------------------------------------------
### -- AI::Gator
### -- Licenses: MIT
### -- Authors: Brian Duggan
### -- File: lib/AI/Gator.rakumod
### ----------------------------------------------------
use AI::Gator::Session;
use AI::Gator::ToolBuilder;
use Log::Async;
use Terminal::ANSI::OO 't';
use HTTP::Tiny;
use JSON::Fast;
logger.untapped-ok = True;
# Base class, which is OpenAI-compatible.
class AI::Gator {
has $.toolbox = Supplier.new;
has $.ua = HTTP::Tiny.new;
has Str $.model;
has @.tools;
has %.tool-funcs;
has Supply $.tools-supply;
has $.base-uri = 'https://api.openai.com/v1';
has Bool $.quiet = False;
submethod TWEAK {
$!tools-supply = $!toolbox.Supply;
for @!tools -> $tool is rw {
# if it's a function, build the spec and store it
if $tool ~~ Callable {
my $spec = build-tool($tool);
$tool = { spec => $spec, func => $tool };
}
trace "tool :" ~ to-json $tool<spec>;
my $name = $tool<spec><function><name>;
my $func = $tool<func>;
next unless defined $name;
%!tool-funcs{$name} = $func;
}
}
method post(Str $url!, %content!, %more-headers = %( ) --> Str) {
debug "POST $url";
trace "POST $url with content: " ~ to-json %content;
my %headers = 'Content-Type' => 'application/json';
%headers.append: %more-headers if %more-headers;
my $content = to-json %content;
my $res = $.ua.post: $url, :$content, :%headers;
die "http error ({$res<status reason>}): " ~ ($res<content>.?decode // '') unless $res<success>;
$res<content>.decode;
}
method post-stream(Str $url!, Hash $payload!, %more-headers = %( ) --> Supply) {
my %headers = 'Content-Type' => 'application/json';
%headers.append: %more-headers if %more-headers;
supply {
my $errs is default('');
my $content = to-json $payload;
debug "POST (async) $url with content: " ~ $content;
my $res = $.ua.post: $url, :$content, :%headers,
data-callback => sub ( $blob, $state ) {
trace "received data $state<status reason> bytes=" ~ $blob.elems ~ " data=" ~ $blob.decode;
emit $blob;
$errs ~= $blob.decode;
}
die "http error ({$res<status reason>}): $errs" unless $res<success>;
done;
}
}
method tool-builder($session) {
my %call-me;
# Arguments are sent in fragments of json, so we have to assemble them.
react whenever self.tools-supply -> $tool {
for $tool.list -> $t {
if $t<id> && %call-me<id> && ($t<id> ne %call-me<id>) {
debug "adding tool call " ~ to-json %call-me;
$session.add-tool-call(%call-me.clone);
%call-me<arguments> = "";
}
%call-me<index> = $_ with $t<index>;
%call-me<id> = $_ with $t<id>;
%call-me<name> = $_ with $t<function><name>;
%call-me<arguments> ~= $_ with $t<function><arguments>;
}
}
debug "adding tool call " ~ to-json %call-me if %call-me<id>;
$session.add-tool-call(%call-me) if %call-me<id>;
}
method output($text) {
print $text unless $!quiet;
}
# Display a streaming response and also emit tool calls as they come in.
method get-response($session --> Str) {
my $tool-promise = start self.tool-builder($session);
my $response is default('');
my $printed = 0;
react whenever self.chat($session) -> $chunk {
self.output(t.yellow ~ "Gator: " ~ t.text-reset) if $chunk.chars > 0 && !($printed++);
self.output: $chunk;
$response ~= $chunk;
}
put "" if $response.trim.chars && !$response.ends-with("\n");
await $tool-promise;
return $response.trim;
}
method summarize($session --> Str) {
my $response;
my @messages = $session.with-message: 'Make a very brief description of the conversation -- no more than 40 characters.';
self.chat-once($session, :@messages);
}
method chat-once($session, :@messages = $session.messages --> Str) {
my %more-headers;
%more-headers<Authorization> = "Bearer $_" with %*ENV<OPENAI_API_KEY>;
return self.post("{ $.base-uri }/chat/completions",
%( :$.model, :@messages, :tools(@.tools.map(*<spec>)) ),
%more-headers
).&from-json<choices>[0]<message><content>;
}
method chat-stream($session, :@messages = $session.messages --> Supply) {
my %more-headers;
%more-headers<Authorization> = "Bearer $_" with %*ENV<OPENAI_API_KEY>;
return self.post-stream: "{ $.base-uri }/chat/completions",
%( :stream, :$.model, :@messages, :tools(@.tools.map(*<spec>)) ),
%more-headers;
}
method process-byte-stream(Supply $byte-stream, $session --> Supply) {
my $buffer;
supply whenever $byte-stream.map(*.decode) {
$buffer ~= $_;
if $buffer.contains("\n") {
$buffer.emit;
$buffer = ''
}
}
}
method chat(AI::Gator::Session $session) {
debug "chatting with model { $.model }";
my $byte-stream = self.chat-stream($session);
my $json-stream = self.process-byte-stream: $byte-stream, $session;
supply whenever $json-stream.lines {
done when /data \s* ':' \s* '[DONE]' /;
when /data ':' (.*)/ {
my $data = try from-json $0 or fail "failed to parse json: $0";
given $data<choices>[0] {
with .<finish_reason> {
$session.last-finish-reason = $_;
$.toolbox.done;
done if $_ eq 'stop';
}
given .<delta> {
.emit with .<content>; # text
$.toolbox.emit: $_ with .<tool_calls>; # tool call
}
}
}
}
}
method add-tool-call-message($session,%call) {
$session.add-message: :role<assistant>, tool_calls => [ {
id => %call<id>, type => 'function',
function => { name => %call<name>, arguments => %call<arguments> }
},
];
}
method add-tool-response($session, :$tool_call_id, :$tool-response, :$name) {
$session.add-message: :role<tool>, :$tool_call_id, :content($tool-response);
}
method do-tool-calls($session) {
return unless $session.has-pending-tool-calls;
debug "number of tool calls: " ~ $session.tool-calls.elems;
for $session.tool-calls.list -> %call-me {
debug "adding tool call " ~ %call-me.raku;
my $arg-summary = %call-me<arguments>.Str;
if $arg-summary.chars > 40 {
$arg-summary = %call-me<arguments>.Str.substr(0, 40) ~ '...';
}
self.output: t.cyan ~ "[tool]" ~ t.text-reset ~ ' ' ~ %call-me<name> ~ t.color('#8888ff') ~ ' ' ~ $arg-summary;
self.add-tool-call-message($session,%call-me);
my $args = %call-me<arguments>;
$args = (try from-json( $args ) ) if $args ~~ Str;
die "failed to parse tool call arguments: { %call-me<arguments>.raku }" without $args;
my $callback = self.tool-funcs{ %call-me<name> };
my Str $tool-response = ( (try $callback(|$args)) // '').Str;
if $! {
$tool-response = "Error: {$!}";
my $name = %call-me<name>;
warning "tool call failed: $name: {$!}";
}
debug "tool response: $tool-response";
self.add-tool-response: $session, tool_call_id => %call-me<id>, :$tool-response, name => %call-me<name>;
self.output: t.cyan ~ "\n[tool]" ~ t.text-reset ~ ' ' ~ %call-me<name> ~ ' done' ~ "\n"
}
$session.clear-tool-calls;
debug "done with tool calls";
}
}
class AI::Gator::Gemini is AI::Gator {
has $.base-uri = 'https://generativelanguage.googleapis.com/v1beta/models';
has $.key = %*ENV<GEMINI_API_KEY>;
method chat-once($session, :@messages = $session.messages --> Str) {
return self.post: "{ $.base-uri }/{ $.model }:generateContent?key={ $.key }", %(
:contents(@messages),
|(@.tools ?? { tools => [ { functionDeclarations => @.tools.map(*<spec><function>) } ] } !! {})
);
}
method chat-stream($session, :@messages = $session.messages --> Supply) {
return self.post-stream: "{ $.base-uri }/{ $.model }:streamGenerateContent?key={ $.key }", %(
:contents(@messages),
|(@.tools ?? { tools => [ { functionDeclarations => @.tools.map(*<spec><function>) } ] } !! {})
)
}
method chat(AI::Gator::Session $session) {
my $byte-stream = self.chat-stream($session);
supply whenever $byte-stream.map(*.decode) -> $data {
my $json-data = (try from-json $data)
// (try from-json $data ~ ']')
// (try from-json $data.subst( /^^ [',' | ']'] $$/ ,''));
if $json-data ~~ List {
$json-data = $json-data[0]
}
unless $json-data ~~ Hash && $json-data<candidates> {
error "data was $data " ~ $json-data.raku;
die "data was not a valid Gemini response";
}
for $json-data<candidates>.list -> $candidate {
given $candidate {
with .<content><parts> {
for .list -> $part {
trace "gemini response part: " ~ to-json $part;
.emit with $part<text>;
with $part<functionCall> {
$.toolbox.emit: $_
}
}
}
with .<finishReason> {
$session.last-finish-reason = $_ eq 'TOOL_CALLS' ?? 'tool_calls' !! $_;
$.toolbox.done if $_ eq 'STOP';
done if $_ eq 'STOP';
}
}
}
}
}
method tool-builder($session) {
react whenever self.tools-supply -> $tool {
debug "building gemini tool :" ~ to-json $tool;
$session.add-tool-call(%( name => $tool<name>, arguments => $tool<args> ));
}
}
method add-tool-call-message($session,%call) {
$session.add-message: :role<model>, parts => [ {
functionCall => { name => %call<name>, args => %call<args> } }, ];
}
method add-tool-response($session, :$tool_call_id, :$tool-response, :$name) {
$session.add-message: :role<function>, parts => [ {
functionResponse => { :$name, response => { content => $tool-response } }
}, ];
}
}
=begin pod
=head1 NAME
AI::Gator - Ailigator -- your AI Generic Assistant with a Tool-Oriented REPL
<img src="https://github.com/user-attachments/assets/0e71fb98-e149-483a-8654-300316e413e8" alt="ailigator" width="300">
=head1 SYNOPSIS
Put this into $HOME/ai-gator/tools/weather.raku:
#| Get real time weather for a given city
our sub get_weather(
Str :$city! #= The city to get the weather for
) {
"The weather in $city is sunny.";
}
Then start the AI Gator REPL:
$ ai-gator
You: Is it raining in Toledo?
[tool] get_weather city Toledo
[tool] get_weather done
Gator: No, it is not raining in Toledo. The weather is sunny.
You: What about Philadelphia or San Francisco?
[tool] get_weather city Philadelphia
[tool] get_weather done
[tool] get_weather city San Francisco
[tool] get_weather done
Gator: It is sunny in both Philadelphia and San Francisco.
For other options, run:
$ ai-gator -h
This module can also be used programmatically:
use AI::Gator;
my AI::Gator $gator = AI::Gator::Gemini.new: model => 'gemini-2.0-flash';
my AI::Gator::Session $session = AI::Gator::Session::Gemini.new;
$session.add-message: "Hello, Gator!";
react whenever $gator.chat($session) -> $chunk {
print $chunk;
}
# Hello! How can I help you today?
To use tools programmatically, here is an example:
use AI::Gator;
#| Get real time weather for a given city
sub get_weather(
Str :$city! #= The city to get the weather for
) {
"The weather in $city is sunny.";
}
my AI::Gator $gator = AI::Gator::Gemini.new:
model => 'gemini-2.0-flash',
:quiet,
tools => @( &get_weather, );
my AI::Gator::Session $session = AI::Gator::Session::Gemini.new;
$session.add-message: "Hello ailigator!";
react whenever $gator.chat($session) { .print }
# Hello! How can I help you today? 🐊
my $tool-promise = start $gator.tool-builder($session);
$session.add-message: "What is the weather in Paris?";
react whenever $gator.chat($session) { .print }
await $tool-promise;
$gator.do-tool-calls: $session;
react whenever $gator.chat($session) { .print }
# The weather in Paris is sunny.
=head1 DESCRIPTION
AI::Gator is an AI assistant oriented towards using tools and a REPL interface.
Features:
- streaming responses
- tool definitions in Raku
- tool calls
- session storage
- Gemini and OpenAI support
- REPL interface with history
Tools are defined as Raku functions and converted into an OpenAI or Gemini specification using
declarator pod and other native Raku features.
All sessions are stored in the sessions/ directory, and the REPL stores the history
in a .history file, readline-style.
=head1 COMMAND LINE OPTIONS
`ai-gator resume-last` will resume the last session, if it exists.
`ai-gator resume session-id` will resume the specified session.
`ai-gator sessions` will list all sessions.
Also in the REPL:
`\history` will show user + assistant commands
`\history all` will show all commands, including tool calls
`\history mine` will show just the user commands
`\inspect` will enter an interactive ui that shows all previous prompts and responses
=head1 CONFIGURATION
Set AI_GATOR_HOME to ai-gator's home (by default $HOME/ai-gator).
In this directory, the following files and directories are used:
- config.toml: configuration file
- tools/: directory with files containing tools
- sessions/: directory with session files (created by the REPL)
- .history: file with readline history (also created by the REPL)
=head1 CONFIGURATION FILE
Sample configuration to use Gemini:
model = "gemini-2.0-flash"
adapter = 'Gemini'
Sample configuration to use OpenAI:
model = "gpt-4o"
base-uri = "https://api.openai.com/v1"
=head1 ENVIRONMENT
- AI_GATOR_HOME: home directory for AI::Gator (default: $HOME/ai-gator)
- GEMINI_API_KEY: API key for Gemini (if using Gemini)
- OPENAI_API_KEY: API key for OpenAI (if using OpenAI)
=head1 NOTES
This is all pretty rough and experimental. Expect the api to change. Patches welcome!
=head1 AUTHOR
Brian Duggan
=end pod
|
### ----------------------------------------------------
### -- AI::Gator
### -- Licenses: MIT
### -- Authors: Brian Duggan
### -- File: lib/AI/Gator/ToolBuilder.rakumod
### ----------------------------------------------------
unit module AI::Gator::ToolBuilder;
use Log::Async;
sub build-tool(&func) is export {
my $sig = &func.signature;
my %properties;
my @required;
my $where = 'function ' ~ &func.name ~ ' on line ' ~ &func.line;
debug "loading function $where";
for $sig.params.list -> $param {
my $name = $param.name.subst('$', '');
my $description = $param.WHY.Str.?trim || die "No description found for parameter $name ($where)";
%properties{$name} = {
type => $param.does(Numeric) ?? 'number' !! 'string',
description => ~$param.WHY
};
@required.push($name) if ($param.suffix // '') eq '!';
}
my $description = &func.WHY.Str.trim;
without $description {
note "Missing description for { &func.name } at line { &func.line }";
exit;
}
return {
type => 'function',
function => {
name => &func.name,
:$description,
parameters => {
type => 'object',
properties => %properties,
required => @required
}
}
}
}
|
### ----------------------------------------------------
### -- AI::Gator
### -- Licenses: MIT
### -- Authors: Brian Duggan
### -- File: lib/AI/Gator/Tools.rakumod
### ----------------------------------------------------
unit module AI::Gator::Tools;
use Log::Async;
use AI::Gator::ToolBuilder;
our @TOOLS;
sub get-tools is export {
unless $*tool-dir.IO.d {
warning "Could not find directory $*tool-dir";
return [];
}
return @TOOLS if @TOOLS.elems > 0;
for $*tool-dir.dir(test => { .ends-with('.raku') }) -> $file {
info "Loading tools from $file";
my $code = $file.slurp;
try $code.EVAL;
if $! {
error "Failed to load tools from $file: $!";
next;
}
debug "successfully processed $file";
}
my @names = (OUR::.keys).grep: { .Str ne 'EXPORT' | '@TOOLS' }
@TOOLS = @names.sort.map: {
%( spec => build-tool( OUR::{$_} ), func => OUR::{$_} )
}
return @TOOLS;
}
sub lookup-tool(Str $name) is export {
get-tools.first: {
.<spec><function><name> eq $name
}
}
sub get-tool-spec(Str $name) is export {
lookup-tool($name)<spec>;
}
sub get-tool(Str $name) is export {
lookup-tool($name)<func>;
}
|
### ----------------------------------------------------
### -- AI::Gator
### -- Licenses: MIT
### -- Authors: Brian Duggan
### -- File: lib/AI/Gator/Session.rakumod
### ----------------------------------------------------
#!raku
use Log::Async;
use JSON::Fast;
class AI::Gator::Session {
has @.messages;
has @.tool-calls;
has $.last-finish-reason is rw is default('');
has IO::Path $.session-dir;
has IO::Path $.session-file;
method TWEAK {
with $!session-dir {
.d or mkdir $_;
} else {
unless $!session-file {
my $default = $*HOME.child('ai-gator').child('sessions');
debug "writing sessions to $default";
$!session-dir = $default;
}
}
$!session-file //= $!session-dir.child(now.Rat ~ '.json');
}
multi method add-message($content, :$role = 'user', *%args) {
@!messages.push: { :$role, :$content, |%args };
}
multi method add-message(:$role = 'user', *%args) {
@!messages.push: { :$role, |%args };
}
method add-tool-call(%args) {
@!tool-calls.push: %args.deepmap: { $_ }
}
method clear-tool-calls {
@!tool-calls := [];
}
method has-pending-tool-calls {
return @!tool-calls.elems > 0;
}
method save(:$summary) {
info "saving session to {$!session-file}";
info "summary: {$summary}" if $summary;
$!session-file.spurt: to-json %( :@!messages, :$summary, timestamp => DateTime.now.Str );
}
multi method with-message($content, :$role = 'user', *%args) {
my @messages = @.messages;
@messages.push: { :$role, :$content };
@messages;
}
multi method load(IO::Path $file) {
info "loading session from {$file}";
my $data = from-json $file.slurp;
@!messages := $data<messages>;
$.last-finish-reason = $data<last_finish_reason> // '';
$!session-file = $file;
info "loaded session with { @!messages.elems } messages";
return True;
}
method load-last-session(IO::Path $dir) {
my @files = $dir.dir(test => *.ends-with('.json'));
return unless @files;
return self.load: @files.sort({ .modified }).tail
}
method list-sessions(IO::Path $dir) {
my @files = $dir.dir(test => *.ends-with('.json'));
return unless @files;
@files.sort({ .modified }).map: {
my %h = from-json .slurp;
%h<filename> = ~$_;
%h;
}
}
}
class AI::Gator::Session::Gemini is AI::Gator::Session {
multi method add-message($content, :$role = 'user', *%args) {
@.messages.push: { :$role, parts => [ { text => $content }, ], |%args };
}
multi method with-message($content, :$role = 'user', *%args) {
my @messages = @.messages;
@messages.push: { :$role, parts => [ { text => $content }, ], |%args };
@messages;
}
}
|
### ----------------------------------------------------
### -- AI::Gator
### -- Licenses: MIT
### -- Authors: Brian Duggan
### -- File: eg/chat-tools.raku
### ----------------------------------------------------
use AI::Gator;
#| Get real time weather for a given city
sub get_weather(
Str :$city! #= The city to get the weather for
) {
"The weather in $city is sunny.";
}
my AI::Gator $gator = AI::Gator::Gemini.new:
model => 'gemini-2.0-flash',
:quiet,
tools => @( &get_weather, );
my AI::Gator::Session $session = AI::Gator::Session::Gemini.new;
$session.add-message: "Hello ailigator!";
react whenever $gator.chat($session) { .print }
# Hello! How can I help you today? 🐊
my $tool-promise = start $gator.tool-builder($session);
$session.add-message: "What is the weather in Paris?";
react whenever $gator.chat($session) { .print }
await $tool-promise;
$gator.do-tool-calls: $session;
react whenever $gator.chat($session) { .print }
# The weather in Paris is sunny.
|
### ----------------------------------------------------
### -- AI::Gator
### -- Licenses: MIT
### -- Authors: Brian Duggan
### -- File: eg/chat.raku
### ----------------------------------------------------
use AI::Gator;
my AI::Gator $gator = AI::Gator::Gemini.new: model => 'gemini-2.0-flash';
my AI::Gator::Session $session = AI::Gator::Session::Gemini.new;
$session.add-message: "Hello, Gator!";
react whenever $gator.chat($session) { .print }
# Hello! How can I help you today?
$session.add-message: "What is the capital of France?";
react whenever $gator.chat($session) { .print }
# The capital of France is Paris.
$session.add-message: "What is its population?";
react whenever $gator.chat($session) { .print }
|
### ----------------------------------------------------
### -- AI::Gator
### -- Licenses: MIT
### -- Authors: Brian Duggan
### -- File: eg/tools/weather.raku
### ----------------------------------------------------
#| Get real time weather for a given city
our sub get_weather(
Str :$city! #= The city to get the weather for
) {
"The weather in $city is sunny.";
}
|
### ----------------------------------------------------
### -- ANTLR4::Grammar
### -- Licenses: Artistic-2.0
### -- Authors: Jeffrey Goff <[email protected]>
### -- File: META6.json
### ----------------------------------------------------
{
"auth" : "github:drforr",
"authors" : [
"Jeffrey Goff <[email protected]>"
],
"build-depends" : [ ],
"depends" : [
"Test::META"
],
"description" : "Turn ANTLR4 Grammars into Perl 6 Grammars",
"license" : "Artistic-2.0",
"meta6" : "0",
"name" : "ANTLR4::Grammar",
"perl" : "6.c",
"provides" : {
"ANTLR4::Actions::Perl6" : "lib/ANTLR4/Actions/Perl6.pm6",
"ANTLR4::Grammar" : "lib/ANTLR4/Grammar.pm6",
"ANTLR4::Grammar::Parser" : "lib/ANTLR4/Grammar/Parser.pm6"
},
"resources" : [ ],
"source-url" : "https://github.com/drforr/perl6-ANTLR4.git",
"support" : {
"source" : "https://github.com/drforr/perl6-ANTLR4.git"
},
"tags" : [
"ANTLR",
"ANTLR4",
"Grammar",
"Transform",
"Languages",
"parse",
"parser",
"parsing"
],
"test-depends" : [
"Test",
"JSON::Tiny"
],
"version" : "0.6.2"
}
|
### ----------------------------------------------------
### -- ANTLR4::Grammar
### -- Licenses: Artistic-2.0
### -- Authors: Jeffrey Goff <[email protected]>
### -- File: README.md
### ----------------------------------------------------
ANTLR4
=======
ANTLR4 proides an ANTLR4 to Perl6 Grammar converter.
The grammar, AST and Perl6 bindings are provided as separate modules, so you can view both the raw abstract syntax tree and the final Perl6 converted output.
Installation
============
* Using panda (a module management tool bundled with Rakudo Star):
```
panda update && panda install ANTLR4
```
* Using ufo (a project Makefile creation script bundled with Rakudo Star) and make:
```
ufo
make
make test
make install
```
## Testing
To run tests:
```
prove -e perl6
```
## Author
Jeffrey Goff, DrFOrr on #perl6, https://github.com/drforr/
## License
Artistic License 2.0
|
### ----------------------------------------------------
### -- ANTLR4::Grammar
### -- Licenses: Artistic-2.0
### -- Authors: Jeffrey Goff <[email protected]>
### -- File: .travis.yml
### ----------------------------------------------------
language: perl6
sudo: true
perl6:
- latest
install:
- rakudobrew build-zef
- zef --debug --depsonly install .
|
### ----------------------------------------------------
### -- ANTLR4::Grammar
### -- Licenses: Artistic-2.0
### -- Authors: Jeffrey Goff <[email protected]>
### -- File: dist.ini
### ----------------------------------------------------
[ReadmeFromPod]
disable = true
|
### ----------------------------------------------------
### -- ANTLR4::Grammar
### -- Licenses: Artistic-2.0
### -- Authors: Jeffrey Goff <[email protected]>
### -- File: t/15-rule-modifiers.t
### ----------------------------------------------------
use v6;
use ANTLR4::Grammar;
use Test;
plan 5;
# XXX Please note that I've changed my mind a bit on how the out-of-band
# XXX signaling should work. You'll see here that I'm simply returning the
# XXX text that I get out of the parsed stream.
# XXX
# XXX This should get rid of a dependency down the road.
# XXX
#`{
is ANTLR4::Grammar.to-string( Q:to[END] ), Q:to[END], 'channel';
grammar Empty;
BLOCK_COMMENT : EOF -> channel(HIDDEN) ;
END
grammar Empty {
token BLOCK_COMMENT {
|| $
#|{channel(HIDDEN)}
}
}
END
}
is ANTLR4::Grammar.to-string( Q:to[END] ), Q:to[END], 'channel XXX PARTIALLY BROKEN';
grammar Empty;
BLOCK_COMMENT : EOF -> channel(HIDDEN) ;
END
grammar Empty {
token BLOCK_COMMENT {
|| $
}
}
END
#`{
is ANTLR4::Grammar.to-string( Q:to[END] ), Q:to[END], 'push';
grammar Empty;
BLOCK_COMMENT : ('0'..'9') -> pushMode(I) ;
END
grammar Empty {
token BLOCK_COMMENT {
|| ( || <[ 0 .. 9 ]>
#|{pushMode(I)}
)
}
}
END
}
is ANTLR4::Grammar.to-string( Q:to[END] ), Q:to[END], 'push XXX PARTIALLY BROKEN';
grammar Empty;
BLOCK_COMMENT : ('0'..'9') -> pushMode(I) ;
END
grammar Empty {
token BLOCK_COMMENT {
|| ( || <[ 0 .. 9 ]>
)
}
}
END
subtest 'token options', {
#`{
is ANTLR4::Grammar.to-string( Q:to[END] ), Q:to[END], 'single token with options';
grammar Empty;
fragment parametrized[String name, int total]
returns [int amount] throws XFoo options{I=1;} : ;
END
grammar Empty {
#|{fragment parametrized[String name, int total]}
token parametrized { #|{returns [int amount] throws XFoo options{I=1;}}
}
}
END
}
is ANTLR4::Grammar.to-string( Q:to[END] ), Q:to[END], 'single token with options XXX PARTIALLY BROKEN';
grammar Empty;
fragment parametrized[String name, int total]
returns [int amount] throws XFoo options{I=1;} : ;
END
grammar Empty {
token parametrized {
}
}
END
#`(
is ANTLR4::Grammar.to-string( Q:to[END] ), Q:to[END], 'single token with options';
grammar Empty;
public test_catch_locals locals[int n = 0] : ;
catch [int amount] {amount++} finally {amount=1}
END
grammar Empty {
token test_catch_locals { #|{locals[int n = 0]}
#|{catch [int amount] {amount++} finally {amount=1}}
}
}
END
)
is ANTLR4::Grammar.to-string( Q:to[END] ), Q:to[END], 'single token with options XXX PARTIALLY BROKEN';
grammar Empty;
public test_catch_locals locals[int n = 0] : ;
catch [int amount] {amount++} finally {amount=1}
END
grammar Empty {
token test_catch_locals {
}
}
END
done-testing;
};
is ANTLR4::Grammar.to-string( Q:to[END] ), Q:to[END], 'action';
grammar Lexer;
plain : {System.out.println("Found end");} ;
END
grammar Lexer {
token plain {
|| #|{System.out.println("Found end");}
}
}
END
subtest 'actions', {
#`(
is ANTLR4::Grammar.to-string( Q:to[END] ), Q:to[END], 'skip';
grammar Lexer;
plain : 'X' -> skip ;
END
grammar Lexer {
token plain {
|| 'X'
#|{skip}
}
}
END
)
is ANTLR4::Grammar.to-string( Q:to[END] ), Q:to[END], 'skip XXX PARTIALLY BROKEN';
grammar Lexer;
plain : 'X' -> skip ;
END
grammar Lexer {
token plain {
|| 'X'
}
}
END
#`(
is ANTLR4::Grammar.to-string( Q:to[END] ), Q:to[END], 'more';
grammar Lexer;
plain : 'X' -> more ;
END
grammar Lexer {
token plain {
|| 'X'
#|{more}
}
}
END
)
is ANTLR4::Grammar.to-string( Q:to[END] ), Q:to[END], 'more XXX PARTIALLY BROKEN';
grammar Lexer;
plain : 'X' -> more ;
END
grammar Lexer {
token plain {
|| 'X'
}
}
END
#`(
is ANTLR4::Grammar.to-string( Q:to[END] ), Q:to[END], 'type';
grammar Lexer;
plain : 'X' -> type(STRING) ;
END
grammar Lexer {
token plain {
|| 'X'
#|{type(STRING)}
}
}
END
)
is ANTLR4::Grammar.to-string( Q:to[END] ), Q:to[END], 'type XXX PARTIALLY BROKEN';
grammar Lexer;
plain : 'X' -> type(STRING) ;
END
grammar Lexer {
token plain {
|| 'X'
}
}
END
#`(
is ANTLR4::Grammar.to-string( Q:to[END] ), Q:to[END], 'channel';
grammar Lexer;
plain : 'X' -> channel(HIDDEN) ;
END
grammar Lexer {
token plain {
|| 'X'
#|{channel(HIDDEN)}
}
}
END
)
is ANTLR4::Grammar.to-string( Q:to[END] ), Q:to[END], 'channel XXX PARTIALLY BROKEN';
grammar Lexer;
plain : 'X' -> channel(HIDDEN) ;
END
grammar Lexer {
token plain {
|| 'X'
}
}
END
done-testing;
};
done-testing;
# vim: ft=perl6
|
### ----------------------------------------------------
### -- ANTLR4::Grammar
### -- Licenses: Artistic-2.0
### -- Authors: Jeffrey Goff <[email protected]>
### -- File: t/17-modes.t
### ----------------------------------------------------
use v6;
use ANTLR4::Grammar;
use Test;
plan 2;
# '-> more' &c are per-alternative, not at the rule level.
# '<assoc=right> are also per-alternative.
#
#`(
is ANTLR4::Grammar.to-string( Q:to[END] ), Q:to[END], 'single rule with options';
grammar Empty;
plain : ;
mode Remainder;
lexer_stuff : ;
mode SkipThis;
mode YetAnother;
parser_stuff : ;
END
grammar Empty {
token plain {
}
#|{ "mode" : "Remainder" }
token lexer_stuff {
||
}
#|{ "mode" : "SkipThis" }
#|{ "mode" : "YetAnother" }
token parser_stuff {
||
}
}
END
)
#`{
is ANTLR4::Grammar.to-string( Q:to[END] ), Q:to[END], 'single rule with options XXX PARTIALLY BROKEN';
grammar Empty;
plain : ;
mode Remainder;
lexer_stuff : ;
mode SkipThis;
mode YetAnother;
parser_stuff : ;
END
grammar Empty {
token plain {
}
token lexer_stuff {
||
}
token parser_stuff {
||
}
}
END
}
#`(
is ANTLR4::Grammar.to-string( Q:to[END] ), Q:to[END], 'pushMode';
grammar Lexer;
plain : 'X' -> pushMode(INSIDE) ;
END
grammar Lexer {
token plain {
|| 'X'
#|{pushMode(INSIDE)}
}
}
END
)
is ANTLR4::Grammar.to-string( Q:to[END] ), Q:to[END], 'pushMode XXX PARTIALLY BROKEN';
grammar Lexer;
plain : 'X' -> pushMode(INSIDE) ;
END
grammar Lexer {
token plain {
|| 'X'
}
}
END
#`(
is ANTLR4::Grammar.to-string( Q:to[END] ), Q:to[END], 'popMode';
grammar Lexer;
plain : 'X' -> popMode(INSIDE) ;
END
grammar Lexer {
token plain {
|| 'X'
#|{popMode(INSIDE)}
}
}
END
)
is ANTLR4::Grammar.to-string( Q:to[END] ), Q:to[END], 'popMode XXX PARTIALLY BROKEN';
grammar Lexer;
plain : 'X' -> popMode(INSIDE) ;
END
grammar Lexer {
token plain {
|| 'X'
}
}
END
done-testing;
# vim: ft=perl6
|
### ----------------------------------------------------
### -- ANTLR4::Grammar
### -- Licenses: Artistic-2.0
### -- Authors: Jeffrey Goff <[email protected]>
### -- File: t/01-parse.t
### ----------------------------------------------------
use v6;
use ANTLR4::Grammar::Parser;
use Test;
plan 1;
#############################################################################
my $csv-grammar = Q{/*
[The "BSD licence"]
Copyright (c) 2013 Terence Parr
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. The name of the author may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
grammar CSV;
file: hdr row+ ;
hdr : row ;
row : field (',' field)* '\r'? '\n' ;
field
: TEXT
| STRING
|
;
TEXT : ~[,\n\r"]+ ;
STRING : '"' ('""'|~'"')* '"' ; // quote-quote is an escaped quote
};
#############################################################################
my $p = ANTLR4::Grammar::Parser.new;
ok $p.parse( $csv-grammar );
# vim: ft=perl6
|
### ----------------------------------------------------
### -- ANTLR4::Grammar
### -- Licenses: Artistic-2.0
### -- Authors: Jeffrey Goff <[email protected]>
### -- File: t/12-alternation.t
### ----------------------------------------------------
use v6;
use ANTLR4::Grammar;
use Test;
plan 6;
is ANTLR4::Grammar.to-string( Q:to[END] ), Q:to[END], 'terminal-terminal';
grammar Lexer;
plain : 'terminal' | 'other' ;
END
grammar Lexer {
token plain {
|| 'terminal'
|| 'other'
}
}
END
is ANTLR4::Grammar.to-string( Q:to[END] ), Q:to[END], 'terminal-character range';
grammar Lexer;
plain : 'terminal' | 'a'..'z' ;
END
grammar Lexer {
token plain {
|| 'terminal'
|| <[ a .. z ]>
}
}
END
is ANTLR4::Grammar.to-string( Q:to[END] ), Q:to[END], 'terminal-character set';
grammar Lexer;
plain : 'terminal' | [by] ;
END
grammar Lexer {
token plain {
|| 'terminal'
|| <[ b y ]>
}
}
END
is ANTLR4::Grammar.to-string( Q:to[END] ), Q:to[END], 'terminal-negated subrule';
grammar Lexer;
plain : 'terminal' | ~('W') ;
END
grammar Lexer {
token plain {
|| 'terminal'
|| <-[ W ]>
}
}
END
is ANTLR4::Grammar.to-string( Q:to[END] ), Q:to[END], 'terminal-wildcard';
grammar Lexer;
plain : 'terminal' | . ;
END
grammar Lexer {
token plain {
|| 'terminal'
|| .
}
}
END
is ANTLR4::Grammar.to-string( Q:to[END] ), Q:to[END], 'terminal-nonterminal';
grammar Lexer;
plain : 'terminal' | Str ;
END
grammar Lexer {
token plain {
|| 'terminal'
|| <Str>
}
}
END
done-testing;
# vim: ft=perl6
|
### ----------------------------------------------------
### -- ANTLR4::Grammar
### -- Licenses: Artistic-2.0
### -- Authors: Jeffrey Goff <[email protected]>
### -- File: t/13-grouping.t
### ----------------------------------------------------
use v6;
use ANTLR4::Grammar;
use Test;
plan 9;
# No way to generate an empty token, otherwise it'd be here.
#
is ANTLR4::Grammar.to-string( Q:to[END] ), Q:to[END], 'empty rule';
grammar Empty;
empty : ( ) ;
END
grammar Empty {
token empty {
|| (
)
}
}
END
is ANTLR4::Grammar.to-string( Q:to[END] ), Q:to[END], 'empty fragment';
grammar Empty;
fragment empty : ( ) ;
END
grammar Empty {
token empty {
|| (
)
}
}
END
subtest 'modifiers', {
# a negated group is actually a negated character class, which
# we checked earlier.
#
is ANTLR4::Grammar.to-string( Q:to[END] ), Q:to[END], 'question';
grammar Empty;
empty : ( )? ;
END
grammar Empty {
token empty {
|| (
)?
}
}
END
is ANTLR4::Grammar.to-string( Q:to[END] ), Q:to[END], 'star';
grammar Empty;
empty : ( )* ;
END
grammar Empty {
token empty {
|| (
)*
}
}
END
is ANTLR4::Grammar.to-string( Q:to[END] ), Q:to[END], 'plus';
grammar Empty;
empty : ( )+ ;
END
grammar Empty {
token empty {
|| (
)+
}
}
END
done-testing;
};
subtest 'grouped thing', {
is ANTLR4::Grammar.to-string( Q:to[END] ), Q:to[END], 'terminal';
grammar Empty;
stuff : ( 'foo' ) ;
END
grammar Empty {
token stuff {
|| ( || 'foo'
)
}
}
END
is ANTLR4::Grammar.to-string( Q:to[END] ), Q:to[END], 'character range';
grammar Empty;
stuff : ( 'a'..'z' ) ;
END
grammar Empty {
token stuff {
|| ( || <[ a .. z ]>
)
}
}
END
subtest 'modifiers', {
is ANTLR4::Grammar.to-string( Q:to[END] ), Q:to[END], 'question';
grammar Empty;
stuff : ( 'a'..'z'? ) ;
END
grammar Empty {
token stuff {
|| ( || <[ a .. z ]>?
)
}
}
END
is ANTLR4::Grammar.to-string( Q:to[END] ), Q:to[END], 'star';
grammar Empty;
stuff : ( 'a'..'z'* ) ;
END
grammar Empty {
token stuff {
|| ( || <[ a .. z ]>*
)
}
}
END
is ANTLR4::Grammar.to-string( Q:to[END] ), Q:to[END], 'plus';
grammar Empty;
stuff : ( 'a'..'z'+ ) ;
END
grammar Empty {
token stuff {
|| ( || <[ a .. z ]>+
)
}
}
END
done-testing;
};
is ANTLR4::Grammar.to-string( Q:to[END] ), Q:to[END], 'character set';
grammar Empty;
stuff : ( [c] ) ;
END
grammar Empty {
token stuff {
|| ( || <[ c ]>
)
}
}
END
is ANTLR4::Grammar.to-string( Q:to[END] ), Q:to[END], 'alternate character set';
grammar Empty;
stuff : ( ~'c' ) ;
END
grammar Empty {
token stuff {
|| ( || <-[ c ]>
)
}
}
END
is ANTLR4::Grammar.to-string( Q:to[END] ), Q:to[END], 'negated character set subrule';
grammar Empty;
stuff : ( ~( 'c' ) ) ;
END
grammar Empty {
token stuff {
|| ( || <-[ c ]>
)
}
}
END
is ANTLR4::Grammar.to-string( Q:to[END] ), Q:to[END], 'wildcard';
grammar Empty;
stuff : ( . ) ;
END
grammar Empty {
token stuff {
|| ( || .
)
}
}
END
is ANTLR4::Grammar.to-string( Q:to[END] ), Q:to[END], 'nonterminal';
grammar Empty;
stuff : ( Str ) ;
END
grammar Empty {
token stuff {
|| ( || <Str>
)
}
}
END
done-testing;
};
is ANTLR4::Grammar.to-string( Q:to[END] ), Q:to[END], 'concatenation';
grammar Empty;
stuff : ( Str 'testing' ) ;
END
grammar Empty {
token stuff {
|| ( || <Str>
'testing'
)
}
}
END
is ANTLR4::Grammar.to-string( Q:to[END] ), Q:to[END], 'alternation';
grammar Empty;
stuff : ( Str | 'testing' ) ;
END
grammar Empty {
token stuff {
|| ( || <Str>
|| 'testing'
)
}
}
END
is ANTLR4::Grammar.to-string( Q:to[END] ), Q:to[END], 'nesting';
grammar Empty;
stuff : ( ( Str | 'testing' ) ) ;
END
grammar Empty {
token stuff {
|| ( || ( || <Str>
|| 'testing'
)
)
}
}
END
is ANTLR4::Grammar.to-string( Q:to[END] ), Q:to[END], 'terminal + nesting';
grammar Empty;
stuff : ( ( Str | 'testing' ) 'foo' ) ;
END
grammar Empty {
token stuff {
|| ( || ( || <Str>
|| 'testing'
)
'foo'
)
}
}
END
is ANTLR4::Grammar.to-string( Q:to[END] ), Q:to[END], 'regression from IDL';
grammar Empty;
stuff : ('0' | '1'..'9' '0'..'9'*) SUFFIX? ;
END
grammar Empty {
token stuff {
|| ( || '0'
|| <[ 1 .. 9 ]>
<[ 0 .. 9 ]>*
)
<SUFFIX>?
}
}
END
done-testing;
# vim: ft=perl6
|
### ----------------------------------------------------
### -- ANTLR4::Grammar
### -- Licenses: Artistic-2.0
### -- Authors: Jeffrey Goff <[email protected]>
### -- File: t/11-concatenation.t
### ----------------------------------------------------
use v6;
use ANTLR4::Grammar;
use Test;
plan 9;
# No, I'm not going to go through all the permutations of the possible stuff
# inside character ranges, just the basic types outline above.
#
# And I'll bravely assume that other permutations such as C<Str Str> will
# work if these do.
#
is ANTLR4::Grammar.to-string( Q:to[END] ), Q:to[END], 'terminal,terminal';
grammar Lexer;
plain : 'terminal' 'other' ;
END
grammar Lexer {
token plain {
|| 'terminal'
'other'
}
}
END
is ANTLR4::Grammar.to-string( Q:to[END] ), Q:to[END], 'terminal,character range';
grammar Lexer;
plain : 'terminal' 'a'..'z' ;
END
grammar Lexer {
token plain {
|| 'terminal'
<[ a .. z ]>
}
}
END
is ANTLR4::Grammar.to-string( Q:to[END] ), Q:to[END], 'terminal,character set';
grammar Lexer;
plain : 'terminal' [by] ;
END
grammar Lexer {
token plain {
|| 'terminal'
<[ b y ]>
}
}
END
# This is needed because a terminal for some reason shifts ANTLR to
# using the lexerAlt stuff, which needs to be built out separately.
# Again, I could redesign the grammar to get rid of this problem,
# but I think I'm going to leave it as-is to show what sort of
# challenges can result from this.
#
subtest 'terminal,character set modifiers', {
is ANTLR4::Grammar.to-string( Q:to[END] ), Q:to[END], 'terminal,negated character set';
grammar Lexer;
plain : 'terminal' ~[by] ;
END
grammar Lexer {
token plain {
|| 'terminal'
<-[ b y ]>
}
}
END
is ANTLR4::Grammar.to-string( Q:to[END] ), Q:to[END], 'terminal,character set with question';
grammar Lexer;
plain : 'terminal' [by]? ;
END
grammar Lexer {
token plain {
|| 'terminal'
<[ b y ]>?
}
}
END
is ANTLR4::Grammar.to-string( Q:to[END] ), Q:to[END], 'terminal,character set with star';
grammar Lexer;
plain : 'terminal' [by]* ;
END
grammar Lexer {
token plain {
|| 'terminal'
<[ b y ]>*
}
}
END
is ANTLR4::Grammar.to-string( Q:to[END] ), Q:to[END], 'terminal,character set with plus';
grammar Lexer;
plain : 'terminal' [by]+ ;
END
grammar Lexer {
token plain {
|| 'terminal'
<[ b y ]>+
}
}
END
done-testing;
};
is ANTLR4::Grammar.to-string( Q:to[END] ), Q:to[END], 'terminal,negated subrule';
grammar Lexer;
plain : 'terminal' ~('W') ;
END
grammar Lexer {
token plain {
|| 'terminal'
<-[ W ]>
}
}
END
is ANTLR4::Grammar.to-string( Q:to[END] ), Q:to[END], 'terminal-wildcard';
grammar Lexer;
plain : 'terminal' . ;
END
grammar Lexer {
token plain {
|| 'terminal'
.
}
}
END
is ANTLR4::Grammar.to-string( Q:to[END] ), Q:to[END], 'terminal-nonterminal';
grammar Lexer;
plain : 'terminal' Str ;
END
grammar Lexer {
token plain {
|| 'terminal'
<Str>
}
}
END
is ANTLR4::Grammar.to-string( Q:to[END] ), Q:to[END], 'regression from Clojure';
grammar Lexer;
plain: '0' [xX] HEXD+ ;
END
grammar Lexer {
token plain {
|| '0'
<[ x X ]>
<HEXD>+
}
}
END
is ANTLR4::Grammar.to-string( Q:to[END] ), Q:to[END], 'regression from Abnf';
grammar Lexer;
plain : '\r'? -> channel(HIDDEN) ;
END
grammar Lexer {
token plain {
|| '\r'?
}
}
END
done-testing;
# vim: ft=perl6
|
### ----------------------------------------------------
### -- ANTLR4::Grammar
### -- Licenses: Artistic-2.0
### -- Authors: Jeffrey Goff <[email protected]>
### -- File: t/10-basic-grammar.t
### ----------------------------------------------------
use v6;
use ANTLR4::Grammar;
use Test;
plan 4;
sub compile( $orig ) {
return ANTLR4::Grammar.to-string( $orig )
}
# It's most important to test things that can easily translate into Perl 6.
#
# Parametrize types, return types, options, and exceptions won't make sense
# until the C/Java types get translated to Perl 6.
is compile( Q:to[END] ), Q:to[END], 'empty grammar';
grammar Empty;
END
grammar Empty {
}
END
# These will generate errors in Perl because null regexes are illegal.
#
subtest 'empty rule, fragment', {
# No way to generate an empty token, otherwise it'd be here.
#
is compile( Q:to[END] ), Q:to[END], 'empty rule';
grammar Empty;
empty : ;
END
grammar Empty {
token empty {
}
}
END
is compile( Q:to[END] ), Q:to[END], 'multiple empty rules';
grammar Empty;
empty : ;
emptier : ;
END
grammar Empty {
token empty {
}
token emptier {
}
}
END
is compile( Q:to[END] ), Q:to[END], 'empty fragment';
grammar Empty;
fragment empty : ;
END
grammar Empty {
token empty {
}
}
END
is compile( Q:to[END] ), Q:to[END], 'multiple empty fragments';
grammar Empty;
fragment empty : ;
fragment emptier : ;
END
grammar Empty {
token empty {
}
token emptier {
}
}
END
done-testing;
};
# Tokens in ANTLR can't get complex, they're simple strings.
#
subtest 'token', {
is compile( Q:to[END] ), Q:to[END], 'single token';
grammar Empty;
tokens { INDENT }
END
grammar Empty {
token INDENT {
|| 'indent'
}
}
END
is compile( Q:to[END] ), Q:to[END], 'multiple tokens';
grammar Empty;
tokens { INDENT, DEDENT }
END
grammar Empty {
token INDENT {
|| 'indent'
}
token DEDENT {
|| 'dedent'
}
}
END
done-testing;
};
subtest 'rule', {
subtest 'terminal', {
is compile( Q:to[END] ), Q:to[END], 'bare';
grammar Lexer;
plain : 'terminal' ;
END
grammar Lexer {
token plain {
|| 'terminal'
}
}
END
is compile( Q:to[END] ), Q:to[END], 'multiple terms, letters only';
grammar Lexer;
plain : 'terminal' 'station' ;
END
grammar Lexer {
token plain {
|| 'terminal'
'station'
}
}
END
is compile( Q:to[END] ), Q:to[END], 'quoted terminal';
grammar Lexer;
sign : '-' ;
END
grammar Lexer {
token sign {
|| '-'
}
}
END
is compile( Q:to[END] ), Q:to[END], 'escaped terminal';
grammar Lexer;
sign : '\t' ;
END
grammar Lexer {
token sign {
|| '\t'
}
}
END
is compile( Q:to[END] ), Q:to[END], 'Unicode terminal';
grammar Lexer;
sign : 'Hello\u236a' ;
END
grammar Lexer {
token sign {
|| 'Hello\x[236a]'
}
}
END
# Even though ~'t' is valid, 't' in this context isn't a
# terminal but a (degenerate) character set, I think.
#
subtest 'modifiers', {
is compile( Q:to[END] ), Q:to[END], 'question';
grammar Lexer;
plain : 'terminal'? ;
END
grammar Lexer {
token plain {
|| 'terminal'?
}
}
END
is compile( Q:to[END] ), Q:to[END], 'star';
grammar Lexer;
plain : 'terminal'* ;
END
grammar Lexer {
token plain {
|| 'terminal'*
}
}
END
is compile( Q:to[END] ), Q:to[END], 'plus';
grammar Lexer;
plain : 'terminal'+ ;
END
grammar Lexer {
token plain {
|| 'terminal'+
}
}
END
done-testing;
};
subtest 'greedy modifiers', {
is compile( Q:to[END] ), Q:to[END], 'question';
grammar Lexer;
plain : 'terminal'?? ;
END
grammar Lexer {
token plain {
|| 'terminal'??
}
}
END
is compile( Q:to[END] ), Q:to[END], 'star';
grammar Lexer;
plain : 'terminal'*? ;
END
grammar Lexer {
token plain {
|| 'terminal'*?
}
}
END
is compile( Q:to[END] ), Q:to[END], 'plus';
grammar Lexer;
plain : 'terminal'+? ;
END
grammar Lexer {
token plain {
|| 'terminal'+?
}
}
END
done-testing;
};
done-testing;
};
subtest 'negated terminal (character)', {
is compile( Q:to[END] ), Q:to[END], 'negated alternate form';
grammar Lexer;
plain : ~'c' ;
END
grammar Lexer {
token plain {
|| <-[ c ]>
}
}
END
subtest 'modifiers', {
is compile( Q:to[END] ), Q:to[END], 'question';
grammar Lexer;
plain : ~'c'? ;
END
grammar Lexer {
token plain {
|| <-[ c ]>?
}
}
END
is compile( Q:to[END] ), Q:to[END], 'star';
grammar Lexer;
plain : ~'c'* ;
END
grammar Lexer {
token plain {
|| <-[ c ]>*
}
}
END
is compile( Q:to[END] ), Q:to[END], 'plus';
grammar Lexer;
plain : ~'c'+ ;
END
grammar Lexer {
token plain {
|| <-[ c ]>+
}
}
END
};
subtest 'greedy modifiers', {
is compile( Q:to[END] ), Q:to[END], 'question';
grammar Lexer;
plain : ~'c'?? ;
END
grammar Lexer {
token plain {
|| <-[ c ]>??
}
}
END
is compile( Q:to[END] ), Q:to[END], 'star';
grammar Lexer;
plain : ~'c'*? ;
END
grammar Lexer {
token plain {
|| <-[ c ]>*?
}
}
END
is compile( Q:to[END] ), Q:to[END], 'plus';
grammar Lexer;
plain : ~'c'+? ;
END
grammar Lexer {
token plain {
|| <-[ c ]>+?
}
}
END
done-testing;
};
done-testing;
};
subtest 'dotted character range', {
is compile( Q:to[END] ), Q:to[END], 'letters';
grammar Lexer;
plain : 'a'..'z' ;
END
grammar Lexer {
token plain {
|| <[ a .. z ]>
}
}
END
is compile( Q:to[END] ), Q:to[END], 'letter..non-letter';
grammar Lexer;
plain : 'a'..']' ;
END
grammar Lexer {
token plain {
|| <[ a .. \] ]>
}
}
END
is compile( Q:to[END] ), Q:to[END], 'Unicode escape';
grammar Lexer;
plain : '\u0300'..'\u036F' ;
END
grammar Lexer {
token plain {
|| <[ \x[0300] .. \x[036F] ]>
}
}
END
subtest 'modifiers', {
is compile( Q:to[END] ), Q:to[END], 'negation';
grammar Lexer;
plain : ~'a'..'z' ;
END
grammar Lexer {
token plain {
|| <-[ a .. z ]>
}
}
END
subtest 'negated modifiers', {
is compile( Q:to[END] ), Q:to[END], 'question';
grammar Lexer;
plain : ~'a'..'z'? ;
END
grammar Lexer {
token plain {
|| <-[ a .. z ]>?
}
}
END
is compile( Q:to[END] ), Q:to[END], 'star';
grammar Lexer;
plain : ~'a'..'z'* ;
END
grammar Lexer {
token plain {
|| <-[ a .. z ]>*
}
}
END
is compile( Q:to[END] ), Q:to[END], 'plus';
grammar Lexer;
plain : ~'a'..'z'+ ;
END
grammar Lexer {
token plain {
|| <-[ a .. z ]>+
}
}
END
done-testing;
};
is compile( Q:to[END] ), Q:to[END], 'question';
grammar Lexer;
plain : 'a'..'z'? ;
END
grammar Lexer {
token plain {
|| <[ a .. z ]>?
}
}
END
is compile( Q:to[END] ), Q:to[END], 'star';
grammar Lexer;
plain : 'a'..'z'* ;
END
grammar Lexer {
token plain {
|| <[ a .. z ]>*
}
}
END
is compile( Q:to[END] ), Q:to[END], 'plus';
grammar Lexer;
plain : 'a'..'z'+ ;
END
grammar Lexer {
token plain {
|| <[ a .. z ]>+
}
}
END
done-testing;
};
subtest 'greedy modifiers', {
subtest 'negated modifiers', {
is compile( Q:to[END] ), Q:to[END], 'question';
grammar Lexer;
plain : ~'a'..'z'?? ;
END
grammar Lexer {
token plain {
|| <-[ a .. z ]>??
}
}
END
is compile( Q:to[END] ), Q:to[END], 'star';
grammar Lexer;
plain : ~'a'..'z'*? ;
END
grammar Lexer {
token plain {
|| <-[ a .. z ]>*?
}
}
END
is compile( Q:to[END] ), Q:to[END], 'plus';
grammar Lexer;
plain : ~'a'..'z'+? ;
END
grammar Lexer {
token plain {
|| <-[ a .. z ]>+?
}
}
END
done-testing;
};
is compile( Q:to[END] ), Q:to[END], 'question';
grammar Lexer;
plain : 'a'..'z'?? ;
END
grammar Lexer {
token plain {
|| <[ a .. z ]>??
}
}
END
is compile( Q:to[END] ), Q:to[END], 'star';
grammar Lexer;
plain : 'a'..'z'*? ;
END
grammar Lexer {
token plain {
|| <[ a .. z ]>*?
}
}
END
is compile( Q:to[END] ), Q:to[END], 'plus';
grammar Lexer;
plain : 'a'..'z'+? ;
END
grammar Lexer {
token plain {
|| <[ a .. z ]>+?
}
}
END
done-testing;
};
done-testing;
};
subtest 'bracketed character set', {
is compile( Q:to[END] ), Q:to[END], 'single character';
grammar Lexer;
plain : [c] ;
END
grammar Lexer {
token plain {
|| <[ c ]>
}
}
END
is compile( Q:to[END] ), Q:to[END], 'Unicode character';
grammar Lexer;
plain : [\u000C] ;
END
grammar Lexer {
token plain {
|| <[ \x[000C] ]>
}
}
END
is compile( Q:to[END] ), Q:to[END], 'close-bracket';
grammar Lexer;
plain : [\]] ;
END
grammar Lexer {
token plain {
|| <[ \] ]>
}
}
END
subtest 'modifiers', {
is compile( Q:to[END] ), Q:to[END], 'negated';
grammar Lexer;
plain : ~[c] ;
END
grammar Lexer {
token plain {
|| <-[ c ]>
}
}
END
subtest 'negated modifiers', {
is compile( Q:to[END] ), Q:to[END], 'question';
grammar Lexer;
plain : ~[c]? ;
END
grammar Lexer {
token plain {
|| <-[ c ]>?
}
}
END
is compile( Q:to[END] ), Q:to[END], 'star';
grammar Lexer;
plain : ~[c]* ;
END
grammar Lexer {
token plain {
|| <-[ c ]>*
}
}
END
is compile( Q:to[END] ), Q:to[END], 'plus';
grammar Lexer;
plain : ~[c]+ ;
END
grammar Lexer {
token plain {
|| <-[ c ]>+
}
}
END
done-testing;
};
is compile( Q:to[END] ), Q:to[END], 'question';
grammar Lexer;
plain : [c]? ;
END
grammar Lexer {
token plain {
|| <[ c ]>?
}
}
END
is compile( Q:to[END] ), Q:to[END], 'star';
grammar Lexer;
plain : [c]* ;
END
grammar Lexer {
token plain {
|| <[ c ]>*
}
}
END
is compile( Q:to[END] ), Q:to[END], 'plus';
grammar Lexer;
plain : [c]+ ;
END
grammar Lexer {
token plain {
|| <[ c ]>+
}
}
END
done-testing;
};
subtest 'greedy modifiers', {
subtest 'negated modifiers', {
is compile( Q:to[END] ), Q:to[END], 'question';
grammar Lexer;
plain : ~[c]?? ;
END
grammar Lexer {
token plain {
|| <-[ c ]>??
}
}
END
is compile( Q:to[END] ), Q:to[END], 'star';
grammar Lexer;
plain : ~[c]*? ;
END
grammar Lexer {
token plain {
|| <-[ c ]>*?
}
}
END
is compile( Q:to[END] ), Q:to[END], 'plus';
grammar Lexer;
plain : ~[c]+? ;
END
grammar Lexer {
token plain {
|| <-[ c ]>+?
}
}
END
done-testing;
};
is compile( Q:to[END] ), Q:to[END], 'question';
grammar Lexer;
plain : [c]?? ;
END
grammar Lexer {
token plain {
|| <[ c ]>??
}
}
END
is compile( Q:to[END] ), Q:to[END], 'star';
grammar Lexer;
plain : [c]*? ;
END
grammar Lexer {
token plain {
|| <[ c ]>*?
}
}
END
is compile( Q:to[END] ), Q:to[END], 'plus';
grammar Lexer;
plain : [c]+? ;
END
grammar Lexer {
token plain {
|| <[ c ]>+?
}
}
END
done-testing;
};
done-testing;
};
subtest 'multiple-character set', {
is compile( Q:to[END] ), Q:to[END], 'normal';
grammar Lexer;
plain : [abc] ;
END
grammar Lexer {
token plain {
|| <[ a b c ]>
}
}
END
subtest 'modifiers', {
is compile( Q:to[END] ), Q:to[END], 'negated';
grammar Lexer;
plain : ~[abc] ;
END
grammar Lexer {
token plain {
|| <-[ a b c ]>
}
}
END
is compile( Q:to[END] ), Q:to[END], 'question';
grammar Lexer;
plain : [abc]? ;
END
grammar Lexer {
token plain {
|| <[ a b c ]>?
}
}
END
is compile( Q:to[END] ), Q:to[END], 'star';
grammar Lexer;
plain : [abc]* ;
END
grammar Lexer {
token plain {
|| <[ a b c ]>*
}
}
END
is compile( Q:to[END] ), Q:to[END], 'plus';
grammar Lexer;
plain : [abc]+ ;
END
grammar Lexer {
token plain {
|| <[ a b c ]>+
}
}
END
done-testing;
};
done-testing;
};
subtest 'ranged character set', {
is compile( Q:to[END] ), Q:to[END], 'normal';
grammar Lexer;
plain : [a-c] ;
END
grammar Lexer {
token plain {
|| <[ a .. c ]>
}
}
END
is compile( Q:to[END] ), Q:to[END], 'normal';
grammar Lexer;
plain : [\u000a-\u000c] ;
END
grammar Lexer {
token plain {
|| <[ \x[000a] .. \x[000c] ]>
}
}
END
subtest 'modifiers', {
is compile( Q:to[END] ), Q:to[END], 'negated';
grammar Lexer;
plain : ~[a-c] ;
END
grammar Lexer {
token plain {
|| <-[ a .. c ]>
}
}
END
subtest 'negated modifiers', {
is compile( Q:to[END] ), Q:to[END], 'question';
grammar Lexer;
plain : ~[a-c]? ;
END
grammar Lexer {
token plain {
|| <-[ a .. c ]>?
}
}
END
is compile( Q:to[END] ), Q:to[END], 'star';
grammar Lexer;
plain : ~[a-c]* ;
END
grammar Lexer {
token plain {
|| <-[ a .. c ]>*
}
}
END
is compile( Q:to[END] ), Q:to[END], 'plus';
grammar Lexer;
plain : ~[a-c]+ ;
END
grammar Lexer {
token plain {
|| <-[ a .. c ]>+
}
}
END
done-testing;
};
done-testing;
};
done-testing;
};
# Again, a little quirk of ANTLR4.
#
# Negating a group of things actually means you're negating a character
# set composed of the alternatives.
#
subtest 'negated character set, subrule form', {
is compile( Q:to[END] ), Q:to[END], 'single character';
grammar Lexer;
plain : ~( 'W' ) ;
END
grammar Lexer {
token plain {
|| <-[ W ]>
}
}
END
is compile( Q:to[END] ), Q:to[END], 'multiple characters';
grammar Lexer;
plain : ~( 'W' | 'Y' ) ;
END
grammar Lexer {
token plain {
|| <-[ W Y ]>
}
}
END
is compile( Q:to[END] ), Q:to[END], 'character set';
grammar Lexer;
plain : ~( [ \n\r\t\,] ) ;
END
grammar Lexer {
token plain {
|| <-[ \n \r \t \, ]>
}
}
END
is compile( Q:to[END] ), Q:to[END], 'multiple characters';
grammar Lexer;
plain : ~( 'W' .. 'X' | 'Y' ) ;
END
grammar Lexer {
token plain {
|| <-[ W .. X Y ]>
}
}
END
subtest 'modifiers', {
is compile( Q:to[END] ), Q:to[END], 'question';
grammar Lexer;
plain : ~( 'W' )? ;
END
grammar Lexer {
token plain {
|| <-[ W ]>?
}
}
END
is compile( Q:to[END] ), Q:to[END], 'star';
grammar Lexer;
plain : ~( 'W' )* ;
END
grammar Lexer {
token plain {
|| <-[ W ]>*
}
}
END
is compile( Q:to[END] ), Q:to[END], 'plus';
grammar Lexer;
plain : ~( 'W' )+ ;
END
grammar Lexer {
token plain {
|| <-[ W ]>+
}
}
END
done-testing;
};
subtest 'greedy modifiers', {
is compile( Q:to[END] ), Q:to[END], 'question';
grammar Lexer;
plain : ~( 'W' )?? ;
END
grammar Lexer {
token plain {
|| <-[ W ]>??
}
}
END
is compile( Q:to[END] ), Q:to[END], 'star';
grammar Lexer;
plain : ~( 'W' )*? ;
END
grammar Lexer {
token plain {
|| <-[ W ]>*?
}
}
END
is compile( Q:to[END] ), Q:to[END], 'plus';
grammar Lexer;
plain : ~( 'W' )+? ;
END
grammar Lexer {
token plain {
|| <-[ W ]>+?
}
}
END
done-testing;
};
done-testing;
};
# XXX Make sure that wildcard semantics match ANTLR?
#
subtest 'wildcard', {
is compile( Q:to[END] ), Q:to[END], 'bare';
grammar Lexer;
plain : . ;
END
grammar Lexer {
token plain {
|| .
}
}
END
subtest 'modifiers', {
# Negated wildcard is illegal.
# Good thing , no idea what it would mean.
is compile( Q:to[END] ), Q:to[END], 'question';
grammar Lexer;
plain : .? ;
END
grammar Lexer {
token plain {
|| .?
}
}
END
is compile( Q:to[END] ), Q:to[END], 'star';
grammar Lexer;
plain : .* ;
END
grammar Lexer {
token plain {
|| .*
}
}
END
is compile( Q:to[END] ), Q:to[END], 'plus';
grammar Lexer;
plain : .+ ;
END
grammar Lexer {
token plain {
|| .+
}
}
END
done-testing;
};
subtest 'greedy modifiers', {
# Negated wildcard is illegal.
# Good thing , no idea what it would mean.
is compile( Q:to[END] ), Q:to[END], 'question';
grammar Lexer;
plain : .?? ;
END
grammar Lexer {
token plain {
|| .??
}
}
END
is compile( Q:to[END] ), Q:to[END], 'star';
grammar Lexer;
plain : .*? ;
END
grammar Lexer {
token plain {
|| .*?
}
}
END
is compile( Q:to[END] ), Q:to[END], 'plus';
grammar Lexer;
plain : .+? ;
END
grammar Lexer {
token plain {
|| .+?
}
}
END
done-testing;
};
done-testing;
};
subtest 'token with nonterminal', {
is compile( Q:to[END] ), Q:to[END], 'bare';
grammar Lexer;
plain : Str ;
END
grammar Lexer {
token plain {
|| <Str>
}
}
END
is compile( Q:to[END] ), Q:to[END], 'aliased';
grammar Lexer;
plain : alias=Str ;
END
grammar Lexer {
token plain {
|| <alias=Str>
}
}
END
is compile( Q:to[END] ), Q:to[END], 'negated';
grammar Lexer;
plain : ~Str ;
END
grammar Lexer {
token plain {
|| <!Str>
}
}
END
is compile( Q:to[END] ), Q:to[END], 'special EOF nontermnal';
grammar Lexer;
plain : EOF ;
END
grammar Lexer {
token plain {
|| $
}
}
END
subtest 'modifiers', {
is compile( Q:to[END] ), Q:to[END], 'negation';
grammar Lexer;
plain : ~Str* ;
END
grammar Lexer {
token plain {
|| <!Str>*
}
}
END
is compile( Q:to[END] ), Q:to[END], 'question';
grammar Lexer;
plain : Str? ;
END
grammar Lexer {
token plain {
|| <Str>?
}
}
END
is compile( Q:to[END] ), Q:to[END], 'star';
grammar Lexer;
plain : Str* ;
END
grammar Lexer {
token plain {
|| <Str>*
}
}
END
is compile( Q:to[END] ), Q:to[END], 'plus';
grammar Lexer;
plain : Str+ ;
END
grammar Lexer {
token plain {
|| <Str>+
}
}
END
done-testing;
};
subtest 'greedy modifiers', {
# Negation is allowed in the grammar but is illegal
# in the actual language, apparently.
is compile( Q:to[END] ), Q:to[END], 'question';
grammar Lexer;
plain : Str?? ;
END
grammar Lexer {
token plain {
|| <Str>??
}
}
END
is compile( Q:to[END] ), Q:to[END], 'star';
grammar Lexer;
plain : Str*? ;
END
grammar Lexer {
token plain {
|| <Str>*?
}
}
END
is compile( Q:to[END] ), Q:to[END], 'plus';
grammar Lexer;
plain : Str+? ;
END
grammar Lexer {
token plain {
|| <Str>+?
}
}
END
done-testing;
};
done-testing;
};
done-testing;
};
done-testing;
# vim: ft=perl6
|
### ----------------------------------------------------
### -- ANTLR4::Grammar
### -- Licenses: Artistic-2.0
### -- Authors: Jeffrey Goff <[email protected]>
### -- File: t/04-use-parser.t
### ----------------------------------------------------
use v6;
use ANTLR4::Grammar;
use Test;
#plan 50;
plan 2;
sub compile( $name ) {
return ANTLR4::Grammar.file-to-string( 'corpus/' ~ $name );
}
do {
my $grammar-text = compile( 'Abnf.g4' );
my $out = EVAL $grammar-text ~ Q:to[END];
ok Abnf.parse( :rule( 'rule_' ), Q:to[TEST-END].chomp ), 'parses ABNF input';
Abnf=3Digits/"foo"
TEST-END
END
};
#`(
eval-lives-ok compile( 'ANTLRv4Lexer.g4' ), 'ANTLRv4Lexer.g4';
eval-lives-ok compile( 'ANTLRv4Parser.g4' ), 'ANTLRv4Parser.g4';
)
# XXX 'prog' really is the root, work on this.
do {
my $grammar-text = compile( 'asm6502.g4' );
my $out = EVAL $grammar-text ~ Q:to[END];
ok asm6502.parse( :rule( 'line' ), Q:to[TEST-END].chomp ), 'parses asm6502 input';
label:
TEST-END
END
};
#`(
eval-lives-ok compile( 'ATL.g4' ), 'ATL.g4';
eval-lives-ok compile( 'bnf.g4' ), 'bnf.g4';
eval-lives-ok compile( 'C.g4' ), 'C.g4';
eval-lives-ok compile( 'Clojure.g4' ), 'Clojure.g4';
eval-lives-ok compile( 'creole.g4' ), 'creole.g4';
eval-lives-ok compile( 'CSharp4.g4' ), 'CSharp4.g4';
eval-lives-ok compile( 'CSharp4Lexer.g4' ), 'CSharp4Lexer.g4';
eval-lives-ok compile( 'CSharp4PreProcessor.g4' ), 'CSharp4PreProcessor.g4';
eval-lives-ok compile( 'CSV.g4' ), 'CSV.g4';
eval-lives-ok compile( 'DOT.g4' ), 'DOT.g4';
#eval-lives-ok compile( 'ECMAScript.g4' ), 'ECMAScript.g4'; # Impedance mismatch
eval-lives-ok compile( 'Erlang.g4' ), 'Erlang.g4';
eval-lives-ok compile( 'fasta.g4' ), 'fasta.g4';
eval-lives-ok compile( 'gff3.g4' ), 'gff3.g4';
eval-lives-ok compile( 'HTMLLexer.g4' ), 'HTMLLexer.g4';
eval-lives-ok compile( 'HTMLParser.g4' ), 'HTMLParser.g4';
#eval-lives-ok compile( 'ICalendar.g4' ), 'ICalendar.g4'; # Impedance mismatch
eval-lives-ok compile( 'IDL.g4' ), 'IDL.g4';
#eval-lives-ok compile( 'IRI.g4' ), 'IRI.g4'; # Impedance mismatch
#eval-lives-ok compile( 'Java8.g4' ), 'Java8.g4'; # Impedance mismatch
eval-lives-ok compile( 'Java.g4' ), 'Java.g4';
eval-lives-ok compile( 'JSON.g4' ), 'JSON.g4';
eval-lives-ok compile( 'jvmBasic.g4' ), 'jvmBasic.g4';
eval-lives-ok compile( 'LessLexer.g4' ), 'LessLexer.g4';
eval-lives-ok compile( 'LessParser.g4' ), 'LessParser.g4';
eval-lives-ok compile( 'logo.g4' ), 'logo.g4';
eval-lives-ok compile( 'Lua.g4' ), 'Lua.g4';
eval-lives-ok compile( 'MySQLBase.g4' ), 'MySQLBase.g4';
eval-lives-ok compile( 'MySQL.g4' ), 'MySQL.g4';
eval-lives-ok compile( 'ObjC.g4' ), 'ObjC.g4';
eval-lives-ok compile( 'PCRE.g4' ), 'PCRE.g4';
eval-lives-ok compile( 'PGN.g4' ), 'PGN.g4';
eval-lives-ok compile( 'Python3.g4' ), 'Python3.g4';
eval-lives-ok compile( 'redcode.g4' ), 'redcode.g4';
eval-lives-ok compile( 'RFilter.g4' ), 'RFilter.g4';
eval-lives-ok compile( 'R.g4' ), 'R.g4';
eval-lives-ok compile( 'scala.g4' ), 'scala.g4';
eval-lives-ok compile( 'ScssLexer.g4' ), 'ScssLexer.g4';
eval-lives-ok compile( 'ScssParser.g4' ), 'ScssParser.g4';
eval-lives-ok compile( 'Smalltalk.g4' ), 'Smalltalk.g4';
eval-lives-ok compile( 'SQLite.g4' ), 'SQLite.g4';
eval-lives-ok compile( 'Swift.g4' ), 'Swift.g4';
eval-lives-ok compile( 'tnsnames.g4' ), 'tnsnames.g4';
eval-lives-ok compile( 'tnt.g4' ), 'tnt.g4';
eval-lives-ok compile( 'TURTLE.g4' ), 'TURTLE.g4';
#eval-lives-ok compile( 'UCBLogo.g4' ), 'UCBLogo.g4'; # Impedance mismatch
eval-lives-ok compile( 'Verilog2001.g4' ), 'Verilog2001.g4';
eval-lives-ok compile( 'vhdl.g4' ), 'vhdl.g4';
##eval-lives-ok compile( /VisualBasic6.g4' ), 'VisualBasic6.g4';
#skip 'Need to fix UTF-8 issue', 1;
eval-lives-ok compile( 'WebIDL.g4' ), 'WebIDL.g4';
eval-lives-ok compile( 'XMLLexer.g4' ), 'XMLLexer.g4';
eval-lives-ok compile( 'XMLParser.g4' ), 'XMLParser.g4';
)
# vim: ft=perl6
|
### ----------------------------------------------------
### -- ANTLR4::Grammar
### -- Licenses: Artistic-2.0
### -- Authors: Jeffrey Goff <[email protected]>
### -- File: t/16-term-modifiers.t
### ----------------------------------------------------
use v6;
use ANTLR4::Grammar;
use Test;
plan 1;
is ANTLR4::Grammar.to-string( Q:to[END] ), Q:to[END], 'alternating action';
grammar Lexer;
plain : 'X' {doStuff();} ;
END
grammar Lexer {
token plain {
|| 'X'
#|{doStuff();}
}
}
END
done-testing;
# vim: ft=perl6
|
### ----------------------------------------------------
### -- ANTLR4::Grammar
### -- Licenses: Artistic-2.0
### -- Authors: Jeffrey Goff <[email protected]>
### -- File: t/03-corpus-compile.t
### ----------------------------------------------------
use v6;
use ANTLR4::Grammar;
use Test;
plan 48;
sub compile( $name ) {
return ANTLR4::Grammar.file-to-string( 'corpus/' ~ $name );
}
# Commenting out the Abnf test as 04-use-parser.t tests:
# parsing a .g4 file
# Compiling the .g4 file into Perl 6
# Evaluating the grammar
# Parsing a sample .abnf document
#
# So it's a pretty complete test now.
#
#eval-lives-ok compile( 'Abnf.g4' ), 'Abnf.g4'; # roundtrip
eval-lives-ok compile( 'ANTLRv4Lexer.g4' ), 'ANTLRv4Lexer.g4';
eval-lives-ok compile( 'ANTLRv4Parser.g4' ), 'ANTLRv4Parser.g4';
#eval-lives-ok compile( 'asm6502.g4' ), 'asm6502.g4'; # roundtrip
eval-lives-ok compile( 'ATL.g4' ), 'ATL.g4';
eval-lives-ok compile( 'bnf.g4' ), 'bnf.g4';
eval-lives-ok compile( 'C.g4' ), 'C.g4';
eval-lives-ok compile( 'Clojure.g4' ), 'Clojure.g4';
eval-lives-ok compile( 'creole.g4' ), 'creole.g4';
eval-lives-ok compile( 'CSharp4.g4' ), 'CSharp4.g4';
eval-lives-ok compile( 'CSharp4Lexer.g4' ), 'CSharp4Lexer.g4';
eval-lives-ok compile( 'CSharp4PreProcessor.g4' ), 'CSharp4PreProcessor.g4';
eval-lives-ok compile( 'CSV.g4' ), 'CSV.g4';
eval-lives-ok compile( 'DOT.g4' ), 'DOT.g4';
#eval-lives-ok compile( 'ECMAScript.g4' ), 'ECMAScript.g4'; # Impedance mismatch
eval-lives-ok compile( 'Erlang.g4' ), 'Erlang.g4';
eval-lives-ok compile( 'fasta.g4' ), 'fasta.g4';
eval-lives-ok compile( 'gff3.g4' ), 'gff3.g4';
eval-lives-ok compile( 'HTMLLexer.g4' ), 'HTMLLexer.g4';
eval-lives-ok compile( 'HTMLParser.g4' ), 'HTMLParser.g4';
#eval-lives-ok compile( 'ICalendar.g4' ), 'ICalendar.g4'; # Impedance mismatch
eval-lives-ok compile( 'IDL.g4' ), 'IDL.g4';
#eval-lives-ok compile( 'IRI.g4' ), 'IRI.g4'; # Impedance mismatch
#eval-lives-ok compile( 'Java8.g4' ), 'Java8.g4'; # Impedance mismatch
eval-lives-ok compile( 'Java.g4' ), 'Java.g4';
eval-lives-ok compile( 'JSON.g4' ), 'JSON.g4';
eval-lives-ok compile( 'jvmBasic.g4' ), 'jvmBasic.g4';
eval-lives-ok compile( 'LessLexer.g4' ), 'LessLexer.g4';
eval-lives-ok compile( 'LessParser.g4' ), 'LessParser.g4';
eval-lives-ok compile( 'logo.g4' ), 'logo.g4';
eval-lives-ok compile( 'Lua.g4' ), 'Lua.g4';
eval-lives-ok compile( 'MySQLBase.g4' ), 'MySQLBase.g4';
eval-lives-ok compile( 'MySQL.g4' ), 'MySQL.g4';
eval-lives-ok compile( 'ObjC.g4' ), 'ObjC.g4';
eval-lives-ok compile( 'PCRE.g4' ), 'PCRE.g4';
eval-lives-ok compile( 'PGN.g4' ), 'PGN.g4';
eval-lives-ok compile( 'Python3.g4' ), 'Python3.g4';
eval-lives-ok compile( 'redcode.g4' ), 'redcode.g4';
eval-lives-ok compile( 'RFilter.g4' ), 'RFilter.g4';
eval-lives-ok compile( 'R.g4' ), 'R.g4';
eval-lives-ok compile( 'scala.g4' ), 'scala.g4';
eval-lives-ok compile( 'ScssLexer.g4' ), 'ScssLexer.g4';
eval-lives-ok compile( 'ScssParser.g4' ), 'ScssParser.g4';
eval-lives-ok compile( 'Smalltalk.g4' ), 'Smalltalk.g4';
eval-lives-ok compile( 'SQLite.g4' ), 'SQLite.g4';
eval-lives-ok compile( 'Swift.g4' ), 'Swift.g4';
eval-lives-ok compile( 'tnsnames.g4' ), 'tnsnames.g4';
eval-lives-ok compile( 'tnt.g4' ), 'tnt.g4';
eval-lives-ok compile( 'TURTLE.g4' ), 'TURTLE.g4';
#eval-lives-ok compile( 'UCBLogo.g4' ), 'UCBLogo.g4'; # Impedance mismatch
eval-lives-ok compile( 'Verilog2001.g4' ), 'Verilog2001.g4';
eval-lives-ok compile( 'vhdl.g4' ), 'vhdl.g4';
##eval-lives-ok compile( /VisualBasic6.g4' ), 'VisualBasic6.g4';
#skip 'Need to fix UTF-8 issue', 1;
eval-lives-ok compile( 'WebIDL.g4' ), 'WebIDL.g4';
eval-lives-ok compile( 'XMLLexer.g4' ), 'XMLLexer.g4';
eval-lives-ok compile( 'XMLParser.g4' ), 'XMLParser.g4';
# vim: ft=perl6
|
### ----------------------------------------------------
### -- ANTLR4::Grammar
### -- Licenses: Artistic-2.0
### -- Authors: Jeffrey Goff <[email protected]>
### -- File: t/meta.t
### ----------------------------------------------------
use v6;
use lib 'lib';
use Test;
use Test::META;
meta-ok;
done-testing;
|
### ----------------------------------------------------
### -- ANTLR4::Grammar
### -- Licenses: Artistic-2.0
### -- Authors: Jeffrey Goff <[email protected]>
### -- File: t/02-corpus.t
### ----------------------------------------------------
use v6;
use ANTLR4::Grammar::Parser;
use Test;
plan 54;
my $p = ANTLR4::Grammar::Parser.new;
# Commenting out the Abnf test as 04-use-parser.t tests:
# parsing a .g4 file
# Compiling the .g4 file into Perl 6
# Evaluating the grammar
# Parsing a sample .abnf document
#
# So it's a pretty complete test now.
#
#ok $p.parsefile( 'corpus/Abnf.g4' ), 'Abnf.g4'; # roundtrip
ok $p.parsefile( 'corpus/ANTLRv4Lexer.g4' ), 'ANTLRv4Lexer.g4';
ok $p.parsefile( 'corpus/ANTLRv4Parser.g4' ), 'ANTLRv4Parser.g4';
#ok $p.parsefile( 'corpus/asm6502.g4' ), 'asm6502.g4'; # roundtrip
ok $p.parsefile( 'corpus/ATL.g4' ), 'ATL.g4';
ok $p.parsefile( 'corpus/bnf.g4' ), 'bnf.g4';
ok $p.parsefile( 'corpus/C.g4' ), 'C.g4';
ok $p.parsefile( 'corpus/Clojure.g4' ), 'Clojure.g4';
ok $p.parsefile( 'corpus/creole.g4' ), 'creole.g4';
ok $p.parsefile( 'corpus/CSharp4.g4' ), 'CSharp4.g4';
ok $p.parsefile( 'corpus/CSharp4Lexer.g4' ), 'CSharp4Lexer.g4';
ok $p.parsefile( 'corpus/CSharp4PreProcessor.g4' ), 'CSharp4PreProcessor.g4';
ok $p.parsefile( 'corpus/CSV.g4' ), 'CSV.g4';
ok $p.parsefile( 'corpus/DOT.g4' ), 'DOT.g4';
ok $p.parsefile( 'corpus/ECMAScript.g4' ), 'ECMAScript.g4';
ok $p.parsefile( 'corpus/Erlang.g4' ), 'Erlang.g4';
ok $p.parsefile( 'corpus/fasta.g4' ), 'fasta.g4';
ok $p.parsefile( 'corpus/gff3.g4' ), 'gff3.g4';
ok $p.parsefile( 'corpus/HTMLLexer.g4' ), 'HTMLLexer.g4';
ok $p.parsefile( 'corpus/HTMLParser.g4' ), 'HTMLParser.g4';
ok $p.parsefile( 'corpus/ICalendar.g4' ), 'ICalendar.g4';
ok $p.parsefile( 'corpus/IDL.g4' ), 'IDL.g4';
ok $p.parsefile( 'corpus/IRI.g4' ), 'IRI.g4';
ok $p.parsefile( 'corpus/Java8.g4' ), 'Java8.g4';
ok $p.parsefile( 'corpus/Java.g4' ), 'Java.g4';
ok $p.parsefile( 'corpus/JSON.g4' ), 'JSON.g4';
ok $p.parsefile( 'corpus/jvmBasic.g4' ), 'jvmBasic.g4';
ok $p.parsefile( 'corpus/LessLexer.g4' ), 'LessLexer.g4';
ok $p.parsefile( 'corpus/LessParser.g4' ), 'LessParser.g4';
ok $p.parsefile( 'corpus/logo.g4' ), 'logo.g4';
ok $p.parsefile( 'corpus/Lua.g4' ), 'Lua.g4';
ok $p.parsefile( 'corpus/MySQLBase.g4' ), 'MySQLBase.g4';
ok $p.parsefile( 'corpus/MySQL.g4' ), 'MySQL.g4';
ok $p.parsefile( 'corpus/ObjC.g4' ), 'ObjC.g4';
ok $p.parsefile( 'corpus/PCRE.g4' ), 'PCRE.g4';
ok $p.parsefile( 'corpus/PGN.g4' ), 'PGN.g4';
ok $p.parsefile( 'corpus/Python3.g4' ), 'Python3.g4';
ok $p.parsefile( 'corpus/redcode.g4' ), 'redcode.g4';
ok $p.parsefile( 'corpus/RFilter.g4' ), 'RFilter.g4';
ok $p.parsefile( 'corpus/R.g4' ), 'R.g4';
ok $p.parsefile( 'corpus/scala.g4' ), 'scala.g4';
ok $p.parsefile( 'corpus/ScssLexer.g4' ), 'ScssLexer.g4';
ok $p.parsefile( 'corpus/ScssParser.g4' ), 'ScssParser.g4';
ok $p.parsefile( 'corpus/Smalltalk.g4' ), 'Smalltalk.g4';
ok $p.parsefile( 'corpus/SQLite.g4' ), 'SQLite.g4';
ok $p.parsefile( 'corpus/Swift.g4' ), 'Swift.g4';
ok $p.parsefile( 'corpus/tnsnames.g4' ), 'tnsnames.g4';
ok $p.parsefile( 'corpus/tnt.g4' ), 'tnt.g4';
ok $p.parsefile( 'corpus/TURTLE.g4' ), 'TURTLE.g4';
ok $p.parsefile( 'corpus/UCBLogo.g4' ), 'UCBLogo.g4';
ok $p.parsefile( 'corpus/Verilog2001.g4' ), 'Verilog2001.g4';
ok $p.parsefile( 'corpus/vhdl.g4' ), 'vhdl.g4';
#ok $p.parsefile( 'corpus/VisualBasic6.g4' ), 'VisualBasic6.g4';
skip 'Need to fix UTF-8 issue', 1;
ok $p.parsefile( 'corpus/WebIDL.g4' ), 'WebIDL.g4';
ok $p.parsefile( 'corpus/XMLLexer.g4' ), 'XMLLexer.g4';
ok $p.parsefile( 'corpus/XMLParser.g4' ), 'XMLParser.g4';
# vim: ft=perl6
|
### ----------------------------------------------------
### -- ANTLR4::Grammar
### -- Licenses: Artistic-2.0
### -- Authors: Jeffrey Goff <[email protected]>
### -- File: t/14-grammar-modifiers.t
### ----------------------------------------------------
use v6;
use ANTLR4::Grammar;
use Test;
plan 4;
# The double comment blocks are around bits of the grammar that don't
# necessarily translate into Perl 6.
#
# Taking a much more pragmatic approach this time 'round.
#
subtest 'grammar basics', {
is ANTLR4::Grammar.to-string( Q:to[END] ), Q:to[END], 'lexer grammar';
lexer grammar Empty;
END
#|{ "type" : "lexer" }
grammar Empty {
}
END
is ANTLR4::Grammar.to-string( Q:to[END] ), Q:to[END], 'parser grammar';
parser grammar Empty;
END
#|{ "type" : "parser" }
grammar Empty {
}
END
done-testing;
};
# A blank option array may be possible, but it won't be placed
# into the JSON block.
#
is ANTLR4::Grammar.to-string( Q:to[END] ), Q:to[END], 'single option';
grammar Empty;
options { tokenVocab=Antlr; }
END
#|{ "option" : { "tokenVocab" : "Antlr" } }
grammar Empty {
}
END
subtest 'import', {
is ANTLR4::Grammar.to-string( Q:to[END] ), Q:to[END], 'import';
grammar Empty;
import ChristmasParser;
END
#|{ "import" : { "ChristmasParser" : null } }
grammar Empty {
}
END
is ANTLR4::Grammar.to-string( Q:to[END] ), Q:to[END], 'import with alias';
grammar Empty;
import ChristmasParser=Christmas;
END
#|{ "import" : { "ChristmasParser" : "Christmas" } }
grammar Empty {
}
END
done-testing;
};
# The test text below is rather dense because the here-doc seems to eat a
# tab that it shouldn't, so I write everything out "longhand" as it were, with
# literal \n characters.
#
is ANTLR4::Grammar.to-string( Q:to[END] ), Q:to[END], 'action';
grammar Empty;
@members {
/** Track whether we are inside of a rule and whether it is lexical parser.
*/
public void setCurrentRuleType(int ruleType) {
this._currentRuleType = ruleType;
}
}
END
#|{ "action" : { "@members" : "{\n\t/** Track whether we are inside of a rule and whether it is lexical parser.\n\t */\n\tpublic void setCurrentRuleType(int ruleType) {\n\t\tthis._currentRuleType = ruleType;\n\t}\n}" } }
grammar Empty {
}
END
done-testing;
# vim: ft=perl6
|
### ----------------------------------------------------
### -- API::Discord
### -- Licenses: BSD-3-Clause
### -- Authors: Alastair 'altreus' Douglas <[email protected]>, Jonathan 'jnthn' Worthington <[email protected]>, Kane 'kawaii' Valentine <[email protected]>
### -- File: META6.json
### ----------------------------------------------------
{
"auth": "github:shuppet",
"authors": [
"Alastair 'altreus' Douglas <[email protected]>",
"Jonathan 'jnthn' Worthington <[email protected]>",
"Kane 'kawaii' Valentine <[email protected]>"
],
"build-depends": [
],
"depends": [
"Cro::WebSocket",
"Data::Dump",
"Object::Delayed",
"URI::Encode",
"Subset::Helper",
"Test::META"
],
"description": "Raku module for interacting with the Discord API.",
"license": "BSD-3-Clause",
"meta-version": "0",
"name": "API::Discord",
"perl": "6.d",
"provides": {
"API::Discord": "lib/API/Discord.rakumod",
"API::Discord::Channel": "lib/API/Discord/Channel.rakumod",
"API::Discord::Channel::ButReal": "lib/API/Discord/Channel.rakumod",
"API::Discord::Connection": "lib/API/Discord/Connection.rakumod",
"API::Discord::DataObject": "lib/API/Discord/Object.rakumod",
"API::Discord::Debug": "lib/API/Discord/Debug.rakumod",
"API::Discord::Endpoints": "lib/API/Discord/Endpoints.rakumod",
"API::Discord::Exceptions": "lib/API/Discord/Exceptions.rakumod",
"API::Discord::Guild": "lib/API/Discord/Guild.rakumod",
"API::Discord::Guild::ButReal": "lib/API/Discord/Guild.rakumod",
"API::Discord::HTTPResource": "lib/API/Discord/HTTPResource.rakumod",
"API::Discord::JSONy": "lib/API/Discord/HTTPResource.rakumod",
"API::Discord::Message": "lib/API/Discord/Message.rakumod",
"API::Discord::Message::ButReal": "lib/API/Discord/Message.rakumod",
"API::Discord::Object": "lib/API/Discord/Object.rakumod",
"API::Discord::Permissions": "lib/API/Discord/Permissions.rakumod",
"API::Discord::RESTy": "lib/API/Discord/HTTPResource.rakumod",
"API::Discord::Types": "lib/API/Discord/Types.rakumod",
"API::Discord::User": "lib/API/Discord/User.rakumod",
"API::Discord::User::ButReal": "lib/API/Discord/User.rakumod",
"API::Discord::WebSocket": "lib/API/Discord/WebSocket.rakumod",
"API::Discord::WebSocket::Messages": "lib/API/Discord/WebSocket/Messages.rakumod",
"X::API::Discord::Connection::Flatline": "lib/API/Discord/Exceptions.rakumod",
"X::API::Discord::Endpoint::NotEnoughArguments": "lib/API/Discord/Endpoints.rakumod"
},
"raku": null,
"resources": [
],
"source-url": "git://[email protected]/shuppet/raku-api-discord.git",
"support": {
"bugtracker": "https://github.com/shuppet/raku-api-discord/issues",
"source": "https://github.com/shuppet/raku-api-discord.git"
},
"tags": [
],
"test-depends": [
"Test::META"
],
"version": "0.6"
}
|
### ----------------------------------------------------
### -- API::Discord
### -- Licenses: BSD-3-Clause
### -- Authors: Alastair 'altreus' Douglas <[email protected]>, Jonathan 'jnthn' Worthington <[email protected]>, Kane 'kawaii' Valentine <[email protected]>
### -- File: LICENSE
### ----------------------------------------------------
BSD 3-Clause License
Copyright (c) 2018,
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the copyright holder nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
### ----------------------------------------------------
### -- API::Discord
### -- Licenses: BSD-3-Clause
### -- Authors: Alastair 'altreus' Douglas <[email protected]>, Jonathan 'jnthn' Worthington <[email protected]>, Kane 'kawaii' Valentine <[email protected]>
### -- File: README.md
### ----------------------------------------------------

`API::Discord` is a Raku (formerly Perl 6) module for interacting with the Discord API. Built on
top of [`Cro::WebSocket::Client`](https://github.com/croservices/cro-websocket)
and [`Cro::HTTP::Client`](https://github.com/croservices/cro-http), this allows
for fast asynchronous operations between your application and the API.
## Installation
### ... from zef
```
zef install API::Discord
```
### ... from source
```
git clone https://github.com/shuppet/raku-api-discord
cd raku-api-discord/ && zef install ${PWD}
```
## Usage
Full documentation can be found by reading the pod6 directly from the module source.
```
p6doc API::Discord
```
## Example
`API::Discord` is designed to do all the hard work for you. Let us handle the connection, authentication, heartbeats, message parsing and all that other boring stuff - leaving you to focus on writing logic for your applications.
```raku
#!raku
use API::Discord;
use API::Discord::Debug; # remove to disable debug output
sub MAIN($token) {
my $discord = API::Discord.new(:$token);
$discord.connect;
await $discord.ready;
react {
whenever $discord.messages -> $message {
$message.channel.send-message($message.content);
}
}
}
```
More examples can be found within the [`examples/`](https://github.com/shuppet/raku-api-discord/tree/master/examples) directory of this repository.
## Support
### Official
Join our official Discord server where we discuss development, bugs and test changes or new features to our library. Please note that this is a volunteer project and we all have real lives, day jobs and other responsiblities outside of the Internet. Replies may not be immediate and a resolution of your problem is not guaranteed outside of valid bug reports (for which raising an [issue](https://github.com/shuppet/raku-api-discord/issues/new) here on GitHub is far preferable).
[](https://discord.gg/8FqQFCF)
### Community
If you have a more general Raku question, or need help with a programming issue then it might be best to join the Raku Discord community instead. Some of the members there are also familiar with `API::Discord` and it's quite likely they'll be able to help you faster than we can. They're also really nice people. :)
[](https://discord.gg/VzYpdQ6)
|
### ----------------------------------------------------
### -- API::Discord
### -- Licenses: BSD-3-Clause
### -- Authors: Alastair 'altreus' Douglas <[email protected]>, Jonathan 'jnthn' Worthington <[email protected]>, Kane 'kawaii' Valentine <[email protected]>
### -- File: t/endpoint.t
### ----------------------------------------------------
use API::Discord::Endpoints;
use API::Discord::Message;
use Test;
throws-like {
my $m = Message.new(:channel-id(1));
endpoint-for($m, 'read');
}, X::API::Discord::Endpoint::NotEnoughArguments, message => / 'channel-id id'/;
{
my $m = Message.new(:channel-id(1234));
is endpoint-for($m, 'create'), '/channels/1234/messages', "Got correct URL";
}
{
my $m = Message.new(:channel-id(1234));
is endpoint-for($m, 'read', id => 123), '/channels/1234/messages/123', "Got correct URL";
}
done-testing;
|
### ----------------------------------------------------
### -- API::Discord
### -- Licenses: BSD-3-Clause
### -- Authors: Alastair 'altreus' Douglas <[email protected]>, Jonathan 'jnthn' Worthington <[email protected]>, Kane 'kawaii' Valentine <[email protected]>
### -- File: t/00-meta.t
### ----------------------------------------------------
use v6;
use lib 'lib';
use Test;
plan 1;
constant AUTHOR = ?%*ENV<AUTHOR_TESTING>;
if AUTHOR {
require Test::META <&meta-ok>;
meta-ok;
done-testing;
}
else {
skip-rest "Skipping author test";
exit;
}
|
### ----------------------------------------------------
### -- API::Discord
### -- Licenses: BSD-3-Clause
### -- Authors: Alastair 'altreus' Douglas <[email protected]>, Jonathan 'jnthn' Worthington <[email protected]>, Kane 'kawaii' Valentine <[email protected]>
### -- File: t/meta.t
### ----------------------------------------------------
use v6;
use lib 'lib';
use Test;
use Test::META;
meta-ok;
done-testing;
|
### ----------------------------------------------------
### -- API::Discord
### -- Licenses: BSD-3-Clause
### -- Authors: Alastair 'altreus' Douglas <[email protected]>, Jonathan 'jnthn' Worthington <[email protected]>, Kane 'kawaii' Valentine <[email protected]>
### -- File: examples/ruthless-mod.raku
### ----------------------------------------------------
#!perl6
use API::Discord;
sub MAIN($token) {
my $discord = API::Discord.new(:$token);
await $discord.connect;
react {
whenever $discord.messages -> $message {
await $message.delete
}
}
}
|
### ----------------------------------------------------
### -- API::Discord
### -- Licenses: BSD-3-Clause
### -- Authors: Alastair 'altreus' Douglas <[email protected]>, Jonathan 'jnthn' Worthington <[email protected]>, Kane 'kawaii' Valentine <[email protected]>
### -- File: examples/toxicity.raku
### ----------------------------------------------------
#!perl6
use API::Discord;
use Cro::HTTP::Client;
sub MAIN($discord-token, $perspective-token) {
my $discord = API::Discord.new(:token($discord-token));
await $discord.connect;
my $http = Cro::HTTP::Client.new(
content-type => 'application/json',
http => '1.1'
);
react {
whenever $discord.messages -> $message {
my $toxicity = await $http.post(
"https://commentanalyzer.googleapis.com/v1alpha1/comments:analyze?key={$perspective-token}",
body => {
comment => {
text => $message.content
},
languages => ["en"],
requestedAttributes => { TOXICITY => {} }
}
);
my $result = await $toxicity.body;
if $result<attributeScores><TOXICITY><summaryScore><value> > 0.7 {
$message.add-reaction('☹');
}
}
}
}
|
### ----------------------------------------------------
### -- API::Discord
### -- Licenses: BSD-3-Clause
### -- Authors: Alastair 'altreus' Douglas <[email protected]>, Jonathan 'jnthn' Worthington <[email protected]>, Kane 'kawaii' Valentine <[email protected]>
### -- File: examples/automessage.raku
### ----------------------------------------------------
#!perl6
use API::Discord;
sub MAIN($token, $channel-id) {
my $discord = API::Discord.new(:$token);
$discord.connect;
await $discord.ready;
react {
whenever Supply.interval(300) {
my $time = DateTime.now;
$discord.get-channel($channel-id).send-message("Test message sent at $time.");
}
}
}
|
### ----------------------------------------------------
### -- API::Discord
### -- Licenses: BSD-3-Clause
### -- Authors: Alastair 'altreus' Douglas <[email protected]>, Jonathan 'jnthn' Worthington <[email protected]>, Kane 'kawaii' Valentine <[email protected]>
### -- File: examples/autostar.raku
### ----------------------------------------------------
use API::Discord;
use API::Discord::Debug;
sub MAIN($token) {
my $discord = API::Discord.new(:$token);
$discord.connect;
await $discord.ready;
react {
whenever $discord.messages -> $message {
$message.add-reaction('⭐');
}
whenever $discord.events -> $event {
if $event<t> eq 'MESSAGE_REACTION_ADD' {
say $event<d><member><user><username> ~ '#' ~ $event<d><member><user><discriminator> ~ ' added a reaction to message ' ~ $event<d><message_id>;
}
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.