Symbolic/MiscAlgebra.pm

filter: Statementstmt 100% 85 / 85 Branchbran 71.4% 20 / 28 Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 12 / 12 Podpod 100% 2 / 2 totaltotal 93.7% 119 / 127 CC 23 SCAR 17.0
CC
23
Cov
93%
linear_solve
9.4
det
7.1
bell_polynomial
5.0
CRAP 5.5
« Symbolic/Compiler.pm ↑ Summary Symbolic/Variable.pm »
1  
2 =encoding utf8
3  
4 =head1 NAME
5  
6 Math::Symbolic::MiscAlgebra - Miscellaneous algebra routines like det()
7  
8 =head1 SYNOPSIS
9  
10 use Math::Symbolic qw/:all/;
11 use Math::Symbolic::MiscAlgebra qw/:all/; # not loaded by Math::Symbolic
12
13 @matrix = (['x*y', 'z*x', 'y*z'],['x', 'z', 'z'],['x', 'x', 'y']);
14 $det = det @matrix;
15
16 @vector = ('x', 'y', 'z');
17 $solution = solve_linear(\@matrix, \@vector);
18
19 =head1 DESCRIPTION
20  
21 This module provides several subroutines related to
22 algebra such as computing the determinant of quadratic matrices, solving
23 linear equation systems and computation of Bell Polynomials.
24  
25 Please note that the code herein may or may not be refactored into
26 the OO-interface of the Math::Symbolic module in the future.
27  
28 =head2 EXPORT
29  
30 None by default.
31  
32 You may choose to have any of the following routines exported to the
33 calling namespace. ':all' tag exports all of the following:
34  
35 det
36 linear_solve
37 bell_polynomial
38  
39 =head1 SUBROUTINES
40  
41 =cut
42  
43 package Math::Symbolic::MiscAlgebra;
44  
45 3 ▶use 5.006;
Subroutine BEGIN: called CC=1 SCAR=0.0
46 3 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
47 3 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
48  
49 3 ▶use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
50 3 ▶use Memoize;
Subroutine BEGIN: called CC=1 SCAR=0.0
51  
52 3 ▶use Math::Symbolic qw/:all/;
Subroutine BEGIN: called CC=1 SCAR=0.0
53  
54 3 require Exporter;
55 3 our @ISA = qw(Exporter);
56 3 our %EXPORT_TAGS = (
57 'all' => [
58 qw(
59 det
60 bell_polynomial
61 linear_solve
62 )
63 ]
64 );
65  
66 3 our @EXPORT_OK = ( @{ $EXPORT_TAGS{'all'} } );
67  
68 3 our $VERSION = '0.613';
69  
70 =head2 det
71  
72 det() computes the determinant of a matrix of Math::Symbolic trees (or strings
73 that can be parsed as such). First argument must be a literal array:
74 "det @matrix", where @matrix is an n x n matrix.
75  
76 Please note that calculating determinants of matrices using the
77 straightforward Laplace algorithm is a slow (O(n!))
78 operation. This implementation cannot make use of the various optimizations
79 resulting from the determinant properties since we are dealing with
80 symbolic matrix elements. If you have a matrix of reals, it is strongly
81 suggested that you use Math::MatrixReal or Math::Pari to get the determinant
82 which can be calculated using LR decomposition much faster.
83  
84 On a related note: Calculating the determinant of a 20x20 matrix would take
85 over 77146 years if your Perl could do 1 million calculations per second.
86 Given that we're talking about several method calls per calculation, that's
87 much more than todays computers could do. On the other hand, if you'd be
88 using this straightforward algorithm with numbers only and in C, you might
89 be done in 26 years alright, so please go for the smarter route (better
90 algorithm) instead if you have numbers only.
91  
92 =cut
93  
94 7 ▶sub det (\@) {
Subroutine det: called CC=7 SCAR=19.6
Pod documented
95 7 my $matrix = shift;
96 7 my $size = @$matrix;
97  
98 7 foreach (@$matrix) {
99 20 ▶ croak "det(Matrix) requires n x n matrix!" if @$_ != $size;
Branch: 1 branch
BranchTrueFalseTotal
if @$_ != $size 0 20 20
100 20 foreach (@$_) {
101 60 ▶ $_ = Math::Symbolic::parse_from_string($_)
Branch: 1 branch
BranchTrueFalseTotal
unless ref($_) =~ /^Math::Symbolic/ 20 40 60
102 if ref($_) !~ /^Math::Symbolic/;
103 }
104 }
105  
106 7 ▶ return $matrix->[0][0] if $size == 1;
Branch: 1 branch
BranchTrueFalseTotal
if $size == 1 0 7 7
107 7 ▶ return $matrix->[0][0] * $matrix->[1][1] - $matrix->[1][0] * $matrix->[0][1]
Branch: 1 branch
BranchTrueFalseTotal
if $size == 2 2 5 7
108 if $size == 2;
109 5 return _det_helper( $matrix, $size );
110 }
111  
112 9 ▶sub _det_helper {
Subroutine _det_helper: called CC=4 SCAR=13.9
113 9 my $matrix = shift;
114 9 my $size = shift;
115  
116 9 ▶ return $matrix->[0][0] * $matrix->[1][1] * $matrix->[2][2] + $matrix->[1][0]
Branch: 1 branch
BranchTrueFalseTotal
if $size == 3 8 1 9
117 * $matrix->[2][1] * $matrix->[0][2] + $matrix->[2][0] * $matrix->[0][1] *
118 $matrix->[1][2] - $matrix->[0][2] * $matrix->[1][1] * $matrix->[2][0] -
119 $matrix->[1][2] * $matrix->[2][1] * $matrix->[0][0] - $matrix->[2][2] *
120 $matrix->[0][1] * $matrix->[1][0]
121 if $size == 3;
122  
123 1 my $det;
124 1 foreach ( 0 .. $size - 1 ) {
125 4 ▶ if ( $_ % 2 ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($_ % 2) { } 2 2 4
126 2 $det -=
127 $matrix->[0][$_] *
128 _det_helper( _matrix_slice( $matrix, 0, $_ ), $size - 1 );
129 }
130 else {
131 2 $det +=
132 $matrix->[0][$_] *
133 _det_helper( _matrix_slice( $matrix, 0, $_ ), $size - 1 );
134 }
135 }
136 1 return $det;
137 }
138  
139 7 ▶sub _matrix_slice {
Subroutine _matrix_slice: called CC=1 SCAR=0.0
140 7 my $matrix = shift;
141 7 my $x = shift;
142 7 my $y = shift;
143  
144 18 return [ map { [ @{$_}[ 0 .. $y - 1, $y + 1 ... $#$_ ] ] }
145 7 @{$matrix}[ 0 .. $x - 1, $x + 1 .. $#$matrix ] ];
146 }
147  
148 =head2 linear_solve
149  
150 Calculates the solutions x (vector) of a linear equation system of the form
151 C<Ax = b> with C<A> being a matrix, C<b> a vector and the solution C<x> a
152 vector. Due to implementation limitations, C<A> must be a quadratic matrix and
153 C<b> must have a dimension that is equivalent to that of C<A>. Furthermore,
154 the determinant of C<A> must be non-zero. The algorithm used is devised from
155 Cramer's Rule and thus inefficient. The preferred algorithm for this task is
156 Gaussian Elimination. If you have a matrix and a vector of real numbers, please
157 consider using either Math::MatrixReal or Math::Pari instead.
158  
159 First argument must be a reference to a matrix (array of arrays) of symbolic
160 terms, second argument must be a reference to a vector (array) of symbolic
161 terms. Strings will be automatically converted to Math::Symbolic trees.
162 Returns a reference to the solution vector.
163  
164 =cut
165  
166 1 ▶sub linear_solve {
Subroutine linear_solve: called CC=9 SCAR=22.4
Pod documented
167 1 my ( $m, $v ) = @_;
168 1 my $dim = @$v;
169  
170 1 ▶ croak "linear_solve(Matrix, Vector) requires n x n matrix and n-vector!"
Branch: 1 branch
BranchTrueFalseTotal
if @$m != $dim 0 1 1
171 if @$m != $dim;
172 1 foreach (@$m) {
173 3 ▶ croak "linear_solve(Matrix, Vector) requires n x n matrix and n-vector!"
Branch: 1 branch
BranchTrueFalseTotal
if @$_ != $dim 0 3 3
174 if @$_ != $dim;
175 3 foreach (@$_) {
176 9 ▶ $_ = Math::Symbolic::parse_from_string($_)
Branch: 1 branch
BranchTrueFalseTotal
unless ref($_) =~ /^Math::Symbolic/ 9 0 9
177 if ref($_) !~ /^Math::Symbolic/;
178 }
179 }
180 1 foreach (@$v) {
181 3 ▶ $_ = Math::Symbolic::parse_from_string($_)
Branch: 1 branch
BranchTrueFalseTotal
unless ref($_) =~ /^Math::Symbolic/ 3 0 3
182 if ref($_) !~ /^Math::Symbolic/;
183 }
184  
185 1 my $det = det @$m;
186  
187 1 my @vec;
188  
189 1 foreach my $i ( 0 .. $#$m ) {
190 3 my $nm = _replace_col( $m, $v, $i );
191 3 my $det_i = det @$nm;
192 3 push @vec, $det_i / $det;
193 }
194  
195 1 return \@vec;
196 }
197  
198 3 ▶sub _replace_col {
Subroutine _replace_col: called CC=2 SCAR=6.9
199 3 my $m = shift;
200 3 my $v = shift;
201 3 my $col = shift;
202 3 my $nm = [];
203 3 foreach my $i ( 0 .. $#$m ) {
204 $nm->[$i] = [
205 9 @{ $m->[$i] }[ 0 .. $col - 1 ],
206 $v->[$i],
207 9 @{ $m->[$i] }[ $col + 1 .. $#$m ]
208 ];
209 }
210 3 return $nm;
211 }
212  
213 =head2 bell_polynomial
214  
215 This functions returns the nth Bell Polynomial. It uses memoization for
216 speed increase.
217  
218 First argument is the n. Second (optional) argument is the variable or
219 variable name to use in the polynomial. Defaults to 'x'.
220  
221 The Bell Polynomial is defined as follows:
222  
223 phi_0 (x) = 1
224 phi_n+1(x) = x * ( phi_n(x) + partial_derivative( phi_n(x), x ) )
225  
226 Bell Polynomials are Exponential Polynimals with phi_n(1) = the nth bell
227 number. Please refer to the bell_number() function in the
228 Math::Symbolic::AuxFunctions module for a method of generating these numbers.
229  
230 =cut
231  
232 3 memoize('bell_polynomial');
233  
234 3 ▶sub bell_polynomial {
Subroutine bell_polynomial: called CC=5 SCAR=16.2
235 3 my $n = shift;
236 3 my $var = shift;
237 3 ▶ $var = 'x' if not defined $var;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $var 3 0 3
238 3 $var = Math::Symbolic::Variable->new($var);
239  
240 3 ▶ return undef if $n < 0;
Branch: 1 branch
BranchTrueFalseTotal
if $n < 0 0 3 3
241 3 ▶ return Math::Symbolic::Constant->new(1) if $n == 0;
Branch: 1 branch
BranchTrueFalseTotal
if $n == 0 1 2 3
242 2 ▶ return $var if $n == 1;
Branch: 1 branch
BranchTrueFalseTotal
if $n == 1 1 1 2
243  
244 1 my $bell = bell_polynomial( $n - 1 );
245 1 $bell = Math::Symbolic::Operator->new(
246 '+',
247 Math::Symbolic::Operator->new( '*', $var, $bell )->simplify(),
248 Math::Symbolic::Operator->new(
249 '*',
250 $var,
251 Math::Symbolic::Operator->new( 'partial_derivative', $bell, $var )
252 ->apply_derivatives()->simplify()
253 )->simplify()
254 );
255 1 return $bell;
256 }
257  
258 3 1;
259 __END__
« Symbolic/Compiler.pm ↑ Summary Symbolic/Variable.pm »