]> www.ginac.de Git - ginac.git/blob - ginac/matrix.cpp
f34534afdb1ab3ee39b567bd11c7ed7408010855
[ginac.git] / ginac / matrix.cpp
1 /** @file matrix.cpp
2  *
3  *  Implementation of symbolic matrices */
4
5 /*
6  *  GiNaC Copyright (C) 1999-2001 Johannes Gutenberg University Mainz, Germany
7  *
8  *  This program is free software; you can redistribute it and/or modify
9  *  it under the terms of the GNU General Public License as published by
10  *  the Free Software Foundation; either version 2 of the License, or
11  *  (at your option) any later version.
12  *
13  *  This program is distributed in the hope that it will be useful,
14  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
15  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  *  GNU General Public License for more details.
17  *
18  *  You should have received a copy of the GNU General Public License
19  *  along with this program; if not, write to the Free Software
20  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
21  */
22
23 #include <algorithm>
24 #include <map>
25 #include <stdexcept>
26
27 #include "matrix.h"
28 #include "archive.h"
29 #include "numeric.h"
30 #include "lst.h"
31 #include "idx.h"
32 #include "indexed.h"
33 #include "utils.h"
34 #include "debugmsg.h"
35 #include "power.h"
36 #include "symbol.h"
37 #include "normal.h"
38
39 namespace GiNaC {
40
41 GINAC_IMPLEMENT_REGISTERED_CLASS(matrix, basic)
42
43 //////////
44 // default ctor, dtor, copy ctor, assignment operator and helpers:
45 //////////
46
47 // public
48
49 /** Default ctor.  Initializes to 1 x 1-dimensional zero-matrix. */
50 matrix::matrix() : inherited(TINFO_matrix), row(1), col(1)
51 {
52         debugmsg("matrix default ctor",LOGLEVEL_CONSTRUCT);
53         m.push_back(_ex0());
54 }
55
56 // protected
57
58 /** For use by copy ctor and assignment operator. */
59 void matrix::copy(const matrix & other)
60 {
61         inherited::copy(other);
62         row = other.row;
63         col = other.col;
64         m = other.m;  // STL's vector copying invoked here
65 }
66
67 void matrix::destroy(bool call_parent)
68 {
69         if (call_parent) inherited::destroy(call_parent);
70 }
71
72 //////////
73 // other ctors
74 //////////
75
76 // public
77
78 /** Very common ctor.  Initializes to r x c-dimensional zero-matrix.
79  *
80  *  @param r number of rows
81  *  @param c number of cols */
82 matrix::matrix(unsigned r, unsigned c)
83   : inherited(TINFO_matrix), row(r), col(c)
84 {
85         debugmsg("matrix ctor from unsigned,unsigned",LOGLEVEL_CONSTRUCT);
86         m.resize(r*c, _ex0());
87 }
88
89 // protected
90
91 /** Ctor from representation, for internal use only. */
92 matrix::matrix(unsigned r, unsigned c, const exvector & m2)
93   : inherited(TINFO_matrix), row(r), col(c), m(m2)
94 {
95         debugmsg("matrix ctor from unsigned,unsigned,exvector",LOGLEVEL_CONSTRUCT);
96 }
97
98 //////////
99 // archiving
100 //////////
101
102 /** Construct object from archive_node. */
103 matrix::matrix(const archive_node &n, const lst &sym_lst) : inherited(n, sym_lst)
104 {
105         debugmsg("matrix ctor from archive_node", LOGLEVEL_CONSTRUCT);
106         if (!(n.find_unsigned("row", row)) || !(n.find_unsigned("col", col)))
107                 throw (std::runtime_error("unknown matrix dimensions in archive"));
108         m.reserve(row * col);
109         for (unsigned int i=0; true; i++) {
110                 ex e;
111                 if (n.find_ex("m", e, sym_lst, i))
112                         m.push_back(e);
113                 else
114                         break;
115         }
116 }
117
118 /** Unarchive the object. */
119 ex matrix::unarchive(const archive_node &n, const lst &sym_lst)
120 {
121         return (new matrix(n, sym_lst))->setflag(status_flags::dynallocated);
122 }
123
124 /** Archive the object. */
125 void matrix::archive(archive_node &n) const
126 {
127         inherited::archive(n);
128         n.add_unsigned("row", row);
129         n.add_unsigned("col", col);
130         exvector::const_iterator i = m.begin(), iend = m.end();
131         while (i != iend) {
132                 n.add_ex("m", *i);
133                 ++i;
134         }
135 }
136
137 //////////
138 // functions overriding virtual functions from bases classes
139 //////////
140
141 // public
142
143 void matrix::print(std::ostream & os, unsigned upper_precedence) const
144 {
145         debugmsg("matrix print",LOGLEVEL_PRINT);
146         os << "[[ ";
147         for (unsigned r=0; r<row-1; ++r) {
148                 os << "[[";
149                 for (unsigned c=0; c<col-1; ++c)
150                         os << m[r*col+c] << ",";
151                 os << m[col*(r+1)-1] << "]], ";
152         }
153         os << "[[";
154         for (unsigned c=0; c<col-1; ++c)
155                 os << m[(row-1)*col+c] << ",";
156         os << m[row*col-1] << "]] ]]";
157 }
158
159 void matrix::printraw(std::ostream & os) const
160 {
161         debugmsg("matrix printraw",LOGLEVEL_PRINT);
162         os << class_name() << "(" << row << "," << col <<",";
163         for (unsigned r=0; r<row-1; ++r) {
164                 os << "(";
165                 for (unsigned c=0; c<col-1; ++c)
166                         os << m[r*col+c] << ",";
167                 os << m[col*(r-1)-1] << "),";
168         }
169         os << "(";
170         for (unsigned c=0; c<col-1; ++c)
171                 os << m[(row-1)*col+c] << ",";
172         os << m[row*col-1] << "))";
173 }
174
175 /** nops is defined to be rows x columns. */
176 unsigned matrix::nops() const
177 {
178         return row*col;
179 }
180
181 /** returns matrix entry at position (i/col, i%col). */
182 ex matrix::op(int i) const
183 {
184         return m[i];
185 }
186
187 /** returns matrix entry at position (i/col, i%col). */
188 ex & matrix::let_op(int i)
189 {
190         GINAC_ASSERT(i>=0);
191         GINAC_ASSERT(i<nops());
192         
193         return m[i];
194 }
195
196 /** expands the elements of a matrix entry by entry. */
197 ex matrix::expand(unsigned options) const
198 {
199         exvector tmp(row*col);
200         for (unsigned i=0; i<row*col; ++i)
201                 tmp[i] = m[i].expand(options);
202         
203         return matrix(row, col, tmp);
204 }
205
206 /** Search ocurrences.  A matrix 'has' an expression if it is the expression
207  *  itself or one of the elements 'has' it. */
208 bool matrix::has(const ex & other) const
209 {
210         GINAC_ASSERT(other.bp!=0);
211         
212         // tautology: it is the expression itself
213         if (is_equal(*other.bp)) return true;
214         
215         // search all the elements
216         for (exvector::const_iterator r=m.begin(); r!=m.end(); ++r)
217                 if ((*r).has(other)) return true;
218         
219         return false;
220 }
221
222 /** Evaluate matrix entry by entry. */
223 ex matrix::eval(int level) const
224 {
225         debugmsg("matrix eval",LOGLEVEL_MEMBER_FUNCTION);
226         
227         // check if we have to do anything at all
228         if ((level==1)&&(flags & status_flags::evaluated))
229                 return *this;
230         
231         // emergency break
232         if (level == -max_recursion_level)
233                 throw (std::runtime_error("matrix::eval(): recursion limit exceeded"));
234         
235         // eval() entry by entry
236         exvector m2(row*col);
237         --level;
238         for (unsigned r=0; r<row; ++r)
239                 for (unsigned c=0; c<col; ++c)
240                         m2[r*col+c] = m[r*col+c].eval(level);
241         
242         return (new matrix(row, col, m2))->setflag(status_flags::dynallocated |
243                                                                                            status_flags::evaluated );
244 }
245
246 /** Evaluate matrix numerically entry by entry. */
247 ex matrix::evalf(int level) const
248 {
249         debugmsg("matrix evalf",LOGLEVEL_MEMBER_FUNCTION);
250                 
251         // check if we have to do anything at all
252         if (level==1)
253                 return *this;
254         
255         // emergency break
256         if (level == -max_recursion_level) {
257                 throw (std::runtime_error("matrix::evalf(): recursion limit exceeded"));
258         }
259         
260         // evalf() entry by entry
261         exvector m2(row*col);
262         --level;
263         for (unsigned r=0; r<row; ++r)
264                 for (unsigned c=0; c<col; ++c)
265                         m2[r*col+c] = m[r*col+c].evalf(level);
266         
267         return matrix(row, col, m2);
268 }
269
270 ex matrix::subs(const lst & ls, const lst & lr) const
271 {
272         exvector m2(row * col);
273         for (unsigned r=0; r<row; ++r)
274                 for (unsigned c=0; c<col; ++c)
275                         m2[r*col+c] = m[r*col+c].subs(ls, lr);
276
277         return matrix(row, col, m2);
278 }
279
280 // protected
281
282 int matrix::compare_same_type(const basic & other) const
283 {
284         GINAC_ASSERT(is_exactly_of_type(other, matrix));
285         const matrix & o = static_cast<matrix &>(const_cast<basic &>(other));
286         
287         // compare number of rows
288         if (row != o.rows())
289                 return row < o.rows() ? -1 : 1;
290         
291         // compare number of columns
292         if (col != o.cols())
293                 return col < o.cols() ? -1 : 1;
294         
295         // equal number of rows and columns, compare individual elements
296         int cmpval;
297         for (unsigned r=0; r<row; ++r) {
298                 for (unsigned c=0; c<col; ++c) {
299                         cmpval = ((*this)(r,c)).compare(o(r,c));
300                         if (cmpval!=0) return cmpval;
301                 }
302         }
303         // all elements are equal => matrices are equal;
304         return 0;
305 }
306
307 /** Automatic symbolic evaluation of an indexed matrix. */
308 ex matrix::eval_indexed(const basic & i) const
309 {
310         GINAC_ASSERT(is_of_type(i, indexed));
311         GINAC_ASSERT(is_ex_of_type(i.op(0), matrix));
312
313         bool all_indices_unsigned = static_cast<const indexed &>(i).all_index_values_are(info_flags::nonnegint);
314
315         // Check indices
316         if (i.nops() == 2) {
317
318                 // One index, must be one-dimensional vector
319                 if (row != 1 && col != 1)
320                         throw (std::runtime_error("matrix::eval_indexed(): vector must have exactly 1 index"));
321
322                 const idx & i1 = ex_to_idx(i.op(1));
323
324                 if (col == 1) {
325
326                         // Column vector
327                         if (!i1.get_dim().is_equal(row))
328                                 throw (std::runtime_error("matrix::eval_indexed(): dimension of index must match number of vector elements"));
329
330                         // Index numeric -> return vector element
331                         if (all_indices_unsigned) {
332                                 unsigned n1 = ex_to_numeric(i1.get_value()).to_int();
333                                 if (n1 >= row)
334                                         throw (std::runtime_error("matrix::eval_indexed(): value of index exceeds number of vector elements"));
335                                 return (*this)(n1, 0);
336                         }
337
338                 } else {
339
340                         // Row vector
341                         if (!i1.get_dim().is_equal(col))
342                                 throw (std::runtime_error("matrix::eval_indexed(): dimension of index must match number of vector elements"));
343
344                         // Index numeric -> return vector element
345                         if (all_indices_unsigned) {
346                                 unsigned n1 = ex_to_numeric(i1.get_value()).to_int();
347                                 if (n1 >= col)
348                                         throw (std::runtime_error("matrix::eval_indexed(): value of index exceeds number of vector elements"));
349                                 return (*this)(0, n1);
350                         }
351                 }
352
353         } else if (i.nops() == 3) {
354
355                 // Two indices
356                 const idx & i1 = ex_to_idx(i.op(1));
357                 const idx & i2 = ex_to_idx(i.op(2));
358
359                 if (!i1.get_dim().is_equal(row))
360                         throw (std::runtime_error("matrix::eval_indexed(): dimension of first index must match number of rows"));
361                 if (!i2.get_dim().is_equal(col))
362                         throw (std::runtime_error("matrix::eval_indexed(): dimension of second index must match number of columns"));
363
364                 // Pair of dummy indices -> compute trace
365                 if (is_dummy_pair(i1, i2))
366                         return trace();
367
368                 // Both indices numeric -> return matrix element
369                 if (all_indices_unsigned) {
370                         unsigned n1 = ex_to_numeric(i1.get_value()).to_int(), n2 = ex_to_numeric(i2.get_value()).to_int();
371                         if (n1 >= row)
372                                 throw (std::runtime_error("matrix::eval_indexed(): value of first index exceeds number of rows"));
373                         if (n2 >= col)
374                                 throw (std::runtime_error("matrix::eval_indexed(): value of second index exceeds number of columns"));
375                         return (*this)(n1, n2);
376                 }
377
378         } else
379                 throw (std::runtime_error("matrix::eval_indexed(): matrix must have exactly 2 indices"));
380
381         return i.hold();
382 }
383
384 /** Sum of two indexed matrices. */
385 ex matrix::add_indexed(const ex & self, const ex & other) const
386 {
387         GINAC_ASSERT(is_ex_of_type(self, indexed));
388         GINAC_ASSERT(is_ex_of_type(other, indexed));
389         GINAC_ASSERT(self.nops() == 2 || self.nops() == 3);
390
391         // Only add two matrices
392         if (is_ex_of_type(other.op(0), matrix)) {
393                 GINAC_ASSERT(other.nops() == 2 || other.nops() == 3);
394
395                 const matrix &self_matrix = ex_to_matrix(self.op(0));
396                 const matrix &other_matrix = ex_to_matrix(other.op(0));
397
398                 if (self.nops() == 2 && other.nops() == 2) { // vector + vector
399
400                         if (self_matrix.row == other_matrix.row)
401                                 return indexed(self_matrix.add(other_matrix), self.op(1));
402                         else if (self_matrix.row == other_matrix.col)
403                                 return indexed(self_matrix.add(other_matrix.transpose()), self.op(1));
404
405                 } else if (self.nops() == 3 && other.nops() == 3) { // matrix + matrix
406
407                         if (self.op(1).is_equal(other.op(1)) && self.op(2).is_equal(other.op(2)))
408                                 return indexed(self_matrix.add(other_matrix), self.op(1), self.op(2));
409                         else if (self.op(1).is_equal(other.op(2)) && self.op(2).is_equal(other.op(1)))
410                                 return indexed(self_matrix.add(other_matrix.transpose()), self.op(1), self.op(2));
411
412                 }
413         }
414
415         // Don't know what to do, return unevaluated sum
416         return self + other;
417 }
418
419 /** Contraction of an indexed matrix with something else. */
420 bool matrix::contract_with(exvector::iterator self, exvector::iterator other, exvector & v) const
421 {
422         GINAC_ASSERT(is_ex_of_type(*self, indexed));
423         GINAC_ASSERT(is_ex_of_type(*other, indexed));
424         GINAC_ASSERT(self->nops() == 2 || self->nops() == 3);
425         GINAC_ASSERT(is_ex_of_type(self->op(0), matrix));
426
427         // Only contract with other matrices
428         if (!is_ex_of_type(other->op(0), matrix))
429                 return false;
430
431         GINAC_ASSERT(other->nops() == 2 || other->nops() == 3);
432
433         const matrix &self_matrix = ex_to_matrix(self->op(0));
434         const matrix &other_matrix = ex_to_matrix(other->op(0));
435
436         if (self->nops() == 2) {
437                 unsigned self_dim = (self_matrix.col == 1) ? self_matrix.row : self_matrix.col;
438
439                 if (other->nops() == 2) { // vector * vector (scalar product)
440                         unsigned other_dim = (other_matrix.col == 1) ? other_matrix.row : other_matrix.col;
441
442                         if (self_matrix.col == 1) {
443                                 if (other_matrix.col == 1) {
444                                         // Column vector * column vector, transpose first vector
445                                         *self = self_matrix.transpose().mul(other_matrix)(0, 0);
446                                 } else {
447                                         // Column vector * row vector, swap factors
448                                         *self = other_matrix.mul(self_matrix)(0, 0);
449                                 }
450                         } else {
451                                 if (other_matrix.col == 1) {
452                                         // Row vector * column vector, perfect
453                                         *self = self_matrix.mul(other_matrix)(0, 0);
454                                 } else {
455                                         // Row vector * row vector, transpose second vector
456                                         *self = self_matrix.mul(other_matrix.transpose())(0, 0);
457                                 }
458                         }
459                         *other = _ex1();
460                         return true;
461
462                 } else { // vector * matrix
463
464                         // B_i * A_ij = (B*A)_j (B is row vector)
465                         if (is_dummy_pair(self->op(1), other->op(1))) {
466                                 if (self_matrix.row == 1)
467                                         *self = indexed(self_matrix.mul(other_matrix), other->op(2));
468                                 else
469                                         *self = indexed(self_matrix.transpose().mul(other_matrix), other->op(2));
470                                 *other = _ex1();
471                                 return true;
472                         }
473
474                         // B_j * A_ij = (A*B)_i (B is column vector)
475                         if (is_dummy_pair(self->op(1), other->op(2))) {
476                                 if (self_matrix.col == 1)
477                                         *self = indexed(other_matrix.mul(self_matrix), other->op(1));
478                                 else
479                                         *self = indexed(other_matrix.mul(self_matrix.transpose()), other->op(1));
480                                 *other = _ex1();
481                                 return true;
482                         }
483                 }
484
485         } else if (other->nops() == 3) { // matrix * matrix
486
487                 // A_ij * B_jk = (A*B)_ik
488                 if (is_dummy_pair(self->op(2), other->op(1))) {
489                         *self = indexed(self_matrix.mul(other_matrix), self->op(1), other->op(2));
490                         *other = _ex1();
491                         return true;
492                 }
493
494                 // A_ij * B_kj = (A*Btrans)_ik
495                 if (is_dummy_pair(self->op(2), other->op(2))) {
496                         *self = indexed(self_matrix.mul(other_matrix.transpose()), self->op(1), other->op(1));
497                         *other = _ex1();
498                         return true;
499                 }
500
501                 // A_ji * B_jk = (Atrans*B)_ik
502                 if (is_dummy_pair(self->op(1), other->op(1))) {
503                         *self = indexed(self_matrix.transpose().mul(other_matrix), self->op(2), other->op(2));
504                         *other = _ex1();
505                         return true;
506                 }
507
508                 // A_ji * B_kj = (B*A)_ki
509                 if (is_dummy_pair(self->op(1), other->op(2))) {
510                         *self = indexed(other_matrix.mul(self_matrix), other->op(1), self->op(2));
511                         *other = _ex1();
512                         return true;
513                 }
514         }
515
516         return false;
517 }
518
519
520 //////////
521 // non-virtual functions in this class
522 //////////
523
524 // public
525
526 /** Sum of matrices.
527  *
528  *  @exception logic_error (incompatible matrices) */
529 matrix matrix::add(const matrix & other) const
530 {
531         if (col != other.col || row != other.row)
532                 throw (std::logic_error("matrix::add(): incompatible matrices"));
533         
534         exvector sum(this->m);
535         exvector::iterator i;
536         exvector::const_iterator ci;
537         for (i=sum.begin(), ci=other.m.begin(); i!=sum.end(); ++i, ++ci)
538                 (*i) += (*ci);
539         
540         return matrix(row,col,sum);
541 }
542
543
544 /** Difference of matrices.
545  *
546  *  @exception logic_error (incompatible matrices) */
547 matrix matrix::sub(const matrix & other) const
548 {
549         if (col != other.col || row != other.row)
550                 throw (std::logic_error("matrix::sub(): incompatible matrices"));
551         
552         exvector dif(this->m);
553         exvector::iterator i;
554         exvector::const_iterator ci;
555         for (i=dif.begin(), ci=other.m.begin(); i!=dif.end(); ++i, ++ci)
556                 (*i) -= (*ci);
557         
558         return matrix(row,col,dif);
559 }
560
561
562 /** Product of matrices.
563  *
564  *  @exception logic_error (incompatible matrices) */
565 matrix matrix::mul(const matrix & other) const
566 {
567         if (this->cols() != other.rows())
568                 throw (std::logic_error("matrix::mul(): incompatible matrices"));
569         
570         exvector prod(this->rows()*other.cols());
571         
572         for (unsigned r1=0; r1<this->rows(); ++r1) {
573                 for (unsigned c=0; c<this->cols(); ++c) {
574                         if (m[r1*col+c].is_zero())
575                                 continue;
576                         for (unsigned r2=0; r2<other.cols(); ++r2)
577                                 prod[r1*other.col+r2] += (m[r1*col+c] * other.m[c*other.col+r2]).expand();
578                 }
579         }
580         return matrix(row, other.col, prod);
581 }
582
583
584 /** operator() to access elements.
585  *
586  *  @param ro row of element
587  *  @param co column of element
588  *  @exception range_error (index out of range) */
589 const ex & matrix::operator() (unsigned ro, unsigned co) const
590 {
591         if (ro>=row || co>=col)
592                 throw (std::range_error("matrix::operator(): index out of range"));
593
594         return m[ro*col+co];
595 }
596
597
598 /** Set individual elements manually.
599  *
600  *  @exception range_error (index out of range) */
601 matrix & matrix::set(unsigned ro, unsigned co, ex value)
602 {
603         if (ro>=row || co>=col)
604                 throw (std::range_error("matrix::set(): index out of range"));
605     
606         ensure_if_modifiable();
607         m[ro*col+co] = value;
608         return *this;
609 }
610
611
612 /** Transposed of an m x n matrix, producing a new n x m matrix object that
613  *  represents the transposed. */
614 matrix matrix::transpose(void) const
615 {
616         exvector trans(this->cols()*this->rows());
617         
618         for (unsigned r=0; r<this->cols(); ++r)
619                 for (unsigned c=0; c<this->rows(); ++c)
620                         trans[r*this->rows()+c] = m[c*this->cols()+r];
621         
622         return matrix(this->cols(),this->rows(),trans);
623 }
624
625
626 /** Determinant of square matrix.  This routine doesn't actually calculate the
627  *  determinant, it only implements some heuristics about which algorithm to
628  *  run.  If all the elements of the matrix are elements of an integral domain
629  *  the determinant is also in that integral domain and the result is expanded
630  *  only.  If one or more elements are from a quotient field the determinant is
631  *  usually also in that quotient field and the result is normalized before it
632  *  is returned.  This implies that the determinant of the symbolic 2x2 matrix
633  *  [[a/(a-b),1],[b/(a-b),1]] is returned as unity.  (In this respect, it
634  *  behaves like MapleV and unlike Mathematica.)
635  *
636  *  @param     algo allows to chose an algorithm
637  *  @return    the determinant as a new expression
638  *  @exception logic_error (matrix not square)
639  *  @see       determinant_algo */
640 ex matrix::determinant(unsigned algo) const
641 {
642         if (row!=col)
643                 throw (std::logic_error("matrix::determinant(): matrix not square"));
644         GINAC_ASSERT(row*col==m.capacity());
645         
646         // Gather some statistical information about this matrix:
647         bool numeric_flag = true;
648         bool normal_flag = false;
649         unsigned sparse_count = 0;  // counts non-zero elements
650         for (exvector::const_iterator r=m.begin(); r!=m.end(); ++r) {
651                 lst srl;  // symbol replacement list
652                 ex rtest = (*r).to_rational(srl);
653                 if (!rtest.is_zero())
654                         ++sparse_count;
655                 if (!rtest.info(info_flags::numeric))
656                         numeric_flag = false;
657                 if (!rtest.info(info_flags::crational_polynomial) &&
658                          rtest.info(info_flags::rational_function))
659                         normal_flag = true;
660         }
661         
662         // Here is the heuristics in case this routine has to decide:
663         if (algo == determinant_algo::automatic) {
664                 // Minor expansion is generally a good guess:
665                 algo = determinant_algo::laplace;
666                 // Does anybody know when a matrix is really sparse?
667                 // Maybe <~row/2.236 nonzero elements average in a row?
668                 if (row>3 && 5*sparse_count<=row*col)
669                         algo = determinant_algo::bareiss;
670                 // Purely numeric matrix can be handled by Gauss elimination.
671                 // This overrides any prior decisions.
672                 if (numeric_flag)
673                         algo = determinant_algo::gauss;
674         }
675         
676         // Trap the trivial case here, since some algorithms don't like it
677         if (this->row==1) {
678                 // for consistency with non-trivial determinants...
679                 if (normal_flag)
680                         return m[0].normal();
681                 else
682                         return m[0].expand();
683         }
684         
685         // Compute the determinant
686         switch(algo) {
687                 case determinant_algo::gauss: {
688                         ex det = 1;
689                         matrix tmp(*this);
690                         int sign = tmp.gauss_elimination(true);
691                         for (unsigned d=0; d<row; ++d)
692                                 det *= tmp.m[d*col+d];
693                         if (normal_flag)
694                                 return (sign*det).normal();
695                         else
696                                 return (sign*det).normal().expand();
697                 }
698                 case determinant_algo::bareiss: {
699                         matrix tmp(*this);
700                         int sign;
701                         sign = tmp.fraction_free_elimination(true);
702                         if (normal_flag)
703                                 return (sign*tmp.m[row*col-1]).normal();
704                         else
705                                 return (sign*tmp.m[row*col-1]).expand();
706                 }
707                 case determinant_algo::divfree: {
708                         matrix tmp(*this);
709                         int sign;
710                         sign = tmp.division_free_elimination(true);
711                         if (sign==0)
712                                 return _ex0();
713                         ex det = tmp.m[row*col-1];
714                         // factor out accumulated bogus slag
715                         for (unsigned d=0; d<row-2; ++d)
716                                 for (unsigned j=0; j<row-d-2; ++j)
717                                         det = (det/tmp.m[d*col+d]).normal();
718                         return (sign*det);
719                 }
720                 case determinant_algo::laplace:
721                 default: {
722                         // This is the minor expansion scheme.  We always develop such
723                         // that the smallest minors (i.e, the trivial 1x1 ones) are on the
724                         // rightmost column.  For this to be efficient it turns out that
725                         // the emptiest columns (i.e. the ones with most zeros) should be
726                         // the ones on the right hand side.  Therefore we presort the
727                         // columns of the matrix:
728                         typedef std::pair<unsigned,unsigned> uintpair;
729                         std::vector<uintpair> c_zeros;  // number of zeros in column
730                         for (unsigned c=0; c<col; ++c) {
731                                 unsigned acc = 0;
732                                 for (unsigned r=0; r<row; ++r)
733                                         if (m[r*col+c].is_zero())
734                                                 ++acc;
735                                 c_zeros.push_back(uintpair(acc,c));
736                         }
737                         sort(c_zeros.begin(),c_zeros.end());
738                         std::vector<unsigned> pre_sort;
739                         for (std::vector<uintpair>::iterator i=c_zeros.begin(); i!=c_zeros.end(); ++i)
740                                 pre_sort.push_back(i->second);
741                         int sign = permutation_sign(pre_sort);
742                         exvector result(row*col);  // represents sorted matrix
743                         unsigned c = 0;
744                         for (std::vector<unsigned>::iterator i=pre_sort.begin();
745                                  i!=pre_sort.end();
746                                  ++i,++c) {
747                                 for (unsigned r=0; r<row; ++r)
748                                         result[r*col+c] = m[r*col+(*i)];
749                         }
750                         
751                         if (normal_flag)
752                                 return (sign*matrix(row,col,result).determinant_minor()).normal();
753                         else
754                                 return sign*matrix(row,col,result).determinant_minor();
755                 }
756         }
757 }
758
759
760 /** Trace of a matrix.  The result is normalized if it is in some quotient
761  *  field and expanded only otherwise.  This implies that the trace of the
762  *  symbolic 2x2 matrix [[a/(a-b),x],[y,b/(b-a)]] is recognized to be unity.
763  *
764  *  @return    the sum of diagonal elements
765  *  @exception logic_error (matrix not square) */
766 ex matrix::trace(void) const
767 {
768         if (row != col)
769                 throw (std::logic_error("matrix::trace(): matrix not square"));
770         
771         ex tr;
772         for (unsigned r=0; r<col; ++r)
773                 tr += m[r*col+r];
774         
775         if (tr.info(info_flags::rational_function) &&
776                 !tr.info(info_flags::crational_polynomial))
777                 return tr.normal();
778         else
779                 return tr.expand();
780 }
781
782
783 /** Characteristic Polynomial.  Following mathematica notation the
784  *  characteristic polynomial of a matrix M is defined as the determiant of
785  *  (M - lambda * 1) where 1 stands for the unit matrix of the same dimension
786  *  as M.  Note that some CASs define it with a sign inside the determinant
787  *  which gives rise to an overall sign if the dimension is odd.  This method
788  *  returns the characteristic polynomial collected in powers of lambda as a
789  *  new expression.
790  *
791  *  @return    characteristic polynomial as new expression
792  *  @exception logic_error (matrix not square)
793  *  @see       matrix::determinant() */
794 ex matrix::charpoly(const symbol & lambda) const
795 {
796         if (row != col)
797                 throw (std::logic_error("matrix::charpoly(): matrix not square"));
798         
799         bool numeric_flag = true;
800         for (exvector::const_iterator r=m.begin(); r!=m.end(); ++r) {
801                 if (!(*r).info(info_flags::numeric)) {
802                         numeric_flag = false;
803                 }
804         }
805         
806         // The pure numeric case is traditionally rather common.  Hence, it is
807         // trapped and we use Leverrier's algorithm which goes as row^3 for
808         // every coefficient.  The expensive part is the matrix multiplication.
809         if (numeric_flag) {
810                 matrix B(*this);
811                 ex c = B.trace();
812                 ex poly = power(lambda,row)-c*power(lambda,row-1);
813                 for (unsigned i=1; i<row; ++i) {
814                         for (unsigned j=0; j<row; ++j)
815                                 B.m[j*col+j] -= c;
816                         B = this->mul(B);
817                         c = B.trace()/ex(i+1);
818                         poly -= c*power(lambda,row-i-1);
819                 }
820                 if (row%2)
821                         return -poly;
822                 else
823                         return poly;
824         }
825         
826         matrix M(*this);
827         for (unsigned r=0; r<col; ++r)
828                 M.m[r*col+r] -= lambda;
829         
830         return M.determinant().collect(lambda);
831 }
832
833
834 /** Inverse of this matrix.
835  *
836  *  @return    the inverted matrix
837  *  @exception logic_error (matrix not square)
838  *  @exception runtime_error (singular matrix) */
839 matrix matrix::inverse(void) const
840 {
841         if (row != col)
842                 throw (std::logic_error("matrix::inverse(): matrix not square"));
843         
844         // NOTE: the Gauss-Jordan elimination used here can in principle be
845         // replaced by two clever calls to gauss_elimination() and some to
846         // transpose().  Wouldn't be more efficient (maybe less?), just more
847         // orthogonal.
848         matrix tmp(row,col);
849         // set tmp to the unit matrix
850         for (unsigned i=0; i<col; ++i)
851                 tmp.m[i*col+i] = _ex1();
852         
853         // create a copy of this matrix
854         matrix cpy(*this);
855         for (unsigned r1=0; r1<row; ++r1) {
856                 int indx = cpy.pivot(r1, r1);
857                 if (indx == -1) {
858                         throw (std::runtime_error("matrix::inverse(): singular matrix"));
859                 }
860                 if (indx != 0) {  // swap rows r and indx of matrix tmp
861                         for (unsigned i=0; i<col; ++i)
862                                 tmp.m[r1*col+i].swap(tmp.m[indx*col+i]);
863                 }
864                 ex a1 = cpy.m[r1*col+r1];
865                 for (unsigned c=0; c<col; ++c) {
866                         cpy.m[r1*col+c] /= a1;
867                         tmp.m[r1*col+c] /= a1;
868                 }
869                 for (unsigned r2=0; r2<row; ++r2) {
870                         if (r2 != r1) {
871                                 if (!cpy.m[r2*col+r1].is_zero()) {
872                                         ex a2 = cpy.m[r2*col+r1];
873                                         // yes, there is something to do in this column
874                                         for (unsigned c=0; c<col; ++c) {
875                                                 cpy.m[r2*col+c] -= a2 * cpy.m[r1*col+c];
876                                                 if (!cpy.m[r2*col+c].info(info_flags::numeric))
877                                                         cpy.m[r2*col+c] = cpy.m[r2*col+c].normal();
878                                                 tmp.m[r2*col+c] -= a2 * tmp.m[r1*col+c];
879                                                 if (!tmp.m[r2*col+c].info(info_flags::numeric))
880                                                         tmp.m[r2*col+c] = tmp.m[r2*col+c].normal();
881                                         }
882                                 }
883                         }
884                 }
885         }
886         
887         return tmp;
888 }
889
890
891 /** Solve a linear system consisting of a m x n matrix and a m x p right hand
892  *  side by applying an elimination scheme to the augmented matrix.
893  *
894  *  @param vars n x p matrix, all elements must be symbols 
895  *  @param rhs m x p matrix
896  *  @return n x p solution matrix
897  *  @exception logic_error (incompatible matrices)
898  *  @exception invalid_argument (1st argument must be matrix of symbols)
899  *  @exception runtime_error (inconsistent linear system)
900  *  @see       solve_algo */
901 matrix matrix::solve(const matrix & vars,
902                                          const matrix & rhs,
903                                          unsigned algo) const
904 {
905         const unsigned m = this->rows();
906         const unsigned n = this->cols();
907         const unsigned p = rhs.cols();
908         
909         // syntax checks    
910         if ((rhs.rows() != m) || (vars.rows() != n) || (vars.col != p))
911                 throw (std::logic_error("matrix::solve(): incompatible matrices"));
912         for (unsigned ro=0; ro<n; ++ro)
913                 for (unsigned co=0; co<p; ++co)
914                         if (!vars(ro,co).info(info_flags::symbol))
915                                 throw (std::invalid_argument("matrix::solve(): 1st argument must be matrix of symbols"));
916         
917         // build the augmented matrix of *this with rhs attached to the right
918         matrix aug(m,n+p);
919         for (unsigned r=0; r<m; ++r) {
920                 for (unsigned c=0; c<n; ++c)
921                         aug.m[r*(n+p)+c] = this->m[r*n+c];
922                 for (unsigned c=0; c<p; ++c)
923                         aug.m[r*(n+p)+c+n] = rhs.m[r*p+c];
924         }
925         
926         // Gather some statistical information about the augmented matrix:
927         bool numeric_flag = true;
928         for (exvector::const_iterator r=aug.m.begin(); r!=aug.m.end(); ++r) {
929                 if (!(*r).info(info_flags::numeric))
930                         numeric_flag = false;
931         }
932         
933         // Here is the heuristics in case this routine has to decide:
934         if (algo == solve_algo::automatic) {
935                 // Bareiss (fraction-free) elimination is generally a good guess:
936                 algo = solve_algo::bareiss;
937                 // For m<3, Bareiss elimination is equivalent to division free
938                 // elimination but has more logistic overhead
939                 if (m<3)
940                         algo = solve_algo::divfree;
941                 // This overrides any prior decisions.
942                 if (numeric_flag)
943                         algo = solve_algo::gauss;
944         }
945         
946         // Eliminate the augmented matrix:
947         switch(algo) {
948                 case solve_algo::gauss:
949                         aug.gauss_elimination();
950                 case solve_algo::divfree:
951                         aug.division_free_elimination();
952                 case solve_algo::bareiss:
953                 default:
954                         aug.fraction_free_elimination();
955         }
956         
957         // assemble the solution matrix:
958         matrix sol(n,p);
959         for (unsigned co=0; co<p; ++co) {
960                 unsigned last_assigned_sol = n+1;
961                 for (int r=m-1; r>=0; --r) {
962                         unsigned fnz = 1;    // first non-zero in row
963                         while ((fnz<=n) && (aug.m[r*(n+p)+(fnz-1)].is_zero()))
964                                 ++fnz;
965                         if (fnz>n) {
966                                 // row consists only of zeros, corresponding rhs must be 0, too
967                                 if (!aug.m[r*(n+p)+n+co].is_zero()) {
968                                         throw (std::runtime_error("matrix::solve(): inconsistent linear system"));
969                                 }
970                         } else {
971                                 // assign solutions for vars between fnz+1 and
972                                 // last_assigned_sol-1: free parameters
973                                 for (unsigned c=fnz; c<last_assigned_sol-1; ++c)
974                                         sol.set(c,co,vars.m[c*p+co]);
975                                 ex e = aug.m[r*(n+p)+n+co];
976                                 for (unsigned c=fnz; c<n; ++c)
977                                         e -= aug.m[r*(n+p)+c]*sol.m[c*p+co];
978                                 sol.set(fnz-1,co,
979                                                 (e/(aug.m[r*(n+p)+(fnz-1)])).normal());
980                                 last_assigned_sol = fnz;
981                         }
982                 }
983                 // assign solutions for vars between 1 and
984                 // last_assigned_sol-1: free parameters
985                 for (unsigned ro=0; ro<last_assigned_sol-1; ++ro)
986                         sol.set(ro,co,vars(ro,co));
987         }
988         
989         return sol;
990 }
991
992
993 // protected
994
995 /** Recursive determinant for small matrices having at least one symbolic
996  *  entry.  The basic algorithm, known as Laplace-expansion, is enhanced by
997  *  some bookkeeping to avoid calculation of the same submatrices ("minors")
998  *  more than once.  According to W.M.Gentleman and S.C.Johnson this algorithm
999  *  is better than elimination schemes for matrices of sparse multivariate
1000  *  polynomials and also for matrices of dense univariate polynomials if the
1001  *  matrix' dimesion is larger than 7.
1002  *
1003  *  @return the determinant as a new expression (in expanded form)
1004  *  @see matrix::determinant() */
1005 ex matrix::determinant_minor(void) const
1006 {
1007         // for small matrices the algorithm does not make any sense:
1008         const unsigned n = this->cols();
1009         if (n==1)
1010                 return m[0].expand();
1011         if (n==2)
1012                 return (m[0]*m[3]-m[2]*m[1]).expand();
1013         if (n==3)
1014                 return (m[0]*m[4]*m[8]-m[0]*m[5]*m[7]-
1015                         m[1]*m[3]*m[8]+m[2]*m[3]*m[7]+
1016                         m[1]*m[5]*m[6]-m[2]*m[4]*m[6]).expand();
1017         
1018         // This algorithm can best be understood by looking at a naive
1019         // implementation of Laplace-expansion, like this one:
1020         // ex det;
1021         // matrix minorM(this->rows()-1,this->cols()-1);
1022         // for (unsigned r1=0; r1<this->rows(); ++r1) {
1023         //     // shortcut if element(r1,0) vanishes
1024         //     if (m[r1*col].is_zero())
1025         //         continue;
1026         //     // assemble the minor matrix
1027         //     for (unsigned r=0; r<minorM.rows(); ++r) {
1028         //         for (unsigned c=0; c<minorM.cols(); ++c) {
1029         //             if (r<r1)
1030         //                 minorM.set(r,c,m[r*col+c+1]);
1031         //             else
1032         //                 minorM.set(r,c,m[(r+1)*col+c+1]);
1033         //         }
1034         //     }
1035         //     // recurse down and care for sign:
1036         //     if (r1%2)
1037         //         det -= m[r1*col] * minorM.determinant_minor();
1038         //     else
1039         //         det += m[r1*col] * minorM.determinant_minor();
1040         // }
1041         // return det.expand();
1042         // What happens is that while proceeding down many of the minors are
1043         // computed more than once.  In particular, there are binomial(n,k)
1044         // kxk minors and each one is computed factorial(n-k) times.  Therefore
1045         // it is reasonable to store the results of the minors.  We proceed from
1046         // right to left.  At each column c we only need to retrieve the minors
1047         // calculated in step c-1.  We therefore only have to store at most 
1048         // 2*binomial(n,n/2) minors.
1049         
1050         // Unique flipper counter for partitioning into minors
1051         std::vector<unsigned> Pkey;
1052         Pkey.reserve(n);
1053         // key for minor determinant (a subpartition of Pkey)
1054         std::vector<unsigned> Mkey;
1055         Mkey.reserve(n-1);
1056         // we store our subminors in maps, keys being the rows they arise from
1057         typedef std::map<std::vector<unsigned>,class ex> Rmap;
1058         typedef std::map<std::vector<unsigned>,class ex>::value_type Rmap_value;
1059         Rmap A;
1060         Rmap B;
1061         ex det;
1062         // initialize A with last column:
1063         for (unsigned r=0; r<n; ++r) {
1064                 Pkey.erase(Pkey.begin(),Pkey.end());
1065                 Pkey.push_back(r);
1066                 A.insert(Rmap_value(Pkey,m[n*(r+1)-1]));
1067         }
1068         // proceed from right to left through matrix
1069         for (int c=n-2; c>=0; --c) {
1070                 Pkey.erase(Pkey.begin(),Pkey.end());  // don't change capacity
1071                 Mkey.erase(Mkey.begin(),Mkey.end());
1072                 for (unsigned i=0; i<n-c; ++i)
1073                         Pkey.push_back(i);
1074                 unsigned fc = 0;  // controls logic for our strange flipper counter
1075                 do {
1076                         det = _ex0();
1077                         for (unsigned r=0; r<n-c; ++r) {
1078                                 // maybe there is nothing to do?
1079                                 if (m[Pkey[r]*n+c].is_zero())
1080                                         continue;
1081                                 // create the sorted key for all possible minors
1082                                 Mkey.erase(Mkey.begin(),Mkey.end());
1083                                 for (unsigned i=0; i<n-c; ++i)
1084                                         if (i!=r)
1085                                                 Mkey.push_back(Pkey[i]);
1086                                 // Fetch the minors and compute the new determinant
1087                                 if (r%2)
1088                                         det -= m[Pkey[r]*n+c]*A[Mkey];
1089                                 else
1090                                         det += m[Pkey[r]*n+c]*A[Mkey];
1091                         }
1092                         // prevent build-up of deep nesting of expressions saves time:
1093                         det = det.expand();
1094                         // store the new determinant at its place in B:
1095                         if (!det.is_zero())
1096                                 B.insert(Rmap_value(Pkey,det));
1097                         // increment our strange flipper counter
1098                         for (fc=n-c; fc>0; --fc) {
1099                                 ++Pkey[fc-1];
1100                                 if (Pkey[fc-1]<fc+c)
1101                                         break;
1102                         }
1103                         if (fc<n-c && fc>0)
1104                                 for (unsigned j=fc; j<n-c; ++j)
1105                                         Pkey[j] = Pkey[j-1]+1;
1106                 } while(fc);
1107                 // next column, so change the role of A and B:
1108                 A = B;
1109                 B.clear();
1110         }
1111         
1112         return det;
1113 }
1114
1115
1116 /** Perform the steps of an ordinary Gaussian elimination to bring the m x n
1117  *  matrix into an upper echelon form.  The algorithm is ok for matrices
1118  *  with numeric coefficients but quite unsuited for symbolic matrices.
1119  *
1120  *  @param det may be set to true to save a lot of space if one is only
1121  *  interested in the diagonal elements (i.e. for calculating determinants).
1122  *  The others are set to zero in this case.
1123  *  @return sign is 1 if an even number of rows was swapped, -1 if an odd
1124  *  number of rows was swapped and 0 if the matrix is singular. */
1125 int matrix::gauss_elimination(const bool det)
1126 {
1127         ensure_if_modifiable();
1128         const unsigned m = this->rows();
1129         const unsigned n = this->cols();
1130         GINAC_ASSERT(!det || n==m);
1131         int sign = 1;
1132         
1133         unsigned r0 = 0;
1134         for (unsigned r1=0; (r1<n-1)&&(r0<m-1); ++r1) {
1135                 int indx = pivot(r0, r1, true);
1136                 if (indx == -1) {
1137                         sign = 0;
1138                         if (det)
1139                                 return 0;  // leaves *this in a messy state
1140                 }
1141                 if (indx>=0) {
1142                         if (indx > 0)
1143                                 sign = -sign;
1144                         for (unsigned r2=r0+1; r2<m; ++r2) {
1145                                 if (!this->m[r2*n+r1].is_zero()) {
1146                                         // yes, there is something to do in this row
1147                                         ex piv = this->m[r2*n+r1] / this->m[r0*n+r1];
1148                                         for (unsigned c=r1+1; c<n; ++c) {
1149                                                 this->m[r2*n+c] -= piv * this->m[r0*n+c];
1150                                                 if (!this->m[r2*n+c].info(info_flags::numeric))
1151                                                         this->m[r2*n+c] = this->m[r2*n+c].normal();
1152                                         }
1153                                 }
1154                                 // fill up left hand side with zeros
1155                                 for (unsigned c=0; c<=r1; ++c)
1156                                         this->m[r2*n+c] = _ex0();
1157                         }
1158                         if (det) {
1159                                 // save space by deleting no longer needed elements
1160                                 for (unsigned c=r0+1; c<n; ++c)
1161                                         this->m[r0*n+c] = _ex0();
1162                         }
1163                         ++r0;
1164                 }
1165         }
1166         
1167         return sign;
1168 }
1169
1170
1171 /** Perform the steps of division free elimination to bring the m x n matrix
1172  *  into an upper echelon form.
1173  *
1174  *  @param det may be set to true to save a lot of space if one is only
1175  *  interested in the diagonal elements (i.e. for calculating determinants).
1176  *  The others are set to zero in this case.
1177  *  @return sign is 1 if an even number of rows was swapped, -1 if an odd
1178  *  number of rows was swapped and 0 if the matrix is singular. */
1179 int matrix::division_free_elimination(const bool det)
1180 {
1181         ensure_if_modifiable();
1182         const unsigned m = this->rows();
1183         const unsigned n = this->cols();
1184         GINAC_ASSERT(!det || n==m);
1185         int sign = 1;
1186         
1187         unsigned r0 = 0;
1188         for (unsigned r1=0; (r1<n-1)&&(r0<m-1); ++r1) {
1189                 int indx = pivot(r0, r1, true);
1190                 if (indx==-1) {
1191                         sign = 0;
1192                         if (det)
1193                                 return 0;  // leaves *this in a messy state
1194                 }
1195                 if (indx>=0) {
1196                         if (indx>0)
1197                                 sign = -sign;
1198                         for (unsigned r2=r0+1; r2<m; ++r2) {
1199                                 for (unsigned c=r1+1; c<n; ++c)
1200                                         this->m[r2*n+c] = (this->m[r0*n+r1]*this->m[r2*n+c] - this->m[r2*n+r1]*this->m[r0*n+c]).expand();
1201                                 // fill up left hand side with zeros
1202                                 for (unsigned c=0; c<=r1; ++c)
1203                                         this->m[r2*n+c] = _ex0();
1204                         }
1205                         if (det) {
1206                                 // save space by deleting no longer needed elements
1207                                 for (unsigned c=r0+1; c<n; ++c)
1208                                         this->m[r0*n+c] = _ex0();
1209                         }
1210                         ++r0;
1211                 }
1212         }
1213         
1214         return sign;
1215 }
1216
1217
1218 /** Perform the steps of Bareiss' one-step fraction free elimination to bring
1219  *  the matrix into an upper echelon form.  Fraction free elimination means
1220  *  that divide is used straightforwardly, without computing GCDs first.  This
1221  *  is possible, since we know the divisor at each step.
1222  *  
1223  *  @param det may be set to true to save a lot of space if one is only
1224  *  interested in the last element (i.e. for calculating determinants). The
1225  *  others are set to zero in this case.
1226  *  @return sign is 1 if an even number of rows was swapped, -1 if an odd
1227  *  number of rows was swapped and 0 if the matrix is singular. */
1228 int matrix::fraction_free_elimination(const bool det)
1229 {
1230         // Method:
1231         // (single-step fraction free elimination scheme, already known to Jordan)
1232         //
1233         // Usual division-free elimination sets m[0](r,c) = m(r,c) and then sets
1234         //     m[k+1](r,c) = m[k](k,k) * m[k](r,c) - m[k](r,k) * m[k](k,c).
1235         //
1236         // Bareiss (fraction-free) elimination in addition divides that element
1237         // by m[k-1](k-1,k-1) for k>1, where it can be shown by means of the
1238         // Sylvester determinant that this really divides m[k+1](r,c).
1239         //
1240         // We also allow rational functions where the original prove still holds.
1241         // However, we must care for numerator and denominator separately and
1242         // "manually" work in the integral domains because of subtle cancellations
1243         // (see below).  This blows up the bookkeeping a bit and the formula has
1244         // to be modified to expand like this (N{x} stands for numerator of x,
1245         // D{x} for denominator of x):
1246         //     N{m[k+1](r,c)} = N{m[k](k,k)}*N{m[k](r,c)}*D{m[k](r,k)}*D{m[k](k,c)}
1247         //                     -N{m[k](r,k)}*N{m[k](k,c)}*D{m[k](k,k)}*D{m[k](r,c)}
1248         //     D{m[k+1](r,c)} = D{m[k](k,k)}*D{m[k](r,c)}*D{m[k](r,k)}*D{m[k](k,c)}
1249         // where for k>1 we now divide N{m[k+1](r,c)} by
1250         //     N{m[k-1](k-1,k-1)}
1251         // and D{m[k+1](r,c)} by
1252         //     D{m[k-1](k-1,k-1)}.
1253         
1254         ensure_if_modifiable();
1255         const unsigned m = this->rows();
1256         const unsigned n = this->cols();
1257         GINAC_ASSERT(!det || n==m);
1258         int sign = 1;
1259         if (m==1)
1260                 return 1;
1261         ex divisor_n = 1;
1262         ex divisor_d = 1;
1263         ex dividend_n;
1264         ex dividend_d;
1265         
1266         // We populate temporary matrices to subsequently operate on.  There is
1267         // one holding numerators and another holding denominators of entries.
1268         // This is a must since the evaluator (or even earlier mul's constructor)
1269         // might cancel some trivial element which causes divide() to fail.  The
1270         // elements are normalized first (yes, even though this algorithm doesn't
1271         // need GCDs) since the elements of *this might be unnormalized, which
1272         // makes things more complicated than they need to be.
1273         matrix tmp_n(*this);
1274         matrix tmp_d(m,n);  // for denominators, if needed
1275         lst srl;  // symbol replacement list
1276         exvector::iterator it = this->m.begin();
1277         exvector::iterator tmp_n_it = tmp_n.m.begin();
1278         exvector::iterator tmp_d_it = tmp_d.m.begin();
1279         for (; it!= this->m.end(); ++it, ++tmp_n_it, ++tmp_d_it) {
1280                 (*tmp_n_it) = (*it).normal().to_rational(srl);
1281                 (*tmp_d_it) = (*tmp_n_it).denom();
1282                 (*tmp_n_it) = (*tmp_n_it).numer();
1283         }
1284         
1285         unsigned r0 = 0;
1286         for (unsigned r1=0; (r1<n-1)&&(r0<m-1); ++r1) {
1287                 int indx = tmp_n.pivot(r0, r1, true);
1288                 if (indx==-1) {
1289                         sign = 0;
1290                         if (det)
1291                                 return 0;
1292                 }
1293                 if (indx>=0) {
1294                         if (indx>0) {
1295                                 sign = -sign;
1296                                 // tmp_n's rows r0 and indx were swapped, do the same in tmp_d:
1297                                 for (unsigned c=r1; c<n; ++c)
1298                                         tmp_d.m[n*indx+c].swap(tmp_d.m[n*r0+c]);
1299                         }
1300                         for (unsigned r2=r0+1; r2<m; ++r2) {
1301                                 for (unsigned c=r1+1; c<n; ++c) {
1302                                         dividend_n = (tmp_n.m[r0*n+r1]*tmp_n.m[r2*n+c]*
1303                                                       tmp_d.m[r2*n+r1]*tmp_d.m[r0*n+c]
1304                                                      -tmp_n.m[r2*n+r1]*tmp_n.m[r0*n+c]*
1305                                                       tmp_d.m[r0*n+r1]*tmp_d.m[r2*n+c]).expand();
1306                                         dividend_d = (tmp_d.m[r2*n+r1]*tmp_d.m[r0*n+c]*
1307                                                       tmp_d.m[r0*n+r1]*tmp_d.m[r2*n+c]).expand();
1308                                         bool check = divide(dividend_n, divisor_n,
1309                                                             tmp_n.m[r2*n+c], true);
1310                                         check &= divide(dividend_d, divisor_d,
1311                                                         tmp_d.m[r2*n+c], true);
1312                                         GINAC_ASSERT(check);
1313                                 }
1314                                 // fill up left hand side with zeros
1315                                 for (unsigned c=0; c<=r1; ++c)
1316                                         tmp_n.m[r2*n+c] = _ex0();
1317                         }
1318                         if ((r1<n-1)&&(r0<m-1)) {
1319                                 // compute next iteration's divisor
1320                                 divisor_n = tmp_n.m[r0*n+r1].expand();
1321                                 divisor_d = tmp_d.m[r0*n+r1].expand();
1322                                 if (det) {
1323                                         // save space by deleting no longer needed elements
1324                                         for (unsigned c=0; c<n; ++c) {
1325                                                 tmp_n.m[r0*n+c] = _ex0();
1326                                                 tmp_d.m[r0*n+c] = _ex1();
1327                                         }
1328                                 }
1329                         }
1330                         ++r0;
1331                 }
1332         }
1333         // repopulate *this matrix:
1334         it = this->m.begin();
1335         tmp_n_it = tmp_n.m.begin();
1336         tmp_d_it = tmp_d.m.begin();
1337         for (; it!= this->m.end(); ++it, ++tmp_n_it, ++tmp_d_it)
1338                 (*it) = ((*tmp_n_it)/(*tmp_d_it)).subs(srl);
1339         
1340         return sign;
1341 }
1342
1343
1344 /** Partial pivoting method for matrix elimination schemes.
1345  *  Usual pivoting (symbolic==false) returns the index to the element with the
1346  *  largest absolute value in column ro and swaps the current row with the one
1347  *  where the element was found.  With (symbolic==true) it does the same thing
1348  *  with the first non-zero element.
1349  *
1350  *  @param ro is the row from where to begin
1351  *  @param co is the column to be inspected
1352  *  @param symbolic signal if we want the first non-zero element to be pivoted
1353  *  (true) or the one with the largest absolute value (false).
1354  *  @return 0 if no interchange occured, -1 if all are zero (usually signaling
1355  *  a degeneracy) and positive integer k means that rows ro and k were swapped.
1356  */
1357 int matrix::pivot(unsigned ro, unsigned co, bool symbolic)
1358 {
1359         unsigned k = ro;
1360         if (symbolic) {
1361                 // search first non-zero element in column co beginning at row ro
1362                 while ((k<row) && (this->m[k*col+co].expand().is_zero()))
1363                         ++k;
1364         } else {
1365                 // search largest element in column co beginning at row ro
1366                 GINAC_ASSERT(is_ex_of_type(this->m[k*col+co],numeric));
1367                 unsigned kmax = k+1;
1368                 numeric mmax = abs(ex_to_numeric(m[kmax*col+co]));
1369                 while (kmax<row) {
1370                         GINAC_ASSERT(is_ex_of_type(this->m[kmax*col+co],numeric));
1371                         numeric tmp = ex_to_numeric(this->m[kmax*col+co]);
1372                         if (abs(tmp) > mmax) {
1373                                 mmax = tmp;
1374                                 k = kmax;
1375                         }
1376                         ++kmax;
1377                 }
1378                 if (!mmax.is_zero())
1379                         k = kmax;
1380         }
1381         if (k==row)
1382                 // all elements in column co below row ro vanish
1383                 return -1;
1384         if (k==ro)
1385                 // matrix needs no pivoting
1386                 return 0;
1387         // matrix needs pivoting, so swap rows k and ro
1388         ensure_if_modifiable();
1389         for (unsigned c=0; c<col; ++c)
1390                 this->m[k*col+c].swap(this->m[ro*col+c]);
1391         
1392         return k;
1393 }
1394
1395 /** Convert list of lists to matrix. */
1396 ex lst_to_matrix(const ex &l)
1397 {
1398         if (!is_ex_of_type(l, lst))
1399                 throw(std::invalid_argument("argument to lst_to_matrix() must be a lst"));
1400         
1401         // Find number of rows and columns
1402         unsigned rows = l.nops(), cols = 0, i, j;
1403         for (i=0; i<rows; i++)
1404                 if (l.op(i).nops() > cols)
1405                         cols = l.op(i).nops();
1406         
1407         // Allocate and fill matrix
1408         matrix &m = *new matrix(rows, cols);
1409         for (i=0; i<rows; i++)
1410                 for (j=0; j<cols; j++)
1411                         if (l.op(i).nops() > j)
1412                                 m.set(i, j, l.op(i).op(j));
1413                         else
1414                                 m.set(i, j, ex(0));
1415         return m;
1416 }
1417
1418 } // namespace GiNaC