| 1 | package PDL::LinearAlgebra; |
| 2 | use PDL::Ops; |
| 3 | use PDL::Core; |
| 4 | use PDL::Basic qw/sequence/; |
| 5 | use PDL::Primitive qw/which whichND_both/; |
| 6 | use PDL::Ufunc qw/sumover/; |
| 7 | use PDL::NiceSlice; |
| 8 | use PDL::MatrixOps qw(stretcher gurney); |
| 9 | use PDL::Slices; |
| 10 | use PDL::LinearAlgebra::Real; |
| 11 | use PDL::LinearAlgebra::Complex; |
| 12 | use PDL::LinearAlgebra::Special qw//; |
| 13 | use PDL::Exporter; |
| 14 | no warnings 'uninitialized'; |
| 15 | use constant { |
| 16 | NO => 0, |
| 17 | WARN => 1, |
| 18 | BARF => 2, |
| 19 | }; |
| 20 | |
| 21 | use strict; |
| 22 | |
| 23 | our $VERSION = '0.437'; |
| 24 | $VERSION =~ tr/_//d; |
| 25 | |
| 26 | our @ISA = qw/PDL::Exporter/; |
| 27 | our @EXPORT_OK = qw/diag issym minv mtriinv msyminv mposinv mdet mposdet mrcond |
| 28 | positivise |
| 29 | mdsvd msvd mgsvd mpinv mlu mhessen mchol mqr mql mlq mrq meigen meigenx |
| 30 | mgeigen mgeigenx msymeigen msymeigenx msymgeigen msymgeigenx |
| 31 | msolve mtrisolve msymsolve mpossolve msolvex msymsolvex mpossolvex |
| 32 | mrank mlls mllsy mllss mglm mlse tritosym mnorm mgschur mgschurx |
| 33 | mcrossprod mcond morth mschur mschurx |
| 34 | NO WARN BARF setlaerror getlaerorr laerror/; |
| 35 | our %EXPORT_TAGS = (Func=>\@EXPORT_OK); |
| 36 | |
| 37 | my $_laerror = BARF; |
| 38 | |
| 39 | ######################################################################## |
| 40 | |
| 41 | =encoding utf8 |
| 42 | |
| 43 | =head1 NAME |
| 44 | |
| 45 | PDL::LinearAlgebra - Linear Algebra utils for PDL |
| 46 | |
| 47 | =head1 SYNOPSIS |
| 48 | |
| 49 | use PDL::LinearAlgebra; |
| 50 | |
| 51 | $a = random (100,100); |
| 52 | ($U, $s, $V) = mdsvd($a); |
| 53 | |
| 54 | =head1 DESCRIPTION |
| 55 | |
| 56 | This module provides a convenient interface to L<PDL::LinearAlgebra::Real> |
| 57 | and L<PDL::LinearAlgebra::Complex>. Since |
| 58 | BLAS and LAPACK use a column major ordering scheme some routines here need to transpose matrices before |
| 59 | calling fortran routines and transpose back (see the documentation of each routine). If you need |
| 60 | optimized code use directly L<PDL::LinearAlgebra::Real> and |
| 61 | L<PDL::LinearAlgebra::Complex>. |
| 62 | |
| 63 | =cut |
| 64 | |
| 65 | =head1 FUNCTIONS |
| 66 | |
| 67 | =head2 setlaerror |
| 68 | |
| 69 | =for ref |
| 70 | |
| 71 | Sets action type when an error is encountered, returns previous type. Available values are NO, WARN and BARF (predefined constants). |
| 72 | If, for example, in computation of the inverse, singularity is detected, |
| 73 | the routine can silently return values from computation (see manuals), |
| 74 | warn about singularity or barf. BARF is the default value. |
| 75 | |
| 76 | =for example |
| 77 | |
| 78 | # h : x -> g(f(x)) |
| 79 | |
| 80 | $a = sequence(5,5); |
| 81 | $err = setlaerror(NO); |
| 82 | ($b, $info)= f($a); |
| 83 | setlaerror($err); |
| 84 | $info ? barf "can't compute h" : return g($b); |
| 85 | |
| 86 | |
| 87 | =cut |
| 88 | |
| 89 | sub setlaerror($) { |
| 90 | my $err = $_laerror; |
| 91 | $_laerror = shift; |
| 92 | $err; |
| 93 | } |
| 94 | |
| 95 | =head2 getlaerror |
| 96 | |
| 97 | =for ref |
| 98 | |
| 99 | Gets action type when an error is encountered. |
| 100 | |
| 101 | 0 => NO, |
| 102 | 1 => WARN, |
| 103 | 2 => BARF |
| 104 | |
| 105 | =cut |
| 106 | |
| 107 | sub getlaerror { |
| 108 | $_laerror; |
| 109 | } |
| 110 | |
| 111 | sub laerror { |
| 112 | return unless $_laerror; |
| 113 | if ($_laerror < 2) { |
| 114 | warn "$_[0]\n"; |
| 115 | } else { |
| 116 | barf "$_[0]\n"; |
| 117 | } |
| 118 | } |
| 119 | |
| 120 | sub PDL::_similar { |
| 121 | my ($m, @vdims) = @_; |
| 122 | ref($m)->new_from_specification($m->type, @vdims); |
| 123 | } |
| 124 | sub PDL::_similar_null { ref($_[0])->null } |
| 125 | sub _complex_null { |
| 126 | PDL->null |
| 127 | } |
| 128 | sub _ecplx { |
| 129 | my ($re, $im) = @_; |
| 130 | $re = PDL->topdl($re); |
| 131 | return $re if !$re->type->real; |
| 132 | Carp::confess("Usage: _ecplx(re,im) or (complex)") if !defined $im; |
| 133 | $im = PDL->topdl($im); |
| 134 | $re->czip($im); |
| 135 | } |
| 136 | sub PDL::_is_complex { !$_[0]->type->real } |
| 137 | sub PDL::_norm { |
| 138 | my ($m, $real, $trans) = @_; |
| 139 | # If trans == true => transpose output matrix |
| 140 | # If real == true => rotate (complex as a vector) |
| 141 | # such that max abs will be real |
| 142 | my $ret = PDL::LinearAlgebra::Complex::cnrm2($m); |
| 143 | return ($trans ? $m->t/$ret->dummy(0)->t : $m/$ret->dummy(0))->reshape(-1) if !$real; |
| 144 | $m = ($m/$ret->dummy(0))->reshape(-1); |
| 145 | my $index = $m->abs->maximum_ind; |
| 146 | my $scale = $m->mv(0,-1)->index($index)->mv(-1,0); |
| 147 | $scale = $scale->conj/$scale->abs; |
| 148 | return $trans ? $m->t*$scale->dummy(2) : $m*$scale->dummy(2)->t; |
| 149 | } |
| 150 | |
| 151 | =head2 issym |
| 152 | |
| 153 | =for usage |
| 154 | |
| 155 | PDL = issym(PDL, SCALAR|PDL(tol),SCALAR(hermitian)) |
| 156 | tol : tolerance value, default: 1e-8 for double else 1e-5 |
| 157 | hermitian : Hermitian = 1 | Symmetric = 0, default = 0; |
| 158 | |
| 159 | =for ref |
| 160 | |
| 161 | Checks symmetricity/Hermitianicity of matrix. |
| 162 | Supports broadcasting. |
| 163 | |
| 164 | =cut |
| 165 | |
| 166 | sub _2d_array { |
| 167 | my @dims = $_[0]->dims; |
| 168 | barf("Require 2D array(s)") unless @dims >= 2; |
| 169 | } |
| 170 | sub _square { |
| 171 | &_2d_array; |
| 172 | my @dims = $_[0]->dims; |
| 173 | barf("Require square array(s)") unless $dims[0] == $dims[1]; |
| 174 | } |
| 175 | sub _square_same { |
| 176 | my @adims = $_[0]->dims; |
| 177 | my @bdims = $_[1]->dims; |
| 178 | barf("Require square matrices of same order") |
| 179 | unless( $adims[0] == $adims[1] && $bdims[0] == $bdims[1] && $adims[0] == $bdims[0]); |
| 180 | } |
| 181 | sub _matrices_match { |
| 182 | my @adims = $_[0]->dims; |
| 183 | my @bdims = $_[1]->dims; |
| 184 | barf("Require right hand side array(s) B with number". |
| 185 | " of row equal to number of columns of A") |
| 186 | unless @adims >= 2 && @bdims >= 2 && $bdims[1] == $adims[0]; |
| 187 | } |
| 188 | sub _matrices_matchcolumns { |
| 189 | my @adims = $_[0]->dims; |
| 190 | my @bdims = $_[1]->dims; |
| 191 | barf("Require 2 matrices with equal number of columns") |
| 192 | unless( ((@adims >= 2 && @bdims >= 2)) && |
| 193 | $adims[0] == $bdims[0]); |
| 194 | } |
| 195 | sub _matrices_matchrows { |
| 196 | my @adims = $_[0]->dims; |
| 197 | my @bdims = $_[1]->dims; |
| 198 | barf("Require a 2D right hand side matrix B with number". |
| 199 | " of rows equal to number of rows of A") |
| 200 | unless @adims >= 2 && @bdims >= 2 && $bdims[1] == $adims[1]; |
| 201 | } |
| 202 | sub _same_dims { |
| 203 | my @adims = $_[0]->dims; |
| 204 | my @bdims = $_[1]->dims; |
| 205 | barf("Require arrays with equal number of dimensions") if @adims != @bdims; |
| 206 | } |
| 207 | sub _error { |
| 208 | my ($info, $msg) = @_; |
| 209 | return unless $info->max > 0 && $_laerror; |
| 210 | my @list = (which($info > 0)+1)->list; |
| 211 | laerror(sprintf $msg . ": \$info = $info", "@list"); |
| 212 | } |
| 213 | sub _error_schur { |
| 214 | my ($info, $select_func, $N, $func, $algo) = @_; |
| 215 | return unless $info->max > 0 && $_laerror; |
| 216 | my $index = which((($info > 0)+($info <=$N))==2); |
| 217 | if (!$index->isempty) { |
| 218 | laerror("$func: The $algo algorithm failed to converge for matrix (PDL(s) @{[$index->list]}): \$info = $info"); |
| 219 | print "Returning converged eigenvalues\n"; |
| 220 | } |
| 221 | return if !$select_func; |
| 222 | if (!($index = which($info == $N+1))->isempty) { |
| 223 | if ($algo eq 'QR') { |
| 224 | laerror("$func: The eigenvalues could not be reordered because some\n". |
| 225 | "eigenvalues were too close to separate (the problem". |
| 226 | " is very ill-conditioned) for PDL(s) @{[$index->list]}: \$info = $info"); |
| 227 | } else { |
| 228 | laerror("$func: Error in hgeqz for matrix (PDL(s) @{[$index->list]}): \$info = $info"); |
| 229 | } |
| 230 | } |
| 231 | if (!($index = which($info == $N+2))->isempty) { |
| 232 | warn("$func: The Schur form no longer satisfy select_func = 1\n because of roundoff". |
| 233 | " or underflow (PDL(s) @{[$index->list]})\n"); |
| 234 | } |
| 235 | } |
| 236 | sub PDL::_wrap_select_func { |
| 237 | my ($m, $select_func) = @_; |
| 238 | return $select_func if !defined $select_func or $m->_is_complex; |
| 239 | sub { &$select_func(_ecplx(@_[0,1]), @_>2 ? PDL->topdl($_[2]) : ()) }; |
| 240 | } |
| 241 | |
| 242 | *issym = \&PDL::issym; |
| 243 | sub PDL::issym { |
| 244 | &_square; |
| 245 | my ($m, $tol, $conj) = @_; |
| 246 | $tol //= ($m->type >= double) ? 1e-8 : 1e-5; |
| 247 | $m = $m - $m->t($conj); |
| 248 | my ($min,$max) = PDL::Ufunc::minmaximum($m); |
| 249 | $min = $min->minimum; |
| 250 | $max = $max->maximum; |
| 251 | return (((abs($max) > $tol) + (abs($min) > $tol)) == 0); |
| 252 | } |
| 253 | |
| 254 | =head2 diag |
| 255 | |
| 256 | =for ref |
| 257 | |
| 258 | Returns i-th diagonal if matrix in entry or matrix with i-th diagonal |
| 259 | with entry. I-th diagonal returned flows data back&forth. |
| 260 | Can be used as lvalue subs if your perl supports it. |
| 261 | Supports broadcasting. |
| 262 | |
| 263 | =for usage |
| 264 | |
| 265 | PDL = diag(PDL, SCALAR(i), SCALAR(vector))) |
| 266 | i : i-th diagonal, default = 0 |
| 267 | vector : create diagonal matrices by broadcasting over row vectors, default = 0 |
| 268 | |
| 269 | =for example |
| 270 | |
| 271 | my $a = random(5,5); |
| 272 | my $diag = diag($a,2); |
| 273 | # If your perl support lvaluable subroutines. |
| 274 | $a->diag(-2) .= pdl(1,2,3); |
| 275 | # Construct a (5,5,5) PDL (5 matrices) with |
| 276 | # diagonals from row vectors of $a |
| 277 | $a->diag(0,1) |
| 278 | |
| 279 | =cut |
| 280 | |
| 281 | *diag = \&PDL::diag; |
| 282 | sub PDL::diag { |
| 283 | my @diag_args = (0,1); |
| 284 | my ($a,$i, $vec) = @_; |
| 285 | my $z; |
| 286 | my @dims = $a->dims; |
| 287 | my $diag = ($i < 0) ? -$i : $i; |
| 288 | if (@dims == 1 || $vec) { |
| 289 | my $dim = $dims[0]; |
| 290 | my $zz = $dim + $diag; |
| 291 | my $v = $z = $a->_similar($zz,$zz,@dims[1..$#dims]); |
| 292 | $v = ($i < 0) ? $v->slice(":@{[$dim-1]},$diag:") : $v->slice("$diag:,:@{[$dim-1]}") if $i; |
| 293 | $v->diagonal(@diag_args) .= $a; |
| 294 | } elsif ($i < 0) { |
| 295 | $z = $a->slice(":-@{[$diag+1]} , $diag:")->diagonal(@diag_args); |
| 296 | } elsif ($i) { |
| 297 | $z = $a->slice("$diag:, :-@{[$diag+1]}")->diagonal(@diag_args); |
| 298 | } |
| 299 | else { $z = $a->diagonal(@diag_args); } |
| 300 | $z; |
| 301 | } |
| 302 | use attributes 'PDL', \&PDL::diag, 'lvalue'; |
| 303 | |
| 304 | =head2 positivise |
| 305 | |
| 306 | =for ref |
| 307 | |
| 308 | Returns entry pdl with changed sign by row so that average of positive sign > 0. |
| 309 | In other words broadcasts among dimension 1 and row = -row if sum(sign(row)) < 0. |
| 310 | Only makes sense for real ndarrays. |
| 311 | Works inplace. |
| 312 | |
| 313 | =for example |
| 314 | |
| 315 | my $a = random(10,10); |
| 316 | $a -= 0.5; |
| 317 | $a->xchg(0,1)->inplace->positivise; |
| 318 | |
| 319 | =cut |
| 320 | |
| 321 | *positivise = \&PDL::positivise; |
| 322 | sub PDL::positivise { |
| 323 | my $m = shift->new_or_inplace; |
| 324 | $m->dice('X', which(($m->lt(0,0)->sumover > ($m->dim(0)/2))>0)) *= -1; |
| 325 | $m; |
| 326 | } |
| 327 | |
| 328 | =head2 mcrossprod |
| 329 | |
| 330 | =for ref |
| 331 | |
| 332 | Computes the cross-product of two matrix: A' x B. |
| 333 | If only one matrix is given, takes B to be the same as A. |
| 334 | Supports broadcasting. |
| 335 | Uses L<crossprod|PDL::LinearAlgebra::Real/crossprod> or L<ccrossprod|PDL::LinearAlgebra::Complex/ccrossprod>. |
| 336 | |
| 337 | =for usage |
| 338 | |
| 339 | PDL = mcrossprod(PDL(A), (PDL(B)) |
| 340 | |
| 341 | =for example |
| 342 | |
| 343 | my $a = random(10,10); |
| 344 | my $crossproduct = mcrossprod($a); |
| 345 | |
| 346 | =cut |
| 347 | |
| 348 | sub PDL::_call_method { |
| 349 | my ($m, $method, @args) = @_; |
| 350 | $method = [$method, "c$method"] if !ref $method; |
| 351 | $method = $method->[!$m->type->real ? 1 : 0]; |
| 352 | $m->$method(@args); |
| 353 | } |
| 354 | *mcrossprod = \&PDL::mcrossprod; |
| 355 | sub PDL::mcrossprod { |
| 356 | &_2d_array; |
| 357 | my($a, $b) = @_; |
| 358 | $b = $a unless defined $b; |
| 359 | $a->_call_method('crossprod', $b); |
| 360 | } |
| 361 | |
| 362 | =head2 mrank |
| 363 | |
| 364 | =for ref |
| 365 | |
| 366 | Computes the rank of a matrix, using a singular value decomposition, |
| 367 | returning a Perl scalar. |
| 368 | from LAPACK. |
| 369 | |
| 370 | =for usage |
| 371 | |
| 372 | SCALAR = mrank(PDL, SCALAR(TOL)) |
| 373 | TOL: tolerance value, default : mnorm(dims(PDL),'inf') * mnorm(PDL) * EPS |
| 374 | |
| 375 | =for example |
| 376 | |
| 377 | my $a = random(10,10); |
| 378 | my $b = mrank($a, 1e-5); |
| 379 | |
| 380 | =cut |
| 381 | |
| 382 | *mrank = \&PDL::mrank; |
| 383 | |
| 384 | sub PDL::mrank { |
| 385 | &_2d_array; |
| 386 | my($m, $tol) = @_; |
| 387 | my(@dims) = $m->dims; |
| 388 | my $err = setlaerror(NO); |
| 389 | my ($sv, $info) = $m->mdsvd(0); |
| 390 | setlaerror($err); |
| 391 | barf("mrank: SVD algorithm did not converge\n") if $info->any; |
| 392 | $tol //= ($dims[1] > $dims[0] ? $dims[1] : $dims[0]) * $sv->slice(0) * lamch(3); |
| 393 | ($sv > $tol)->sumover; |
| 394 | } |
| 395 | |
| 396 | =head2 mnorm |
| 397 | |
| 398 | =for ref |
| 399 | |
| 400 | Computes norm of real or complex matrix |
| 401 | Supports broadcasting. |
| 402 | |
| 403 | =for usage |
| 404 | |
| 405 | PDL(norm) = mnorm(PDL, SCALAR(ord)); |
| 406 | ord : |
| 407 | 0|'inf' : Infinity norm |
| 408 | 1|'one' : One norm |
| 409 | 2|'two' : norm 2 (default) |
| 410 | 3|'fro' : frobenius norm |
| 411 | |
| 412 | =for example |
| 413 | |
| 414 | my $a = random(10,10); |
| 415 | my $norm = mnorm($a); |
| 416 | |
| 417 | =cut |
| 418 | |
| 419 | my %norms = (inf=>0, one=>1, two=>2, fro=>3); |
| 420 | my %norm2arg = (0=>1, 1=>2, 3=>3); |
| 421 | *mnorm = \&PDL::mnorm; |
| 422 | sub PDL::mnorm { |
| 423 | my ($m, $ord) = @_; |
| 424 | $ord //= 2; |
| 425 | $ord = $norms{$ord} if exists $norms{$ord}; |
| 426 | return $m->_call_method('lange', $norm2arg{$ord}) if exists $norm2arg{$ord}; |
| 427 | my $err = setlaerror(NO); |
| 428 | my ($sv, $info) = $m->msvd(0, 0); |
| 429 | setlaerror($err); |
| 430 | _error($info, "mnorm: SVD algorithm did not converge for matrix (PDL(s) %s"); |
| 431 | $sv->slice('(0)')->reshape(-1)->sever; |
| 432 | } |
| 433 | |
| 434 | =head2 mdet |
| 435 | |
| 436 | =for ref |
| 437 | |
| 438 | Computes determinant of a general square matrix using LU factorization. |
| 439 | Supports broadcasting. |
| 440 | Uses L<getrf|PDL::LinearAlgebra::Real/getrf> or L<cgetrf|PDL::LinearAlgebra::Complex/cgetrf> |
| 441 | from LAPACK. |
| 442 | |
| 443 | =for usage |
| 444 | |
| 445 | PDL(determinant) = mdet(PDL); |
| 446 | |
| 447 | =for example |
| 448 | |
| 449 | my $a = random(10,10); |
| 450 | my $det = mdet($a); |
| 451 | |
| 452 | =cut |
| 453 | |
| 454 | *mdet = \&PDL::mdet; |
| 455 | sub PDL::mdet { |
| 456 | &_square; |
| 457 | my $m_orig = my $m = shift->copy; |
| 458 | my ($ipiv, $info) = $m->_call_method('getrf'); |
| 459 | $m = $m->diagonal(0,1); |
| 460 | $m = $m->prodover; |
| 461 | $m = $m * ((PDL::Ufunc::sumover(sequence($ipiv->dim(0))->plus(1,0) != $ipiv)%2)*(-2)+1); |
| 462 | $info = which($info != 0); |
| 463 | $m->flat->index($info) .= 0 if !$info->isempty; |
| 464 | $m; |
| 465 | } |
| 466 | |
| 467 | =head2 mposdet |
| 468 | |
| 469 | =for ref |
| 470 | |
| 471 | Compute determinant of a symmetric or Hermitian positive definite square matrix using Cholesky factorization. |
| 472 | Supports broadcasting. |
| 473 | Uses L<potrf|PDL::LinearAlgebra::Real/potrf> or L<cpotrf|PDL::LinearAlgebra::Complex/cpotrf> from LAPACK. |
| 474 | |
| 475 | =for usage |
| 476 | |
| 477 | (PDL, PDL) = mposdet(PDL, SCALAR) |
| 478 | SCALAR : UPPER = 0 | LOWER = 1, default = 0 |
| 479 | |
| 480 | =for example |
| 481 | |
| 482 | my $a = random(10,10); |
| 483 | my $det = mposdet($a); |
| 484 | |
| 485 | =cut |
| 486 | |
| 487 | *mposdet = \&PDL::mposdet; |
| 488 | sub PDL::mposdet { |
| 489 | &_square; |
| 490 | my ($m, $upper) = @_; |
| 491 | $m = $m->copy; |
| 492 | my ($info) = $m->_call_method('potrf', $upper); |
| 493 | _error($info, "mposdet: Matrix (PDL(s) %s) is/are not positive definite (after potrf factorization)"); |
| 494 | $m = $m->re if $m->_is_complex; |
| 495 | $m = $m->diagonal(0,1)->prodover->pow(2); |
| 496 | wantarray ? ($m, $info) : $m; |
| 497 | } |
| 498 | |
| 499 | =head2 mcond |
| 500 | |
| 501 | =for ref |
| 502 | |
| 503 | Computes the condition number (two-norm) of a general matrix. |
| 504 | |
| 505 | The condition number in two-n is defined: |
| 506 | |
| 507 | norm (a) * norm (inv (a)). |
| 508 | |
| 509 | Uses a singular value decomposition. |
| 510 | Supports broadcasting. |
| 511 | |
| 512 | =for usage |
| 513 | |
| 514 | PDL = mcond(PDL) |
| 515 | |
| 516 | =for example |
| 517 | |
| 518 | my $a = random(10,10); |
| 519 | my $cond = mcond($a); |
| 520 | |
| 521 | =cut |
| 522 | |
| 523 | *mcond = \&PDL::mcond; |
| 524 | sub PDL::mcond { |
| 525 | &_2d_array; |
| 526 | my $m = shift; |
| 527 | my @dims = $m->dims; |
| 528 | my $err = setlaerror(NO); |
| 529 | my ($sv, $info) = $m->msvd(0, 0); |
| 530 | setlaerror($err); |
| 531 | _error($info, "mcond: Algorithm did not converge for matrix (PDL(s) %s)"); |
| 532 | $sv->slice('(0)')/$sv->slice("(-1)"); |
| 533 | } |
| 534 | |
| 535 | =head2 mrcond |
| 536 | |
| 537 | =for ref |
| 538 | |
| 539 | Estimates the reciprocal condition number of a |
| 540 | general square matrix using LU factorization |
| 541 | in either the 1-norm or the infinity-norm. |
| 542 | |
| 543 | The reciprocal condition number is defined: |
| 544 | |
| 545 | 1/(norm (a) * norm (inv (a))) |
| 546 | |
| 547 | Supports broadcasting. |
| 548 | Works on transposed array(s) |
| 549 | |
| 550 | =for usage |
| 551 | |
| 552 | PDL = mrcond(PDL, SCALAR(ord)) |
| 553 | ord : |
| 554 | 0 : Infinity norm (default) |
| 555 | 1 : One norm |
| 556 | |
| 557 | =for example |
| 558 | |
| 559 | my $a = random(10,10); |
| 560 | my $rcond = mrcond($a,1); |
| 561 | |
| 562 | =cut |
| 563 | |
| 564 | *mrcond = \&PDL::mrcond; |
| 565 | sub PDL::mrcond { |
| 566 | &_square; |
| 567 | my ($m,$anorm) = @_; |
| 568 | $anorm //= 0; |
| 569 | my $norm = $m->mnorm($anorm); |
| 570 | $m = $m->t->copy; |
| 571 | my ($ipiv, $info) = $m->_call_method('getrf'); |
| 572 | _error($info, "mrcond: Factor(s) U (PDL(s) %s) is/are singular (after getrf factorization)"); |
| 573 | (my $rcond, $info) = $m->_call_method('gecon',$anorm,$norm); |
| 574 | wantarray ? ($rcond, $info) : $rcond; |
| 575 | } |
| 576 | |
| 577 | =head2 morth |
| 578 | |
| 579 | =for ref |
| 580 | |
| 581 | Returns an orthonormal basis of the range space of matrix A. No broadcast. |
| 582 | |
| 583 | =for usage |
| 584 | |
| 585 | PDL = morth(PDL(A), SCALAR(tol)) |
| 586 | tol : tolerance for determining rank, default: 1e-8 for double else 1e-5 |
| 587 | |
| 588 | =for example |
| 589 | |
| 590 | my $a = sequence(10,10); |
| 591 | my $ortho = morth($a, 1e-8); |
| 592 | |
| 593 | =cut |
| 594 | |
| 595 | *morth = \&PDL::morth; |
| 596 | |
| 597 | sub PDL::morth { |
| 598 | &_2d_array; |
| 599 | my ($m, $tol) = @_; |
| 600 | $tol //= ($m->type >= double) ? 1e-8 : 1e-5; |
| 601 | (my $u, my $s, undef, my $info) = $m->mdsvd; |
| 602 | barf("morth: SVD algorithm did not converge\n") if $info->any; |
| 603 | my $rank = (which($s > $tol))->dim(0) - 1; |
| 604 | $rank < 0 ? $m->_similar_null : $u->slice(":$rank,")->sever; |
| 605 | } |
| 606 | |
| 607 | =head2 mnull |
| 608 | |
| 609 | =for ref |
| 610 | |
| 611 | Returns an orthonormal basis of the null space of matrix A. No broadcast. |
| 612 | |
| 613 | =for usage |
| 614 | |
| 615 | PDL = mnull(PDL(A), SCALAR(tol)) |
| 616 | tol : tolerance for determining rank, default: 1e-8 for double else 1e-5 |
| 617 | |
| 618 | =for example |
| 619 | |
| 620 | my $a = sequence(10,10); |
| 621 | my $null = mnull($a, 1e-8); |
| 622 | |
| 623 | =cut |
| 624 | |
| 625 | *mnull = \&PDL::mnull; |
| 626 | |
| 627 | sub PDL::mnull { |
| 628 | &_2d_array; |
| 629 | my ($m, $tol) = @_; |
| 630 | my @dims = $m->dims; |
| 631 | $tol //= ($m->type == double) ? 1e-8 : 1e-5; |
| 632 | (undef, my $s, my $vt, my $info) = $m->mdsvd; |
| 633 | barf("mnull: SVD algorithm did not converge\n") if $info->any; |
| 634 | #TODO: USE TRANSPOSED A |
| 635 | my $rank = (which($s > $tol))->dim(0); |
| 636 | $rank < $dims[0] ? $vt->t(1)->slice("$rank:")->sever : $m->_similar_null; |
| 637 | } |
| 638 | |
| 639 | =head2 minv |
| 640 | |
| 641 | =for ref |
| 642 | |
| 643 | Computes inverse of a general square matrix using LU factorization. Supports inplace and broadcasting. |
| 644 | Uses L<getrf|PDL::LinearAlgebra::Real/getrf> and L<getri|PDL::LinearAlgebra::Real/getri> |
| 645 | or L<cgetrf|PDL::LinearAlgebra::Complex/cgetrf> and L<cgetri|PDL::LinearAlgebra::Complex/cgetri> |
| 646 | from LAPACK and returns C<inverse, info> in array context. |
| 647 | |
| 648 | =for usage |
| 649 | |
| 650 | PDL(inv) = minv(PDL) |
| 651 | |
| 652 | =for example |
| 653 | |
| 654 | my $a = random(10,10); |
| 655 | my $inv = minv($a); |
| 656 | |
| 657 | =cut |
| 658 | |
| 659 | *minv = \&PDL::minv; |
| 660 | sub PDL::minv { |
| 661 | &_square; |
| 662 | my $m = shift->new_or_inplace; |
| 663 | my ($ipiv, $info) = $m->_call_method('getrf'); |
| 664 | _error($info, "minv: Factor(s) U (PDL(s) %s) is/are singular (after getrf factorization)"); |
| 665 | $m->_call_method('getri', $ipiv, $info); |
| 666 | wantarray ? ($m, $info) : $m; |
| 667 | } |
| 668 | |
| 669 | =head2 mtriinv |
| 670 | |
| 671 | =for ref |
| 672 | |
| 673 | Computes inverse of a triangular matrix. Supports inplace and broadcasting. |
| 674 | Uses L<trtri|PDL::LinearAlgebra::Real/trtri> or L<ctrtri|PDL::LinearAlgebra::Complex/ctrtri> from LAPACK. |
| 675 | Returns C<inverse, info> in array context. |
| 676 | |
| 677 | =for usage |
| 678 | |
| 679 | (PDL, PDL(info))) = mtriinv(PDL, SCALAR(uplo), SCALAR|PDL(diag)) |
| 680 | uplo : UPPER = 0 | LOWER = 1, default = 0 |
| 681 | diag : UNITARY DIAGONAL = 1, default = 0 |
| 682 | |
| 683 | =for example |
| 684 | |
| 685 | # Assume $a is upper triangular |
| 686 | my $a = random(10,10); |
| 687 | my $inv = mtriinv($a); |
| 688 | |
| 689 | =cut |
| 690 | |
| 691 | *mtriinv = \&PDL::mtriinv; |
| 692 | sub PDL::mtriinv { |
| 693 | &_square; |
| 694 | my $m = shift->new_or_inplace; |
| 695 | my $upper = @_ ? (1 - shift) : pdl (long,1); |
| 696 | my $diag = shift; |
| 697 | my ($info) = $m->_call_method('trtri', $upper, $diag); |
| 698 | _error($info, "mtriinv: Matrix (PDL(s) %s) is/are singular"); |
| 699 | wantarray ? ($m, $info) : $m; |
| 700 | } |
| 701 | |
| 702 | =head2 msyminv |
| 703 | |
| 704 | =for ref |
| 705 | |
| 706 | Computes inverse of a symmetric square matrix using the Bunch-Kaufman diagonal pivoting method. |
| 707 | Supports inplace and broadcasting. |
| 708 | Uses L<sytrf|PDL::LinearAlgebra::Real/sytrf> and L<sytri|PDL::LinearAlgebra::Real/sytri> or |
| 709 | L<csytrf|PDL::LinearAlgebra::Complex/csytrf> and L<csytri|PDL::LinearAlgebra::Complex/csytri> |
| 710 | from LAPACK and returns C<inverse, info> in array context. |
| 711 | |
| 712 | =for usage |
| 713 | |
| 714 | (PDL, (PDL(info))) = msyminv(PDL, SCALAR|PDL(uplo)) |
| 715 | uplo : UPPER = 0 | LOWER = 1, default = 0 |
| 716 | |
| 717 | =for example |
| 718 | |
| 719 | # Assume $a is symmetric |
| 720 | my $a = random(10,10); |
| 721 | my $inv = msyminv($a); |
| 722 | |
| 723 | =cut |
| 724 | |
| 725 | *msyminv = \&PDL::msyminv; |
| 726 | sub PDL::msyminv { |
| 727 | &_square; |
| 728 | my $m = shift->new_or_inplace; |
| 729 | my $upper = @_ ? (1 - shift) : pdl (long,1); |
| 730 | my ($ipiv, $info) = $m->_call_method('sytrf', $upper); |
| 731 | _error($info, "msyminv: Block diagonal matrix D (PDL(s) %s) is/are singular (after sytrf factorization)"); |
| 732 | $m->_call_method('sytri',$upper,$ipiv,$info); |
| 733 | $m = $m->t->tritosym($upper, 0); |
| 734 | wantarray ? ($m, $info) : $m; |
| 735 | } |
| 736 | |
| 737 | =head2 mposinv |
| 738 | |
| 739 | =for ref |
| 740 | |
| 741 | Computes inverse of a symmetric positive definite square matrix using Cholesky factorization. |
| 742 | Supports inplace and broadcasting. |
| 743 | Uses L<potrf|PDL::LinearAlgebra::Real/potrf> and L<potri|PDL::LinearAlgebra::Real/potri> or |
| 744 | L<cpotrf|PDL::LinearAlgebra::Complex/cpotrf> and L<cpotri|PDL::LinearAlgebra::Complex/cpotri> |
| 745 | from LAPACK and returns C<inverse, info> in array context. |
| 746 | |
| 747 | =for usage |
| 748 | |
| 749 | (PDL, (PDL(info))) = mposinv(PDL, SCALAR|PDL(uplo)) |
| 750 | uplo : UPPER = 0 | LOWER = 1, default = 0 |
| 751 | |
| 752 | =for example |
| 753 | |
| 754 | # Assume $a is symmetric positive definite |
| 755 | my $a = random(10,10); |
| 756 | $a = $a->crossprod($a); |
| 757 | my $inv = mposinv($a); |
| 758 | |
| 759 | =cut |
| 760 | |
| 761 | *mposinv = \&PDL::mposinv; |
| 762 | sub PDL::mposinv { |
| 763 | &_square; |
| 764 | my $m = shift->new_or_inplace; |
| 765 | my $upper = @_ ? (1 - shift) : pdl (long,1); |
| 766 | my ($info) = $m->_call_method('potrf', $upper); |
| 767 | _error($info, "mposinv: matrix (PDL(s) %s) is/are not positive definite (after potrf factorization)"); |
| 768 | $m->_call_method('potri', $upper, $info); |
| 769 | wantarray ? ($m, $info) : $m; |
| 770 | } |
| 771 | |
| 772 | =head2 mpinv |
| 773 | |
| 774 | =for ref |
| 775 | |
| 776 | Computes pseudo-inverse (Moore-Penrose) of a general matrix. |
| 777 | Works on transposed array. |
| 778 | |
| 779 | =for usage |
| 780 | |
| 781 | PDL(pseudo-inv) = mpinv(PDL, SCALAR(tol)) |
| 782 | TOL: tolerance value, default : mnorm(dims(PDL),'inf') * mnorm(PDL) * EPS |
| 783 | |
| 784 | =for example |
| 785 | |
| 786 | my $a = random(5,10); |
| 787 | my $inv = mpinv($a); |
| 788 | |
| 789 | =cut |
| 790 | |
| 791 | *mpinv = \&PDL::mpinv; |
| 792 | sub PDL::mpinv { |
| 793 | &_2d_array; |
| 794 | my ($m, $tol) = @_; |
| 795 | my @dims = $m->dims; |
| 796 | my $err = setlaerror(NO); |
| 797 | my ($u, $s, $vt, $info) = $m->mdsvd(2); |
| 798 | setlaerror($err); |
| 799 | _error($info, "mpinv: SVD algorithm did not converge (PDL %s)"); |
| 800 | $tol //= ($dims[1] > $dims[0] ? $dims[1] : $dims[0]) * $s->slice('(0)') * lamch(3); |
| 801 | my ($ind, $cind) = whichND_both( $s > $tol ); |
| 802 | $s->indexND($cind) .= 0 if defined $cind and !$cind->isempty; |
| 803 | $s->indexND($ind) .= 1/$s->indexND($ind); |
| 804 | my $pinv = gurney($s,@dims[1,0,2..$#dims]) x $u->t(1); |
| 805 | $pinv = $vt->t(1) x $pinv; |
| 806 | return wantarray ? ($pinv, $info) : $pinv; |
| 807 | } |
| 808 | |
| 809 | =head2 mlu |
| 810 | |
| 811 | =for ref |
| 812 | |
| 813 | Computes LU factorization. |
| 814 | Uses L<getrf|PDL::LinearAlgebra::Real/getrf> or L<cgetrf|PDL::LinearAlgebra::Complex/cgetrf> |
| 815 | from LAPACK and returns L, U, pivot and info. |
| 816 | Works on transposed array. |
| 817 | |
| 818 | =for usage |
| 819 | |
| 820 | (PDL(l), PDL(u), PDL(pivot), PDL(info)) = mlu(PDL) |
| 821 | |
| 822 | =for example |
| 823 | |
| 824 | my $a = random(10,10); |
| 825 | ($l, $u, $pivot, $info) = mlu($a); |
| 826 | |
| 827 | =cut |
| 828 | |
| 829 | *mlu = \&PDL::mlu; |
| 830 | |
| 831 | sub PDL::mlu { |
| 832 | &_2d_array; |
| 833 | my $m = shift; |
| 834 | my @dims = $m->dims; |
| 835 | $m = $m->copy; |
| 836 | my ($ipiv, $info) = $m->t->_call_method('getrf'); |
| 837 | if ($info > 0) { |
| 838 | $info--; |
| 839 | laerror("mlu: Factor U is singular: U($info,$info) = 0 (after getrf factorization)"); |
| 840 | return $m, $m, $ipiv, $info; |
| 841 | } |
| 842 | my $u = $m->mtri; |
| 843 | my $l = $m->mtri(1); |
| 844 | my $smallerm1 = ($dims[0] < $dims[1] ? $dims[0] : $dims[1]) - 1; |
| 845 | if ($dims[1] > $dims[0]) { |
| 846 | $u = $u->slice(",:$smallerm1")->sever; |
| 847 | $l->slice(":$smallerm1, :$smallerm1")->diagonal(0,1) .= 1; |
| 848 | } else { |
| 849 | $l = $l->slice(":$smallerm1")->sever if $dims[1] < $dims[0]; |
| 850 | $l->diagonal(0,1) .= 1; |
| 851 | } |
| 852 | $l, $u, $ipiv, $info; |
| 853 | } |
| 854 | |
| 855 | =head2 mchol |
| 856 | |
| 857 | =for ref |
| 858 | |
| 859 | Computes Cholesky decomposition of a symmetric matrix also known as symmetric square root. |
| 860 | If inplace flag is set, overwrite the leading upper or lower triangular part of A else returns |
| 861 | triangular matrix. Returns C<cholesky, info> in array context. |
| 862 | Supports broadcasting. |
| 863 | Uses L<potrf|PDL::LinearAlgebra::Real/potrf> or L<cpotrf|PDL::LinearAlgebra::Complex/cpotrf> from LAPACK. |
| 864 | |
| 865 | =for usage |
| 866 | |
| 867 | PDL(Cholesky) = mchol(PDL, SCALAR) |
| 868 | SCALAR : UPPER = 0 | LOWER = 1, default = 0 |
| 869 | |
| 870 | =for example |
| 871 | |
| 872 | my $a = random(10,10); |
| 873 | $a = crossprod($a, $a); |
| 874 | my $u = mchol($a); |
| 875 | |
| 876 | =cut |
| 877 | |
| 878 | *mchol = \&PDL::mchol; |
| 879 | sub PDL::mchol { |
| 880 | &_square; |
| 881 | my ($m, $upper) = @_; |
| 882 | my @dims = $m->dims; |
| 883 | $m = $m->mtri($upper) unless $m->is_inplace(0); |
| 884 | @dims = @dims[2..$#dims]; |
| 885 | my $uplo = 1 - $upper; |
| 886 | my ($info) = $m->_call_method('potrf',$uplo); |
| 887 | _error($info, "mchol: matrix (PDL(s) %s) is/are not positive definite (after potrf factorization)"); |
| 888 | wantarray ? ($m, $info) : $m; |
| 889 | } |
| 890 | |
| 891 | =head2 mhessen |
| 892 | |
| 893 | =for ref |
| 894 | |
| 895 | Reduces a square matrix to Hessenberg form H and orthogonal matrix Q. |
| 896 | |
| 897 | It reduces a general matrix A to upper Hessenberg form H by an orthogonal |
| 898 | similarity transformation: |
| 899 | |
| 900 | Q' x A x Q = H |
| 901 | |
| 902 | or |
| 903 | |
| 904 | A = Q x H x Q' |
| 905 | |
| 906 | Uses L<gehrd|PDL::LinearAlgebra::Real/gehrd> and L<orghr|PDL::LinearAlgebra::Real/orghr> or |
| 907 | L<cgehrd|PDL::LinearAlgebra::Complex/cgehrd> and L<cunghr|PDL::LinearAlgebra::Complex/cunghr> |
| 908 | from LAPACK and returns C<H> in scalar context else C<H> and C<Q>. |
| 909 | Works on transposed array. |
| 910 | |
| 911 | =for usage |
| 912 | |
| 913 | (PDL(h), (PDL(q))) = mhessen(PDL) |
| 914 | |
| 915 | =for example |
| 916 | |
| 917 | my $a = random(10,10); |
| 918 | ($h, $q) = mhessen($a); |
| 919 | |
| 920 | =cut |
| 921 | |
| 922 | *mhessen = \&PDL::mhessen; |
| 923 | sub PDL::mhessen { |
| 924 | &_square; |
| 925 | my @diag_args = (0,1); |
| 926 | my $slice_arg = ":-2, 1:"; |
| 927 | my $m = shift; |
| 928 | my(@dims) = $m->dims; |
| 929 | $m = $m->t->copy; |
| 930 | $m->_call_method('gehrd',1,$dims[0], my $tau = $m->_similar($dims[0]-1),my $info = null); |
| 931 | (my $q = $m->copy)->_call_method(['orghr','cunghr'], 1, $dims[0], $tau, $info) if wantarray; |
| 932 | my $h = ($m = $m->t)->mtri; |
| 933 | $h->slice($slice_arg)->diagonal(@diag_args) .= $m->slice($slice_arg)->diagonal(@diag_args); |
| 934 | wantarray ? return ($h, $q->t->sever) : $h; |
| 935 | } |
| 936 | |
| 937 | =head2 mschur |
| 938 | |
| 939 | =for ref |
| 940 | |
| 941 | Computes Schur form, works inplace. |
| 942 | |
| 943 | A = Z x T x Z' |
| 944 | |
| 945 | Supports broadcasting for unordered eigenvalues. |
| 946 | Uses L<gees|PDL::LinearAlgebra::Real/gees> or L<cgees|PDL::LinearAlgebra::Complex/cgees> |
| 947 | from LAPACK and returns schur(T) in scalar context. |
| 948 | Works on transposed array(s). |
| 949 | |
| 950 | =for usage |
| 951 | |
| 952 | ( PDL(schur), (PDL(eigenvalues), (PDL(left schur vectors), PDL(right schur vectors), $sdim), $info) ) = mschur(PDL(A), SCALAR(schur vector),SCALAR(left eigenvector), SCALAR(right eigenvector),SCALAR(select_func), SCALAR(backtransform), SCALAR(norm)) |
| 953 | schur vector : Schur vectors returned, none = 0 | all = 1 | selected = 2, default = 0 |
| 954 | left eigenvector : Left eigenvectors returned, none = 0 | all = 1 | selected = 2, default = 0 |
| 955 | right eigenvector : Right eigenvectors returned, none = 0 | all = 1 | selected = 2, default = 0 |
| 956 | select_func : Select_func is used to select eigenvalues to sort |
| 957 | to the top left of the Schur form. |
| 958 | An eigenvalue is selected if PerlInt select_func(w) is true; |
| 959 | (the inputs are converted to complex ndarrays for you) |
| 960 | Note that a selected complex eigenvalue may no longer |
| 961 | satisfy select_func(w) = 1 after ordering, since |
| 962 | ordering may change the value of complex eigenvalues |
| 963 | (especially if the eigenvalue is ill-conditioned). |
| 964 | All eigenvalues/vectors are selected if select_func is undefined. |
| 965 | backtransform : Whether or not backtransforms eigenvectors to those of A. |
| 966 | Only supported if schur vectors are computed, default = 1. |
| 967 | norm : Whether or not computed eigenvectors are normalized to have Euclidean norm equal to |
| 968 | 1 and largest component real, default = 1 |
| 969 | |
| 970 | Returned values : |
| 971 | Schur form T (SCALAR CONTEXT), |
| 972 | eigenvalues, |
| 973 | Schur vectors (Z) if requested, |
| 974 | left eigenvectors if requested |
| 975 | right eigenvectors if requested |
| 976 | sdim: Number of eigenvalues selected if select_func is defined. |
| 977 | info: Info output from gees/cgees. |
| 978 | |
| 979 | =for example |
| 980 | |
| 981 | my $a = random(10,10); |
| 982 | my $schur = mschur($a); |
| 983 | sub select { |
| 984 | my $w = shift; |
| 985 | # select "discrete time" eigenspace |
| 986 | return $w->Cabs < 1 ? 1 : 0; |
| 987 | } |
| 988 | my ($schur,$eigen,$svectors,$evectors) = mschur($a,1,1,0,\&select); |
| 989 | |
| 990 | =cut |
| 991 | |
| 992 | sub _eigen_extract { |
| 993 | my ($jobvl, $jobvr, $vl, $vr, @w) = @_; |
| 994 | return ($w[0], $vl, $vr) if @w == 1; |
| 995 | my $w; |
| 996 | ($w, $vl) = cplx_eigen(@w, $vl, 1) if $jobvl; |
| 997 | ($w, $vr) = cplx_eigen(@w, $vr, 1) if $jobvr; |
| 998 | $w = _ecplx(@w) if !defined $w; |
| 999 | ($w, $vl, $vr); |
| 1000 | } |
| 1001 | |
| 1002 | sub _eigen_one { |
| 1003 | my ($mm, $select_func, $jobv, $jobvl, $jobvr, $mult, $norm, $mdim, $sdim, @w) = @_; |
| 1004 | my $job = $jobvr && $jobvl ? undef : $jobvl ? 2 : 1; |
| 1005 | my $is_mult = $jobvl == 1 || $jobvr == 1 || $mult; |
| 1006 | $_ = $mm->_similar_null for my ($vl, $vr); |
| 1007 | $mult = ($select_func && !$is_mult) ? 2 : !$jobv ? 0 : $mult; |
| 1008 | my $sel = ($select_func && !$is_mult) ? zeroes($mdim) : undef; |
| 1009 | $sel(:($sdim-1)) .= 1 if defined $sel; |
| 1010 | $mm->_call_method('trevc', $job, $mult, $sel, $vl, $vr, $sdim, my $infos=null); |
| 1011 | @w = map $is_mult || !$select_func ? $_ : $_(:($sdim-1)), @w if @w == 2; |
| 1012 | my @ret; |
| 1013 | for ([$jobvr,$vr], [$jobvl,$vl]) { |
| 1014 | unshift(@ret, undef), next if !$_->[0]; |
| 1015 | my $val; |
| 1016 | if (@w == 2) { |
| 1017 | (undef,$val) = cplx_eigen(@w,$norm?($_->[1],1):($_->[1]->t,0)); |
| 1018 | } else { |
| 1019 | $val = $_->[1]; |
| 1020 | } |
| 1021 | unshift(@ret, $norm ? $val->_norm(1,1) : $val), next if !$is_mult or !$select_func; |
| 1022 | $val = $val->slice(",:@{[$sdim-1]}")->sever if $_->[0] == 2; |
| 1023 | $val = $val->_norm(1,1) if $norm; |
| 1024 | unshift @ret, $val; |
| 1025 | } |
| 1026 | @ret; |
| 1027 | } |
| 1028 | |
| 1029 | *mschur = \&PDL::mschur; |
| 1030 | sub PDL::mschur { |
| 1031 | &_square; |
| 1032 | my ($m, $jobv, $jobvl, $jobvr, $select_func, $mult, $norm) = @_; |
| 1033 | my @dims = $m->dims; |
| 1034 | barf("mschur: broadcasting not supported for selected vectors") |
| 1035 | if $select_func && @dims > 2 |
| 1036 | && (grep $_ == 2, $jobv, $jobvl, $jobvr); |
| 1037 | $mult //= 1; |
| 1038 | $norm //= 1; |
| 1039 | $jobv = $jobvl = $jobvr = 0 unless wantarray; |
| 1040 | my $mm = $m->new_or_inplace->t; |
| 1041 | my $v = $m->_similar_null; |
| 1042 | my @w = map $m->_similar_null, $m->_is_complex ? 1 : 1..2; |
| 1043 | my $select_f = $m->_wrap_select_func($select_func); |
| 1044 | $mm->_call_method('gees', |
| 1045 | $jobv, $select_func ? 1 : 0, $select_f, @w, |
| 1046 | $v, my $sdim = null, my $info = null |
| 1047 | ); |
| 1048 | _error_schur($info, $select_func, $dims[0], 'mschur', 'QR'); |
| 1049 | my @ret = !$select_func || $sdim ? () : map _complex_null(), grep $_ == 2, $jobvl, $jobvr; |
| 1050 | push @ret, $sdim if $select_func; |
| 1051 | $_ = 0 for grep $select_func && $_ == 2 && !$sdim, $jobvl, $jobvr; |
| 1052 | my $w = @w == 2 ? _ecplx(@w) : @w[0]; |
| 1053 | if ($jobvl || $jobvr) { |
| 1054 | unshift @ret, grep defined, _eigen_one( |
| 1055 | $mm, $select_func, $jobv, $jobvl, $jobvr, |
| 1056 | $mult, $norm, $dims[1], $sdim, @w |
| 1057 | ); |
| 1058 | } |
| 1059 | if ($jobv == 2 && $select_func) { |
| 1060 | unshift @ret, $sdim > 0 ? $v->t->slice(":@{[$sdim-1]}")->sever : $m->_similar_null; |
| 1061 | } elsif ($jobv) { |
| 1062 | unshift @ret, $v->t->sever; |
| 1063 | } |
| 1064 | $m = $mm->t->sever unless $m->is_inplace(0); |
| 1065 | return wantarray ? ($m, $w, @ret, $info) : $m; |
| 1066 | } |
| 1067 | |
| 1068 | =head2 mschurx |
| 1069 | |
| 1070 | =for ref |
| 1071 | |
| 1072 | Computes Schur form, works inplace. |
| 1073 | Uses L<geesx|PDL::LinearAlgebra::Real/geesx> or L<cgeesx|PDL::LinearAlgebra::Complex/cgeesx> |
| 1074 | from LAPACK and returns schur(T) in scalar context. |
| 1075 | Works on transposed array. |
| 1076 | |
| 1077 | =for usage |
| 1078 | |
| 1079 | ( PDL(schur) (,PDL(eigenvalues)) (, PDL(schur vectors), HASH(result)) ) = mschurx(PDL, SCALAR(schur vector), SCALAR(left eigenvector), SCALAR(right eigenvector),SCALAR(select_func), SCALAR(sense), SCALAR(backtransform), SCALAR(norm)) |
| 1080 | schur vector : Schur vectors returned, none = 0 | all = 1 | selected = 2, default = 0 |
| 1081 | left eigenvector : Left eigenvectors returned, none = 0 | all = 1 | selected = 2, default = 0 |
| 1082 | right eigenvector : Right eigenvectors returned, none = 0 | all = 1 | selected = 2, default = 0 |
| 1083 | select_func : Select_func is used to select eigenvalues to sort |
| 1084 | to the top left of the Schur form. |
| 1085 | An eigenvalue is selected if PerlInt select_func(w) is true; |
| 1086 | (the inputs are converted to complex ndarrays for you) |
| 1087 | Note that a selected complex eigenvalue may no longer |
| 1088 | satisfy select_func(w) = 1 after ordering, since |
| 1089 | ordering may change the value of complex eigenvalues |
| 1090 | (especially if the eigenvalue is ill-conditioned). |
| 1091 | All eigenvalues/vectors are selected if select_func is undefined. |
| 1092 | sense : Determines which reciprocal condition numbers will be computed. |
| 1093 | 0: None are computed |
| 1094 | 1: Computed for average of selected eigenvalues only |
| 1095 | 2: Computed for selected right invariant subspace only |
| 1096 | 3: Computed for both |
| 1097 | If select_func is undefined, sense is not used. |
| 1098 | backtransform : Whether or not backtransforms eigenvectors to those of A. |
| 1099 | Only supported if schur vector are computed, default = 1 |
| 1100 | norm : Whether or not computed eigenvectors are normalized to have Euclidean norm equal to |
| 1101 | 1 and largest component real, default = 1 |
| 1102 | |
| 1103 | Returned values : |
| 1104 | Schur form T (SCALAR CONTEXT), |
| 1105 | eigenvalues, |
| 1106 | Schur vectors if requested, |
| 1107 | HASH{VL}: left eigenvectors if requested |
| 1108 | HASH{VR}: right eigenvectors if requested |
| 1109 | HASH{info}: info output from gees/cgees. |
| 1110 | if select_func is defined: |
| 1111 | HASH{n}: number of eigenvalues selected, |
| 1112 | HASH{rconde}: reciprocal condition numbers for the average of |
| 1113 | the selected eigenvalues if requested, |
| 1114 | HASH{rcondv}: reciprocal condition numbers for the selected |
| 1115 | right invariant subspace if requested. |
| 1116 | |
| 1117 | =for example |
| 1118 | |
| 1119 | my $a = random(10,10); |
| 1120 | my $schur = mschurx($a); |
| 1121 | sub select { |
| 1122 | my $m = shift; |
| 1123 | # select "discrete time" eigenspace |
| 1124 | return $m->Cabs < 1 ? 1 : 0; |
| 1125 | } |
| 1126 | my ($schur,$eigen, $vectors,%ret) = mschurx($a,1,0,0,\&select); |
| 1127 | |
| 1128 | =cut |
| 1129 | |
| 1130 | *mschurx = \&PDL::mschurx; |
| 1131 | sub PDL::mschurx { |
| 1132 | &_square; |
| 1133 | my($m, $jobv, $jobvl, $jobvr, $select_func, $sense, $mult,$norm) = @_; |
| 1134 | my(@dims) = $m->dims; |
| 1135 | $mult //= 1; |
| 1136 | $norm //= 1; |
| 1137 | $jobv = $jobvl = $jobvr = 0 unless wantarray; |
| 1138 | my $select = long($select_func ? 1 : 0); |
| 1139 | $sense = pdl(long,0) if !$select_func; |
| 1140 | $_ = null for my ($info, $sdim, $rconde, $rcondv); |
| 1141 | my $mm = $m->new_or_inplace->t; |
| 1142 | my $v = $m->_similar_null; |
| 1143 | my @w = map $m->_similar_null, $m->_is_complex ? 1 : 1..2; |
| 1144 | my $select_f = $m->_wrap_select_func($select_func); |
| 1145 | $mm->_call_method('geesx', $jobv, $select, $sense, $select_f, @w, $v, $sdim, $rconde, $rcondv,$info); |
| 1146 | _error_schur($info, $select_func, $dims[0], 'mschurx', 'QR'); |
| 1147 | my @vl = ('VL', $jobvl); |
| 1148 | my @vr = ('VR', $jobvr); |
| 1149 | my %ret; |
| 1150 | $ret{$_->[0]} = _complex_null(), $_->[1]=0 for grep $select_func && !$sdim && $_->[1] == 2, \@vl, \@vr; |
| 1151 | $ret{n} = $sdim if $select_func; |
| 1152 | if ($vl[1] || $vr[1]) { |
| 1153 | my ($vl, $vr) = _eigen_one( |
| 1154 | $mm, $select_func, $jobv, $vl[1], $vr[1], |
| 1155 | $mult, $norm, $dims[1], $sdim, @w |
| 1156 | ); |
| 1157 | $ret{$_->[0]} = $_->[1] for grep defined $_->[1], ['VL',$vl], ['VR',$vr]; |
| 1158 | } |
| 1159 | my $w = _ecplx(@w); |
| 1160 | if ($jobv == 2 && $select_func) { |
| 1161 | $v = $sdim > 0 ? $v->t->slice(":@{[$sdim-1]},")->sever : $m->_similar_null; |
| 1162 | } elsif ($jobv) { |
| 1163 | $v = $v->t->sever; |
| 1164 | } |
| 1165 | $ret{info} = $info; |
| 1166 | $ret{rconde} = $rconde if $sense & 1; |
| 1167 | $ret{rcondv} = $rcondv if $sense & 2; |
| 1168 | $m = $mm->t->sever unless $m->is_inplace(0); |
| 1169 | !wantarray ? $m : ($m, $w, ($jobv ? $v : ()), %ret); |
| 1170 | } |
| 1171 | |
| 1172 | # scale by max(abs(real)+abs(imag)) |
| 1173 | sub magn_norm { |
| 1174 | my ($m, $trans) = @_; |
| 1175 | # If trans == true => transpose output matrix |
| 1176 | my $ret = PDL::cat(map $m->$_, qw(re im))->mv(-1,0)->abs->sumover->maxover->dummy(0); |
| 1177 | $m = $m->t, $ret = $ret->t if $trans; |
| 1178 | ($m/$ret)->reshape(-1); |
| 1179 | } |
| 1180 | |
| 1181 | #TODO: inplace ? |
| 1182 | |
| 1183 | =head2 mgschur |
| 1184 | |
| 1185 | =for ref |
| 1186 | |
| 1187 | Computes generalized Schur decomposition of the pair (A,B). |
| 1188 | |
| 1189 | A = Q x S x Z' |
| 1190 | B = Q x T x Z' |
| 1191 | |
| 1192 | Uses L<gges|PDL::LinearAlgebra::Real/gges> or L<cgges|PDL::LinearAlgebra::Complex/cgges> |
| 1193 | from LAPACK. |
| 1194 | Works on transposed array. |
| 1195 | |
| 1196 | =for usage |
| 1197 | |
| 1198 | ( PDL(schur S), PDL(schur T), PDL(alpha), PDL(beta), HASH{result}) = mgschur(PDL(A), PDL(B), SCALAR(left schur vector),SCALAR(right schur vector),SCALAR(left eigenvector), SCALAR(right eigenvector), SCALAR(select_func), SCALAR(backtransform), SCALAR(scale)) |
| 1199 | left schur vector : Left Schur vectors returned, none = 0 | all = 1 | selected = 2, default = 0 |
| 1200 | right schur vector : Right Schur vectors returned, none = 0 | all = 1 | selected = 2, default = 0 |
| 1201 | left eigenvector : Left eigenvectors returned, none = 0 | all = 1 | selected = 2, default = 0 |
| 1202 | right eigenvector : Right eigenvectors returned, none = 0 | all = 1 | selected = 2, default = 0 |
| 1203 | select_func : Select_func is used to select eigenvalues to sort. |
| 1204 | to the top left of the Schur form. |
| 1205 | An eigenvalue w = wr(j)+sqrt(-1)*wi(j) is selected if |
| 1206 | PerlInt select_func(alpha,beta) is true; |
| 1207 | (the inputs are converted to complex ndarrays for you) |
| 1208 | Note that a selected complex eigenvalue may no longer |
| 1209 | satisfy select_func = 1 after ordering, since |
| 1210 | ordering may change the value of complex eigenvalues |
| 1211 | (especially if the eigenvalue is ill-conditioned). |
| 1212 | All eigenvalues/vectors are selected if select_func is undefined. |
| 1213 | backtransform : Whether or not backtransforms eigenvectors to those of (A,B). |
| 1214 | Only supported if right and/or left schur vector are computed, |
| 1215 | scale : Whether or not computed eigenvectors are scaled so the largest component |
| 1216 | will have abs(real part) + abs(imag. part) = 1, default = 1 |
| 1217 | |
| 1218 | Returned values : |
| 1219 | Schur form S, |
| 1220 | Schur form T, |
| 1221 | alpha, |
| 1222 | beta (eigenvalues = alpha/beta), |
| 1223 | HASH{info}: info output from gges/cgges. |
| 1224 | HASH{SL}: left Schur vectors if requested |
| 1225 | HASH{SR}: right Schur vectors if requested |
| 1226 | HASH{VL}: left eigenvectors if requested |
| 1227 | HASH{VR}: right eigenvectors if requested |
| 1228 | HASH{n} : Number of eigenvalues selected if select_func is defined. |
| 1229 | |
| 1230 | =for example |
| 1231 | |
| 1232 | my $a = random(10,10); |
| 1233 | my $b = random(10,10); |
| 1234 | my ($S,$T) = mgschur($a,$b); |
| 1235 | sub select { |
| 1236 | my ($alpha,$beta) = @_; |
| 1237 | return $alpha->Cabs < abs($beta) ? 1 : 0; |
| 1238 | } |
| 1239 | my ($S, $T, $alpha, $beta, %res) = mgschur( $a, $b, 1, 1, 1, 1,\&select); |
| 1240 | |
| 1241 | =cut |
| 1242 | |
| 1243 | sub _eigen_pair { |
| 1244 | my ( |
| 1245 | $mm, $pp, $select_func, $jobvl, $jobvr, $jobvsl, $jobvsr, $vsl, $vsr, |
| 1246 | $mult, $norm, $mdim, $sdim, @w |
| 1247 | ) = @_; |
| 1248 | my $job = !($jobvr && $jobvl) ? $jobvl ? 2 : 1 : undef; |
| 1249 | $_ = $mm->_similar_null for my ($vl, $vr); |
| 1250 | $mult = 0 if ($jobvl && !$jobvsl) || ($jobvr && !$jobvsr); |
| 1251 | if (!$select_func || ($jobvl == 1 || $jobvr == 1 || $mult)) { |
| 1252 | $vl .= $vsl if $jobvl && $jobvsl; |
| 1253 | $vr .= $vsr if $jobvr && $jobvsr; |
| 1254 | } |
| 1255 | my ($sdim_in, $sel) = $sdim; |
| 1256 | if ($select_func) { |
| 1257 | if ($jobvl == 1 || $jobvr == 1 || $mult) { |
| 1258 | $sdim_in = null; |
| 1259 | } else { |
| 1260 | $sel = zeroes($mdim); |
| 1261 | $sel(:($sdim-1)) .= 1; |
| 1262 | $mult = 2; |
| 1263 | @w = map $_(:($sdim-1)), @w; |
| 1264 | } |
| 1265 | } |
| 1266 | $mm->_call_method('tgevc', $job, $mult, $pp, $sel, $vl, $vr, $sdim_in, my $infos=null); |
| 1267 | if (@w == 2) { |
| 1268 | (undef,$vl) = cplx_eigen(@w,$vl->t,0) if $jobvl; |
| 1269 | (undef,$vr) = cplx_eigen(@w,$vr->t,0) if $jobvr; |
| 1270 | } |
| 1271 | if ($select_func && ($jobvl == 1 || $jobvr == 1 || $mult)) { |
| 1272 | $vr = $vr(,:($sdim-1))->sever if $jobvr == 2; |
| 1273 | $vl = $vl(,:($sdim-1))->sever if $jobvl == 2; |
| 1274 | } |
| 1275 | $vl = magn_norm($vl,1) if $jobvl and $norm; |
| 1276 | $vr = magn_norm($vr,1) if $jobvr and $norm; |
| 1277 | ($vl, $vr); |
| 1278 | } |
| 1279 | |
| 1280 | *mgschur = \&PDL::mgschur; |
| 1281 | sub PDL::mgschur { |
| 1282 | &_square_same; |
| 1283 | my($m, $p, $jobvsl, $jobvsr, $jobvl, $jobvr, $select_func, $mult, $norm) = @_; |
| 1284 | my @mdims = $m->dims; |
| 1285 | $_ = $_->new_or_inplace->t for $m, $p; |
| 1286 | barf("mgschur: broadcasting isn't supported for selected vectors") |
| 1287 | if ($select_func && ((@mdims > 2) || ($p->ndims > 2)) && |
| 1288 | ($jobvsl == 2 || $jobvsr == 2 || $jobvl == 2 || $jobvr == 2)); |
| 1289 | $mult //= 1; |
| 1290 | $norm //= 1; |
| 1291 | my $select = $select_func ? pdl(long,1) : pdl(long,0); |
| 1292 | $_ = null for my ($info, $sdim); |
| 1293 | my $select_f = $m->_wrap_select_func($select_func); |
| 1294 | my @w = map $m->_similar_null, $m->_is_complex ? 1 : 1..2; |
| 1295 | $_ = $m->_similar_null for my ($beta, $vsl, $vsr); |
| 1296 | $m->_call_method('gges', $jobvsl, $jobvsr, $select, $p, $select_f, @w, $beta, $vsl, $vsr, $sdim, $info); |
| 1297 | _error_schur($info, $select_func, $mdims[0], 'mgschur', 'QZ'); |
| 1298 | my @vl = ('VL', $jobvl); |
| 1299 | my @vr = ('VR', $jobvr); |
| 1300 | my %ret; |
| 1301 | $ret{$_->[0]} = _complex_null(), $_->[1]=0 for grep $select_func && !$sdim && $_->[1] == 2, \@vl, \@vr; |
| 1302 | $ret{n} = $sdim if $select_func; |
| 1303 | if ($vl[1] || $vr[1]) { |
| 1304 | my ($vl, $vr) = _eigen_pair( |
| 1305 | $m, $p, $select_func, $vl[1], $vr[1], $jobvsl, $jobvsr, $vsl, $vsr, |
| 1306 | $mult, $norm, $mdims[1], $sdim, @w |
| 1307 | ); |
| 1308 | $ret{$_->[0]} = $_->[1] for grep defined $_->[1], ['VL',$vl], ['VR',$vr]; |
| 1309 | } |
| 1310 | my $w = @w == 2 ? _ecplx(@w) : @w[0]; |
| 1311 | if ($jobvsl == 2 && $select_func) { |
| 1312 | $ret{SL} = $sdim ? $vsl->t->slice(":@{[$sdim-1]},")->sever : $m->_similar_null; |
| 1313 | } elsif ($jobvsl) { |
| 1314 | $ret{SL} = $vsl->t->sever; |
| 1315 | } |
| 1316 | if ($jobvsr == 2 && $select_func) { |
| 1317 | $ret{SR} = $sdim ? $vsr->t->slice(":@{[$sdim-1]},")->sever : $m->_similar_null; |
| 1318 | } elsif ($jobvsr) { |
| 1319 | $ret{SR} = $vsr->t->sever; |
| 1320 | } |
| 1321 | $ret{info} = $info; |
| 1322 | return ($m->t, $p->t, $w, $beta, %ret); |
| 1323 | } |
| 1324 | |
| 1325 | =head2 mgschurx |
| 1326 | |
| 1327 | =for ref |
| 1328 | |
| 1329 | Computes generalized Schur decomposition of the pair (A,B). |
| 1330 | |
| 1331 | A = Q x S x Z' |
| 1332 | B = Q x T x Z' |
| 1333 | |
| 1334 | Uses L<ggesx|PDL::LinearAlgebra::Real/ggesx> or L<cggesx|PDL::LinearAlgebra::Complex/cggesx> |
| 1335 | from LAPACK. Works on transposed array. |
| 1336 | |
| 1337 | =for usage |
| 1338 | |
| 1339 | ( PDL(schur S), PDL(schur T), PDL(alpha), PDL(beta), HASH{result}) = mgschurx(PDL(A), PDL(B), SCALAR(left schur vector),SCALAR(right schur vector),SCALAR(left eigenvector), SCALAR(right eigenvector), SCALAR(select_func), SCALAR(sense), SCALAR(backtransform), SCALAR(scale)) |
| 1340 | left schur vector : Left Schur vectors returned, none = 0 | all = 1 | selected = 2, default = 0 |
| 1341 | right schur vector : Right Schur vectors returned, none = 0 | all = 1 | selected = 2, default = 0 |
| 1342 | left eigenvector : Left eigenvectors returned, none = 0 | all = 1 | selected = 2, default = 0 |
| 1343 | right eigenvector : Right eigenvectors returned, none = 0 | all = 1 | selected = 2, default = 0 |
| 1344 | select_func : Select_func is used to select eigenvalues to sort. |
| 1345 | to the top left of the Schur form. |
| 1346 | An eigenvalue w = wr(j)+sqrt(-1)*wi(j) is selected if |
| 1347 | PerlInt select_func(alpha,beta) is true; |
| 1348 | (the inputs are converted to complex ndarrays for you) |
| 1349 | Note that a selected complex eigenvalue may no longer |
| 1350 | satisfy select_func = 1 after ordering, since |
| 1351 | ordering may change the value of complex eigenvalues |
| 1352 | (especially if the eigenvalue is ill-conditioned). |
| 1353 | All eigenvalues/vectors are selected if select_func is undefined. |
| 1354 | sense : Determines which reciprocal condition numbers will be computed. |
| 1355 | 0: None are computed |
| 1356 | 1: Computed for average of selected eigenvalues only |
| 1357 | 2: Computed for selected deflating subspaces only |
| 1358 | 3: Computed for both |
| 1359 | If select_func is undefined, sense is not used. |
| 1360 | |
| 1361 | backtransform : Whether or not backtransforms eigenvectors to those of (A,B). |
| 1362 | Only supported if right and/or left schur vector are computed, default = 1 |
| 1363 | scale : Whether or not computed eigenvectors are scaled so the largest component |
| 1364 | will have abs(real part) + abs(imag. part) = 1, default = 1 |
| 1365 | |
| 1366 | Returned values : |
| 1367 | Schur form S, |
| 1368 | Schur form T, |
| 1369 | alpha, |
| 1370 | beta (eigenvalues = alpha/beta), |
| 1371 | HASH{info}: info output from gges/cgges. |
| 1372 | HASH{SL}: left Schur vectors if requested |
| 1373 | HASH{SR}: right Schur vectors if requested |
| 1374 | HASH{VL}: left eigenvectors if requested |
| 1375 | HASH{VR}: right eigenvectors if requested |
| 1376 | HASH{rconde}: reciprocal condition numbers for average of selected eigenvalues if requested |
| 1377 | HASH{rcondv}: reciprocal condition numbers for selected deflating subspaces if requested |
| 1378 | HASH{n} : Number of eigenvalues selected if select_func is defined. |
| 1379 | |
| 1380 | =for example |
| 1381 | |
| 1382 | my $a = random(10,10); |
| 1383 | my $b = random(10,10); |
| 1384 | my ($S,$T) = mgschurx($a,$b); |
| 1385 | sub select { |
| 1386 | my ($alpha,$beta) = @_; |
| 1387 | return $alpha->Cabs < abs($beta) ? 1 : 0; |
| 1388 | } |
| 1389 | my ($S, $T, $alpha, $beta, %res) = mgschurx( $a, $b, 1, 1, 1, 1,\&select,3); |
| 1390 | |
| 1391 | =cut |
| 1392 | |
| 1393 | *mgschurx = \&PDL::mgschurx; |
| 1394 | sub PDL::mgschurx { |
| 1395 | &_square_same; |
| 1396 | my($m, $p, $jobvsl, $jobvsr, $jobvl, $jobvr, $select_func, $sense, $mult, $norm) = @_; |
| 1397 | my (@mdims) = $m->dims; |
| 1398 | $_ = $_->new_or_inplace->t for $m, $p; |
| 1399 | $mult //= 1; |
| 1400 | $norm //= 1; |
| 1401 | my $select = $select_func ? 1 : 0; |
| 1402 | $sense = 0 if !$select_func; |
| 1403 | $_ = null for my ($info, $rconde, $rcondv, $sdim); |
| 1404 | $_ = $m->_similar_null for my ($beta, $vsl, $vsr); |
| 1405 | my @w = map $m->_similar_null, $m->_is_complex ? 1 : 1..2; |
| 1406 | my $select_f = $m->_wrap_select_func($select_func); |
| 1407 | $m->_call_method('ggesx', $jobvsl, $jobvsr, $select, $sense, $p, $select_f, @w, $beta, $vsl, $vsr, $sdim, $rconde, $rcondv,$info); |
| 1408 | _error_schur($info, $select_func, $mdims[0], 'mgschurx', 'QZ'); |
| 1409 | my @vl = ('VL', $jobvl); |
| 1410 | my @vr = ('VR', $jobvr); |
| 1411 | my %ret; |
| 1412 | $ret{$_->[0]} = _complex_null(), $_->[1]=0 for grep $select_func && !$sdim && $_->[1] == 2, \@vl, \@vr; |
| 1413 | $ret{n} = $sdim if $select_func; |
| 1414 | if ($vl[1] || $vr[1]) { |
| 1415 | my ($vl, $vr) = _eigen_pair( |
| 1416 | $m, $p, $select_func, $vl[1], $vr[1], $jobvsl, $jobvsr, $vsl, $vsr, |
| 1417 | $mult, $norm, $mdims[1], $sdim, @w |
| 1418 | ); |
| 1419 | $ret{$_->[0]} = $_->[1] for grep defined $_->[1], ['VL',$vl], ['VR',$vr]; |
| 1420 | } |
| 1421 | if ($jobvsl == 2 && $select_func) { |
| 1422 | $ret{SL} = $sdim ? $vsl->t->slice(":@{[$sdim-1]},")->sever : $m->_similar_null; |
| 1423 | } elsif ($jobvsl) { |
| 1424 | $ret{SL} = $vsl->t->sever; |
| 1425 | } |
| 1426 | if ($jobvsr == 2 && $select_func) { |
| 1427 | $ret{SR} = $sdim ? $vsr->t->slice(":@{[$sdim-1]},")->sever : $m->_similar_null; |
| 1428 | } elsif ($jobvsr) { |
| 1429 | $ret{SR} = $vsr->t->sever; |
| 1430 | } |
| 1431 | my $w = @w == 2 ? _ecplx(@w) : @w[0]; |
| 1432 | $ret{info} = $info; |
| 1433 | $ret{rconde} = $rconde if $sense & 1; |
| 1434 | $ret{rcondv} = $rcondv if $sense & 2; |
| 1435 | return ($m->t, $p->t, $w, $beta, %ret); |
| 1436 | } |
| 1437 | |
| 1438 | =head2 mqr |
| 1439 | |
| 1440 | =for ref |
| 1441 | |
| 1442 | Computes QR decomposition. |
| 1443 | Handles complex data. |
| 1444 | Uses L<geqrf|PDL::LinearAlgebra::Real/geqrf> and L<orgqr|PDL::LinearAlgebra::Real/orgqr> |
| 1445 | or L<cgeqrf|PDL::LinearAlgebra::Complex/cgeqrf> and L<cungqr|PDL::LinearAlgebra::Complex/cungqr> |
| 1446 | from LAPACK and returns C<Q> in scalar context. Works on transposed array. |
| 1447 | |
| 1448 | =for usage |
| 1449 | |
| 1450 | (PDL(Q), PDL(R), PDL(info)) = mqr(PDL, SCALAR) |
| 1451 | SCALAR : ECONOMIC = 0 | FULL = 1, default = 0 |
| 1452 | |
| 1453 | =for example |
| 1454 | |
| 1455 | my $a = random(10,10); |
| 1456 | my ( $q, $r ) = mqr($a); |
| 1457 | # Can compute full decomposition if nrow > ncol |
| 1458 | $a = random(5,7); |
| 1459 | ( $q, $r ) = $a->mqr(1); |
| 1460 | |
| 1461 | =cut |
| 1462 | |
| 1463 | *mqr = \&PDL::mqr; |
| 1464 | sub PDL::mqr { |
| 1465 | &_2d_array; |
| 1466 | my($m, $full) = @_; |
| 1467 | my(@dims) = $m->dims; |
| 1468 | $m = $m->t->copy; |
| 1469 | my $min = $dims[0] < $dims[1] ? $dims[0] : $dims[1]; |
| 1470 | my $slice_arg = ",:@{[$min-1]}"; |
| 1471 | my $tau = $m->_similar($min); |
| 1472 | $m->_call_method('geqrf', $tau, my $info = null); |
| 1473 | if ($info) { |
| 1474 | laerror ("mqr: Error $info in geqrf\n"); |
| 1475 | return ($m->t->sever, $m, $info); |
| 1476 | } |
| 1477 | my $q = ($dims[0] > $dims[1] ? $m->slice($slice_arg) : $m)->copy; |
| 1478 | $q->reshape(@dims[1,1]) if $full && $dims[0] < $dims[1]; |
| 1479 | $q->_call_method(['orgqr','cungqr'], $tau, $info); |
| 1480 | return $q->t->sever unless wantarray; |
| 1481 | my $r = (($dims[0] < $dims[1] && !$full) ? $m->t->slice($slice_arg) : $m->t)->tricpy(0); |
| 1482 | return ($q->t->sever, $r, $info); |
| 1483 | } |
| 1484 | |
| 1485 | =head2 mrq |
| 1486 | |
| 1487 | =for ref |
| 1488 | |
| 1489 | Computes RQ decomposition. |
| 1490 | Handles complex data. |
| 1491 | Uses L<gerqf|PDL::LinearAlgebra::Real/gerqf> and L<orgrq|PDL::LinearAlgebra::Real/orgrq> |
| 1492 | or L<cgerqf|PDL::LinearAlgebra::Complex/cgerqf> and L<cungrq|PDL::LinearAlgebra::Complex/cungrq> |
| 1493 | from LAPACK and returns C<Q> in scalar context. Works on transposed array. |
| 1494 | |
| 1495 | =for usage |
| 1496 | |
| 1497 | (PDL(R), PDL(Q), PDL(info)) = mrq(PDL, SCALAR) |
| 1498 | SCALAR : ECONOMIC = 0 | FULL = 1, default = 0 |
| 1499 | |
| 1500 | =for example |
| 1501 | |
| 1502 | my $a = random(10,10); |
| 1503 | my ( $r, $q ) = mrq($a); |
| 1504 | # Can compute full decomposition if nrow < ncol |
| 1505 | $a = random(5,7); |
| 1506 | ( $r, $q ) = $a->mrq(1); |
| 1507 | |
| 1508 | =cut |
| 1509 | |
| 1510 | *mrq = \&PDL::mrq; |
| 1511 | sub PDL::mrq { |
| 1512 | &_2d_array; |
| 1513 | my @diag_args = (0,1); |
| 1514 | my($m, $full) = @_; |
| 1515 | my(@dims) = $m->dims; |
| 1516 | my ($q, $r); |
| 1517 | $m = $m->t->copy; |
| 1518 | my $min = $dims[0] < $dims[1] ? $dims[0] : $dims[1]; |
| 1519 | my $tau = $m->_similar($min); |
| 1520 | $m->_call_method('gerqf', $tau, my $info = null); |
| 1521 | if ($info) { |
| 1522 | laerror ("mrq: Error $info in gerqf\n"); |
| 1523 | return ($m, $m->t->sever, $info); |
| 1524 | } |
| 1525 | if ($dims[0] > $dims[1] && $full) { |
| 1526 | $q = $m->_similar(@dims[0,0]); |
| 1527 | $q->slice("@{[$dims[0] - $dims[1]]}:") .= $m; |
| 1528 | } elsif ($dims[0] < $dims[1]) { |
| 1529 | $q = $m->slice("@{[$dims[1] - $dims[0]]}:")->copy; |
| 1530 | } else { |
| 1531 | $q = $m->copy; |
| 1532 | } |
| 1533 | $q->_call_method(['orgrq','cungrq'], $tau, $info); |
| 1534 | return $q->t->sever unless wantarray; |
| 1535 | if ($dims[0] > $dims[1] && $full) { |
| 1536 | $r = $m->t->tricpy(0); |
| 1537 | $r->slice(":@{[$min-1]},:@{[$min-1]}")->diagonal(@diag_args) .= 0; |
| 1538 | } elsif ($dims[0] < $dims[1]) { |
| 1539 | my $temp = $m->_similar(@dims[1,1]); |
| 1540 | $temp->slice("-$min:") .= $m->t; |
| 1541 | $r = $temp->tricpy(0); |
| 1542 | $r = $r->slice("-$min:")->sever; |
| 1543 | } else { |
| 1544 | $r = $m->t->slice("@{[$dims[0] - $dims[1]]}:")->tricpy(0); |
| 1545 | } |
| 1546 | return ($r, $q->t->sever, $info); |
| 1547 | } |
| 1548 | |
| 1549 | =head2 mql |
| 1550 | |
| 1551 | =for ref |
| 1552 | |
| 1553 | Computes QL decomposition. |
| 1554 | Handles complex data. |
| 1555 | Uses L<geqlf|PDL::LinearAlgebra::Real/geqlf> and L<orgql|PDL::LinearAlgebra::Real/orgql> |
| 1556 | or L<cgeqlf|PDL::LinearAlgebra::Complex/cgeqlf> and L<cungql|PDL::LinearAlgebra::Complex/cungql> |
| 1557 | from LAPACK and returns C<Q> in scalar context. Works on transposed array. |
| 1558 | |
| 1559 | =for usage |
| 1560 | |
| 1561 | (PDL(Q), PDL(L), PDL(info)) = mql(PDL, SCALAR) |
| 1562 | SCALAR : ECONOMIC = 0 | FULL = 1, default = 0 |
| 1563 | |
| 1564 | =for example |
| 1565 | |
| 1566 | my $a = random(10,10); |
| 1567 | my ( $q, $l ) = mql($a); |
| 1568 | # Can compute full decomposition if nrow > ncol |
| 1569 | $a = random(5,7); |
| 1570 | ( $q, $l ) = $a->mql(1); |
| 1571 | |
| 1572 | =cut |
| 1573 | |
| 1574 | *mql = \&PDL::mql; |
| 1575 | sub PDL::mql { |
| 1576 | &_2d_array; |
| 1577 | my @diag_args = (0,1); |
| 1578 | my($m, $full) = @_; |
| 1579 | my(@dims) = $m->dims; |
| 1580 | my ($q, $l); |
| 1581 | $m = $m->t->copy; |
| 1582 | my $min = $dims[0] < $dims[1] ? $dims[0] : $dims[1]; |
| 1583 | my $tau = $m->_similar($min); |
| 1584 | $m->_call_method('geqlf', $tau, my $info = null); |
| 1585 | if ($info) { |
| 1586 | laerror("mql: Error $info in geqlf\n"); |
| 1587 | return ($m->t->sever, $m, $info); |
| 1588 | } |
| 1589 | if ($dims[0] < $dims[1] && $full) { |
| 1590 | $q = $m->_similar(@dims[1,1]); |
| 1591 | $q->slice(":,-$dims[0]:") .= $m; |
| 1592 | } elsif ($dims[0] > $dims[1]) { |
| 1593 | $q = $m->slice(":,-$min:")->copy; |
| 1594 | } else { |
| 1595 | $q = $m->copy; |
| 1596 | } |
| 1597 | $q->_call_method(['orgql','cungql'], $tau, $info); |
| 1598 | return $q->t->sever unless wantarray; |
| 1599 | if ($dims[0] < $dims[1] && $full) { |
| 1600 | $l = $m->t->tricpy(1); |
| 1601 | $l->slice(":@{[$min-1]},:@{[$min-1]}")->diagonal(@diag_args) .= 0; |
| 1602 | } elsif ($dims[0] > $dims[1]) { |
| 1603 | my $temp = $m->_similar(@dims[0,0]); |
| 1604 | $temp->slice(":,-$dims[1]:") .= $m->t; |
| 1605 | $l = $temp->tricpy(0); |
| 1606 | $l = $l->slice(":,-$dims[1]:"); |
| 1607 | } else { |
| 1608 | $l = $m->t->slice(":,@{[$dims[1] - $min]}:")->tricpy(1); |
| 1609 | } |
| 1610 | return ($q->t->sever, $l, $info); |
| 1611 | } |
| 1612 | |
| 1613 | =head2 mlq |
| 1614 | |
| 1615 | =for ref |
| 1616 | |
| 1617 | Computes LQ decomposition. |
| 1618 | Handles complex data. |
| 1619 | Uses L<gelqf|PDL::LinearAlgebra::Real/gelqf> and L<orglq|PDL::LinearAlgebra::Real/orglq> |
| 1620 | or L<cgelqf|PDL::LinearAlgebra::Complex/cgelqf> and L<cunglq|PDL::LinearAlgebra::Complex/cunglq> |
| 1621 | from LAPACK and returns C<Q> in scalar context. Works on transposed array. |
| 1622 | |
| 1623 | =for usage |
| 1624 | |
| 1625 | ( PDL(L), PDL(Q), PDL(info) ) = mlq(PDL, SCALAR) |
| 1626 | SCALAR : ECONOMIC = 0 | FULL = 1, default = 0 |
| 1627 | |
| 1628 | =for example |
| 1629 | |
| 1630 | my $a = random(10,10); |
| 1631 | my ( $l, $q ) = mlq($a); |
| 1632 | # Can compute full decomposition if nrow < ncol |
| 1633 | $a = random(5,7); |
| 1634 | ( $l, $q ) = $a->mlq(1); |
| 1635 | |
| 1636 | =cut |
| 1637 | |
| 1638 | *mlq = \&PDL::mlq; |
| 1639 | sub PDL::mlq { |
| 1640 | &_2d_array; |
| 1641 | my($m, $full) = @_; |
| 1642 | my(@dims) = $m->dims; |
| 1643 | my ($q); |
| 1644 | $m = $m->t->copy; |
| 1645 | my $min = $dims[0] < $dims[1] ? $dims[0] : $dims[1]; |
| 1646 | my $slice_arg = ":@{[$min-1]}"; |
| 1647 | my $tau = $m->_similar($min); |
| 1648 | $m->_call_method('gelqf', $tau, my $info = null); |
| 1649 | if ($info) { |
| 1650 | laerror("mlq: Error $info in gelqf\n"); |
| 1651 | return ($m, $m->t->sever, $info); |
| 1652 | } |
| 1653 | if ($dims[0] > $dims[1] && $full) { |
| 1654 | $q = $m->_similar(@dims[0,0]); |
| 1655 | $q->slice($slice_arg) .= $m; |
| 1656 | } elsif ($dims[0] < $dims[1]) { |
| 1657 | $q = $m->slice($slice_arg)->copy; |
| 1658 | } else { |
| 1659 | $q = $m->copy; |
| 1660 | } |
| 1661 | $q->_call_method(['orglq','cunglq'], $tau, $info); |
| 1662 | return $q->t->sever unless wantarray; |
| 1663 | my $l = (($dims[0] > $dims[1] && !$full) ? $m->t->slice($slice_arg) : $m->t)->tricpy(1); |
| 1664 | return ($l, $q->t->sever, $info); |
| 1665 | } |
| 1666 | |
| 1667 | =head2 msolve |
| 1668 | |
| 1669 | =for ref |
| 1670 | |
| 1671 | Solves linear system of equations using LU decomposition. |
| 1672 | |
| 1673 | A * X = B |
| 1674 | |
| 1675 | Returns X in scalar context else X, LU, pivot vector and info. |
| 1676 | B is overwritten by X if its inplace flag is set. |
| 1677 | Supports broadcasting. |
| 1678 | Uses L<gesv|PDL::LinearAlgebra::Real/gesv> or L<cgesv|PDL::LinearAlgebra::Complex/cgesv> from LAPACK. |
| 1679 | Works on transposed arrays. |
| 1680 | |
| 1681 | =for usage |
| 1682 | |
| 1683 | (PDL(X), (PDL(LU), PDL(pivot), PDL(info))) = msolve(PDL(A), PDL(B) ) |
| 1684 | |
| 1685 | =for example |
| 1686 | |
| 1687 | my $a = random(5,5); |
| 1688 | my $b = random(10,5); |
| 1689 | my $X = msolve($a, $b); |
| 1690 | |
| 1691 | =cut |
| 1692 | |
| 1693 | *msolve = \&PDL::msolve; |
| 1694 | sub PDL::msolve { |
| 1695 | &_square; |
| 1696 | &_matrices_match; |
| 1697 | &_same_dims; |
| 1698 | my ($a, $b) = @_; |
| 1699 | $a = $a->t->copy; |
| 1700 | my $c = $b->new_or_inplace->t; |
| 1701 | my ($ipiv, $info) = $a->_call_method('gesv', $c); |
| 1702 | _error($info, "msolve: Can't solve system of linear equations (after getrf factorization): matrix (PDL(s) %s) is/are singular"); |
| 1703 | $b = $c->t->sever if !$b->is_inplace(0); |
| 1704 | wantarray ? ($b, $a->t->sever, $ipiv, $info) : $b; |
| 1705 | } |
| 1706 | |
| 1707 | =head2 msolvex |
| 1708 | |
| 1709 | =for ref |
| 1710 | |
| 1711 | Solves linear system of equations using LU decomposition. |
| 1712 | |
| 1713 | A * X = B |
| 1714 | |
| 1715 | Can optionally equilibrate the matrix. |
| 1716 | Uses L<gesvx|PDL::LinearAlgebra::Real/gesvx> or L<cgesvx|PDL::LinearAlgebra::Complex/cgesvx> from LAPACK. |
| 1717 | Works on transposed arrays. |
| 1718 | |
| 1719 | =for usage |
| 1720 | |
| 1721 | (PDL, (HASH(result))) = msolvex(PDL(A), PDL(B), HASH(options)) |
| 1722 | where options are: |
| 1723 | transpose: solves A' * X = B |
| 1724 | 0: false |
| 1725 | 1: true |
| 1726 | equilibrate: equilibrates A if necessary. |
| 1727 | form equilibration is returned in HASH{'equilibration'}: |
| 1728 | 0: no equilibration |
| 1729 | 1: row equilibration |
| 1730 | 2: column equilibration |
| 1731 | row scale factors are returned in HASH{'row'} |
| 1732 | column scale factors are returned in HASH{'column'} |
| 1733 | 0: false |
| 1734 | 1: true |
| 1735 | LU: returns lu decomposition in HASH{LU} |
| 1736 | 0: false |
| 1737 | 1: true |
| 1738 | A: returns scaled A if equilibration was done in HASH{A} |
| 1739 | 0: false |
| 1740 | 1: true |
| 1741 | B: returns scaled B if equilibration was done in HASH{B} |
| 1742 | 0: false |
| 1743 | 1: true |
| 1744 | Returned values: |
| 1745 | X (SCALAR CONTEXT), |
| 1746 | HASH{'pivot'}: |
| 1747 | Pivot indice from LU factorization |
| 1748 | HASH{'rcondition'}: |
| 1749 | Reciprocal condition of the matrix |
| 1750 | HASH{'ferror'}: |
| 1751 | Forward error bound |
| 1752 | HASH{'berror'}: |
| 1753 | Componentwise relative backward error |
| 1754 | HASH{'rpvgrw'}: |
| 1755 | Reciprocal pivot growth factor |
| 1756 | HASH{'info'}: |
| 1757 | Info: output from gesvx |
| 1758 | |
| 1759 | =for example |
| 1760 | |
| 1761 | my $a = random(10,10); |
| 1762 | my $b = random(5,10); |
| 1763 | my %options = ( |
| 1764 | LU=>1, |
| 1765 | equilibrate => 1, |
| 1766 | ); |
| 1767 | my( $X, %result) = msolvex($a,$b,%options); |
| 1768 | |
| 1769 | =cut |
| 1770 | |
| 1771 | |
| 1772 | *msolvex = \&PDL::msolvex; |
| 1773 | |
| 1774 | sub PDL::msolvex { |
| 1775 | &_square; |
| 1776 | &_matrices_match; |
| 1777 | my($a, $b, %opt) = @_; |
| 1778 | my @adims = $a->dims; |
| 1779 | $a = $a->t->copy; |
| 1780 | $b = $b->t->copy; |
| 1781 | my $af = PDL::zeroes $a; |
| 1782 | my $equed = pdl(long, 0); |
| 1783 | my $ipiv = zeroes(long, $adims[0]); |
| 1784 | my ($r, $c, $x, $rcond, $ferr, $berr, $rpvgrw, $info) = $a->_call_method('gesvx', $opt{transpose}, $opt{equilibrate} ? 2 : 1, $b, $af, $ipiv, $equed); |
| 1785 | if ($info < $adims[0] && $info > 0) { |
| 1786 | $info--; |
| 1787 | laerror("msolvex: Can't solve system of linear equations:\nfactor U($info,$info)". |
| 1788 | " of coefficient matrix is exactly 0"); |
| 1789 | } elsif ($info != 0 and $_laerror) { |
| 1790 | warn "msolvex: The matrix is singular to working precision"; |
| 1791 | } |
| 1792 | return $x->t->sever unless wantarray; |
| 1793 | my %result = (rcondition => $rcond, ferror => $ferr, berror => $berr); |
| 1794 | if ($opt{equilibrate}) { |
| 1795 | $result{equilibration} = $equed; |
| 1796 | $result{row} = $r if $equed & 1; |
| 1797 | $result{column} = $c if $equed & 2; |
| 1798 | if ($equed) { |
| 1799 | $result{A} = $a->t->sever if $opt{A}; |
| 1800 | $result{B} = $b->t->sever if $opt{B}; |
| 1801 | } |
| 1802 | } |
| 1803 | @result{qw(pivot rpvgrw info)} = ($ipiv, $rpvgrw, $info); |
| 1804 | $result{LU} = $af->t->sever if $opt{LU}; |
| 1805 | ($x->t->sever, %result); |
| 1806 | } |
| 1807 | |
| 1808 | =head2 mtrisolve |
| 1809 | |
| 1810 | =for ref |
| 1811 | |
| 1812 | Solves linear system of equations with triangular matrix A. |
| 1813 | |
| 1814 | A * X = B or A' * X = B |
| 1815 | |
| 1816 | B is overwritten by X if its inplace flag is set. |
| 1817 | Supports broadcasting. |
| 1818 | Uses L<trtrs|PDL::LinearAlgebra::Real/trtrs> or L<ctrtrs|PDL::LinearAlgebra::Complex/ctrtrs> from LAPACK. |
| 1819 | Work on transposed array(s). |
| 1820 | |
| 1821 | =for usage |
| 1822 | |
| 1823 | (PDL(X), (PDL(info)) = mtrisolve(PDL(A), SCALAR(uplo), PDL(B), SCALAR(trans), SCALAR(diag)) |
| 1824 | uplo : UPPER = 0 | LOWER = 1 |
| 1825 | trans : NOTRANSPOSE = 0 | TRANSPOSE = 1, default = 0 |
| 1826 | uplo : UNITARY DIAGONAL = 1, default = 0 |
| 1827 | |
| 1828 | =for example |
| 1829 | |
| 1830 | # Assume $a is upper triagonal |
| 1831 | my $a = random(5,5); |
| 1832 | my $b = random(5,10); |
| 1833 | my $X = mtrisolve($a, 0, $b); |
| 1834 | |
| 1835 | =cut |
| 1836 | |
| 1837 | *mtrisolve = \&PDL::mtrisolve; |
| 1838 | sub PDL::mtrisolve { |
| 1839 | &_square; |
| 1840 | my $uplo = splice @_, 1, 1; |
| 1841 | &_matrices_match; |
| 1842 | &_same_dims; |
| 1843 | my($a, $b, $trans, $diag) = @_; |
| 1844 | $uplo = 1 - $uplo; |
| 1845 | $trans = 1 - $trans; |
| 1846 | my $c = $b->new_or_inplace->t; |
| 1847 | my ($info) = $a->_call_method('trtrs', $uplo, $trans, $diag, $c); |
| 1848 | _error($info, "mtrisolve: Can't solve system of linear equations: matrix (PDL(s) %s) is/are singular"); |
| 1849 | $b = $c->t->sever if !$b->is_inplace(0); |
| 1850 | wantarray ? ($b, $info) : $b; |
| 1851 | } |
| 1852 | |
| 1853 | =head2 msymsolve |
| 1854 | |
| 1855 | =for ref |
| 1856 | |
| 1857 | Solves linear system of equations using diagonal pivoting method with symmetric matrix A. |
| 1858 | |
| 1859 | A * X = B |
| 1860 | |
| 1861 | Returns X in scalar context else X, block diagonal matrix D (and the |
| 1862 | multipliers), pivot vector an info. B is overwritten by X if its inplace flag is set. |
| 1863 | Supports broadcasting. |
| 1864 | Uses L<sysv|PDL::LinearAlgebra::Real/sysv> or L<csysv|PDL::LinearAlgebra::Complex/csysv> from LAPACK. |
| 1865 | Works on transposed array(s). |
| 1866 | |
| 1867 | =for usage |
| 1868 | |
| 1869 | (PDL(X), ( PDL(D), PDL(pivot), PDL(info) ) ) = msymsolve(PDL(A), SCALAR(uplo), PDL(B) ) |
| 1870 | uplo : UPPER = 0 | LOWER = 1, default = 0 |
| 1871 | |
| 1872 | =for example |
| 1873 | |
| 1874 | # Assume $a is symmetric |
| 1875 | my $a = random(5,5); |
| 1876 | my $b = random(5,10); |
| 1877 | my $X = msymsolve($a, 0, $b); |
| 1878 | |
| 1879 | =cut |
| 1880 | |
| 1881 | *msymsolve = \&PDL::msymsolve; |
| 1882 | sub PDL::msymsolve { |
| 1883 | &_square; |
| 1884 | my $uplo = splice @_, 1, 1; |
| 1885 | &_matrices_match; |
| 1886 | &_same_dims; |
| 1887 | my ($a, $b) = @_; |
| 1888 | $uplo = 1 - $uplo; |
| 1889 | $a = $a->copy; |
| 1890 | my $c = $b->new_or_inplace->t; |
| 1891 | my ($ipiv, $info) = $a->_call_method('sysv', $uplo, $c); |
| 1892 | _error($info, "msymsolve: Can't solve system of linear equations (after sytrf factorization): matrix (PDL(s) %s) is/are singular"); |
| 1893 | $b = $c->t->sever if !$b->is_inplace(0); |
| 1894 | wantarray ? ($b, $a, $ipiv, $info) : $b; |
| 1895 | } |
| 1896 | |
| 1897 | =head2 msymsolvex |
| 1898 | |
| 1899 | =for ref |
| 1900 | |
| 1901 | Solves linear system of equations using diagonal pivoting method with symmetric matrix A. |
| 1902 | |
| 1903 | A * X = B |
| 1904 | |
| 1905 | Uses L<sysvx|PDL::LinearAlgebra::Real/sysvx> or L<csysvx|PDL::LinearAlgebra::Complex/csysvx> |
| 1906 | from LAPACK. Works on transposed array. |
| 1907 | |
| 1908 | =for usage |
| 1909 | |
| 1910 | (PDL, (HASH(result))) = msymsolvex(PDL(A), SCALAR (uplo), PDL(B), SCALAR(d)) |
| 1911 | uplo : UPPER = 0 | LOWER = 1, default = 0 |
| 1912 | d : whether return diagonal matrix d and pivot vector |
| 1913 | FALSE = 0 | TRUE = 1, default = 0 |
| 1914 | Returned values: |
| 1915 | X (SCALAR CONTEXT), |
| 1916 | HASH{'D'}: |
| 1917 | Block diagonal matrix D (and the multipliers) (if requested) |
| 1918 | HASH{'pivot'}: |
| 1919 | Pivot indice from LU factorization (if requested) |
| 1920 | HASH{'rcondition'}: |
| 1921 | Reciprocal condition of the matrix |
| 1922 | HASH{'ferror'}: |
| 1923 | Forward error bound |
| 1924 | HASH{'berror'}: |
| 1925 | Componentwise relative backward error |
| 1926 | HASH{'info'}: |
| 1927 | Info: output from sysvx |
| 1928 | |
| 1929 | =for example |
| 1930 | |
| 1931 | # Assume $a is symmetric |
| 1932 | my $a = random(10,10); |
| 1933 | my $b = random(5,10); |
| 1934 | my ($X, %result) = msolvex($a, 0, $b); |
| 1935 | |
| 1936 | |
| 1937 | =cut |
| 1938 | |
| 1939 | |
| 1940 | *msymsolvex = \&PDL::msymsolvex; |
| 1941 | sub PDL::msymsolvex { |
| 1942 | &_square; |
| 1943 | my $uplo = splice @_, 1, 1; |
| 1944 | &_matrices_match; |
| 1945 | my ($a, $b, $d) = @_; |
| 1946 | my @adims = $a->dims; |
| 1947 | $uplo = 1 - $uplo; |
| 1948 | $b = $b->t; |
| 1949 | my $af = PDL::zeroes $a; |
| 1950 | my $ipiv = zeroes(long, $adims[0]); |
| 1951 | my ($x, $rcond, $ferr, $berr, $info) = $a->_call_method('sysvx', $uplo, 0, $b, $af, $ipiv); |
| 1952 | if ($info < $adims[0] && $info > 0) { |
| 1953 | $info--; |
| 1954 | laerror("msymsolvex: Can't solve system of linear equations:\nfactor D($info,$info)". |
| 1955 | " of coefficient matrix is exactly 0"); |
| 1956 | } elsif ($info != 0 and $_laerror) { |
| 1957 | warn("msymsolvex: The matrix is singular to working precision"); |
| 1958 | } |
| 1959 | my %result = (rcondition => $rcond, ferror => $ferr, berror => $berr, info => $info); |
| 1960 | @result{qw(pivot D)} = ($ipiv, $af) if $d; |
| 1961 | wantarray ? ($x->t->sever, %result): $x->t->sever; |
| 1962 | } |
| 1963 | |
| 1964 | =head2 mpossolve |
| 1965 | |
| 1966 | =for ref |
| 1967 | |
| 1968 | Solves linear system of equations using Cholesky decomposition with |
| 1969 | symmetric positive definite matrix A. |
| 1970 | |
| 1971 | A * X = B |
| 1972 | |
| 1973 | Returns X in scalar context else X, U or L and info. |
| 1974 | B is overwritten by X if its inplace flag is set. |
| 1975 | Supports broadcasting. |
| 1976 | Uses L<posv|PDL::LinearAlgebra::Real/posv> or L<cposv|PDL::LinearAlgebra::Complex/cposv> from LAPACK. |
| 1977 | Works on transposed array(s). |
| 1978 | |
| 1979 | =for usage |
| 1980 | |
| 1981 | (PDL, (PDL, PDL, PDL)) = mpossolve(PDL(A), SCALAR(uplo), PDL(B) ) |
| 1982 | uplo : UPPER = 0 | LOWER = 1, default = 0 |
| 1983 | |
| 1984 | =for example |
| 1985 | |
| 1986 | # asume $a is symmetric positive definite |
| 1987 | my $a = random(5,5); |
| 1988 | my $b = random(5,10); |
| 1989 | my $X = mpossolve($a, 0, $b); |
| 1990 | |
| 1991 | =cut |
| 1992 | |
| 1993 | |
| 1994 | *mpossolve = \&PDL::mpossolve; |
| 1995 | sub PDL::mpossolve { |
| 1996 | &_square; |
| 1997 | my $uplo = splice @_, 1, 1; |
| 1998 | &_matrices_match; |
| 1999 | &_same_dims; |
| 2000 | my ($a, $b) = @_; |
| 2001 | $uplo = 1 - $uplo; |
| 2002 | $a = $a->copy; |
| 2003 | my $c = $b->new_or_inplace->t; |
| 2004 | my ($info) = $a->_call_method('posv', $uplo, $c); |
| 2005 | _error($info, "mpossolve: Can't solve system of linear equations: matrix (PDL(s) %s) is/are not positive definite"); |
| 2006 | wantarray ? $b->is_inplace(0) ? ($b, $a,$info) : ($c->t->sever , $a,$info) : $b->is_inplace(0) ? $b : $c->t->sever; |
| 2007 | } |
| 2008 | |
| 2009 | =head2 mpossolvex |
| 2010 | |
| 2011 | =for ref |
| 2012 | |
| 2013 | Solves linear system of equations using Cholesky decomposition with |
| 2014 | symmetric positive definite matrix A |
| 2015 | |
| 2016 | A * X = B |
| 2017 | |
| 2018 | Can optionally equilibrate the matrix. |
| 2019 | Uses L<posvx|PDL::LinearAlgebra::Real/posvx> or |
| 2020 | L<cposvx|PDL::LinearAlgebra::Complex/cposvx> from LAPACK. |
| 2021 | Works on transposed array(s). |
| 2022 | |
| 2023 | =for usage |
| 2024 | |
| 2025 | (PDL, (HASH(result))) = mpossolvex(PDL(A), SCARA(uplo), PDL(B), HASH(options)) |
| 2026 | uplo : UPPER = 0 | LOWER = 1, default = 0 |
| 2027 | where options are: |
| 2028 | equilibrate: equilibrates A if necessary. |
| 2029 | form equilibration is returned in HASH{'equilibration'}: |
| 2030 | 0: no equilibration |
| 2031 | 1: equilibration |
| 2032 | scale factors are returned in HASH{'scale'} |
| 2033 | 0: false |
| 2034 | 1: true |
| 2035 | U|L: returns Cholesky factorization in HASH{U} or HASH{L} |
| 2036 | 0: false |
| 2037 | 1: true |
| 2038 | A: returns scaled A if equilibration was done in HASH{A} |
| 2039 | 0: false |
| 2040 | 1: true |
| 2041 | B: returns scaled B if equilibration was done in HASH{B} |
| 2042 | 0: false |
| 2043 | 1: true |
| 2044 | Returned values: |
| 2045 | X (SCALAR CONTEXT), |
| 2046 | HASH{'rcondition'}: |
| 2047 | Reciprocal condition of the matrix |
| 2048 | HASH{'ferror'}: |
| 2049 | Forward error bound |
| 2050 | HASH{'berror'}: |
| 2051 | Componentwise relative backward error |
| 2052 | HASH{'info'}: |
| 2053 | Info: output from gesvx |
| 2054 | |
| 2055 | =for example |
| 2056 | |
| 2057 | # Assume $a is symmetric positive definite |
| 2058 | my $a = random(10,10); |
| 2059 | my $b = random(5,10); |
| 2060 | my %options = (U=>1, |
| 2061 | equilibrate => 1, |
| 2062 | ); |
| 2063 | my ($X, %result) = msolvex($a, 0, $b,%opt); |
| 2064 | |
| 2065 | =cut |
| 2066 | |
| 2067 | |
| 2068 | *mpossolvex = \&PDL::mpossolvex; |
| 2069 | |
| 2070 | sub PDL::mpossolvex { |
| 2071 | &_square; |
| 2072 | my $uplo = splice(@_, 1, 1) ? 0 : 1; |
| 2073 | &_matrices_match; |
| 2074 | my ($a, $b, %opt) = @_; |
| 2075 | my @adims = $a->dims; |
| 2076 | my @bdims = $b->dims; |
| 2077 | my $equilibrate = $opt{'equilibrate'} ? 2: 1; |
| 2078 | $a = $a->copy; |
| 2079 | $b = $b->t->copy; |
| 2080 | my $af = PDL::zeroes $a; |
| 2081 | my $equed = pdl(long, 0); |
| 2082 | my ($s, $x, $rcond, $ferr, $berr, $info) = $a->_call_method('posvx', $uplo, $equilibrate, $b, $af, $equed); |
| 2083 | if ($info < $adims[0] && $info > 0) { |
| 2084 | $info--; |
| 2085 | barf("mpossolvex: Can't solve system of linear equations:\n". |
| 2086 | "the leading minor of order $info of A is not positive definite"); |
| 2087 | return; |
| 2088 | } elsif ($info and $_laerror) { |
| 2089 | warn "mpossolvex: The matrix is singular to working precision"; |
| 2090 | } |
| 2091 | my %result = (rcondition=>$rcond, ferror=>$ferr, berror=>$berr); |
| 2092 | if ($opt{equilibrate}) { |
| 2093 | $result{equilibration} = $equed; |
| 2094 | if ($equed) { |
| 2095 | $result{scale} = $s if $equed; |
| 2096 | $result{A} = $a if $opt{A}; |
| 2097 | $result{B} = $b->t->sever if $opt{B}; |
| 2098 | } |
| 2099 | } |
| 2100 | $result{info} = $info; |
| 2101 | $result{L} = $af if $opt{L}; |
| 2102 | $result{U} = $af if $opt{U}; |
| 2103 | wantarray ? ($x->t->sever, %result): $x->t->sever; |
| 2104 | } |
| 2105 | |
| 2106 | =head2 mlls |
| 2107 | |
| 2108 | =for ref |
| 2109 | |
| 2110 | Solves overdetermined or underdetermined real linear systems using QR or LQ factorization. |
| 2111 | |
| 2112 | If M > N in the M-by-N matrix A, returns the residual sum of squares too. |
| 2113 | Uses L<gels|PDL::LinearAlgebra::Real/gels> or L<cgels|PDL::LinearAlgebra::Complex/cgels> from LAPACK. |
| 2114 | Works on transposed arrays. |
| 2115 | |
| 2116 | =for usage |
| 2117 | |
| 2118 | PDL(X) = mlls(PDL(A), PDL(B), SCALAR(trans)) |
| 2119 | trans : NOTRANSPOSE = 0 | TRANSPOSE/CONJUGATE = 1, default = 0 |
| 2120 | |
| 2121 | =for example |
| 2122 | |
| 2123 | $a = random(4,5); |
| 2124 | $b = random(3,5); |
| 2125 | ($x, $res) = mlls($a, $b); |
| 2126 | |
| 2127 | =cut |
| 2128 | |
| 2129 | *mlls = \&PDL::mlls; |
| 2130 | |
| 2131 | sub PDL::mlls { |
| 2132 | &_matrices_matchrows; |
| 2133 | my ($a, $b, $trans) = @_; |
| 2134 | my @adims = $a->dims; |
| 2135 | my @bdims = $b->dims; |
| 2136 | my $x; |
| 2137 | $a = $a->copy; |
| 2138 | if ($adims[1] < $adims[0]) { |
| 2139 | $x = $a->_similar($adims[0], $bdims[0]); |
| 2140 | $x->slice(":@{[$bdims[1]-1]}, :@{[$bdims[0]-1]}") .= $b->t; |
| 2141 | } else { |
| 2142 | $x = $b->t->copy; |
| 2143 | } |
| 2144 | my ($info) = $a->_call_method('gels', $trans ? 0 : 1, $x); |
| 2145 | $x = $x->t; |
| 2146 | return $x->sever if $adims[1] <= $adims[0]; |
| 2147 | my $sliced = $x->slice(", :@{[$adims[0]-1]}")->sever; |
| 2148 | return $sliced if !wantarray; |
| 2149 | my $power = $a->_similar(1); $power .= 2; |
| 2150 | ($sliced, ($x->slice(", $adims[0]:")->t ** $power)->sumover); |
| 2151 | } |
| 2152 | |
| 2153 | =head2 mllsy |
| 2154 | |
| 2155 | =for ref |
| 2156 | |
| 2157 | Computes the minimum-norm solution to a real linear least squares problem |
| 2158 | using a complete orthogonal factorization. |
| 2159 | |
| 2160 | Uses L<gelsy|PDL::LinearAlgebra::Real/gelsy> or L<cgelsy|PDL::LinearAlgebra::Complex/cgelsy> |
| 2161 | from LAPACK. Works on transposed arrays. |
| 2162 | |
| 2163 | =for usage |
| 2164 | |
| 2165 | ( PDL(X), ( HASH(result) ) ) = mllsy(PDL(A), PDL(B)) |
| 2166 | Returned values: |
| 2167 | X (SCALAR CONTEXT), |
| 2168 | HASH{'A'}: |
| 2169 | complete orthogonal factorization of A |
| 2170 | HASH{'jpvt'}: |
| 2171 | details of columns interchanges |
| 2172 | HASH{'rank'}: |
| 2173 | effective rank of A |
| 2174 | |
| 2175 | =for example |
| 2176 | |
| 2177 | my $a = random(10,10); |
| 2178 | my $b = random(10,10); |
| 2179 | $X = mllsy($a, $b); |
| 2180 | |
| 2181 | =cut |
| 2182 | |
| 2183 | *mllsy = \&PDL::mllsy; |
| 2184 | sub PDL::mllsy { |
| 2185 | &_matrices_matchrows; |
| 2186 | my ($a, $b) = @_; |
| 2187 | my @adims = $a->dims; |
| 2188 | my @bdims = $b->dims; |
| 2189 | my $rcond = lamch(0); |
| 2190 | $rcond = $rcond->sqrt - ($rcond->sqrt - $rcond) / 2; |
| 2191 | $a = $a->t->copy; |
| 2192 | my $x; |
| 2193 | if ($adims[1] < $adims[0]) { |
| 2194 | $x = $a->_similar($adims[0], $bdims[0]); |
| 2195 | $x->slice(":@{[$bdims[1]-1]}, :@{[$bdims[0]-1]}") .= $b->t; |
| 2196 | } else { |
| 2197 | $x = $b->t->copy; |
| 2198 | } |
| 2199 | my $jpvt = zeroes(long, $adims[0]); |
| 2200 | my ($rank, $info) = $a->_call_method('gelsy', $x, $rcond, $jpvt); |
| 2201 | my %ret = !wantarray ? () : (A=> $a->t->sever, rank => $rank, jpvt=>$jpvt); |
| 2202 | return wantarray ? ($x->t->sever, %ret) : $x->t->sever if $adims[1] <= $adims[0]; |
| 2203 | $x = $x->t->slice(", :@{[$adims[0]-1]}")->sever; |
| 2204 | wantarray ? ($x, %ret) : $x; |
| 2205 | } |
| 2206 | |
| 2207 | =head2 mllss |
| 2208 | |
| 2209 | =for ref |
| 2210 | |
| 2211 | Computes the minimum-norm solution to a real linear least squares problem |
| 2212 | using a singular value decomposition. |
| 2213 | |
| 2214 | Uses L<gelss|PDL::LinearAlgebra::Real/gelss> or L<gelsd|PDL::LinearAlgebra::Real/gelsd> from LAPACK. |
| 2215 | Works on transposed arrays. |
| 2216 | |
| 2217 | =for usage |
| 2218 | |
| 2219 | ( PDL(X), ( HASH(result) ) )= mllss(PDL(A), PDL(B), SCALAR(method)) |
| 2220 | method: specifies which method to use (see LAPACK for further details) |
| 2221 | '(c)gelss' or '(c)gelsd', default = '(c)gelsd' |
| 2222 | Returned values: |
| 2223 | X (SCALAR CONTEXT), |
| 2224 | HASH{'V'}: |
| 2225 | if method = (c)gelss, the right singular vectors, stored columnwise |
| 2226 | HASH{'s'}: |
| 2227 | singular values from SVD |
| 2228 | HASH{'res'}: |
| 2229 | if A has full rank the residual sum-of-squares for the solution |
| 2230 | HASH{'rank'}: |
| 2231 | effective rank of A |
| 2232 | HASH{'info'}: |
| 2233 | info output from method |
| 2234 | |
| 2235 | =for example |
| 2236 | |
| 2237 | my $a = random(10,10); |
| 2238 | my $b = random(10,10); |
| 2239 | $X = mllss($a, $b); |
| 2240 | |
| 2241 | =cut |
| 2242 | |
| 2243 | *mllss = \&PDL::mllss; |
| 2244 | |
| 2245 | sub PDL::mllss { |
| 2246 | &_matrices_matchrows; |
| 2247 | my ($a, $b, $method) = @_; |
| 2248 | my @adims = $a->dims; |
| 2249 | my @bdims = $b->dims; |
| 2250 | #TODO: Add this in option |
| 2251 | my $rcond = lamch(0); |
| 2252 | $rcond = $rcond->sqrt - ($rcond->sqrt - $rcond) / 2; |
| 2253 | $a = $a->t->copy; |
| 2254 | my $x; |
| 2255 | if ($adims[1] < $adims[0]) { |
| 2256 | $x = $a->_similar($adims[0], $bdims[0]); |
| 2257 | $x->slice(":@{[$bdims[1]-1]}, :@{[$bdims[0]-1]}") .= $b->t; |
| 2258 | } else { |
| 2259 | $x = $b->t->copy; |
| 2260 | } |
| 2261 | my $min = ($adims[0] > $adims[1]) ? $adims[1] : $adims[0]; |
| 2262 | $method ||= 'gelsd'; |
| 2263 | my ($s, $rank, $info) = $a->_call_method($method, $x, $rcond); |
| 2264 | laerror("mllss: The algorithm for computing the SVD failed to converge\n") if $info->any; |
| 2265 | $x = $x->t; |
| 2266 | my %ret = !wantarray ? () : (rank => $rank, s=>$s, info=>$info); |
| 2267 | $ret{V} = $a if wantarray and $method =~ /gelss/; |
| 2268 | return wantarray ? ($x->sever, %ret) : $x->sever if $adims[1] <= $adims[0]; |
| 2269 | if (wantarray and $rank == $min) { |
| 2270 | my $power = $a->_similar(1); $power .= 2; |
| 2271 | $ret{res} = ($x->slice(", $adims[0]:")->t ** $power)->sumover; |
| 2272 | } |
| 2273 | $x = $x->slice(", :@{[$adims[0]-1]}")->sever; |
| 2274 | wantarray ? ($x->sever, %ret) : $x->sever; |
| 2275 | } |
| 2276 | |
| 2277 | =head2 mglm |
| 2278 | |
| 2279 | =for ref |
| 2280 | |
| 2281 | Solves a general Gauss-Markov Linear Model (GLM) problem. |
| 2282 | Supports broadcasting. |
| 2283 | Uses L<ggglm|PDL::LinearAlgebra::Real/ggglm> or L<cggglm|PDL::LinearAlgebra::Complex/cggglm> |
| 2284 | from LAPACK. Works on transposed arrays. |
| 2285 | |
| 2286 | =for usage |
| 2287 | |
| 2288 | (PDL(x), PDL(y)) = mglm(PDL(a), PDL(b), PDL(d)) |
| 2289 | where d is the left hand side of the GLM equation |
| 2290 | |
| 2291 | =for example |
| 2292 | |
| 2293 | my $a = random(8,10); |
| 2294 | my $b = random(7,10); |
| 2295 | my $d = random(10); |
| 2296 | my ($x, $y) = mglm($a, $b, $d); |
| 2297 | |
| 2298 | =cut |
| 2299 | |
| 2300 | *mglm = \&PDL::mglm; |
| 2301 | sub PDL::mglm { |
| 2302 | my($a, $b, $d) = @_; |
| 2303 | my(@adims) = $a->dims; |
| 2304 | my(@bdims) = $b->dims; |
| 2305 | my(@ddims) = $d->dims; |
| 2306 | barf("mglm: Require arrays with equal number of rows") |
| 2307 | unless( @adims >= 2 && @bdims >= 2 && $adims[1] == $bdims[1]); |
| 2308 | barf "mglm: Require that column(A) <= row(A) <= column(A) + column(B)" unless |
| 2309 | ( ($adims[0] <= $adims[1] ) && ($adims[1] <= ($adims[0] + $bdims[0])) ); |
| 2310 | barf("mglm: Require vector(s) with size equal to number of rows of A") |
| 2311 | unless( @ddims >= 1 && $adims[1] == $ddims[0]); |
| 2312 | $a = $a->t->copy; |
| 2313 | $b = $b->t->copy; |
| 2314 | $d = $d->copy; |
| 2315 | my ($x, $y, $info) = $a->_call_method('ggglm', $b, $d); |
| 2316 | $x, $y; |
| 2317 | } |
| 2318 | |
| 2319 | =head2 mlse |
| 2320 | |
| 2321 | =for ref |
| 2322 | |
| 2323 | Solves a linear equality-constrained least squares (LSE) problem. |
| 2324 | Uses L<gglse|PDL::LinearAlgebra::Real/gglse> or L<cgglse|PDL::LinearAlgebra::Complex/cgglse> |
| 2325 | from LAPACK. Works on transposed arrays. |
| 2326 | |
| 2327 | =for usage |
| 2328 | |
| 2329 | (PDL(x), PDL(res2)) = mlse(PDL(a), PDL(b), PDL(c), PDL(d)) |
| 2330 | where |
| 2331 | c : The right hand side vector for the |
| 2332 | least squares part of the LSE problem. |
| 2333 | d : The right hand side vector for the |
| 2334 | constrained equation. |
| 2335 | x : The solution of the LSE problem. |
| 2336 | res2 : The residual sum of squares for the solution |
| 2337 | (returned only in array context) |
| 2338 | |
| 2339 | |
| 2340 | =for example |
| 2341 | |
| 2342 | my $a = random(5,4); |
| 2343 | my $b = random(5,3); |
| 2344 | my $c = random(4); |
| 2345 | my $d = random(3); |
| 2346 | my ($x, $res2) = mlse($a, $b, $c, $d); |
| 2347 | |
| 2348 | =cut |
| 2349 | |
| 2350 | *mlse = \&PDL::mlse; |
| 2351 | |
| 2352 | sub PDL::mlse { |
| 2353 | my($a, $b, $c, $d) = @_; |
| 2354 | my(@adims) = $a->dims; |
| 2355 | my(@bdims) = $b->dims; |
| 2356 | my(@cdims) = $c->dims; |
| 2357 | my(@ddims) = $d->dims; |
| 2358 | &_matrices_matchcolumns; |
| 2359 | barf("mlse: Require 1D vector C with size equal to number of A rows") |
| 2360 | unless( (@cdims == 1)&& $adims[1] == $cdims[0]); |
| 2361 | barf("mlse: Require 1D vector D with size equal to number of B rows") |
| 2362 | unless( (@ddims == 1)&& $bdims[1] == $ddims[0]); |
| 2363 | barf "mlse: Require that row(B) <= column(A) <= row(A) + row(B)" unless |
| 2364 | ( ($bdims[1] <= $adims[0] ) && ($adims[0] <= ($adims[1]+ $bdims[1])) ); |
| 2365 | $a = $a->t->copy; |
| 2366 | $b = $b->t->copy; |
| 2367 | $c = $c->copy; |
| 2368 | $d = $d->copy; |
| 2369 | my ($x, $info) = $a->_call_method('gglse', $b, $c, $d); |
| 2370 | my $power = $a->_similar(1); $power .= 2; |
| 2371 | my $sumsq = ($c->slice("@{[$adims[0]-$bdims[1]]}:@{[$adims[1]-1]}") ** $power)->sumover; |
| 2372 | wantarray ? ($x, $sumsq) : $x; |
| 2373 | } |
| 2374 | |
| 2375 | =head2 meigen |
| 2376 | |
| 2377 | =for ref |
| 2378 | |
| 2379 | Computes eigenvalues and, optionally, the left and/or right eigenvectors of a general square matrix |
| 2380 | (spectral decomposition). |
| 2381 | Eigenvectors are normalized (Euclidean norm = 1) and largest component real. |
| 2382 | The eigenvalues and eigenvectors returned are complex ndarrays. |
| 2383 | If only eigenvalues are requested, info is returned in array context. |
| 2384 | Supports broadcasting. |
| 2385 | Uses L<geev|PDL::LinearAlgebra::Real/geev> or L<cgeev|PDL::LinearAlgebra::Complex/cgeev> from LAPACK. |
| 2386 | Works on transposed arrays. |
| 2387 | |
| 2388 | =for usage |
| 2389 | |
| 2390 | (PDL(values), (PDL(LV), (PDL(RV)), (PDL(info)))) = meigen(PDL, SCALAR(left vector), SCALAR(right vector)) |
| 2391 | left vector : FALSE = 0 | TRUE = 1, default = 0 |
| 2392 | right vector : FALSE = 0 | TRUE = 1, default = 0 |
| 2393 | |
| 2394 | =for example |
| 2395 | |
| 2396 | my $a = random(10,10); |
| 2397 | my ( $eigenvalues, $left_eigenvectors, $right_eigenvectors ) = meigen($a,1,1); |
| 2398 | |
| 2399 | =cut |
| 2400 | |
| 2401 | *meigen = \&PDL::meigen; |
| 2402 | sub PDL::meigen { |
| 2403 | &_square; |
| 2404 | my ($m,$jobvl,$jobvr) = @_; |
| 2405 | $_ = null for my ($info, $sdim); |
| 2406 | my @w = map $m->_similar_null, $m->_is_complex ? 1 : 1..2; |
| 2407 | $_ = $m->_similar_null for my ($vl, $vr); |
| 2408 | $m->t->_call_method('geev', $jobvl, $jobvr, @w, $vl, $vr, $info); |
| 2409 | _error($info, "meigen: The QR algorithm failed to converge for PDL(s) %s"); |
| 2410 | (my $w, $vl, $vr) = _eigen_extract($jobvl, $jobvr, $vl, $vr, @w); |
| 2411 | return $w if !wantarray; |
| 2412 | ($w, ($jobvl?$vl->t->sever:()), ($jobvr?$vr->t->sever:()), $info); |
| 2413 | } |
| 2414 | |
| 2415 | =head2 meigenx |
| 2416 | |
| 2417 | =for ref |
| 2418 | |
| 2419 | Computes eigenvalues, one-norm and, optionally, the left and/or right eigenvectors of a general square matrix |
| 2420 | (spectral decomposition). |
| 2421 | Eigenvectors are normalized (Euclidean norm = 1) and largest component real. |
| 2422 | The eigenvalues and eigenvectors returned are complex ndarrays. |
| 2423 | Uses L<geevx|PDL::LinearAlgebra::Real/geevx> or |
| 2424 | L<cgeevx|PDL::LinearAlgebra::Complex/cgeevx> from LAPACK. |
| 2425 | Works on transposed arrays. |
| 2426 | |
| 2427 | =for usage |
| 2428 | |
| 2429 | (PDL(value), (PDL(lv), (PDL(rv)), HASH(result)), HASH(result)) = meigenx(PDL, HASH(options)) |
| 2430 | where options are: |
| 2431 | vector: eigenvectors to compute |
| 2432 | 'left': computes left eigenvectors |
| 2433 | 'right': computes right eigenvectors |
| 2434 | 'all': computes left and right eigenvectors |
| 2435 | 0: doesn't compute (default) |
| 2436 | rcondition: reciprocal condition numbers to compute (returned in HASH{'rconde'} for eigenvalues and HASH{'rcondv'} for eigenvectors) |
| 2437 | 'value': computes reciprocal condition numbers for eigenvalues |
| 2438 | 'vector': computes reciprocal condition numbers for eigenvectors |
| 2439 | 'all': computes reciprocal condition numbers for eigenvalues and eigenvectors |
| 2440 | 0: doesn't compute (default) |
| 2441 | error: specifies whether or not it computes the error bounds (returned in HASH{'eerror'} and HASH{'verror'}) |
| 2442 | error bound = EPS * One-norm / rcond(e|v) |
| 2443 | (reciprocal condition numbers for eigenvalues or eigenvectors must be computed). |
| 2444 | 1: returns error bounds |
| 2445 | 0: not computed |
| 2446 | scale: specifies whether or not it diagonaly scales the entry matrix |
| 2447 | (scale details returned in HASH : 'scale') |
| 2448 | 1: scales |
| 2449 | 0: Doesn't scale (default) |
| 2450 | permute: specifies whether or not it permutes row and columns |
| 2451 | (permute details returned in HASH{'balance'}) |
| 2452 | 1: permutes |
| 2453 | 0: Doesn't permute (default) |
| 2454 | schur: specifies whether or not it returns the Schur form (returned in HASH{'schur'}) |
| 2455 | 1: returns Schur form |
| 2456 | 0: not returned |
| 2457 | Returned values: |
| 2458 | eigenvalues (SCALAR CONTEXT), |
| 2459 | left eigenvectors if requested, |
| 2460 | right eigenvectors if requested, |
| 2461 | HASH{'norm'}: |
| 2462 | One-norm of the matrix |
| 2463 | HASH{'info'}: |
| 2464 | Info: if > 0, the QR algorithm failed to compute all the eigenvalues |
| 2465 | (see syevx for further details) |
| 2466 | |
| 2467 | =for example |
| 2468 | |
| 2469 | my $a = random(10,10); |
| 2470 | my %options = ( rcondition => 'all', |
| 2471 | vector => 'all', |
| 2472 | error => 1, |
| 2473 | scale => 1, |
| 2474 | permute=>1, |
| 2475 | schur => 1 |
| 2476 | ); |
| 2477 | my ( $eigenvalues, $left_eigenvectors, $right_eigenvectors, %result) = meigenx($a,%options); |
| 2478 | print "Error bounds for eigenvalues:\n $eigenvalues\n are:\n". transpose($result{'eerror'}) unless $info; |
| 2479 | |
| 2480 | =cut |
| 2481 | |
| 2482 | my %rcondition2sense = (value => 1, vector => 2, all => 3); |
| 2483 | my %vector2jobvl = (left => 1, all => 1); |
| 2484 | my %vector2jobvr = (right => 1, all => 1); |
| 2485 | *meigenx = \&PDL::meigenx; |
| 2486 | sub PDL::meigenx { |
| 2487 | &_square; |
| 2488 | my($m, %opt) = @_; |
| 2489 | my (%result); |
| 2490 | $m = $m->copy; |
| 2491 | $_ = null for my ($info, $ilo, $ihi, $abnrm, $scale, $rconde, $rcondv); |
| 2492 | $_ = $m->_similar_null for my ($vl, $vr); |
| 2493 | my @w = map $m->_similar_null, $m->_is_complex ? 1 : 1..2; |
| 2494 | my $balanc = ($opt{'scale'}?2:0) | ($opt{permute}?1:0); |
| 2495 | my $jobvl = $vector2jobvl{$opt{vector}} || $opt{rcondition} ? 1 : 0; |
| 2496 | my $jobvr = $vector2jobvr{$opt{vector}} || $opt{rcondition} ? 1 : 0; |
| 2497 | my $sense = $rcondition2sense{$opt{rcondition}} || 0; |
| 2498 | $m->t->_call_method('geevx', $jobvl, $jobvr, $balanc, $sense, @w, $vl, $vr, $ilo, $ihi, $scale, $abnrm, $rconde, $rcondv, $info); |
| 2499 | (my $w, $vl, $vr) = _eigen_extract($jobvl, $jobvr, $vl, $vr, @w); |
| 2500 | if ($info) { |
| 2501 | laerror("meigenx: The QR algorithm failed to converge"); |
| 2502 | print "Returning converged eigenvalues\n" if $_laerror; |
| 2503 | } |
| 2504 | $result{'schur'} = $m if $opt{'schur'}; |
| 2505 | $result{'balance'} = cat $ilo, $ihi if $opt{'permute'}; |
| 2506 | @result{qw(info norm)} = ($info, $abnrm); |
| 2507 | $result{'scale'} = $scale if $opt{'scale'}; |
| 2508 | if ($sense & 2) { |
| 2509 | $result{'rcondv'} = $rcondv; |
| 2510 | $result{'verror'} = (lamch(0)* $abnrm /$rcondv ) if $opt{'error'}; |
| 2511 | } |
| 2512 | if ($sense & 1) { |
| 2513 | $result{'rconde'} = $rconde; |
| 2514 | $result{'eerror'} = (lamch(0)* $abnrm /$rconde ) if $opt{'error'}; |
| 2515 | } |
| 2516 | ($w, ($vector2jobvl{$opt{vector}}?$vl->t->sever:()), ($vector2jobvr{$opt{vector}}?$vr->t->sever:()), %result); |
| 2517 | } |
| 2518 | |
| 2519 | =head2 mgeigen |
| 2520 | |
| 2521 | =for ref |
| 2522 | |
| 2523 | Computes generalized eigenvalues and, optionally, the left and/or right generalized eigenvectors |
| 2524 | for a pair of N-by-N real nonsymmetric matrices (A,B) . |
| 2525 | The alpha from ratio alpha/beta is a complex ndarray. |
| 2526 | Supports broadcasting. Uses L<ggev|PDL::LinearAlgebra::Real/ggev> or |
| 2527 | L<cggev|PDL::LinearAlgebra::Complex/cggev> from LAPACK. |
| 2528 | Works on transposed arrays. |
| 2529 | |
| 2530 | =for usage |
| 2531 | |
| 2532 | ( PDL(alpha), PDL(beta), ( PDL(LV), (PDL(RV) ), PDL(info)) = mgeigen(PDL(A),PDL(B) SCALAR(left vector), SCALAR(right vector)) |
| 2533 | left vector : FALSE = 0 | TRUE = 1, default = 0 |
| 2534 | right vector : FALSE = 0 | TRUE = 1, default = 0 |
| 2535 | |
| 2536 | =for example |
| 2537 | |
| 2538 | my $a = random(10,10); |
| 2539 | my $b = random(10,10); |
| 2540 | my ( $alpha, $beta, $left_eigenvectors, $right_eigenvectors ) = mgeigen($a, $b,1, 1); |
| 2541 | |
| 2542 | =cut |
| 2543 | |
| 2544 | *mgeigen = \&PDL::mgeigen; |
| 2545 | sub PDL::mgeigen { |
| 2546 | &_square_same; |
| 2547 | &_same_dims; |
| 2548 | my ($a,$b,$jobvl,$jobvr) = @_; |
| 2549 | $_ = $_->new_or_inplace->t for $a, $b; |
| 2550 | $_ = null for my ($info, $sdim); |
| 2551 | my @w = map $a->_similar_null, $a->_is_complex ? 1 : 1..2; |
| 2552 | $_ = $a->_similar_null for my ($vl, $vr, $beta); |
| 2553 | $a->_call_method('ggev', $jobvl, $jobvr, $b, @w, $beta, $vl, $vr, $info); |
| 2554 | _error($info, "mgeigen: Can't compute eigenvalues/vectors for PDL(s) %s"); |
| 2555 | (my $w, $vl, $vr) = _eigen_extract($jobvl, $jobvr, $vl, $vr, @w); |
| 2556 | ($w, $beta, ($jobvl?$vl->t->sever:()), ($jobvr?$vr->t->sever:()), $info); |
| 2557 | } |
| 2558 | |
| 2559 | =head2 mgeigenx |
| 2560 | |
| 2561 | =for ref |
| 2562 | |
| 2563 | Computes generalized eigenvalues, one-norms and, optionally, the left and/or right generalized |
| 2564 | eigenvectors for a pair of N-by-N real nonsymmetric matrices (A,B). |
| 2565 | The alpha from ratio alpha/beta is a complex ndarray. |
| 2566 | Uses L<ggevx|PDL::LinearAlgebra::Real/ggevx> or |
| 2567 | L<cggevx|PDL::LinearAlgebra::Complex/cggevx> from LAPACK. |
| 2568 | Works on transposed arrays. |
| 2569 | |
| 2570 | =for usage |
| 2571 | |
| 2572 | (PDL(alpha), PDL(beta), PDL(lv), PDL(rv), HASH(result) ) = mgeigenx(PDL(a), PDL(b), HASH(options)) |
| 2573 | where options are: |
| 2574 | vector: eigenvectors to compute |
| 2575 | 'left': computes left eigenvectors |
| 2576 | 'right': computes right eigenvectors |
| 2577 | 'all': computes left and right eigenvectors |
| 2578 | 0: doesn't compute (default) |
| 2579 | rcondition: reciprocal condition numbers to compute (returned in HASH{'rconde'} for eigenvalues and HASH{'rcondv'} for eigenvectors) |
| 2580 | 'value': computes reciprocal condition numbers for eigenvalues |
| 2581 | 'vector': computes reciprocal condition numbers for eigenvectors |
| 2582 | 'all': computes reciprocal condition numbers for eigenvalues and eigenvectors |
| 2583 | 0: doesn't compute (default) |
| 2584 | error: specifies whether or not it computes the error bounds (returned in HASH{'eerror'} and HASH{'verror'}) |
| 2585 | error bound = EPS * sqrt(one-norm(a)**2 + one-norm(b)**2) / rcond(e|v) |
| 2586 | (reciprocal condition numbers for eigenvalues or eigenvectors must be computed). |
| 2587 | 1: returns error bounds |
| 2588 | 0: not computed |
| 2589 | scale: specifies whether or not it diagonaly scales the entry matrix |
| 2590 | (scale details returned in HASH : 'lscale' and 'rscale') |
| 2591 | 1: scales |
| 2592 | 0: doesn't scale (default) |
| 2593 | permute: specifies whether or not it permutes row and columns |
| 2594 | (permute details returned in HASH{'balance'}) |
| 2595 | 1: permutes |
| 2596 | 0: Doesn't permute (default) |
| 2597 | schur: specifies whether or not it returns the Schur forms (returned in HASH{'aschur'} and HASH{'bschur'}) |
| 2598 | (right or left eigenvectors must be computed). |
| 2599 | 1: returns Schur forms |
| 2600 | 0: not returned |
| 2601 | Returned values: |
| 2602 | alpha, |
| 2603 | beta, |
| 2604 | left eigenvectors if requested, |
| 2605 | right eigenvectors if requested, |
| 2606 | HASH{'anorm'}, HASH{'bnorm'}: |
| 2607 | One-norm of the matrix A and B |
| 2608 | HASH{'info'}: |
| 2609 | Info: if > 0, the QR algorithm failed to compute all the eigenvalues |
| 2610 | (see syevx for further details) |
| 2611 | |
| 2612 | =for example |
| 2613 | |
| 2614 | $a = random(10,10); |
| 2615 | $b = random(10,10); |
| 2616 | %options = (rcondition => 'all', |
| 2617 | vector => 'all', |
| 2618 | error => 1, |
| 2619 | scale => 1, |
| 2620 | permute=>1, |
| 2621 | schur => 1 |
| 2622 | ); |
| 2623 | ($alpha, $beta, $left_eigenvectors, $right_eigenvectors, %result) = mgeigenx($a, $b,%options); |
| 2624 | print "Error bounds for eigenvalues:\n $eigenvalues\n are:\n". transpose($result{'eerror'}) unless $info; |
| 2625 | |
| 2626 | =cut |
| 2627 | |
| 2628 | *mgeigenx = \&PDL::mgeigenx; |
| 2629 | sub PDL::mgeigenx { |
| 2630 | &_square_same; |
| 2631 | my ($a, $b, %opt) = @_; |
| 2632 | my @adims = $a->dims; |
| 2633 | $_ = $_->new_or_inplace->t for $a, $b; |
| 2634 | my (%result); |
| 2635 | $_ = $a->_similar_null for my ($vl, $vr, $beta); |
| 2636 | my @w = map $a->_similar_null, $a->_is_complex ? 1 : 1..2; |
| 2637 | $_ = null for my ($rconde, $rcondv, $info, $ilo, $ihi, $rscale, $lscale, $abnrm, $bbnrm); |
| 2638 | my $jobvl = $vector2jobvl{$opt{vector}} || $opt{rcondition} ? 1 : 0; |
| 2639 | my $jobvr = $vector2jobvr{$opt{vector}} || $opt{rcondition} ? 1 : 0; |
| 2640 | my $sense = $rcondition2sense{$opt{rcondition}} || 0; |
| 2641 | my $balanc = ($opt{scale}?2:0) | ($opt{permute}?1:0); |
| 2642 | $a->_call_method('ggevx', $balanc, $jobvl, $jobvr, $sense, $b, @w, |
| 2643 | $beta, $vl, $vr, $ilo, $ihi, $lscale, $rscale, |
| 2644 | $abnrm, $bbnrm, $rconde, $rcondv, $info); |
| 2645 | (my $w, $vl, $vr) = _eigen_extract($jobvl, $jobvr, $vl, $vr, @w); |
| 2646 | if ($info > 0 && $info < $adims[1]) { |
| 2647 | laerror("mgeigenx: The QZ algorithm failed to converge"); |
| 2648 | print "Returning converged eigenvalues\n" if $_laerror; |
| 2649 | } elsif ($info) { |
| 2650 | laerror("mgeigenx: Error from hgeqz or tgevc"); |
| 2651 | } |
| 2652 | @result{qw(aschur bschur)} = map $_->t, $a, $b if $opt{schur}; |
| 2653 | $result{balance} = cat $ilo, $ihi if $opt{permute}; |
| 2654 | @result{qw(info anorm bnorm)} = ($info, $abnrm, $bbnrm); |
| 2655 | @result{qw(lscale rscale)} = ($lscale, $rscale) if $opt{scale}; |
| 2656 | # Doesn't use lacpy2 =(sqrt **2 , **2) without unnecessary overflow |
| 2657 | if ($sense & 2) { |
| 2658 | $result{rcondv} = $rcondv; |
| 2659 | $result{verror} = lamch(0) * sqrt($abnrm->pow(2) + $bbnrm->pow(2)) /$rcondv if $opt{error}; |
| 2660 | } |
| 2661 | if ($sense & 1) { |
| 2662 | $result{rconde} = $rconde; |
| 2663 | $result{eerror} = lamch(0) * sqrt($abnrm->pow(2) + $bbnrm->pow(2)) /$rconde if $opt{error}; |
| 2664 | } |
| 2665 | ($w, $beta, ($vector2jobvl{$opt{vector}}?$vl->t:()), ($vector2jobvr{$opt{vector}}?$vr->t:()), %result); |
| 2666 | } |
| 2667 | |
| 2668 | =head2 msymeigen |
| 2669 | |
| 2670 | =for ref |
| 2671 | |
| 2672 | Computes eigenvalues and, optionally eigenvectors of a real symmetric square or |
| 2673 | complex Hermitian matrix (spectral decomposition). |
| 2674 | The eigenvalues are computed from lower or upper triangular matrix. |
| 2675 | If only eigenvalues are requested, info is returned in array context. |
| 2676 | Supports broadcasting and works inplace if eigenvectors are requested. |
| 2677 | From LAPACK, uses L<syev|PDL::LinearAlgebra::Real/syev> or L<syevd|PDL::LinearAlgebra::Real/syevd> for real |
| 2678 | and L<cheev|PDL::LinearAlgebra::Complex/cheev> or L<cheevd|PDL::LinearAlgebra::Complex/cheevd> for complex. |
| 2679 | Works on transposed array(s). |
| 2680 | |
| 2681 | =for usage |
| 2682 | |
| 2683 | (PDL(values), (PDL(VECTORS)), PDL(info)) = msymeigen(PDL, SCALAR(uplo), SCALAR(vector), SCALAR(method)) |
| 2684 | uplo : UPPER = 0 | LOWER = 1, default = 0 |
| 2685 | vector : FALSE = 0 | TRUE = 1, default = 0 |
| 2686 | method : 'syev' | 'syevd' | 'cheev' | 'cheevd', default = 'syevd'|'cheevd' |
| 2687 | |
| 2688 | =for example |
| 2689 | |
| 2690 | # Assume $a is symmetric |
| 2691 | my $a = random(10,10); |
| 2692 | my ( $eigenvalues, $eigenvectors ) = msymeigen($a,0,1, 'syev'); |
| 2693 | |
| 2694 | =cut |
| 2695 | |
| 2696 | *msymeigen = \&PDL::msymeigen; |
| 2697 | sub PDL::msymeigen { |
| 2698 | &_square; |
| 2699 | my ($m, $upper, $jobv, $method) = @_; |
| 2700 | $method //= [ 'syevd', 'cheevd' ]; |
| 2701 | $m = $m->copy unless ($m->is_inplace(0) and $jobv); |
| 2702 | my ($w, $info) = $m->t->_call_method($method, $jobv, $upper); |
| 2703 | _error($info, "msymeigen: The algorithm failed to converge for PDL(s) %s"); |
| 2704 | !wantarray ? $w : ($w, ($jobv?$m:()), $info); |
| 2705 | } |
| 2706 | |
| 2707 | =head2 msymeigenx |
| 2708 | |
| 2709 | =for ref |
| 2710 | |
| 2711 | Computes eigenvalues and, optionally eigenvectors of a symmetric square matrix (spectral decomposition). |
| 2712 | The eigenvalues are computed from lower or upper triangular matrix and can be selected by specifying a |
| 2713 | range. From LAPACK, uses L<syevx|PDL::LinearAlgebra::Real/syevx> or |
| 2714 | L<syevr|PDL::LinearAlgebra::Real/syevr> for real and L<cheevx|PDL::LinearAlgebra::Complex/cheevx> |
| 2715 | or L<cheevr|PDL::LinearAlgebra::Complex/cheevr> for complex. Works on transposed arrays. |
| 2716 | |
| 2717 | =for usage |
| 2718 | |
| 2719 | (PDL(value), (PDL(vector)), PDL(n), PDL(info), (PDL(support)) ) = msymeigenx(PDL, SCALAR(uplo), SCALAR(vector), HASH(options)) |
| 2720 | uplo : UPPER = 0 | LOWER = 1, default = 0 |
| 2721 | vector : FALSE = 0 | TRUE = 1, default = 0 |
| 2722 | where options are: |
| 2723 | range_type: method for selecting eigenvalues |
| 2724 | indice: range of indices |
| 2725 | interval: range of values |
| 2726 | 0: find all eigenvalues and optionally all vectors |
| 2727 | range: PDL(2), lower and upper bounds interval or smallest and largest indices |
| 2728 | 1<=range<=N for indice |
| 2729 | abstol: specifies error tolerance for eigenvalues |
| 2730 | method: specifies which method to use (see LAPACK for further details) |
| 2731 | 'syevx' (default) |
| 2732 | 'syevr' |
| 2733 | 'cheevx' (default) |
| 2734 | 'cheevr' |
| 2735 | Returned values: |
| 2736 | eigenvalues (SCALAR CONTEXT), |
| 2737 | eigenvectors if requested, |
| 2738 | total number of eigenvalues found (n), |
| 2739 | info |
| 2740 | issupz or ifail (support) according to method used and returned info, |
| 2741 | for (sy|che)evx returns support only if info != 0 |
| 2742 | |
| 2743 | |
| 2744 | =for example |
| 2745 | |
| 2746 | # Assume $a is symmetric |
| 2747 | my $a = random(10,10); |
| 2748 | my $overflow = lamch(9); |
| 2749 | my $range = cat pdl(0),$overflow; |
| 2750 | my $abstol = pdl(1.e-5); |
| 2751 | my %options = (range_type=>'interval', |
| 2752 | range => $range, |
| 2753 | abstol => $abstol, |
| 2754 | method=>'syevd'); |
| 2755 | my ( $eigenvalues, $eigenvectors, $n, $isuppz ) = msymeigenx($a,0,1, %options); |
| 2756 | |
| 2757 | =cut |
| 2758 | |
| 2759 | *msymeigenx = \&PDL::msymeigenx; |
| 2760 | |
| 2761 | my %range_type2range = (interval => 1, indice => 2); |
| 2762 | sub PDL::msymeigenx { |
| 2763 | &_square; |
| 2764 | my ($m, $upper, $jobz, %opt) = @_; |
| 2765 | my @dims = $m->dims; |
| 2766 | my $range = $range_type2range{$opt{range_type}} || 0; |
| 2767 | if ((ref $opt{range}) ne 'PDL') { |
| 2768 | $opt{range} = pdl([0,0]); |
| 2769 | $range = 0; |
| 2770 | } elsif ($range == 2) { |
| 2771 | barf "msymeigenx: Indices must be > 0" unless $opt{range}->(0) > 0; |
| 2772 | barf "msymeigenx: Indices must be <= $dims[1]" unless $opt{range}->(1) <= $dims[1]; |
| 2773 | } elsif ($range == 1) { |
| 2774 | barf "msymeigenx: Interval limits must be different" unless ($opt{range}->(0) != $opt{range}->(1)); |
| 2775 | } |
| 2776 | if (!defined $opt{'abstol'}) { |
| 2777 | my $unfl = lamch(1); |
| 2778 | $unfl->labad(lamch(9)); |
| 2779 | $opt{abstol} = $unfl + $unfl; |
| 2780 | } |
| 2781 | my $method = $opt{'method'} || ['syevx','cheevx']; |
| 2782 | $upper = $upper ? 0 : 1; |
| 2783 | $m = $m->copy; |
| 2784 | my ($n, $w, $z, $support, $info) = $m->_call_method($method, $jobz, $range, $upper, $opt{range}->(0), $opt{range}->(1),$opt{range}->(0),$opt{range}->(1),$opt{abstol}); |
| 2785 | if ($info) { |
| 2786 | laerror("msymeigenx: The algorithm failed to converge."); |
| 2787 | print "See support for details.\n" if $_laerror; |
| 2788 | } |
| 2789 | if ($jobz) { |
| 2790 | return ($w, $z->t->sever, $n, $info, $support) if $info->any; |
| 2791 | return (undef,undef,$n,$info,$method =~ qr/evr/?$support:()) if $n == 0; |
| 2792 | return ($w(:$n-1)->sever, $z->t->slice(":@{[$n->sclr-1]}")->sever, $n, $info, $method =~ qr/evr/?$support:()); |
| 2793 | } else { |
| 2794 | return $w if !wantarray; |
| 2795 | if ($info) { |
| 2796 | ($w, $n, $info, $support); |
| 2797 | } else { |
| 2798 | ($w(:$n-1)->sever, $n, $info, $method =~ qr/evr/?$support:()); |
| 2799 | } |
| 2800 | } |
| 2801 | } |
| 2802 | |
| 2803 | =head2 msymgeigen |
| 2804 | |
| 2805 | =for ref |
| 2806 | |
| 2807 | Computes eigenvalues and, optionally eigenvectors of a real generalized |
| 2808 | symmetric-definite or Hermitian-definite eigenproblem. |
| 2809 | The eigenvalues are computed from lower or upper triangular matrix |
| 2810 | If only eigenvalues are requested, info is returned in array context. |
| 2811 | Supports broadcasting. From LAPACK, uses L<sygv|PDL::LinearAlgebra::Real/sygv> or L<sygvd|PDL::LinearAlgebra::Real/sygvd> for real |
| 2812 | or L<chegv|PDL::LinearAlgebra::Complex/chegv> or L<chegvd|PDL::LinearAlgebra::Complex/chegvd> for complex. |
| 2813 | Works on transposed array(s). |
| 2814 | |
| 2815 | =for usage |
| 2816 | |
| 2817 | (PDL(values), (PDL(vectors)), PDL(info)) = msymgeigen(PDL(a), PDL(b),SCALAR(uplo), SCALAR(vector), SCALAR(type), SCALAR(method)) |
| 2818 | uplo : UPPER = 0 | LOWER = 1, default = 0 |
| 2819 | vector : FALSE = 0 | TRUE = 1, default = 0 |
| 2820 | type : |
| 2821 | 1: A * x = (lambda) * B * x |
| 2822 | 2: A * B * x = (lambda) * x |
| 2823 | 3: B * A * x = (lambda) * x |
| 2824 | default = 1 |
| 2825 | method : 'sygv' | 'sygvd' for real or ,'chegv' | 'chegvd' for complex, default = 'sygvd' | 'chegvd' |
| 2826 | |
| 2827 | =for example |
| 2828 | |
| 2829 | # Assume $a is symmetric |
| 2830 | my $a = random(10,10); |
| 2831 | my $b = random(10,10); |
| 2832 | $b = $b->crossprod($b); |
| 2833 | my ( $eigenvalues, $eigenvectors ) = msymgeigen($a, $b, 0, 1, 1, 'sygv'); |
| 2834 | |
| 2835 | =cut |
| 2836 | |
| 2837 | *msymgeigen = \&PDL::msymgeigen; |
| 2838 | sub PDL::msymgeigen { |
| 2839 | &_square_same; |
| 2840 | &_same_dims; |
| 2841 | my ($a, $b, $upper, $jobv, $type, $method) = @_; |
| 2842 | $type ||= 1; |
| 2843 | $method //= [ 'sygvd', 'chegvd' ]; |
| 2844 | $upper = 1-$upper; |
| 2845 | $a = $a->copy; |
| 2846 | $b = $b->copy; |
| 2847 | my ($w, $info) = $a->_call_method($method, $type, $jobv, $upper, $b); |
| 2848 | _error($info, "msymgeigen: Can't compute eigenvalues/vectors: matrix (PDL(s) %s) is/are not positive definite or the algorithm failed to converge"); |
| 2849 | !wantarray ? $w : ($w, $jobv?$a->t->sever:(), $info); |
| 2850 | } |
| 2851 | |
| 2852 | =head2 msymgeigenx |
| 2853 | |
| 2854 | =for ref |
| 2855 | |
| 2856 | Computes eigenvalues and, optionally eigenvectors of a real generalized |
| 2857 | symmetric-definite or Hermitian eigenproblem. |
| 2858 | The eigenvalues are computed from lower or upper triangular matrix and can be selected by specifying a |
| 2859 | range. Uses L<sygvx|PDL::LinearAlgebra::Real/syevx> or L<cheevx|PDL::LinearAlgebra::Complex/cheevx> |
| 2860 | from LAPACK. Works on transposed arrays. |
| 2861 | |
| 2862 | =for usage |
| 2863 | |
| 2864 | (PDL(value), (PDL(vector)), PDL(info), PDL(n), (PDL(support)) ) = msymeigenx(PDL(a), PDL(b), SCALAR(uplo), SCALAR(vector), HASH(options)) |
| 2865 | uplo : UPPER = 0 | LOWER = 1, default = 0 |
| 2866 | vector : FALSE = 0 | TRUE = 1, default = 0 |
| 2867 | where options are: |
| 2868 | type : Specifies the problem type to be solved |
| 2869 | 1: A * x = (lambda) * B * x |
| 2870 | 2: A * B * x = (lambda) * x |
| 2871 | 3: B * A * x = (lambda) * x |
| 2872 | default = 1 |
| 2873 | range_type: method for selecting eigenvalues |
| 2874 | indice: range of indices |
| 2875 | interval: range of values |
| 2876 | 0: find all eigenvalues and optionally all vectors |
| 2877 | range: PDL(2), lower and upper bounds interval or smallest and largest indices |
| 2878 | 1<=range<=N for indice |
| 2879 | abstol: specifies error tolerance for eigenvalues |
| 2880 | Returned values: |
| 2881 | eigenvalues (SCALAR CONTEXT), |
| 2882 | eigenvectors if requested, |
| 2883 | total number of eigenvalues found (n), |
| 2884 | info |
| 2885 | ifail according to returned info (support). |
| 2886 | |
| 2887 | =for example |
| 2888 | |
| 2889 | # Assume $a is symmetric |
| 2890 | my $a = random(10,10); |
| 2891 | my $b = random(10,10); |
| 2892 | $b = $b->crossprod($b); |
| 2893 | my $overflow = lamch(9); |
| 2894 | my $range = cat pdl(0),$overflow; |
| 2895 | my $abstol = pdl(1.e-5); |
| 2896 | my %options = (range_type=>'interval', |
| 2897 | range => $range, |
| 2898 | abstol => $abstol, |
| 2899 | type => 1); |
| 2900 | my ( $eigenvalues, $eigenvectors, $n, $isuppz ) = msymgeigenx($a, $b, 0,1, %options); |
| 2901 | |
| 2902 | =cut |
| 2903 | |
| 2904 | *msymgeigenx = \&PDL::msymgeigenx; |
| 2905 | |
| 2906 | sub PDL::msymgeigenx { |
| 2907 | &_square_same; |
| 2908 | my ($a, $b, $upper, $jobv, %opt) = @_; |
| 2909 | my @adims = $a->dims; |
| 2910 | my $range = $range_type2range{$opt{range_type}} || 0; |
| 2911 | if (!UNIVERSAL::isa($opt{range},'PDL')) { |
| 2912 | $opt{range} = pdl([0,0]); |
| 2913 | $range = 0; |
| 2914 | } |
| 2915 | $opt{type} //= 1; |
| 2916 | if (!defined $opt{'abstol'}) { |
| 2917 | my $unfl = lamch(1); |
| 2918 | my $ovfl = lamch(9); |
| 2919 | $unfl->labad($ovfl); |
| 2920 | $opt{'abstol'} = $unfl + $unfl; |
| 2921 | } |
| 2922 | $upper = $upper ? 0 : 1; |
| 2923 | $a = $a->copy; |
| 2924 | $b = $b->copy; |
| 2925 | my ($n, $w, $z, $support, $info) =$a->_call_method(['sygvx','chegvx'], $opt{type}, $jobv, $range, $upper, |
| 2926 | $b, $opt{range}->(0), $opt{range}->(1),$opt{range}->(0),$opt{range}->(1), |
| 2927 | $opt{abstol}); |
| 2928 | if ($info > 0 && $info < $adims[1]) { |
| 2929 | laerror("msymgeigenx: The algorithm failed to converge"); |
| 2930 | print("see support for details\n") if $_laerror; |
| 2931 | } elsif ($info) { |
| 2932 | $info = $info - $adims[1] - 1; |
| 2933 | barf("msymgeigenx: The leading minor of order $info of B is not positive definite\n"); |
| 2934 | } |
| 2935 | return $w if !wantarray; |
| 2936 | ($w, $jobv?$z->t->sever:(), $n, $info, $info?$support:()); |
| 2937 | } |
| 2938 | |
| 2939 | |
| 2940 | =head2 mdsvd |
| 2941 | |
| 2942 | =for ref |
| 2943 | |
| 2944 | Computes SVD using Cuppen's divide and conquer algorithm. |
| 2945 | Return singular values in scalar context else left (U), |
| 2946 | singular values, right (V' (hermitian for complex)) singular vectors and info. |
| 2947 | Supports broadcasting. |
| 2948 | If only singulars values are requested, info is only returned in array context. |
| 2949 | Uses L<gesdd|PDL::LinearAlgebra::Real/gesdd> or L<cgesdd|PDL::LinearAlgebra::Complex/cgesdd> from LAPACK. |
| 2950 | |
| 2951 | =for usage |
| 2952 | |
| 2953 | (PDL(U), (PDL(s), PDL(Vt)), PDL(info)) = mdsvd(PDL, SCALAR(job)) |
| 2954 | job : 0 = computes only singular values |
| 2955 | 1 = computes full SVD (square U and Vt) |
| 2956 | 2 = computes SVD (singular values, right and left singular vectors) |
| 2957 | default = 1 |
| 2958 | |
| 2959 | =for example |
| 2960 | |
| 2961 | my $a = random(5,10); |
| 2962 | my ($u, $s, $vt) = mdsvd($a); |
| 2963 | print $u x gurney($s, $a->dims) x $vt; |
| 2964 | |
| 2965 | =cut |
| 2966 | |
| 2967 | *mdsvd = \&PDL::mdsvd; |
| 2968 | sub PDL::mdsvd { |
| 2969 | my ($m, $jobz) = @_; |
| 2970 | my @dims = $m->dims; |
| 2971 | $jobz = !wantarray ? 0 : $jobz // 1; |
| 2972 | $m = $m->t->copy; |
| 2973 | my ($s, $u, $vt, $info) = $m->_call_method('gesdd', $jobz); |
| 2974 | _error($info, "mdsvd: Matrix (PDL(s) %s) is/are singular"); |
| 2975 | return ($u->t, $s, $vt->t, $info) if $jobz; |
| 2976 | wantarray ? ($s, $info) : $s; |
| 2977 | } |
| 2978 | |
| 2979 | =head2 msvd |
| 2980 | |
| 2981 | =for ref |
| 2982 | |
| 2983 | Computes SVD. |
| 2984 | |
| 2985 | Can compute singular values, either U or Vt or neither. |
| 2986 | Return singular values in scalar context else left (U), |
| 2987 | singular values, right (V' (hermitian for complex) singular vector and info. |
| 2988 | Supports broadcasting. |
| 2989 | If only singular values are requested, info is returned in array context. |
| 2990 | Uses L<gesvd|PDL::LinearAlgebra::Real/gesvd> or L<cgesvd|PDL::LinearAlgebra::Complex/cgesvd> from LAPACK. |
| 2991 | |
| 2992 | =for usage |
| 2993 | |
| 2994 | ( (PDL(U)), PDL(s), (PDL(Vt), PDL(info)) = msvd(PDL, SCALAR(jobu), SCALAR(jobv)) |
| 2995 | jobu : 0 = Doesn't compute U |
| 2996 | 1 = computes full SVD (square U) |
| 2997 | 2 = computes right singular vectors |
| 2998 | default = 1 |
| 2999 | jobv : 0 = Doesn't compute Vt |
| 3000 | 1 = computes full SVD (square Vt) |
| 3001 | 2 = computes left singular vectors |
| 3002 | default = 1 |
| 3003 | |
| 3004 | =for example |
| 3005 | |
| 3006 | my $a = random(10,10); |
| 3007 | my ($u, $s, $vt) = msvd($a); |
| 3008 | print $u x gurney($s, $a->dims) x $vt; |
| 3009 | |
| 3010 | =cut |
| 3011 | |
| 3012 | *msvd = \&PDL::msvd; |
| 3013 | sub PDL::msvd { |
| 3014 | my ($m, $jobu, $jobv) = @_; |
| 3015 | $jobu = !wantarray ? 0 : $jobu // 1; |
| 3016 | $jobv = !wantarray ? 0 : $jobv // 1; |
| 3017 | $m = $m->t->copy; |
| 3018 | my ($s, $u, $vt, $info) =$m->_call_method('gesvd', $jobu, $jobv); |
| 3019 | _error($info, "msvd: Matrix (PDL(s) %s) is/are singular"); |
| 3020 | wantarray ? ($jobu?$u->t:(), $s, $jobv?$vt->t:(), $info) : $s; |
| 3021 | } |
| 3022 | |
| 3023 | =head2 mgsvd |
| 3024 | |
| 3025 | =for ref |
| 3026 | |
| 3027 | Computes generalized (or quotient) singular value decomposition. |
| 3028 | If the effective rank of (A',B')' is 0 return only unitary V, U, Q. |
| 3029 | Handles complex data. |
| 3030 | Uses L<ggsvd|PDL::LinearAlgebra::Real/ggsvd> or |
| 3031 | L<cggsvd|PDL::LinearAlgebra::Complex/cggsvd> from LAPACK. Works on transposed arrays. |
| 3032 | |
| 3033 | =for usage |
| 3034 | |
| 3035 | (PDL(sa), PDL(sb), %ret) = mgsvd(PDL(a), PDL(b), %HASH(options)) |
| 3036 | where options are: |
| 3037 | V: whether or not computes V (boolean, returned in HASH{'V'}) |
| 3038 | U: whether or not computes U (boolean, returned in HASH{'U'}) |
| 3039 | Q: whether or not computes Q (boolean, returned in HASH{'Q'}) |
| 3040 | D1: whether or not computes D1 (boolean, returned in HASH{'D1'}) |
| 3041 | D2: whether or not computes D2 (boolean, returned in HASH{'D2'}) |
| 3042 | 0R: whether or not computes 0R (boolean, returned in HASH{'0R'}) |
| 3043 | R: whether or not computes R (boolean, returned in HASH{'R'}) |
| 3044 | X: whether or not computes X (boolean, returned in HASH{'X'}) |
| 3045 | all: whether or not computes all the above. |
| 3046 | Returned value: |
| 3047 | sa,sb : singular value pairs of A and B (generalized singular values = sa/sb) |
| 3048 | $ret{'rank'} : effective numerical rank of (A',B')' |
| 3049 | $ret{'info'} : info from (c)ggsvd |
| 3050 | |
| 3051 | =for example |
| 3052 | |
| 3053 | my $a = random(5,5); |
| 3054 | my $b = random(5,7); |
| 3055 | my ($c, $s, %ret) = mgsvd($a, $b, X => 1); |
| 3056 | |
| 3057 | =cut |
| 3058 | |
| 3059 | my @gsvd_opts = qw(V U Q D1 D2 0R R X); |
| 3060 | *mgsvd = \&PDL::mgsvd; |
| 3061 | sub PDL::mgsvd { |
| 3062 | &_matrices_matchcolumns; |
| 3063 | my @diag_args = (0,1); |
| 3064 | my ($a, $b, %opt) = @_; |
| 3065 | my @adims = $a->dims; |
| 3066 | my @bdims = $b->dims; |
| 3067 | @opt{@gsvd_opts} = (1) x @gsvd_opts if $opt{all}; |
| 3068 | my $type = $a->type; |
| 3069 | my $jobqx = ($opt{Q} || $opt{X}) ? 1 : 0; |
| 3070 | $a = $a->copy; |
| 3071 | $b = $b->copy; |
| 3072 | my ($k, $l, $alpha, $beta, $U, $V, $Q, $iwork, $info) = $a->t->_call_method('ggsvd', $opt{U}, $opt{V}, $jobqx, $b->t); |
| 3073 | laerror("mgsvd: The Jacobi procedure fails to converge") if $info->any; |
| 3074 | my %ret = (rank=>$k + $l, info=>$info); |
| 3075 | warn "mgsvd: Effective rank of 0 in mgsvd" if (!$ret{rank} and $_laerror); |
| 3076 | if (%opt) { |
| 3077 | $Q = $Q->t->sever if $jobqx; |
| 3078 | if (($adims[1] - $k - $l) < 0 && $ret{rank}) { |
| 3079 | if ($opt{'0R'} || $opt{R} || $opt{X}) { |
| 3080 | $a->reshape($adims[0], ($k + $l)); |
| 3081 | # Slice $a ??? => always square ?? |
| 3082 | $a->slice("@{[$adims[0] - ($k+$l-$adims[1])]} : , $adims[1]:") .= |
| 3083 | $b->slice("@{[$adims[1]-$k]}:@{[$l-1]},@[[$adims[0]+$adims[1]-$k - $l]}:@{[$adims[0]-1]}")->t; |
| 3084 | $ret{'0R'} = $a if $opt{'0R'}; |
| 3085 | } |
| 3086 | if ($opt{D1}) { |
| 3087 | my $D1 = zeroes($type, @adims[1,1]); |
| 3088 | $D1->diagonal(0,1) .= $alpha(:($adims[1]-1)); |
| 3089 | $D1 = $D1->t->reshape($adims[1] , ($k+$l))->t->sever; |
| 3090 | $ret{D1} = $D1; |
| 3091 | } |
| 3092 | } elsif ($ret{rank}) { |
| 3093 | if ($opt{'0R'} || $opt{R} || $opt{X}) { |
| 3094 | $a->reshape($adims[0], ($k + $l)); |
| 3095 | $ret{'0R'} = $a if $opt{'0R'}; |
| 3096 | } |
| 3097 | if ($opt{D1}) { |
| 3098 | my $D1 = zeroes($type, ($k + $l) x 2); |
| 3099 | $D1->diagonal(0,1) .= $alpha(:($k+$l-1)); |
| 3100 | $D1->reshape(($k + $l), $adims[1]); |
| 3101 | $ret{D1} = $D1; |
| 3102 | } |
| 3103 | } |
| 3104 | if ($opt{D2} && $ret{rank}) { |
| 3105 | my $work = zeroes($b->type, $l, $l); |
| 3106 | $work->diagonal(0,1) .= $beta($k:($k+$l-1)); |
| 3107 | my $D2 = zeroes($b->type, ($k + $l), $bdims[1]); |
| 3108 | $D2( $k:, :($l-1) ) .= $work; |
| 3109 | $ret{D2} = $D2; |
| 3110 | } |
| 3111 | if ($ret{rank} && ($opt{X} || $opt{R})) { |
| 3112 | my $work = $a->slice("@{[-($k + $l)]}:"); |
| 3113 | $ret{R} = $work if $opt{R}; |
| 3114 | if ($opt{X}) { |
| 3115 | my $X = $a->_similar(@adims[0,0]); |
| 3116 | $X->diagonal(@diag_args) .= 1 if ($adims[0] > ($k + $l)); |
| 3117 | $X->slice("@{[-($k + $l)]}:, @{[-($k + $l)]}:") .= $work->t; |
| 3118 | $ret{X} = $Q x $X; |
| 3119 | } |
| 3120 | } |
| 3121 | $ret{U} = $U->t->sever if $opt{U}; |
| 3122 | $ret{V} = $V->t->sever if $opt{V}; |
| 3123 | $ret{Q} = $Q if $opt{Q}; |
| 3124 | } |
| 3125 | $ret{rank} ? ($alpha($k:($k+$l-1))->sever, $beta($k:($k+$l-1))->sever, %ret ) : (undef, undef, %ret); |
| 3126 | } |
| 3127 | |
| 3128 | #TODO |
| 3129 | |
| 3130 | # Others things |
| 3131 | |
| 3132 | # rectangular diag |
| 3133 | # usage |
| 3134 | # is_inplace and function which modify entry matrix |
| 3135 | # broadcasting support |
| 3136 | # automatically create PDL |
| 3137 | # inplace operation and memory |
| 3138 | # PDL type, verify float/double |
| 3139 | # eig_det qr_det |
| 3140 | # (g)schur(x): |
| 3141 | # if conjugate pair |
| 3142 | # non generalized pb: $seldim ?? (cf: generalized) |
| 3143 | # return conjugate pair if only selected? |
| 3144 | # port to PDL::Matrix |
| 3145 | |
| 3146 | =head1 AUTHOR |
| 3147 | |
| 3148 | Copyright (C) Grégory Vanuxem 2005-2018. |
| 3149 | |
| 3150 | This library is free software; you can redistribute it and/or modify |
| 3151 | it under the terms of the Perl Artistic License as in the file Artistic_2 |
| 3152 | in this distribution. |
| 3153 | |
| 3154 | =cut |
| 3155 | |
| 3156 | 1; |