Skip to content

Instantly share code, notes, and snippets.

@zmughal
Last active January 2, 2016 03:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zmughal/8244764 to your computer and use it in GitHub Desktop.
Save zmughal/8244764 to your computer and use it in GitHub Desktop.
#!/usr/bin/env perl
use strict;
use warnings;
use PDL;
use PDL::NiceSlice;
use feature qw(say);
use Benchmark qw(timethese);
use Test::More;
my $eps = 1e-12;
my $in = (10 * random(200))->floor;
my $N = 20;
my $one = mv_avg_map($in, $N);
my $two = mv_avg_conv1d($in, $N);
my $all = all( abs($one - $two) < $eps );
say $in;
say $one;
say $two;
say $all;
ok( compare( mv_avg_map($in, 5), mv_avg_conv1d($in, 5) ), 'test N odd' );
ok( compare( mv_avg_map($in, 8), mv_avg_conv1d($in, 8) ), 'test N even' );
done_testing;
timethese(100_000, {
mv_avg_map => sub { mv_avg_map($in, $N) },
mv_avg_conv1d => sub { mv_avg_conv1d($in, $N) },
});
sub mv_avg_map {
my ($p, $N) = @_;
pdl [ map { $p($_ - $N : $_ - 1)->avg } $N .. $p->nelem ];
}
my $_filter_cache;
sub mv_avg_conv1d {
my ($p, $N) = @_;
unless( exists $_filter_cache->{$N} ) {
$_filter_cache->{$N} = ones($N) / $N;
}
my $mv_avg_filter = $_filter_cache->{$N};
my $mv = conv1d($p, $mv_avg_filter);
$mv( floor(($N - 1)/2):-1-ceil(($N -1)/2) );
}
sub compare {
return all( abs( $_[0] - $_[1] ) < $eps );
}
@zmughal
Copy link
Author

zmughal commented Jan 5, 2014

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment