Update Copyright years
[Math-GSL.git] / pod / Vector.pod
blobbd34174d7d7db244c8c0f0eb95ff4a17e11a79ea
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 overload
8     '*'      => \&_multiplication,
9     '+'      => \&_addition,
10     '-'      => \&_subtract,
11     'abs'    => \&_abs,
12     fallback => 1,
15 @EXPORT_all  = qw/fopen fclose
16                  gsl_vector_alloc gsl_vector_calloc gsl_vector_alloc_from_block gsl_vector_alloc_from_vector
17                  gsl_vector_free gsl_vector_view_array gsl_vector_const_view_array gsl_vector_view_array_with_stride
18                  gsl_vector_const_view_array_with_stride gsl_vector_subvector gsl_vector_subvector_wi gsl_vector_subvector_with_stride
19                  gsl_vector_const_subvec gsl_vector_const_subvec gsl_vector_get gsl_vector_set
20                  gsl_vector_ptr gsl_vector_const_ptr gsl_vector_set_zero gsl_vector_set_all
21                  gsl_vector_set_basis gsl_vector_fread gsl_vector_fwrite gsl_vector_fscanf
22                  gsl_vector_fprintf gsl_vector_memcpy gsl_vector_reverse gsl_vector_swap 
23                  gsl_vector_swap_elements gsl_vector_max gsl_vector_min gsl_vector_minmax 
24                  gsl_vector_max_index gsl_vector_min_index gsl_vector_minmax_index
25                  gsl_vector_add gsl_vector_sub gsl_vector_mul gsl_vector_div
26                  gsl_vector_scale gsl_vector_add_constant gsl_vector_isnull
27                  gsl_vector_ispos gsl_vector_isneg gsl_vector_isnonneg
28                  gsl_vector_float_alloc gsl_vector_float_calloc gsl_vector_float_alloc_from_block 
29                  gsl_vector_float_alloc_from_vector gsl_vector_float_free gsl_vector_float_view_array
30                  gsl_vector_float_view_array_with_stride gsl_vector_float_const_view_array gsl_vector_float_const_view_array_with_stride
31                  gsl_vector_float_subvector gsl_vector_float_subvector_with_stride gsl_vector_float_const_subvector
32                  gsl_vector_float_const_subvector_with_stride gsl_vector_float_get gsl_vector_float_set gsl_vector_float_ptr
33                  gsl_vector_float_const_ptr gsl_vector_float_set_zero gsl_vector_float_set_all gsl_vector_float_set_basis
34                  gsl_vector_float_fread gsl_vector_float_fwrite gsl_vector_float_fscanf gsl_vector_float_fprintf
35                  gsl_vector_float_memcpy gsl_vector_float_reverse gsl_vector_float_swap gsl_vector_float_swap_elements
36                  gsl_vector_float_max gsl_vector_float_min gsl_vector_float_minmax gsl_vector_float_max_index gsl_vector_float_min_index
37                  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
38                  gsl_vector_float_add_constant gsl_vector_float_isnull gsl_vector_float_ispos gsl_vector_float_isneg gsl_vector_float_isnonneg
41 @EXPORT_file =qw/ fopen fclose/;
42 @EXPORT_OK = (@EXPORT_all, @EXPORT_file);
43 %EXPORT_TAGS = ( file => \@EXPORT_file, all => \@EXPORT_all );
45 =head1 NAME
47 Math::GSL::Vector - Functions concerning vectors
49 =head1 SYNOPSIS
51     use Math::GSL::Vector qw/:all/;
52     my $vec1 = Math::GSL::Vector->new([1, 7, 94, 15 ]);
53     my $vec2 = $vec1 * 5; 
54     my $vec3 = Math::GSL::Vector>new(10);   # 10 element zero vector 
55     my $vec4 = $vec1 + $vec2;
57     # set the element at index 1 to 9
58     # and the element at index 3 to 8
59     $vec3->set([ 1, 3 ], [ 9, 8 ]);
61     my @vec = $vec2->as_list;               # return elements as Perl list
63     my $dot_product = $vec1 * $vec2;
64     my $length      = $vec2->length;
65     my $first       = $vec1->get(0);
68 =cut
70 =head1 Objected Oriented Interface to GSL Math::GSL::Vector
72 =head2 Math::GSL::Vector->new()
74 Creates a new Vector of the given size.
76     my $vector = Math::GSL::Vector->new(3);
78 You can also create and set directly the values of the vector like this :
80    my $vector = Math::GSL::Vector->new([2,4,1]);
82 =cut
84 sub new {
85     my ($class, $values) = @_;
86     my $length  = $#$values;
87     my $this = {}; 
88     my $vector;
89     if ( ref $values eq 'ARRAY' ){
90         die __PACKAGE__.'::new($x) - $x must be a nonempty array reference' if $length == -1;
91         $vector  = gsl_vector_alloc($length+1);
92         map { gsl_vector_set($vector, $_, $values->[$_] ) }  (0 .. $length);
93         $this->{_length} = $length+1;
94     } elsif ( (int($values) == $values) && ($values > 0)) {
95         $vector  = gsl_vector_alloc($values);
96         gsl_vector_set_zero($vector);
97         $this->{_length} = $values;
98     } else {
99         die __PACKAGE__.'::new($x) - $x must be an int or array reference';
100     }
101     $this->{_vector} = $vector; 
102     bless $this, $class;
104 =head2 raw()
106 Get the underlying GSL vector object created by SWIG, useful for using gsl_vector_* functions which do not have an OO counterpart.
108     my $vector    = Math::GSL::Vector->new(3);
109     my $gsl_vector = $vector->raw;
110     my $stuff      = gsl_vector_get($gsl_vector, 1);
112 =cut
114 sub raw {
115     my $self = shift;
116     return $self->{_vector};
119 =head2 swap()
121 Exchanges the values in the vectors $v with $w by copying.
123     my $v = Math::GSL::Vector->new([1..5]);
124     my $w = Math::GSL::Vector->new([3..7]);
125     $v->swap( $w );
127 =cut
129 sub swap() {
130     my ($self,$other) = @_;
131     croak "Math::GSL::Vector: \$v->swap(\$w) : \$w must be a Math::GSL::Vector"
132         unless ref $other eq 'Math::GSL::Vector';
133     gsl_vector_swap( $self->raw, $other->raw );
134     return $self;
137 =head2 reverse()
139 Reverse the elements in the vector.
141     $v->reverse;
143 =cut
145 sub reverse() {
146     my $self = shift;
147     gsl_vector_reverse($self->raw);
148     return $self;
151 =head2 min()
153 Returns the minimum value contained in the vector.
155    my $vector = Math::GSL::Vector->new([2,4,1]);
156    my $minimum = $vector->min;
158 =cut 
160 sub min {
161     my $self=shift;
162     return gsl_vector_min($self->raw);
165 =head2 max()
167 Returns the minimum value contained in the vector.
169    my $vector = Math::GSL::Vector->new([2,4,1]);
170    my $maximum = $vector->max;
172 =cut 
174 sub max {
175     my $self=shift;
176     return gsl_vector_max($self->raw);
179 =head2 length()
181 Returns the number of elements contained in the vector.
183    my $vector = Math::GSL::Vector->new([2,4,1]);
184    my $length = $vector->length;
186 =cut 
188 sub length { my $self=shift; $self->{_length} }
190 =head2 $v->norm($p)
192 Returns the p-norm of $v, which defaults to the Euclidean (p=2) norm when no argument is given.
194     my $euclidean_distance = $v->norm;
196 =cut
198 sub norm($;$)
200     my ($self,$p) = @_;
201     my $norm = 0;
202     $p ||= 2;
204     map { $norm += $p == 1 ? abs $_ : $_ ** $p } ($self->as_list);
205     return $norm **  (1 / $p);
208 =head2 normalize($p)
210 Divide each element of a vector by it's norm, hence creating a unit vector. Returns the vector for chaining.
211 If you just want the value of the norm without changing the vector, use C<norm()>. The default value for C<$p>
212 is 2, which gives the familiar Euclidean distance norm.
214     my $unit_vector = $vector->normalize(2);
216 is the same as
218     my $unit_vector = $vector->normalize;
220 =cut
222 sub normalize($;$)
224     my ($self,$p) = @_;
225     $p ||= 2;
226     my $norm = $self->norm($p);
227     return $self if ($norm == 0);
229     my $status = gsl_vector_scale( $self->raw, 1/$norm );
230     croak "Math::GSL::Vector - could not scale vectr" unless $status == $GSL_SUCCESS;
231     return $self;
234 =head2  as_list()
236 Gets the content of a Math::GSL::Vector object as a Perl list.
238     my $vector = Math::GSL::Vector->new(3);
239     ...
240     my @values = $vector->as_list;
242 =cut
244 sub as_list {
245     my $self=shift;
246     $self->get( [ 0 .. $self->length - 1  ] );
249 =head2  get()
251 Gets the value of an of a Math::GSL::Vector object.
253     my $vector = Math::GSL::Vector->new(3);
254     ...
255     my @values = $vector->get(2);
257 You can also enter an array of indices to receive their corresponding values:
259     my $vector = Math::GSL::Vector->new(3);
260     ...
261     my @values = $vector->get([0,2]);
263 =cut
265 sub get {
266     my ($self, $indices) = @_;
267     return  map {  gsl_vector_get($self->raw, $_ ) } @$indices ;
270 =head2  set() 
272 Sets values of an of a Math::GSL::Vector object.
274     my $vector = Math::GSL::Vector->new(3);
275     $vector->set([1,2], [8,23]);
277 This sets the second and third value to 8 and 23.
279 =cut
281 sub set {
282     my ($self, $indices, $values) = @_;
283     die (__PACKAGE__.'::set($indices, $values) - $indices and $values must be array references of the same length') 
284         unless ( ref $indices eq 'ARRAY' && ref $values eq 'ARRAY' &&  $#$indices == $#$values );
285     eval { 
286         map {  gsl_vector_set($self->{_vector}, $indices->[$_], $values->[$_] ) } (0..$#$indices);
287     }; 
288     return;
291 =head2 copy() 
293 Returns a copy of the vector, which has the same length and values but resides at a different location in memory.
295     my $vector = Math::GSL::Vector->new([10 .. 20]);
296     my $copy   = $vector->copy;
298 =cut
301 sub copy {
302     my $self = shift;
303     my $copy = Math::GSL::Vector->new( $self->length );
304     if ( gsl_vector_memcpy($copy->raw, $self->raw) != $GSL_SUCCESS ) {
305         croak "Math::GSL - error copying memory, aborting";
306     }
307     return $copy;
310 sub _multiplication {
311     my ($left,$right) = @_;
312     my $lcopy = $left->copy;
314     if ( blessed $right && $right->isa('Math::GSL::Vector') ) {
315         return $lcopy->dot_product($right);
316     } else {
317         gsl_vector_scale($lcopy->raw, $right);
318     }
319     return $lcopy;
322 sub _subtract {
323     my ($left, $right, $flip) = @_;
325     if ($flip) {
326         my $lcopy = $left->copy;
327         gsl_vector_scale($lcopy->raw, -1 );
328         gsl_vector_add_constant($lcopy->raw, $right);
329         return $lcopy;
330     } else { 
331         return _addition($left, -1.0*$right);
332     }
335 sub _abs {
336     my $self = shift;
337     $self->norm;
340 sub _addition {
341     my ($left, $right, $flip) = @_;
343     my $lcopy = $left->copy;
345     if ( blessed $right && $right->isa('Math::GSL::Vector') && blessed $left && $left->isa('Math::GSL::Vector') ) {
346         if ( $left->length == $right->length ) {
347             gsl_vector_add($lcopy->raw, $right->raw);
348         } else {
349             croak "Math::GSL - addition of vectors must be called with two objects vectors and must have the same length";
350         }
351     } else {
352         gsl_vector_add_constant($lcopy->raw, $right);
353     }
354     return $lcopy;
357 sub dot_product_pp {
358     my ($left,$right) = @_;
359     my $sum=0;
360     if ( blessed $right && $right->isa('Math::GSL::Vector') && 
361          $left->length == $right->length ) {
362          my @l = $left->as_list;
363          my @r = $right->as_list;
364          map { $sum += $l[$_] * $r[$_] } (0..$#l);
365         return $sum;
366     } else {
367         croak "dot_product() must be called with two vectors";
368     }
371 sub dot_product {
372     my ($left,$right) = @_;
373     
374     my ($status, $product) = gsl_blas_ddot($left->raw,$right->raw);
375     croak sprintf "Math::GSL::dot_product - %s", gsl_strerror($status) if ($status != $GSL_SUCCESS);  
376     return $product;
379 =head1 DESCRIPTION
381 Here is a list of all the functions included in this module :
383 =over 1
385 =item C<gsl_vector_alloc($x)> - create a vector of size $x
387 =item C<gsl_vector_calloc($x)> - create a vector of size $x and initializes all the elements of the vector to zero
389 =item C<gsl_vector_alloc_from_block> 
391 =item C<gsl_vector_alloc_from_vector> 
393 =item C<gsl_vector_free($v)> - free a previously allocated vector $v
395 =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.  
397 =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. 
399 =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}. 
401 =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.
403 =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
405 =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
407 =item C<gsl_vector_const_subvector> 
409 =item C<gsl_vector_get($v, $i)> - return the $i-th element of a vector $v
411 =item C<gsl_vector_set($v, $i, $x)> - return the vector $v with his $i-th element set to $x
413 =item C<gsl_vector_ptr> 
415 =item C<gsl_vector_const_ptr> 
417 =item C<gsl_vector_set_zero($v)> - set all the elements of $v to 0
419 =item C<gsl_vector_set_all($v, $x)> - set all the elements of $v to $x
421 =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.
423 =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.
425 =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. 
427 =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. 
429 =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.  
431 =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.  
433 =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
435 =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 
437 =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.
439 =item C<gsl_vector_max($v)> - return the maximum value in the vector $v
441 =item C<gsl_vector_min($v)> - return the minimum value in the vector $v
443 =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.
445 =item C<gsl_vector_max_index($v)> - return the position of the maximum value in the vector $v
447 =item C<gsl_vector_min_index($v)> - return the position of the minimum value in the vector $v
449 =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.
451 =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.
453 =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.
455 =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.
457 =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.
459 =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.
461 =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.
463 =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.
465 =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.
467 =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.
469 =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.
471 =back
473 Precision on the vector_view type : every modification you'll make on a vector_view will also modify the original vector. 
474 For example, the following code will zero the even elements of the vector $v of length $size, while leaving the odd elements untouched :
476 =over 1
478 =item C<$v_even= gsl_vector_subvector_with_stride ($v, 0, 2, $size/2);>
480 =item C<gsl_vector_set_zero ($v_even-E<gt>{vector});>
482 =back
484 For more informations on the functions, we refer you to the GSL offcial documentation: 
485 L<http://www.gnu.org/software/gsl/manual/html_node/>
487 Tip : search on google: site:http://www.gnu.org/software/gsl/manual/html_node/ name_of_the_function_you_want
489 =head1 EXAMPLES
491 Here is an example using both interfaces.
493  use Math::GSL::Vector qw/:all/;
495  print "We'll create this vector : [0,1,4,9,16] \n";
496  my $vector = Math::GSL::Vector->new([0,1,4,9,16]);
497  my ($min, $max) = gsl_vector_minmax_index($vector->raw);
499  print "We then check the index value of the maximum and minimum values of the vector. \n";
500  print "The index of the maximum should be 4 and we received $max \n";
501  print "The index of the minimum should be 0 and we received $min \n";
502  print "We'll then swap the first and the third elements of the vector \n";
504  gsl_vector_swap_elements($vector->raw, 0, 3);
505  my @got = $vector->as_list;
506  print "The vector should now be like this : [9,1,4,0,16] \n";
507  print "and we received : [ @got ]\n";
509 =head1 AUTHORS
511 Jonathan Leto <jonathan@leto.net> and Thierry Moisan <thierry.moisan@gmail.com>
513 =head1 COPYRIGHT AND LICENSE
515 Copyright (C) 2008-2009 Jonathan Leto and Thierry Moisan
517 This program is free software; you can redistribute it and/or modify it
518 under the same terms as Perl itself.
520 =cut