Math-Vector-Real-0.10/0000755000175000017500000000000012001250614013431 5ustar salvasalvaMath-Vector-Real-0.10/examples/0000755000175000017500000000000012001250614015247 5ustar salvasalvaMath-Vector-Real-0.10/examples/dist_to_line.pl0000644000175000017500000000110111574113725020270 0ustar salvasalva#!/usr/bin/perl use strict; use warnings; # see http://perlmonks.org/?node_id=814899 # Given a line defined by two points $l0 and $l1 calculate the # distance to another point $p: use Math::Vector::Real; my $l0 = V(2, 3, 4); my $l1 = V(1, 0, 1); my $p = V(2, 2, 2); # calculate the vector $n perpendicular to the line that goes to $p: my $u = $l1 - $l0; # line direction my $n = $p - $l0; $n -= ($u * $n)/($u * $u) * $u; # the distance is the length of the vector: printf "The distance between the point %s and the line [%s - %s] is %g\n", $p, $l0, $l1, abs($n) Math-Vector-Real-0.10/Changes0000644000175000017500000000255312001250571014733 0ustar salvasalvaRevision history for Perl extension Math::Vector::Real. 0.10 Jul 17, 2012 - correct broken max_component_index method - add select_in_ball method - solve issue in *= operator, - use Math::Vector::Real::XS when available - add manhattan norm and dist methods, - doc correction (reported by Laszlo Kajan) 0.09 Jun 13, 2012 - add rotation_base_3d and rotate_3d operations 0.08 Nov 8, 2011 - add complementary_base and rewrite normal_base to use it - canonical_base was broken - don't use method syntax to call vector subroutines inside module - doc improvements 0.07 Nov 7, 2011 - normal_base was broken - several doc improvements - minor code cleanups 0.06 Jun 16, 2011 - import POSIX module - add new_ref constructor 0.04 Jun 14, 2011 - add cube constructor and min, max, dist, dist2 and abs2 methods - add canonical_base, normal_base, decompose - wrap method modified 0.03 Jun 9, 2011 - add methods axis_versor, versor, zero, is_zero and wrap - some doc corrections and improvements 0.02 Dec 31, 2009 - clean up Makefile.PL - remove 5.10 requirement - doc minor improvements - add example 0.01 Wed Dec 30 19:47:00 2009 - original version; created by h2xs 1.23 with options -AXn Math::Vector::Real Math-Vector-Real-0.10/META.yml0000664000175000017500000000100612001250614014701 0ustar salvasalva--- #YAML:1.0 name: Math-Vector-Real version: 0.10 abstract: ~ author: - Salvador Fandiño license: unknown distribution_type: module configure_requires: ExtUtils::MakeMaker: 0 build_requires: ExtUtils::MakeMaker: 0 requires: {} no_index: directory: - t - inc generated_by: ExtUtils::MakeMaker version 6.57_05 meta-spec: url: http://module-build.sourceforge.net/META-spec-v1.4.html version: 1.4 Math-Vector-Real-0.10/README0000644000175000017500000000111011766120546014323 0ustar salvasalvaMath-Vector-Real ================ Perform arithmetic over real vectors of any dimension INSTALLATION To install this module type the following: perl Makefile.PL make make test make install DEPENDENCIES This module requires these other modules and libraries: Test::More (for testing) COPYRIGHT AND LICENCE Copyright (C) 2009-2012 by Salvador Fandiño This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself, either Perl version 5.10.0 or, at your option, any later version of Perl 5 you may have available. Math-Vector-Real-0.10/Makefile.PL0000644000175000017500000000035711574113725015427 0ustar salvasalva use ExtUtils::MakeMaker; WriteMakefile( NAME => 'Math::Vector::Real', VERSION_FROM => 'lib/Math/Vector/Real.pm', PREREQ_PM => {}, # e.g., Module::Name => 1.1 AUTHOR => 'Salvador Fandiño ' ); Math-Vector-Real-0.10/MANIFEST0000644000175000017500000000030212001250614014555 0ustar salvasalvaChanges Makefile.PL MANIFEST README t/Math-Vector-Real.t t/pods.t lib/Math/Vector/Real.pm examples/dist_to_line.pl META.yml Module meta-data (added by MakeMaker) Math-Vector-Real-0.10/lib/0000755000175000017500000000000012001250614014177 5ustar salvasalvaMath-Vector-Real-0.10/lib/Math/0000755000175000017500000000000012001250614015070 5ustar salvasalvaMath-Vector-Real-0.10/lib/Math/Vector/0000755000175000017500000000000012001250614016332 5ustar salvasalvaMath-Vector-Real-0.10/lib/Math/Vector/Real.pm0000644000175000017500000004107411775041125017575 0ustar salvasalvapackage Math::Vector::Real; our $VERSION = '0.10'; use strict; use warnings; use Carp; use POSIX (); use Exporter qw(import); our @EXPORT = qw(V); local ($@, $!, $SIG{__DIE__}); eval { require Math::Vector::Real::XS }; our %op = (add => '+', neg => 'neg', sub => '-', mul => '*', div => '/', cross => 'x', add_me => '+=', sub_me => '-=', mul_me => '*=', div_me => '/=', abs => 'abs', atan2 => 'atan2', equal => '==', nequal => '!=', clone => '=', as_string => '""'); our %ol; $ol{$op{$_}} = \&{${Math::Vector::Real::}{$_}} for keys %op; require overload; overload->import(%ol); sub V { bless [@_] } sub new { my $class = shift; bless [@_], $class } sub new_ref { my $class = shift; bless [@{shift()}], $class; } sub zero { my ($class, $dim) = @_; $dim >= 0 or croak "negative dimension"; bless [(0) x $dim], $class } sub is_zero { $_ and return 0 for @$_[0]; return 1 } sub cube { my ($class, $dim, $size) = @_; bless [($size) x $dim], $class; } sub axis_versor { my ($class, $dim, $ix); if (ref $_[0]) { my ($self, $ix) = @_; $class = ref $self; $dim = @$self; } else { ($class, $dim, $ix) = @_; $dim >= 0 or croak "negative dimension"; } ($ix >= 0 and $ix < $dim) or croak "axis index out of range"; my $self = [(0) x $dim]; $self->[$ix] = 1; bless $self, $class } sub _caller_op { my $level = (shift||1) + 1; my $sub = (caller $level)[3]; $sub =~ s/.*:://; my $op = $op{$sub}; (defined $op ? $op : $sub); } sub _check_dim { local ($@, $SIG{__DIE__}); eval { @{$_[0]} == @{$_[1]} } and return; my $op = _caller_op(1); my $loc = ($_[2] ? 'first' : 'second'); UNIVERSAL::isa($_[1], 'ARRAY') or croak "$loc argument to vector operator '$op' is not a vector"; croak "vector dimensions do not match"; } sub clone { bless [@{$_[0]}] } sub set { &_check_dim; my ($v0, $v1) = @_; $v0->[$_] = $v1->[$_] for 0..$#$v1; } sub add { &_check_dim; my ($v0, $v1) = @_; bless [map $v0->[$_] + $v1->[$_], 0..$#$v0] } sub add_me { &_check_dim; my ($v0, $v1) = @_; $v0->[$_] += $v1->[$_] for 0..$#$v0; $v0; } sub neg { bless [map -$_, @{$_[0]}] } sub sub { &_check_dim; my ($v0, $v1) = ($_[2] ? @_[1, 0] : @_); bless [map $v0->[$_] - $v1->[$_], 0..$#$v0] } sub sub_me { &_check_dim; my ($v0, $v1) = @_; $v0->[$_] -= $v1->[$_] for 0..$#$v0; $v0; } sub mul { if (ref $_[1]) { &_check_dim; my ($v0, $v1) = @_; my $acu = 0; $acu += $v0->[$_] * $v1->[$_] for 0..$#$v0; $acu; } else { my ($v, $s) = @_; bless [map $s * $_, @$v]; } } sub mul_me { ref $_[1] and croak "can not multiply by a vector in place as the result is not a vector"; my ($v, $s) = @_; $_ *= $s for @$v; $v } sub div { croak "can't use vector as dividend" if ($_[2] or ref $_[1]); my ($v, $div) = @_; $div == 0 and croak "illegal division by zero"; my $i = 1 / $div; bless [map $i * $_, @$v] } sub div_me { croak "can't use vector as dividend" if ref $_[1]; my $v = shift; my $i = 1 / shift; $_ *= $i for @$v; $v; } sub equal { &_check_dim; my ($v0, $v1) = @_; $v0->[$_] == $v1->[$_] || return 0 for 0..$#$v0; 1; } sub nequal { &_check_dim; my ($v0, $v1) = @_; $v0->[$_] == $v1->[$_] || return 1 for 0..$#$v0; 0; } sub cross { &_check_dim; my ($v0, $v1) = ($_[2] ? @_[1, 0] : @_); my $dim = @$v0; if ($dim == 3) { return bless [$v0->[1] * $v1->[2] - $v0->[2] * $v1->[1], $v0->[2] * $v1->[0] - $v0->[0] * $v1->[2], $v0->[0] * $v1->[1] - $v0->[1] * $v1->[0]] } if ($dim == 7) { croak "cross product for dimension 7 not implemented yet, patches welcome!"; } else { croak "cross product not defined for dimension $dim" } } sub as_string { "{" . join(", ", @{$_[0]}). "}" } sub abs { my $acu = 0; $acu += $_ * $_ for @{$_[0]}; sqrt $acu; } *norm = \&abs; sub abs2 { my $acu = 0; $acu += $_ * $_ for @{$_[0]}; $acu; } *norm2 = \&abs2; sub dist { &_check_dim; my ($v0, $v1) = @_; my $d2 = 0; for (0..$#$v0) { my $d = $v0->[$_] - $v1->[$_]; $d2 += $d * $d; } sqrt($d2); } sub dist2 { &_check_dim; my ($v0, $v1) = @_; my $d2 = 0; for (0..$#$v0) { my $d = $v0->[$_] - $v1->[$_]; $d2 += $d * $d; } $d2; } sub manhattan_norm { my $n = 0; $n += CORE::abs($_) for @{$_[0]}; return $n; } sub manhattan_dist { &_check_dim; my ($v0, $v1) = @_; my $d = 0; $d += CORE::abs($v0->[$_] - $v1->[$_]) for 0..$#$v0; return $d; } sub _upgrade { my $dim; map { my $d = eval { @{$_} }; defined $d or croak "argument is not a vector or array"; if (defined $dim) { $d == $dim or croak "dimensions do not match"; } else { $dim = $d; } UNIVERSAL::isa($_, __PACKAGE__) ? $_ : clone($_); } @_; } sub atan2 { my ($v0, $v1) = @_; my $a0 = &abs($v0); return 0 unless $a0; my $u0 = $v0 / $a0; my $p = $v1 * $u0; CORE::atan2(&abs($v1 - $p * $u0), $p); } sub versor { my $self = shift; my $f = 0; $f += $_ * $_ for @$self; $f == 0 and croak "Illegal division by zero"; $f = 1/sqrt $f; bless [map $f * $_, @$self] } sub wrap { my ($self, $v) = @_; &_check_dim; bless [map { my $s = $self->[$_]; my $c = $v->[$_]; $c - $s * POSIX::floor($c/$s) } (0..$#$self)]; } sub max_component { my $max = 0; for (@{shift()}) { my $abs = CORE::abs($_); $abs > $max and $max = $abs; } $max } sub min_component { my $self = shift; my $min = CORE::abs($self->[0]); for (@$self) { my $abs = CORE::abs($_); $abs < $min and $min = $abs; } $min } *max = \&max_component; *min = \&min_component; sub box { shift; return unless @_; my $min = clone(shift); my $max = clone($min); my $dim = $#$min; for (@_) { for my $ix (0..$dim) { my $c = $_->[$ix]; if ($max->[$ix] < $c) { $max->[$ix] = $c; } elsif ($min->[$ix] > $c) { $min->[$ix] = $c } } } ($min, $max); } sub max_component_index { my $self = shift; return unless @$self; my $max = 0; my $max_ix = 0; for my $ix (0..$#$self) { my $c = CORE::abs($self->[$ix]); if ($c > $max) { $max = $c; $max_ix = $ix; } } $max_ix; } sub min_component_index { my $self = shift; return unless @$self; my $min = CORE::abs($self->[0]); my $min_ix = 0; for my $ix (1..$#$self) { my $c = CORE::abs($self->[$ix]); if ($c < $min) { $min = $c; $min_ix = $ix } } $min_ix; } sub decompose { my ($u, $v) = @_; my $p = $u * ($u * $v)/abs2($u); my $n = $v - $p; wantarray ? ($p, $n) : $n; } sub canonical_base { my ($class, $dim) = @_; my @base = map { bless [(0) x $dim], $class } 1..$dim; $base[$_][$_] = 1 for 0..$#base; return @base; } sub rotation_base_3d { my $v = shift; @$v == 3 or croak "rotation_base_3d requires a vector with three dimensions"; $v = $v->versor; my $n = [0, 0, 0]; for (0..2) { if (CORE::abs($v->[$_]) > 0.57) { $n->[($_ + 1) % 3] = 1; $n = $v->decompose($n)->versor; return ($v, $n, $v x $n); } } die "internal error, all the components where smaller than 0.57!"; } sub rotate_3d { my $v = shift; my $angle = shift; my $c = cos($angle); my $s = sin($angle); my ($i, $j, $k) = $v->rotation_base_3d; my $rj = $c * $j + $s * $k; my $rk = $c * $k - $s * $j; if (wantarray) { return map { ($_ * $i) * $i + ($_ * $j) * $rj + ($_ * $k) * $rk } @_; } else { my $a = shift; return (($a * $i) * $i + ($a * $j) * $rj + ($a * $k) * $rk); } } sub normal_base { __PACKAGE__->complementary_base(@_) } sub complementary_base { shift; @_ or croak "complementaty_base requires at least one argument in order to determine the dimension"; my $dim = @{$_[0]}; if ($dim == 2 and @_ == 1) { my $u = versor($_[0]); @$u = ($u->[1], -$u->[0]); return $u; } my @v = map clone($_), @_; my @base = Math::Vector::Real->canonical_base($dim); for my $i (0..$#v) { my $u = versor($v[$i]); $_ = decompose($u, $_) for @v[$i+1 .. $#v]; $_ = decompose($u, $_) for @base; } my $last = $#base - @v; return if $last < 0; for my $i (0 .. $last) { my $max = abs2($base[$i]); if ($max < 0.3) { for my $j ($i+1 .. $#base) { my $d2 = abs2($base[$j]); if ($d2 > $max) { @base[$i, $j] = @base[$j, $i]; last unless $d2 < 0.3; $max = $d2; } } } my $versor = $base[$i] = versor($base[$i]); $_ = decompose($versor, $_) for @base[$i+1..$#base]; } wantarray ? @base[0..$last] : $base[0]; } sub select_in_ball { my $v = shift; my $r = shift; my $r2 = $r * $r; grep $v->dist2($_) <= $r2, @_; } sub select_in_ball_ref2bitmap { my $v = shift; my $r = shift; my $p = shift; my $r2 = $r * $r; my $bm = "\0" x int((@$p + 7) / 8); for my $ix (0..$#$p) { vec($bm, $ix, 1) = 1 if $v->dist2($p->[$ix]) <= $r2; } return $bm; } 1; __END__ =head1 NAME Math::Vector::Real - Real vector arithmetic in Perl =head1 SYNOPSIS use Math::Vector::Real; my $v = V(1.1, 2.0, 3.1, -4.0, -12.0); my $u = V(2.0, 0.0, 0.0, 1.0, 0.3); printf "abs(%s) = %d\n", $v, abs($b); my $dot = $u * $v; my $sub = $u - $v; # etc... =head1 DESCRIPTION A simple pure perl module to manipulate vectors of any dimension. The function C, always exported by the module, allows one to create new vectors: my $v = V(0, 1, 3, -1); Vectors are represented as blessed array references. It is allowed to manipulate the arrays directly as far as only real numbers are inserted (well, actually, integers are also allowed because from a mathematical point of view, integers are a subset of the real numbers). Example: my $v = V(0.0, 1.0); # extending the 2D vector to 3D: push @$v, 0.0; # setting some component value: $v->[0] = 23; Vectors can be used in mathematical expressions: my $u = V(3, 3, 0); $p = $u * $v; # dot product $f = 1.4 * $u + $v; # scalar product and vector addition $c = $u x $v; # cross product, only defined for 3D vectors # etc. The currently supported operations are: + * / - (both unary and binary) x (cross product for 3D vectors) += -= *= /= x= == != "" (stringfication) abs (returns the norm) atan2 (returns the angle between two vectors) That, AFAIK, are all the operations that can be applied to vectors. When an array reference is used in an operation involving a vector, it is automatically upgraded to a vector. For instance: my $v = V(1, 2); $v += [0, 2]; =head2 Extra methods Besides the common mathematical operations described above, the following methods are available from the package. Note that all these methods are non destructive returning new objects with the result. =over 4 =item $v = Math::Vector::Real->new(@components) Equivalent to C. =item $zero = Math::Vector::Real->zero($dim) Returns the zero vector of the given dimension. =item $v = Math::Vector::Real->cube($dim, $size) Returns a vector of the given dimension with all its components set to C<$size>. =item $u = Math::Vector::Real->axis_versor($dim, $ix) Returns a unitary vector of the given dimension parallel to the axis with index C<$ix> (0-based). For instance: Math::Vector::Real->axis_versor(5, 3); # V(0, 0, 0, 1, 0) Math::Vector::Real->axis_versor(2, 0); # V(1, 0) =item @b = Math::Vector::Real->canonical_base($dim) Returns the canonical base for the vector space of the given dimension. =item $u = $v->versor Returns the versor for the given vector. It is equivalent to: $u = $v / abs($v); =item $wrapped = $w->wrap($v) Returns the result of wrapping the given vector in the box (hyper-cube) defined by C<$w>. Long description: Given the vector C and the canonical base C such that C. For every component C we can consider the infinite set of affine hyperplanes perpendicular to C such that they contain the point C being C an integer number. The combination of all the hyperplanes defined by every component define a grid that divides the space into an infinite set of affine hypercubes. Every hypercube can be identified by its lower corner indexes C or its lower corner point C. Given the vector C, wrapping it by C is equivalent to finding where it lays relative to the lower corner point of the hypercube inside the grid containing it: Wrapped = V - (j1*w1*U1 + j2*w2*U2 +...+ jn*wn*Un) such that ji*wi <= vi < (ji+1)*wi =item $max = $v->max_component Returns the maximum of the absolute values of the vector components. =item $min = $v->min_component Returns the minimum of the absolute values of the vector components. =item $d2 = $b->norm2 Returns the norm of the vector squared. =item $d = $v->dist($u) Returns the distance between the two vectors. =item $d = $v->dist2($u) Returns the distance between the two vectors squared. =item ($bottom, $top) = Math::Vector::Real->box($v0, $v1, $v2, ...) Returns the two corners of a hyper-box containing all the given vectors. =item $v->set($u) Equivalent to C<$v = $u> but without allocating a new object. Note that this method is destructive. =item $d = $v->max_component_index Return the index of the vector component with the maximum size. =item ($p, $n) = $v->decompose($u) Decompose the given vector C<$u> in two vectors: one parallel to C<$v> and another normal. In scalar context returns the normal vector. =item @b = Math::Vector::Real->complementary_base(@v) Returns a base for the subspace complementary to the one defined by the base @v. The vectors on @v must be linearly independent. Otherwise a division by zero error may pop up or probably due to rounding errors, just a wrong result may be generated. =item @b = $v->normal_base Returns a set of vectors forming an ortonormal base for the hyperplane normal to $v. In scalar context returns just some unitary vector normal to $v. Note that this two expressions are equivalent: @b = $v->normal_base; @b = Math::Vector::Real->complementary_base($v); =item ($i, $j, $k) = $v->rotation_base_3d Given a 3D vector, returns a list of 3 vectors forming an orthonormal base where $i has the same direction as the given vector C<$v> and C<$k = $i x $j>. =item @r = $v->rotate_3d($angle, @s) Returns the vectors C<@u> rotated around the vector C<$v> an angle C<$angle> in radians in anticlockwise direction. See L. =item @s = $center->select_in_ball($radius, $v1, $v2, $v3, ...) Selects from the list of given vectors those that lay inside the n-ball determined by the given radius and center (C<$radius> and C<$center> respectively). =back =head2 Zero vector handling Passing the zero vector to some methods (i.e. C, C, C, etc.) is not acceptable. In those cases, the module will croak with an "Illegal division by zero" error. C is an exceptional case that will return 0 when any of its arguments is the zero vector (for consistency with the C builtin operating over real numbers). In any case note that, in practice, rounding errors frequently cause the check for the zero vector to fail resulting in numerical instabilities. The correct way to handle this problem is to introduce in your code checks of this kind: if ($v->norm2 < $epsilon2) { croak "$v is too small"; } Or even better, reorder the operations to minimize the chance of instabilities if the algorithm allows it. =head1 SEE ALSO L extends this module with random vector generation methods. L, L. There are other vector manipulation packages in CPAN (L, L, L), but they can only handle 3 dimensional vectors. =head1 COPYRIGHT AND LICENSE Copyright (C) 2009-2012 by Salvador FandiEo (sfandino@yahoo.com) This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself, either Perl version 5.10.0 or, at your option, any later version of Perl 5 you may have available. =cut Math-Vector-Real-0.10/t/0000755000175000017500000000000012001250614013674 5ustar salvasalvaMath-Vector-Real-0.10/t/pods.t0000644000175000017500000000047211574113725015050 0ustar salvasalva#!/usr/bin/perl use strict; use Test::More; plan skip_all => "Only the author needs to check that POD docs are right" unless eval "no warnings; getlogin eq 'salva'"; eval "use Test::Pod 1.00"; plan skip_all => "Test::Pod 1.00 required for testing POD" if $@; all_pod_files_ok( all_pod_files( qw(blib) ) ); Math-Vector-Real-0.10/t/Math-Vector-Real.t0000644000175000017500000000232211774565447017127 0ustar salvasalva#!/usr/bin/perl use Test::More tests => 27; use Math::Vector::Real; my $PI = 3.14159_26535_89793_23846_26433_83279; my $u = V(1, 0, 0); my $v = V(0, 1, 0); my $w = V(0, 0, 1); my $r = V(1, 1, 1); is (abs($_), 1) for ($u, $v, $w); is (abs($u + $w), sqrt(2)); ok (cos(atan2($u, $v)) < 1e-4); ok ($u + $v == [1, 1, 0]); ok ($u + $w != [1, 1, 1]); ok ($u - $v == [1, -1, 0]); ok (-$v - $w * 2 == [0, -1, -2]); ok (-2 * $v - $w == [0, -2, -1]); is ($u * $v, 0); is (($u + $v) * $v, 1); ok ($u x $v == $w); ok (abs($u->rotate_3d($PI/2, $v) - $w) < 0.0001); ok (abs($v->rotate_3d($PI/2, $w) - $u) < 0.0001); ok (abs($w->rotate_3d($PI/2, $v) - (-$u)) < 0.0001); my ($b1, $b2, $b3) = $r->rotation_base_3d; ok (abs($b1 * $r * $b1 - $r) < 0.0001); ok (abs($b1 x $b2 - $b3) < 0.0001); my $x = V(2,3,4); ok ($x x $x == [ 0, 0, 0]); ok ($x x [ 1, 0, 0] == [ 0, 4, -3]); ok ($x x [ 1, 1, 0] == [ -4, 4, -1]); ok ($x x [ -4, 4, -1] == [ -19, -14, 20]); ok ($x x [-19, -14, 20] == [ 116, -116, 29]); ok ([ 1, 0, 0] x $x == [ 0, -4, 3]); ok ([ 1, 1, 0] x $x == [ 4, -4, 1]); ok ([ -4, 4, -1] x $x == [ 19, 14, -20]); ok ([-19, -14, 20] x $x == [-116, 116, -29]);