Add == and != operators to Vector
[Math-GSL.git] / pod / Vector.pod
blob5a38e616c7319ddd0732c47abfdb2fc36fb9d5bf
1 %perlcode %{
2 use Scalar::Util 'blessed';
3 use Data::Dumper;
4 use Carp qw/croak/;
5 use Math::GSL::Errno qw/:all/;
6 use Math::GSL::BLAS qw/gsl_blas_ddot/;
7 use Math::GSL::Test     qw/is_similar/;
8 use overload
9     '*'      => \&_multiplication,
10     '+'      => \&_addition,
11     '-'      => \&_subtract,
12     'abs'    => \&_abs,
13     '=='     => \&_equal,
14     '!='     => \&_not_equal,
15     fallback => 1,
18 @EXPORT_all  = qw/fopen fclose
19                  gsl_vector_alloc gsl_vector_calloc gsl_vector_alloc_from_block gsl_vector_alloc_from_vector
20                  gsl_vector_free gsl_vector_view_array gsl_vector_const_view_array gsl_vector_view_array_with_stride
21                  gsl_vector_const_view_array_with_stride gsl_vector_subvector gsl_vector_subvector_wi gsl_vector_subvector_with_stride
22                  gsl_vector_const_subvec gsl_vector_const_subvec gsl_vector_get gsl_vector_set
23                  gsl_vector_ptr gsl_vector_const_ptr gsl_vector_set_zero gsl_vector_set_all
24                  gsl_vector_set_basis gsl_vector_fread gsl_vector_fwrite gsl_vector_fscanf
25                  gsl_vector_fprintf gsl_vector_memcpy gsl_vector_reverse gsl_vector_swap 
26                  gsl_vector_swap_elements gsl_vector_max gsl_vector_min gsl_vector_minmax 
27                  gsl_vector_max_index gsl_vector_min_index gsl_vector_minmax_index
28                  gsl_vector_add gsl_vector_sub gsl_vector_mul gsl_vector_div
29                  gsl_vector_scale gsl_vector_add_constant gsl_vector_isnull
30                  gsl_vector_ispos gsl_vector_isneg gsl_vector_isnonneg
31                  gsl_vector_float_alloc gsl_vector_float_calloc gsl_vector_float_alloc_from_block 
32                  gsl_vector_float_alloc_from_vector gsl_vector_float_free gsl_vector_float_view_array
33                  gsl_vector_float_view_array_with_stride gsl_vector_float_const_view_array gsl_vector_float_const_view_array_with_stride
34                  gsl_vector_float_subvector gsl_vector_float_subvector_with_stride gsl_vector_float_const_subvector
35                  gsl_vector_float_const_subvector_with_stride gsl_vector_float_get gsl_vector_float_set gsl_vector_float_ptr
36                  gsl_vector_float_const_ptr gsl_vector_float_set_zero gsl_vector_float_set_all gsl_vector_float_set_basis
37                  gsl_vector_float_fread gsl_vector_float_fwrite gsl_vector_float_fscanf gsl_vector_float_fprintf
38                  gsl_vector_float_memcpy gsl_vector_float_reverse gsl_vector_float_swap gsl_vector_float_swap_elements
39                  gsl_vector_float_max gsl_vector_float_min gsl_vector_float_minmax gsl_vector_float_max_index gsl_vector_float_min_index
40                  gsl_vector_float_minmax_index gsl_vector_float_add gsl_vector_float_sub gsl_vector_float_mul gsl_vector_float_div gsl_vector_float_scale
41                  gsl_vector_float_add_constant gsl_vector_float_isnull gsl_vector_float_ispos gsl_vector_float_isneg gsl_vector_float_isnonneg
44 @EXPORT_file =qw/ fopen fclose/;
45 @EXPORT_OK = (@EXPORT_all, @EXPORT_file);
46 %EXPORT_TAGS = ( file => \@EXPORT_file, all => \@EXPORT_all );
48 =head1 NAME
50 Math::GSL::Vector - Functions concerning vectors
52 =head1 SYNOPSIS
54     use Math::GSL::Vector qw/:all/;
55     my $vec1 = Math::GSL::Vector->new([1, 7, 94, 15 ]);
56     my $vec2 = $vec1 * 5; 
57     my $vec3 = Math::GSL::Vector>new(10);   # 10 element zero vector 
58     my $vec4 = $vec1 + $vec2;
60     # set the element at index 1 to 9
61     # and the element at index 3 to 8
62     $vec3->set([ 1, 3 ], [ 9, 8 ]);
64     my @vec = $vec2->as_list;               # return elements as Perl list
66     my $dot_product = $vec1 * $vec2;
67     my $length      = $vec2->length;
68     my $first       = $vec1->get(0);
71 =cut
73 =head1 Objected Oriented Interface to GSL Math::GSL::Vector
75 =head2 Math::GSL::Vector->new()
77 Creates a new Vector of the given size.
79     my $vector = Math::GSL::Vector->new(3);
81 You can also create and set directly the values of the vector like this :
83    my $vector = Math::GSL::Vector->new([2,4,1]);
85 =cut
87 sub new {
88     my ($class, $values) = @_;
89     my $length  = $#$values;
90     my $this = {}; 
91     my $vector;
92     if ( ref $values eq 'ARRAY' ){
93         die __PACKAGE__.'::new($x) - $x must be a nonempty array reference' if $length == -1;
94         $vector  = gsl_vector_alloc($length+1);
95         map { gsl_vector_set($vector, $_, $values->[$_] ) }  (0 .. $length);
96         $this->{_length} = $length+1;
97     } elsif ( (int($values) == $values) && ($values > 0)) {
98         $vector  = gsl_vector_alloc($values);
99         gsl_vector_set_zero($vector);
100         $this->{_length} = $values;
101     } else {
102         die __PACKAGE__.'::new($x) - $x must be an int or array reference';
103     }
104     $this->{_vector} = $vector; 
105     bless $this, $class;
107 =head2 raw()
109 Get the underlying GSL vector object created by SWIG, useful for using gsl_vector_* functions which do not have an OO counterpart.
111     my $vector    = Math::GSL::Vector->new(3);
112     my $gsl_vector = $vector->raw;
113     my $stuff      = gsl_vector_get($gsl_vector, 1);
115 =cut
117 sub raw {
118     my $self = shift;
119     return $self->{_vector};
122 =head2 swap()
124 Exchanges the values in the vectors $v with $w by copying.
126     my $v = Math::GSL::Vector->new([1..5]);
127     my $w = Math::GSL::Vector->new([3..7]);
128     $v->swap( $w );
130 =cut
132 sub swap() {
133     my ($self,$other) = @_;
134     croak "Math::GSL::Vector: \$v->swap(\$w) : \$w must be a Math::GSL::Vector"
135         unless ref $other eq 'Math::GSL::Vector';
136     gsl_vector_swap( $self->raw, $other->raw );
137     return $self;
140 =head2 reverse()
142 Reverse the elements in the vector.
144     $v->reverse;
146 =cut
148 sub reverse() {
149     my $self = shift;
150     gsl_vector_reverse($self->raw);
151     return $self;
154 =head2 min()
156 Returns the minimum value contained in the vector.
158    my $vector = Math::GSL::Vector->new([2,4,1]);
159    my $minimum = $vector->min;
161 =cut 
163 sub min {
164     my $self=shift;
165     return gsl_vector_min($self->raw);
168 =head2 max()
170 Returns the minimum value contained in the vector.
172    my $vector = Math::GSL::Vector->new([2,4,1]);
173    my $maximum = $vector->max;
175 =cut 
177 sub max {
178     my $self=shift;
179     return gsl_vector_max($self->raw);
182 =head2 length()
184 Returns the number of elements contained in the vector.
186    my $vector = Math::GSL::Vector->new([2,4,1]);
187    my $length = $vector->length;
189 =cut 
191 sub length { my $self=shift; $self->{_length} }
193 =head2 $v->norm($p)
195 Returns the p-norm of $v, which defaults to the Euclidean (p=2) norm when no argument is given.
197     my $euclidean_distance = $v->norm;
199 =cut
201 sub norm($;$)
203     my ($self,$p) = @_;
204     my $norm = 0;
205     $p ||= 2;
207     map { $norm += $p == 1 ? abs $_ : $_ ** $p } ($self->as_list);
208     return $norm **  (1 / $p);
211 =head2 normalize($p)
213 Divide each element of a vector by it's norm, hence creating a unit vector. Returns the vector for chaining.
214 If you just want the value of the norm without changing the vector, use C<norm()>. The default value for C<$p>
215 is 2, which gives the familiar Euclidean distance norm.
217     my $unit_vector = $vector->normalize(2);
219 is the same as
221     my $unit_vector = $vector->normalize;
223 =cut
225 sub normalize($;$)
227     my ($self,$p) = @_;
228     $p ||= 2;
229     my $norm = $self->norm($p);
230     return $self if ($norm == 0);
232     my $status = gsl_vector_scale( $self->raw, 1/$norm );
233     croak "Math::GSL::Vector - could not scale vectr" unless $status == $GSL_SUCCESS;
234     return $self;
237 =head2  as_list()
239 Gets the content of a Math::GSL::Vector object as a Perl list.
241     my $vector = Math::GSL::Vector->new(3);
242     ...
243     my @values = $vector->as_list;
245 =cut
247 sub as_list {
248     my $self=shift;
249     $self->get( [ 0 .. $self->length - 1  ] );
252 =head2  get()
254 Gets the value of an of a Math::GSL::Vector object.
256     my $vector = Math::GSL::Vector->new(3);
257     ...
258     my @values = $vector->get(2);
260 You can also enter an array of indices to receive their corresponding values:
262     my $vector = Math::GSL::Vector->new(3);
263     ...
264     my @values = $vector->get([0,2]);
266 =cut
268 sub get {
269     my ($self, $indices) = @_;
270     return  map {  gsl_vector_get($self->raw, $_ ) } @$indices ;
273 =head2  set() 
275 Sets values of an of a Math::GSL::Vector object.
277     my $vector = Math::GSL::Vector->new(3);
278     $vector->set([1,2], [8,23]);
280 This sets the second and third value to 8 and 23.
282 =cut
284 sub set {
285     my ($self, $indices, $values) = @_;
286     die (__PACKAGE__.'::set($indices, $values) - $indices and $values must be array references of the same length') 
287         unless ( ref $indices eq 'ARRAY' && ref $values eq 'ARRAY' &&  $#$indices == $#$values );
288     eval { 
289         map {  gsl_vector_set($self->{_vector}, $indices->[$_], $values->[$_] ) } (0..$#$indices);
290     }; 
291     return;
294 =head2 copy() 
296 Returns a copy of the vector, which has the same length and values but resides at a different location in memory.
298     my $vector = Math::GSL::Vector->new([10 .. 20]);
299     my $copy   = $vector->copy;
301 =cut
304 sub copy {
305     my $self = shift;
306     my $copy = Math::GSL::Vector->new( $self->length );
307     if ( gsl_vector_memcpy($copy->raw, $self->raw) != $GSL_SUCCESS ) {
308         croak "Math::GSL - error copying memory, aborting";
309     }
310     return $copy;
313 sub _multiplication {
314     my ($left,$right) = @_;
315     my $lcopy = $left->copy;
317     if ( blessed $right && $right->isa('Math::GSL::Vector') ) {
318         return $lcopy->dot_product($right);
319     } else {
320         gsl_vector_scale($lcopy->raw, $right);
321     }
322     return $lcopy;
325 sub _subtract {
326     my ($left, $right, $flip) = @_;
328     if ($flip) {
329         my $lcopy = $left->copy;
330         gsl_vector_scale($lcopy->raw, -1 );
331         gsl_vector_add_constant($lcopy->raw, $right);
332         return $lcopy;
333     } else { 
334         return _addition($left, -1.0*$right);
335     }
338 sub _abs {
339     my $self = shift;
340     $self->norm;
343 sub _addition {
344     my ($left, $right, $flip) = @_;
346     my $lcopy = $left->copy;
348     if ( blessed $right && $right->isa('Math::GSL::Vector') && blessed $left && $left->isa('Math::GSL::Vector') ) {
349         if ( $left->length == $right->length ) {
350             gsl_vector_add($lcopy->raw, $right->raw);
351         } else {
352             croak "Math::GSL - addition of vectors must be called with two objects vectors and must have the same length";
353         }
354     } else {
355         gsl_vector_add_constant($lcopy->raw, $right);
356     }
357     return $lcopy;
360 sub dot_product_pp {
361     my ($left,$right) = @_;
362     my $sum=0;
363     if ( blessed $right && $right->isa('Math::GSL::Vector') && 
364          $left->length == $right->length ) {
365          my @l = $left->as_list;
366          my @r = $right->as_list;
367          map { $sum += $l[$_] * $r[$_] } (0..$#l);
368         return $sum;
369     } else {
370         croak "dot_product() must be called with two vectors";
371     }
374 sub dot_product {
375     my ($left,$right) = @_;
376     
377     my ($status, $product) = gsl_blas_ddot($left->raw,$right->raw);
378     croak sprintf "Math::GSL::dot_product - %s", gsl_strerror($status) if ($status != $GSL_SUCCESS);  
379     return $product;
382 sub _equal {
383     my ($left,$right) = @_;
384     if ($left->length != $right->length)
385     {   
386         return 0;
387     }
388     return is_similar(  [$left->as_list ],
389                         [$right->as_list ]);
392 sub _not_equal {
393     my ($left, $right) = @_;
394     return !_equal($left,$right);
397 =head1 DESCRIPTION
399 Here is a list of all the functions included in this module :
401 =over 1
403 =item C<gsl_vector_alloc($x)> - create a vector of size $x
405 =item C<gsl_vector_calloc($x)> - create a vector of size $x and initializes all the elements of the vector to zero
407 =item C<gsl_vector_alloc_from_block> 
409 =item C<gsl_vector_alloc_from_vector> 
411 =item C<gsl_vector_free($v)> - free a previously allocated vector $v
413 =item C<gsl_vector_view_array($base, $n)> - This function returns a vector view of an array reference $base. The start of the new vector is given by $base and has $n elements. Mathematically, the i-th element of the new vector v' is given by, v'(i) = $base->[i] where the index i runs from 0 to $n-1. The array containing the elements of v is not owned by the new vector view. When the view goes out of scope the original array will continue to exist. The original memory can only be deallocated by freeing the original pointer base. Of course, the original array should not be deallocated while the view is still in use.  
415 =item C<gsl_vector_const_view_array($base, $n)> - This function is equivalent to gsl_vector_view_array but can be used for arrays which are declared const. 
417 =item C<gsl_vector_view_array_with_stride($base, $stride, $n)> - This function returns a vector view of an array reference $base with an additional $stride argument. The subvector is formed in the same way as for gsl_vector_view_array but the new vector has $n elements with a step-size of $stride from one element to the next in the original array. Mathematically, the i-th element of the new vector v' is given by, v'(i) = $base->[i*$stride] where the index i runs from 0 to $n-1. Note that the view gives direct access to the underlying elements of the original array. A vector view $view can be passed to any subroutine which takes a vector argument just as a directly allocated vector would be, using $view->{vector}. 
419 =item C<gsl_vector_const_view_array_with_stride($base, $stride, $n)> - This function is equivalent to gsl_vector_view_array_with_stride but can be used for arrays which are declared const.
421 =item C<gsl_vector_subvector($v, $offset, $n)> - return a vector_view type which contains a subvector of $v, with a size of $size, starting from the $offset position
423 =item C<gsl_vector_subvector_with_stride($v, $offset, $stride, $size)> - return a vector_view type which contains a subvector of $v, with a size of $size, starting from the $offset position and with a $stride step between each element of $v
425 =item C<gsl_vector_const_subvector> 
427 =item C<gsl_vector_get($v, $i)> - return the $i-th element of a vector $v
429 =item C<gsl_vector_set($v, $i, $x)> - return the vector $v with his $i-th element set to $x
431 =item C<gsl_vector_ptr> 
433 =item C<gsl_vector_const_ptr> 
435 =item C<gsl_vector_set_zero($v)> - set all the elements of $v to 0
437 =item C<gsl_vector_set_all($v, $x)> - set all the elements of $v to $x
439 =item C<gsl_vector_set_basis($v, $i)> - set all the elements of $v to 0 except for the $i-th element which is set to 1 and return 0 if the operation succeded, 1 otherwise.
441 =item C<gsl_vector_fread($file, $v)> - This function reads into the vector $v from the open stream $file opened with gsl_fopen function from the Math::GSL module in binary format. The vector $v must be preallocated with the correct length since the function uses the size of $v to determine how many bytes to read. The return value is 0 for success and 1 if there was a problem reading from the file.
443 =item C<gsl_vector_fwrite($file, $v)> - This function writes the elements of the vector $v to the stream $file opened with gsl_fopen function from the Math::GSL module in binary format. The return value is 0 for success and 1 if there was a problem writing to the file. Since the data is written in the native binary format it may not be portable between different architectures. 
445 =item C<gsl_vector_fscanf($file, $v)> This function reads formatted data from the stream $file opened with gsl_fopen function from the Math::GSL module into the vector $v. The vector $v must be preallocated with the correct length since the function uses the size of $v to determine how many numbers to read. The function returns 0 for success and 1 if there was a problem reading from the file. 
447 =item C<gsl_vector_fprintf($file, $v, $format)> -This function writes the elements of the vector $v line-by-line to the stream $file opened with gsl_fopen function from the Math::GSL module using the format specifier $format, which should be one of the "%g", "%e" or "%f" formats for floating point numbers and "%d" for integers. The function returns 0 for success and 1 if there was a problem writing to the file.  
449 =item C<gsl_vector_memcpy($dest, $src)> - This function copies the elements of the vector $src into the vector $dest and return 0 if the opertaion succeded, 1 otherwise. The two vectors must have the same length.  
451 =item C<gsl_vector_reverse($v)> - reverse the order of the elements of the vector $v and return 0 if the opertaion succeded, 1 otherwise
453 =item C<gsl_vector_swap($v, $v2)> - swap the values of the vectors $v and $v2 and return 0 if the opertaion succeded, 1 otherwise 
455 =item C<gsl_vector_swap_elements($v, $i, $j)> - permute the elements at position $i and $j in the vector $v and return 0 if the operation succeded, 1 otherwise.
457 =item C<gsl_vector_max($v)> - return the maximum value in the vector $v
459 =item C<gsl_vector_min($v)> - return the minimum value in the vector $v
461 =item C<gsl_vector_minmax($v)> - return two values, the first is the minimum value in the vector $v and the second is the maximum value.
463 =item C<gsl_vector_max_index($v)> - return the position of the maximum value in the vector $v
465 =item C<gsl_vector_min_index($v)> - return the position of the minimum value in the vector $v
467 =item C<gsl_vector_minmax_index> -  return two values, the first is the position of the minimum value in the vector $v and the second is the position of the maximum value.
469 =item C<gsl_vector_add($v, $v2)> - add the elements of $v2 to the elements of $v, the two vectors must have the same lenght and return 0 if the operation succeded, 1 otherwise.
471 =item C<gsl_vector_sub($v, $v2)> - substract the elements of $v2 from the elements of $v, the two vectors must have the same lenght and return 0 if the operation succeded, 1 otherwise.
473 =item C<gsl_vector_mul($v, $v2)> - multiply the elements of $v by the elements of $v2, the two vectors must have the same lenght and return 0 if the operation succeded, 1 otherwise.
475 =item C<gsl_vector_div($v, $v2)> - divides the elements of $v by the elements of $v2, the two vectors must have the same lenght and return 0 if the operation succeded, 1 otherwise.
477 =item C<gsl_vector_scale($v, $x)> - multiplty the elements of the vector $v by a constant $x and return 0 if the operation succeded, 1 otherwise.
479 =item C<gsl_vector_add_constant($v, $x)> - add a constant $x to the elements of the vector $v and return 0 if the operation succeded, 1 otherwise.
481 =item C<gsl_vector_isnull($v)> - verify if all the elements of the vector $v are null, return 0 if it's the case, 1 otherwise.
483 =item C<gsl_vector_ispos($v)> - verify if all the elements of the vector $v are positive, return 0 if it's the case, 1 otherwise.
485 =item C<gsl_vector_isneg($v)> - verify if all the elements of the vector $v are negative, return 0 if it's the case, 1 otherwise.
487 =item C<gsl_vector_isnonneg($v)> - verify if all the elements the vector $v are not negative, return 0 if it's the case, 1 otherwise.
489 =back
491 Precision on the vector_view type : every modification you'll make on a vector_view will also modify the original vector. 
492 For example, the following code will zero the even elements of the vector $v of length $size, while leaving the odd elements untouched :
494 =over 1
496 =item C<$v_even= gsl_vector_subvector_with_stride ($v, 0, 2, $size/2);>
498 =item C<gsl_vector_set_zero ($v_even-E<gt>{vector});>
500 =back
502 For more informations on the functions, we refer you to the GSL offcial documentation: 
503 L<http://www.gnu.org/software/gsl/manual/html_node/>
505 Tip : search on google: site:http://www.gnu.org/software/gsl/manual/html_node/ name_of_the_function_you_want
507 =head1 EXAMPLES
509 Here is an example using both interfaces.
511  use Math::GSL::Vector qw/:all/;
513  print "We'll create this vector : [0,1,4,9,16] \n";
514  my $vector = Math::GSL::Vector->new([0,1,4,9,16]);
515  my ($min, $max) = gsl_vector_minmax_index($vector->raw);
517  print "We then check the index value of the maximum and minimum values of the vector. \n";
518  print "The index of the maximum should be 4 and we received $max \n";
519  print "The index of the minimum should be 0 and we received $min \n";
520  print "We'll then swap the first and the third elements of the vector \n";
522  gsl_vector_swap_elements($vector->raw, 0, 3);
523  my @got = $vector->as_list;
524  print "The vector should now be like this : [9,1,4,0,16] \n";
525  print "and we received : [ @got ]\n";
527 =head1 AUTHORS
529 Jonathan Leto <jonathan@leto.net> and Thierry Moisan <thierry.moisan@gmail.com>
531 =head1 COPYRIGHT AND LICENSE
533 Copyright (C) 2008-2009 Jonathan Leto and Thierry Moisan
535 This program is free software; you can redistribute it and/or modify it
536 under the same terms as Perl itself.
538 =cut