| 1 | use strict; |
| 2 | use warnings; |
| 3 | use Test::More; |
| 4 | use PDL::Fit::Linfit; |
| 5 | use PDL::LiteF; |
| 6 | use Test::PDL; |
| 7 | |
| 8 | { |
| 9 | # Simple Test Case: |
| 10 | |
| 11 | # Generate data from a set of functions |
| 12 | my $xvalues = sequence(100); |
| 13 | my $data = 3*$xvalues + 2*cos($xvalues) + 3*sin($xvalues*2); |
| 14 | |
| 15 | # Fit functions are the linear, cos, and sin2x functions used in |
| 16 | # the data generation step above: |
| 17 | my $fitFuncs = cat $xvalues, cos($xvalues), sin($xvalues*2); |
| 18 | |
| 19 | # Perform the fit, Coefs should equal 3,2,3 |
| 20 | my ($yfit, $coeffs) = PDL::linfit1d($data, $fitFuncs); |
| 21 | |
| 22 | my @coefs = $coeffs->list; |
| 23 | |
| 24 | is_pdl $coeffs, pdl([3,2,3]); |
| 25 | } |
| 26 | |
| 27 | { |
| 28 | # More Complex Example |
| 29 | |
| 30 | |
| 31 | my $noPoints = 501; |
| 32 | |
| 33 | my @expectedCoefs = qw( 0.988375918186647 -0.000278823311771375 0.161669997297754 0.0626069008452451); |
| 34 | |
| 35 | my $noCoefs = 4; |
| 36 | my $i; |
| 37 | my ($deltaT,$Amp,$lin,$HOper,$AmpHO,$Amphalf,$Ampfull); |
| 38 | |
| 39 | my @PulsedB; |
| 40 | |
| 41 | my @Pulse; |
| 42 | my $psum = 0; |
| 43 | |
| 44 | my $pi = 3.1415926; |
| 45 | |
| 46 | my $Pwidth = 2000; |
| 47 | my $pave; |
| 48 | |
| 49 | $deltaT = 4; # 4 nS increments |
| 50 | $Amp = 2.8; # 2.8V amplitude of pulse |
| 51 | $lin = .2; |
| 52 | $HOper = 200; # HO period |
| 53 | $AmpHO=.1; |
| 54 | $Amphalf = .5; |
| 55 | $Ampfull = .2; |
| 56 | |
| 57 | # generate waveform: |
| 58 | for(my $i = 0; $i < $noPoints; $i++){ |
| 59 | $PulsedB[$i]= |
| 60 | -$lin*1e-3*$i*$deltaT + |
| 61 | $Amphalf*sin($pi/$Pwidth*$i*$deltaT) + |
| 62 | $Ampfull*sin(2*$pi/$Pwidth*$i*$deltaT) + |
| 63 | $AmpHO*sin(2*$pi/$HOper*$i*$deltaT); |
| 64 | |
| 65 | $Pulse[$i] = $Amp*exp($PulsedB[$i]/20*2.3025851); |
| 66 | $psum += $Pulse[$i]; # used to get DC value |
| 67 | |
| 68 | # printf(" %4d %g %g\n",$i,$PulsedB[$i],$Pulse[$i]); |
| 69 | |
| 70 | } |
| 71 | |
| 72 | $pave = $psum/$noPoints; |
| 73 | |
| 74 | # printf("DC Value = %g\n",$pave); |
| 75 | |
| 76 | # Make PDL from waveform: |
| 77 | my $data = PDL->new(\@Pulse); |
| 78 | my @functions; |
| 79 | |
| 80 | # setup matrix contains functions to fit |
| 81 | for ($i=0; $i<$noPoints; $i++) { |
| 82 | |
| 83 | $functions[0][$i] = $pave; |
| 84 | $functions[1][$i] = $i; |
| 85 | $functions[2][$i] = sin($pi*$i/($noPoints-1)); |
| 86 | $functions[3][$i] = sin(2*$pi*$i/($noPoints-1)); |
| 87 | |
| 88 | } |
| 89 | |
| 90 | my $fitFuncs = PDL->new(\@functions); |
| 91 | |
| 92 | my ($yfit, $coeffs) = linfit1d($data, $fitFuncs); |
| 93 | |
| 94 | my @coefs = $coeffs->list; |
| 95 | |
| 96 | is_pdl $coeffs, pdl( \@expectedCoefs ); |
| 97 | } |
| 98 | |
| 99 | done_testing; |