]> www.ginac.de Git - ginac.git/blob - ginac/matrix.cpp
81d31bdb9e8739a5d073a2e20ddbb95e58f25c3f
[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 "utils.h"
32 #include "debugmsg.h"
33 #include "power.h"
34 #include "symbol.h"
35 #include "normal.h"
36
37 #ifndef NO_NAMESPACE_GINAC
38 namespace GiNaC {
39 #endif // ndef NO_NAMESPACE_GINAC
40
41 GINAC_IMPLEMENT_REGISTERED_CLASS(matrix, basic)
42
43 //////////
44 // default constructor, destructor, copy constructor, assignment operator
45 // and helpers:
46 //////////
47
48 // public
49
50 /** Default ctor.  Initializes to 1 x 1-dimensional zero-matrix. */
51 matrix::matrix() : inherited(TINFO_matrix), row(1), col(1)
52 {
53         debugmsg("matrix default constructor",LOGLEVEL_CONSTRUCT);
54         m.push_back(_ex0());
55 }
56
57 // protected
58
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 constructors
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 constructor 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 constructor 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 constructor 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 << "matrix(" << 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 // protected
271
272 int matrix::compare_same_type(const basic & other) const
273 {
274         GINAC_ASSERT(is_exactly_of_type(other, matrix));
275         const matrix & o = static_cast<matrix &>(const_cast<basic &>(other));
276         
277         // compare number of rows
278         if (row != o.rows())
279                 return row < o.rows() ? -1 : 1;
280         
281         // compare number of columns
282         if (col != o.cols())
283                 return col < o.cols() ? -1 : 1;
284         
285         // equal number of rows and columns, compare individual elements
286         int cmpval;
287         for (unsigned r=0; r<row; ++r) {
288                 for (unsigned c=0; c<col; ++c) {
289                         cmpval = ((*this)(r,c)).compare(o(r,c));
290                         if (cmpval!=0) return cmpval;
291                 }
292         }
293         // all elements are equal => matrices are equal;
294         return 0;
295 }
296
297 //////////
298 // non-virtual functions in this class
299 //////////
300
301 // public
302
303 /** Sum of matrices.
304  *
305  *  @exception logic_error (incompatible matrices) */
306 matrix matrix::add(const matrix & other) const
307 {
308         if (col != other.col || row != other.row)
309                 throw (std::logic_error("matrix::add(): incompatible matrices"));
310         
311         exvector sum(this->m);
312         exvector::iterator i;
313         exvector::const_iterator ci;
314         for (i=sum.begin(), ci=other.m.begin(); i!=sum.end(); ++i, ++ci)
315                 (*i) += (*ci);
316         
317         return matrix(row,col,sum);
318 }
319
320
321 /** Difference of matrices.
322  *
323  *  @exception logic_error (incompatible matrices) */
324 matrix matrix::sub(const matrix & other) const
325 {
326         if (col != other.col || row != other.row)
327                 throw (std::logic_error("matrix::sub(): incompatible matrices"));
328         
329         exvector dif(this->m);
330         exvector::iterator i;
331         exvector::const_iterator ci;
332         for (i=dif.begin(), ci=other.m.begin(); i!=dif.end(); ++i, ++ci)
333                 (*i) -= (*ci);
334         
335         return matrix(row,col,dif);
336 }
337
338
339 /** Product of matrices.
340  *
341  *  @exception logic_error (incompatible matrices) */
342 matrix matrix::mul(const matrix & other) const
343 {
344         if (this->cols() != other.rows())
345                 throw (std::logic_error("matrix::mul(): incompatible matrices"));
346         
347         exvector prod(this->rows()*other.cols());
348         
349         for (unsigned r1=0; r1<this->rows(); ++r1) {
350                 for (unsigned c=0; c<this->cols(); ++c) {
351                         if (m[r1*col+c].is_zero())
352                                 continue;
353                         for (unsigned r2=0; r2<other.cols(); ++r2)
354                                 prod[r1*other.col+r2] += (m[r1*col+c] * other.m[c*other.col+r2]).expand();
355                 }
356         }
357         return matrix(row, other.col, prod);
358 }
359
360
361 /** operator() to access elements.
362  *
363  *  @param ro row of element
364  *  @param co column of element
365  *  @exception range_error (index out of range) */
366 const ex & matrix::operator() (unsigned ro, unsigned co) const
367 {
368         if (ro>=row || co>=col)
369                 throw (std::range_error("matrix::operator(): index out of range"));
370
371         return m[ro*col+co];
372 }
373
374
375 /** Set individual elements manually.
376  *
377  *  @exception range_error (index out of range) */
378 matrix & matrix::set(unsigned ro, unsigned co, ex value)
379 {
380         if (ro>=row || co>=col)
381                 throw (std::range_error("matrix::set(): index out of range"));
382     
383         ensure_if_modifiable();
384         m[ro*col+co] = value;
385         return *this;
386 }
387
388
389 /** Transposed of an m x n matrix, producing a new n x m matrix object that
390  *  represents the transposed. */
391 matrix matrix::transpose(void) const
392 {
393         exvector trans(this->cols()*this->rows());
394         
395         for (unsigned r=0; r<this->cols(); ++r)
396                 for (unsigned c=0; c<this->rows(); ++c)
397                         trans[r*this->rows()+c] = m[c*this->cols()+r];
398         
399         return matrix(this->cols(),this->rows(),trans);
400 }
401
402
403 /** Determinant of square matrix.  This routine doesn't actually calculate the
404  *  determinant, it only implements some heuristics about which algorithm to
405  *  run.  If all the elements of the matrix are elements of an integral domain
406  *  the determinant is also in that integral domain and the result is expanded
407  *  only.  If one or more elements are from a quotient field the determinant is
408  *  usually also in that quotient field and the result is normalized before it
409  *  is returned.  This implies that the determinant of the symbolic 2x2 matrix
410  *  [[a/(a-b),1],[b/(a-b),1]] is returned as unity.  (In this respect, it
411  *  behaves like MapleV and unlike Mathematica.)
412  *
413  *  @param     algo allows to chose an algorithm
414  *  @return    the determinant as a new expression
415  *  @exception logic_error (matrix not square)
416  *  @see       determinant_algo */
417 ex matrix::determinant(unsigned algo) const
418 {
419         if (row!=col)
420                 throw (std::logic_error("matrix::determinant(): matrix not square"));
421         GINAC_ASSERT(row*col==m.capacity());
422         
423         // Gather some statistical information about this matrix:
424         bool numeric_flag = true;
425         bool normal_flag = false;
426         unsigned sparse_count = 0;  // counts non-zero elements
427         for (exvector::const_iterator r=m.begin(); r!=m.end(); ++r) {
428                 lst srl;  // symbol replacement list
429                 ex rtest = (*r).to_rational(srl);
430                 if (!rtest.is_zero())
431                         ++sparse_count;
432                 if (!rtest.info(info_flags::numeric))
433                         numeric_flag = false;
434                 if (!rtest.info(info_flags::crational_polynomial) &&
435                          rtest.info(info_flags::rational_function))
436                         normal_flag = true;
437         }
438         
439         // Here is the heuristics in case this routine has to decide:
440         if (algo == determinant_algo::automatic) {
441                 // Minor expansion is generally a good guess:
442                 algo = determinant_algo::laplace;
443                 // Does anybody know when a matrix is really sparse?
444                 // Maybe <~row/2.236 nonzero elements average in a row?
445                 if (row>3 && 5*sparse_count<=row*col)
446                         algo = determinant_algo::bareiss;
447                 // Purely numeric matrix can be handled by Gauss elimination.
448                 // This overrides any prior decisions.
449                 if (numeric_flag)
450                         algo = determinant_algo::gauss;
451         }
452         
453         // Trap the trivial case here, since some algorithms don't like it
454         if (this->row==1) {
455                 // for consistency with non-trivial determinants...
456                 if (normal_flag)
457                         return m[0].normal();
458                 else
459                         return m[0].expand();
460         }
461         
462         // Compute the determinant
463         switch(algo) {
464                 case determinant_algo::gauss: {
465                         ex det = 1;
466                         matrix tmp(*this);
467                         int sign = tmp.gauss_elimination(true);
468                         for (unsigned d=0; d<row; ++d)
469                                 det *= tmp.m[d*col+d];
470                         if (normal_flag)
471                                 return (sign*det).normal();
472                         else
473                                 return (sign*det).normal().expand();
474                 }
475                 case determinant_algo::bareiss: {
476                         matrix tmp(*this);
477                         int sign;
478                         sign = tmp.fraction_free_elimination(true);
479                         if (normal_flag)
480                                 return (sign*tmp.m[row*col-1]).normal();
481                         else
482                                 return (sign*tmp.m[row*col-1]).expand();
483                 }
484                 case determinant_algo::divfree: {
485                         matrix tmp(*this);
486                         int sign;
487                         sign = tmp.division_free_elimination(true);
488                         if (sign==0)
489                                 return _ex0();
490                         ex det = tmp.m[row*col-1];
491                         // factor out accumulated bogus slag
492                         for (unsigned d=0; d<row-2; ++d)
493                                 for (unsigned j=0; j<row-d-2; ++j)
494                                         det = (det/tmp.m[d*col+d]).normal();
495                         return (sign*det);
496                 }
497                 case determinant_algo::laplace:
498                 default: {
499                         // This is the minor expansion scheme.  We always develop such
500                         // that the smallest minors (i.e, the trivial 1x1 ones) are on the
501                         // rightmost column.  For this to be efficient it turns out that
502                         // the emptiest columns (i.e. the ones with most zeros) should be
503                         // the ones on the right hand side.  Therefore we presort the
504                         // columns of the matrix:
505                         typedef std::pair<unsigned,unsigned> uintpair;
506                         std::vector<uintpair> c_zeros;  // number of zeros in column
507                         for (unsigned c=0; c<col; ++c) {
508                                 unsigned acc = 0;
509                                 for (unsigned r=0; r<row; ++r)
510                                         if (m[r*col+c].is_zero())
511                                                 ++acc;
512                                 c_zeros.push_back(uintpair(acc,c));
513                         }
514                         sort(c_zeros.begin(),c_zeros.end());
515                         std::vector<unsigned> pre_sort;
516                         for (std::vector<uintpair>::iterator i=c_zeros.begin(); i!=c_zeros.end(); ++i)
517                                 pre_sort.push_back(i->second);
518                         int sign = permutation_sign(pre_sort);
519                         exvector result(row*col);  // represents sorted matrix
520                         unsigned c = 0;
521                         for (std::vector<unsigned>::iterator i=pre_sort.begin();
522                                  i!=pre_sort.end();
523                                  ++i,++c) {
524                                 for (unsigned r=0; r<row; ++r)
525                                         result[r*col+c] = m[r*col+(*i)];
526                         }
527                         
528                         if (normal_flag)
529                                 return (sign*matrix(row,col,result).determinant_minor()).normal();
530                         else
531                                 return sign*matrix(row,col,result).determinant_minor();
532                 }
533         }
534 }
535
536
537 /** Trace of a matrix.  The result is normalized if it is in some quotient
538  *  field and expanded only otherwise.  This implies that the trace of the
539  *  symbolic 2x2 matrix [[a/(a-b),x],[y,b/(b-a)]] is recognized to be unity.
540  *
541  *  @return    the sum of diagonal elements
542  *  @exception logic_error (matrix not square) */
543 ex matrix::trace(void) const
544 {
545         if (row != col)
546                 throw (std::logic_error("matrix::trace(): matrix not square"));
547         
548         ex tr;
549         for (unsigned r=0; r<col; ++r)
550                 tr += m[r*col+r];
551         
552         if (tr.info(info_flags::rational_function) &&
553                 !tr.info(info_flags::crational_polynomial))
554                 return tr.normal();
555         else
556                 return tr.expand();
557 }
558
559
560 /** Characteristic Polynomial.  Following mathematica notation the
561  *  characteristic polynomial of a matrix M is defined as the determiant of
562  *  (M - lambda * 1) where 1 stands for the unit matrix of the same dimension
563  *  as M.  Note that some CASs define it with a sign inside the determinant
564  *  which gives rise to an overall sign if the dimension is odd.  This method
565  *  returns the characteristic polynomial collected in powers of lambda as a
566  *  new expression.
567  *
568  *  @return    characteristic polynomial as new expression
569  *  @exception logic_error (matrix not square)
570  *  @see       matrix::determinant() */
571 ex matrix::charpoly(const symbol & lambda) const
572 {
573         if (row != col)
574                 throw (std::logic_error("matrix::charpoly(): matrix not square"));
575         
576         bool numeric_flag = true;
577         for (exvector::const_iterator r=m.begin(); r!=m.end(); ++r) {
578                 if (!(*r).info(info_flags::numeric)) {
579                         numeric_flag = false;
580                 }
581         }
582         
583         // The pure numeric case is traditionally rather common.  Hence, it is
584         // trapped and we use Leverrier's algorithm which goes as row^3 for
585         // every coefficient.  The expensive part is the matrix multiplication.
586         if (numeric_flag) {
587                 matrix B(*this);
588                 ex c = B.trace();
589                 ex poly = power(lambda,row)-c*power(lambda,row-1);
590                 for (unsigned i=1; i<row; ++i) {
591                         for (unsigned j=0; j<row; ++j)
592                                 B.m[j*col+j] -= c;
593                         B = this->mul(B);
594                         c = B.trace()/ex(i+1);
595                         poly -= c*power(lambda,row-i-1);
596                 }
597                 if (row%2)
598                         return -poly;
599                 else
600                         return poly;
601         }
602         
603         matrix M(*this);
604         for (unsigned r=0; r<col; ++r)
605                 M.m[r*col+r] -= lambda;
606         
607         return M.determinant().collect(lambda);
608 }
609
610
611 /** Inverse of this matrix.
612  *
613  *  @return    the inverted matrix
614  *  @exception logic_error (matrix not square)
615  *  @exception runtime_error (singular matrix) */
616 matrix matrix::inverse(void) const
617 {
618         if (row != col)
619                 throw (std::logic_error("matrix::inverse(): matrix not square"));
620         
621         // NOTE: the Gauss-Jordan elimination used here can in principle be
622         // replaced by two clever calls to gauss_elimination() and some to
623         // transpose().  Wouldn't be more efficient (maybe less?), just more
624         // orthogonal.
625         matrix tmp(row,col);
626         // set tmp to the unit matrix
627         for (unsigned i=0; i<col; ++i)
628                 tmp.m[i*col+i] = _ex1();
629         
630         // create a copy of this matrix
631         matrix cpy(*this);
632         for (unsigned r1=0; r1<row; ++r1) {
633                 int indx = cpy.pivot(r1, r1);
634                 if (indx == -1) {
635                         throw (std::runtime_error("matrix::inverse(): singular matrix"));
636                 }
637                 if (indx != 0) {  // swap rows r and indx of matrix tmp
638                         for (unsigned i=0; i<col; ++i)
639                                 tmp.m[r1*col+i].swap(tmp.m[indx*col+i]);
640                 }
641                 ex a1 = cpy.m[r1*col+r1];
642                 for (unsigned c=0; c<col; ++c) {
643                         cpy.m[r1*col+c] /= a1;
644                         tmp.m[r1*col+c] /= a1;
645                 }
646                 for (unsigned r2=0; r2<row; ++r2) {
647                         if (r2 != r1) {
648                                 if (!cpy.m[r2*col+r1].is_zero()) {
649                                         ex a2 = cpy.m[r2*col+r1];
650                                         // yes, there is something to do in this column
651                                         for (unsigned c=0; c<col; ++c) {
652                                                 cpy.m[r2*col+c] -= a2 * cpy.m[r1*col+c];
653                                                 if (!cpy.m[r2*col+c].info(info_flags::numeric))
654                                                         cpy.m[r2*col+c] = cpy.m[r2*col+c].normal();
655                                                 tmp.m[r2*col+c] -= a2 * tmp.m[r1*col+c];
656                                                 if (!tmp.m[r2*col+c].info(info_flags::numeric))
657                                                         tmp.m[r2*col+c] = tmp.m[r2*col+c].normal();
658                                         }
659                                 }
660                         }
661                 }
662         }
663         
664         return tmp;
665 }
666
667
668 /** Solve a linear system consisting of a m x n matrix and a m x p right hand
669  *  side by applying an elimination scheme to the augmented matrix.
670  *
671  *  @param vars n x p matrix, all elements must be symbols 
672  *  @param rhs m x p matrix
673  *  @return n x p solution matrix
674  *  @exception logic_error (incompatible matrices)
675  *  @exception invalid_argument (1st argument must be matrix of symbols)
676  *  @exception runtime_error (inconsistent linear system)
677  *  @see       solve_algo */
678 matrix matrix::solve(const matrix & vars,
679                                          const matrix & rhs,
680                                          unsigned algo) const
681 {
682         const unsigned m = this->rows();
683         const unsigned n = this->cols();
684         const unsigned p = rhs.cols();
685         
686         // syntax checks    
687         if ((rhs.rows() != m) || (vars.rows() != n) || (vars.col != p))
688                 throw (std::logic_error("matrix::solve(): incompatible matrices"));
689         for (unsigned ro=0; ro<n; ++ro)
690                 for (unsigned co=0; co<p; ++co)
691                         if (!vars(ro,co).info(info_flags::symbol))
692                                 throw (std::invalid_argument("matrix::solve(): 1st argument must be matrix of symbols"));
693         
694         // build the augmented matrix of *this with rhs attached to the right
695         matrix aug(m,n+p);
696         for (unsigned r=0; r<m; ++r) {
697                 for (unsigned c=0; c<n; ++c)
698                         aug.m[r*(n+p)+c] = this->m[r*n+c];
699                 for (unsigned c=0; c<p; ++c)
700                         aug.m[r*(n+p)+c+n] = rhs.m[r*p+c];
701         }
702         
703         // Gather some statistical information about the augmented matrix:
704         bool numeric_flag = true;
705         for (exvector::const_iterator r=aug.m.begin(); r!=aug.m.end(); ++r) {
706                 if (!(*r).info(info_flags::numeric))
707                         numeric_flag = false;
708         }
709         
710         // Here is the heuristics in case this routine has to decide:
711         if (algo == solve_algo::automatic) {
712                 // Bareiss (fraction-free) elimination is generally a good guess:
713                 algo = solve_algo::bareiss;
714                 // For m<3, Bareiss elimination is equivalent to division free
715                 // elimination but has more logistic overhead
716                 if (m<3)
717                         algo = solve_algo::divfree;
718                 // This overrides any prior decisions.
719                 if (numeric_flag)
720                         algo = solve_algo::gauss;
721         }
722         
723         // Eliminate the augmented matrix:
724         switch(algo) {
725                 case solve_algo::gauss:
726                         aug.gauss_elimination();
727                 case solve_algo::divfree:
728                         aug.division_free_elimination();
729                 case solve_algo::bareiss:
730                 default:
731                         aug.fraction_free_elimination();
732         }
733         
734         // assemble the solution matrix:
735         matrix sol(n,p);
736         for (unsigned co=0; co<p; ++co) {
737                 unsigned last_assigned_sol = n+1;
738                 for (int r=m-1; r>=0; --r) {
739                         unsigned fnz = 1;    // first non-zero in row
740                         while ((fnz<=n) && (aug.m[r*(n+p)+(fnz-1)].is_zero()))
741                                 ++fnz;
742                         if (fnz>n) {
743                                 // row consists only of zeros, corresponding rhs must be 0, too
744                                 if (!aug.m[r*(n+p)+n+co].is_zero()) {
745                                         throw (std::runtime_error("matrix::solve(): inconsistent linear system"));
746                                 }
747                         } else {
748                                 // assign solutions for vars between fnz+1 and
749                                 // last_assigned_sol-1: free parameters
750                                 for (unsigned c=fnz; c<last_assigned_sol-1; ++c)
751                                         sol.set(c,co,vars.m[c*p+co]);
752                                 ex e = aug.m[r*(n+p)+n+co];
753                                 for (unsigned c=fnz; c<n; ++c)
754                                         e -= aug.m[r*(n+p)+c]*sol.m[c*p+co];
755                                 sol.set(fnz-1,co,
756                                                 (e/(aug.m[r*(n+p)+(fnz-1)])).normal());
757                                 last_assigned_sol = fnz;
758                         }
759                 }
760                 // assign solutions for vars between 1 and
761                 // last_assigned_sol-1: free parameters
762                 for (unsigned ro=0; ro<last_assigned_sol-1; ++ro)
763                         sol.set(ro,co,vars(ro,co));
764         }
765         
766         return sol;
767 }
768
769
770 // protected
771
772 /** Recursive determinant for small matrices having at least one symbolic
773  *  entry.  The basic algorithm, known as Laplace-expansion, is enhanced by
774  *  some bookkeeping to avoid calculation of the same submatrices ("minors")
775  *  more than once.  According to W.M.Gentleman and S.C.Johnson this algorithm
776  *  is better than elimination schemes for matrices of sparse multivariate
777  *  polynomials and also for matrices of dense univariate polynomials if the
778  *  matrix' dimesion is larger than 7.
779  *
780  *  @return the determinant as a new expression (in expanded form)
781  *  @see matrix::determinant() */
782 ex matrix::determinant_minor(void) const
783 {
784         // for small matrices the algorithm does not make any sense:
785         const unsigned n = this->cols();
786         if (n==1)
787                 return m[0].expand();
788         if (n==2)
789                 return (m[0]*m[3]-m[2]*m[1]).expand();
790         if (n==3)
791                 return (m[0]*m[4]*m[8]-m[0]*m[5]*m[7]-
792                         m[1]*m[3]*m[8]+m[2]*m[3]*m[7]+
793                         m[1]*m[5]*m[6]-m[2]*m[4]*m[6]).expand();
794         
795         // This algorithm can best be understood by looking at a naive
796         // implementation of Laplace-expansion, like this one:
797         // ex det;
798         // matrix minorM(this->rows()-1,this->cols()-1);
799         // for (unsigned r1=0; r1<this->rows(); ++r1) {
800         //     // shortcut if element(r1,0) vanishes
801         //     if (m[r1*col].is_zero())
802         //         continue;
803         //     // assemble the minor matrix
804         //     for (unsigned r=0; r<minorM.rows(); ++r) {
805         //         for (unsigned c=0; c<minorM.cols(); ++c) {
806         //             if (r<r1)
807         //                 minorM.set(r,c,m[r*col+c+1]);
808         //             else
809         //                 minorM.set(r,c,m[(r+1)*col+c+1]);
810         //         }
811         //     }
812         //     // recurse down and care for sign:
813         //     if (r1%2)
814         //         det -= m[r1*col] * minorM.determinant_minor();
815         //     else
816         //         det += m[r1*col] * minorM.determinant_minor();
817         // }
818         // return det.expand();
819         // What happens is that while proceeding down many of the minors are
820         // computed more than once.  In particular, there are binomial(n,k)
821         // kxk minors and each one is computed factorial(n-k) times.  Therefore
822         // it is reasonable to store the results of the minors.  We proceed from
823         // right to left.  At each column c we only need to retrieve the minors
824         // calculated in step c-1.  We therefore only have to store at most 
825         // 2*binomial(n,n/2) minors.
826         
827         // Unique flipper counter for partitioning into minors
828         std::vector<unsigned> Pkey;
829         Pkey.reserve(n);
830         // key for minor determinant (a subpartition of Pkey)
831         std::vector<unsigned> Mkey;
832         Mkey.reserve(n-1);
833         // we store our subminors in maps, keys being the rows they arise from
834         typedef std::map<std::vector<unsigned>,class ex> Rmap;
835         typedef std::map<std::vector<unsigned>,class ex>::value_type Rmap_value;
836         Rmap A;
837         Rmap B;
838         ex det;
839         // initialize A with last column:
840         for (unsigned r=0; r<n; ++r) {
841                 Pkey.erase(Pkey.begin(),Pkey.end());
842                 Pkey.push_back(r);
843                 A.insert(Rmap_value(Pkey,m[n*(r+1)-1]));
844         }
845         // proceed from right to left through matrix
846         for (int c=n-2; c>=0; --c) {
847                 Pkey.erase(Pkey.begin(),Pkey.end());  // don't change capacity
848                 Mkey.erase(Mkey.begin(),Mkey.end());
849                 for (unsigned i=0; i<n-c; ++i)
850                         Pkey.push_back(i);
851                 unsigned fc = 0;  // controls logic for our strange flipper counter
852                 do {
853                         det = _ex0();
854                         for (unsigned r=0; r<n-c; ++r) {
855                                 // maybe there is nothing to do?
856                                 if (m[Pkey[r]*n+c].is_zero())
857                                         continue;
858                                 // create the sorted key for all possible minors
859                                 Mkey.erase(Mkey.begin(),Mkey.end());
860                                 for (unsigned i=0; i<n-c; ++i)
861                                         if (i!=r)
862                                                 Mkey.push_back(Pkey[i]);
863                                 // Fetch the minors and compute the new determinant
864                                 if (r%2)
865                                         det -= m[Pkey[r]*n+c]*A[Mkey];
866                                 else
867                                         det += m[Pkey[r]*n+c]*A[Mkey];
868                         }
869                         // prevent build-up of deep nesting of expressions saves time:
870                         det = det.expand();
871                         // store the new determinant at its place in B:
872                         if (!det.is_zero())
873                                 B.insert(Rmap_value(Pkey,det));
874                         // increment our strange flipper counter
875                         for (fc=n-c; fc>0; --fc) {
876                                 ++Pkey[fc-1];
877                                 if (Pkey[fc-1]<fc+c)
878                                         break;
879                         }
880                         if (fc<n-c && fc>0)
881                                 for (unsigned j=fc; j<n-c; ++j)
882                                         Pkey[j] = Pkey[j-1]+1;
883                 } while(fc);
884                 // next column, so change the role of A and B:
885                 A = B;
886                 B.clear();
887         }
888         
889         return det;
890 }
891
892
893 /** Perform the steps of an ordinary Gaussian elimination to bring the m x n
894  *  matrix into an upper echelon form.  The algorithm is ok for matrices
895  *  with numeric coefficients but quite unsuited for symbolic matrices.
896  *
897  *  @param det may be set to true to save a lot of space if one is only
898  *  interested in the diagonal elements (i.e. for calculating determinants).
899  *  The others are set to zero in this case.
900  *  @return sign is 1 if an even number of rows was swapped, -1 if an odd
901  *  number of rows was swapped and 0 if the matrix is singular. */
902 int matrix::gauss_elimination(const bool det)
903 {
904         ensure_if_modifiable();
905         const unsigned m = this->rows();
906         const unsigned n = this->cols();
907         GINAC_ASSERT(!det || n==m);
908         int sign = 1;
909         
910         unsigned r0 = 0;
911         for (unsigned r1=0; (r1<n-1)&&(r0<m-1); ++r1) {
912                 int indx = pivot(r0, r1, true);
913                 if (indx == -1) {
914                         sign = 0;
915                         if (det)
916                                 return 0;  // leaves *this in a messy state
917                 }
918                 if (indx>=0) {
919                         if (indx > 0)
920                                 sign = -sign;
921                         for (unsigned r2=r0+1; r2<m; ++r2) {
922                                 if (!this->m[r2*n+r1].is_zero()) {
923                                         // yes, there is something to do in this row
924                                         ex piv = this->m[r2*n+r1] / this->m[r0*n+r1];
925                                         for (unsigned c=r1+1; c<n; ++c) {
926                                                 this->m[r2*n+c] -= piv * this->m[r0*n+c];
927                                                 if (!this->m[r2*n+c].info(info_flags::numeric))
928                                                         this->m[r2*n+c] = this->m[r2*n+c].normal();
929                                         }
930                                 }
931                                 // fill up left hand side with zeros
932                                 for (unsigned c=0; c<=r1; ++c)
933                                         this->m[r2*n+c] = _ex0();
934                         }
935                         if (det) {
936                                 // save space by deleting no longer needed elements
937                                 for (unsigned c=r0+1; c<n; ++c)
938                                         this->m[r0*n+c] = _ex0();
939                         }
940                         ++r0;
941                 }
942         }
943         
944         return sign;
945 }
946
947
948 /** Perform the steps of division free elimination to bring the m x n matrix
949  *  into an upper echelon form.
950  *
951  *  @param det may be set to true to save a lot of space if one is only
952  *  interested in the diagonal elements (i.e. for calculating determinants).
953  *  The others are set to zero in this case.
954  *  @return sign is 1 if an even number of rows was swapped, -1 if an odd
955  *  number of rows was swapped and 0 if the matrix is singular. */
956 int matrix::division_free_elimination(const bool det)
957 {
958         ensure_if_modifiable();
959         const unsigned m = this->rows();
960         const unsigned n = this->cols();
961         GINAC_ASSERT(!det || n==m);
962         int sign = 1;
963         
964         unsigned r0 = 0;
965         for (unsigned r1=0; (r1<n-1)&&(r0<m-1); ++r1) {
966                 int indx = pivot(r0, r1, true);
967                 if (indx==-1) {
968                         sign = 0;
969                         if (det)
970                                 return 0;  // leaves *this in a messy state
971                 }
972                 if (indx>=0) {
973                         if (indx>0)
974                                 sign = -sign;
975                         for (unsigned r2=r0+1; r2<m; ++r2) {
976                                 for (unsigned c=r1+1; c<n; ++c)
977                                         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();
978                                 // fill up left hand side with zeros
979                                 for (unsigned c=0; c<=r1; ++c)
980                                         this->m[r2*n+c] = _ex0();
981                         }
982                         if (det) {
983                                 // save space by deleting no longer needed elements
984                                 for (unsigned c=r0+1; c<n; ++c)
985                                         this->m[r0*n+c] = _ex0();
986                         }
987                         ++r0;
988                 }
989         }
990         
991         return sign;
992 }
993
994
995 /** Perform the steps of Bareiss' one-step fraction free elimination to bring
996  *  the matrix into an upper echelon form.  Fraction free elimination means
997  *  that divide is used straightforwardly, without computing GCDs first.  This
998  *  is possible, since we know the divisor at each step.
999  *  
1000  *  @param det may be set to true to save a lot of space if one is only
1001  *  interested in the last element (i.e. for calculating determinants). The
1002  *  others are set to zero in this case.
1003  *  @return sign is 1 if an even number of rows was swapped, -1 if an odd
1004  *  number of rows was swapped and 0 if the matrix is singular. */
1005 int matrix::fraction_free_elimination(const bool det)
1006 {
1007         // Method:
1008         // (single-step fraction free elimination scheme, already known to Jordan)
1009         //
1010         // Usual division-free elimination sets m[0](r,c) = m(r,c) and then sets
1011         //     m[k+1](r,c) = m[k](k,k) * m[k](r,c) - m[k](r,k) * m[k](k,c).
1012         //
1013         // Bareiss (fraction-free) elimination in addition divides that element
1014         // by m[k-1](k-1,k-1) for k>1, where it can be shown by means of the
1015         // Sylvester determinant that this really divides m[k+1](r,c).
1016         //
1017         // We also allow rational functions where the original prove still holds.
1018         // However, we must care for numerator and denominator separately and
1019         // "manually" work in the integral domains because of subtle cancellations
1020         // (see below).  This blows up the bookkeeping a bit and the formula has
1021         // to be modified to expand like this (N{x} stands for numerator of x,
1022         // D{x} for denominator of x):
1023         //     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)}
1024         //                     -N{m[k](r,k)}*N{m[k](k,c)}*D{m[k](k,k)}*D{m[k](r,c)}
1025         //     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)}
1026         // where for k>1 we now divide N{m[k+1](r,c)} by
1027         //     N{m[k-1](k-1,k-1)}
1028         // and D{m[k+1](r,c)} by
1029         //     D{m[k-1](k-1,k-1)}.
1030         
1031         ensure_if_modifiable();
1032         const unsigned m = this->rows();
1033         const unsigned n = this->cols();
1034         GINAC_ASSERT(!det || n==m);
1035         int sign = 1;
1036         if (m==1)
1037                 return 1;
1038         ex divisor_n = 1;
1039         ex divisor_d = 1;
1040         ex dividend_n;
1041         ex dividend_d;
1042         
1043         // We populate temporary matrices to subsequently operate on.  There is
1044         // one holding numerators and another holding denominators of entries.
1045         // This is a must since the evaluator (or even earlier mul's constructor)
1046         // might cancel some trivial element which causes divide() to fail.  The
1047         // elements are normalized first (yes, even though this algorithm doesn't
1048         // need GCDs) since the elements of *this might be unnormalized, which
1049         // makes things more complicated than they need to be.
1050         matrix tmp_n(*this);
1051         matrix tmp_d(m,n);  // for denominators, if needed
1052         lst srl;  // symbol replacement list
1053         exvector::iterator it = this->m.begin();
1054         exvector::iterator tmp_n_it = tmp_n.m.begin();
1055         exvector::iterator tmp_d_it = tmp_d.m.begin();
1056         for (; it!= this->m.end(); ++it, ++tmp_n_it, ++tmp_d_it) {
1057                 (*tmp_n_it) = (*it).normal().to_rational(srl);
1058                 (*tmp_d_it) = (*tmp_n_it).denom();
1059                 (*tmp_n_it) = (*tmp_n_it).numer();
1060         }
1061         
1062         unsigned r0 = 0;
1063         for (unsigned r1=0; (r1<n-1)&&(r0<m-1); ++r1) {
1064                 int indx = tmp_n.pivot(r0, r1, true);
1065                 if (indx==-1) {
1066                         sign = 0;
1067                         if (det)
1068                                 return 0;
1069                 }
1070                 if (indx>=0) {
1071                         if (indx>0) {
1072                                 sign = -sign;
1073                                 // tmp_n's rows r0 and indx were swapped, do the same in tmp_d:
1074                                 for (unsigned c=r1; c<n; ++c)
1075                                         tmp_d.m[n*indx+c].swap(tmp_d.m[n*r0+c]);
1076                         }
1077                         for (unsigned r2=r0+1; r2<m; ++r2) {
1078                                 for (unsigned c=r1+1; c<n; ++c) {
1079                                         dividend_n = (tmp_n.m[r0*n+r1]*tmp_n.m[r2*n+c]*
1080                                                       tmp_d.m[r2*n+r1]*tmp_d.m[r0*n+c]
1081                                                      -tmp_n.m[r2*n+r1]*tmp_n.m[r0*n+c]*
1082                                                       tmp_d.m[r0*n+r1]*tmp_d.m[r2*n+c]).expand();
1083                                         dividend_d = (tmp_d.m[r2*n+r1]*tmp_d.m[r0*n+c]*
1084                                                       tmp_d.m[r0*n+r1]*tmp_d.m[r2*n+c]).expand();
1085                                         bool check = divide(dividend_n, divisor_n,
1086                                                             tmp_n.m[r2*n+c], true);
1087                                         check &= divide(dividend_d, divisor_d,
1088                                                         tmp_d.m[r2*n+c], true);
1089                                         GINAC_ASSERT(check);
1090                                 }
1091                                 // fill up left hand side with zeros
1092                                 for (unsigned c=0; c<=r1; ++c)
1093                                         tmp_n.m[r2*n+c] = _ex0();
1094                         }
1095                         if ((r1<n-1)&&(r0<m-1)) {
1096                                 // compute next iteration's divisor
1097                                 divisor_n = tmp_n.m[r0*n+r1].expand();
1098                                 divisor_d = tmp_d.m[r0*n+r1].expand();
1099                                 if (det) {
1100                                         // save space by deleting no longer needed elements
1101                                         for (unsigned c=0; c<n; ++c) {
1102                                                 tmp_n.m[r0*n+c] = _ex0();
1103                                                 tmp_d.m[r0*n+c] = _ex1();
1104                                         }
1105                                 }
1106                         }
1107                         ++r0;
1108                 }
1109         }
1110         // repopulate *this matrix:
1111         it = this->m.begin();
1112         tmp_n_it = tmp_n.m.begin();
1113         tmp_d_it = tmp_d.m.begin();
1114         for (; it!= this->m.end(); ++it, ++tmp_n_it, ++tmp_d_it)
1115                 (*it) = ((*tmp_n_it)/(*tmp_d_it)).subs(srl);
1116         
1117         return sign;
1118 }
1119
1120
1121 /** Partial pivoting method for matrix elimination schemes.
1122  *  Usual pivoting (symbolic==false) returns the index to the element with the
1123  *  largest absolute value in column ro and swaps the current row with the one
1124  *  where the element was found.  With (symbolic==true) it does the same thing
1125  *  with the first non-zero element.
1126  *
1127  *  @param ro is the row from where to begin
1128  *  @param co is the column to be inspected
1129  *  @param symbolic signal if we want the first non-zero element to be pivoted
1130  *  (true) or the one with the largest absolute value (false).
1131  *  @return 0 if no interchange occured, -1 if all are zero (usually signaling
1132  *  a degeneracy) and positive integer k means that rows ro and k were swapped.
1133  */
1134 int matrix::pivot(unsigned ro, unsigned co, bool symbolic)
1135 {
1136         unsigned k = ro;
1137         if (symbolic) {
1138                 // search first non-zero element in column co beginning at row ro
1139                 while ((k<row) && (this->m[k*col+co].expand().is_zero()))
1140                         ++k;
1141         } else {
1142                 // search largest element in column co beginning at row ro
1143                 GINAC_ASSERT(is_ex_of_type(this->m[k*col+co],numeric));
1144                 unsigned kmax = k+1;
1145                 numeric mmax = abs(ex_to_numeric(m[kmax*col+co]));
1146                 while (kmax<row) {
1147                         GINAC_ASSERT(is_ex_of_type(this->m[kmax*col+co],numeric));
1148                         numeric tmp = ex_to_numeric(this->m[kmax*col+co]);
1149                         if (abs(tmp) > mmax) {
1150                                 mmax = tmp;
1151                                 k = kmax;
1152                         }
1153                         ++kmax;
1154                 }
1155                 if (!mmax.is_zero())
1156                         k = kmax;
1157         }
1158         if (k==row)
1159                 // all elements in column co below row ro vanish
1160                 return -1;
1161         if (k==ro)
1162                 // matrix needs no pivoting
1163                 return 0;
1164         // matrix needs pivoting, so swap rows k and ro
1165         ensure_if_modifiable();
1166         for (unsigned c=0; c<col; ++c)
1167                 this->m[k*col+c].swap(this->m[ro*col+c]);
1168         
1169         return k;
1170 }
1171
1172 /** Convert list of lists to matrix. */
1173 ex lst_to_matrix(const ex &l)
1174 {
1175         if (!is_ex_of_type(l, lst))
1176                 throw(std::invalid_argument("argument to lst_to_matrix() must be a lst"));
1177         
1178         // Find number of rows and columns
1179         unsigned rows = l.nops(), cols = 0, i, j;
1180         for (i=0; i<rows; i++)
1181                 if (l.op(i).nops() > cols)
1182                         cols = l.op(i).nops();
1183         
1184         // Allocate and fill matrix
1185         matrix &m = *new matrix(rows, cols);
1186         for (i=0; i<rows; i++)
1187                 for (j=0; j<cols; j++)
1188                         if (l.op(i).nops() > j)
1189                                 m.set(i, j, l.op(i).op(j));
1190                         else
1191                                 m.set(i, j, ex(0));
1192         return m;
1193 }
1194
1195 #ifndef NO_NAMESPACE_GINAC
1196 } // namespace GiNaC
1197 #endif // ndef NO_NAMESPACE_GINAC