txt
stringlengths 202
72.4k
|
---|
### ----------------------------------------------------
### -- Algorithm::Evolutionary::Simple
### -- Licenses: Artistic-2.0
### -- Authors: JJ Merelo
### -- File: resources/examples/concurrent-selecto-recombinative-EA.p6
### ----------------------------------------------------
#!/usr/bin/env perl6
use v6;
use Algorithm::Evolutionary::Simple;
sub selecto-recombinative-EA( |parameters (
UInt :$length = 64,
UInt :$population-size = 256,
UInt :$diversify-size = 8,
UInt :$max-evaluations = 10000,
UInt :$tournament-size = 4
)) {
# Channel definition
my Channel $raw .= new;
my Channel $evaluated .= new;
my Channel $channel-three = $evaluated.Supply.batch( elems => $tournament-size).Channel;
my Channel $shuffler = $raw.Supply.batch( elems => $diversify-size).Channel;
my Channel $output .= new;
# Creates initial population
$raw.send( random-chromosome($length).list ) for ^$population-size;
my $count = 0;
my $end;
my $shuffle = start react whenever $shuffler -> @group {
my @shuffled = @group.pick(*);
$raw.send( $_ ) for @shuffled;
}
my $evaluation = start react whenever $raw -> $one {
my $with-fitness = $one => max-ones($one);
$output.send( $with-fitness );
$evaluated.send( $with-fitness);
say $count++, " → $with-fitness";
if $with-fitness.value == $length {
$raw.close;
$end = "Solution found";
}
if $count >= $max-evaluations {
$raw.close;
$end = "Solution not found";
}
}
my $selection = start react whenever $channel-three -> @tournament {
my @ranked = @tournament.sort( { .values } ).reverse;
$evaluated.send( $_ ) for @ranked[0..1];
$raw.send( $_.list ) for crossover(@ranked[0].key,@ranked[1].key);
}
await $evaluation;
loop {
if my $item = $output.poll {
$item.say;
} else {
$output.close;
}
if $output.closed { last };
}
say "Parameters ==";
say "Evaluations => $count";
for parameters.kv -> $key, $value {
say "$key → $value";
};
say "=============";
return $end;
}
sub MAIN ( UInt :$repetitions = 30,
UInt :$length = 64,
UInt :$population-size = 512,
UInt :$diversify-size = 8,
UInt :$max-evaluations = 10000,
UInt :$tournament-size = 4 ) {
my $found;
for ^$repetitions {
my $result = selecto-recombinative-EA( length => $length,
population-size => $population-size,
diversify-size => $diversify-size,
max-evaluations => $max-evaluations,
tournament-size => $tournament-size );
$found++ if $result eq "Solution found";
}
say "Result ", $found/$repetitions;
}
=begin pod
=head1 NAME
concurrent-selecto-recombinative-EA.p6 - Implements a selecto-recombinative algorithm to find population without mutation
=head1 SYNOPSIS
./concurrent-selecto-recombinative-EA.p6 --length[=64] --repetitions[=30]
--population-size[=512] --diversify-size[=8] --max-evaluations[=10000]
--tournament-size[=4]
=head1 DESCRIPTION
Uses a individual-based selecto-recombinative algorithm, with no population. Mainly used for finding out the correct population for an evolutionary algorithm
=end pod
|
### ----------------------------------------------------
### -- Algorithm::Evolutionary::Simple
### -- Licenses: Artistic-2.0
### -- Authors: JJ Merelo
### -- File: resources/examples/p-peaks.p6
### ----------------------------------------------------
#!/usr/bin/env perl6
# Examples of using auto-threading with a heavy function, P-Peaks.
use v6;
use Algorithm::Evolutionary::Simple;
use Algorithm::Evolutionary::Fitness::P-Peaks;
sub MAIN ( UInt :$repetitions = 15,
UInt :$length = 32,
UInt :$number-of-peaks = 100,
UInt :$population-size = 4096 ) {
my @found;
my $p-peaks = Algorithm::Evolutionary::Fitness::P-Peaks.new: number-of-peaks => $number-of-peaks, bits => $length;
my $length-peaks = -> @chromosome { $p-peaks.distance( @chromosome ) };
for ^$repetitions {
my @initial-population = initialize( size => $population-size,
genome-length => $length );
my %fitness-of;
my $population = evaluate( population => @initial-population,
fitness-of => %fitness-of,
evaluator => $length-peaks,
auto-t => True );
my $result = 0;
while $population.sort(*.value).reverse.[0].value < 1 {
say "Best → ", $population.sort(*.value).reverse.[0].value;
$population = generation( population => $population,
fitness-of => %fitness-of,
evaluator => $length-peaks,
population-size => $population-size,
auto-t => True ) ;
$result += $population-size;
}
say "Found → $population.sort(*.value).reverse.[0]";
@found.push( $result );
}
say "Found ", @found;
}
|
### ----------------------------------------------------
### -- Algorithm::Evolutionary::Simple
### -- Licenses: Artistic-2.0
### -- Authors: JJ Merelo
### -- File: resources/examples/royal-road.p6
### ----------------------------------------------------
#!/usr/bin/env p6
use v6;
use lib <../../lib>;
use Algorithm::Evolutionary::Simple;
use Log::Async;
use JSON::Fast;
sub json-formatter ( $m, :$fh ) {
say $m;
$fh.say: to-json( { msg => from-json($m<msg>),
time => $m<when>.Str });
}
logger.send-to("royal-road-" ~ DateTime.now.Str ~ ".json", formatter => &json-formatter);
sub MAIN ( UInt :$repetitions = 30,
UInt :$length = 64,
UInt :$population-size = 256,
UInt :$no-change-limit = 64 ) {
my @found;
info(to-json( { length => $length,
population-size => $population-size,
start-at => DateTime.now.Str} ));
my $best-fitness = 0;
for ^$repetitions {
my @initial-population = initialize( size => $population-size,
genome-length => $length );
my %fitness-of;
my $population = evaluate( population => @initial-population,
fitness-of => %fitness-of,
evaluator => &royal-road );
my $result = 0;
repeat {
$population = generation( population => $population,
fitness-of => %fitness-of,
evaluator => &royal-road,
population-size => $population-size) ;
$result += $population-size;
info(to-json( { best => best-fitness($population) } ));
$best-fitness = $population.sort(*.value).reverse.[0].value;
} until ( $best-fitness >= $length/4 ) or
no-change-during( $no-change-limit, $best-fitness );
say "Best fitness $best-fitness";
info(to-json( { best => best-fitness($population),
found => ? ( $best-fitness >= $length/4 ),
finishing-at => DateTime.now.Str} ));
@found.push( $result );
}
say "Found ", @found;
}
|
### ----------------------------------------------------
### -- Algorithm::Evolutionary::Simple
### -- Licenses: Artistic-2.0
### -- Authors: JJ Merelo
### -- File: resources/examples/concurrent-evolutionary-algorithm.p6
### ----------------------------------------------------
#!/usr/bin/env perl6
use v6;
use Algorithm::Evolutionary::Simple;
use Log::Async;
constant tournament-size = 2;
sub json-formatter ( $m, :$fh ) {
say $m;
$fh.say: to-json( { msg => from-json($m<msg>),
time => $m<when>.Str });
}
logger.send-to("test.json", formatter => &json-formatter);
sub regular-EA ( |parameters (
UInt :$length = 64,
UInt :$population-size = 256,
UInt :$diversify-size = 8,
UInt :$max-evaluations = 10000,
UInt :$threads = 1 )
) {
my Channel $raw .= new;
my Channel $evaluated .= new;
my Channel $channel-three = $evaluated.Supply.batch( elems => tournament-size).Channel;
my Channel $shuffler = $raw.Supply.batch( elems => $diversify-size).Channel;
$raw.send( random-chromosome($length).list ) for ^$population-size;
my $count = 0;
my $end;
my $shuffle = start react whenever $shuffler -> @group {
# say "Mixing in ", $*THREAD.id;
my @shuffled = @group.pick(*);
$raw.send( $_ ) for @shuffled;
};
my @evaluation = ( start react whenever $raw -> $one {
my $with-fitness = $one => max-ones($one);
info( to-json( $with-fitness ));
$evaluated.send( $with-fitness);
# say $count++, " → $with-fitness";
if $with-fitness.value == $length {
$raw.close;
$end = "Found" => $count;
}
if $count++ >= $max-evaluations {
$raw.close;
$end = "Found" => False;
}
# say "Evaluating in " , $*THREAD.id;
} ) for ^$threads;
my $selection = ( start react whenever $channel-three -> @tournament {
# say "Selecting in " , $*THREAD.id;
my @ranked = @tournament.sort( { .values } ).reverse;
$evaluated.send( $_ ) for @ranked[0..1];
my @crossed = crossover(@ranked[0].key,@ranked[1].key);
$raw.send( $_.list ) for @crossed.map: { mutation($^þ)};
} ) for ^($threads/2);
await @evaluation;
say "Parameters ==";
for parameters.kv -> $key, $value {
say "$key → $value";
};
say "=============";
return $end;
}
sub MAIN ( UInt :$repetitions = 15,
UInt :$length = 64,
UInt :$population-size = 256,
UInt :$diversify-size = 8,
UInt :$max-evaluations = 10000,
UInt :$threads = 2) {
my @found;
for ^$repetitions {
my $result = regular-EA( length => $length,
population-size => $population-size,
diversify-size => $diversify-size,
max-evaluations => $max-evaluations,
threads => $threads);
say( $result );
@found.push( $result );
}
say "Result ", @found;
}
|
### ----------------------------------------------------
### -- Algorithm::Evolutionary::Simple
### -- Licenses: Artistic-2.0
### -- Authors: JJ Merelo
### -- File: resources/examples/META6.json
### ----------------------------------------------------
{
"name": "An Algorithm::Evolutionary::Simple set of examples",
"description": "A simple evolutionary algorithm",
"version": "0.0.1",
"perl": "6.*",
"authors": [
"JJ Merelo"
],
"auth": "github:JJ",
"depends": [
"Log::Async",
"JSON::Fast"
],
"license": "Artistic-2.0",
"tags": [
"evolutionary algorithms",
"genetic algorithms",
"optimization",
"computational intelligence"
],
"source-url": "https://github.com/JJ/p6-algorithm-evolutionary-simple.git"
}
|
### ----------------------------------------------------
### -- Algorithm::Evolutionary::Simple
### -- Licenses: Artistic-2.0
### -- Authors: JJ Merelo
### -- File: resources/examples/concurrent-p-peaks.p6
### ----------------------------------------------------
#!/usr/bin/env perl6
use v6.d.PREVIEW;
use Algorithm::Evolutionary::Simple;
use Algorithm::Evolutionary::Fitness::P-Peaks;
use Log::Async;
sub json-formatter ( $m, :$fh ) {
say $m;
$fh.say: to-json( { msg => from-json($m<msg>),
time => $m<when>.Str });
}
logger.send-to("test.json", formatter => &json-formatter);
constant tournament-size = 2;
sub regular-EA ( |parameters (
UInt :$length = 32,
UInt :$population-size = 1024,
UInt :$diversify-size = 8,
UInt :$max-evaluations = 100000,
UInt :$number-of-peaks = 100,
UInt :$threads = 1 )
) {
my Channel $raw .= new;
my Channel $evaluated .= new;
my Channel $channel-three = $evaluated.Supply.batch( elems => tournament-size).Channel;
my Channel $shuffler = $raw.Supply.batch( elems => $diversify-size).Channel;
info(to-json({ length => $length,
population-size => $population-size,
diversify-size => $diversify-size,
threads => $threads,
start => True }
));
$raw.send( random-chromosome($length).list ) for ^$population-size;
my $count = 0;
my $end;
my $shuffle = start react whenever $shuffler -> @group {
# say "Mixing in ", $*THREAD.id;
my @shuffled = @group.pick(*);
$raw.send( $_ ) for @shuffled;
};
my $p-peaks = Algorithm::Evolutionary::Fitness::P-Peaks.new:
number-of-peaks => $number-of-peaks,
bits => $length;
my @evaluation = ( start react whenever $raw -> $one {
my $distance = $p-peaks.distance($one);
my $with-fitness = $one => $distance;
say $with-fitness;
info( to-json([$one,$distance]) );
$evaluated.send( $with-fitness);
# say $count++, " → $with-fitness";
if $with-fitness.value == $length {
$raw.close;
$end = "Found" => $count;
}
if $count++ >= $max-evaluations {
$raw.close;
$end = "Found" => False;
}
say "Evaluating in " , $*THREAD.id;
} ) for ^$threads;
my $selection = (
start react whenever $channel-three -> @tournament {
say "Selecting in " , $*THREAD.id;
my @ranked = @tournament.sort( { .values } ).reverse;
$evaluated.send( $_ ) for @ranked[0..1];
my @crossed = crossover(@ranked[0].key,@ranked[1].key);
$raw.send( $_.list ) for @crossed.map: { mutation($^þ)};
}
) for ^$threads/2;
await @evaluation;
loop {
say "Parameters ==";
say "Evaluations => $count";
for parameters.kv -> $key, $value {
say "$key → $value";
};
say "=============";
return $end;
}
}
sub MAIN ( UInt :$repetitions = 15,
UInt :$length = 32,
UInt :$population-size = 2048,
UInt :$diversify-size = 32,
UInt :$number-of-peaks = 100,
UInt :$max-evaluations = 10000,
UInt :$threads = 2) {
my @found;
for ^$repetitions {
my $result = regular-EA(:$length,
:$population-size,
:$diversify-size,
:$max-evaluations,
:$number-of-peaks,
:$threads);
say( $result );
@found.push( $result );
}
say "Result ", @found;
}
|
### ----------------------------------------------------
### -- Algorithm::Evolutionary::Simple
### -- Licenses: Artistic-2.0
### -- Authors: JJ Merelo
### -- File: resources/examples/population-mixer-freqs.p6
### ----------------------------------------------------
#!/usr/bin/env perl6
use v6;
use lib <../../lib>;
use Algorithm::Evolutionary::Simple;
use Log::Async;
use JSON::Fast;
sub json-formatter ( $m, :$fh ) {
say $m;
$fh.say: to-json( { msg => from-json($m<msg>),
time => $m<when>.Str });
}
logger.send-to("pmf-" ~ DateTime.now.Str ~ ".json", formatter => &json-formatter);
sub MAIN( UInt :$length = 64,
UInt :$population-size = 256,
UInt :$generations = 16,
UInt :$threads = 2
) {
my $parameters = .Capture;
my Channel $channel-one .= new;
my Channel $to-mix .= new;
my Channel $mixer = $to-mix.Supply.batch( elems => 2).Channel;
my $evaluations = 0;
my $initial-populations = $threads * 1.5;
info(to-json( { length => $length,
population-size => $population-size,
initial-populations => $initial-populations,
generations => $generations,
threads => $threads,
start-at => DateTime.now.Str} ));
# Initialize three populations for the mixer
for ^$initial-populations {
$channel-one.send( 1.rand xx $length );
}
my @promises;
for ^$threads {
my $promise = start react whenever $channel-one -> @crew {
my %fitness-of;
my @unpacked-pop = generate-by-frequencies( $population-size, @crew );
my $population = evaluate( population => @unpacked-pop,
fitness-of => %fitness-of,
evaluator => &max-ones);
my $count = 0;
while $count++ < $generations && best-fitness($population) < $length {
LAST {
if best-fitness($population) >= $length {
info(to-json( { id => $*THREAD.id,
best => best-fitness($population),
found => True,
finishing-at => DateTime.now.Str} ));
say "Solution found" => $evaluations;
$channel-one.close;
} else {
say "Emitting after $count generations in thread ", $*THREAD.id, " Best fitness ",best-fitness($population) ;
info(to-json( { id => $*THREAD.id,
best => best-fitness($population) }));
$to-mix.send( frequencies-best($population, 8) );
}
};
$population = generation( population => $population,
fitness-of => %fitness-of,
evaluator => &max-ones,
population-size => $population-size);
$evaluations += $population.elems;
};
};
@promises.push: $promise;
}
my $pairs = start react whenever $mixer -> @pair {
$to-mix.send( @pair.pick ); # To avoid getting it hanged up
my @new-population = crossover-frequencies( @pair[0], @pair[1] );
$channel-one.send( @new-population);
say "Mixing in ", $*THREAD.id;
};
start { sleep 800; exit }; # Just in case it gets stuck
await @promises;
say "Parameters ==";
say "Evaluations => $evaluations";
for $parameters.kv -> $key, $value {
say "$key → $value";
};
say "=============";
}
|
### ----------------------------------------------------
### -- Algorithm::Evolutionary::Simple
### -- Licenses: Artistic-2.0
### -- Authors: JJ Merelo
### -- File: resources/examples/concurrent-ea-leading-ones.p6
### ----------------------------------------------------
#!/usr/bin/env perl6
use v6;
use lib <../../lib>;
use Algorithm::Evolutionary::Simple;
use Log::Async;
use JSON::Fast;
sub json-formatter ( $m, :$fh ) {
say $m;
$fh.say: to-json( { msg => from-json($m<msg>),
time => $m<when>.Str });
}
logger.send-to("lo-pma-" ~ DateTime.now.Str ~ ".json", formatter => &json-formatter);
sub MAIN( UInt :$length = 48,
UInt :$total-population = 2048,
UInt :$generations = 16,
UInt :$threads = 2
) {
my $parameters = .Capture;
my $population-size = ($total-population/$threads).floor;
my Channel $channel-one .= new;
my Channel $to-mix .= new;
my Channel $mixer = $to-mix.Supply.batch( elems => 2).Channel;
my $evaluations = 0;
my $max-fitness = $length;
my $initial-populations = $threads + 1;
info(to-json( { length => $length,
population-size => $population-size,
initial-populations => $initial-populations,
generations => $generations,
threads => $threads,
start-at => DateTime.now.Str} ));
# Initialize three populations for the mixer
for ^$initial-populations {
$channel-one.send( 1.rand xx $length );
}
my @promises;
for ^$threads {
my $promise = start react whenever $channel-one -> @crew {
my %fitness-of;
my @unpacked-pop = generate-by-frequencies( $population-size, @crew );
my $population = evaluate( population => @unpacked-pop,
fitness-of => %fitness-of,
evaluator => &leading-ones);
my $count = 0;
while $count++ < $generations && best-fitness($population) < $max-fitness {
LAST {
if best-fitness($population) >= $max-fitness {
info(to-json( { id => $*THREAD.id,
best => best-fitness($population),
found => True,
finishing-at => DateTime.now.Str} ));
say "Solution found" => $evaluations;
$channel-one.close;
} else {
say "Emitting after $count generations in thread ", $*THREAD.id, " Best fitness ",best-fitness($population) ;
info(to-json( { id => $*THREAD.id,
best => best-fitness($population) }));
$to-mix.send( frequencies-best($population, 8) );
}
};
$population = generation( population => $population,
fitness-of => %fitness-of,
evaluator => &leading-ones,
population-size => $population-size);
$evaluations += $population.elems;
};
};
@promises.push: $promise;
}
my $pairs = start react whenever $mixer -> @pair {
$to-mix.send( @pair.pick ); # To avoid getting it hanged up
my @new-population = crossover-frequencies( @pair[0], @pair[1] );
$channel-one.send( @new-population);
say "Mixing in ", $*THREAD.id;
};
start { sleep 1200;
say "Reached time limit";
exit
}; # Just in case it gets stuck
await @promises;
say "Parameters ==";
say "Evaluations => $evaluations";
for $parameters.kv -> $key, $value {
say "$key → $value";
};
say "=============";
}
|
### ----------------------------------------------------
### -- Algorithm::Evolutionary::Simple
### -- Licenses: Artistic-2.0
### -- Authors: JJ Merelo
### -- File: resources/examples/concurrent-ea-leading-ones-best.p6
### ----------------------------------------------------
#!/usr/bin/env perl6
use v6;
use lib <../../lib>;
use Algorithm::Evolutionary::Simple;
use Log::Async;
use JSON::Fast;
sub json-formatter ( $m, :$fh ) {
say $m;
$fh.say: to-json( { msg => from-json($m<msg>),
time => $m<when>.Str });
}
logger.send-to("lo-pma-" ~ DateTime.now.Str ~ ".json", formatter => &json-formatter);
sub MAIN( UInt :$length = 48,
UInt :$total-population = 2048,
UInt :$generations = 16,
UInt :$threads = 2
) {
my $parameters = .Capture;
my $population-size = ($total-population/$threads).floor;
my Channel $channel-one .= new;
my Channel $to-mix .= new;
my Channel $mixer = $to-mix.Supply.batch( elems => 2).Channel;
my $evaluations = 0;
my $max-fitness = $length;
my $initial-populations = $threads + 1;
info(to-json( { length => $length,
population-size => $population-size,
initial-populations => $initial-populations,
generations => $generations,
threads => $threads,
start-at => DateTime.now.Str} ));
# Initialize three populations for the mixer
for ^$initial-populations {
$channel-one.send( { freqs => 1.rand xx $length } );
}
my @promises;
for ^$threads {
my $promise = start react whenever $channel-one -> $msg {
dd $msg;
my %fitness-of;
my @unpacked-pop;
if $msg<best> {
@unpacked-pop = generate-with-best( $population-size, @($msg<freqs>), $msg<best> );
} else {
@unpacked-pop = generate-by-frequencies( $population-size, @($msg<freqs>) );
}
my $population = evaluate( population => @unpacked-pop,
fitness-of => %fitness-of,
evaluator => &leading-ones);
my $count = 0;
my $best-one = best-one($population);
my $best-fitness = $best-one.value;
while $count++ < $generations && $best-fitness < $max-fitness {
LAST {
if $best-fitness >= $max-fitness {
info(to-json( { id => $*THREAD.id,
best => $best-fitness,
found => True,
finishing-at => DateTime.now.Str} ));
say "Solution found" => $evaluations;
$channel-one.close;
} else {
say "Emitting after $count generations in thread ", $*THREAD.id, " Best fitness ", $best-fitness ;
info(to-json( { id => $*THREAD.id,
best => $best-fitness }));
$to-mix.send( { freqs => frequencies-best($population, 8),
best => $best-one } );
}
};
$population = generation( population => $population,
fitness-of => %fitness-of,
evaluator => &leading-ones,
population-size => $population-size);
$evaluations += $population.elems;
};
};
@promises.push: $promise;
}
my $pairs = start react whenever $mixer -> @pair {
$to-mix.send( @pair.pick ); # To avoid getting it hanged up
my @new-population = crossover-frequencies( @pair[0]<freqs>, @pair[1]<freqs> );
my $best-one = (@pair[0]<best>.value > @pair[1]<best>.value ) ?? @pair[0]<best> !! @pair[1]<best>;
$channel-one.send( { freqs => @new-population,
best => $best-one } );
say "Mixing in ", $*THREAD.id;
};
start { sleep 1200;
say "Reached time limit";
exit
}; # Just in case it gets stuck
await @promises;
say "Parameters ==";
say "Evaluations => $evaluations";
for $parameters.kv -> $key, $value {
say "$key → $value";
};
say "=============";
}
|
### ----------------------------------------------------
### -- Algorithm::Evolutionary::Simple
### -- Licenses: Artistic-2.0
### -- Authors: JJ Merelo
### -- File: resources/examples/population-mixer-freqs-ap-rr.p6
### ----------------------------------------------------
#!/usr/bin/env perl6
use v6;
use lib <../../lib>;
use Algorithm::Evolutionary::Simple;
use Log::Async;
use JSON::Fast;
sub json-formatter ( $m, :$fh ) {
say $m;
$fh.say: to-json( { msg => from-json($m<msg>),
time => $m<when>.Str });
}
logger.send-to("rr-pma-" ~ DateTime.now.Str ~ ".json", formatter => &json-formatter);
sub MAIN( UInt :$length = 64,
UInt :$total-population = 8192,
UInt :$generations = 8,
UInt :$threads = 2
) {
my $parameters = .Capture;
my $population-size = ($total-population/$threads).floor;
my Channel $channel-one .= new;
my Channel $to-mix .= new;
my Channel $mixer = $to-mix.Supply.batch( elems => 2).Channel;
my $evaluations = 0;
my $initial-populations = $threads + 1;
info(to-json( { length => $length,
population-size => $population-size,
initial-populations => $initial-populations,
generations => $generations,
threads => $threads,
start-at => DateTime.now.Str} ));
# Initialize three populations for the mixer
for ^$initial-populations {
$channel-one.send( 1.rand xx $length );
}
my @promises;
for ^$threads {
my $promise = start react whenever $channel-one -> @crew {
my %fitness-of;
my @unpacked-pop = generate-by-frequencies( $population-size, @crew );
my $population = evaluate( population => @unpacked-pop,
fitness-of => %fitness-of,
evaluator => &royal-road);
my $count = 0;
while $count++ < $generations && best-fitness($population) < $length/4 {
LAST {
if best-fitness($population) >= $length/4 {
info(to-json( { id => $*THREAD.id,
best => best-fitness($population),
found => True,
finishing-at => DateTime.now.Str} ));
say "Solution found" => $evaluations;
$channel-one.close;
} else {
say "Emitting after $count generations in thread ", $*THREAD.id, " Best fitness ",best-fitness($population) ;
info(to-json( { id => $*THREAD.id,
best => best-fitness($population) }));
$to-mix.send( frequencies-best($population, 8) );
}
};
$population = generation( population => $population,
fitness-of => %fitness-of,
evaluator => &royal-road,
population-size => $population-size);
$evaluations += $population.elems;
};
};
@promises.push: $promise;
}
my $pairs = start react whenever $mixer -> @pair {
$to-mix.send( @pair.pick ); # To avoid getting it hanged up
my @new-population = crossover-frequencies( @pair[0], @pair[1] );
$channel-one.send( @new-population);
say "Mixing in ", $*THREAD.id;
};
start { sleep 800;
say "Reached time limit";
exit
}; # Just in case it gets stuck
await @promises;
say "Parameters ==";
say "Evaluations => $evaluations";
for $parameters.kv -> $key, $value {
say "$key → $value";
};
say "=============";
}
|
### ----------------------------------------------------
### -- Algorithm::Evolutionary::Simple
### -- Licenses: Artistic-2.0
### -- Authors: JJ Merelo
### -- File: resources/examples/README.md
### ----------------------------------------------------
# Evolutionary computation examples
This directory contains most of the examples used in several papers on
evolutionary algorithms in Perl 6, as well as bash scripts needed to
run them.
If you want to run them, first go to the main directory and run
zef install --deps-only .
Come back to this directory, and run, for instance
nohup ./pop-mixer-fan-compress-gecco-generations.sh >> evosoft-2019-2.dat 2> evosoft-2019-2.err < /dev/null
(Just in case you will leave it running on a server. Check out the
shell script for the program it's running; right now it's the leading
ones).
This will leave a slew of JSON files, which you use late on for
post-mortem analysis.
|
### ----------------------------------------------------
### -- Algorithm::Evolutionary::Simple
### -- Licenses: Artistic-2.0
### -- Authors: JJ Merelo
### -- File: resources/examples/population-mixer-compress.p6
### ----------------------------------------------------
#!/usr/bin/env perl6
use v6;
use lib <../../lib>;
use Algorithm::Evolutionary::Simple;
use Log::Async;
use JSON::Fast;
sub json-formatter ( $m, :$fh ) {
say $m;
$fh.say: to-json( { msg => from-json($m<msg>),
time => $m<when>.Str });
}
logger.send-to("pmg-" ~ DateTime.now.Str ~ ".json", formatter => &json-formatter);
sub MAIN( UInt :$length = 64,
UInt :$population-size = 256,
UInt :$generations = 16,
UInt :$threads = 2
) {
my $initial-populations = $threads * 1.5;
info(to-json( { length => $length,
initial-populations => $initial-populations,
population-size => $population-size,
generations => $generations,
threads => $threads,
start-at => DateTime.now.Str} ));
my $parameters = .Capture;
my Channel $channel-one .= new;
my Channel $to-mix .= new;
my Channel $mixer = $to-mix.Supply.batch( elems => 2).Channel;
my $evaluations = 0;
# Initialize three populations for the mixer
for ^$initial-populations {
my @initial-population = initialize( size => $population-size,
genome-length => $length );
my %fitness-of;
my $population = evaluate( population => @initial-population,
fitness-of => %fitness-of,
evaluator => &max-ones );
$evaluations += $population.elems;
$channel-one.send( pack-population($population.keys) );
}
my @promises;
for ^$threads {
my $promise = start react whenever $channel-one -> $crew {
my @unpacked-pop = unpack-population( $crew, $length );
my %fitness-of;
my $population = evaluate( population => @unpacked-pop,
fitness-of => %fitness-of,
evaluator => &max-ones );
my $count = 0;
while $count++ < $generations && best-fitness($population) < $length {
LAST {
say "In LAST";
say "Best-fitness ", best-fitness($population);
if best-fitness($population) >= $length {
info(to-json( { id => $*THREAD.id,
best => best-fitness($population),
found => True,
finishing-at => DateTime.now.Str} ));
say "Solution found" => $evaluations;
$channel-one.close;
} else {
say "Emitting after $count generations in thread ", $*THREAD.id, " Best fitness ",best-fitness($population) ;
info(to-json( { id => $*THREAD.id,
best => best-fitness($population) }));
$to-mix.send( pack-population($population.keys) );
}
};
$population = generation( population => $population,
fitness-of => %fitness-of,
evaluator => &max-ones,
population-size => $population-size);
$evaluations += $population.elems;
};
};
@promises.push: $promise;
}
my $pairs = start react whenever $mixer -> @pair {
$to-mix.send( @pair.pick ); # To avoid getting it hanged up
my @new-population = unpack-population(@pair[0], $length);
my @new-population-prime = unpack-population(@pair[1], $length);
my $new-population = mix-raw( @new-population,
@new-population-prime,
$population-size,
&max-ones );
$channel-one.send( pack-population($new-population.keys));
say "Mixing in ", $*THREAD.id;
};
start { sleep 800; exit }; # Just in case it gets stuck
await @promises;
say "Parameters ==";
say "Evaluations => $evaluations";
for $parameters.kv -> $key, $value {
say "$key → $value";
};
say "=============";
return $evaluations;
}
|
### ----------------------------------------------------
### -- Algorithm::Evolutionary::Simple
### -- Licenses: Artistic-2.0
### -- Authors: JJ Merelo
### -- File: resources/examples/population-mixer-compress-fan.p6
### ----------------------------------------------------
#!/usr/bin/env perl6
use v6;
use lib <../../lib>;
use Algorithm::Evolutionary::Simple;
use Log::Async;
use JSON::Fast;
sub json-formatter ( $m, :$fh ) {
say $m;
$fh.say: to-json( { msg => from-json($m<msg>),
time => $m<when>.Str });
}
logger.send-to("pmo-" ~ DateTime.now.Str ~ ".json", formatter => &json-formatter);
sub MAIN( UInt :$length = 64,
UInt :$population-size = 256,
UInt :$generations = 16,
UInt :$threads = 2
) {
my $initial-populations = $threads * 1.5;
info(to-json( { length => $length,
initial-populations => $initial-populations,
population-size => $population-size,
generations => $generations,
threads => $threads,
start-at => DateTime.now.Str} ));
my $parameters = .Capture;
my Channel $channel-one .= new;
my Channel $to-mix .= new;
my Channel $mixer = $to-mix.Supply.batch( elems => 2).Channel;
my $evaluations = 0;
# Initialize three populations for the mixer
for ^$initial-populations {
my @initial-population = initialize( size => $population-size,
genome-length => $length );
my %fitness-of;
my $population = evaluate( population => @initial-population,
fitness-of => %fitness-of,
evaluator => &max-ones );
$evaluations += $population.elems;
$channel-one.send( pack-population($population.keys) );
}
my @promises;
for ^$threads {
my $promise = start react whenever $channel-one -> $crew {
my @unpacked-pop = unpack-population( $crew, $length );
my %fitness-of;
my $population = evaluate( population => @unpacked-pop,
fitness-of => %fitness-of,
evaluator => &max-ones );
my $count = 0;
while $count++ < $generations && best-fitness($population) < $length {
LAST {
say "In LAST";
say "Best-fitness ", best-fitness($population);
if best-fitness($population) >= $length {
info(to-json( { id => $*THREAD.id,
best => best-fitness($population),
found => True,
finishing-at => DateTime.now.Str} ));
say "Solution found" => $evaluations;
$channel-one.close;
} else {
say "Emitting after $count generations in thread ", $*THREAD.id, " Best fitness ",best-fitness($population) ;
info(to-json( { id => $*THREAD.id,
best => best-fitness($population) }));
$to-mix.send( pack-population($population.keys) );
$channel-one.send( pack-population($population.keys) );
}
};
$population = generation( population => $population,
fitness-of => %fitness-of,
evaluator => &max-ones,
population-size => $population-size);
$evaluations += $population.elems;
};
};
@promises.push: $promise;
}
my $pairs = start react whenever $mixer -> @pair {
my @new-population = unpack-population(@pair[0], $length);
my @new-population-prime = unpack-population(@pair[1], $length);
my $new-population = mix-raw( @new-population,
@new-population-prime,
$population-size,
&max-ones );
$channel-one.send( pack-population($new-population.keys));
say "Mixing in ", $*THREAD.id;
};
start { sleep 800; exit }; # Just in case it gets stuck
await @promises;
say "Parameters ==";
say "Evaluations => $evaluations";
for $parameters.kv -> $key, $value {
say "$key → $value";
};
say "=============";
return $evaluations;
}
|
### ----------------------------------------------------
### -- Algorithm::Evolutionary::Simple
### -- Licenses: Artistic-2.0
### -- Authors: JJ Merelo
### -- File: resources/examples/population-mixer-freqs-ap.p6
### ----------------------------------------------------
#!/usr/bin/env perl6
use v6;
use lib <../../lib>;
use Algorithm::Evolutionary::Simple;
use Log::Async;
use JSON::Fast;
sub json-formatter ( $m, :$fh ) {
say $m;
$fh.say: to-json( { msg => from-json($m<msg>),
time => $m<when>.Str });
}
logger.send-to("pma-" ~ DateTime.now.Str ~ ".json", formatter => &json-formatter);
sub MAIN( UInt :$length = 64,
UInt :$total-population = 512,
UInt :$generations = 8,
UInt :$threads = 2
) {
my $parameters = .Capture;
my $population-size = ($total-population/$threads).floor;
my Channel $channel-one .= new;
my Channel $to-mix .= new;
my Channel $mixer = $to-mix.Supply.batch( elems => 2).Channel;
my $evaluations = 0;
my $initial-populations = $threads + 1;
info(to-json( { length => $length,
population-size => $population-size,
initial-populations => $initial-populations,
generations => $generations,
threads => $threads,
start-at => DateTime.now.Str} ));
# Initialize three populations for the mixer
for ^$initial-populations {
$channel-one.send( 1.rand xx $length );
}
my @promises;
for ^$threads {
my $promise = start react whenever $channel-one -> @crew {
my %fitness-of;
my @unpacked-pop = generate-by-frequencies( $population-size, @crew );
my $population = evaluate( population => @unpacked-pop,
fitness-of => %fitness-of,
evaluator => &max-ones);
my $count = 0;
while $count++ < $generations && best-fitness($population) < $length {
LAST {
if best-fitness($population) >= $length {
info(to-json( { id => $*THREAD.id,
best => best-fitness($population),
found => True,
finishing-at => DateTime.now.Str} ));
say "Solution found" => $evaluations;
$channel-one.close;
} else {
say "Emitting after $count generations in thread ", $*THREAD.id, " Best fitness ",best-fitness($population) ;
info(to-json( { id => $*THREAD.id,
best => best-fitness($population) }));
$to-mix.send( frequencies-best($population, 8) );
}
};
$population = generation( population => $population,
fitness-of => %fitness-of,
evaluator => &max-ones,
population-size => $population-size);
$evaluations += $population.elems;
};
};
@promises.push: $promise;
}
my $pairs = start react whenever $mixer -> @pair {
$to-mix.send( @pair.pick ); # To avoid getting it hanged up
my @new-population = crossover-frequencies( @pair[0], @pair[1] );
$channel-one.send( @new-population);
say "Mixing in ", $*THREAD.id;
};
start { sleep 800; exit }; # Just in case it gets stuck
await @promises;
say "Parameters ==";
say "Evaluations => $evaluations";
for $parameters.kv -> $key, $value {
say "$key → $value";
};
say "=============";
}
|
### ----------------------------------------------------
### -- Algorithm::Evolutionary::Simple
### -- Licenses: Artistic-2.0
### -- Authors: JJ Merelo
### -- File: resources/examples/population-mixer-compress-nowb.p6
### ----------------------------------------------------
#!/usr/bin/env perl6
use v6;
use lib <../../lib>;
use Algorithm::Evolutionary::Simple;
use Log::Async;
use JSON::Fast;
sub json-formatter ( $m, :$fh ) {
say $m;
$fh.say: to-json( { msg => from-json($m<msg>),
time => $m<when>.Str });
}
logger.send-to("pmn-" ~ DateTime.now.Str ~ ".json", formatter => &json-formatter);
sub MAIN( UInt :$length = 64,
UInt :$population-size = 256,
UInt :$generations = 8,
UInt :$threads = 2
) {
my $initial-populations = $threads + 1;
info(to-json( { length => $length,
initial-populations => $initial-populations,
population-size => $population-size,
generations => $generations,
threads => $threads,
start-at => DateTime.now.Str} ));
my $parameters = .Capture;
my Channel $channel-one .= new;
my Channel $to-mix .= new;
my Channel $mixer = $to-mix.Supply.batch( elems => 2).Channel;
my $evaluations = 0;
# Initialize three populations for the mixer
for ^$initial-populations {
my @initial-population = initialize( size => $population-size,
genome-length => $length );
my %fitness-of;
my $population = evaluate( population => @initial-population,
fitness-of => %fitness-of,
evaluator => &max-ones );
$evaluations += $population.elems;
$channel-one.send( pack-population($population.keys) );
}
my @promises;
for ^$threads {
my $promise = start react whenever $channel-one -> $crew {
my @unpacked-pop = unpack-population( $crew, $length );
my %fitness-of;
my $population = evaluate( population => @unpacked-pop,
fitness-of => %fitness-of,
evaluator => &max-ones );
my $count = 0;
while $count++ < $generations && best-fitness($population) < $length {
LAST {
say "In LAST";
say "Best-fitness ", best-fitness($population);
if best-fitness($population) >= $length {
info(to-json( { id => $*THREAD.id,
best => best-fitness($population),
found => True,
finishing-at => DateTime.now.Str} ));
say "Solution found" => $evaluations;
$channel-one.close;
} else {
say "Emitting after $count generations in thread ", $*THREAD.id, " Best fitness ",best-fitness($population) ;
info(to-json( { id => $*THREAD.id,
best => best-fitness($population) }));
$to-mix.send( pack-population($population.keys) );
}
};
$population = generation( population => $population,
fitness-of => %fitness-of,
evaluator => &max-ones,
population-size => $population-size);
$evaluations += $population.elems;
};
};
@promises.push: $promise;
}
my $pairs = start react whenever $mixer -> @pair {
$channel-one.send( @pair.pick ); # To avoid getting it hanged up
my @new-population = unpack-population(@pair[0], $length);
my @new-population-prime = unpack-population(@pair[1], $length);
my $new-population = mix-raw( @new-population,
@new-population-prime,
$population-size,
&max-ones );
$channel-one.send( pack-population($new-population.keys));
say "Mixing in ", $*THREAD.id;
};
start { sleep 800; exit }; # Just in case it gets stuck
await @promises;
say "Parameters ==";
say "Evaluations => $evaluations";
for $parameters.kv -> $key, $value {
say "$key → $value";
};
say "=============";
return $evaluations;
}
|
### ----------------------------------------------------
### -- Algorithm::Evolutionary::Simple
### -- Licenses: Artistic-2.0
### -- Authors: JJ Merelo
### -- File: resources/examples/channel.p6
### ----------------------------------------------------
#!/usr/bin/env perl6
# An example of using concurrent evaluation with channels
use v6;
use Algorithm::Evolutionary::Simple;
my $length = 16;
my Channel $channel-pop .= new;
my Channel $channel-batch = $channel-pop.Supply.batch( elems => 2).Channel;
my Channel $output .= new;
my $count = 0;
$channel-pop.send( random-chromosome($length).list ) for ^11;
my $pairs = start react whenever $channel-batch -> @pair {
if ( $count++ < 100 ) {
say "In Channel 2: ", @pair;
$output.send( $_ => max-ones($_) ) for @pair;
my @new-chromosome = crossover( @pair[0], @pair[1] );
$channel-pop.send( $_.list ) for @new-chromosome;
} else {
say "Closing channel";
$channel-pop.close;
}
}
await $pairs;
loop {
if my $item = $output.poll {
$item.say;
} else {
$output.close;
}
if $output.closed { last };
}
|
### ----------------------------------------------------
### -- Algorithm::Evolutionary::Simple
### -- Licenses: Artistic-2.0
### -- Authors: JJ Merelo
### -- File: resources/examples/max-ones.p6
### ----------------------------------------------------
#!/usr/bin/env raku
use v6;
use lib <lib ../../lib>;
use Algorithm::Evolutionary::Simple;
use Log::Async;
use JSON::Fast;
sub json-formatter ( $m, :$fh ) {
say $m;
$fh.say: to-json( { msg => from-json($m<msg>),
time => $m<when>.Str });
}
logger.send-to("max-ones-" ~ DateTime.now.Str ~ ".json", formatter => &json-formatter);
sub MAIN ( UInt :$repetitions = 30,
UInt :$length = 64,
UInt :$population-size = 256 ) {
my @found;
info(to-json( { length => $length,
population-size => $population-size,
start-at => DateTime.now.Str} ));
for ^$repetitions {
my @initial-population = initialize( size => $population-size,
genome-length => $length );
my %fitness-of;
my $population = evaluate( population => @initial-population,
fitness-of => %fitness-of,
evaluator => &max-ones );
my $result = 0;
while $population.sort(*.value).reverse.[0].value < $length {
$population = generation( population => $population,
fitness-of => %fitness-of,
evaluator => &max-ones,
population-size => $population-size) ;
$result += $population-size;
info(to-json( { best => best-fitness($population) } ));
}
info(to-json( { best => best-fitness($population),
found => True,
finishing-at => DateTime.now.Str} ));
@found.push( $result );
}
say "Found ", @found;
}
|
### ----------------------------------------------------
### -- Algorithm::Evolutionary::Simple
### -- Licenses: Artistic-2.0
### -- Authors: JJ Merelo
### -- File: resources/examples/population-mixer.p6
### ----------------------------------------------------
#!/usr/bin/env perl6
use v6;
use lib <../../lib>;
use Algorithm::Evolutionary::Simple;
use Log::Async;
use JSON::Fast;
sub json-formatter ( $m, :$fh ) {
say $m;
$fh.say: to-json( { msg => from-json($m<msg>),
time => $m<when>.Str });
}
logger.send-to("population-mixer-" ~ DateTime.now.Str ~ ".json", formatter => &json-formatter);
sub mixer-EA( |parameters (
UInt :$length = 64,
UInt :$initial-populations = 3,
UInt :$population-size = 256,
UInt :$generations = 8,
UInt :$threads = 1
)
) {
info(to-json( { length => $length,
initial-populations => $initial-populations,
population-size => $population-size,
generations => $generations,
threads => $threads,
start-at => DateTime.now.Str} ));
my Channel $channel-one .= new;
my Channel $to-mix .= new;
my Channel $mixer = $to-mix.Supply.batch( elems => 2).Channel;
my $evaluations = 0;
# Initialize three populations for the mixer
for ^$initial-populations {
my @initial-population = initialize( size => $population-size,
genome-length => $length );
my %fitness-of;
my $population = evaluate( population => @initial-population,
fitness-of => %fitness-of,
evaluator => &max-ones );
$evaluations += $population.elems;
$channel-one.send( $population );
}
my @promises;
for ^$threads {
my $promise = start react whenever $channel-one -> $crew {
my $population = $crew.Mix;
my $count = 0;
my %fitness-of = $population.Hash;
while $count++ < $generations && best-fitness($population) < $length {
LAST {
if best-fitness($population) >= $length {
info(to-json( { id => $*THREAD.id,
best => best-fitness($population),
found => True,
finishing-at => DateTime.now.Str} ));
say "Solution found" => $evaluations;
$channel-one.close;
} else {
say "Emitting after $count generations in thread ", $*THREAD.id, " Best fitness ",best-fitness($population) ;
info(to-json( { id => $*THREAD.id,
best => best-fitness($population) }));
$to-mix.send( $population );
}
};
$population = generation( population => $population,
fitness-of => %fitness-of,
evaluator => &max-ones,
population-size => $population-size);
$evaluations += $population.elems;
};
};
@promises.push: $promise;
}
my $pairs = start react whenever $mixer -> @pair {
$to-mix.send( @pair.pick ); # To avoid getting it hanged up
$channel-one.send(mix( @pair[0], @pair[1], $population-size ));
say "Mixing in ", $*THREAD.id;
};
await @promises;
say "Parameters ==";
say "Evaluations => $evaluations";
for parameters.kv -> $key, $value {
say "$key → $value";
};
say "=============";
return $evaluations;
}
sub MAIN ( UInt :$repetitions = 30,
UInt :$initial-populations = 3,
UInt :$length = 64,
UInt :$population-size = 256,
UInt :$generations=8,
UInt :$threads = 1 ) {
my @results;
for ^$repetitions {
my $result = mixer-EA( length => $length,
initial-populations => $initial-populations,
population-size => $population-size,
generations => $generations,
threads => $threads );
push @results, $result;
}
say @results;
}
|
### ----------------------------------------------------
### -- Algorithm::Evolutionary::Simple
### -- Licenses: Artistic-2.0
### -- Authors: JJ Merelo
### -- File: resources/examples/population-mixer-freqs-nowb.p6
### ----------------------------------------------------
#!/usr/bin/env perl6
use v6;
use lib <../../lib>;
use Algorithm::Evolutionary::Simple;
use Log::Async;
use JSON::Fast;
sub json-formatter ( $m, :$fh ) {
say $m;
$fh.say: to-json( { msg => from-json($m<msg>),
time => $m<when>.Str });
}
logger.send-to("pmw-" ~ DateTime.now.Str ~ ".json", formatter => &json-formatter);
sub MAIN( UInt :$length = 64,
UInt :$population-size = 256,
UInt :$generations = 8,
UInt :$threads = 2
) {
my $parameters = .Capture;
my Channel $channel-one .= new;
my Channel $to-mix .= new;
my Channel $mixer = $to-mix.Supply.batch( elems => 2).Channel;
my $evaluations = 0;
my $initial-populations = $threads * 2;
info(to-json( { length => $length,
population-size => $population-size,
initial-populations => $initial-populations,
generations => $generations,
threads => $threads,
start-at => DateTime.now.Str} ));
# Initialize three populations for the mixer
for ^$initial-populations {
$channel-one.send( 1.rand xx $length );
}
my @promises;
for ^$threads {
my $promise = start react whenever $channel-one -> @crew {
my %fitness-of;
my @unpacked-pop = generate-by-frequencies( $population-size, @crew );
my $population = evaluate( population => @unpacked-pop,
fitness-of => %fitness-of,
evaluator => &max-ones);
my $count = 0;
while $count++ < $generations && best-fitness($population) < $length {
LAST {
if best-fitness($population) >= $length {
info(to-json( { id => $*THREAD.id,
best => best-fitness($population),
found => True,
finishing-at => DateTime.now.Str} ));
say "Solution found" => $evaluations;
$channel-one.close;
} else {
say "Emitting after $count generations in thread ", $*THREAD.id, " Best fitness ",best-fitness($population) ;
info(to-json( { id => $*THREAD.id,
best => best-fitness($population) }));
$to-mix.send( frequencies-best($population, 8) );
}
};
$population = generation( population => $population,
fitness-of => %fitness-of,
evaluator => &max-ones,
population-size => $population-size);
$evaluations += $population.elems;
};
};
@promises.push: $promise;
}
my $pairs = start react whenever $mixer -> @pair {
$channel-one.send( @pair.pick ); # To avoid getting it hanged up
my @new-population = crossover-frequencies( @pair[0], @pair[1] );
$channel-one.send( @new-population);
say "Mixing in ", $*THREAD.id;
};
start { sleep 800; exit }; # Just in case it gets stuck
await @promises;
say "Parameters ==";
say "Evaluations => $evaluations";
for $parameters.kv -> $key, $value {
say "$key → $value";
};
say "=============";
}
|
### ----------------------------------------------------
### -- Algorithm::Evolutionary::Simple
### -- Licenses: Artistic-2.0
### -- Authors: JJ Merelo
### -- File: resources/examples/concurrent-evaluation.p6
### ----------------------------------------------------
#!/usr/bin/env perl6
use v6;
use Algorithm::Evolutionary::Simple;
my $length = 16;
my Channel $channel-pop .= new;
my Channel $channel-batch = $channel-pop.Supply.batch( elems => 2).Channel;
my Channel $output .= new;
my $count = 0;
$channel-pop.send( random-chromosome($length).list ) for ^11;
my $pairs = start react whenever $channel-batch -> @pair {
if ( $count++ < 100 ) {
say "In Channel 2: ", @pair;
$output.send( $_ => max-ones($_) ) for @pair;
my @new-chromosome = crossover( @pair[0], @pair[1] );
$channel-pop.send( $_.list ) for @new-chromosome;
} else {
say "Closing channel";
$channel-pop.close;
}
}
await $pairs;
loop {
if my $item = $output.poll {
$item.say;
} else {
$output.close;
}
if $output.closed { last };
}
|
### ----------------------------------------------------
### -- Algorithm::Evolutionary::Simple
### -- Licenses: Artistic-2.0
### -- Authors: JJ Merelo
### -- File: resources/examples/population-mixer-old.p6
### ----------------------------------------------------
#!/usr/bin/env perl6
use v6;
use lib <../../lib>;
use Algorithm::Evolutionary::Simple;
use Log::Async;
sub json-formatter ( $m, :$fh ) {
say $m;
$fh.say: to-json( { msg => from-json($m<msg>),
time => $m<when>.Str });
}
logger.send-to("population-mixer-" ~ DateTime.now.Str ~ ".json", formatter => &json-formatter);
sub mixer-EA( |parameters (
UInt :$length = 64,
UInt :$initial-populations = 3,
UInt :$population-size = 256,
UInt :$generations = 8,
UInt :$threads = 2
)
) {
info(to-json( { length => $length,
initial-populations => $initial-populations,
population-size => $population-size,
generations => $generations,
threads => $threads,
start-at => DateTime.now.Str} ));
my Channel $channel-one .= new;
my Channel $to-mix .= new;
my Channel $mixer = $to-mix.Supply.batch( elems => 2).Channel;
my $evaluations = 0;
# Initialize three populations for the mixer
for ^$initial-populations {
my @initial-population = initialize( size => $population-size,
genome-length => $length );
my %fitness-of;
my $population = evaluate( population => @initial-population,
fitness-of => %fitness-of,
evaluator => &max-ones );
$evaluations += $population.elems;
$channel-one.send( $population );
}
my $single = ( start react whenever $channel-one -> $crew {
my $population = $crew.Mix;
my $count = 0;
my %fitness-of = $population.Hash;
while $count++ < $generations && best-fitness($population) < $length {
LAST {
if best-fitness($population) >= $length {
info(to-json( { id => $*THREAD.id,
best => best-fitness($population),
found => True,
finishing-at => DateTime.now.Str} ));
say "Solution found" => $evaluations;
$channel-one.close;
} else {
say "Emitting after $count generations in thread ", $*THREAD.id, " Best fitness ",best-fitness($population) ;
info(to-json( { id => $*THREAD.id,
best => best-fitness($population) }));
$to-mix.send( $population );
}
};
$population = generation( population => $population,
fitness-of => %fitness-of,
evaluator => &max-ones,
population-size => $population-size);
$evaluations += $population.elems;
}
} for ^$threads );
my $pairs = start react whenever $mixer -> @pair {
$to-mix.send( @pair.pick ); # To avoid getting it hanged up
$channel-one.send(mix( @pair[0], @pair[1], $population-size ));
say "Mixing in ", $*THREAD.id;
};
await $single;
say "Parameters ==";
say "Evaluations => $evaluations";
for parameters.kv -> $key, $value {
say "$key → $value";
};
say "=============";
return $evaluations;
}
sub MAIN ( UInt :$repetitions = 30,
UInt :$initial-populations = 3,
UInt :$length = 64,
UInt :$population-size = 256,
UInt :$generations=8,
UInt :$threads = 1 ) {
my @results;
for ^$repetitions {
my $result = mixer-EA( length => $length,
initial-populations => $initial-populations,
population-size => $population-size,
generations => $generations,
threads => $threads );
push @results, $result;
}
say @results;
}
|
### ----------------------------------------------------
### -- Algorithm::Evolutionary::Simple
### -- Licenses: Artistic-2.0
### -- Authors: JJ Merelo
### -- File: resources/benchmarks/evaluation-autothreading.p6
### ----------------------------------------------------
#!/usr/bin/env p6
# Examples of using auto-threading with a heavy function, P-Peaks.
use v6;
use Algorithm::Evolutionary::Simple;
use Algorithm::Evolutionary::Fitness::P-Peaks;
sub MAIN ( UInt :$repetitions = 30,
UInt :$length = 32,
UInt :$number-of-peaks = 100,
UInt :$population-size = 1024 ) {
my $p-peaks = Algorithm::Evolutionary::Fitness::P-Peaks.new: number-of-peaks => $number-of-peaks, bits => $length;
my $length-peaks = -> @chromosome { $p-peaks.distance( @chromosome ) };
my $start = now;
for ^$repetitions {
my @initial-population = initialize( size => $population-size,
genome-length => $length );
my %fitness-of;
my $population = evaluate( population => @initial-population,
fitness-of => %fitness-of,
evaluator => $length-peaks,
auto-t => True );
}
say "Time → ", now - $start;
}
|
### ----------------------------------------------------
### -- Algorithm::Evolutionary::Simple
### -- Licenses: Artistic-2.0
### -- Authors: JJ Merelo
### -- File: resources/benchmarks/sequential-evaluation.p6
### ----------------------------------------------------
#!/usr/bin/env p6
# Examples of using auto-threading with a heavy function, P-Peaks.
use v6;
use Algorithm::Evolutionary::Simple;
use Algorithm::Evolutionary::Fitness::P-Peaks;
sub MAIN ( UInt :$repetitions = 30,
UInt :$length = 32,
UInt :$number-of-peaks = 100,
UInt :$population-size = 1024 ) {
my $p-peaks = Algorithm::Evolutionary::Fitness::P-Peaks.new: number-of-peaks => $number-of-peaks, bits => $length;
my $length-peaks = -> @chromosome { $p-peaks.distance( @chromosome ) };
my $start = now;
for ^$repetitions {
my @initial-population = initialize( size => $population-size,
genome-length => $length );
my %fitness-of;
my $population = evaluate( population => @initial-population,
fitness-of => %fitness-of,
evaluator => $length-peaks );
}
say "Time → ", now - $start;
}
|
### ----------------------------------------------------
### -- Algorithm::Evolutionary::Simple
### -- Licenses: Artistic-2.0
### -- Authors: JJ Merelo
### -- File: resources/benchmarks/benchmark-max-ones.p6
### ----------------------------------------------------
#!/usr/bin/env p6
use v6;
use Algorithm::Evolutionary::Simple;
sub MAIN ( UInt :$length is copy = 32,
UInt :$how-many = 10000 ) {
while $length <= 2048 {
my $start = now;
for 1..$how-many {
my @ones = Bool.roll xx $length ;
my $maxones = max-ones(@ones);
}
say "perl6-BitVector, $length, ",now - $start;
$length = $length*2;
}
}
|
### ----------------------------------------------------
### -- Algorithm::Evolutionary::Simple
### -- Licenses: Artistic-2.0
### -- Authors: JJ Merelo
### -- File: t/04-leading-ones.t
### ----------------------------------------------------
#!/usr/bin/env perl6
use v6;
use Test;
use Algorithm::Evolutionary::Simple;
my $length = 64;
my @χ= random-chromosome( $length );
cmp-ok( leading-ones( @χ ), ">=", 0, "Basic testing Leading Ones");
@χ = ( True, True, True, True, False, False, False, False, True, False, True, False );
is( leading-ones( @χ ), 4, "Testing Leading Ones");
@χ = ( False, True, True, True, False, False, False, False, True, False, True, False );
is( leading-ones( @χ ), 0, "Testing Leading Ones - no leading one");
@χ = (True xx 33);
is( leading-ones( @χ ), 33, "Testing Leading Ones - all ones");
done-testing;
|
### ----------------------------------------------------
### -- Algorithm::Evolutionary::Simple
### -- Licenses: Artistic-2.0
### -- Authors: JJ Merelo
### -- File: t/00-functions.t
### ----------------------------------------------------
#!/usr/bin/env perl6
use v6;
use Test;
use Algorithm::Evolutionary::Simple;
my $length = 32;
my $population-size = 32;
my @initial-population;
for 1..$population-size -> $p {
@initial-population.push: random-chromosome( $length );
cmp-ok( @initial-population[$p-1], "==", mutation( @initial-population[$p-1] ), "Mutation works" );
}
my @another-population = initialize( size => $population-size,
genome-length => $length );
cmp-ok( @another-population.elems, "==", $population-size );
# Crossover
my @χs = crossover( @initial-population[0], @initial-population[1]);
cmp-ok( @initial-population[$_], &[!eqv], @χs[$_], "$_ chromosome xovered" ) for 0..1;
# Evaluation
my %fitness-of;
my $population = evaluate( population => @initial-population,
fitness-of => %fitness-of,
evaluator => &max-ones );
my $one-of-them = $population.roll();
ok( %fitness-of{$one-of-them}, "Evaluated to " ~ %fitness-of{$one-of-them});
my $best = $population.sort(*.value).reverse.[0..1].Mix;
my $initial-fitness = $best.values.[0];
my @pool = get-pool-roulette-wheel( $population, $population-size-2);
cmp-ok( @pool.elems, "==", $population-size-2, "Correct number of elements" );
# Reproduce
my @new-population= produce-offspring( @pool );
cmp-ok( @new-population.elems, "==", $population-size-2, "Correct number of elements in reproduction" );
$population = (evaluate( population => @new-population,
fitness-of => %fitness-of,
evaluator => &max-ones ) ∪ $best).Mix;
cmp-ok( $population.elems, "<=", $population-size, "Correct number of elements in new generation" );
my $now-fitness = $population.sort(*.value).reverse.[0].value;
cmp-ok( $now-fitness, ">=", $initial-fitness, "Improving fitness " );
$population = generation( population => $population,
fitness-of => %fitness-of,
evaluator => &max-ones,
population-size => $population-size);
my $evolved-fitness = $population.sort(*.value).reverse.[0].value;
cmp-ok( $evolved-fitness, ">=", $now-fitness, "Improving fitness by evolving " );
# Merge populations
my $another-population = evaluate( population => @another-population,
fitness-of => %fitness-of,
evaluator => &max-ones,
auto-t => True);
$population = generation( population => $another-population,
fitness-of => %fitness-of,
evaluator => &max-ones,
population-size => $population-size,
auto-t => True);
$evolved-fitness = $population.sort(*.value).reverse.[0].value;
my $merged = mix( $population, $another-population, $population-size);
cmp-ok( best-fitness($merged), ">=", $evolved-fitness, "Improving fitness by mixing " );
# Merge populations
$another-population = $population;
$evolved-fitness = $population.sort(*.value).reverse.[0].value;
$population = generation( population => $another-population,
fitness-of => %fitness-of,
evaluator => &max-ones,
population-size => $population-size,
:no-mutation);
$merged = mix( $population, $another-population, $population-size);
cmp-ok( best-fitness($merged), ">=", $evolved-fitness, "Improving fitness by mixing " );
done-testing;
|
### ----------------------------------------------------
### -- Algorithm::Evolutionary::Simple
### -- Licenses: Artistic-2.0
### -- Authors: JJ Merelo
### -- File: t/02-royal-road.t
### ----------------------------------------------------
#!/usr/bin/env perl6
use v6;
use Test;
use Algorithm::Evolutionary::Simple;
my $length = 32;
my @χ= random-chromosome( $length );
cmp-ok( royal-road( @χ ), ">=", 0, "Basic testing Royal Road");
@χ = ( True, True, True, True, False, False, False, False, True, False, True, False );
is( royal-road( @χ ), 2, "Testing Royal Road");
done-testing;
|
### ----------------------------------------------------
### -- Algorithm::Evolutionary::Simple
### -- Licenses: Artistic-2.0
### -- Authors: JJ Merelo
### -- File: t/03-p-peaks.t
### ----------------------------------------------------
#!/usr/bin/env perl6
use v6;
use Test;
use Algorithm::Evolutionary::Fitness::P-Peaks;
my $length = 32;
my $number-of-peaks=100;
my $p-peaks = Algorithm::Evolutionary::Fitness::P-Peaks.new: number-of-peaks => $number-of-peaks, bits => $length;
cmp-ok $p-peaks, "~~", Algorithm::Evolutionary::Fitness::P-Peaks, "Correct object";
cmp-ok $p-peaks.peaks().elems, "==", $number-of-peaks, "Number of peaks correct";
cmp-ok $p-peaks.peaks[0].elems, "==", $length, "Length of peaks correct";
my @random-chromosome = Bool.pick xx $length ;
cmp-ok $p-peaks.distance( @random-chromosome), ">=", 0, "Distance computed";
done-testing;
|
### ----------------------------------------------------
### -- Algorithm::Evolutionary::Simple
### -- Licenses: Artistic-2.0
### -- Authors: JJ Merelo
### -- File: t/01-basic.t
### ----------------------------------------------------
use v6.c;
use Test;
use Algorithm::Evolutionary::Simple;
my $population-size = 32;
# TODO: add 64 here when regression in Rakudo is fixed.
for <32 48> -> $length {
for ^$population-size {
my @random-chromosome = random-chromosome( $length );
is( @random-chromosome.elems, $length, "Chromosome length OK" );
my $packed-in-an-int = pack-individual( @random-chromosome);
isa-ok( $packed-in-an-int, Int, "Individual with @random-chromosome[0] is packed in $packed-in-an-int" );
is-deeply( unpack-individual( $packed-in-an-int, $length), @random-chromosome, "Individual unpacks OK" );
}
my @initial-population = initialize( size => $population-size,
genome-length => $length );
is( @initial-population.elems, $population-size, "Pop is the right size");
my $packed-pop = pack-population( @initial-population);
does-ok( $packed-pop, Buf[uint64], "Population is packed");
is( $packed-pop.elems, $population-size, "Buf is the right size");
my @unpacked-pop = unpack-population( $packed-pop, $length);
is( @unpacked-pop.elems, $population-size, "Population unpacked OK");
is-deeply( @unpacked-pop[0], @initial-population[0].Array, "Unpacking works");
}
my $length = 32;
my @population = initialize( size => $population-size,
genome-length => $length );
my $evaluated-pop = evaluate-nocache(:@population,
evaluator => &max-ones );
is best-one( $evaluated-pop).value, best-fitness( $evaluated-pop), "Best fitness OK";
cmp-ok best-fitness( $evaluated-pop ), "≥", $evaluated-pop.sort(*.value).reverse.[1].value, "Best is equal or better than second";
for $evaluated-pop.keys -> $k {
is( $evaluated-pop{$k}, max-ones( $k ), "Evaluation is correct, {$evaluated-pop{$k}}");
}
does-ok($evaluated-pop, Mix, "Evaluated pop is the right class" );
my @population-prime = initialize( size => $population-size,
genome-length => $length );
my $new-pop = mix-raw( @population, @population-prime, $population-size, &max-ones);
is( $new-pop.elems, $population-size, "Size is correct" );
my @fake-population = [ [True,True,True,True],[True,True,True,False],[True,True,False,False],[True,False,False,False] ];
my @frequencies = frequencies( @fake-population);
is-deeply(@frequencies, [1.0,0.75,0.5,0.25], "Frequencies OK" );
# Check on real pop
my $best-one = best-one( $new-pop );
@frequencies = frequencies( $new-pop );
is( @frequencies.elems, $length, "Size is correct" );
cmp-ok( any(@frequencies), ">", 0, "Some frequencies are not null" );
my @freqs-other-way = frequencies( $new-pop.keys );
is-deeply( @freqs-other-way, @frequencies, "Checking frequencies both ways" );
@population = generate-by-frequencies( $population-size, @frequencies );
is( @population.elems, $population-size, "Size is correct" );
for @population -> @p {
is( @p.elems, $length, "Size of generated elem is correct" );
}
@population = generate-with-best( $population-size, @frequencies, $best-one);
is( @population.elems, $population-size, "Size is correct" );
my @new-frequencies = frequencies( @population );
my $difference = [+] @new-frequencies Z- @frequencies;
cmp-ok( $difference, "<", $population-size * 0.3, "Frequencies differ in $difference" );
my @freqs-best = frequencies-best( $new-pop );
is( @freqs-best.elems, $length, "Size of freqs-best is correct" );
cmp-ok((sum @freqs-best), ">", (sum @frequencies), "Frequencies of the best are better");
my @crossed = crossover-frequencies( @frequencies, @new-frequencies );
is @crossed.elems, @frequencies.elems, "Same length frequencies";
is( @crossed[0], any(@frequencies[0],@new-frequencies[0]), "Crossing OK");
is( @crossed[*-1], any(@frequencies[*-1],@new-frequencies[*-1]), "Crossing OK");
# Test no-change
for ^2 {
is( no-change-during( 3, 3 ), False, "No change for $_ generations" );
}
is( no-change-during( 3, 3 ), True, "No change for 3 generations" );
is( no-change-during( 3, 4 ), False, "There's been change" );
done-testing;
|
### ----------------------------------------------------
### -- Algorithm::Evolutionary::Simple
### -- Licenses: Artistic-2.0
### -- Authors: JJ Merelo
### -- File: t/01-max-ones.t
### ----------------------------------------------------
#!/usr/bin/env perl6
use v6;
use Test;
use Algorithm::Evolutionary::Simple;
my @length = 32, * * 2 … 1024;
for @length -> $l {
my @zeros = False xx $l;
cmp-ok( max-ones( @zeros ), "==", 0, "False-ed chromosome evaluated");
@zeros = 0 xx $l;
cmp-ok( max-ones( @zeros ), "==", 0, "0-ed chromosome evaluated");
my @ones = True xx $l;
cmp-ok( max-ones( @ones ), "==", $l, "True-ed chromosome evaluated");
@zeros = 1 xx $l;
cmp-ok( max-ones( @ones ), "==", $l, "1-ed chromosome evaluated");
for ^$l {
my @χ = random-chromosome( $l );
cmp-ok( @χ, "ne", random-chromosome($l), "Random chromosome size $l");
my $number-ones = reduce { $^b + $^a }, 0, |@χ;
cmp-ok( max-ones( @χ ), "==", $number-ones, "Max ones correct");
}
}
cmp-ok( max-ones( [0,True,False,1]), "==", 2, "Mixed chromosome tested" );
cmp-ok( max-ones( [3,24,0,i]), "==", 3, "Error chromosome tested" );
done-testing;
|
### ----------------------------------------------------
### -- Algorithm::Genetic
### -- Licenses: Artistic-2.0
### -- Authors: Sam Gillespie
### -- File: META6.json
### ----------------------------------------------------
{
"authors" : [
"Sam Gillespie"
],
"build-depends" : [ ],
"depends" : [ ],
"description" : "A basic genetic algorithm implementation for Perl6!",
"license" : "Artistic-2.0",
"name" : "Algorithm::Genetic",
"perl" : "6.c",
"provides" : {
"Algorithm::Genetic" : "lib/Algorithm/Genetic.pm6",
"Algorithm::Genetic::Crossoverable" : "lib/Algorithm/Genetic/Crossoverable.pm6",
"Algorithm::Genetic::Genotype" : "lib/Algorithm/Genetic/Genotype.pm6",
"Algorithm::Genetic::Selection" : "lib/Algorithm/Genetic/Selection.pm6",
"Algorithm::Genetic::Selection::Roulette" : "lib/Algorithm/Genetic/Selection/Roulette.pm6"
},
"resources" : [ ],
"source-url" : "git://github.com/samgwise/p6-algorithm-genetic.git",
"tags" : [ ],
"test-depends" : [ ],
"version" : "0.0.2"
}
|
### ----------------------------------------------------
### -- Algorithm::Genetic
### -- Licenses: Artistic-2.0
### -- Authors: Sam Gillespie
### -- File: LICENSE
### ----------------------------------------------------
The Artistic License 2.0
Copyright (c) 2000-2015, 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.
|
### ----------------------------------------------------
### -- Algorithm::Genetic
### -- Licenses: Artistic-2.0
### -- Authors: Sam Gillespie
### -- File: readme.md
### ----------------------------------------------------
[](https://travis-ci.org/samgwise/p6-algorithm-genetic)
NAME
====
Algorithm::Genetic - A basic genetic algorithm implementation for Perl6!
Use the Algorithm::Genetic distribution to implement your own evolutionary searches.
This library was written primarily for learning so there likely are some rough edges. Feel to report any issues and contributions are welcome!
SYNOPSIS
========
use Algorithm::Genetic;
use Algorithm::Genetic::Genotype;
use Algorithm::Genetic::Selection::Roulette;
my $target = 42;
# First implement the is-finished method for our specific application.
# Note that we compose in our selection behaviour of the Roulette role.
class FindMeaning does Algorithm::Genetic does Algorithm::Genetic::Selection::Roulette {
has int $.target;
method is-finished() returns Bool {
#say "Gen{ self.generation } - pop. size: { @!population.elems }";
self.population.tail[0].result == $!target;
}
}
# Create our Genotype
class Equation does Algorithm::Genetic::Genotype {
our $eq-target = $target;
our @options = 1, 9;
# Note that we use the custom is mutable trait to provide a routine to mutate our attribute.
has Int $.a is mutable( -> $v { (-1, 1).pick + $v } ) = @options.pick;
has Int $.b is mutable( -> $v { (-1, 1).pick + $v } ) = @options.pick;
method result() { $!a * $!b }
# A scoring method is required for our genotype :)
method !calc-score() returns Numeric {
(self.result() - $eq-target) ** 2
}
}
# Instantiate our search
my FindMeaning $ga .= new(
:genotype(Equation.new)
:mutation-probability(4/5)
:$target
);
# Go!
$ga.evolve(:generations(1000), :size(16));
say "stopped at generation { $ga.generation } with result: { .a } x { .b } = { .result } and a score of { .score }" given $ga.population.tail[0];
DESCRIPTION
===========
Algorithm::Genetic distribution currently provides the following classes:
* Algorithm::Genetic
* Algorithm::Genetic::Crossoverable
* Algorithm::Genetic::Genotype
* Algorithm::Genetic::Selection
* Algorithm::Genetic::Selection::Roulette
AUTHOR
======
Sam Gillespie <[email protected]>
COPYRIGHT AND LICENSE
=====================
Copyright 2016 Sam Gillespie
This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
Reference
=========
NAME
====
Algorithm::Genetic - A role for genetic algorithms.
unit role Algorithm::Genetic does Algorithm::Genetic::Selection
METHODS
=======
method new(
Int:D :$population-size = 100,
Rat:D :$crossover-probability = 7/10,
Rat:D :$mutation-probability = 1/100,
Algorithm::Genetic::Genotype :$genotype is required
)
Probability values are expected to be between 0 and 1.
### method generation
```perl6
method generation() returns Int
```
Returns the current generation. Returns 0 if there have been no evolutions
### method population
```perl6
method population() returns Seq
```
Returns a sequence of the current population. This may be an empty list if no calls to Evolve have been made.
### method evolve
```perl6
method evolve(
Int :$generations = 1,
Int :$size = 1
) returns Mu
```
Evolve our population. generations sets an upper limit of generations if the conditions in is-finished our not satisfied. Size is how many couples to pair each generation.
### method sort-population
```perl6
method sort-population() returns Mu
```
Sort our population by score. The higher the score the better! (This is a private method but may not appear that way in the doc...)
### method is-finished
```perl6
method is-finished() returns Bool
```
The termination condition for this algorithm. This must be implemented by an algorithm for assessing if we have achieved our goal.
NAME
====
Algorithm::Genetic::Selection - A role for selection algorithms.
unit role Algorithm::Genetic::Selection;
METHODS
=======
### method selection-strategy
```perl6
method selection-strategy(
Int $selection = 2
) returns Seq
```
The selection strategy for an algorithm. This method holds the logic for a selection strategy and must be implemented by consuming roles. The selection parameter specifies how many entities from our population to select.
### method population
```perl6
method population() returns Seq
```
A method for accessing a population. We expect that all elements of the returned list will implement the score method as per Genotype.
NAME
====
Algorithm::Genetic::Selection::Roulette - A role for roulette selection.
unit role Algorithm::Genetic::Selection::Roulette does Algorithm::Genetic::Selection;
METHODS
=======
### method selection-strategy
```perl6
method selection-strategy(
Int $selection = 2
) returns Mu
```
implements roulette selection for a population provided by the population method. Roulette selection selects randomly from the population with a preference towards higher scoring individuals.
NAME
====
Algorithm::Genetic::Genotype - A role for defining genotypes.
unit role Algorithm::Genetic::Genotype does Algorithm::Genetic::Crossoverable;
METHODS
=======
### method score
```perl6
method score() returns Numeric
```
Score this genotype instance. The score will be calculated and cached on the first call.
### multi sub trait_mod:<is>
```perl6
multi sub trait_mod:<is>(
Attribute $attr,
:$mutable!
) returns Mu
```
The is mutable trait attaches a mutation function to an attribute. the :mutable argument must be Callable. On mutation the mutator will be executed with the current value of the attribute. The return value of the mutator will be assigned to the attribute.
### method calc-score
```perl6
method calc-score() returns Numeric
```
This method must be implemented by a consuming class. The calc-score method is called by score the score method. (This method is private but may not appear that way in the docs!)
### method new-random
```perl6
method new-random() returns Algorithm::Genetic::Genotype
```
This method may be optionally overridden if the genotype has required values. new-random is called when construction the initial population for a Algorithm::Genetic implementing class.
NAME
====
Algorithm::Genetic::Crossoverable - A role providing crossover behaviour of attribute values.
unit role Algorithm::Genetic::Crossoverable;
METHODS
=======
### method crossover
```perl6
method crossover(
Algorithm::Genetic::Crossoverable $other,
Rat $ratio
) returns List
```
Crossover between this and another Crossoverable object. Use the ratio to manage where the crossover point will be. standard attribute types will be swapped by value and Arrays will be swapped recursively. Note that this process effectively duck types attributes so best to only crossover between instances of the same class!
|
### ----------------------------------------------------
### -- Algorithm::Genetic
### -- Licenses: Artistic-2.0
### -- Authors: Sam Gillespie
### -- File: .travis.yml
### ----------------------------------------------------
os:
- linux
- osx
language: perl6
perl6:
- latest
- 2016.01
install:
- rakudobrew build-panda
- panda --notests installdeps .
script:
- perl6 -MPanda::Builder -e 'Panda::Builder.build(~$*CWD)'
- PERL6LIB=$PWD/lib prove -e perl6 -vr t/
sudo: false
|
### ----------------------------------------------------
### -- Algorithm::Genetic
### -- Licenses: Artistic-2.0
### -- Authors: Sam Gillespie
### -- File: res/readme-header.md
### ----------------------------------------------------
[](https://travis-ci.org/samgwise/p6-algorithm-genetic)
|
### ----------------------------------------------------
### -- Algorithm::Genetic
### -- Licenses: Artistic-2.0
### -- Authors: Sam Gillespie
### -- File: t/test-meta.t
### ----------------------------------------------------
use v6;
use Test;
plan 1;
constant AUTHOR = ?%*ENV<TEST_AUTHOR>;
if AUTHOR {
require Test::META <&meta-ok>;
meta-ok;
done-testing;
}
else {
skip-rest "Skipping author test";
exit;
}
|
### ----------------------------------------------------
### -- Algorithm::Genetic
### -- Licenses: Artistic-2.0
### -- Authors: Sam Gillespie
### -- File: t/Algorithm/Genetic.t
### ----------------------------------------------------
#! /usr/bin/env perl6
use v6;
use Test;
use-ok 'Algorithm::Genetic';
done-testing;
|
### ----------------------------------------------------
### -- Algorithm::Genetic
### -- Licenses: Artistic-2.0
### -- Authors: Sam Gillespie
### -- File: t/Algorithm/Genetic/Crossoverable.t
### ----------------------------------------------------
#! /usr/bin/env perl6
use v6;
use Test;
use-ok 'Algorithm::Genetic::Crossoverable';
use Algorithm::Genetic::Crossoverable;
class Point does Algorithm::Genetic::Crossoverable {
has Int $.x;
has Int $.y;
}
{
my Point $a .= new( :x(0), :y(0) );
my Point $b .= new( :x(1), :y(1) );
my ($c, $d) = |$a.crossover($b, 1/2);
is $c.x, 1, "Child Point A.x post crossover";
is $c.y, 0, "Child Point A.y post crossover";
is $d.x, 0, "Child Point B.x post crossover";
is $d.y, 1, "Child Point B.y post crossover";
}
class Point3D is Point {
has Int $.z;
}
{
my Point3D $a .= new( :x(0), :y(0), :z(0) );
my Point3D $b .= new( :x(1), :y(1), :z(1) );
my ($c, $d) = |$a.crossover($b, 1/2);
is $c.x, 1, "Child Point3D A.x post crossover";
is $c.y, 0, "Child Point3D A.y post crossover";
is $c.z, 1, "Child Point3D A.z post crossover";
is $d.x, 0, "Child Point3D B.x post crossover";
is $d.y, 1, "Child Point3D B.y post crossover";
is $d.z, 0, "Child Point3D B.z post crossover";
}
done-testing;
|
### ----------------------------------------------------
### -- Algorithm::Genetic
### -- Licenses: Artistic-2.0
### -- Authors: Sam Gillespie
### -- File: t/Algorithm/Genetic/Genotype.t
### ----------------------------------------------------
#! /usr/bin/env perl6
use v6;
use Test;
use-ok 'Algorithm::Genetic::Genotype';
use Algorithm::Genetic::Genotype;
class Point does Algorithm::Genetic::Genotype {
my sub mutate-int (Numeric $v) returns Int {
(-1, 1).pick + $v
}
has Int $.x is mutable( &mutate-int );
has Int $.y is mutable( &mutate-int );
}
my Point $test .= new( :x(0), :y(0) );
$test.mutate(1/1);
is $test.x, any(1, -1), "point.x is mutated";
is $test.y, any(1, -1), "point.y is mutated";
done-testing;
|
### ----------------------------------------------------
### -- Algorithm::Genetic
### -- Licenses: Artistic-2.0
### -- Authors: Sam Gillespie
### -- File: t/Algorithm/Genetic/Selection/Roulette.t
### ----------------------------------------------------
#! /usr/bin/env perl6
use v6;
use Test;
use-ok 'Algorithm::Genetic::Selection::Roulette';
use Algorithm::Genetic::Selection::Roulette;
use Algorithm::Genetic::Genotype;
class Point does Algorithm::Genetic::Genotype {
has Int $.x = (-10..10).pick;
has Int $.y = (-10..10).pick;
method !calc-score() returns Numeric {
$!x * $!y
}
}
class Cloud does Algorithm::Genetic::Selection::Roulette {
has Point @.population handles<map elems>;
}
my Point @possible = Point.new( :x(1), :y(1) ), Point.new( :x(2), :y(1) ), Point.new( :x(1), :y(2) ), ;
my Point @impossible = Point.new( :x(0), :y(0) ), Point.new( :x(0), :y(1) ), Point.new( :x(1), :y(0) ), ;
my Cloud $test .= new( :population(
|@possible,
|@impossible,
) );
is $test.selection-strategy(@possible.elems).elems, @possible.elems, "Roulette selects correct number of elements";
is $test.selection-strategy($test.elems + 1).elems, $test.elems, "Roulette selects no more than it's maximum elements";
is $test.selection-strategy(0).elems, 0, "Roulette selects 0 elements for 0";
is $test.selection-strategy(1).elems, 1, "Roulette selects 1 elements for 1";
is $test.selection-strategy(@possible.elems).all, @possible.any, "Roulette select all possible canidates";
done-testing;
|
### ----------------------------------------------------
### -- Algorithm::Genetic
### -- Licenses: Artistic-2.0
### -- Authors: Sam Gillespie
### -- File: examples/basic.p6
### ----------------------------------------------------
#! /usr/bin/env perl6
use v6;
use Algorithm::Genetic;
use Algorithm::Genetic::Genotype;
use Algorithm::Genetic::Selection::Roulette;
my $target = 42;
class FindMeaning does Algorithm::Genetic does Algorithm::Genetic::Selection::Roulette {
has int $.target;
method is-finished() returns Bool {
#say "Gen{ self.generation } - pop. size: { @!population.elems }";
self.population.tail[0].result == $!target;
}
}
class Equation does Algorithm::Genetic::Genotype {
our $eq-target = $target;
# our @options = (|('A'..'Z'), |('a'..'z'));
our @options = 1, 9;
has Int $.a is mutable( -> $v { (-1, 1).pick + $v } ) = @options.pick;
has Int $.b is mutable( -> $v { (-1, 1).pick + $v } ) = @options.pick;
method result() { $!a * $!b }
method !calc-score() returns Numeric {
(self.result() - $eq-target) ** 2
}
}
my FindMeaning $ga .= new(
:genotype(Equation.new)
:mutation-probability(4/5)
:$target
);
$ga.evolve(:generations(1000), :size(16));
say "stopped at generation { $ga.generation } with result: { .a } x { .b } = { .result } and a score of { .score }" given $ga.population.tail[0];
|
### ----------------------------------------------------
### -- Algorithm::GooglePolylineEncoding
### -- Licenses: Artistic-2.0
### -- Authors: Simon Proctor
### -- File: META6.json
### ----------------------------------------------------
{
"auth" : "[email protected]",
"authors" : [
"Simon Proctor"
],
"build-depends" : [ ],
"depends" : [ ],
"description" : "Encode and Decode lat/lon polygons using Google Maps string encoding.",
"license" : "Artistic-2.0",
"name" : "Algorithm::GooglePolylineEncoding",
"perl" : "6.c",
"provides" : {
"Algorithm::GooglePolylineEncoding" : "lib/Algorithm/GooglePolylineEncoding.rakumod"
},
"resources" : [ ],
"source-url" : "https://github.com/Scimon/p6-Algorithm-GooglePolylineEncoding.git",
"tags" : [
"geo",
"google"
],
"test-depends" : [ ],
"version" : "1.0.3"
}
|
### ----------------------------------------------------
### -- Algorithm::GooglePolylineEncoding
### -- Licenses: Artistic-2.0
### -- Authors: Simon Proctor
### -- 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.
|
### ----------------------------------------------------
### -- Algorithm::GooglePolylineEncoding
### -- Licenses: Artistic-2.0
### -- Authors: Simon Proctor
### -- File: README.md
### ----------------------------------------------------
[](https://travis-ci.org/Scimon/p6-Algorithm-GooglePolylineEncoding)
NAME
====
Algorithm::GooglePolylineEncoding - Encode and Decode lat/lon polygons using Google Maps string encoding.
SYNOPSIS
========
use Algorithm::GooglePolylineEncoding;
my $encoded = encode-polyline( { :lat(90), :lon(90) }, { :lat(0), :lon(0) }, { :lat(22.5678), :lon(45.2394) } );
my @polyline = deocde-polyline( $encoded );
DESCRIPTION
===========
Algorithm::GooglePolylineEncoding is intended to be used to encoded and decode Google Map polylines.
Note this is a lossy encoded, any decimal values beyond the 5th place in a latitude of longitude will be lost.
USAGE
-----
### encode-polyline( { :lat(Real), :lon(Real) }, ... ) --> Str
### encode-polyline( [ { :lat(Real), :lon(Real) }, ... ] ) --> Str
### encode-polyline( Real, Real, ... ) --> Str
Encodes a polyline list (supplied in any of the listed formats) and returns a Str of the encoded data.
### decode-polyline( Str ) --> [ { :lat(Real), :lon(Real) }, ... ]
Takes a string encoded using the algorithm and returns an Array of Hashes with lat / lon keys.
For further details on the encoding algorithm please see the follow link:
https://developers.google.com/maps/documentation/utilities/polylinealgorithm
AUTHOR
======
Simon Proctor <[email protected]>
COPYRIGHT AND LICENSE
=====================
Copyright 2018 Simon Proctor
This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
|
### ----------------------------------------------------
### -- Algorithm::GooglePolylineEncoding
### -- Licenses: Artistic-2.0
### -- Authors: Simon Proctor
### -- File: .travis.yml
### ----------------------------------------------------
os:
- linux
- osx
language: perl6
perl6:
- latest
install:
- rakudobrew build zef
- zef install --deps-only --/test .
script:
- PERL6LIB=$PWD/lib prove -e perl6 -vr --ext .t --ext .t6 --ext .rakutest t/
sudo: false
|
### ----------------------------------------------------
### -- Algorithm::GooglePolylineEncoding
### -- Licenses: Artistic-2.0
### -- Authors: Simon Proctor
### -- File: dist.ini
### ----------------------------------------------------
name = Algorithm-GooglePolylineEncoding
[ReadmeFromPod]
; disable = true
filename = lib/Algorithm/GooglePolylineEncoding.rakumod
[PruneFiles]
; match = ^ 'xt/'
|
### ----------------------------------------------------
### -- Algorithm::GooglePolylineEncoding
### -- Licenses: Artistic-2.0
### -- Authors: Simon Proctor
### -- File: t/03-encode-list.rakutest
### ----------------------------------------------------
use v6.c;
use Test;
use Algorithm::GooglePolylineEncoding;
plan 6;
my $encoded = q[_p~iF~ps|U_ulLnnqC_mqNvxq`@];
is encode-polyline( ( { :lat(38.5), :lon(-120.2) }, { :lat(40.7), :lon(-120.95) }, { :lat(43.252), :lon(-126.453) } ) ), $encoded, "list of hashes $encoded OK";
is encode-polyline( [ { :lat(38.5), :lon(-120.2) }, { :lat(40.7), :lon(-120.95) }, { :lat(43.252), :lon(-126.453) } ] ), $encoded, "array of hashes $encoded OK";
is encode-polyline( { :lat(38.5), :lon(-120.2) }, { :lat(40.7), :lon(-120.95) }, { :lat(43.252), :lon(-126.453) } ), $encoded, "hashes as args $encoded OK";
is encode-polyline( 38.5, -120.2, 40.7, -120.95, 43.252, -126.453 ), $encoded, "list of reals $encoded OK";
$encoded = q<yikzH{o`@zsHdP|nIsnBxiE{wFboBuxJwi@m|Sc_DonMmdGqcLqnLqcLycFpGonD~eBonCngJ|N`lWfyB~y]vnA|wFpnD~lE>;
is encode-polyline( [
{ 'lat' => 51.67277, 'lon' => 0.17166, },
{ 'lat' => 51.62335, 'lon' => 0.16891, },
{ 'lat' => 51.5696, 'lon' => 0.18677, },
{ 'lat' => 51.53715, 'lon' => 0.22659, },
{ 'lat' => 51.51921, 'lon' => 0.28702, },
{ 'lat' => 51.52605, 'lon' => 0.39413, },
{ 'lat' => 51.55167, 'lon' => 0.46829, },
{ 'lat' => 51.5935, 'lon' => 0.53558, },
{ 'lat' => 51.66255, 'lon' => 0.60287, },
{ 'lat' => 51.69916, 'lon' => 0.6015, },
{ 'lat' => 51.72724, 'lon' => 0.58502, },
{ 'lat' => 51.7502, 'lon' => 0.52734, },
{ 'lat' => 51.74765, 'lon' => 0.40237, },
{ 'lat' => 51.72809, 'lon' => 0.24445, },
{ 'lat' => 51.71533, 'lon' => 0.20462, },
{ 'lat' => 51.68724, 'lon' => 0.17166, },
] ), $encoded;
$encoded = q<kzxxHemkAamEvXu|BhjBm|@|nD{aBrb^vaArsFzkBhjDiNnPjLrnBhoBbyAzjIwXt_D_fB~dCgzGzdBwmIlTs_Ny|AgaKmrC_oD>;
is encode-polyline( [
{ 'lat' => 51.4143, 'lon' => 0.39139, },
{ 'lat' => 51.44727, 'lon' => 0.38727, },
{ 'lat' => 51.46738, 'lon' => 0.3701, },
{ 'lat' => 51.47721, 'lon' => 0.34195, },
{ 'lat' => 51.49303, 'lon' => 0.18265, },
{ 'lat' => 51.48235, 'lon' => 0.14351, },
{ 'lat' => 51.46493, 'lon' => 0.1161, },
{ 'lat' => 51.46738, 'lon' => 0.1133, },
{ 'lat' => 51.46524, 'lon' => 0.09544, },
{ 'lat' => 51.44727, 'lon' => 0.08102, },
{ 'lat' => 51.39417, 'lon' => 0.08514, },
{ 'lat' => 51.36846, 'lon' => 0.10162, },
{ 'lat' => 51.34702, 'lon' => 0.14694, },
{ 'lat' => 51.33072, 'lon' => 0.2005, },
{ 'lat' => 51.32729, 'lon' => 0.2774, },
{ 'lat' => 51.3423, 'lon' => 0.3392, },
{ 'lat' => 51.36589, 'lon' => 0.36736, },
] ), $encoded;
|
### ----------------------------------------------------
### -- Algorithm::GooglePolylineEncoding
### -- Licenses: Artistic-2.0
### -- Authors: Simon Proctor
### -- File: t/01-basic.rakutest
### ----------------------------------------------------
use v6.c;
use Test;
plan 1;
use-ok "Algorithm::GooglePolylineEncoding";
|
### ----------------------------------------------------
### -- Algorithm::GooglePolylineEncoding
### -- Licenses: Artistic-2.0
### -- Authors: Simon Proctor
### -- File: t/02-encode-number.rakutest
### ----------------------------------------------------
use v6.c;
use Test;
use Algorithm::GooglePolylineEncoding;
plan 7;
my @tests = (
{ in => -179.9832104, out => '`~oia@' },
{ in => 38.5, out => '_p~iF' },
{ in => -120.2, out => '~ps|U' },
{ in => 2.2, out => '_ulL' },
{ in => -0.75, out => 'nnqC' },
{ in => 2.552, out => '_mqN' },
{ in => -5.503, out => 'vxq`@' }
);
for @tests -> %test-data {
is encode-number( %test-data<in> ), %test-data<out>, "{%test-data<in>} encodes to {%test-data<out>}";
}
|
### ----------------------------------------------------
### -- Algorithm::GooglePolylineEncoding
### -- Licenses: Artistic-2.0
### -- Authors: Simon Proctor
### -- File: t/04-decode-string.rakutest
### ----------------------------------------------------
use v6.c;
use Test;
use Algorithm::GooglePolylineEncoding;
plan 3;
my $encoded = q[_p~iF~ps|U_ulLnnqC_mqNvxq`@];
is-deeply decode-polyline( $encoded ), [
{ lat => 38.5, lon => -120.2 },
{ lat => 40.7, lon => -120.95 },
{ lat => 43.252, lon => -126.453 },
], "String decoded OK";
$encoded = q<yikzH{o`@zsHdP|nIsnBxiE{wFboBuxJwi@m|Sc_DonMmdGqcLqnLqcLycFpGonD~eBonCngJ|N`lWfyB~y]vnA|wFpnD~lE>;
is-deeply decode-polyline( $encoded ), [
{ lat => 51.67277, lon => 0.17166, },
{ lat => 51.62335, lon => 0.16891, },
{ lat => 51.5696, lon => 0.18677, },
{ lat => 51.53715, lon => 0.22659, },
{ lat => 51.51921, lon => 0.28702, },
{ lat => 51.52605, lon => 0.39413, },
{ lat => 51.55167, lon => 0.46829, },
{ lat => 51.5935, lon => 0.53558, },
{ lat => 51.66255, lon => 0.60287, },
{ lat => 51.69916, lon => 0.6015, },
{ lat => 51.72724, lon => 0.58502, },
{ lat => 51.7502, lon => 0.52734, },
{ lat => 51.74765, lon => 0.40237, },
{ lat => 51.72809, lon => 0.24445, },
{ lat => 51.71533, lon => 0.20462, },
{ lat => 51.68724, lon => 0.17166, },
];
$encoded = q<kzxxHemkAamEvXu|BhjBm|@|nD{aBrb^vaArsFzkBhjDiNnPjLrnBhoBbyAzjIwXt_D_fB~dCgzGzdBwmIlTs_Ny|AgaKmrC_oD>;
is-deeply decode-polyline( $encoded ), [
{ lat => 51.4143, lon => 0.39139, },
{ lat => 51.44727, lon => 0.38727, },
{ lat => 51.46738, lon => 0.3701, },
{ lat => 51.47721, lon => 0.34195, },
{ lat => 51.49303, lon => 0.18265, },
{ lat => 51.48235, lon => 0.14351, },
{ lat => 51.46493, lon => 0.1161, },
{ lat => 51.46738, lon => 0.1133, },
{ lat => 51.46524, lon => 0.09544, },
{ lat => 51.44727, lon => 0.08102, },
{ lat => 51.39417, lon => 0.08514, },
{ lat => 51.36846, lon => 0.10162, },
{ lat => 51.34702, lon => 0.14694, },
{ lat => 51.33072, lon => 0.2005, },
{ lat => 51.32729, lon => 0.2774, },
{ lat => 51.3423, lon => 0.3392, },
{ lat => 51.36589, lon => 0.36736, },
];
|
### ----------------------------------------------------
### -- Algorithm::GooglePolylineEncoding
### -- Licenses: Artistic-2.0
### -- Authors: Simon Proctor
### -- File: t/05-round-robin.rakutest
### ----------------------------------------------------
use v6.c;
use Test;
use Algorithm::GooglePolylineEncoding;
plan :skip-all<Skipping round robin test. Set ENV TEST_ROUND_ROBIN to run tests.> unless %*ENV<TEST_ROUND_ROBIN>:exists;
plan 25920;
for (-90, * + 5 ... 85 ) -> $lat1 {
for ( -180, * + 5 ... 175 ) -> $lon1 {
for ( 0.01, * + 0.01 ... 0.1 ) -> $d1 {
my $d2 = $d1 / 10;
my $lat2 = $lat1 + $d1;
my $lat3 = $lat2 + $d2;
my $lon2 = $lon1 + $d1;
my $lon3 = $lon2 + $d2;
is decode-polyline( encode-polyline( $lat1, $lon1, $lat2, $lon2, $lat3, $lon3 ) ),
[ { :lat($lat1), :lon($lon1) }, {:lat($lat2), :lon($lon2) }, {:lat($lat3), :lon($lon3) } ],
"$lat1, $lon1, $lat2, $lon2, $lat3, $lon3 OK";
}
}
}
|
### ----------------------------------------------------
### -- Algorithm::GooglePolylineEncoding
### -- Licenses: Artistic-2.0
### -- Authors: Simon Proctor
### -- File: lib/Algorithm/GooglePolylineEncoding.rakumod
### ----------------------------------------------------
use v6;
subset Latitude of Real where { -90 <= $_ <= 90 or note "Latitude $_ out of range" and False };
subset Longitude of Real where { -180 <= $_ <= 180 or note "Longitude $_ out of range" and False };
module Algorithm::GooglePolylineEncoding:ver<1.0.3>:auth<[email protected]> {
class PosPair {
has Latitude $.lat;
has Longitude $.lon;
method Hash {
return { :lat($.lat), :lon($.lon) };
}
}
multi sub encode-number ( Real $value is copy where * < 0 ) returns Str is export {
$value = round( $value * 10⁵ );
$value = $value +< 1;
$value = $value +& 0xffffffff;
$value = +^ $value;
$value = $value +& 0xffffffff;
return encode-shifted( $value );
}
multi sub encode-number ( Real $value is copy ) returns Str is export {
$value = round( $value * 10⁵ );
$value = $value +< 1;
$value = $value +& 0xffffffff;
return encode-shifted( $value );
}
sub encode-shifted ( Int $value is copy ) returns Str {
my $bin = $value.base(2);
unless $bin.chars %% 5 {
$bin = '0' x ( 5 - $bin.chars % 5 ) ~ $bin;
}
my @chunks = $bin.comb( /\d ** 5/ ).reverse.map( *.parse-base(2) );
@chunks[0..*-2].map( { $_ = $_ +| 0x20 } );
return @chunks.map( { $_ + 63 } ).map( { chr( $_ ) } ).join("");
}
multi sub encode-polyline( PosPair @pairs ) returns Str {
my ( $cur-lat, $cur-lon ) = ( 0,0 );
my @list = ();
for @pairs -> $pair {
@list.push( encode-number( $pair.lat - $cur-lat ) );
@list.push( encode-number( $pair.lon - $cur-lon ) );
( $cur-lat, $cur-lon ) = ( $pair.lat, $pair.lon );
}
return @list.join();
}
multi sub encode-polyline( @pairs where { $_.all ~~ Hash } ) returns Str is export {
my PosPair @values = @pairs.map( -> %p { PosPair.new( |%p ) } );
encode-polyline( @values );
}
multi sub encode-polyline( **@pairs where { $_.all ~~ Hash } ) returns Str is export {
my PosPair @values = @pairs.map( -> %p { PosPair.new( |%p ) } );
encode-polyline( @values );
}
multi sub encode-polyline( *@points where { $_.all ~~ Real && $_.elems %% 2 } ) returns Str is export {
my PosPair @values = @points.map( -> $la,$lo { PosPair.new( :lat($la), :lon($lo) ) } );
encode-polyline( @values );
}
constant END-VALUES = any( (63..94).map( *.chr ) );
multi sub decode-polyline( Str $encoded ) returns Array is export {
my ( $lat, $lon ) = ( 0, 0 );
my @out = [];
my @values = $encoded.comb(/ .*? (.) <?{ $/[0] ~~ END-VALUES }> /).map( &decode-str );
for @values -> $dlat, $dlon {
@out.push( PosPair.new( :lat($lat+$dlat), :lon($lon+$dlon) ).Hash );
($lat,$lon) = ( $lat + $dlat, $lon + $dlon );
}
return @out;
}
sub decode-str( Str $encoded ) returns Real {
my $value = ( $encoded.comb().reverse.map( *.ord - 63 ).map( * +& 0x1f ).map( *.base(2) ).map( { '0' x ( $_.chars %% 5 ?? 0 !! 5 - $_.chars % 5 ) ~ $_ } ).join() ).parse-base(2);
$value = +^ $value if $value +& 1;
$value = $value +> 1;
$value = $value / 10⁵;
return $value;
}
}
=begin pod
=head1 NAME
Algorithm::GooglePolylineEncoding - Encode and Decode lat/lon polygons using Google Maps string encoding.
=head1 SYNOPSIS
use Algorithm::GooglePolylineEncoding;
my $encoded = encode-polyline( { :lat(90), :lon(90) }, { :lat(0), :lon(0) }, { :lat(22.5678), :lon(45.2394) } );
my @polyline = deocde-polyline( $encoded );
=head1 DESCRIPTION
Algorithm::GooglePolylineEncoding is intended to be used to encoded and decode Google Map polylines.
Note this is a lossy encoded, any decimal values beyond the 5th place in a latitude of longitude will be lost.
=head2 USAGE
=head3 encode-polyline( { :lat(Real), :lon(Real) }, ... ) --> Str
=head3 encode-polyline( [ { :lat(Real), :lon(Real) }, ... ] ) --> Str
=head3 encode-polyline( Real, Real, ... ) --> Str
Encodes a polyline list (supplied in any of the listed formats) and returns a Str of the encoded data.
=head3 decode-polyline( Str ) --> [ { :lat(Real), :lon(Real) }, ... ]
Takes a string encoded using the algorithm and returns an Array of Hashes with lat / lon keys.
For further details on the encoding algorithm please see the follow link:
https://developers.google.com/maps/documentation/utilities/polylinealgorithm
=head1 AUTHOR
Simon Proctor <[email protected]>
=head1 COPYRIGHT AND LICENSE
Copyright 2018 Simon Proctor
This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
=end pod
|
### ----------------------------------------------------
### -- Algorithm::Heap::Binary
### -- Licenses: Artistic-2.0
### -- Authors: cono
### -- File: META6.json
### ----------------------------------------------------
{
"perl" : "6.c",
"name" : "Algorithm::Heap::Binary",
"version" : "0.0.1",
"description" : "BinaryHeap data structure",
"authors" : [ "cono" ],
"license" : "Artistic-2.0",
"provides" : {
"Algorithm::Heap" : "lib/Algorithm/Heap.pm6",
"Algorithm::Heap::Binary" : "lib/Algorithm/Heap/Binary.pm6"
},
"depends" : [ ],
"resources" : [ ],
"source-url" : "[email protected]:cono/p6-algorithm-heap-binary.git"
}
|
### ----------------------------------------------------
### -- Algorithm::Heap::Binary
### -- Licenses: Artistic-2.0
### -- Authors: cono
### -- 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.
|
### ----------------------------------------------------
### -- Algorithm::Heap::Binary
### -- Licenses: Artistic-2.0
### -- Authors: cono
### -- File: README.md
### ----------------------------------------------------
[](https://travis-ci.org/cono/p6-algorithm-heap-binary)
NAME
====
Algorithm::Heap::Binary - Implementation of a BinaryHeap
SYNOPSIS
========
use Algorithm::Heap::Binary;
my Algorithm::Heap::Binary $heap .= new(
comparator => * <=> *,
3 => 'c',
2 => 'b',
1 => 'a'
);
$heap.size.say; # 3
# heap-sort example
$heap.delete-min.value.say; # a
$heap.delete-min.value.say; # b
$heap.delete-min.value.say; # c
DESCRIPTION
===========
Algorithm::Heap::Binary provides to you BinaryHeap data structure with basic heap operations defined in Algorithm::Heap role:
peek
----
find a maximum item of a max-heap, or a minimum item of a min-heap, respectively
push
----
returns the node of maximum value from a max heap [or minimum value from a min heap] after removing it from the heap
pop
---
removing the root node of a max heap [or min heap]
replace
-------
pop root and push a new key. More efficient than pop followed by push, since only need to balance once, not twice, and appropriate for fixed-size heaps
is-empty
--------
return true if the heap is empty, false otherwise
size
----
return the number of items in the heap
merge
-----
joining two heaps to form a valid new heap containing all the elements of both, preserving the original heaps
METHODS
=======
Constructor
-----------
BinaryHeap contains `Pair` objects and define order between `Pair.key` by the comparator. Comparator - is a `Code` which defines how to order elements internally. With help of the comparator you can create Min-heap or Max-heap.
* empty constructor
my $heap = Algorithm::Heap::Binary.new;
Default comparator is: `* <=> *`
* named constructor
my $heap = Algorithm::Heap::Binary.new(comparator => -> $a, $b {$b cmp $a});
* constructor with heapify
my @numbers = 1 .. *;
my @letters = 'a' .. *;
my @data = @numbers Z=> @letters;
my $heap = Algorithm::Heap::Binary.new(comparator => * <=> *, |@data[^5]);
This will automatically heapify data for you.
clone
-----
Clones heap object for you with all internal data.
is-empty
--------
Returns `Bool` result as to empty Heap or not.
size
----
Returns `Int` which corresponds to amount elements in the Heap data structure.
push(Pair)
----------
Adds new Pair to the heap and resort it.
insert(Pair)
------------
Alias for push method.
peek
----
Returns `Pair` from the top of the Heap.
find-max
--------
Just an syntatic alias for peek method.
find-min
--------
Just an syntatic alias for peek method.
pop
---
Returns `Piar` from the top of the Heap and also removes it from the Heap.
delete-max
----------
Just an syntatic alias for pop method.
delete-min
----------
Just an syntatic alias for pop method.
replace(Pair)
-------------
Replace top element with another Pair. Returns replaced element as a result.
merge(Algorithm::Heap)
----------------------
Construct a new Heap merging current one and passed to as an argument.
Seq
---
Returns `Seq` of Heap elements. This will clone the data for you, so initial data structure going to be untouched.
Str
---
Prints internal representation of the Heap (as an `Array`).
iterator
--------
Method wich provides iterator (`role Iterable`). Will clone current Heap for you.
sift-up
-------
Internal method to make sift-up operation.
sift-down
---------
Internal method to make sift-down operation.
AUTHOR
======
[cono](mailto:[email protected])
COPYRIGHT AND LICENSE
=====================
Copyright 2018 cono
This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
LINKS
=====
* [https://en.wikipedia.org/wiki/Heap_(data_structure)](https://en.wikipedia.org/wiki/Heap_(data_structure))
* [https://en.wikipedia.org/wiki/Binary_heap](https://en.wikipedia.org/wiki/Binary_heap)
|
### ----------------------------------------------------
### -- Algorithm::Heap::Binary
### -- Licenses: Artistic-2.0
### -- Authors: cono
### -- File: .travis.yml
### ----------------------------------------------------
---
language: perl6
perl6:
- latest
...
|
### ----------------------------------------------------
### -- Algorithm::Heap::Binary
### -- Licenses: Artistic-2.0
### -- Authors: cono
### -- File: t/00-basic.t
### ----------------------------------------------------
use v6;
use Test;
use-ok('Algorithm::Heap::Binary');
done-testing;
# vim: ft=perl6
|
### ----------------------------------------------------
### -- Algorithm::Heap::Binary
### -- Licenses: Artistic-2.0
### -- Authors: cono
### -- File: t/01-class.t
### ----------------------------------------------------
use v6;
use Test;
use Algorithm::Heap::Binary;
my $heap = Algorithm::Heap::Binary.new;
isa-ok($heap, Algorithm::Heap::Binary);
does-ok($heap, Algorithm::Heap);
does-ok($heap, Iterable);
done-testing;
# vim: ft=perl6
|
### ----------------------------------------------------
### -- Algorithm::Heap::Binary
### -- Licenses: Artistic-2.0
### -- Authors: cono
### -- File: t/02-binary-heap.t
### ----------------------------------------------------
use v6;
use Test;
use Algorithm::Heap::Binary;
my @numbers = 1 .. *;
my @letters = 'a' .. *;
my @data = @numbers Z=> @letters;
sub test-values($heap, $list, $msg) {
is-deeply($heap.Seq.map(*.value), $list, $msg);
}
sub test-keys($heap, $list, $msg) {
is-deeply($heap.Seq.map(*.key), $list, $msg);
}
subtest {
my $heap = Algorithm::Heap::Binary.new;
ok($heap.size == 0, 'heap size == 0');
ok($heap.is-empty, 'empty heap');
$heap.insert(2 => 'b');
$heap.insert(3 => 'c');
$heap.insert(1 => 'a');
ok($heap.size == 3, 'heap size == 3');
test-values($heap, <a b c>, 'check order');
ok($heap.size == 3, 'original heap not touched by Seq');
done-testing;
}, 'size tests';
subtest {
my $heap = Algorithm::Heap::Binary.new;
$heap.insert(2 => 'b');
$heap.insert(3 => 'c');
$heap.insert(1 => 'a');
is($heap.peek.value, 'a', 'peek method');
is($heap.find-min.value, 'a', 'find-min method');
is($heap.find-max.value, 'a', 'find-max method');
done-testing;
}, 'peek tests';
subtest {
my $heap = Algorithm::Heap::Binary.new(comparator => * <=> *, |@data[^5]);
test-keys($heap, (^5 + 1).List, 'heapify keys');
test-values($heap, <a b c d e>, 'heapify values');
done-testing;
}, 'heapify test';
subtest {
my $heap = Algorithm::Heap::Binary.new;
$heap.insert(2 => 'second');
$heap.insert(1 => 'first');
test-values($heap, <first second>, 'void constructor');
$heap = Algorithm::Heap::Binary.new(comparator => -> $a, $b {$b cmp $a});
$heap.insert('a' => 1);
$heap.insert('b' => 2);
$heap.insert('c' => 3);
test-keys($heap, <c b a>, 'named comparator');
$heap = Algorithm::Heap::Binary.new(1 => 'first', 2 => 'second');
test-values($heap, <first second>, 'hepify w/ default comparator');
$heap = Algorithm::Heap::Binary.new(
comparator => * cmp *,
'alex' => 'cono',
'cono' => 'alex'
);
test-keys($heap, <alex cono>, 'hepify w/ comparator');
done-testing;
}, 'constructors';
subtest {
my $heap = Algorithm::Heap::Binary.new;
$heap.insert(2 => 'second');
$heap.insert(1 => 'first');
is($heap.size, 2, 'two insert');
$heap.push(3 => 'third');
is($heap.size, 3, 'and one push');
}, 'insert';
subtest {
my $heap = Algorithm::Heap::Binary.new(|@data[^5]);
is($heap.pop.value, 'a', 'pop method');
is($heap.delete-min.value, 'b', 'delete-min method');
is($heap.delete-max.value, 'c', 'delete-max method');
test-keys($heap, (4, 5), 'test rest');
}, 'pop';
subtest {
my $heap = Algorithm::Heap::Binary.new(|@data[^5]);
is($heap.replace(42 => 'cono'), 1 => 'a', 'replace method');
test-values($heap, <b c d e cono>, 'test rest');
}, 'replace';
subtest {
my $heap1 = Algorithm::Heap::Binary.new(|@data[0,2,4]);
my $heap2 = Algorithm::Heap::Binary.new(|@data[1,3]);
my $merged = $heap1.merge($heap2);
test-values($merged, <a b c d e>, 'new heap from merge');
}, 'merge';
done-testing;
# vim: ft=perl6
|
### ----------------------------------------------------
### -- Algorithm::HierarchicalPAM
### -- Licenses: Artistic-2.0
### -- Authors: titsuki
### -- File: META6.json
### ----------------------------------------------------
{
"auth" : "cpan:TITSUKI",
"authors" : [
"titsuki"
],
"build-depends" : [
"LibraryMake",
"Distribution::Builder::MakeFromJSON",
"Algorithm::HierarchicalPAM::CustomBuilder"
],
"builder" : "Algorithm::HierarchicalPAM::CustomBuilder",
"depends" : [ ],
"description" : "A Raku Hierarchical PAM (model 2) implementation.",
"license" : "Artistic-2.0",
"name" : "Algorithm::HierarchicalPAM",
"perl" : "6.c",
"provides" : {
"Algorithm::HierarchicalPAM" : "lib/Algorithm/HierarchicalPAM.pm6",
"Algorithm::HierarchicalPAM::CustomBuilder" : "lib/Algorithm/HierarchicalPAM/CustomBuilder.pm6",
"Algorithm::HierarchicalPAM::Document" : "lib/Algorithm/HierarchicalPAM/Document.pm6",
"Algorithm::HierarchicalPAM::Formatter" : "lib/Algorithm/HierarchicalPAM/Formatter.pm6",
"Algorithm::HierarchicalPAM::HierarchicalPAMModel" : "lib/Algorithm/HierarchicalPAM/HierarchicalPAMModel.pm6",
"Algorithm::HierarchicalPAM::Phi" : "lib/Algorithm/HierarchicalPAM/Phi.pm6",
"Algorithm::HierarchicalPAM::Theta" : "lib/Algorithm/HierarchicalPAM/Theta.pm6"
},
"resources" : [
"libraries/hpam"
],
"source-url" : "https://github.com/titsuki/raku-Algorithm-HierarchicalPAM.git",
"tags" : [ ],
"test-depends" : [ ],
"version" : "0.0.2"
}
|
### ----------------------------------------------------
### -- Algorithm::HierarchicalPAM
### -- Licenses: Artistic-2.0
### -- Authors: titsuki
### -- 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.
|
### ----------------------------------------------------
### -- Algorithm::HierarchicalPAM
### -- Licenses: Artistic-2.0
### -- Authors: titsuki
### -- File: README.md
### ----------------------------------------------------
[](https://travis-ci.org/titsuki/raku-Algorithm-HierarchicalPAM)
NAME
====
Algorithm::HierarchicalPAM - A Raku Hierarchical PAM (model 2) implementation.
SYNOPSIS
========
EXAMPLE 1
---------
use Algorithm::HierarchicalPAM;
use Algorithm::HierarchicalPAM::Formatter;
use Algorithm::HierarchicalPAM::HierarchicalPAMModel;
my @documents = (
"a b c",
"d e f",
);
my ($documents, $vocabs) = Algorithm::HierarchicalPAM::Formatter.from-plain(@documents);
my Algorithm::HierarchicalPAM $hpam .= new(:$documents, :$vocabs);
my Algorithm::HierarchicalPAMModel $model = $hpam.fit(:num-super-topics(3), :num-sub-topics(5), :num-iterations(500));
$model.topic-word-matrix.say; # show topic-word matrix
$model.document-topic-matrix; # show document-topic matrix
$model.log-likelihood.say; # show likelihood
$model.nbest-words-per-topic.say # show nbest words per topic
EXAMPLE 2
---------
use Algorithm::HierarchicalPAM;
use Algorithm::HierarchicalPAM::Formatter;
use Algorithm::HierarchicalPAM::HierarchicalPAMModel;
# Note: You can get AP corpus as follows:
# $ wget "https://github.com/Blei-Lab/lda-c/blob/master/example/ap.tgz?raw=true" -O ap.tgz
# $ tar xvzf ap.tgz
my @vocabs = "./ap/vocab.txt".IO.lines;
my @documents = "./ap/ap.dat".IO.lines;
my $documents = Algorithm::HierarchicalPAM::Formatter.from-libsvm(@documents);
my Algorithm::HierarchicalPAM $hpam .= new(:$documents, :@vocabs);
my Algorithm::HierarchicalPAM::HierarchicalPAMModel $model = $hpam.fit(:num-super-topics(10), :num-sub-topics(20), :num-iterations(500));
$model.topic-word-matrix.say; # show topic-word matrix
$model.document-topic-matrix; # show document-topic matrix
$model.log-likelihood.say; # show likelihood
$model.nbest-words-per-topic.say # show nbest words per topic
DESCRIPTION
===========
Algorithm::HierarchicalPAM - A Raku Hierarchical PAM (model 2) implementation.
CONSTRUCTOR
-----------
### new
Defined as:
submethod BUILD(:$!documents!, :$!vocabs! is raw) { }
Constructs a new Algorithm::HierarchicalPAM instance.
METHODS
-------
### fit
Defined as:
method fit(Int :$num-iterations = 500, Int :$num-super-topics!, Int :$num-sub-topics!, Num :$alpha = 0.1e0, Num :$beta = 0.1e0, Int :$seed --> Algorithm::HierarchicalPAM::HierarchicalPAMModel)
Returns an Algorithm::HierarchicalPAM::HierarchicalPAMModel instance.
* `:$num-iterations` is the number of iterations for gibbs sampler
* `:$num-super-topics!` is the number of super topics
* `:$num-sub-topics!` is the number of sub topics
* `alpha` is the prior for theta distribution (i.e., document-topic distribution)
* `beta` is the prior for phi distribution (i.e., topic-word distribution)
* `seed` is the seed for srand
AUTHOR
======
titsuki <[email protected]>
COPYRIGHT AND LICENSE
=====================
Copyright 2019 titsuki
This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
The algorithm is from:
* Mimno, David, Wei Li, and Andrew McCallum. "Mixtures of hierarchical topics with pachinko allocation." Proceedings of the 24th international conference on Machine learning. ACM, 2007.
* Minka, Thomas. "Estimating a Dirichlet distribution." (2000): 4.
|
### ----------------------------------------------------
### -- Algorithm::HierarchicalPAM
### -- Licenses: Artistic-2.0
### -- Authors: titsuki
### -- File: .travis.yml
### ----------------------------------------------------
os:
- linux
- osx
language: perl6
perl6:
- latest
install:
- rakudobrew build zef
- zef install --deps-only --/test .
script:
- PERL6LIB=$PWD/lib zef build .
- PERL6LIB=$PWD/lib prove -e perl6 -vr t/
sudo: false
|
### ----------------------------------------------------
### -- Algorithm::HierarchicalPAM
### -- Licenses: Artistic-2.0
### -- Authors: titsuki
### -- File: dist.ini
### ----------------------------------------------------
name = Algorithm-HierarchicalPAM
[ReadmeFromPod]
; enable = false
filename = lib/Algorithm/HierarchicalPAM.pm6
[PruneFiles]
; match = ^ 'xt/'
[Badges]
provider = travis-ci.com
|
### ----------------------------------------------------
### -- Algorithm::HierarchicalPAM
### -- Licenses: Artistic-2.0
### -- Authors: titsuki
### -- File: t/01-basic.t
### ----------------------------------------------------
use v6.c;
use Test;
use Algorithm::HierarchicalPAM;
use Algorithm::HierarchicalPAM::HierarchicalPAMModel;
use Algorithm::HierarchicalPAM::Document;
use Algorithm::HierarchicalPAM::Formatter;
subtest {
my @documents = (
"a b c",
"d e f",
);
my ($documents, $vocabs) = Algorithm::HierarchicalPAM::Formatter.from-plain(@documents);
is-deeply $vocabs, ["a", "b", "c", "d", "e", "f"];
my Algorithm::HierarchicalPAM $hpam .= new(:$documents, :$vocabs);
my Algorithm::HierarchicalPAM::HierarchicalPAMModel $model = $hpam.fit(:num-super-topics(3), :num-sub-topics(5), :num-iterations(1000));
lives-ok { $model.topic-word-matrix }
lives-ok { $model.document-topic-matrix }
lives-ok { $model.log-likelihood }
lives-ok { $model.nbest-words-per-topic }
}, "Check if it could process a very short document. (just a smoke test)";
subtest {
my @documents = (
"a b c d",
"e f g h",
);
my ($documents, $vocabs) = Algorithm::HierarchicalPAM::Formatter.from-plain(@documents);
my Algorithm::HierarchicalPAM $lda .= new(:$documents, :$vocabs);
my Algorithm::HierarchicalPAM::HierarchicalPAMModel $model = $lda.fit(:num-super-topics(3), :num-sub-topics(5), :num-iterations(1000));
is $model.topic-word-matrix.shape, (3 + 3 * 5, 8);
is $model.document-topic-matrix.shape, (2, 3 + 3 * 5);
is $model.nbest-words-per-topic(9).shape, (3 + 3 * 5, 8), "n is greater than vocab size";
is $model.nbest-words-per-topic(8).shape, (3 + 3 * 5, 8), "n is equal to the vocab size";
is $model.nbest-words-per-topic(7).shape, (3 + 3 * 5, 7), "n is less than vocab size";
}, "Check resulting matrix shape";
subtest {
my @documents = (
"a b c d",
"e f g h",
);
my ($documents, $vocabs) = Algorithm::HierarchicalPAM::Formatter.from-plain(@documents);
my Algorithm::HierarchicalPAM $lda .= new(:$documents, :$vocabs);
my Algorithm::HierarchicalPAM::HierarchicalPAMModel $model = $lda.fit(:num-super-topics(3), :num-sub-topics(5), :num-iterations(1000));
is $model.vocabulary.elems, 8;
}, "Check vocabulary size";
subtest {
my @documents = (
("a" .. "z").pick(100).join(" "),
("a" .. "z").pick(100).join(" "),
("a" .. "z").pick(100).join(" ")
);
my ($documents, $vocabs) = Algorithm::HierarchicalPAM::Formatter.from-plain(@documents);
my Algorithm::HierarchicalPAM $lda .= new(:$documents, :$vocabs);
my @prev;
for 1..5 {
my Algorithm::HierarchicalPAM::HierarchicalPAMModel $model = $lda.fit(:num-super-topics(3), :num-sub-topics(5), :num-iterations(1000), :seed(2));
if @prev {
is @prev, $model.document-topic-matrix;
}
@prev = $model.document-topic-matrix;
}
}, "Check reproducibility";
done-testing;
|
### ----------------------------------------------------
### -- Algorithm::KDimensionalTree
### -- Licenses: Artistic-2.0
### -- Authors: Anton Antonov
### -- File: META6.json
### ----------------------------------------------------
{
"name": "Algorithm::KDimensionalTree",
"description": "K-dimensional Tree (K-d tree) algorithm implementations.",
"version": "0.1.1",
"authors": [
"Anton Antonov"
],
"auth": "zef:antononcube",
"depends": [
"Math::DistanceFunctions:ver<0.1.1+>"
],
"build-depends": [],
"test-depends": [],
"provides": {
"Algorithm::KDimensionalTree": "lib/Algorithm/KDimensionalTree.rakumod"
},
"resources": [
"KDTreeTest.json",
"DeriveTestData.wl"
],
"license": "Artistic-2.0",
"tags": [
"k-d tree",
"k-dimensional tree",
"spatial search",
"nearest"
],
"api": "1",
"source-url": "https://github.com/antononcube/Raku-Algorithm-KDTree.git",
"raku": "6.d"
}
|
### ----------------------------------------------------
### -- Algorithm::KDimensionalTree
### -- Licenses: Artistic-2.0
### -- Authors: Anton Antonov
### -- 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.
|
### ----------------------------------------------------
### -- Algorithm::KDimensionalTree
### -- Licenses: Artistic-2.0
### -- Authors: Anton Antonov
### -- File: README-work.md
### ----------------------------------------------------
# Algorithm::KDimensionalTree
Raku package with implementations of the [K-Dimensional Tree (K-D Tree) algorithm](https://en.wikipedia.org/wiki/K-d_tree).
**Remark:** This package should not be confused with
["Algorithm::KdTree"](https://raku.land/github:titsuki/Algorithm::KdTree), [ITp1],
which provides Raku bindings to a C-implementation of the K-D Tree algorithm.
(A primary motivation for making this package, "Algorithm::KDimensionalTree", was to have a pure-Raku implementation.)
**Remark:** The versions "ver<0.1.0+>" with the API "api<1>" of this package are better utilized via the
package ["Math::Nearest"](https://github.com/antononcube/Raku-Math-Nearest).
Compared to the simple scanning algorithm this implementation of the K-D Tree algorithm is often 2÷15 times faster
for randomly generated low dimensional data. (Say. less than 6D.)
It can be 200+ times faster for "real life" data, like, Geo-locations of USA cities.
The implementation is tested for correctness against Mathematica's [`Nearest`](https://reference.wolfram.com/language/ref/Nearest.html).
(See the resource files.)
### Features
- Finds both top-k Nearest Neighbors (NNs).
- See the method `k-nearest`.
- Finds NNs within a ball with a given radius.
- See the method `nearest-within-ball`.
- Can return indexes and distances for the found NNs.
- The result shape is controlled with the adverb `:values`.
- Works with arrays of numbers, arrays of arrays of numbers, and arrays of pairs.
- Utilizes distance functions from ["Math::DistanceFunctions"](https://github.com/antononcube/Raku-Math-DistanceFunctions).
- Which can be specified by their string names, like, "bray-curtis" or "cosine-distance".
- Allows custom distance functions to be used.
------
## Installation
From Zef ecosystem:
```
zef install Algorithm::KDimensionalTree
```
From GitHub:
```
zef install https://github.com/antononcube/Raku-Algorithm-KDimensionalTree.git
```
-----
## Usage examples
### Setup
```perl6
use Algorithm::KDimensionalTree;
use Data::TypeSystem;
use Text::Plot;
```
### Set of points
Make a random set of points:
```perl6
my @points = ([(^100).rand, (^100).rand] xx 30).unique;
deduce-type(@points);
```
### Create the K-dimensional tree object
```perl6
my $kdTree = Algorithm::KDimensionalTree.new(@points);
say $kdTree;
```
### Nearest k-neighbors
Use as a search point one from the points set:
```perl6
my @searchPoint = |@points.head;
```
Find 6 nearest neighbors:
```perl6
my @res = $kdTree.k-nearest(@searchPoint, 6);
.say for @res;
```
### Plot
Plot the points, the found nearest neighbors, and the search point:
```perl6
my @point-char = <* ⏺ ▲>;
say <data nns search> Z=> @point-char;
say text-list-plot(
[@points, @res, [@searchPoint,]],
:@point-char,
x-limit => (0, 100),
y-limit => (0, 100),
width => 60,
height => 20);
```
-----
## TODO
- [ ] TODO Implementation
- [X] DONE Using distance functions from an "universal" package
- E.g. "Math::DistanceFunctions"
- [X] DONE Using distance functions other than Euclidean distance
- [X] DONE Returning properties
- [X] DONE Points
- [X] DONE Indexes
- [X] DONE Distances
- [X] DONE Labels
- [X] DONE Combinations of those
- This is implemented by should be removed.
- There is another package -- ["Math::Nearest"](https://github.com/antononcube/Raku-Math-Nearest) --
that handles *all* nearest neighbors finders.
- Version "0.1.0 with "api<1>" is without the `.nearest` method.
- [X] DONE Having an umbrella function `nearest`
- Instead of creating a KDTree object etc.
- This might require making a functor `nearest-function`
- This is better done in a different package
- See ["Math::Nearest"](https://github.com/antononcube/Raku-Math-Nearest)
- [ ] TODO Make the nearest methods work with strings
- For example, using Hamming distance over a collection of words.
- Requires using the distance function as a comparator for the splitting hyperplanes.
- This means, any objects can be used as long as they provide a distance function.
- [X] DONE Extensive correctness tests
- Derived with Mathematica / WL (see the resources)
- [ ] TODO Documentation
- [X] DONE Basic usage examples with text plots
- [ ] TODO More extensive documentation with a Jupyter notebook
- Using "JavaScript::D3".
- [ ] TODO Corresponding blog post
- [ ] MAYBE Corresponding video
-----
## References
[AAp1] Anton Antonov, [Math::DistanceFunctions Raku package](https://github.com/antononcube/Raku-Math-DistanceFunctions), (2024), [GitHub/antononcube](https://github.com/antononcube).
[AAp2] Anton Antonov, [Math::Nearest Raku package](https://github.com/antononcube/Raku-Math-Nearest), (2024), [GitHub/antononcube](https://github.com/antononcube).
[AAp3] Anton Antonov, [Data::TypeSystem Raku package](https://github.com/antononcube/Raku-Data-TypeSystem), (2023), [GitHub/antononcube](https://github.com/antononcube).
[AAp4] Anton Antonov, [Text::Plot Raku package](https://github.com/antononcube/Raku-Text-Plot), (2022), [GitHub/antononcube](https://github.com/antononcube).
[ITp1] Itsuki Toyota, [Algorithm::KdTree Raku package](https://github.com/titsuki/p6-Algorithm-KdTree), (2016-2024), [GitHub/titsuki](https://github.com/titsuki).
|
### ----------------------------------------------------
### -- Algorithm::KDimensionalTree
### -- Licenses: Artistic-2.0
### -- Authors: Anton Antonov
### -- File: README.md
### ----------------------------------------------------
# Algorithm::KDimensionalTree
Raku package with implementations of the [K-Dimensional Tree (K-D Tree) algorithm](https://en.wikipedia.org/wiki/K-d_tree).
**Remark:** This package should not be confused with
["Algorithm::KdTree"](https://raku.land/github:titsuki/Algorithm::KdTree), [ITp1],
which provides Raku bindings to a C-implementation of the K-D Tree algorithm.
(A primary motivation for making this package, "Algorithm::KDimensionalTree", was to have a pure-Raku implementation.)
**Remark:** The versions "ver<0.1.0+>" with the API "api<1>" of this package are better utilized via the
package ["Math::Nearest"](https://github.com/antononcube/Raku-Math-Nearest).
Compared to the simple scanning algorithm this implementation of the K-D Tree algorithm is often 2÷15 times faster
for randomly generated low dimensional data. (Say. less than 6D.)
It can be 200+ times faster for "real life" data, like, Geo-locations of USA cities.
The implementation is tested for correctness against Mathematica's [`Nearest`](https://reference.wolfram.com/language/ref/Nearest.html).
(See the resource files.)
### Features
- Finds both top-k Nearest Neighbors (NNs).
- See the method `k-nearest`.
- Finds NNs within a ball with a given radius.
- See the method `nearest-within-ball`.
- Can return indexes and distances for the found NNs.
- The result shape is controlled with the adverb `:values`.
- Works with arrays of numbers, arrays of arrays of numbers, and arrays of pairs.
- Utilizes distance functions from ["Math::DistanceFunctions"](https://github.com/antononcube/Raku-Math-DistanceFunctions).
- Which can be specified by their string names, like, "bray-curtis" or "cosine-distance".
- Allows custom distance functions to be used.
------
## Installation
From Zef ecosystem:
```
zef install Algorithm::KDimensionalTree
```
From GitHub:
```
zef install https://github.com/antononcube/Raku-Algorithm-KDimensionalTree.git
```
-----
## Usage examples
### Setup
```perl6
use Algorithm::KDimensionalTree;
use Data::TypeSystem;
use Text::Plot;
```
```
# (Any)
```
### Set of points
Make a random set of points:
```perl6
my @points = ([(^100).rand, (^100).rand] xx 30).unique;
deduce-type(@points);
```
```
# Vector(Vector(Atom((Numeric)), 2), 30)
```
### Create the K-dimensional tree object
```perl6
my $kdTree = Algorithm::KDimensionalTree.new(@points);
say $kdTree;
```
```
# Algorithm::KDimensionalTree(points => 30, distance-function => &euclidean-distance)
```
### Nearest k-neighbors
Use as a search point one from the points set:
```perl6
my @searchPoint = |@points.head;
```
```
# [89.27640360563157 68.36845738910054]
```
Find 6 nearest neighbors:
```perl6
my @res = $kdTree.k-nearest(@searchPoint, 6);
.say for @res;
```
```
# [89.27640360563157 68.36845738910054]
# [91.96352893754062 73.56174634865347]
# [80.0160216888336 69.80400458389097]
# [99.2564424012451 76.5797786385005]
# [79.5081497932748 52.564329376808196]
# [76.82139591710131 47.8616016873568]
```
### Plot
Plot the points, the found nearest neighbors, and the search point:
```perl6
my @point-char = <* ⏺ ▲>;
say <data nns search> Z=> @point-char;
say text-list-plot(
[@points, @res, [@searchPoint,]],
:@point-char,
x-limit => (0, 100),
y-limit => (0, 100),
width => 60,
height => 20);
```
```
# (data => * nns => ⏺ search => ▲)
# ++----------+-----------+----------+-----------+----------++
# + + 100.00
# | * |
# | * * |
# + + 80.00
# | ⏺ ⏺|
# | * * ⏺ ▲ |
# | * * |
# + + 60.00
# | * * * ⏺ |
# | ⏺ *|
# + * ** * + 40.00
# | |
# | * * * |
# | * |
# + * + 20.00
# | * |
# | * * * |
# + + 0.00
# ++----------+-----------+----------+-----------+----------++
# 0.00 20.00 40.00 60.00 80.00 100.00
```
-----
## TODO
- [ ] TODO Implementation
- [X] DONE Using distance functions from an "universal" package
- E.g. "Math::DistanceFunctions"
- [X] DONE Using distance functions other than Euclidean distance
- [X] DONE Returning properties
- [X] DONE Points
- [X] DONE Indexes
- [X] DONE Distances
- [X] DONE Labels
- [X] DONE Combinations of those
- This is implemented by should be removed.
- There is another package -- ["Math::Nearest"](https://github.com/antononcube/Raku-Math-Nearest) --
that handles *all* nearest neighbors finders.
- Version "0.1.0 with "api<1>" is without the `.nearest` method.
- [X] DONE Having an umbrella function `nearest`
- Instead of creating a KDTree object etc.
- This might require making a functor `nearest-function`
- This is better done in a different package
- See ["Math::Nearest"](https://github.com/antononcube/Raku-Math-Nearest)
- [ ] TODO Make the nearest methods work with strings
- For example, using Hamming distance over a collection of words.
- Requires using the distance function as a comparator for the splitting hyperplanes.
- This means, any objects can be used as long as they provide a distance function.
- [X] DONE Extensive correctness tests
- Derived with Mathematica / WL (see the resources)
- [ ] TODO Documentation
- [X] DONE Basic usage examples with text plots
- [ ] TODO More extensive documentation with a Jupyter notebook
- Using "JavaScript::D3".
- [ ] TODO Corresponding blog post
- [ ] MAYBE Corresponding video
-----
## References
[AAp1] Anton Antonov, [Math::DistanceFunctions Raku package](https://github.com/antononcube/Raku-Math-DistanceFunctions), (2024), [GitHub/antononcube](https://github.com/antononcube).
[AAp2] Anton Antonov, [Math::Nearest Raku package](https://github.com/antononcube/Raku-Math-Nearest), (2024), [GitHub/antononcube](https://github.com/antononcube).
[AAp3] Anton Antonov, [Data::TypeSystem Raku package](https://github.com/antononcube/Raku-Data-TypeSystem), (2023), [GitHub/antononcube](https://github.com/antononcube).
[AAp4] Anton Antonov, [Text::Plot Raku package](https://github.com/antononcube/Raku-Text-Plot), (2022), [GitHub/antononcube](https://github.com/antononcube).
[ITp1] Itsuki Toyota, [Algorithm::KdTree Raku package](https://github.com/titsuki/p6-Algorithm-KdTree), (2016-2024), [GitHub/titsuki](https://github.com/titsuki).
|
### ----------------------------------------------------
### -- Algorithm::KDimensionalTree
### -- Licenses: Artistic-2.0
### -- Authors: Anton Antonov
### -- File: experiments/KDimensionalTree-demo.raku
### ----------------------------------------------------
#!/usr/bin/env raku
use v6.d;
use lib <. lib>;
use Algorithm::KDimensionalTree;
use Math::DistanceFunctions;
use Data::TypeSystem;
use Text::Plot;
my @points = ([(^100).rand, (^100).rand] xx 100).unique;
say deduce-type(@points);
my $kdTree = Algorithm::KDimensionalTree.new(@points);
say $kdTree;
my @searchPoint = |@points.head;
#my @searchPoint = [20, 60];
say (:@searchPoint);
# ========================================================================================================================
say "=" x 120;
say 'Nearest k-neighbors';
say "-" x 120;
my $tstart = now;
my @res = $kdTree.k-nearest(@searchPoint, 12);
my $tend = now;
say "Computation time: {$tend - $tstart}";
say (:@res);
say 'elems => ', @res.elems;
say "Contains the search point: {[||] @res.map({ euclidean-distance(@searchPoint, $_) ≤ 0e-12 })}";
my @point-char = <* ⏺ ▲>;
say <data nns search> Z=> @point-char;
say text-list-plot(
[@points, @res, [@searchPoint,]],
:@point-char,
x-limit => (0, 100),
y-limit => (0, 100),
width => 60,
height => 20);
# ========================================================================================================================
say "=" x 120;
say 'Nearest neighbors within a radius (cosine distance)';
say "-" x 120;
my $kdTree2 = Algorithm::KDimensionalTree.new( @points, distance-function => &cosine-distance );
say $kdTree2;
my $tstart2 = now;
my @res2 = $kdTree2.nearest-within-ball(@searchPoint, 0.02):v;
my $tend2 = now;
say "Computation time: {$tend2 - $tstart2}";
say (:@res2);
@point-char = <* ⏺ ▲>;
say <data nns search> Z=> @point-char;
say text-list-plot(
[@points, @res2, [@searchPoint,]],
:@point-char,
x-limit => (0, 100),
y-limit => (0, 100),
width => 60,
height => 20);
|
### ----------------------------------------------------
### -- Algorithm::KDimensionalTree
### -- Licenses: Artistic-2.0
### -- Authors: Anton Antonov
### -- File: experiments/NodalKDTree-demo.raku
### ----------------------------------------------------
#!/usr/bin/env raku
use v6.d;
use lib <. lib>;
use Algorithm::NodalKDTree;
sub show-nearest($k, $heading, $kd, @p) {
print qq:to/END/;
$heading:
Point: [@p.join(',')]
END
my $n = find-nearest($k, $kd, @p);
print qq:to/END/;
Nearest neighbor: [$n.nearest.join(',')]
Distance: &sqrt($n.dist_sqd)
Nodes visited: $n.nodes_visited()
END
}
sub random-point($k) {
[rand xx $k]
}
sub random-points($k, $n) {
[random-point($k) xx $n]
}
my $kd1 = NodalKDTree.new([[2, 3], [5, 4], [9, 6], [4, 7], [8, 1], [7, 2]],
Orthotope.new(:min([0, 0]), :max([10, 10])));
show-nearest(2, "Wikipedia example data", $kd1, [9, 2]);
my $N = 1000;
my $t0 = now;
my $kd2 = NodalKDTree.new(random-points(3, $N), Orthotope.new(:min([0, 0, 0]), :max([1, 1, 1])));
my $t1 = now;
show-nearest(2,
"k-d tree with $N random 3D points (generation time: { $t1 - $t0 }s)",
$kd2, random-point(3));
|
### ----------------------------------------------------
### -- Algorithm::KDimensionalTree
### -- Licenses: Artistic-2.0
### -- Authors: Anton Antonov
### -- File: experiments/KDTree-tests.raku
### ----------------------------------------------------
#!/usr/bin/env raku
use v6.d;
use lib <. lib>;
use Algorithm::KDimensionalTree;
use Data::TypeSystem;
use Data::Summarizers;
use Math::DistanceFunctions;
use Text::Plot;
use JSON::Fast;
my %data = from-json(slurp($*CWD ~ '/resources/KDTreeTest.json'));
my @points = |%data<points>;
say deduce-type(@points);
say deduce-type(@points):tally;
say text-list-plot(@points);
say @points.head(12);
my $distance-function = 'CosineDistance';
my $radius = %data{$distance-function}<radius>;
my @searchPoint = |%data<searchPoint>;
my @expected = |%data{$distance-function}<nns>;
my $kdTree = Algorithm::KDimensionalTree.new(@points, :$distance-function);
say $kdTree;
my @res = $kdTree.nearest-within-ball(@searchPoint, $radius):v;
say 'expected elems => ', @expected.elems;
say 'result elems => ', @res.elems;
my @diffs = (@expected.sort.Array Z @res.sort.Array).map({ $_.head «-» $_.tail });
say 'max-norm (expected Z- result) => ', norm(@diffs.map({ norm($_) }), p => 1);
my @point-char = <* ⏺ ▲>;
say <data nns search> Z=> @point-char;
say text-list-plot(
[@points, @res, [@searchPoint,]],
:@point-char,
title => 'result',
x-limit => (0, 100),
y-limit => (0, 100),
width => 60,
height => 20);
say "\n";
say text-list-plot(
[@points, @expected, [@searchPoint,]],
:@point-char,
title => 'expected',
x-limit => (0, 100),
y-limit => (0, 100),
width => 60,
height => 20);
|
### ----------------------------------------------------
### -- Algorithm::KDimensionalTree
### -- Licenses: Artistic-2.0
### -- Authors: Anton Antonov
### -- File: experiments/Different-point-types-demo.raku
### ----------------------------------------------------
#!/usr/bin/env raku
use v6.d;
use lib <. lib>;
use Algorithm::KDimensionalTree;
use Math::DistanceFunctions;
use Text::Levenshtein::Damerau;
use Data::TypeSystem;
use Data::Generators;
# ========================================================================================================================
say "=" x 120;
my @points = (10.rand xx 100);
say deduce-type(@points);
my $kdTree = Algorithm::KDimensionalTree.new(@points);
say $kdTree.nearest-within-ball(2, 0.2);
say $kdTree.k-nearest(2, 2);
# ========================================================================================================================
say "=" x 120;
#my @words = (('a'..'z').pick(5) xx 100)>>.join;
#my @words = random-pet-name(400).unique.grep({ $_.chars == 5 });
my @words = random-pet-name(120).unique;
my $searchWord = @words.head;
say deduce-type(@words);
my $kdTree2 = Algorithm::KDimensionalTree.new(@words, distance-function => &dld);
say $kdTree2;
say "searchWord : $searchWord";
say $kdTree2.nearest-within-ball($searchWord, 3);
.say for $kdTree2.k-nearest($searchWord, 8, :!values);
|
### ----------------------------------------------------
### -- Algorithm::KDimensionalTree
### -- Licenses: Artistic-2.0
### -- Authors: Anton Antonov
### -- File: resources/KDTreeTest.json
### ----------------------------------------------------
### -- Chunk 1 of 3
{
"points":[
[
7.902245284318181e1,
3.668742522886822e1
],
[
3.5573610706722235e1,
5.802522622121958e1
],
[
8.449767558749892e1,
4.22881897246086e1
],
[
5.340379374373515e1,
5.033206328659517
],
[
9.892546956195221e1,
4.05287582253728e1
],
[
9.248960472482528e1,
9.971722251496661e1
],
[
1.7644386430575082e1,
2.5755383036047334e1
],
[
2.4662047004356438e1,
6.831713726747651e1
],
[
7.144025878438927e1,
8.332821304481416e1
],
[
6.1736064530517865e1,
3.711666355756594e1
],
[
7.174003893768594e1,
8.114376193053491e1
],
[
2.2007146494501953e1,
3.910138828769894e1
],
[
7.813686079347377e1,
2.345471528033339e1
],
[
8.817224584409368e1,
2.7916180139330677e1
],
[
6.990397677787271e1,
5.905888090423292e1
],
[
1.2830034264135733e1,
5.364187904202521e1
],
[
8.098416847898451e1,
8.777900332948377e1
],
[
6.794272657231718e1,
3.275950757695375e1
],
[
1.5974023549522244e1,
2.2364452844429252e1
],
[
4.996414462650151e1,
5.326424793039743e1
],
[
5.628715146258568e1,
8.514313641648664e1
],
[
1.137365206429979e1,
4.3067332647658105e1
],
[
9.873456722928461e1,
3.1908969981188136e1
],
[
3.638810176943741e1,
2.0869433532575286e1
],
[
5.265113559343007e1,
5.550860282568098e1
],
[
7.692597883833844e1,
5.248697484005734e1
],
[
6.969364754103552,
1.1608628508516091e1
],
[
4.932183790751236e1,
6.43032501233892e1
],
[
2.5326683038663973e1,
1.5428634298252192e1
],
[
6.76264453686839e1,
4.487664896489838e1
],
[
4.0277271354086e1,
2.7702824792445853
],
[
8.634108643933845e1,
7.764276689103414e1
],
[
1.1902387521702579e1,
2.68389464628046e1
],
[
6.947536019931414e1,
4.609491102607103e1
],
[
7.584727504482808e1,
9.769320486828175e1
],
[
8.406494354721514e1,
5.433398520092288e1
],
[
5.1914760988714534e1,
1.7044100109131264e1
],
[
5.286807840983812,
5.9054244101523636e1
],
[
5.530488725440307e1,
7.970792945587053e1
],
[
4.129305951138181e1,
2.7955919607368358e1
],
[
2.5432493577003967e1,
3.4077606855335176
],
[
1.699171200243204e1,
9.228205562763245e1
],
[
4.398951708877169e1,
3.216894887249086e1
],
[
2.981628762316518e1,
2.8521497817851127e1
],
[
3.611894326809275e1,
8.033308260295448e1
],
[
3.27726103165422,
4.797793037924458e1
],
[
8.088715035668972e1,
4.943848260450039e1
],
[
6.716655749254596e1,
2.8002396693404847
],
[
3.034165808636982e1,
6.219457573096696e1
],
[
2.8045889807607324e1,
7.450451343624164e1
],
[
2.9027349637953762e1,
7.658633163410815e1
],
[
4.578983850709648,
9.995455923770788e1
],
[
9.940375534618161e1,
2.2693915126455707e1
],
[
8.629062816095075e1,
5.880427424432557e1
],
[
8.725425532647796e1,
2.7205727708171423e1
],
[
1.3449966046053547e1,
5.177183933743433e1
],
[
1.0033885492379e1,
7.391819225725521e1
],
[
2.143276124657717,
8.858536498107568
],
[
8.674040433293376e1,
2.361844967186157e1
],
[
6.802086061647736e1,
1.4587353259451177e1
],
[
7.852056097397983e1,
9.48362512886819e1
],
[
9.16366203578599e1,
6.714360218617327e1
],
[
4.4634201064764255e1,
7.068065293035025e1
],
[
6.0116009001625685e1,
2.6738909883702263e1
],
[
5.614357281433578e1,
7.110085442215936e1
],
[
3.90650974921939e1,
7.395765717101611
],
[
5.703163866553851e1,
7.162953760875362e1
],
[
8.00869355464923e1,
4.4923621763805414e1
],
[
9.036508347680464e1,
9.89864979001342e1
],
[
8.91865984788403e1,
4.411121794388606e1
],
[
9.898195549416278e1,
7.262452564290038e1
],
[
3.0778973357470647e1,
5.771591157297314e1
],
[
1.7662675847704577e1,
1.4047821995073946
],
[
9.246714887999303e1,
1.7915956149120944e1
],
[
9.913414332799974,
7.598894895411681e1
],
[
1.4554420933129393,
3.3354644121723084e1
],
[
8.572871062678459,
1.3786475241654841e1
],
[
7.336388712809264e1,
7.203655556220573e1
],
[
6.829980903192165e1,
6.288482966482286e1
],
[
7.192096741906994e1,
8.871834460041435e1
],
[
5.528176161097235e1,
6.292027596993208
],
[
3.4784433686037005e1,
5.644346672017332e1
],
[
4.8835454134922855e1,
5.9335815551730434e1
],
[
7.151834272500287e1,
3.1457906261872267e1
],
[
2.2279927589860705e1,
6.643598126273096e1
],
[
4.966423766390113e1,
3.913146700620814e1
],
[
2.8726389443651385e1,
2.6576086933259404
],
[
3.683618538298742e1,
2.9888977689122385e1
],
[
0.923646919079772,
2.5253141806628363e1
],
[
6.385591485841812e1,
5.584995740171797e1
],
[
3.462891818311368e1,
1.9127356864192805e1
],
[
1.3330201976574713e1,
5.3487977501105945e1
],
[
3.1561364171334418e1,
8.04242418243542e1
],
[
7.886503621739854e1,
7.470143338139908e1
],
[
5.030088454372216e1,
9.45109198303501e1
],
[
4.456296858232628e1,
3.008598737900701e1
],
[
1.5826984758008322e1,
3.656546997267921e1
],
[
9.570201067983282e1,
2.6643930393411637
],
[
6.693262196599608e1,
5.7538086338178175e1
],
[
1.3512582708623128e1,
1.8056293945952916e1
],
[
6.40828723138847e1,
3.88117221399105
],
[
7.088382519184583e1,
3.37847574028188e1
],
[
4.454574509490698,
8.186723884083631e1
],
[
5.3839711273070776e1,
6.2601891312238564e1
],
[
3.420753382143306e1,
1.1293172367341441e1
],
[
8.705970056700181,
2.338971450579308
],
[
6.0150910581611924e1,
8.67642322788544e1
],
[
8.529261782849446e1,
6.0341251903571305e1
],
[
2.2798138763232444e1,
3.522105584168932e1
],
[
4.247408338475449e1,
7.125134953857454
],
[
3.528184685134542e1,
7.194115111516987e1
],
[
6.540051387470157,
4.05050742600597e1
],
[
5.018923797147562e1,
5.549005378643156e1
],
[
3.2598994103131673,
1.663861075017931e1
],
[
3.6091013929294746,
8.2018364934923e1
],
[
1.2828549029357774e1,
3.49469736037052e1
],
[
9.338820673732053e1,
8.11061919224328e1
],
[
3.540284667675135e1,
3.8032406266465216e1
],
[
4.9289420555296516e1,
4.1868234443781006e1
],
[
4.0626565761332046e1,
7.860315325075896e1
],
[
2.0733235515862035e1,
3.322986998615255e1
],
[
5.360670032684851,
6.160746070569746e1
],
[
2.7956490189135394e1,
3.388831062469933e1
],
[
6.000489252737111e1,
9.56540397015385e1
],
[
6.857411532371253e1,
6.485594523338912e1
],
[
2.76988177557715e1,
1.1064095933212158e1
],
[
7.91629777138528e1,
8.640596324620986e1
],
[
4.354011385127839e1,
9.18896847232067e1
],
[
8.842508384671427e1,
2.323046206504067e1
],
[
3.852857395216495e1,
2.809760876985169e1
],
[
7.167852804787532e1,
8.289260310905121e1
],
[
2.475562322206592e1,
3.245436662003968
],
[
3.693721021390232,
7.251411835148153e1
],
[
8.004869489978239e1,
4.168363673786661e1
],
[
1.307391247670094e1,
8.837730007608684e1
],
[
9.076718473479914e1,
3.530741963086231e1
],
[
9.56600926655853e1,
5.400299126004481e1
],
[
2.7662233913215545e1,
5.79599713544647
],
[
2.1994872292519446e1,
7.42744352215752e1
],
[
9.030339134278128e1,
2.935593659470453e1
],
[
2.6067355406881873e1,
8.368866310984379e1
],
[
7.131114470872896e1,
5.8132033678317356e1
],
[
7.323050378950745e1,
1.9484207322442913e1
],
[
6.0976767697677786e1,
7.80803190142895e1
],
[
3.050267542440227e1,
1.4280622533772117e1
],
[
6.718480664854735e1,
2.7178755631040502e1
],
[
2.8753770013137654e1,
4.077030043289497e1
],
[
6.09070865500415e1,
3.985551550119823e1
],
[
1.1570477055911965e1,
8.907506310648097e1
],
[
7.759666145388886e1,
5.651189453636175e1
],
[
9.027785639695307e1,
5.7002720719214494e1
],
[
3.964721116572821e1,
7.692987060379673e1
],
[
7.708414131519586e1,
6.48746509217346e1
],
[
3.721897350682232e1,
5.7468864757827276e1
],
[
2.305845287213913,
9.155097291246423e1
],
[
7.971903469499381,
8.055941211607106e1
],
[
5.4770658798604586e1,
3.043053508087351e1
],
[
8.673385049456209e1,
2.3624130565951248e1
],
[
8.627982995121425e1,
6.435215606745223e1
],
[
4.173277741542287e1,
3.3675653958082705e1
],
[
3.853709498110135e1,
5.355140935015015
],
[
8.16605203382718e1,
3.956258711057714e1
],
[
3.7252979355359884e1,
7.175361120074615 |
### ----------------------------------------------------
### -- Algorithm::KDimensionalTree
### -- Licenses: Artistic-2.0
### -- Authors: Anton Antonov
### -- File: resources/KDTreeTest.json
### ----------------------------------------------------
### -- Chunk 2 of 3
e1
],
[
1.4889079490824102e1,
7.483180104597832e1
],
[
8.283837186623481e1,
5.49584052875781e1
],
[
2.0975135557811512e1,
4.624255800260789e1
],
[
1.015265590962187,
5.763345185423347e1
],
[
2.0696964473046634e1,
8.21006501117613e1
],
[
2.793788676819105,
2.7231564058595154e1
],
[
1.4426382935702222e1,
3.166431603280421e1
],
[
6.916640845754029e1,
7.779801344697879e1
],
[
7.36350577490706e1,
9.748767712299346e1
],
[
1.9697491144113854,
3.1866777208003896
],
[
6.518813594201049,
6.150994768010932e1
],
[
6.665672941008626e1,
5.893896758098981e1
],
[
5.500551796996652e1,
8.97910073238063e1
],
[
6.490381564913324e1,
5.8083364127197314e1
],
[
3.8448336186307444,
2.60352112744644e1
],
[
0.20915332243527018,
9.477818555998039e1
],
[
1.1322756387686027e1,
8.57767189817587e1
],
[
4.6051558301576875e1,
6.1783826962581685e1
],
[
4.640755184281829e1,
2.8862503850426293e1
],
[
6.197687999252537,
5.894481661990574e1
],
[
5.988836200057071e1,
4.2285701198332816e1
],
[
1.626321422355366e1,
0.7101003890747961
],
[
2.920407824533052e1,
3.230883472241709e1
],
[
4.109216244840334e1,
4.762232016604608e1
],
[
9.296838030401483e1,
4.8941952864024955e1
],
[
9.133200398634281e1,
5.354618472675497e1
],
[
5.047509915071623e1,
1.097620176213438e1
],
[
8.190329902980471e1,
6.6814856319102205
],
[
6.927139981801787e1,
1.8558342821983757e1
],
[
2.476233775651555e1,
5.3594402401926914e1
],
[
1.1050624811344818e1,
5.718439978617437e1
],
[
4.084759188896595e1,
3.533153942373309e1
],
[
9.703408052099388e1,
1.2397192672182399e1
],
[
3.490833039020765e1,
8.828116698154042e1
],
[
5.7323459627787145e1,
8.528045488965549e1
],
[
4.948196922434431e1,
7.7365835716487e1
],
[
8.461237516097404e1,
8.314353119862136e1
],
[
9.713395186623933e1,
1.9994935463821164e1
],
[
5.128312557851058e1,
8.41440076061713e1
],
[
9.19667890760714e1,
8.199219162841322e1
],
[
8.602511059852799e1,
7.3209717513166055
],
[
7.520150609198444e1,
5.159349370331293e1
],
[
9.374028262850365e1,
8.192766944267515e1
],
[
9.295886805435103e1,
5.962078935328111e1
],
[
3.135298653366391e1,
5.793486278903799e1
],
[
1.9457337718273294e1,
0.7228262211223893
],
[
9.558214281711969e1,
8.545208668979603e1
],
[
2.4380970438583716e1,
4.688426491272742e1
],
[
5.221933120557796e1,
2.0866946660377266e1
],
[
7.907645819462923e1,
4.326172287521658e1
],
[
3.3723265258169135e1,
3.8090400969123266
],
[
6.567606190842619e1,
2.6292435222542707
],
[
7.65815875650695e1,
3.710039828802138
],
[
9.712695380121767e1,
4.025303309812992e1
],
[
9.5735405668961,
1.392452217184676e1
],
[
4.801271619236644e1,
2.313917727499671
],
[
2.2575278311319025e1,
3.1134468281453195e1
],
[
9.641020589548839e1,
4.622845717872991
],
[
7.403840178664237e1,
1.3802332192430782e1
],
[
1.1839095702100863e1,
7.364061312304236e1
],
[
5.644037596019206e1,
1.2689445822415593
],
[
7.936776057753059e1,
6.91514836650482e1
],
[
3.526713150527695e1,
7.169859726779885e1
],
[
4.7258884772174525e1,
9.430776679065764e1
],
[
9.156571373876713e1,
2.1002844357689725e1
],
[
8.718040492621137e1,
3.6709660808487854
],
[
6.492327549150738e1,
6.643434436028059e1
],
[
9.23980171012137,
8.440992454875777e1
],
[
9.531240393767882e1,
7.806552928725017e1
],
[
7.185578892636332e1,
6.545886528880061
],
[
2.291899624437687e1,
5.097841197547214e1
],
[
7.49312022767877e1,
9.223255260558662e1
],
[
3.9545113125478366e1,
6.237359482448758e1
],
[
8.028968958289369e1,
1.4520585508100893e1
],
[
6.036347120371872e1,
5.158191789779184e1
],
[
6.851208822974567e1,
9.057040321502626e1
],
[
0.874001490563387,
1.3072400254788775e1
],
[
5.6065875445777124e1,
9.410654745661358e1
],
[
3.713267270492054e1,
5.04591082407145e1
],
[
6.548589279135996e1,
1.4577793593347295e1
],
[
1.2159072058045666e1,
7.561604608033855e1
],
[
3.268939450767587e1,
4.585760513948824e1
],
[
0.7496445159868301,
1.0206811775640972e1
],
[
6.307007410282591e1,
7.819427114808806e1
],
[
1.890236055517886e1,
7.99059236024743e1
],
[
1.4980593445687035e1,
3.1376306900451084e1
],
[
3.866373335758132e1,
6.778719935631074e1
],
[
2.43777979353292e1,
5.316401435366183e1
],
[
2.0427765392602055e1,
4.722366572127072
],
[
5.2232260665381546e1,
8.884116001645953e1
],
[
5.1776011849611876e1,
6.497773885806669e1
],
[
1.827447926786914e1,
8.415936529008329e1
],
[
1.5321999780269806e1,
8.306377831299318e1
],
[
5.508679740808594e1,
1.1460462193783385e1
],
[
5.6419916134388274e1,
9.439633497831136e1
],
[
4.889808952265534e1,
9.7482101072971e1
],
[
3.0215856817124717e1,
6.447978345705678e1
],
[
3.677604650743581e1,
7.356765712773938e1
],
[
3.1169430973400154e1,
4.8547501164444554e1
],
[
4.8344698456121336e1,
5.71934099705789e1
],
[
6.853463619756269e1,
6.302343448091338e1
],
[
9.986266166083183,
6.42137535460702e1
],
[
8.591028049793877e1,
7.97410841848912e1
],
[
2.42641381118394e1,
7.381578089721492e1
],
[
5.350695570958786e1,
4.063313612755525e1
],
[
4.092609355669708e1,
8.142077306172533e1
],
[
5.361250810716638e1,
4.532262127029199
],
[
4.386100187284717e1,
1.0387912925764155e1
],
[
4.5103068529536245e1,
9.446217612746156e1
],
[
4.9507433895209715e1,
2.0150172366037694e1
],
[
8.012136827114637e1,
1.5159199784080116e1
],
[
3.869924376202525e1,
4.163590199603547
],
[
1.5272194695634482e1,
1.5486509363712827e1
],
[
7.118842838611701e1,
3.223707918219705e1
],
[
1.6837027047378285e1,
7.19651895606452e1
],
[
6.072656198221898e1,
6.606871891380223e1
],
[
6.875581792654663e1,
4.0801783131172016e1
],
[
9.29346791690786e1,
6.23583261085308
],
[
6.575258638631936e1,
1.2605347013783955e1
],
[
2.7630104488783587e1,
7.533873773100683e1
],
[
9.384723233705449e1,
4.005191107447058e1
],
[
4.964509836860242e1,
7.025164570596516e1
],
[
8.447229762764772e1,
9.54658606312008e1
],
[
2.8169361084957927e1,
5.567550495350167e1
],
[
8.267799148206007e1,
9.948731119180448e1
],
[
2.1346920330482504e1,
8.891912469620047e1
],
[
9.460460198812387e1,
9.151413667512824e1
],
[
5.747414188750864e1,
1.7494157789315778
],
[
2.2083958600219916e1,
8.2477741504048e1
],
[
3.915660485233806e1,
2.0050795537152325e1
],
[
1.1854418709509005e1,
5.5931209643899564e1
],
[
4.038772920325442e1,
9.075575866201078e1
],
[
8.479426194063245e1,
8.343006634788318e1
],
[
6.824192675358671e1,
7.533543664334698e1
],
[
4.987240564863248e1,
6.054009711600082e1
],
[
1.0416642441288076e1,
7.041972772870398e1
],
[
7.761182358340548e1,
1.1001780411966706
]
],
"searchPoint":[
7.902245284318181e1,
3.668742522886822e1
],
"EuclideanDistance":{
"radius":20,
"nns":[
[
7.902245284318181e1,
3.668742522886822e1
],
[
8.16605203382718e1,
3.956258711057714e1
],
[
8.004869489978239e1,
4.168363673786661e1
],
[
7.907645819462923e1,
4.326172287521658e1
],
[
8.449767558749892e1,
4.22881897246086e1
],
[
8.00869355464923e1,
4.4923621763805414e1
],
[
7.088382519184583e1,
3.37847574028188e1
],
[
7.118842838611701e1,
3.223707918219705e1
],
[
7.151834272500287e1,
3.1457906261872267e1
],
[
6.875581792654663e1,
4.0801783131172016e1
],
[
6.794272657231718e1,
3.275950757695375e1
],
[
9.076718473479914e1,
3.530741963086231e1
],
[
8.725425532647796e1,
2.7205727708171423e1
],
[
8.91865984788403e1,
4.411121794388606e1
],
[
8.817224584409368e1,
2.7916180139330677e1
],
[
8.088715035668972e1,
4.943848260450039e1
],
[
7.813686079347377e1,
2.345471528033339e1
],
[
6.947536019931414e1,
4.609491102607103e1
],
[
9.030339134278128e1,
2.935593659470453e1
],
[
6.76264453686839e1,
4.487664896489838e1
],
[
8.673385049456209e1,
2.3624130565951248e1
],
[
8.674040433293376e1,
2.361844967186157e1
],
[
6.718480664854735e1,
2.7178755631040502e1
],
[
9.384723233705449e1,
4.005191107447058e1
],
[
7.5201506091 |
### ----------------------------------------------------
### -- Algorithm::KDimensionalTree
### -- Licenses: Artistic-2.0
### -- Authors: Anton Antonov
### -- File: resources/KDTreeTest.json
### ----------------------------------------------------
### -- Chunk 3 of 3
98444e1,
5.159349370331293e1
],
[
7.692597883833844e1,
5.248697484005734e1
],
[
8.842508384671427e1,
2.323046206504067e1
],
[
6.1736064530517865e1,
3.711666355756594e1
],
[
7.323050378950745e1,
1.9484207322442913e1
],
[
8.406494354721514e1,
5.433398520092288e1
],
[
6.09070865500415e1,
3.985551550119823e1
],
[
9.712695380121767e1,
4.025303309812992e1
],
[
9.296838030401483e1,
4.8941952864024955e1
],
[
8.283837186623481e1,
5.49584052875781e1
],
[
7.759666145388886e1,
5.651189453636175e1
],
[
5.988836200057071e1,
4.2285701198332816e1
]
]
},
"CosineDistance":{
"radius":2.0e-2,
"nns":[
[
7.902245284318181e1,
3.668742522886822e1
],
[
3.050267542440227e1,
1.4280622533772117e1
],
[
7.118842838611701e1,
3.223707918219705e1
],
[
7.088382519184583e1,
3.37847574028188e1
],
[
6.794272657231718e1,
3.275950757695375e1
],
[
6.0116009001625685e1,
2.6738909883702263e1
],
[
8.16605203382718e1,
3.956258711057714e1
],
[
7.151834272500287e1,
3.1457906261872267e1
],
[
8.91865984788403e1,
4.411121794388606e1
],
[
8.449767558749892e1,
4.22881897246086e1
],
[
9.384723233705449e1,
4.005191107447058e1
],
[
3.915660485233806e1,
2.0050795537152325e1
],
[
9.712695380121767e1,
4.025303309812992e1
],
[
8.004869489978239e1,
4.168363673786661e1
],
[
9.892546956195221e1,
4.05287582253728e1
],
[
4.9507433895209715e1,
2.0150172366037694e1
],
[
9.296838030401483e1,
4.8941952864024955e1
],
[
6.718480664854735e1,
2.7178755631040502e1
],
[
5.221933120557796e1,
2.0866946660377266e1
],
[
2.76988177557715e1,
1.1064095933212158e1
],
[
9.076718473479914e1,
3.530741963086231e1
],
[
7.907645819462923e1,
4.326172287521658e1
],
[
3.462891818311368e1,
1.9127356864192805e1
],
[
5.4770658798604586e1,
3.043053508087351e1
],
[
8.00869355464923e1,
4.4923621763805414e1
],
[
9.56600926655853e1,
5.400299126004481e1
],
[
3.638810176943741e1,
2.0869433532575286e1
],
[
9.133200398634281e1,
5.354618472675497e1
],
[
6.875581792654663e1,
4.0801783131172016e1
],
[
6.1736064530517865e1,
3.711666355756594e1
],
[
2.5326683038663973e1,
1.5428634298252192e1
],
[
8.088715035668972e1,
4.943848260450039e1
],
[
3.420753382143306e1,
1.1293172367341441e1
],
[
5.1914760988714534e1,
1.7044100109131264e1
],
[
9.030339134278128e1,
2.935593659470453e1
],
[
4.640755184281829e1,
2.8862503850426293e1
],
[
9.873456722928461e1,
3.1908969981188136e1
],
[
8.817224584409368e1,
2.7916180139330677e1
],
[
9.027785639695307e1,
5.7002720719214494e1
],
[
8.725425532647796e1,
2.7205727708171423e1
],
[
9.295886805435103e1,
5.962078935328111e1
],
[
8.406494354721514e1,
5.433398520092288e1
],
[
7.813686079347377e1,
2.345471528033339e1
],
[
6.09070865500415e1,
3.985551550119823e1
],
[
8.283837186623481e1,
5.49584052875781e1
],
[
6.947536019931414e1,
4.609491102607103e1
],
[
6.76264453686839e1,
4.487664896489838e1
],
[
4.456296858232628e1,
3.008598737900701e1
],
[
4.129305951138181e1,
2.7955919607368358e1
],
[
8.629062816095075e1,
5.880427424432557e1
],
[
7.692597883833844e1,
5.248697484005734e1
],
[
7.520150609198444e1,
5.159349370331293e1
],
[
8.673385049456209e1,
2.3624130565951248e1
],
[
8.674040433293376e1,
2.361844967186157e1
],
[
8.705970056700181,
2.338971450579308
],
[
6.927139981801787e1,
1.8558342821983757e1
],
[
7.323050378950745e1,
1.9484207322442913e1
],
[
8.842508384671427e1,
2.323046206504067e1
],
[
5.988836200057071e1,
4.2285701198332816e1
],
[
8.529261782849446e1,
6.0341251903571305e1
],
[
7.759666145388886e1,
5.651189453636175e1
],
[
3.852857395216495e1,
2.809760876985169e1
],
[
4.398951708877169e1,
3.216894887249086e1
],
[
9.16366203578599e1,
6.714360218617327e1
],
[
9.898195549416278e1,
7.262452564290038e1
]
]
},
"ChessboardDistance":{
"radius":20,
"nns":[
[
7.902245284318181e1,
3.668742522886822e1
],
[
8.16605203382718e1,
3.956258711057714e1
],
[
8.004869489978239e1,
4.168363673786661e1
],
[
8.449767558749892e1,
4.22881897246086e1
],
[
7.907645819462923e1,
4.326172287521658e1
],
[
7.151834272500287e1,
3.1457906261872267e1
],
[
7.118842838611701e1,
3.223707918219705e1
],
[
7.088382519184583e1,
3.37847574028188e1
],
[
8.00869355464923e1,
4.4923621763805414e1
],
[
8.817224584409368e1,
2.7916180139330677e1
],
[
8.725425532647796e1,
2.7205727708171423e1
],
[
6.947536019931414e1,
4.609491102607103e1
],
[
8.91865984788403e1,
4.411121794388606e1
],
[
6.875581792654663e1,
4.0801783131172016e1
],
[
6.794272657231718e1,
3.275950757695375e1
],
[
9.030339134278128e1,
2.935593659470453e1
],
[
6.76264453686839e1,
4.487664896489838e1
],
[
9.076718473479914e1,
3.530741963086231e1
],
[
6.718480664854735e1,
2.7178755631040502e1
],
[
8.088715035668972e1,
4.943848260450039e1
],
[
8.673385049456209e1,
2.3624130565951248e1
],
[
8.674040433293376e1,
2.361844967186157e1
],
[
7.813686079347377e1,
2.345471528033339e1
],
[
8.842508384671427e1,
2.323046206504067e1
],
[
9.296838030401483e1,
4.8941952864024955e1
],
[
9.384723233705449e1,
4.005191107447058e1
],
[
7.520150609198444e1,
5.159349370331293e1
],
[
9.156571373876713e1,
2.1002844357689725e1
],
[
7.692597883833844e1,
5.248697484005734e1
],
[
9.133200398634281e1,
5.354618472675497e1
],
[
7.323050378950745e1,
1.9484207322442913e1
],
[
6.1736064530517865e1,
3.711666355756594e1
],
[
9.56600926655853e1,
5.400299126004481e1
],
[
8.406494354721514e1,
5.433398520092288e1
],
[
9.712695380121767e1,
4.025303309812992e1
],
[
9.713395186623933e1,
1.9994935463821164e1
],
[
6.09070865500415e1,
3.985551550119823e1
],
[
6.927139981801787e1,
1.8558342821983757e1
],
[
8.283837186623481e1,
5.49584052875781e1
],
[
6.036347120371872e1,
5.158191789779184e1
],
[
9.246714887999303e1,
1.7915956149120944e1
],
[
6.0116009001625685e1,
2.6738909883702263e1
],
[
5.988836200057071e1,
4.2285701198332816e1
],
[
6.385591485841812e1,
5.584995740171797e1
],
[
9.873456722928461e1,
3.1908969981188136e1
],
[
7.759666145388886e1,
5.651189453636175e1
],
[
9.892546956195221e1,
4.05287582253728e1
]
]
}
}
|
### ----------------------------------------------------
### -- Algorithm::KDimensionalTree
### -- Licenses: Artistic-2.0
### -- Authors: Anton Antonov
### -- File: t/02-gist.rakutest
### ----------------------------------------------------
#!/usr/bin/env raku
use v6.d;
use lib <. lib>;
use Algorithm::KDimensionalTree;
use Test;
plan *;
## 1
ok Algorithm::KDimensionalTree.gist;
## 2
is Algorithm::KDimensionalTree.gist, '(KDimensionalTree)';
## 3
my @points = (2.rand xx 30).Array;
my $obj = Algorithm::KDimensionalTree.new(:@points, distance-function => Whatever);
is $obj.gist, 'Algorithm::KDimensionalTree(points => 30, distance-function => &euclidean-distance)';
done-testing;
|
### ----------------------------------------------------
### -- Algorithm::KDimensionalTree
### -- Licenses: Artistic-2.0
### -- Authors: Anton Antonov
### -- File: t/01-basic-usage.rakutest
### ----------------------------------------------------
use v6.d;
use Test;
use lib <. lib>;
use Algorithm::KDimensionalTree;
plan *;
my @points = ([(^100).rand, (^100).rand] xx 100).unique;
## 1
my $kdTree1;
$kdTree1 = Algorithm::KDimensionalTree.new(@points);
isa-ok $kdTree1, Algorithm::KDimensionalTree:D;
## 2
isa-ok Algorithm::KDimensionalTree.new(points => (3.rand xx 30), distance-function => 'euclidean-distance'), Algorithm::KDimensionalTree:D;
## 3
my @searchPoint1 = |@points.head;
is-deeply $kdTree1.k-nearest(@searchPoint1, 1, :!values).map(*<point>.value).Array, [@searchPoint1,];
## 4
is-deeply
$kdTree1.k-nearest(@searchPoint1, 3, :!values).map(*<point>.value).Array,
$kdTree1.k-nearest(@searchPoint1, 3, :values).Array,
"Values adverb";
## 5
is-deeply
$kdTree1.k-nearest(@searchPoint1, 5),
$kdTree1.nearest-within-ball(@searchPoint1, 60, :!values).sort(*<distance>).map(*<point>.value)[^5],
"Equivalence for k-nearest and within ball";
## 6
# Make verification test with direct scanning of @points.
my @nns6 = @points.sort({ sqrt [+] ($_.Array Z- @searchPoint1).map(* ** 2) });
is-deeply $kdTree1.k-nearest(@searchPoint1, 12), @nns6[^12];
## 7
my $kdTree7 = Algorithm::KDimensionalTree.new(points => (3.rand xx 30), distance-function => 'euclidean-distance');
isa-ok $kdTree7.k-nearest(2, 2), Iterable;
## 8
isa-ok $kdTree7.nearest-within-ball(2, 1), Iterable;
done-testing;
|
### ----------------------------------------------------
### -- Algorithm::KDimensionalTree
### -- Licenses: Artistic-2.0
### -- Authors: Anton Antonov
### -- File: xt/10-Same-NNs-for-words-hamming.rakutest
### ----------------------------------------------------
use v6.d;
use Test;
use lib <. lib>;
use Algorithm::KDimensionalTree;
my $k = 4;
my @words = (('a'..'k').pick($k).join xx 30).unique;
say @words;
my $distance-function = 'hamming-distance';
my $nKDTree = Algorithm::KDimensionalTree.new(@words, :$distance-function);
## 1
# Sometimes passes, sometimes fails.
my $word1 = @words.head;
my @scanRes1 = @words.sort({ $k - ($_.comb >>eq<< $word1.comb).sum }).head(3);
say (:$word1);
say (:@scanRes1);
is $nKDTree.k-nearest($word1, 3), @scanRes1;
done-testing;
|
### ----------------------------------------------------
### -- Algorithm::KDimensionalTree
### -- Licenses: Artistic-2.0
### -- Authors: Anton Antonov
### -- File: lib/Algorithm/NodalKDTree.rakumod
### ----------------------------------------------------
use v6.d;
# Taken from Rosetta Code: https://rosettacode.org/wiki/K-d_tree#Raku
unit module Algorithm::NodalKDTree;
class KD-Node is export {
has $.d;
has $.split;
has $.left;
has $.right;
}
class Orthotope is export {
has $.min;
has $.max;
}
class NodalKDTree is export {
has $.n;
has $.bounds;
method new($pts, $bounds) { self.bless(n => nk2(0,$pts), bounds => $bounds) }
sub nk2($split, @e) {
return () unless @e;
my @exset = @e.sort(*.[$split]);
my $m = +@exset div 2;
my @d = @exset[$m][];
while $m+1 < @exset and @exset[$m+1][$split] eqv @d[$split] {
++$m;
}
my $s2 = ($split + 1) % @d; # cycle coordinates
KD-Node.new: :@d, :$split,
left => nk2($s2, @exset[0 ..^ $m]),
right => nk2($s2, @exset[$m ^.. *]);
}
}
class T3 {
has $.nearest;
has $.dist_sqd = Inf;
has $.nodes_visited = 0;
}
sub find-nearest($k, $t, @p, :$max-distance = Inf) is export {
return nn($t.n, @p, $t.bounds, $max-distance);
sub nn($kd, @target, $hr, $max_dist_sqd is copy) {
return T3.new(:nearest([0.0 xx $k])) unless $kd;
my $nodes_visited = 1;
my $s = $kd.split;
my $pivot = $kd.d;
my $left_hr = $hr.clone;
my $right_hr = $hr.clone;
$left_hr.max[$s] = $pivot[$s];
$right_hr.min[$s] = $pivot[$s];
my $nearer_kd;
my $further_kd;
my $nearer_hr;
my $further_hr;
if @target[$s] <= $pivot[$s] {
($nearer_kd, $nearer_hr) = $kd.left, $left_hr;
($further_kd, $further_hr) = $kd.right, $right_hr;
}
else {
($nearer_kd, $nearer_hr) = $kd.right, $right_hr;
($further_kd, $further_hr) = $kd.left, $left_hr;
}
my $n1 = nn($nearer_kd, @target, $nearer_hr, $max_dist_sqd);
my $nearest = $n1.nearest;
my $dist_sqd = $n1.dist_sqd;
$nodes_visited += $n1.nodes_visited;
if $dist_sqd < $max_dist_sqd {
$max_dist_sqd = $dist_sqd;
}
my $d = ($pivot[$s] - @target[$s]) ** 2;
if $d > $max_dist_sqd {
return T3.new(:$nearest, :$dist_sqd, :$nodes_visited);
}
$d = [+] (@$pivot Z- @target) X** 2;
if $d < $dist_sqd {
$nearest = $pivot;
$dist_sqd = $d;
$max_dist_sqd = $dist_sqd;
}
my $n2 = nn($further_kd, @target, $further_hr, $max_dist_sqd);
$nodes_visited += $n2.nodes_visited;
if $n2.dist_sqd < $dist_sqd {
$nearest = $n2.nearest;
$dist_sqd = $n2.dist_sqd;
}
T3.new(:$nearest, :$dist_sqd, :$nodes_visited);
}
}
|
### ----------------------------------------------------
### -- Algorithm::KDimensionalTree
### -- Licenses: Artistic-2.0
### -- Authors: Anton Antonov
### -- File: lib/Algorithm/KDimensionalTree.rakumod
### ----------------------------------------------------
use v6.d;
use Math::DistanceFunctions;
use Math::DistanceFunctionish;
class Algorithm::KDimensionalTree
does Math::DistanceFunctionish {
has @.points;
has %.tree;
has $.distance-function;
has $!distance-function-orig;
has @.labels;
#======================================================
# Creators
#======================================================
submethod BUILD(:@points, :$distance-function = Whatever) {
@!points = @points;
given $distance-function {
when $_.isa(Whatever) || $_.isa(WhateverCode) {
$!distance-function = &euclidean-distance;
}
when $_ ~~ Str:D {
$!distance-function = self.get-distance-function($_, :!warn);
if $!distance-function.isa(WhateverCode) {
die "Unknown name of a distance function ⎡$distance-function⎦.";
}
}
when $_ ~~ Callable {
$!distance-function = $distance-function;
}
default {
die "Do not know how to process the distance function spec.";
}
}
# Process points
# If an array of arrays make it an array of pairs
if @!points.all ~~ Iterable:D {
@!points = @!points.pairs;
} elsif @!points.all ~~ Pair:D {
@!labels = @!points>>.key;
@!points = @!points>>.value.pairs;
} elsif @!points.all ~~ Str:D {
@!points = @!points.map({[$_, ]}).pairs;
# Assuming we are given a string distance function
$!distance-function-orig = $!distance-function;
$!distance-function = -> @a, @b { $!distance-function-orig(@a.head, @b.head) };
# This "brilliant" idea has to be proven.
# It does not seem to work for Hamming Distance and Levenshtein Distance.
# For Hamming Distance it might be beneficial to use numeric representation of the letters.
# Which means that under the hood some mapping and re-mapping has to happen.
} elsif @!points.all !~~ Iterable:D {
@!points = @!points.map({[$_, ]}).pairs;
} else {
die "The points argument is expected to be an array of numbers, an array of arrays, or an array of pairs.";
}
self.build-tree();
}
multi method new(:@points, :$distance-function = Whatever) {
self.bless(:@points, :$distance-function);
}
multi method new(@points, :$distance-function = Whatever) {
self.bless(:@points, :$distance-function);
}
multi method new(@points, $distance-function = Whatever) {
self.bless(:@points, :$distance-function);
}
#======================================================
# Representation
#======================================================
multi method gist(::?CLASS:D:-->Str) {
my $lblPart = @!labels.elems > 0 ?? ", labels => {@!labels.elems}" !! '';
return "Algorithm::KDimensionalTree(points => {@!points.elems}, distance-function => {$!distance-function.gist}" ~ $lblPart ~ ')';
}
method Str(){
return self.gist();
}
#======================================================
# Insert
#======================================================
multi method insert(@point) {
my $new = Pair.new( @!points.elems, @point);
@!points.push($new);
self.build-tree();
}
multi method insert(Pair:D $new) {
@!points.push($new);
self.build-tree();
}
#======================================================
# Build the tree
#======================================================
method axis-vector(UInt :$dim, UInt :$axis, :$val) {
my @vec = 0 xx $dim;
@vec[$axis] = $val;
return @vec;
}
method build-tree() {
%!tree = self.build-tree-rec(@!points, 0);
}
method build-tree-rec(@points, $depth) {
return %() if @points.elems == 0;
my $axis = $depth % @points[0].value.elems;
@points = @points.sort({ $_.value[$axis] });
my $median = @points.elems div 2;
return {
point => @points[$median],
left => self.build-tree-rec(@points[^$median], $depth + 1),
right => self.build-tree-rec(@points[$median + 1 .. *], $depth + 1)
};
}
#======================================================
# K-nearest
#======================================================
# The check where * !~~ Iterable:D is most like redundant.
multi method k-nearest($point where * !~~ Iterable:D, UInt $k = 1, Bool :v(:$values) = True) {
# Should it be checked that @!points.head.elems == 1 ?
return self.k-nearest([$point,], $k, :$values);
}
multi method k-nearest(@point, UInt $k = 1, Bool :v(:$values) = True) {
my @res = self.k-nearest-rec(%!tree, @point, $k, 0);
return $values ?? @res.map(*<point>.value) !! @res;
}
method k-nearest-rec(%node, @point, $k, UInt $depth) {
return [] unless %node;
my $axis = $depth % @point.elems;
my (%next, %other);
given @point[$axis] cmp %node<point>.value[$axis] {
when Less {
%next = %node<left>; %other = %node<right>;
}
default {
%next = %node<right>; %other = %node<left>;
}
}
# Recursively search
my @best = self.k-nearest-rec(%next, @point, $k, $depth + 1);
@best.push( { point => %node<point>, distance => self.distance-function.(@point, %node<point>.value) } );
# Reorder best neighbors
@best = @best.sort({ $_<distance> });
@best = @best[^$k] if @best.elems > $k;
# Recursively search if viable candidates _might_ exist
#if @best.elems < $k || (abs(@point[$axis] - %node<point>[$axis]) ≤ @best.tail<distance>) {
my @av1 = self.axis-vector(dim => @point.elems, :$axis, val => @point[$axis]);
my @av2 = self.axis-vector(dim => @point.elems, :$axis, val => %node<point>.value[$axis]);
if @best.elems < $k || self.distance-function.(@av1, @av2) ≤ @best.tail<distance> {
@best.append: self.k-nearest-rec(%other, @point, $k, $depth + 1);
@best = @best.sort({ $_<distance> });
@best = @best[^$k] if @best.elems > $k;
}
# Result
return @best;
}
#======================================================
# Nearest within a radius
#======================================================
multi method nearest-within-ball($point where * !~~ Iterable:D, Numeric $r, Bool :v(:$values) = True) {
# Should it be checked that @!points.head.elems == 1 ?
return self.nearest-within-ball([$point, ], $r, :$values);
}
multi method nearest-within-ball(@point, Numeric $r, Bool :v(:$values) = True) {
my @res = self.nearest-within-ball-rec(%!tree, @point, $r, 0);
return $values ?? @res.map(*<point>.value) !! @res;
}
method nearest-within-ball-rec(%node, @point, $r, $depth) {
return [] unless %node;
my $axis = $depth % @point.elems;
my $dist = self.distance-function.(@point, %node<point>.value);
my %inside = $dist ≤ $r ?? { point => %node<point>, distance => $dist } !! Empty;
my (%next, %other);
given @point[$axis] cmp %node<point>.value[$axis] {
when Less {
%next = %node<left>; %other = %node<right>;
}
default {
%next = %node<right>; %other = %node<left>;
}
}
my @neighbors = self.nearest-within-ball-rec(%next, @point, $r, $depth + 1);
@neighbors.push(%inside) if %inside;
#if (abs(@point[$axis] - %node<point>[$axis]) ≤ $r) {
my @av1 = self.axis-vector(dim => @point.elems, :$axis, val => @point[$axis]);
my @av2 = self.axis-vector(dim => @point.elems, :$axis, val => %node<point>.value[$axis]);
if self.distance-function.(@av1, @av2) ≤ $r {
@neighbors.append( self.nearest-within-ball-rec(%other, @point, $r, $depth + 1) );
}
# Result
return @neighbors;
}
}
|
### ----------------------------------------------------
### -- Algorithm::Kruskal
### -- Licenses: Artistic-2.0
### -- Authors: titsuki
### -- File: META6.json
### ----------------------------------------------------
{
"auth": "zef:titsuki",
"authors": [
"titsuki"
],
"build-depends": [
],
"depends": [
"Algorithm::SetUnion",
"Algorithm::MinMaxHeap"
],
"description": "a Raku implementation of Kruskal's Algorithm for constructing a spanning subtree of minimum length",
"license": "Artistic-2.0",
"name": "Algorithm::Kruskal",
"perl": "6.c",
"provides": {
"Algorithm::Kruskal": "lib/Algorithm/Kruskal.pm6"
},
"resources": [
],
"source-url": "https://github.com/titsuki/raku-Algorithm-Kruskal.git",
"tags": [
],
"test-depends": [
],
"version": "0.0.1"
}
|
### ----------------------------------------------------
### -- Algorithm::Kruskal
### -- Licenses: Artistic-2.0
### -- Authors: titsuki
### -- File: LICENSE
### ----------------------------------------------------
The Artistic License 2.0
Copyright (c) 2000-2016, 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.
|
### ----------------------------------------------------
### -- Algorithm::Kruskal
### -- Licenses: Artistic-2.0
### -- Authors: titsuki
### -- File: README.md
### ----------------------------------------------------
[](https://github.com/titsuki/raku-Algorithm-Kruskal/actions)
NAME
====
Algorithm::Kruskal - a Raku implementation of Kruskal's Algorithm for constructing a spanning subtree of minimum length
SYNOPSIS
========
use Algorithm::Kruskal;
my $kruskal = Algorithm::Kruskal.new(vertex-size => 4);
$kruskal.add-edge(0, 1, 2);
$kruskal.add-edge(1, 2, 1);
$kruskal.add-edge(2, 3, 1);
$kruskal.add-edge(3, 0, 1);
$kruskal.add-edge(0, 2, 3);
$kruskal.add-edge(1, 3, 5);
my %forest = $kruskal.compute-minimal-spanning-tree();
%forest<weight>.say; # 3
%forest<edges>.say; # [[1 2] [2 3] [3 0]]
DESCRIPTION
===========
Algorithm::Kruskal is a Raku implementation of Kruskal's Algorithm for constructing a spanning subtree of minimum length
CONSTRUCTOR
-----------
my $kruskal = Algorithm::Kruskal.new(%options);
### OPTIONS
* `vertex-size => $vertex-size`
Sets vertex size. The vertices are numbered from `0` to `$vertex-size - 1`.
METHODS
-------
### add-edge(Int $from, Int $to, Real $weight)
$kruskal.add-edge($from, $to, $weight);
Adds a edge to the graph. `$weight` is the weight between vertex `$from` and vertex `$to`.
### compute-minimal-spanning-tree() returns List
my %forest = $kruskal.compute-minimal-spanning-tree();
%forest<edges>.say; # display edges
%forest<weight>.say; # display weight
Computes and returns a minimal spanning tree and its weight.
AUTHOR
======
titsuki <[email protected]>
COPYRIGHT AND LICENSE
=====================
Copyright 2016 titsuki
This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
This algorithm is from Kruskal, Joseph B. "On the shortest spanning subtree of a graph and the traveling salesman problem." Proceedings of the American Mathematical society 7.1 (1956): 48-50.
|
### ----------------------------------------------------
### -- Algorithm::Kruskal
### -- Licenses: Artistic-2.0
### -- Authors: titsuki
### -- File: dist.ini
### ----------------------------------------------------
name = Algorithm::Kruskal
[ReadmeFromPod]
filename = lib/Algorithm/Kruskal.pm6
[UploadToZef]
[Badges]
provider = github-actions/test.yml
|
### ----------------------------------------------------
### -- Algorithm::Kruskal
### -- Licenses: Artistic-2.0
### -- Authors: titsuki
### -- File: t/01-basic.t
### ----------------------------------------------------
use v6;
use Test;
use Algorithm::Kruskal;
our sub do-it($input-path) {
my $fh = open $input-path, :r;
my $header = $fh.get;
my @header-elems = $header.words;
my ($vertex-size, $num-of-edges) = @header-elems[0,1]>>.Int;
my $weight = @header-elems[2].Num;
my $kruskal = Algorithm::Kruskal.new(vertex-size => $vertex-size);
for $fh.lines -> $line {
my @line-elems = $line.words;
my ($from, $to) = @line-elems[0,1]>>.Int;
my $weight = @line-elems[2].Num;
$kruskal.add-edge($from, $to, $weight);
}
my %forest = $kruskal.compute-minimal-spanning-tree();
is %forest<weight>, $weight;
}
{
do-it("./t/in/01.txt");
}
{
do-it("./t/in/02.txt");
}
{
do-it("./t/in/03.txt");
}
{
do-it("./t/in/04.txt");
}
done-testing;
|
### ----------------------------------------------------
### -- Algorithm::Kruskal
### -- Licenses: Artistic-2.0
### -- Authors: titsuki
### -- File: t/in/01.txt
### ----------------------------------------------------
4 6 3
0 1 2
1 2 1
2 3 1
3 0 1
0 2 3
1 3 5
|
### ----------------------------------------------------
### -- Algorithm::Kruskal
### -- Licenses: Artistic-2.0
### -- Authors: titsuki
### -- File: t/in/02.txt
### ----------------------------------------------------
6 9 5
0 1 1
0 2 3
1 2 1
1 3 7
2 4 1
1 4 3
3 4 1
3 5 1
4 5 6
|
### ----------------------------------------------------
### -- Algorithm::Kruskal
### -- Licenses: Artistic-2.0
### -- Authors: titsuki
### -- File: t/in/03.txt
### ----------------------------------------------------
1 0 0
|
### ----------------------------------------------------
### -- Algorithm::Kruskal
### -- Licenses: Artistic-2.0
### -- Authors: titsuki
### -- File: t/in/04.txt
### ----------------------------------------------------
6 5 15
0 1 1
1 2 2
2 3 3
3 4 4
4 5 5
|
### ----------------------------------------------------
### -- Algorithm::LBFGS
### -- Licenses: MIT
### -- Authors: Itsuki Toyota
### -- File: META6.json
### ----------------------------------------------------
{
"auth": "cpan:TITSUKI",
"authors": [
"Itsuki Toyota"
],
"build-depends": [
"LibraryMake",
"Distribution::Builder::MakeFromJSON",
"Algorithm::LBFGS::CustomBuilder"
],
"builder": "Algorithm::LBFGS::CustomBuilder",
"depends": [
"NativeHelpers::Array"
],
"description": "A Raku bindings for libLBFGS",
"license": "MIT",
"name": "Algorithm::LBFGS",
"perl": "6.c",
"provides": {
"Algorithm::LBFGS": "lib/Algorithm/LBFGS.pm6",
"Algorithm::LBFGS::CustomBuilder": "lib/Algorithm/LBFGS/CustomBuilder.pm6",
"Algorithm::LBFGS::Parameter": "lib/Algorithm/LBFGS/Parameter.pm6",
"Algorithm::LBFGS::Status": "lib/Algorithm/LBFGS/Status.pm6"
},
"resources": [
"libraries/lbfgs"
],
"source-url": "git://github.com/titsuki/raku-Algorithm-LBFGS.git",
"tags": [
],
"test-depends": [
],
"version": "0.0.6"
}
|
### ----------------------------------------------------
### -- Algorithm::LBFGS
### -- Licenses: MIT
### -- Authors: Itsuki Toyota
### -- File: LICENSE
### ----------------------------------------------------
The MIT License
Copyright (c) 1990 Jorge Nocedal
Copyright (c) 2007-2010 Naoaki Okazaki
Copyright (c) 2016 titsuki <[email protected]>
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.
|
### ----------------------------------------------------
### -- Algorithm::LBFGS
### -- Licenses: MIT
### -- Authors: Itsuki Toyota
### -- File: README.md
### ----------------------------------------------------
[](https://github.com/titsuki/raku-Algorithm-LBFGS/actions)
NAME
====
Algorithm::LBFGS - A Raku bindings for libLBFGS
SYNOPSIS
========
use Algorithm::LBFGS;
use Algorithm::LBFGS::Parameter;
my Algorithm::LBFGS $lbfgs .= new;
my &evaluate = sub ($instance, $x, $g, $n, $step --> Num) {
my Num $fx = ($x[0] - 2.0) ** 2 + ($x[1] - 5.0) ** 2;
$g[0] = 2.0 * $x[0] - 4.0;
$g[1] = 2.0 * $x[1] - 10.0;
return $fx;
};
my Algorithm::LBFGS::Parameter $parameter .= new;
my Num @x0 = [0e0, 0e0];
my @x = $lbfgs.minimize(:@x0, :&evaluate, :$parameter);
@x.say; # [2e0, 5e0]
DESCRIPTION
===========
Algorithm::LBFGS is a Raku bindings for libLBFGS. libLBFGS is a C port of the implementation of Limited-memory Broyden-Fletcher-Goldfarb-Shanno (L-BFGS) method written by Jorge Nocedal.
The L-BFGS method solves the unconstrainted minimization problem,
minimize F(x), x = (x1, x2, ..., xN),
only if the objective function F(x) and its gradient G(x) are computable.
CONSTRUCTOR
-----------
my $lbfgs = Algorithm::LBFGS.new;
my Algorithm::LBFGS $lbfgs .= new; # with type restrictions
METHODS
-------
### minimize(:@x0!, :&evaluate!, :&progress, Algorithm::LBFGS::Parameter :$parameter!) returns Array
my @x = $lbfgs.minimize(:@x0!, :&evaluate, :&progress, :$parameter); # use &progress callback
my @x = $lbfgs.minimize(:@x0!, :&evaluate, :$parameter);
Runs the optimization and returns the resulting variables.
`:@x0` is the initial value of the variables.
`:&evaluate` is the callback function. This requires the definition of the objective function F(x) and its gradient G(x).
`:&progress` is the callback function. This gets called on every iteration and can output the internal state of the current iteration.
`:$parameter` is the instance of the `Algorithm::LBFGS::Parameter` class.
#### :&evaluate
The one of the simplest `&evaluate` callback function would be like the following:
my &evaluate = sub ($instance, $x, $g, $n, $step --> Num) {
my Num $fx = ($x[0] - 2.0) ** 2 + ($x[1] - 5.0) ** 2; # F(x) = (x0 - 2.0)^2 + (x1 - 5.0)^2
# G(x) = [∂F(x)/∂x0, ∂F(x)/∂x1]
$g[0] = 2.0 * $x[0] - 4.0; # ∂F(x)/∂x0 = 2.0 * x0 - 4.0
$g[1] = 2.0 * $x[1] - 10.0; # ∂F(x)/∂x1 = 2.0 * x1 - 10.0
return $fx;
};
* `$instance` is the user data. (NOTE: NYI in this binder. You must set it as a first argument, but you can't use it in the callback.)
* `$x` is the current values of variables.
* `$g` is the current gradient values of variables.
* `$n` is the number of variables.
* `$step` is the line-search step used for this iteration.
`&evaluate` requires all of these five arguments in this order.
After writing the definition of the objective function F(x) and its gradient G(x), it requires returning the value of the F(x).
#### :&progress
The one of the simplest `&progress` callback function would be like the following:
my &progress = sub ($instance, $x, $g, $fx, $xnorm, $gnorm, $step, $n, $k, $ls --> Int) {
"Iteration $k".say;
"fx = $fx, x[0] = $x[0], x[1] = $x[1]".say;
return 0;
}
* `$instance` is the user data. (NOTE: NYI in this binder. You must set it as a first argument, but you can't use it in the callback.)
* `$x` is the current values of variables.
* `$g` is the current gradient values of variables.
* `$fx` is the current value of the objective function.
* `$xnorm` is the Euclidean norm of the variables.
* `$gnorm` is the Euclidean norm of the gradients.
* `$step` is the line-search step used for this iteration.
* `$n` is the number of variables.
* `$k` is the iteration count.
* `$ls` the number of evaluations called for this iteration.
`&progress` requires all of these ten arguments in this order.
#### Algorithm::LBFGS::Parameter :$parameter
Below is the examples of creating a <Algorithm::LBFGS::Parameter> instance:
my Algorithm::LBFGS::Parameter $parameter .= new; # sets default parameter
my Algorithm::LBFGS::Parameter $parameter .= new(max_iterations => 100); # sets max_iterations => 100
##### OPTIONS
* Int `m` is the number of corrections to approximate the inverse hessian matrix.
* Num `epsilon` is epsilon for convergence test.
* Int `past` is the distance for delta-based convergence test.
* Num `delta` is delta for convergence test.
* Int `max_iterations` is the maximum number of iterations.
* Int `linesearch` is the line search algorithm. This requires one of `LBFGS_LINESEARCH_DEFAULT`, `LBFGS_LINESEARCH_MORETHUENTE`, `LBFGS_LINESEARCH_BACKTRACKING_ARMIJO`, `LBFGS_LINESEARCH_BACKTRACKING`, `LBFGS_LINESEARCH_BACKTRACKING_WOLFE` and `LBFGS_LINESEARCH_BACKTRACKING_STRONG_WOLFE`. The default value is `LBFGS_LINESEARCH_MORETHUENTE`.
* Int `max_linesearch` is the maximum number of trials for the line search.
* Num `min_step` is the minimum step of the line search routine.
* Num `max_step` is the maximum step of the line search.
* Num `ftol` is a parameter to control the accuracy of the line search routine.
* Num `wolfe` is a coefficient for the Wolfe condition.
* Num `gtol` is a parameter to control the accuracy of the line search routine.
* Num `xtol` is the machine precision for floating-point values.
* Num `orthantwise_c` is a coeefficient for the L1 norm of variables.
* Int `orthantwise_start` is the start index for computing L1 norm of the variables.
* Int `orthantwise_end` is the end index for computing L1 norm of the variables.
STATUS CODES
------------
TBD
AUTHOR
======
titsuki <[email protected]>
COPYRIGHT AND LICENSE
=====================
Copyright 2016 titsuki
Copyright 1990 Jorge Nocedal
Copyright 2007-2010 Naoki Okazaki
libLBFGS by Naoki Okazaki is licensed under the MIT License.
This library is free software; you can redistribute it and/or modify it under the terms of the MIT License.
SEE ALSO
========
* libLBFGS [http://www.chokkan.org/software/liblbfgs/index.html](http://www.chokkan.org/software/liblbfgs/index.html)
|
### ----------------------------------------------------
### -- Algorithm::LBFGS
### -- Licenses: MIT
### -- Authors: Itsuki Toyota
### -- File: dist.ini
### ----------------------------------------------------
name = Algorithm-LBFGS
[ReadmeFromPod]
; disable = true
filename = lib/Algorithm/LBFGS.pm6
[PruneFiles]
; match = ^ 'xt/'
[Badges]
provider = github-actions/test
|
### ----------------------------------------------------
### -- Algorithm::LBFGS
### -- Licenses: MIT
### -- Authors: Itsuki Toyota
### -- File: example/sample.p6
### ----------------------------------------------------
use v6;
use NativeCall;
use lib 'lib';
use Algorithm::LBFGS;
sub lbfgs_evaluate_t($instance, $x, $g, $n, $step) returns Num {
my Num $fx = 0e0;
loop (my $i = 0; $i < $n; $i += 2) {
my Num $t1 = 1.0e0 - $x[$i];
my Num $t2 = 10.0e0 * ($x[$i + 1] - $x[$i] ** 2);
$g[$i + 1] = 20.0e0 * $t2;
$g[$i] = -2.0 * ($x[$i] * $g[$i+1] + $t1);
$fx += $t1 ** 2 + $t2 ** 2;
}
return $fx;
}
sub lbfgs_progress_t($instance, $x, $g, $fx, $xnorm, $gnorm, $step, $n, $k, $ls) returns Int {
"Iteration $k".say;
"fx = $fx, x[0] = $x[0], x[1] = $x[1]".say;
return 0;
}
my Algorithm::LBFGS::Parameter $param .= new;
my Algorithm::LBFGS $lbfgs .= new;
my Num @x0;
loop (my $i = 0; $i < 100; $i += 2) {
@x0[$i] = -1.2e0;
@x0[$i + 1] = 1.0e0;
}
my @ret = $lbfgs.minimize(:@x0, :evaluate(&lbfgs_evaluate_t), :progress(&lbfgs_progress_t), :parameter($param));
@ret.say;
|
### ----------------------------------------------------
### -- Algorithm::LBFGS
### -- Licenses: MIT
### -- Authors: Itsuki Toyota
### -- File: t/01-basic.t
### ----------------------------------------------------
use v6;
use Test;
use Algorithm::LBFGS;
lives-ok { my Algorithm::LBFGS $lbfgs .= new; }, "Algorithm::LBFGS.new requires no arguments";
done-testing;
|
### ----------------------------------------------------
### -- Algorithm::LBFGS
### -- Licenses: MIT
### -- Authors: Itsuki Toyota
### -- File: t/03-minimize.t
### ----------------------------------------------------
use v6;
use Test;
use Algorithm::LBFGS;
use Algorithm::LBFGS::Parameter;
{
my Algorithm::LBFGS $lbfgs .= new;
my &evaluate = sub ($instance, $x, $g, $n, $step --> Num) {
my Num $fx = ($x[0] - 2.0) ** 2 + ($x[1] - 5.0) ** 2;
$g[0] = 2.0 * $x[0] - 4.0;
$g[1] = 2.0 * $x[1] - 10.0;
return $fx;
};
my &progress = sub ($instance, $x, $g, $fx, $xnorm, $gnorm, $step, $n, $k, $ls --> Int) {
return 0;
}
my Algorithm::LBFGS::Parameter $parameter .= new;
my Num @x0 = [0e0, 0e0];
my @x = $lbfgs.minimize(:@x0, :&evaluate, :$parameter);
is-approx @x[0], 2e0, "Given the default parameter and fx = (x1 - 2)^2 + (x2 - 5)^2, then it should return [2e0,5e0] (x[0])";
is-approx @x[1], 5e0, "Given the default parameter and fx = (x1 - 2)^2 + (x2 - 5)^2, then it should return [2e0,5e0] (x[1])";
}
done-testing;
|
### ----------------------------------------------------
### -- Algorithm::LBFGS
### -- Licenses: MIT
### -- Authors: Itsuki Toyota
### -- File: t/02-status.t
### ----------------------------------------------------
use v6;
use Test;
use Algorithm::LBFGS;
use Algorithm::LBFGS::Parameter;
{
my Algorithm::LBFGS $lbfgs .= new;
my &evaluate = sub ($instance, $x, $g, $n, $step --> Num) {
my Num $fx = ($x[0] - 2.0) ** 2 + ($x[1] - 5.0) ** 2;
$g[0] = 2.0 * $x[0] - 4.0;
$g[1] = 2.0 * $x[1] - 10.0;
return $fx;
};
my &progress = sub ($instance, $x, $g, $fx, $xnorm, $gnorm, $step, $n, $k, $ls --> Int) {
return 0;
}
my Algorithm::LBFGS::Parameter $parameter .= new;
my Num @x0 = [0e0, 0e0];
lives-ok {
my @x = $lbfgs.minimize(:@x0, :&evaluate, :$parameter);
}, "Given the default parameter and an optimizable objective function, then it should return the resulting variables";
}
{
my Algorithm::LBFGS $lbfgs .= new;
my &evaluate = sub ($instance, $x, $g, $n, $step --> Num) {
my Num $fx = ($x[0] - 2.0) ** 2 + ($x[1] - 5.0) ** 2;
$g[0] = 2.0 * $x[0] - 4.0;
$g[1] = 2.0 * $x[1] - 10.0;
return $fx;
};
my &progress = sub ($instance, $x, $g, $fx, $xnorm, $gnorm, $step, $n, $k, $ls --> Int) {
return 0;
}
my Algorithm::LBFGS::Parameter $parameter .= new(linesearch => LBFGS_LINESEARCH_MORETHUENTE);
my Num @x0 = [0e0, 0e0];
lives-ok {
my @x = $lbfgs.minimize(:@x0, :&evaluate, :$parameter);
}, "Given the default parameter and an optimizable objective function, when linesearch => LBFGS_LINESEARCH_MORETHUENTE, then it should return the resulting variables";
}
{
my Algorithm::LBFGS $lbfgs .= new;
my &evaluate = sub ($instance, $x, $g, $n, $step --> Num) {
my Num $fx = ($x[0] - 2.0) ** 2 + ($x[1] - 5.0) ** 2;
$g[0] = 2.0 * $x[0] - 4.0;
$g[1] = 2.0 * $x[1] - 10.0;
return $fx;
};
my &progress = sub ($instance, $x, $g, $fx, $xnorm, $gnorm, $step, $n, $k, $ls --> Int) {
return 0;
}
my Algorithm::LBFGS::Parameter $parameter .= new(linesearch => LBFGS_LINESEARCH_BACKTRACKING_ARMIJO);
my Num @x0 = [0e0, 0e0];
lives-ok {
my @x = $lbfgs.minimize(:@x0, :&evaluate, :$parameter);
}, "Given the default parameter and an optimizable objective function, when linesearch => LBFGS_LINESEARCH_BACKTRACKING_ARMIJO, then it should return the resulting variables";
}
{
my Algorithm::LBFGS $lbfgs .= new;
my &evaluate = sub ($instance, $x, $g, $n, $step --> Num) {
my Num $fx = ($x[0] - 2.0) ** 2 + ($x[1] - 5.0) ** 2;
$g[0] = 2.0 * $x[0] - 4.0;
$g[1] = 2.0 * $x[1] - 10.0;
return $fx;
};
my &progress = sub ($instance, $x, $g, $fx, $xnorm, $gnorm, $step, $n, $k, $ls --> Int) {
return 0;
}
my Algorithm::LBFGS::Parameter $parameter .= new(linesearch => LBFGS_LINESEARCH_BACKTRACKING);
my Num @x0 = [0e0, 0e0];
lives-ok {
my @x = $lbfgs.minimize(:@x0, :&evaluate, :$parameter);
}, "Given the default parameter and an optimizable objective function, when linesearch => LBFGS_LINESEARCH_BACKTRACKING, then it should return the resulting variables";
}
{
my Algorithm::LBFGS $lbfgs .= new;
my &evaluate = sub ($instance, $x, $g, $n, $step --> Num) {
my Num $fx = ($x[0] - 2.0) ** 2 + ($x[1] - 5.0) ** 2;
$g[0] = 2.0 * $x[0] - 4.0;
$g[1] = 2.0 * $x[1] - 10.0;
return $fx;
};
my &progress = sub ($instance, $x, $g, $fx, $xnorm, $gnorm, $step, $n, $k, $ls --> Int) {
return 0;
}
my Algorithm::LBFGS::Parameter $parameter .= new(linesearch => LBFGS_LINESEARCH_BACKTRACKING_STRONG_WOLFE);
my Num @x0 = [0e0, 0e0];
lives-ok {
my @x = $lbfgs.minimize(:@x0, :&evaluate, :$parameter);
}, "Given the default parameter and an optimizable objective function, when linesearch => LBFGS_LINESEARCH_BACKTRACKING_STRONG_WOLFE, then it should return the resulting variables";
}
subtest {
my Algorithm::LBFGS $lbfgs .= new;
my &evaluate = sub ($instance, $x, $g, $n, $step --> Num) {
my Num $fx = ($x[0] - 2.0) ** 2 + ($x[1] - 5.0) ** 2;
$g[0] = 2.0 * $x[0] - 4.0;
$g[1] = 2.0 * $x[1] - 10.0;
return $fx;
};
my &progress = sub ($instance, $x, $g, $fx, $xnorm, $gnorm, $step, $n, $k, $ls --> Int) {
return 0;
}
my Algorithm::LBFGS::Parameter $parameter .= new(max_iterations => 1);
my Num @x0 = [0e0, 0e0];
throws-like { $lbfgs.minimize(:@x0, :&evaluate, :$parameter) }, Exception, message => 'ERROR: LBFGSERR_MAXIMUMITERATION';
}, "Given an optimizable objective function, when the number of max_iterations is insufficient, then it should return LBFGSERR_MAXIMUMITERATION";
# TODO: More tests
done-testing;
|
### ----------------------------------------------------
### -- Algorithm::LCS
### -- Licenses: MIT
### -- Authors: Rob Hoelz, Raku Community
### -- File: META6.json
### ----------------------------------------------------
{
"auth": "zef:raku-community-modules",
"authors": [
"Rob Hoelz",
"Raku Community"
],
"build-depends": [
],
"depends": [
],
"description": "Implementation of the longest common subsequence algorithm",
"license": "MIT",
"name": "Algorithm::LCS",
"perl": "6.*",
"provides": {
"Algorithm::LCS": "lib/Algorithm/LCS.rakumod"
},
"resources": [
],
"source-url": "https://github.com/raku-community-modules/Algorithm-LCS.git",
"tags": [
"ALGORITHM",
"LCS"
],
"test-depends": [
],
"version": "0.1.1"
}
|
### ----------------------------------------------------
### -- Algorithm::LCS
### -- Licenses: MIT
### -- Authors: Rob Hoelz, Raku Community
### -- File: LICENSE
### ----------------------------------------------------
Copyright (c) 2014 Rob Hoelz <rob at hoelz.ro>
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.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.