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