lib/PDL/MatrixOps.pd

filter: Statementstmt 40.8% 179 / 438 Branchbran 30.2% 87 / 288 Conditioncond 16.6% 26 / 156 MC/DCmcdc 4.7% 4 / 84 Subroutinesub 47.8% 11 / 23 Podpod 80.0% 16 / 20 totaltotal 32.0% 323 / 1009 CC 209 SCAR 49.8
CC
209
Cov
33%
lu_decomp2
342.0
lu_decomp2
342.0
lu_backsub
232.2
CRAP 145.8
« blib/lib/PDL/Doc/Perldl.pm ↑ Summary blib/lib/PDL/IO/FITS.pm »
1 pp_addhdr('
2 #include <math.h>
3 ');
4  
5 use strict;
6 use warnings;
7 use PDL::Types qw(ppdefs_all);
8  
9 { no warnings 'once'; # pass info back to Makefile.PL
10 $PDL::Core::Dev::EXTRAS{$::PDLMOD}{OBJECT} .= join '', map " $::PDLBASE/$_\$(OBJ_EXT)", qw(eigens simq svd eigen matrix sslib);
11 $PDL::Core::Dev::EXTRAS{$::PDLMOD}{INC} .= qq{ "-I$::PDLBASE"};
12 }
13  
14 pp_addpm({At=>'Top'},<<'EOD');
15 =encoding utf8
16  
17 use strict;
18 use warnings;
19  
20 =head1 NAME
21  
22 PDL::MatrixOps -- Some Useful Matrix Operations
23  
24 =head1 SYNOPSIS
25  
26 $inv = $x->inv;
27  
28 $det = $x->det;
29  
30 ($lu,$perm,$par) = $x->lu_decomp;
31 $y = lu_backsub($lu,$perm,$z); # solve $x x $y = $z
32  
33 =head1 DESCRIPTION
34  
35 PDL::MatrixOps is PDL's built-in matrix manipulation code. It
36 contains utilities for many common matrix operations: inversion,
37 determinant finding, eigenvalue/vector finding, singular value
38 decomposition, etc. PDL::MatrixOps routines are written in a mixture
39 of Perl and C, so that they are reliably present even when there is no
40 external library available (e.g.
41 L<PDL::LinearAlgebra> or any of the PDL::GSL family of modules).
42  
43 Matrix manipulation, particularly with large matrices, is a
44 challenging field and no one algorithm is suitable in all cases. The
45 utilities here use general-purpose algorithms that work acceptably for
46 many cases but might not scale well to very large or pathological
47 (near-singular) matrices.
48  
49 Except as noted, the matrices are PDLs whose 0th dimension ranges over
50 column and whose 1st dimension ranges over row. The matrices appear
51 correctly when printed.
52  
53 These routines should work OK with L<PDL::Matrix> objects
54 as well as with normal PDLs.
55  
56 =head1 TIPS ON MATRIX OPERATIONS
57  
58 Like most computer languages, PDL addresses matrices in (column,row)
59 order in most cases; this corresponds to (X,Y) coordinates in the
60 matrix itself, counting rightwards and downwards from the upper left
61 corner. This means that if you print a PDL that contains a matrix,
62 the matrix appears correctly on the screen, but if you index a matrix
63 element, you use the indices in the reverse order that you would in a
64 math textbook. If you prefer your matrices indexed in (row, column)
65 order, you can try using the L<PDL::Matrix> object, which
66 includes an implicit exchange of the first two dimensions but should
67 be compatible with most of these matrix operations. TIMTOWDTI.
68  
69 Matrices, row vectors, and column vectors can be multiplied with the 'x'
70 operator (which is, of course, broadcastable):
71  
72 $m3 = $m1 x $m2;
73 $col_vec2 = $m1 x $col_vec1;
74 $row_vec2 = $row_vec1 x $m1;
75 $scalar = $row_vec x $col_vec;
76  
77 Because of the (column,row) addressing order, 1-D PDLs are treated as
78 _row_ vectors; if you want a _column_ vector you must add a dummy dimension:
79  
80 $rowvec = pdl(1,2); # row vector
81 $colvec = $rowvec->slice('*1'); # 1x2 column vector
82 $matrix = pdl([[3,4],[6,2]]); # 2x2 matrix
83 $rowvec2 = $rowvec x $matrix; # right-multiplication by matrix
84 $colvec = $matrix x $colvec; # left-multiplication by matrix
85 $m2 = $matrix x $rowvec; # Throws an error
86  
87 Implicit broadcasting works correctly with most matrix operations, but
88 you must be extra careful that you understand the dimensionality. In
89 particular, matrix multiplication and other matrix ops need nx1 PDLs
90 as row vectors and 1xn PDLs as column vectors. In most cases you must
91 explicitly include the trailing 'x1' dimension in order to get the expected
92 results when you broadcast over multiple row vectors.
93  
94 When broadcasting over matrices, it's very easy to get confused about
95 which dimension goes where. It is useful to include comments with
96 every expression, explaining what you think each dimension means:
97  
98 $x = xvals(360)*3.14159/180; # (angle)
99 $rot = cat(cat(cos($x),sin($x)), # rotmat: (col,row,angle)
100 cat(-sin($x),cos($x)));
101  
102 =head1 ACKNOWLEDGEMENTS
103  
104 MatrixOps includes algorithms and pre-existing code from several
105 origins. In particular, C<eigens_sym> is the work of Stephen Moshier,
106 C<svd> uses an SVD subroutine written by Bryant Marks, and C<eigens>
107 uses a subset of the Small Scientific Library by Kenneth Geisshirt.
108 They are free software, distributable under same terms as PDL itself.
109  
110  
111 =head1 NOTES
112  
113 This is intended as a general-purpose linear algebra package for
114 small-to-mid sized matrices. The algorithms may not scale well to
115 large matrices (hundreds by hundreds) or to near singular matrices.
116  
117 If there is something you want that is not here, please add and
118 document it!
119  
120 =cut
121 70 ▶ 
Subroutine BEGIN: called CC=1 SCAR=0.0
122 70 ▶use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: not called CC=1 SCAR=0.0
123 use strict;
124  
125 EOD
126  
127  
128 ######################################################################
129  
130 pp_add_exported('','identity');
131 pp_addpm(<<'EOD');
132 =head2 identity
133  
134 =for sig
135  
136 Signature: (n; [o]a(n,n))
137  
138 =for ref
139  
140 Return an identity matrix of the specified size. If you hand in a
141 scalar, its value is the size of the identity matrix; if you hand in a
142 dimensioned PDL, the 0th dimension is the first two dimensions of the
143 matrix, with higher dimensions preserved.
144  
145 =cut
146  
147 98 ▶sub identity {
Subroutine identity: called CC=5 SCAR=20.9
Pod documented
148 0 ▶ my $n = shift;
Subroutine identity: not called CC=5 SCAR=20.9
Pod documented
149 0 ▶ my $out =
Branch: 4 branches
BranchTrueFalseTotal
!(my $was_pdl = UNIVERSAL::isa($n, 'PDL')) ? : 33 65 98
$n->getndims == 0 ? : 2 63 65
!(my $was_pdl = UNIVERSAL::isa($n, 'PDL')) ? : 0 0 0
$n->getndims == 0 ? : 0 0 0
150 !(my $was_pdl = UNIVERSAL::isa($n,'PDL')) ? zeroes($n,$n) :
151 $n->getndims == 0 ? zeroes($n->type, $n->at(0),$n->at(0)) :
152 undef;
153 0 ▶ if (!defined $out) {
Branch: 2 branches
BranchTrueFalseTotal
unless (defined $out) 63 35 98
unless (defined $out) 0 0 0
154 0 my @dims = $n->dims;
155 0 $out = zeroes($n->type, @dims[0, 0, 2..$#dims]);
156 }
157 0 $out->diagonal(0,1)++;
158 0 ▶ $was_pdl ? bless $out, ref($n) : $out;
Branch: 2 branches
BranchTrueFalseTotal
$was_pdl ? : 65 33 98
$was_pdl ? : 0 0 0
159 }
160 EOD
161  
162 pp_add_exported('','gurney');
163 pp_addpm(<<'EOD');
164  
165 =head2 gurney
166  
167 =for ref
168  
169 Turns a vector into non-square matrix. Takes two dims, one must
170 match vector dim 0.
171  
172 This is useful for dealing with a full SVD:
173  
174 =for example
175  
176 ($u,$s,$v) = svd($in, 1);
177 $reconstructed = $u x gurney($s, $in->dims) x $v->t; # same as $in
178  
179 =cut
180  
181 6 ▶*gurney = \&PDL::gurney;
Subroutine gurney: called CC=5 SCAR=23.1
Pod undocumented
182 0 ▶sub PDL::gurney {
Subroutine gurney: not called CC=5 SCAR=23.1
Pod undocumented
183 0 ▶ my ($diag, $d0, $d1) = @_;
Branch: 2 branches
BranchTrueFalseTotal
if grep((!defined($d0)), $d1) 0 6 6
if grep((!defined($d0)), $d1) 0 0 0
184 0 Carp::confess "gurney: given undef \$d0 or \$d1" if grep !defined $d0, $d1;
185 0 ▶ my $diag_len = $diag->dim(0);
Branch: 2 branches
BranchTrueFalseTotal
unless grep(($diag_len == $_), $d0, $d1) 0 6 6
unless grep(($diag_len == $_), $d0, $d1) 0 0 0
186 0 Carp::confess "diagonal length $diag_len does not match either given dim $d0 or $d1" if !grep $diag_len == $_, $d0, $d1;
187 0 my $diff = abs($d0 - $d1);
188 0 ▶ my $mat = stretcher($diag);
Branch: 2 branches
BranchTrueFalseTotal
unless $diff 0 6 6
unless $diff 0 0 0
189 0 ▶ return $mat if !$diff;
Branch: 2 branches
BranchTrueFalseTotal
if $d0 > $d1 3 3 6
if $d0 > $d1 0 0 0
190 0 return $mat->append(zeroes($diag->type, $diff)) if $d0 > $d1;
191 $mat->t->append(zeroes($diag->type, $diff))->t;
192 }
193 EOD
194  
195 ######################################################################
196 pp_add_exported('','stretcher');
197 pp_addpm(<<'EOD');
198  
199 =head2 stretcher
200  
201 =for sig
202  
203 Signature: (a(n); [o]b(n,n))
204  
205 =for usage
206  
207 $mat = stretcher($eigenvalues);
208  
209 =for ref
210  
211 Return a diagonal matrix with the specified diagonal elements.
212 Preserves higher dimensions.
213 As of 2.096, it will also have the same datatype.
214  
215 =cut
216 15 ▶ 
Subroutine stretcher: called CC=1 SCAR=1.2
Pod documented
217 0 ▶sub stretcher {
Subroutine stretcher: not called CC=1 SCAR=1.2
Pod documented
218 0 my $in = shift;
219 0 my $out = zeroes($in->type, $in->dim(0), $in->dims);
220 0 $out->diagonal(0,1) += $in;
221 $out;
222 }
223  
224 EOD
225  
226 ######################################################################
227  
228 pp_add_exported('','inv');
229 pp_addpm(<<'EOD');
230  
231 =head2 inv
232  
233 =for sig
234  
235 Signature: (a(m,m); sv opt )
236  
237 =for usage
238  
239 $a1 = inv($a, {$opt});
240  
241 =for ref
242  
243 Invert a square matrix.
244  
245 You feed in an NxN matrix in $a, and get back its inverse (if it
246 exists). The code is inplace-aware, so you can get back the inverse
247 in $a itself if you want -- though temporary storage is used either
248 way. You can cache the LU decomposition in an output option variable.
249  
250 C<inv> uses C<lu_decomp> by default; that is a numerically stable
251 (pivoting) LU decomposition method.
252  
253  
254 OPTIONS:
255  
256 =over 3
257  
258 =item * s
259  
260 Boolean value indicating whether to complain if the matrix is singular. If
261 this is false, singular matrices cause inverse to barf. If it is true, then
262 singular matrices cause inverse to return undef.
263  
264 =item * lu (I/O)
265  
266 This value contains a list ref with the LU decomposition, permutation,
267 and parity values for C<$a>. If you do not mention the key, or if the
268 value is undef, then inverse calls C<lu_decomp>. If the key exists with
269 an undef value, then the output of C<lu_decomp> is stashed here (unless
270 the matrix is singular). If the value exists, then it is assumed to
271 hold the LU decomposition.
272  
273 =item * det (Output)
274  
275 If this key exists, then the determinant of C<$a> get stored here,
276 whether or not the matrix is singular.
277  
278 =back
279  
280 =cut
281 60 ▶ 
Subroutine inv: called CC=15 SCAR=40.8
Pod documented
282 0 ▶*PDL::inv = \&inv;
Subroutine inv: not called CC=15 SCAR=40.8
Pod documented
283 sub inv {
284 0 ▶ my $x = shift;
Branch: 2 branches
BranchTrueFalseTotal
unless UNIVERSAL::isa($x, "PDL") and $x->ndims >= 2 and $x->dim(0) == $x->dim(1) 0 60 60
unless UNIVERSAL::isa($x, "PDL") and $x->ndims >= 2 and $x->dim(0) == $x->dim(1) 0 0 0
Condition16%2/12
UNIVERSAL::isa($x, "PDL") and $x->ndims >= 2 and $x->dim(0) == $x->dim(1)
!ll&&!rl&&r
0060
UNIVERSAL::isa($x, "PDL") and $x->ndims >= 2
!ll&&!rl&&r
0060
UNIVERSAL::isa($x, "PDL") and $x->ndims >= 2 and $x->dim(0) == $x->dim(1)
!ll&&!rl&&r
000
UNIVERSAL::isa($x, "PDL") and $x->ndims >= 2
!ll&&!rl&&r
000
MC/DC0%0/3
UNIVERSAL::isa($x, "PDL") and $x->ndims >= 2 and $x->dim(0) == $x->dim(1)
UNIVERSAL::isa($x, "PDL") $x->ndims >= 2 $x->dim(0) == $x->dim(1)
MC/DC0%0/3
UNIVERSAL::isa($x, "PDL") and $x->ndims >= 2 and $x->dim(0) == $x->dim(1)
UNIVERSAL::isa($x, "PDL") $x->ndims >= 2 $x->dim(0) == $x->dim(1)
Truth table25%1/4
A and B and C
A= UNIVERSAL::isa($x, "PDL")B= $x->ndims >= 2C= $x->dim(0) == $x->dim(1)
ABCresult
0XX0
10X0
1100
1111
Truth table0%0/4
A and B and C
A= UNIVERSAL::isa($x, "PDL")B= $x->ndims >= 2C= $x->dim(0) == $x->dim(1)
ABCresult
0XX0
10X0
1100
1111
285  
286 barf "inverse needs a square PDL as a matrix\n"
287 unless UNIVERSAL::isa($x,'PDL') &&
288 $x->ndims >= 2 &&
289 $x->dim(0) == $x->dim(1)
290 0 ;
291 0 ▶ 
Branch: 2 branches
BranchTrueFalseTotal
unless defined $opt 16 44 60
unless defined $opt 0 0 0
292 0 my $opt = shift;
293 0 $opt = {} unless defined($opt);
294 my $is_inplace = $x->is_inplace;
295 0 $x->set_inplace(0);
296 0 ▶ 
Branch: 2 branches
BranchTrueFalseTotal
if (exists $opt->{'lu'} and ref $opt->{'lu'} eq 'ARRAY' and ref $opt->{'lu'}[0] eq 'PDL') { } 42 18 60
if (exists $opt->{'lu'} and ref $opt->{'lu'} eq 'ARRAY' and ref $opt->{'lu'}[0] eq 'PDL') { } 0 0 0
Condition41%5/12
exists $opt->{"lu"} and ref $opt->{"lu"} eq "ARRAY" and ref $opt->{"lu"}[0] eq "PDL"
!ll&&!rl&&r
17142
exists $opt->{"lu"} and ref $opt->{"lu"} eq "ARRAY"
!ll&&!rl&&r
17043
exists $opt->{"lu"} and ref $opt->{"lu"} eq "ARRAY" and ref $opt->{"lu"}[0] eq "PDL"
!ll&&!rl&&r
000
exists $opt->{"lu"} and ref $opt->{"lu"} eq "ARRAY"
!ll&&!rl&&r
000
MC/DC66%2/3
exists $opt->{"lu"} and ref $opt->{"lu"} eq "ARRAY" and ref $opt->{"lu"}[0] eq "PDL"
exists $opt->{"lu"} ref $opt->{"lu"} eq "ARRAY" ref $opt->{"lu"}[0] eq "PDL"
MC/DC0%0/3
exists $opt->{"lu"} and ref $opt->{"lu"} eq "ARRAY" and ref $opt->{"lu"}[0] eq "PDL"
exists $opt->{"lu"} ref $opt->{"lu"} eq "ARRAY" ref $opt->{"lu"}[0] eq "PDL"
Truth table75%3/4
A and B and C
A= exists $opt->{"lu"}B= ref $opt->{"lu"} eq "ARRAY"C= ref $opt->{"lu"}[0] eq "PDL"
ABCresult
0XX0
10X0
1100
1111
Truth table0%0/4
A and B and C
A= exists $opt->{"lu"}B= ref $opt->{"lu"} eq "ARRAY"C= ref $opt->{"lu"}[0] eq "PDL"
ABCresult
0XX0
10X0
1100
1111
297 my ($lu,$perm,$par);
298 if(exists($opt->{lu}) &&
299 0 ref $opt->{lu} eq 'ARRAY' &&
300 ref $opt->{lu}->[0] eq 'PDL') {
301 0 ($lu,$perm,$par) = @{$opt->{lu}};
302 0 } else {
303 0 ▶ ($lu,$perm,$par) = lu_decomp($x);
Branch: 2 branches
BranchTrueFalseTotal
if ref $opt->{"lu"} eq "ARRAY" 1 17 18
if ref $opt->{"lu"} eq "ARRAY" 0 0 0
304 @{$opt->{lu}} = ($lu,$perm,$par)
305 if(ref $opt->{lu} eq 'ARRAY');
306 0 ▶ }
Branch: 2 branches
BranchTrueFalseTotal
defined $lu ? : 60 0 60
defined $lu ? : 0 0 0
307  
308 0 ▶ my $det = (defined $lu) ? $lu->diagonal(0,1)->prodover * $par : pdl(0);
Branch: 2 branches
BranchTrueFalseTotal
if exists $opt->{"det"} 0 60 60
if exists $opt->{"det"} 0 0 0
309 $opt->{det} = $det
310 0 ▶ if exists($opt->{det});
Branch: 2 branches
BranchTrueFalseTotal
unless ($det->nelem > 1 or $det) 1 59 60
unless ($det->nelem > 1 or $det) 0 0 0
Condition50%3/6
$det->nelem > 1 or $det
l!l&&r!l&&!r
3453
$det->nelem > 1 or $det
l!l&&r!l&&!r
000
MC/DC0%0/2
$det->nelem > 1 or $det
$det->nelem > 1 $det
MC/DC0%0/2
$det->nelem > 1 or $det
$det->nelem > 1 $det
Truth table33%1/3
A or B
A= $det->nelem > 1B= $det
ABresult
1X1
011
000
Truth table0%0/3
A or B
A= $det->nelem > 1B= $det
ABresult
1X1
011
000
311  
312 0 ▶ unless($det->nelem > 1 || $det) {
Branch: 2 branches
BranchTrueFalseTotal
if $opt->{"s"} 1 0 1
if $opt->{"s"} 0 0 0
313 0 return undef
314 if $opt->{s};
315 barf("PDL::inv: got a singular matrix or LU decomposition\n");
316 0 }
317 0 ▶ 
Branch: 2 branches
BranchTrueFalseTotal
unless $is_inplace 56 3 59
unless $is_inplace 0 0 0
318 0 my $out = lu_backsub($lu,$perm,$par,identity($x))->transpose->sever;
319 0 return $out if !$is_inplace;
320 $x .= $out;
321 $x;
322 }
323  
324 EOD
325  
326 ######################################################################
327  
328 pp_add_exported('','det');
329 pp_addpm(<<'EOD');
330  
331 =head2 det
332  
333 =for sig
334  
335 Signature: (a(m,m); sv opt)
336  
337 =for usage
338  
339 $det = det($a,{opt});
340  
341 =for ref
342  
343 Determinant of a square matrix using LU decomposition (for large matrices)
344  
345 You feed in a square matrix, you get back the determinant. Some
346 options exist that allow you to cache the LU decomposition of the
347 matrix (note that the LU decomposition is invalid if the determinant
348 is zero!). The LU decomposition is cacheable, in case you want to
349 re-use it. This method of determinant finding is more rapid than
350 recursive-descent on large matrices, and if you reuse the LU
351 decomposition it's essentially free.
352  
353 OPTIONS:
354  
355 =over 3
356  
357 =item * lu (I/O)
358  
359 Provides a cache for the LU decomposition of the matrix. If you
360 provide the key but leave the value undefined, then the LU decomposition
361 goes in here; if you put an LU decomposition here, it will be used and
362 the matrix will not be decomposed again.
363  
364 =back
365  
366 =cut
367  
368 47 ▶*PDL::det = \&det;
Subroutine det: called CC=6 SCAR=23.5
Pod documented
369 0 ▶sub det {
Subroutine det: not called CC=6 SCAR=23.5
Pod documented
370 0 ▶ my ($x, $opt) = @_;
Branch: 2 branches
BranchTrueFalseTotal
unless defined $opt 4 43 47
unless defined $opt 0 0 0
371 0 $opt = {} unless defined($opt);
372 0 ▶ my($lu,$perm,$par);
Branch: 2 branches
BranchTrueFalseTotal
if (exists $opt->{'lu'} and ref $opt->{'lu'} eq 'ARRAY') { } 1 46 47
if (exists $opt->{'lu'} and ref $opt->{'lu'} eq 'ARRAY') { } 0 0 0
Condition50%3/6
exists $opt->{"lu"} and ref $opt->{"lu"} eq "ARRAY"
!ll&&!rl&&r
4421
exists $opt->{"lu"} and ref $opt->{"lu"} eq "ARRAY"
!ll&&!rl&&r
000
MC/DC100%2/2
exists $opt->{"lu"} and ref $opt->{"lu"} eq "ARRAY"
exists $opt->{"lu"} ref $opt->{"lu"} eq "ARRAY"
MC/DC0%0/2
exists $opt->{"lu"} and ref $opt->{"lu"} eq "ARRAY"
exists $opt->{"lu"} ref $opt->{"lu"} eq "ARRAY"
Truth table100%3/3
A and B
A= exists $opt->{"lu"}B= ref $opt->{"lu"} eq "ARRAY"
ABresult
0X0
100
111
Truth table0%0/3
A and B
A= exists $opt->{"lu"}B= ref $opt->{"lu"} eq "ARRAY"
ABresult
0X0
100
111
373 0 if(exists ($opt->{lu}) and (ref $opt->{lu} eq 'ARRAY')) {
374 ($lu,$perm,$par) = @{$opt->{lu}};
375 0 } else {
376 ($lu,$perm,$par) = lu_decomp($x);
377 0 ▶ $opt->{lu} = [$lu,$perm,$par]
Branch: 2 branches
BranchTrueFalseTotal
if exists $opt->{"lu"} 42 4 46
if exists $opt->{"lu"} 0 0 0
378 if(exists($opt->{lu}));
379 0 ▶ }
Branch: 2 branches
BranchTrueFalseTotal
defined $lu ? : 46 1 47
defined $lu ? : 0 0 0
380 defined $lu ? $lu->diagonal(0,1)->prodover * $par : PDL->zeroes(sbyte,1);
381 }
382  
383 EOD
384  
385 ######################################################################
386  
387 pp_add_exported('','determinant');
388 pp_addpm(<<'EOD');
389  
390 =head2 determinant
391  
392 =for sig
393  
394 Signature: (a(m,m))
395  
396 =for usage
397  
398 $det = determinant($x);
399  
400 =for ref
401  
402 Determinant of a square matrix, using recursive descent (broadcastable).
403  
404 This is the traditional, robust recursive determinant method taught in
405 most linear algebra courses. It scales like C<O(n!)> (and hence is
406 pitifully slow for large matrices) but is very robust because no
407 division is involved (hence no division-by-zero errors for singular
408 matrices). It's also broadcastable, so you can find the determinants of
409 a large collection of matrices all at once if you want.
410  
411 Matrices up to 3x3 are handled by direct multiplication; larger matrices
412 are handled by recursive descent to the 3x3 case.
413  
414 The LU-decomposition method L</det> is faster in isolation for
415 single matrices larger than about 4x4, and is much faster if you end up
416 reusing the LU decomposition of C<$a> (NOTE: check performance and
417 broadcasting benchmarks with new code).
418  
419 =cut
420  
421 6 ▶*PDL::determinant = \&determinant;
Subroutine determinant: called CC=9 SCAR=33.5
Pod documented
422 0 ▶sub determinant {
Subroutine determinant: not called CC=9 SCAR=33.5
Pod documented
423 0 my($x) = shift;
424 my($n);
425 0 ▶ return undef unless(
Branch: 2 branches
BranchTrueFalseTotal
unless UNIVERSAL::isa($x, "PDL") and $x->getndims >= 2 and ($n = $x->dim(0)) == $x->dim(1) 0 6 6
unless UNIVERSAL::isa($x, "PDL") and $x->getndims >= 2 and ($n = $x->dim(0)) == $x->dim(1) 0 0 0
Condition16%2/12
UNIVERSAL::isa($x, "PDL") and $x->getndims >= 2 and ($n = $x->dim(0)) == $x->dim(1)
!ll&&!rl&&r
006
UNIVERSAL::isa($x, "PDL") and $x->getndims >= 2
!ll&&!rl&&r
006
UNIVERSAL::isa($x, "PDL") and $x->getndims >= 2 and ($n = $x->dim(0)) == $x->dim(1)
!ll&&!rl&&r
000
UNIVERSAL::isa($x, "PDL") and $x->getndims >= 2
!ll&&!rl&&r
000
MC/DC0%0/3
UNIVERSAL::isa($x, "PDL") and $x->getndims >= 2 and ($n = $x->dim(0)) == $x->dim(1)
UNIVERSAL::isa($x, "PDL") $x->getndims >= 2 ($n = $x->dim(0)) == $x->dim(1)
MC/DC0%0/3
UNIVERSAL::isa($x, "PDL") and $x->getndims >= 2 and ($n = $x->dim(0)) == $x->dim(1)
UNIVERSAL::isa($x, "PDL") $x->getndims >= 2 ($n = $x->dim(0)) == $x->dim(1)
Truth table25%1/4
A and B and C
A= UNIVERSAL::isa($x, "PDL")B= $x->getndims >= 2C= ($n = $x->dim(0)) == $x->dim(1)
ABCresult
0XX0
10X0
1100
1111
Truth table0%0/4
A and B and C
A= UNIVERSAL::isa($x, "PDL")B= $x->getndims >= 2C= ($n = $x->dim(0)) == $x->dim(1)
ABCresult
0XX0
10X0
1100
1111
426 UNIVERSAL::isa($x,'PDL') &&
427 $x->getndims >= 2 &&
428 ($n = $x->dim(0)) == $x->dim(1)
429 );
430 0 ▶ 
Branch: 2 branches
BranchTrueFalseTotal
if $n == 1 0 6 6
if $n == 1 0 0 0
431 0 ▶ return $x->clump(2) if($n==1);
Branch: 2 branches
BranchTrueFalseTotal
if ($n == 2) 0 6 6
if ($n == 2) 0 0 0
432 0 if($n==2) {
433 0 my($y) = $x->clump(2);
434 return $y->index(0)*$y->index(3) - $y->index(1)*$y->index(2);
435 0 ▶ }
Branch: 2 branches
BranchTrueFalseTotal
if ($n == 3) 5 1 6
if ($n == 3) 0 0 0
436 0 if($n==3) {
437 0 my($y) = $x->clump(2);
438 0 my $y3 = $y->index(3);
439 0 my $y4 = $y->index(4);
440 0 my $y5 = $y->index(5);
441 0 my $y6 = $y->index(6);
442 0 my $y7 = $y->index(7);
443 my $y8 = $y->index(8);
444  
445 0 return (
446 $y->index(0) * ( $y4 * $y8 - $y5 * $y7 )
447 + $y->index(1) * ( $y5 * $y6 - $y3 * $y8 )
448 + $y->index(2) * ( $y3 * $y7 - $y4 * $y6 )
449 );
450 }
451 0  
452 0 my($i);
453 my($sum) = zeroes($x->slice('(0),(0)'));
454  
455 0 # Do middle submatrices
456 0 for $i(1..$n-2) {
457 0 ▶ my $el = $x->slice("($i),(0)");
Branch: 2 branches
BranchTrueFalseTotal
if ($el == 0)->all 0 2 2
if ($el == 0)->all 0 0 0
458 0 next if( ($el==0)->all ); # Optimize away unnecessary recursion
459 $sum += $el * (1-2*($i%2)) *
460 determinant($x->slice("0:".($i-1).",1:-1")->
461 append($x->slice(($i+1).":-1,1:-1")));
462 }
463  
464 0 # Do beginning and end submatrices
465 0 $sum += $x->slice("(0),(0)") * determinant($x->slice('1:-1,1:-1'));
466 $sum -= $x->slice("(-1),(0)") * determinant($x->slice('0:-2,1:-1')) * (1 - 2*($n % 2));
467 0  
468 return $sum;
469 }
470  
471 EOD
472  
473 my $TRIANGULAR_REDODIMS = <<'EOF';
474 float n = (sqrtf(1 + 8*$SIZE(m)) - 1)/2;
475 $SIZE(n) = roundf(n);
476 if (fabsf($SIZE(n) - n) > 0.0001)
477 $CROAK("Non-triangular vector size=%"IND_FLAG, $SIZE(m));
478 EOF
479  
480 pp_def("eigens_sym",
481 HandleBad => 0,
482 Pars => '[phys]a(m); [o,phys]ev(n,n); [o,phys]e(n)',
483 RedoDimsCode => $TRIANGULAR_REDODIMS,
484 GenericTypes => ['D'],
485 Code => <<'EOF',
486 extern void eigens( double *A, double *EV, double *E, int N );
487 eigens($P(a), $P(ev), $P(e), $SIZE(n));
488 EOF
489 PMCode => <<'EOF',
490 sub PDL::eigens_sym {
491 my ($x) = @_;
492 my @d = $x->dims;
493 barf "Need real square matrix for eigens_sym"
494 if @d < 2 or $d[0] != $d[1];
495 my ($sym) = 0.5*($x + $x->transpose);
496 my ($err) = PDL::max(abs($sym));
497 barf "Need symmetric component non-zero for eigens_sym" if $err == 0;
498 $err = PDL::max(abs($x-$sym))/$err;
499 warn "Using symmetrized version of the matrix in eigens_sym"
500 if $err > 1e-5 && $PDL::debug;
501 PDL::_eigens_sym_int($sym->squaretotri, my $ev=PDL->null, my $e=PDL->null);
502 return ($ev->transpose, $e) if wantarray;
503 $e; #just eigenvalues
504 }
505 EOF
506 Doc => <<'EOF',
507 =for ref
508  
509 Eigenvalues and -vectors of a symmetric square matrix. If passed
510 an asymmetric matrix, the routine will warn and symmetrize it, by taking
511 the average value. That is, it will solve for 0.5*($a+$a->transpose).
512  
513 It's broadcastable, so if C<$a> is 3x3x100, it's treated as 100 separate 3x3
514 matrices, and both C<$ev> and C<$e> get extra dimensions accordingly.
515  
516 If called in scalar context it hands back only the eigenvalues. Ultimately,
517 it should switch to a faster algorithm in this case (as discarding the
518 eigenvectors is wasteful).
519  
520 The algorithm used is due to J. von Neumann, which was a rediscovery of
521 L<Jacobi's Method|http://en.wikipedia.org/wiki/Jacobi_eigenvalue_algorithm> .
522  
523 The eigenvectors are returned in COLUMNS of the returned PDL. That
524 makes it slightly easier to access individual eigenvectors, since the
525 0th dim of the output PDL runs across the eigenvectors and the 1st dim
526 runs across their components.
527  
528 =for example
529  
530 ($ev,$e) = eigens_sym $x; # Make eigenvector matrix
531 $vector = $ev->slice($n); # Select nth eigenvector as a column-vector
532 $vector = $ev->slice("($n)"); # Select nth eigenvector as a row-vector
533 # or to sort in descending order:
534 $indices = qsorti($ev)->slice("-1:0");
535 $sorted_ev = $ev->slice($indices); # sort values
536 $sorted_e = $e->slice(':', $indices); # sort eigenvectors
537  
538 As of 2.096, the eigenvalues are returned in ascending order.
539  
540 To compare with L<PDL::LinearAlgebra>:
541  
542 use PDL::LinearAlgebra;
543 ($val, $rvec) = msymeigen($A = pdl([3,4], [4,-3]),1,1);
544 print $val->slice(1) * $rvec->slice(1);
545 #[
546 # [ -4.472136]
547 # [ -2.236068]
548 #]
549 print $A x $rvec->slice(1);
550 #[
551 # [ -4.472136]
552 # [ -2.236068]
553 #]
554 ($rvec, $val) = eigens_sym($A); # note return values other way round
555 # otherwise the same
556  
557 =for usage
558  
559 ($ev, $e) = eigens_sym($x); # e-vects & e-values
560 $e = eigens_sym($x); # just eigenvalues
561 EOF
562 );
563  
564 ######################################################################
565 ### eigens
566 ###
567 pp_def("eigens",
568 HandleBad => 0,
569 Pars => '[phys]a(n,n); complex [o,phys]ev(n,n); complex [o,phys]e(n)',
570 GenericTypes => ['D'],
571 CHeader => '#include "eigen.h"',
572 Code => <<'EOF',
573 char *ret = Eigen($SIZE(n), $P(a), 20*$SIZE(n), 1e-13, $P(e), $P(ev));
574 if (ret) $CROAK("%s", ret);
575 EOF
576 PMCode => <<'EOF',
577 sub PDL::eigens {
578 my ($x) = @_;
579 my @d = $x->dims;
580 barf "Need real square matrix for eigens"
581 if @d < 2 or $d[0] != $d[1];
582 my $deviation = PDL::max(abs($x - $x->transpose))/PDL::max(abs($x));
583 if ( $deviation <= 1e-5 ) {
584 PDL::_eigens_sym_int($x->squaretotri, my $ev=PDL->null, my $e=PDL->null);
585 return $ev->transpose, $e if wantarray;
586 return $e; #just eigenvalues
587 } else {
588 PDL::_eigens_int($x, my $ev=PDL->null, my $e=PDL->null);
589 return $ev, $e if wantarray;
590 return $e; #just eigenvalues
591 }
592 }
593 EOF
594 Doc => <<'EOF',
595 =for ref
596  
597 Complex eigenvalues and -vectors of a real square matrix.
598  
599 (See also L<"eigens_sym"|/eigens_sym>, for eigenvalues and -vectors
600 of a real, symmetric, square matrix).
601  
602 The eigens function will attempt to compute the eigenvalues and
603 eigenvectors of a square matrix with real components. If the matrix
604 is symmetric, the same underlying code as L<"eigens_sym"|/eigens_sym>
605 is used. If asymmetric, the eigenvalues and eigenvectors are computed
606 with algorithms from the sslib library. These are a slightly modified
607 version of EISPACK's C<rg> code.
608  
609 Not all square matrices are diagonalizable. If you feed in a
610 non-diagonalizable matrix, then the algorithm may fail, in which case
611 an exception will be thrown.
612  
613 C<eigens> is broadcastable, so you can solve 100 eigenproblems by
614 feeding in a 3x3x100 array. Both C<$ev> and C<$e> get extra dimensions accordingly.
615  
616 If called in scalar context C<eigens> hands back only the eigenvalues. This
617 is somewhat wasteful, as it calculates the eigenvectors anyway.
618  
619 The eigenvectors are returned in COLUMNS of the returned PDL (ie the
620 the 0 dimension). That makes it slightly easier to access individual
621 eigenvectors, since the 0th dim of the output PDL runs across the
622 eigenvectors and the 1st dim runs across their components.
623  
624 =for example
625  
626 ($ev,$e) = eigens $x; # Make eigenvector matrix
627 $vector = $ev->slice($n); # Select nth eigenvector as a column-vector
628 $vector = $ev->slice("($n)"); # Select nth eigenvector as a row-vector
629 # or to sort in descending order:
630 $indices = qsorti($ev)->slice("-1:0");
631 $sorted_ev = $ev->slice($indices); # sort values
632 $sorted_e = $e->slice(':', $indices); # sort eigenvectors
633  
634 To compare with L<PDL::LinearAlgebra>:
635  
636 use PDL::LinearAlgebra;
637 ($val, $lvec, $rvec) = meigen($A = pdl([4,-1], [2,1]),1,1);
638 print $val->slice(1) * $rvec->slice(1);
639 #[
640 # [0.894427190999916]
641 # [ 1.78885438199983]
642 #]
643 print $A x $rvec->slice(1);
644 #[
645 # [0.894427190999916]
646 # [ 1.78885438199983]
647 #]
648 ($rvec, $val) = eigens($A); # note return values other way round
649 # otherwise the same
650  
651 =for usage
652  
653 ($ev, $e) = eigens($x); # e'vects & e'vals
654 $e = eigens($x); # just eigenvalues
655 EOF
656 );
657  
658 pp_def("svd",
659 HandleBad => 0,
660 Pars => 'a(n,m);
661 [o]u(nUCol=CALC($COMP(full) ? $SIZE(m) : PDLMIN($SIZE(m),$SIZE(n))),m);
662 [o]s(nSV=CALC(PDLMIN($SIZE(m),$SIZE(n))));
663 [o]v(nVCol=CALC($COMP(full) ? $SIZE(n) : PDLMIN($SIZE(m),$SIZE(n))),n);
664 [t]sbig(nSVbig=CALC($COMP(full) ? PDLMAX($SIZE(m),$SIZE(n)) : 0));
665 [t]vbig(vbigcols=CALC(
666 $COMP(full) ? PDLMAX($SIZE(n),$SIZE(m)) : 0
667 ),vbigrows=CALC(
668 PDLMAX($SIZE(n),$SIZE(m))
669 ));
670 [t]w(wcols=CALC(
671 $COMP(full) ? PDLMAX($SIZE(m),$SIZE(n)) :
672 $SIZE(m) >= $SIZE(n) ? 0 :
673 $SIZE(m)
674 ),wrows=CALC(
675 ($COMP(full) && $SIZE(m) >= $SIZE(n)) ? $SIZE(m) : $SIZE(n)
676 ));',
677 OtherPars => 'int full',
678 OtherParsDefaults => { full => 0 },
679 GenericTypes => ['D'],
680 CHeader => 'void SVD(double *U, double *V, double *S, int nRow, int nCol);',
681 Code => <<'EOF',
682 char is_wide = $SIZE(m) < $SIZE(n);
683 $GENERIC() *u_ptr = NULL, *v_ptr = NULL, *sv_ptr = NULL;
684 int in_rows = PDLMAX($SIZE(n),$SIZE(m)),
685 in_cols = $COMP(full) ? PDLMAX($SIZE(n),$SIZE(m)) : PDLMIN($SIZE(n),$SIZE(m));
686 broadcastloop %{
687 if ($COMP(full)) {
688 sv_ptr = $P(sbig);
689 u_ptr = $P(w);
690 v_ptr = $P(vbig);
691 if (is_wide) {
692 loop (wrows,wcols) %{ $w() = wrows < $SIZE(m) ? $a(n=>wcols,m=>wrows) : 0; %}
693 } else {
694 loop (wrows,wcols) %{ $w() = wrows < $SIZE(n) ? $a(n=>wrows,m=>wcols) : 0; %}
695 }
696 } else {
697 sv_ptr = $P(s);
698 if (is_wide) {
699 u_ptr = $P(w);
700 v_ptr = $P(u);
701 loop (wrows,wcols) %{ $w() = $a(m=>wcols,n=>wrows); %}
702 } else {
703 u_ptr = $P(u);
704 v_ptr = $P(v);
705 loop (m,nUCol) %{ $u() = $a(n=>nUCol); %}
706 }
707 }
708 SVD(u_ptr, v_ptr, sv_ptr, in_rows, in_cols);
709 if ($COMP(full)) {
710 loop (nSV) %{ $s() = $sbig(nSVbig=>nSV); %}
711 if (is_wide) {
712 loop (m,nUCol) %{ $u() = $w(wcols=>nUCol,wrows=>m); %}
713 loop (n,nVCol) %{ $v() = $vbig(vbigcols=>nVCol,vbigrows=>n); %}
714 } else {
715 loop (m,nUCol) %{ $u() = $vbig(vbigcols=>nUCol,vbigrows=>m); %}
716 loop (n,nVCol) %{ $v() = $w(wcols=>nVCol,wrows=>n); %}
717 }
718 } else {
719 if (is_wide)
720 loop (n,nVCol) %{ $v() = $w(wcols=>nVCol,wrows=>n); %}
721 }
722 %}
723 EOF
724 Doc => <<'EOF',
725 =for ref
726  
727 Singular value decomposition of a matrix.
728  
729 Given an m x n matrix C<$a> that has m rows and n columns,
730 C<svd> computes matrices C<$u> and C<$v>, and a vector of the singular
731 values C<$s>.
732 C<svd> computes the "thin" (or "economy") SVD of C<$a>, such that C<$u> is m
733 x min(m,n), C<$v> is min(m,n) x n, and there are min(m,n) singular values.
734 As of 2.104, you do not need to transpose this yourself to ensure
735 the input is "tall" (or square).
736 The original matrix can be reconstructed as follows:
737  
738 ($u,$s,$v) = svd($x);
739 $x_copy = $u x stretcher($s) x $v->transpose;
740  
741 Also as of 2.104, you can now request the full SVD by passing
742 a true value as the C<$full> parameter. In that case, C<$u> will
743 be m x m, and C<$v> will be n x n. To reconstruct the original
744 input, use:
745  
746 ($u,$s,$v) = svd($in, 1);
747 $in_copy = $u x gurney($s, $in->dims) x $v->t; # same as $in
748  
749 If m==n, C<$u> and C<$v> can be thought of as rotation matrices that
750 convert from the original matrix's singular coordinates to final
751 coordinates, and from original coordinates to singular coordinates,
752 respectively, and C<stretcher($s)> is a diagonal scaling matrix.
753  
754 This uses J.C. Nash's implementation of a one-sided Jacobi rotation.
755 Use LAPACK (i.e. L<PDL::LinearAlgebra>) for better performance if
756 you need it.
757  
758 EXAMPLE
759  
760 The computing literature has loads of examples of how to use SVD.
761 Here's a trivial example (used in L<PDL::Transform::map|PDL::Transform/map>)
762 of how to make a matrix less, er, singular, without changing the
763 orientation of the ellipsoid of transformation:
764  
765 { my($r1,$s,$r2) = svd $x;
766 $s++; # fatten all singular values
767 $r2 *= $s; # implicit broadcasting for cheap mult.
768 $x .= $r2 x $r1; # a gets r2 x ess x r1
769 }
770 EOF
771 );
772  
773 ######################################################################
774 pp_add_exported('','lu_decomp');
775 pp_addpm(<<'EOD');
776  
777 =head2 lu_decomp
778  
779 =for sig
780  
781 Signature: (a(m,m); [o]lu(m,m); [o]perm(m); [o]parity)
782  
783 =for ref
784  
785 LU decompose a matrix, with row permutation
786  
787 =for usage
788  
789 ($lu, $perm, $parity) = lu_decomp($x);
790 $lu = lu_decomp($x, $perm, $par); # $perm and $par are outputs!
791 lu_decomp($x->inplace,$perm,$par); # Everything in place.
792  
793 =for description
794  
795 C<lu_decomp> returns an LU decomposition of a square matrix,
796 using Crout's method with partial pivoting. It's ported
797 from I<Numerical Recipes>. The partial pivoting keeps it
798 numerically stable but means a little more overhead from
799 broadcasting.
800  
801 C<lu_decomp> decomposes the input matrix into matrices L and
802 U such that LU = A, L is a subdiagonal matrix, and U is a
803 superdiagonal matrix. By convention, the diagonal of L is
804 all 1's.
805  
806 The single output matrix contains all the variable elements
807 of both the L and U matrices, stacked together. Because the
808 method uses pivoting (rearranging the lower part of the
809 matrix for better numerical stability), you have to permute
810 input vectors before applying the L and U matrices. The
811 permutation is returned either in the second argument or, in
812 list context, as the second element of the list. You need
813 the permutation for the output to make any sense, so be sure
814 to get it one way or the other.
815  
816 LU decomposition is the answer to a lot of matrix questions,
817 including inversion and determinant-finding, and C<lu_decomp>
818 is used by L</inv>.
819  
820 If you pass in C<$perm> and C<$parity>, they either must be
821 predeclared PDLs of the correct size ($perm is an n-vector,
822 C<$parity> is a scalar) or scalars.
823  
824 If the matrix is singular, then the LU decomposition might
825 not be defined; in those cases, C<lu_decomp> silently returns
826 undef. Some singular matrices LU-decompose just fine, and
827 those are handled OK but give a zero determinant (and hence
828 can't be inverted).
829  
830 C<lu_decomp> uses pivoting, which rearranges the values in the
831 matrix for more numerical stability. This makes it really
832 good for large and even near-singular matrices. There is
833 a non-pivoting version C<lu_decomp2> available which is
834 from 5 to 60 percent faster for typical problems at
835 the expense of failing to compute a result in some cases.
836  
837 Now that the C<lu_decomp> is broadcasted, it is the recommended
838 LU decomposition routine. It no longer falls back to C<lu_decomp2>.
839  
840 C<lu_decomp> is ported from I<Numerical Recipes> to PDL. It
841 should probably be implemented in C.
842  
843 =cut
844  
845 *PDL::lu_decomp = \&lu_decomp;
846 71 ▶ 
Subroutine lu_decomp: called CC=21 SCAR=49.6
Pod documented
847 0 ▶sub lu_decomp {
Subroutine lu_decomp: not called CC=21 SCAR=49.6
Pod documented
848 0 my($in) = shift;
849 0 my($permute) = shift;
850 0 my($parity) = shift;
851 my($sing_ok) = shift;
852 0  
853 my $TINY = 1e-30;
854 0 ▶ 
Branch: 2 branches
BranchTrueFalseTotal
if not UNIVERSAL::isa($in, "PDL") or $in->ndims < 2 or $in->dim(0) != $in->dim(1) 0 71 71
if not UNIVERSAL::isa($in, "PDL") or $in->ndims < 2 or $in->dim(0) != $in->dim(1) 0 0 0
Condition16%2/12
not UNIVERSAL::isa($in, "PDL") or $in->ndims < 2 or $in->dim(0) != $in->dim(1)
l!l&&r!l&&!r
0071
not UNIVERSAL::isa($in, "PDL") or $in->ndims < 2
l!l&&r!l&&!r
0071
not UNIVERSAL::isa($in, "PDL") or $in->ndims < 2 or $in->dim(0) != $in->dim(1)
l!l&&r!l&&!r
000
not UNIVERSAL::isa($in, "PDL") or $in->ndims < 2
l!l&&r!l&&!r
000
MC/DC0%0/3
not UNIVERSAL::isa($in, "PDL") or $in->ndims < 2 or $in->dim(0) != $in->dim(1)
not UNIVERSAL::isa($in, "PDL") $in->ndims < 2 $in->dim(0) != $in->dim(1)
MC/DC0%0/3
not UNIVERSAL::isa($in, "PDL") or $in->ndims < 2 or $in->dim(0) != $in->dim(1)
not UNIVERSAL::isa($in, "PDL") $in->ndims < 2 $in->dim(0) != $in->dim(1)
Truth table25%1/4
not(A) or B or C
A= not UNIVERSAL::isa($in, "PDL")B= $in->ndims < 2C= $in->dim(0) != $in->dim(1)
ABCresult
1XX1
01X1
0011
0000
Truth table0%0/4
not(A) or B or C
A= not UNIVERSAL::isa($in, "PDL")B= $in->ndims < 2C= $in->dim(0) != $in->dim(1)
ABCresult
1XX1
01X1
0011
0000
855 barf("lu_decomp requires a square (2D) PDL\n")
856 if(!UNIVERSAL::isa($in,'PDL') ||
857 $in->ndims < 2 ||
858 $in->dim(0) != $in->dim(1));
859 0  
860 0 my($n) = $in->dim(0);
861 my($n1) = $n; $n1--;
862 0  
863 0 ▶ my($inplace) = $in->is_inplace;
Branch: 2 branches
BranchTrueFalseTotal
$inplace ? : 0 71 71
$inplace ? : 0 0 0
864 my($out) = ($inplace) ? $in : $in->copy;
865 0 ▶ 
Branch: 2 branches
BranchTrueFalseTotal
if (defined $permute) { } 0 71 71
if (defined $permute) { } 0 0 0
866 0 ▶ if(defined $permute) {
Branch: 2 branches
BranchTrueFalseTotal
if not UNIVERSAL::isa($permute, "PDL") or $permute->ndims != 1 or $permute->dim(0) != $out->dim(0) 0 0 0
if not UNIVERSAL::isa($permute, "PDL") or $permute->ndims != 1 or $permute->dim(0) != $out->dim(0) 0 0 0
Condition0%0/12
not UNIVERSAL::isa($permute, "PDL") or $permute->ndims != 1 or $permute->dim(0) != $out->dim(0)
l!l&&r!l&&!r
000
not UNIVERSAL::isa($permute, "PDL") or $permute->ndims != 1
l!l&&r!l&&!r
000
not UNIVERSAL::isa($permute, "PDL") or $permute->ndims != 1 or $permute->dim(0) != $out->dim(0)
l!l&&r!l&&!r
000
not UNIVERSAL::isa($permute, "PDL") or $permute->ndims != 1
l!l&&r!l&&!r
000
MC/DC0%0/3
not UNIVERSAL::isa($permute, "PDL") or $permute->ndims != 1 or $permute->dim(0) != $out->dim(0)
not UNIVERSAL::isa($permute, "PDL") $permute->ndims != 1 $permute->dim(0) != $out->dim(0)
MC/DC0%0/3
not UNIVERSAL::isa($permute, "PDL") or $permute->ndims != 1 or $permute->dim(0) != $out->dim(0)
not UNIVERSAL::isa($permute, "PDL") $permute->ndims != 1 $permute->dim(0) != $out->dim(0)
Truth table0%0/4
not(A) or B or C
A= not UNIVERSAL::isa($permute, "PDL")B= $permute->ndims != 1C= $permute->dim(0) != $out->dim(0)
ABCresult
1XX1
01X1
0011
0000
Truth table0%0/4
not(A) or B or C
A= not UNIVERSAL::isa($permute, "PDL")B= $permute->ndims != 1C= $permute->dim(0) != $out->dim(0)
ABCresult
1XX1
01X1
0011
0000
867 barf('lu_decomp: permutation vector must match the matrix')
868 if(!UNIVERSAL::isa($permute,'PDL') ||
869 $permute->ndims != 1 ||
870 0 $permute->dim(0) != $out->dim(0));
871 $permute .= PDL->xvals($in->dim(0));
872 0 } else {
873 $permute = $in->slice("(0)")->xvals;
874 }
875 0 ▶ 
Branch: 2 branches
BranchTrueFalseTotal
if (defined $parity) { } 0 71 71
if (defined $parity) { } 0 0 0
876 0 ▶ if(defined $parity) {
Branch: 2 branches
BranchTrueFalseTotal
if not UNIVERSAL::isa($parity, "PDL") or $parity->dim(0) != 1 0 0 0
if not UNIVERSAL::isa($parity, "PDL") or $parity->dim(0) != 1 0 0 0
Condition0%0/6
not UNIVERSAL::isa($parity, "PDL") or $parity->dim(0) != 1
l!l&&r!l&&!r
000
not UNIVERSAL::isa($parity, "PDL") or $parity->dim(0) != 1
l!l&&r!l&&!r
000
MC/DC0%0/2
not UNIVERSAL::isa($parity, "PDL") or $parity->dim(0) != 1
not UNIVERSAL::isa($parity, "PDL") $parity->dim(0) != 1
MC/DC0%0/2
not UNIVERSAL::isa($parity, "PDL") or $parity->dim(0) != 1
not UNIVERSAL::isa($parity, "PDL") $parity->dim(0) != 1
Truth table0%0/3
not(A) or B
A= not UNIVERSAL::isa($parity, "PDL")B= $parity->dim(0) != 1
ABresult
1X1
011
000
Truth table0%0/3
not(A) or B
A= not UNIVERSAL::isa($parity, "PDL")B= $parity->dim(0) != 1
ABresult
1X1
011
000
877 barf('lu_decomp: parity must be a scalar PDL')
878 if(!UNIVERSAL::isa($parity,'PDL') ||
879 0 $parity->dim(0) != 1);
880 $parity .= 1.0;
881 0 } else {
882 $parity = $in->slice('(0),(0)')->ones;
883 }
884 0  
885 my($scales) = $in->copy->abs->maximum; # elementwise by rows
886 0 ▶ 
Branch: 2 branches
BranchTrueFalseTotal
if (($scales == 0)->sum) 0 71 71
if (($scales == 0)->sum) 0 0 0
887 0 if(($scales==0)->sum) {
888 return undef;
889 }
890  
891 0 # Some holding tanks
892 0 ▶ my($tmprow) = $out->slice('(0)')->zeroes;
Branch: 2 branches
BranchTrueFalseTotal
if $tmprow->type < double() 0 71 71
if $tmprow->type < double() 0 0 0
893 0 $tmprow = $tmprow->double if $tmprow->type < double;
894 my($tmpval) = $tmprow->slice('(0)')->sever;
895 0  
896 0 my($col,$row);
897 0 for $col(0..$n1) {
898 0 ▶ for $row(1..$n1) {
Branch: 2 branches
BranchTrueFalseTotal
$row < $col ? : 27 215 242
$row < $col ? : 0 0 0
899 0 ▶ my($klim) = $row<$col ? $row : $col;
Branch: 2 branches
BranchTrueFalseTotal
if ($klim > 0) 148 94 242
if ($klim > 0) 0 0 0
900 0 if($klim > 0) {
901 0 $klim--;
902 0 my($el) = $out->index2d($col,$row);
903 $el -= ( $out->slice("($col),0:$klim") *
904 $out->slice("0:$klim,($row)") )->sumover;
905 }
906  
907 }
908  
909 # Figure a_ij, with pivoting
910 0 ▶ 
Branch: 2 branches
BranchTrueFalseTotal
if ($col < $n1) 94 70 164
if ($col < $n1) 0 0 0
911 if($col < $n1) {
912 0 # Find the maximum value in the rest of the row
913 0 my $sl = $out->slice("($col),$col:$n1");
914 0 my $wh = $sl->abs->maximum_ind;
915 my $big = $sl->index($wh)->sever;
916  
917 # Permute if necessary to make the diagonal the maximum
918 # if($wh != 0)
919 0 { # Permute rows to place maximum element on diagonal.
920 my $whc = $wh+$col;
921 0  
922 0 my $sl1 = $out->mv(1,0)->index($whc->slice("*$n"));
923 0 my $sl2 = $out->slice(":,($col)");
924 $tmprow .= $sl1; $sl1 .= $sl2; $sl2 .= $tmprow;
925 0  
926 0 $sl1 = $permute->index($whc);
927 0 $sl2 = $permute->index($col);
928 $tmpval .= $sl1; $sl1 .= $sl2; $sl2 .= $tmpval;
929 0  
930 $parity->where($wh>0) *= -1.0;
931 }
932  
933 0 # LAPACK cgetrf does not try fix singularity so nor do we, even though NR does
934 0 ▶ my $notbig = $big->where(abs($big) < $TINY);
Branch: 2 branches
BranchTrueFalseTotal
unless $notbig->isempty 1 93 94
unless $notbig->isempty 0 0 0
935 return if !$notbig->isempty;
936  
937 0 # Divide by the diagonal element (which is now the largest element)
938 0 my $tout;
939 ($tout = $out->slice("($col),".($col+1).":$n1")) /= $big->slice('*1');
940 } # end of pivoting part
941 } # end of column loop
942 0 ▶ 
Branch: 2 branches
BranchTrueFalseTotal
wantarray ? : 70 0 70
wantarray ? : 0 0 0
943 wantarray ? ($out,$permute,$parity) : $out;
944 }
945  
946 EOD
947  
948 ######################################################################
949 pp_add_exported('','lu_decomp2');
950 pp_addpm(<<'EOD');
951  
952 =head2 lu_decomp2
953  
954 =for sig
955  
956 Signature: (a(m,m); [o]lu(m,m))
957  
958 =for ref
959  
960 LU decompose a matrix, with no row permutation
961  
962 =for usage
963  
964 ($lu, $perm, $parity) = lu_decomp2($x);
965  
966 $lu = lu_decomp2($x,$perm,$parity); # or
967 $lu = lu_decomp2($x); # $perm and $parity are optional
968  
969 lu_decomp($x->inplace,$perm,$parity); # or
970 lu_decomp($x->inplace); # $perm and $parity are optional
971  
972 =for description
973  
974 C<lu_decomp2> works just like L</lu_decomp>, but it does B<no>
975 pivoting at all. For compatibility with L</lu_decomp>, it
976 will give you a permutation list and a parity scalar if you ask
977 for them -- but they are always trivial.
978  
979 Because C<lu_decomp2> does not pivot, it is numerically B<unstable> --
980 that means it is less precise than L</lu_decomp>, particularly for
981 large or near-singular matrices. There are also specific types of
982 non-singular matrices that confuse it (e.g. ([0,-1,0],[1,0,0],[0,0,1]),
983 which is a 90 degree rotation matrix but which confuses C<lu_decomp2>).
984  
985 On the other hand, if you want to invert rapidly a few hundred thousand
986 small matrices and don't mind missing one or two, it could be the ticket.
987 It can be up to 60% faster at the expense of possible failure of the
988 decomposition for some of the input matrices.
989  
990 The output is a single matrix that contains the LU decomposition of C<$a>;
991 you can even do it in-place, thereby destroying C<$a>, if you want. See
992 L</lu_decomp> for more information about LU decomposition.
993  
994 C<lu_decomp2> is ported from I<Numerical Recipes> into PDL.
995  
996 =cut
997  
998 *PDL::lu_decomp2 = \&lu_decomp2;
999 0 ▶ 
Subroutine lu_decomp2: not called CC=18 SCAR=58.3
Pod documented
1000 0 ▶sub lu_decomp2 {
Subroutine lu_decomp2: not called CC=18 SCAR=58.3
Pod documented
1001 0 my($in) = shift;
1002 0 my($perm) = shift;
1003 my($par) = shift;
1004 0  
1005 my($sing_ok) = shift;
1006 0  
1007 my $TINY = 1e-30;
1008 0 ▶ 
Branch: 2 branches
BranchTrueFalseTotal
if not UNIVERSAL::isa($in, "PDL") or $in->ndims < 2 or $in->dim(0) != $in->dim(1) 0 0 0
if not UNIVERSAL::isa($in, "PDL") or $in->ndims < 2 or $in->dim(0) != $in->dim(1) 0 0 0
Condition0%0/12
not UNIVERSAL::isa($in, "PDL") or $in->ndims < 2 or $in->dim(0) != $in->dim(1)
l!l&&r!l&&!r
000
not UNIVERSAL::isa($in, "PDL") or $in->ndims < 2
l!l&&r!l&&!r
000
not UNIVERSAL::isa($in, "PDL") or $in->ndims < 2 or $in->dim(0) != $in->dim(1)
l!l&&r!l&&!r
000
not UNIVERSAL::isa($in, "PDL") or $in->ndims < 2
l!l&&r!l&&!r
000
MC/DC0%0/3
not UNIVERSAL::isa($in, "PDL") or $in->ndims < 2 or $in->dim(0) != $in->dim(1)
not UNIVERSAL::isa($in, "PDL") $in->ndims < 2 $in->dim(0) != $in->dim(1)
MC/DC0%0/3
not UNIVERSAL::isa($in, "PDL") or $in->ndims < 2 or $in->dim(0) != $in->dim(1)
not UNIVERSAL::isa($in, "PDL") $in->ndims < 2 $in->dim(0) != $in->dim(1)
Truth table0%0/4
not(A) or B or C
A= not UNIVERSAL::isa($in, "PDL")B= $in->ndims < 2C= $in->dim(0) != $in->dim(1)
ABCresult
1XX1
01X1
0011
0000
Truth table0%0/4
not(A) or B or C
A= not UNIVERSAL::isa($in, "PDL")B= $in->ndims < 2C= $in->dim(0) != $in->dim(1)
ABCresult
1XX1
01X1
0011
0000
1009 barf("lu_decomp2 requires a square (2D) PDL\n")
1010 if(!UNIVERSAL::isa($in,'PDL') ||
1011 $in->ndims < 2 ||
1012 $in->dim(0) != $in->dim(1));
1013 0  
1014 0 my($n) = $in->dim(0);
1015 my($n1) = $n; $n1--;
1016 0  
1017 0 ▶ my($inplace) = $in->is_inplace;
Branch: 2 branches
BranchTrueFalseTotal
$inplace ? : 0 0 0
$inplace ? : 0 0 0
1018 my($out) = ($inplace) ? $in : $in->copy;
1019 0 ▶ 
Branch: 2 branches
BranchTrueFalseTotal
if (defined $perm) { } 0 0 0
if (defined $perm) { } 0 0 0
1020 0 ▶ 
Branch: 2 branches
BranchTrueFalseTotal
if not UNIVERSAL::isa($perm, "PDL") or $perm->ndims != 1 or $perm->dim(0) != $out->dim(0) 0 0 0
if not UNIVERSAL::isa($perm, "PDL") or $perm->ndims != 1 or $perm->dim(0) != $out->dim(0) 0 0 0
Condition0%0/12
not UNIVERSAL::isa($perm, "PDL") or $perm->ndims != 1 or $perm->dim(0) != $out->dim(0)
l!l&&r!l&&!r
000
not UNIVERSAL::isa($perm, "PDL") or $perm->ndims != 1
l!l&&r!l&&!r
000
not UNIVERSAL::isa($perm, "PDL") or $perm->ndims != 1 or $perm->dim(0) != $out->dim(0)
l!l&&r!l&&!r
000
not UNIVERSAL::isa($perm, "PDL") or $perm->ndims != 1
l!l&&r!l&&!r
000
MC/DC0%0/3
not UNIVERSAL::isa($perm, "PDL") or $perm->ndims != 1 or $perm->dim(0) != $out->dim(0)
not UNIVERSAL::isa($perm, "PDL") $perm->ndims != 1 $perm->dim(0) != $out->dim(0)
MC/DC0%0/3
not UNIVERSAL::isa($perm, "PDL") or $perm->ndims != 1 or $perm->dim(0) != $out->dim(0)
not UNIVERSAL::isa($perm, "PDL") $perm->ndims != 1 $perm->dim(0) != $out->dim(0)
Truth table0%0/4
not(A) or B or C
A= not UNIVERSAL::isa($perm, "PDL")B= $perm->ndims != 1C= $perm->dim(0) != $out->dim(0)
ABCresult
1XX1
01X1
0011
0000
Truth table0%0/4
not(A) or B or C
A= not UNIVERSAL::isa($perm, "PDL")B= $perm->ndims != 1C= $perm->dim(0) != $out->dim(0)
ABCresult
1XX1
01X1
0011
0000
1021 if(defined $perm) {
1022 barf('lu_decomp2: permutation vector must match the matrix')
1023 if(!UNIVERSAL::isa($perm,'PDL') ||
1024 0 $perm->ndims != 1 ||
1025 $perm->dim(0) != $out->dim(0));
1026 0 $perm .= PDL->xvals($in->dim(0));
1027 } else {
1028 $perm = PDL->xvals($in->dim(0));
1029 0 ▶ }
Branch: 2 branches
BranchTrueFalseTotal
if (defined $par) { } 0 0 0
if (defined $par) { } 0 0 0
1030 0 ▶ 
Branch: 2 branches
BranchTrueFalseTotal
if not UNIVERSAL::isa($par, "PDL") or $par->nelem != 1 0 0 0
if not UNIVERSAL::isa($par, "PDL") or $par->nelem != 1 0 0 0
Condition0%0/6
not UNIVERSAL::isa($par, "PDL") or $par->nelem != 1
l!l&&r!l&&!r
000
not UNIVERSAL::isa($par, "PDL") or $par->nelem != 1
l!l&&r!l&&!r
000
MC/DC0%0/2
not UNIVERSAL::isa($par, "PDL") or $par->nelem != 1
not UNIVERSAL::isa($par, "PDL") $par->nelem != 1
MC/DC0%0/2
not UNIVERSAL::isa($par, "PDL") or $par->nelem != 1
not UNIVERSAL::isa($par, "PDL") $par->nelem != 1
Truth table0%0/3
not(A) or B
A= not UNIVERSAL::isa($par, "PDL")B= $par->nelem != 1
ABresult
1X1
011
000
Truth table0%0/3
not(A) or B
A= not UNIVERSAL::isa($par, "PDL")B= $par->nelem != 1
ABresult
1X1
011
000
1031 if(defined $par) {
1032 barf('lu_decomp: parity must be a scalar PDL')
1033 0 if(!UNIVERSAL::isa($par,'PDL') ||
1034 $par->nelem != 1);
1035 0 $par .= 1.0;
1036 } else {
1037 $par = pdl(1.0);
1038 0 }
1039  
1040 0 my $diagonal = $out->diagonal(0,1);
1041 0  
1042 0 my($col,$row);
1043 0 ▶ for $col(0..$n1) {
Branch: 2 branches
BranchTrueFalseTotal
$row < $col ? : 0 0 0
$row < $col ? : 0 0 0
1044 0 ▶ for $row(1..$n1) {
Branch: 2 branches
BranchTrueFalseTotal
if ($klim > 0) 0 0 0
if ($klim > 0) 0 0 0
1045 0 my($klim) = $row<$col ? $row : $col;
1046 0 if($klim > 0) {
1047 $klim--;
1048 0 my($el) = $out->index2d($col,$row);
1049  
1050 $el -= ( $out->slice("($col),0:$klim") *
1051 $out->slice("0:$klim,($row)") )->sumover;
1052 }
1053  
1054 }
1055 0 ▶ 
Branch: 2 branches
BranchTrueFalseTotal
if ($col < $n1) 0 0 0
if ($col < $n1) 0 0 0
1056 # Figure a_ij, with no pivoting
1057 0 if($col < $n1) {
1058 # Divide the rest of the column by the diagonal element
1059 $out->slice("($col),".($col+1).":$n1") /= $diagonal->index($col)->dummy(0,$n1-$col);
1060 }
1061  
1062 0 ▶ } # end of column loop
Branch: 2 branches
BranchTrueFalseTotal
wantarray ? : 0 0 0
wantarray ? : 0 0 0
1063  
1064 wantarray ? ($out,$perm,$par) : $out;
1065 }
1066  
1067 EOD
1068  
1069 ######################################################################
1070 pp_add_exported('','lu_backsub');
1071 pp_addpm(<<'EOD');
1072  
1073 =head2 lu_backsub
1074  
1075 =for sig
1076  
1077 Signature: (lu(m,m); perm(m); b(m))
1078  
1079 =for ref
1080  
1081 Solve A x = B for matrix A, by back substitution into A's LU decomposition.
1082  
1083 =for usage
1084  
1085 ($lu,$perm,$par) = lu_decomp($A);
1086  
1087 $x = lu_backsub($lu,$perm,$par,$A); # or
1088 $x = lu_backsub($lu,$perm,$B); # $par is not required for lu_backsub
1089  
1090 lu_backsub($lu,$perm,$B->inplace); # modify $B in-place
1091  
1092 $x = lu_backsub(lu_decomp($A),$B); # (ignores parity value from lu_decomp)
1093  
1094 # starting from square matrix A and columns matrix B, with mathematically
1095 # correct dimensions
1096 $A = identity(4) + ones(4, 4);
1097 $A->slice('2,0') .= 0; # break symmetry to see if need transpose
1098 $B = sequence(2, 4);
1099 # all these functions take B as rows, interpret as though notional columns
1100 # mathematically confusing but can't change as back-compat and also
1101 # familiar to Fortran users, so just transpose inputs and outputs
1102  
1103 # using lu_backsub
1104 ($lu,$perm,$par) = lu_decomp($A);
1105 $x = lu_backsub($lu,$perm,$par, $B->transpose)->transpose;
1106  
1107 # using simq
1108 # remove all active dims
1109 @A_dims = $A->dims; @B_dims = $B->transpose->dims;
1110 splice @A_dims, 0, 2; splice @B_dims, 0, 1;
1111 @broadcast = PDL::Core::dims_filled(\@A_dims, \@B_dims);
1112 # simq modifies A, so need 1 copy per broadcast else non-first run has wrong A
1113 ($x) = simq($A->dupN(1,1,map +($A_dims[$_]//1)==1?$broadcast[$_]:1, 0..$#broadcast)->copy, $B->transpose, 0);
1114 $x = $x->transpose;
1115  
1116 # or with PDL::LinearAlgebra wrappers of LAPACK
1117 $x = msolve($A, $B);
1118  
1119 # or with LAPACK
1120 use PDL::LinearAlgebra::Real;
1121 getrf($lu=$A->copy, $ipiv=null, $info=null);
1122 getrs($lu, 1, $x=$B->transpose->copy, $ipiv, $info=null); # again, need transpose
1123 $x=$x->transpose;
1124  
1125 # or with GSL
1126 use PDL::GSL::LINALG;
1127 LU_decomp(my $lu=$A->copy, my $p=null, my $signum=null);
1128 # $B and $x, first dim is because GSL treats as vector, higher dims broadcast
1129 # so we transpose in and back out
1130 LU_solve($lu, $p, $B->transpose, my $x=null);
1131 $x=$x->transpose;
1132  
1133 # proof of the pudding is in the eating:
1134 print $A x $x;
1135  
1136 =for description
1137  
1138 Given the LU decomposition of a square matrix (from L</lu_decomp>),
1139 C<lu_backsub> does back substitution into the matrix to solve
1140 C<a x = b> for given vector C<b>. It is separated from the
1141 C<lu_decomp> method so that you can call the cheap C<lu_backsub>
1142 multiple times and not have to do the expensive LU decomposition
1143 more than once.
1144  
1145 C<lu_backsub> acts on single vectors and broadcasts in the usual
1146 way, which means that it treats C<$y> as the I<transpose>
1147 of the input. If you want to process a matrix, you must
1148 hand in the I<transpose> of the matrix, and then transpose
1149 the output when you get it back. that is because pdls are
1150 indexed by (col,row), and matrices are (row,column) by
1151 convention, so a 1-D pdl corresponds to a row vector, not a
1152 column vector.
1153  
1154 If C<$lu> is dense and you have more than a few points to
1155 solve for, it is probably cheaper to find C<a^-1> with
1156 L</inv>, and just multiply C<x = a^-1 b>.) in fact,
1157 L</inv> works by calling C<lu_backsub> with the identity
1158 matrix.
1159  
1160 C<lu_backsub> is ported from section 2.3 of I<Numerical Recipes>.
1161 It is written in PDL but should probably be implemented in C.
1162  
1163 =cut
1164  
1165 *PDL::lu_backsub = \&lu_backsub;
1166 65 ▶ 
Subroutine lu_backsub: called CC=27 SCAR=54.5
Pod documented
1167 0 ▶sub lu_backsub {
Subroutine lu_backsub: not called CC=27 SCAR=54.5
Pod documented
1168 0 ▶ my ($lu, $perm, $y, $par);
Branch: 2 branches
BranchTrueFalseTotal
if $PDL::debug 0 65 65
if $PDL::debug 0 0 0
1169 0 ▶ print STDERR "lu_backsub: entering debug version...\n" if $PDL::debug;
Branch: 4 branches
BranchTrueFalseTotal
if (@_ == 3) { } 2 63 65
elsif (@_ == 4) { } 63 0 63
if (@_ == 3) { } 0 0 0
elsif (@_ == 4) { } 0 0 0
1170 0 if(@_==3) {
1171 ($lu, $perm, $y) = @_;
1172 0 } elsif(@_==4) {
1173 ($lu, $perm, $par, $y) = @_;
1174 }
1175 0 ▶ 
Branch: 2 branches
BranchTrueFalseTotal
unless defined $lu 0 65 65
unless defined $lu 0 0 0
1176 barf("lu_backsub: LU decomposition is undef -- probably from a singular matrix.\n")
1177 unless defined($lu);
1178 0 ▶ 
Branch: 2 branches
BranchTrueFalseTotal
unless UNIVERSAL::isa($lu, "PDL") and UNIVERSAL::isa($perm, "PDL") and UNIVERSAL::isa($y, "PDL") 0 65 65
unless UNIVERSAL::isa($lu, "PDL") and UNIVERSAL::isa($perm, "PDL") and UNIVERSAL::isa($y, "PDL") 0 0 0
Condition16%2/12
UNIVERSAL::isa($lu, "PDL") and UNIVERSAL::isa($perm, "PDL") and UNIVERSAL::isa($y, "PDL")
!ll&&!rl&&r
0065
UNIVERSAL::isa($lu, "PDL") and UNIVERSAL::isa($perm, "PDL")
!ll&&!rl&&r
0065
UNIVERSAL::isa($lu, "PDL") and UNIVERSAL::isa($perm, "PDL") and UNIVERSAL::isa($y, "PDL")
!ll&&!rl&&r
000
UNIVERSAL::isa($lu, "PDL") and UNIVERSAL::isa($perm, "PDL")
!ll&&!rl&&r
000
MC/DC0%0/3
UNIVERSAL::isa($lu, "PDL") and UNIVERSAL::isa($perm, "PDL") and UNIVERSAL::isa($y, "PDL")
UNIVERSAL::isa($lu, "PDL") UNIVERSAL::isa($perm, "PDL") UNIVERSAL::isa($y, "PDL")
MC/DC0%0/3
UNIVERSAL::isa($lu, "PDL") and UNIVERSAL::isa($perm, "PDL") and UNIVERSAL::isa($y, "PDL")
UNIVERSAL::isa($lu, "PDL") UNIVERSAL::isa($perm, "PDL") UNIVERSAL::isa($y, "PDL")
Truth table25%1/4
A and B and C
A= UNIVERSAL::isa($lu, "PDL")B= UNIVERSAL::isa($perm, "PDL")C= UNIVERSAL::isa($y, "PDL")
ABCresult
0XX0
10X0
1100
1111
Truth table0%0/4
A and B and C
A= UNIVERSAL::isa($lu, "PDL")B= UNIVERSAL::isa($perm, "PDL")C= UNIVERSAL::isa($y, "PDL")
ABCresult
0XX0
10X0
1100
1111
1179 barf("Usage: \$x = lu_backsub(\$lu,\$perm,\$y); all must be PDLs\n")
1180 unless(UNIVERSAL::isa($lu,'PDL') &&
1181 UNIVERSAL::isa($perm,'PDL') &&
1182 UNIVERSAL::isa($y,'PDL'));
1183 0  
1184 0 my $n = $y->dim(0);
1185 my $n1 = $n; $n1--;
1186  
1187 # Make sure broadcasting dimensions are compatible.
1188 # There are two possible sources of broadcast dims:
1189 #
1190 # (1) over multiple LU (i.e., $lu,$perm) instances
1191 # (2) over multiple B (i.e., $y) column instances
1192 #
1193 # The full dimensions of the function call looks like
1194 #
1195 # lu_backsub( lu(m,m,X), perm(m,X), b(m,Y) )
1196 #
1197 # where X is the list of extra LU dims and Y is
1198 # the list of extra B dims. We have several possible
1199 # cases:
1200 #
1201 0 # (1) Check that m dims are compatible
1202 0 my $ludims = pdl($lu->dims);
1203 0 my $permdims = pdl($perm->dims);
1204 my $bdims = pdl($y->dims);
1205 0 ▶ 
Branch: 2 branches
BranchTrueFalseTotal
if $PDL::debug 0 65 65
if $PDL::debug 0 0 0
1206 print STDERR "lu_backsub: called with args: \$lu$ludims, \$perm$permdims, \$y$bdims\n" if $PDL::debug;
1207 0  
1208 0 ▶ my $m = $ludims->slice("(0)"); # this is the sig dimension
Branch: 2 branches
BranchTrueFalseTotal
unless ($ludims->slice(0) == $m and $ludims->slice(1) == $m and $permdims->slice(0) == $m and $bdims->slice(0) == $m) 0 65 65
unless ($ludims->slice(0) == $m and $ludims->slice(1) == $m and $permdims->slice(0) == $m and $bdims->slice(0) == $m) 0 0 0
Condition16%3/18
$ludims->slice(0) == $m and $ludims->slice(1) == $m and $permdims->slice(0) == $m and $bdims->slice(0) == $m
!ll&&!rl&&r
0650
$ludims->slice(0) == $m and $ludims->slice(1) == $m and $permdims->slice(0) == $m
!ll&&!rl&&r
0650
$ludims->slice(0) == $m and $ludims->slice(1) == $m
!ll&&!rl&&r
0650
$ludims->slice(0) == $m and $ludims->slice(1) == $m and $permdims->slice(0) == $m and $bdims->slice(0) == $m
!ll&&!rl&&r
000
$ludims->slice(0) == $m and $ludims->slice(1) == $m and $permdims->slice(0) == $m
!ll&&!rl&&r
000
$ludims->slice(0) == $m and $ludims->slice(1) == $m
!ll&&!rl&&r
000
MC/DC0%0/4
$ludims->slice(0) == $m and $ludims->slice(1) == $m and $permdims->slice(0) == $m and $bdims->slice(0) == $m
$ludims->slice(0) == $m $ludims->slice(1) == $m $permdims->slice(0) == $m $bdims->slice(0) == $m
MC/DC0%0/4
$ludims->slice(0) == $m and $ludims->slice(1) == $m and $permdims->slice(0) == $m and $bdims->slice(0) == $m
$ludims->slice(0) == $m $ludims->slice(1) == $m $permdims->slice(0) == $m $bdims->slice(0) == $m
Truth table0%0/5
A and B and C and D
A= $ludims->slice(0) == $mB= $ludims->slice(1) == $mC= $permdims->slice(0) == $mD= $bdims->slice(0) == $m
ABCDresult
0XXX0
10XX0
110X0
11100
11111
Truth table0%0/5
A and B and C and D
A= $ludims->slice(0) == $mB= $ludims->slice(1) == $mC= $permdims->slice(0) == $mD= $bdims->slice(0) == $m
ABCDresult
0XXX0
10XX0
110X0
11100
11111
1209 unless ( ($ludims->slice(0) == $m) and ($ludims->slice(1) == $m) and
1210 0 ($permdims->slice(0) == $m) and ($bdims->slice(0) == $m)) {
1211 barf "lu_backsub: mismatched sig dimensions";
1212 }
1213 0  
1214 0 my $lunumthr = $ludims->dim(0)-2;
1215 0 my $permnumthr = $permdims->dim(0)-1;
1216 0 ▶ my $bnumthr = $bdims->dim(0)-1;
Branch: 2 branches
BranchTrueFalseTotal
unless ($lunumthr == $permnumthr and ($ludims->slice("1:-1") == $permdims)->all) 0 65 65
unless ($lunumthr == $permnumthr and ($ludims->slice("1:-1") == $permdims)->all) 0 0 0
Condition16%1/6
$lunumthr == $permnumthr and ($ludims->slice("1:-1") == $permdims)->all
!ll&&!rl&&r
0650
$lunumthr == $permnumthr and ($ludims->slice("1:-1") == $permdims)->all
!ll&&!rl&&r
000
MC/DC0%0/2
$lunumthr == $permnumthr and ($ludims->slice("1:-1") == $permdims)->all
$lunumthr == $permnumthr ($ludims->slice("1:-1") == $permdims)->all
MC/DC0%0/2
$lunumthr == $permnumthr and ($ludims->slice("1:-1") == $permdims)->all
$lunumthr == $permnumthr ($ludims->slice("1:-1") == $permdims)->all
Truth table33%1/3
A and B
A= $lunumthr == $permnumthrB= ($ludims->slice("1:-1") == $permdims)->all
ABresult
0X0
100
111
Truth table0%0/3
A and B
A= $lunumthr == $permnumthrB= ($ludims->slice("1:-1") == $permdims)->all
ABresult
0X0
100
111
1217 0 unless ( ($lunumthr == $permnumthr) and ($ludims->slice("1:-1") == $permdims)->all ) {
1218 barf "lu_backsub: \$lu and \$perm broadcast dims not equal! \n";
1219 }
1220  
1221 0 ▶ # (2) If X == Y then default broadcasting is ok
Branch: 2 branches
BranchTrueFalseTotal
if ($bnumthr == $permnumthr and ($bdims == $permdims)->all) 4 61 65
if ($bnumthr == $permnumthr and ($bdims == $permdims)->all) 0 0 0
Condition33%2/6
$bnumthr == $permnumthr and ($bdims == $permdims)->all
!ll&&!rl&&r
6140
$bnumthr == $permnumthr and ($bdims == $permdims)->all
!ll&&!rl&&r
000
MC/DC0%0/2
$bnumthr == $permnumthr and ($bdims == $permdims)->all
$bnumthr == $permnumthr ($bdims == $permdims)->all
MC/DC0%0/2
$bnumthr == $permnumthr and ($bdims == $permdims)->all
$bnumthr == $permnumthr ($bdims == $permdims)->all
Truth table33%1/3
A and B
A= $bnumthr == $permnumthrB= ($bdims == $permdims)->all
ABresult
0X0
100
111
Truth table0%0/3
A and B
A= $bnumthr == $permnumthrB= ($bdims == $permdims)->all
ABresult
0X0
100
111
1222 0 ▶ if ( ($bnumthr==$permnumthr) and ($bdims==$permdims)->all) {
Branch: 2 branches
BranchTrueFalseTotal
if $PDL::debug 0 4 4
if $PDL::debug 0 0 0
1223 0 print STDERR "lu_backsub: have explicit broadcast dims, goto BROADCAST_OK\n" if $PDL::debug;
1224 goto BROADCAST_OK;
1225 }
1226  
1227 # (3) If X == (x,Y) then add x dummy to lu,perm
1228  
1229 # (4) If ndims(X) > ndims(Y) then must have #3
1230  
1231 # (5) If ndims(X) < ndims(Y) then foreach
1232 # non-trivial leading dim in X (x0,x1,..)
1233 # insert dummy (x0,x1) into lu and perm
1234  
1235 # This means that broadcasting occurs over all
1236 # leading non-trivial (not length 1) dims of
1237 # B unless all the broadcast dims are explicitly
1238 # matched to the LU dims.
1239  
1240 BROADCAST_OK:
1241  
1242 0 # Permute the vector and make a copy if necessary.
1243 0 ▶ my $out = $y->dummy(1,$y->dim(0))->index($perm->dummy(1));
Branch: 2 branches
BranchTrueFalseTotal
unless $y->is_inplace 62 3 65
unless $y->is_inplace 0 0 0
1244 0 ▶ $out = $out->sever if !$y->is_inplace;
Branch: 2 branches
BranchTrueFalseTotal
if $PDL::debug 0 65 65
if $PDL::debug 0 0 0
1245 print STDERR "lu_backsub: starting with \$out" . pdl($out->dims) . "\n" if $PDL::debug;
1246  
1247 # Make sure broadcasting over lu happens OK...
1248 0 ▶ 
Branch: 2 branches
BranchTrueFalseTotal
if ($out->ndims < $lu->ndims - 1) 0 65 65
if ($out->ndims < $lu->ndims - 1) 0 0 0
1249 0 ▶ if($out->ndims < $lu->ndims-1) {
Branch: 2 branches
BranchTrueFalseTotal
if $PDL::debug 0 0 0
if $PDL::debug 0 0 0
1250 0 ▶ print STDERR "lu_backsub: adjusting dims for \$out" . pdl($out->dims) . "\n" if $PDL::debug;
Branch: 2 branches
BranchTrueFalseTotal
$out->ndims < $lu->ndims - 1 and do { do { $out = $out->dummy(-1, $lu->dim($out->ndims + 1)) } } 0 0 0
$out->ndims < $lu->ndims - 1 and do { do { $out = $out->dummy(-1, $lu->dim($out->ndims + 1)) } } 0 0 0
1251 0 do {
1252 $out = $out->dummy(-1,$lu->dim($out->ndims+1));
1253 } while($out->ndims < $lu->ndims-1);
1254 }
1255  
1256 0 ## Do forward substitution into L
1257 my $row; my $r1;
1258 0  
1259 0 for $row(1..$n1) {
1260 0 $r1 = $row-1;
1261 $out->index($row) -= ($lu->slice("0:$r1,$row") *
1262 $out->slice("0:$r1")
1263 )->sumover;
1264 }
1265  
1266 0 ## Do backward substitution into U, and normalize by the diagonal
1267 0 my $ludiag = $lu->diagonal(0,1);
1268 $out->index($n1) /= $ludiag->index($n1)->dummy(0); # TODO: check broadcasting
1269 0 ▶ 
Branch: 2 branches
BranchTrueFalseTotal
if ($row > 0) 83 65 148
if ($row > 0) 0 0 0
1270 0 for ($row=$n1; $row>0; $row--) {
1271 0 $r1 = $row-1;
1272 $out->index($r1) -= ($lu->slice("$row:$n1,$r1") * # TODO: check broadcast dims
1273 $out->slice("$row:$n1")
1274 0 )->sumover;
1275 $out->index($r1) /= $ludiag->index($r1)->dummy(0); # TODO: check broadcast dims
1276 }
1277 0 ▶ 
Branch: 2 branches
BranchTrueFalseTotal
if ($y->is_inplace) 3 62 65
if ($y->is_inplace) 0 0 0
1278 0 ▶ if ($y->is_inplace) {
Branch: 2 branches
BranchTrueFalseTotal
unless PDL::all($y->shape == $out->shape) 2 1 3
unless PDL::all($y->shape == $out->shape) 0 0 0
1279 0 $y->setdims([$out->dims]) if !PDL::all($y->shape == $out->shape); # assgn needs same shape
1280 $y .= $out;
1281 0 }
1282 $out;
1283 }
1284 EOD
1285  
1286 # XXX Destroys a!!!
1287 # To use the new a again, must store both a and ips.
1288 pp_def("simq",
1289 HandleBad => 0,
1290 Pars => '[io,phys]a(n,n); [phys]b(n); [o,phys]x(n); int [o,phys]ips(n)',
1291 OtherPars => 'int flag;',
1292 GenericTypes => ['D'],
1293 Code => '
1294 extern int simq( double *A, double *B, double *X,
1295 int n, int flag, int *IPS );
1296 simq($P(a), $P(b), $P(x), $SIZE(n), $COMP(flag), $P(ips));
1297 ',
1298 Doc => '
1299 =for ref
1300  
1301 Solution of simultaneous linear equations, C<a x = b>.
1302 B<NB does not broadcast well>.
1303  
1304 =for usage
1305  
1306 # remove all active dims
1307 @A_dims = $A->dims; @B_dims = $B->transpose->dims;
1308 splice @A_dims, 0, 2; splice @B_dims, 0, 1;
1309 @broadcast = PDL::Core::dims_filled(\@A_dims, \@B_dims);
1310 # simq modifies A, so need 1 copy per broadcast else non-first run has wrong A
1311 ($x) = simq($newA = $A->dupN(1,1,map +($A_dims[$_]//1)==1?$broadcast[$_]:1, 0..$#broadcast)->copy, $B->transpose, 0);
1312 # $newA now contains modified $A for uses in further calls with flag=-1
1313 $x = $x->transpose;
1314  
1315 C<$a> is an C<n x n> matrix (i.e., a vector of length C<n*n>), stored row-wise:
1316 that is, C<a(i,j) = a[ij]>, where C<ij = i*n + j>.
1317  
1318 This corresponds to normal PDL usage. The contents of matrix a may be
1319 altered (but may be required for subsequent calls with flag = -1).
1320  
1321 C<$y>, C<$x>, C<$ips> are vectors of length C<n>.
1322  
1323 Set C<flag=0> to solve.
1324 Set C<flag=-1> to do a new back substitution for
1325 different C<$y> vector using the same a matrix previously reduced when
1326 C<flag=0> (the C<$ips> vector generated in the previous solution is also
1327 required).
1328  
1329 For this function to work well with broadcasting, it will need the LU
1330 decomposition part split out, so that for solving C<A x = B> only C<x>
1331 would be written to.
1332  
1333 See also L</lu_backsub>, which does the same thing with a slightly
1334 less opaque interface.
1335  
1336 =cut
1337  
1338  
1339 ');
1340  
1341 ######################################################################
1342 ### squaretotri
1343 ###
1344 # this doesn't need to be changed to support bad values
1345 # I could put 'HandleBad => 1', but it would just cause an
1346 # unnecessary increase (admittedly small) in the amount of
1347 # code
1348 #
1349 pp_def("squaretotri",
1350 Pars => 'a(n,n); [o]b(m=CALC(($SIZE(n) * ($SIZE(n)+1))/2))',
1351 GenericTypes => [ppdefs_all],
1352 Code => '
1353 register PDL_Indx mna=0, nb=0;
1354 loop(m) %{
1355 $b() = $a(n0 => mna, n1 => nb);
1356 mna++; if(mna > nb) {mna = 0; nb ++;}
1357 %}
1358 ',
1359 Doc => '=for ref
1360  
1361 Convert a lower-triangular square matrix to triangular vector storage.
1362 Ignores upper half of input.
1363 ',
1364 );
1365  
1366 pp_def("tritosquare",
1367 Pars => 'a(m); [o]b(n,n)',
1368 GenericTypes => [ppdefs_all],
1369 RedoDimsCode => $TRIANGULAR_REDODIMS,
1370 Code => '
1371 register PDL_Indx mna=0, nb=0;
1372 loop(m) %{
1373 $b(n0 => mna, n1 => nb) = $a();
1374 mna++; if(mna > nb) {mna = 0; nb ++;}
1375 %}
1376 ',
1377 Doc => '=for ref
1378  
1379 Convert a triangular vector to lower-triangular square matrix storage.
1380 Does not touch upper half of output.
1381  
1382 See also L</tritosym>, L</tricpy>.
1383 ',
1384 );
1385  
1386 pp_def('tricpy',
1387 Pars => 'A(m,n);[o] C(m,n)',
1388 OtherPars => 'int uplo',
1389 OtherParsDefaults => {uplo => 0},
1390 ArgOrder => [qw(A uplo C)],
1391 GenericTypes => [ppdefs_all()],
1392 Code => <<'EOF',
1393 switch ($COMP(uplo)) {
1394 case -1: /* strict upper */
1395 broadcastloop %{ loop(n=:-1,m=n+1) %{ $C() = $A(); %} %}
1396 break;
1397 case 0: /* upper */
1398 broadcastloop %{ loop(n,m=n) %{ $C() = $A(); %} %}
1399 break;
1400 case 1: /* lower */
1401 broadcastloop %{ loop(n,m=:n+1) %{ $C() = $A(); %} %}
1402 break;
1403 case 2: /* strict lower */
1404 broadcastloop %{ loop(n=1,m=:n) %{ $C() = $A(); %} %}
1405 break;
1406 default: $CROAK(" invalid value for uplo '%d', must be -1..2", $COMP(uplo));
1407 }
1408 EOF
1409 Doc => <<'EOT',
1410 =for ref
1411  
1412 Copy triangular part to another matrix.
1413  
1414 C<uplo> meanings to copy: -1 strict upper triangular, 0 = upper, 1
1415 lower, 2 strict lower. The "strict" modes are as of 2.104.
1416  
1417 Originally by Grégory Vanuxem.
1418 See also L</tritosym>, L</tritosquare>.
1419 EOT
1420 );
1421  
1422 pp_add_exported('','tritosym');
1423 pp_addpm(<<'EOF');
1424 =head2 tritosym
1425  
1426 =for ref
1427  
1428 Returns symmetric or Hermitian matrix from lower or upper triangular matrix.
1429 Supports inplace and broadcasting.
1430  
1431 =for usage
1432  
1433 PDL = tritosym(PDL, SCALAR(uplo), SCALAR(conj))
1434 uplo : UPPER = 0 | LOWER = 1, default = 0
1435 conj : Hermitian = 1 | Symmetric = 0, default = 0;
1436  
1437 Originally by Grégory Vanuxem. Added to PDL in 2.104.
1438 See also L</tricpy>, L</tritosquare>.
1439  
1440 =cut
1441  
1442 *tritosym = \&PDL::tritosym;
1443 6 ▶sub PDL::tritosym {
Subroutine tritosym: called CC=7 SCAR=27.8
Pod undocumented
1444 0 ▶ my @dims = $_[0]->dims;
Subroutine tritosym: not called CC=7 SCAR=27.8
Pod undocumented
1445 0 ▶ barf "Require square array but got (@dims)" unless @dims >= 2 && $dims[0] == $dims[1];
Branch: 2 branches
BranchTrueFalseTotal
unless @dims >= 2 and $dims[0] == $dims[1] 0 6 6
unless @dims >= 2 and $dims[0] == $dims[1] 0 0 0
Condition16%1/6
@dims >= 2 and $dims[0] == $dims[1]
!ll&&!rl&&r
006
@dims >= 2 and $dims[0] == $dims[1]
!ll&&!rl&&r
000
MC/DC0%0/2
@dims >= 2 and $dims[0] == $dims[1]
@dims >= 2 $dims[0] == $dims[1]
MC/DC0%0/2
@dims >= 2 and $dims[0] == $dims[1]
@dims >= 2 $dims[0] == $dims[1]
Truth table33%1/3
A and B
A= @dims >= 2B= $dims[0] == $dims[1]
ABresult
0X0
100
111
Truth table0%0/3
A and B
A= @dims >= 2B= $dims[0] == $dims[1]
ABresult
0X0
100
111
1446 0 my ($m, $upper, $conj) = @_;
1447 0 ▶ $conj = 0 if $m->type->real;
Branch: 2 branches
BranchTrueFalseTotal
if $m->type->real 4 2 6
if $m->type->real 0 0 0
1448 0 my $b = $m->new_or_inplace;
1449 0 ▶ ($conj ? $m->conj : $m)->tricpy($upper ? 2 : -1, $b->t); # strict
Branch: 4 branches
BranchTrueFalseTotal
$conj ? : 2 4 6
$upper ? : 4 2 6
$conj ? : 0 0 0
$upper ? : 0 0 0
1450 0 ▶ $b->diagonal(0,1)->im .= 0 if $conj;
Branch: 2 branches
BranchTrueFalseTotal
if $conj 2 4 6
if $conj 0 0 0
1451 0 $b;
1452 }
1453 EOF
1454  
1455 pp_def('mstack',
1456 Pars => 'x(n,m);y(n,p);[o]out(n,q=CALC($SIZE(m)+$SIZE(p)));',
1457 GenericTypes => [ppdefs_all()],
1458 Code => '
1459 loop (m,n) %{ $out(q=>m) = $x(); %}
1460 loop (q=$SIZE(m),n) %{ $out() = $y(p=>q-$SIZE(m)); %}
1461 ',
1462 BackCode => '
1463 loop (m,n) %{ $x() = $out(q=>m); %}
1464 loop (q=$SIZE(m),n) %{ $y(p=>q-$SIZE(m)) = $out(); %}
1465 ',
1466 Doc => <<EOT
1467 =for ref
1468  
1469 Combine two 2D ndarrays into a single ndarray, along the second
1470 ("vertical") dim.
1471  
1472 Originally by Grégory Vanuxem.
1473 EOT
1474 );
1475  
1476 pp_def('augment',
1477 Pars => 'x(n); y(p);[o]out(q=CALC($SIZE(n)+$SIZE(p)))',
1478 GenericTypes => [ppdefs_all()],
1479 Code => '
1480 loop (q=:$SIZE(n)) %{ $out() = $x(n=>q); %}
1481 loop (q=$SIZE(n)) %{ $out() = $y(p=>q-$SIZE(n)); %}
1482 ',
1483 BackCode => '
1484 loop (q=:$SIZE(n)) %{ $x(n=>q) = $out(); %}
1485 loop (q=$SIZE(n)) %{ $y(p=>q-$SIZE(n)) = $out(); %}
1486 ',
1487 Doc => <<EOT
1488 =for ref
1489  
1490 Combine two ndarrays into a single ndarray along the 0-th ("horizontal") dim.
1491  
1492 Originally by Grégory Vanuxem.
1493 EOT
1494 );
1495  
1496 pp_addpm({At=>'Bot'},<<'EOD');
1497  
1498 =head1 AUTHOR
1499  
1500 Copyright (C) 2002 Craig DeForest (deforest@boulder.swri.edu),
1501 R.J.R. Williams (rjrw@ast.leeds.ac.uk), Karl Glazebrook
1502 (kgb@aaoepp.aao.gov.au). There is no warranty. You are allowed to
1503 redistribute and/or modify this work under the same conditions as PDL
1504 itself. If this file is separated from the PDL distribution, then the
1505 PDL copyright notice should be included in this file.
1506  
1507 =cut
1508  
1509 EOD
1510  
1511 pp_done();
« blib/lib/PDL/Doc/Perldl.pm ↑ Summary blib/lib/PDL/IO/FITS.pm »