| 1 | =head1 NAME |
| 2 | |
| 3 | PDL::Filter::Linear - linear filtering for PDL |
| 4 | |
| 5 | =head1 SYNOPSIS |
| 6 | |
| 7 | $x = PDL::Filter::Linear->new( |
| 8 | {Weights => $v, |
| 9 | Point => 10}); |
| 10 | |
| 11 | $y = PDL::Filter::Gaussian->new(15,2); # 15 points, 2 std devn. |
| 12 | |
| 13 | ($pred,$corrslic) = $x->predict($dat); |
| 14 | |
| 15 | =head1 DESCRIPTION |
| 16 | |
| 17 | A wrapper for generic linear filters. |
| 18 | Just for convenience. This should in the future use DataPresenter. |
| 19 | |
| 20 | Also, this class should at some point learn to do FFT whenever it is |
| 21 | useful. |
| 22 | |
| 23 | =cut |
| 24 | |
| 25 | package PDL::Filter::Linear; |
| 26 | use strict; |
| 27 | use warnings; |
| 28 | use PDL; |
| 29 | use PDL::Basic; |
| 30 | use PDL::Slices; |
| 31 | use PDL::Primitive; |
| 32 | |
| 33 | sub new($$) { |
| 34 | my($type,$pars) = @_; |
| 35 | |
| 36 | my $this = bless {},$type; |
| 37 | barf("Must specify weights\n") unless defined $pars->{Weights}; |
| 38 | $this->{Weights} = delete $pars->{Weights}; |
| 39 | $this->{Point} = defined $pars->{Point} ? $pars->{Point} : 0; |
| 40 | $this; |
| 41 | } |
| 42 | |
| 43 | sub predict($$) { |
| 44 | my($this,$data) = @_; |
| 45 | my $ldata = $data->lags(0,1,$this->{Weights}->getdim(0)); |
| 46 | inner($ldata->transpose,$this->{Weights}, |
| 47 | (my $pred = PDL->null)); |
| 48 | return wantarray ? ($pred,$ldata->slice(":,($this->{Point})")) : |
| 49 | $pred ; |
| 50 | } |
| 51 | |
| 52 | package PDL::Filter::Gaussian; |
| 53 | use PDL; use PDL::Basic; use PDL::Slices; use PDL::Primitive; |
| 54 | use strict; |
| 55 | |
| 56 | @PDL::Filter::Gaussian::ISA = qw/PDL::Filter::Linear/; |
| 57 | |
| 58 | sub new($$) { |
| 59 | my($type,$npoints,$sigma) = @_; |
| 60 | my $cent = int($npoints/2); |
| 61 | my $x = PDL->zeroes(float, $npoints )->xvals - $cent; |
| 62 | my $y = exp(-($x**2)/(2*$sigma**2)); |
| 63 | # Normalize to unit total |
| 64 | $y /= sum($y); |
| 65 | return PDL::Filter::Linear::new($type,{Weights => $y, |
| 66 | Point => $cent}); |
| 67 | } |
| 68 | |
| 69 | # Savitzky-Golay (see Numerical Recipes) |
| 70 | package PDL::Filter::SavGol; |
| 71 | use PDL; use PDL::Basic; use PDL::Slices; use PDL::Primitive; |
| 72 | use strict; |
| 73 | |
| 74 | @PDL::Filter::Gaussian::ISA = qw/PDL::Filter::Linear/; |
| 75 | |
| 76 | # XXX Doesn't work |
| 77 | sub new($$) { |
| 78 | my($type,$deg,$nleft,$nright) = @_; |
| 79 | my $npoints = $nright + $nleft + 1; |
| 80 | my $x = PDL->zeroes(float, $npoints )->xvals - $nleft; |
| 81 | my $mat1 = PDL->zeroes(float, $npoints,$deg+1)->xvals; |
| 82 | for(0..$deg-1) { |
| 83 | (my $tmp = $mat1->slice(":,($_)")) .= ($x ** $_); |
| 84 | } |
| 85 | my $y; |
| 86 | # Normalize to unit total |
| 87 | return PDL::Filter::Linear::new($type,{Weights => $y, |
| 88 | Point => $nleft}); |
| 89 | } |
| 90 | |
| 91 | 1; |