]> www.ginac.de Git - ginac.git/blob - ginac/matrix.cpp
- expairseq.cpp: moved expairseq::to_rational to...
[ginac.git] / ginac / matrix.cpp
1 /** @file matrix.cpp
2  *
3  *  Implementation of symbolic matrices */
4
5 /*
6  *  GiNaC Copyright (C) 1999-2000 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()
52     : inherited(TINFO_matrix), row(1), col(1)
53 {
54     debugmsg("matrix default constructor",LOGLEVEL_CONSTRUCT);
55     m.push_back(_ex0());
56 }
57
58 matrix::~matrix()
59 {
60     debugmsg("matrix destructor",LOGLEVEL_DESTRUCT);
61 }
62
63 matrix::matrix(const matrix & other)
64 {
65     debugmsg("matrix copy constructor",LOGLEVEL_CONSTRUCT);
66     copy(other);
67 }
68
69 const matrix & matrix::operator=(const matrix & other)
70 {
71     debugmsg("matrix operator=",LOGLEVEL_ASSIGNMENT);
72     if (this != &other) {
73         destroy(1);
74         copy(other);
75     }
76     return *this;
77 }
78
79 // protected
80
81 void matrix::copy(const matrix & other)
82 {
83     inherited::copy(other);
84     row = other.row;
85     col = other.col;
86     m = other.m;  // STL's vector copying invoked here
87 }
88
89 void matrix::destroy(bool call_parent)
90 {
91     if (call_parent) inherited::destroy(call_parent);
92 }
93
94 //////////
95 // other constructors
96 //////////
97
98 // public
99
100 /** Very common ctor.  Initializes to r x c-dimensional zero-matrix.
101  *
102  *  @param r number of rows
103  *  @param c number of cols */
104 matrix::matrix(unsigned r, unsigned c)
105     : inherited(TINFO_matrix), row(r), col(c)
106 {
107     debugmsg("matrix constructor from unsigned,unsigned",LOGLEVEL_CONSTRUCT);
108     m.resize(r*c, _ex0());
109 }
110
111  // protected
112
113 /** Ctor from representation, for internal use only. */
114 matrix::matrix(unsigned r, unsigned c, const exvector & m2)
115     : inherited(TINFO_matrix), row(r), col(c), m(m2)
116 {
117     debugmsg("matrix constructor from unsigned,unsigned,exvector",LOGLEVEL_CONSTRUCT);
118 }
119
120 //////////
121 // archiving
122 //////////
123
124 /** Construct object from archive_node. */
125 matrix::matrix(const archive_node &n, const lst &sym_lst) : inherited(n, sym_lst)
126 {
127     debugmsg("matrix constructor from archive_node", LOGLEVEL_CONSTRUCT);
128     if (!(n.find_unsigned("row", row)) || !(n.find_unsigned("col", col)))
129         throw (std::runtime_error("unknown matrix dimensions in archive"));
130     m.reserve(row * col);
131     for (unsigned int i=0; true; i++) {
132         ex e;
133         if (n.find_ex("m", e, sym_lst, i))
134             m.push_back(e);
135         else
136             break;
137     }
138 }
139
140 /** Unarchive the object. */
141 ex matrix::unarchive(const archive_node &n, const lst &sym_lst)
142 {
143     return (new matrix(n, sym_lst))->setflag(status_flags::dynallocated);
144 }
145
146 /** Archive the object. */
147 void matrix::archive(archive_node &n) const
148 {
149     inherited::archive(n);
150     n.add_unsigned("row", row);
151     n.add_unsigned("col", col);
152     exvector::const_iterator i = m.begin(), iend = m.end();
153     while (i != iend) {
154         n.add_ex("m", *i);
155         i++;
156     }
157 }
158
159 //////////
160 // functions overriding virtual functions from bases classes
161 //////////
162
163 // public
164
165 basic * matrix::duplicate() const
166 {
167     debugmsg("matrix duplicate",LOGLEVEL_DUPLICATE);
168     return new matrix(*this);
169 }
170
171 void matrix::print(ostream & os, unsigned upper_precedence) const
172 {
173     debugmsg("matrix print",LOGLEVEL_PRINT);
174     os << "[[ ";
175     for (unsigned r=0; r<row-1; ++r) {
176         os << "[[";
177         for (unsigned c=0; c<col-1; ++c) {
178             os << m[r*col+c] << ",";
179         }
180         os << m[col*(r+1)-1] << "]], ";
181     }
182     os << "[[";
183     for (unsigned c=0; c<col-1; ++c) {
184         os << m[(row-1)*col+c] << ",";
185     }
186     os << m[row*col-1] << "]] ]]";
187 }
188
189 void matrix::printraw(ostream & os) const
190 {
191     debugmsg("matrix printraw",LOGLEVEL_PRINT);
192     os << "matrix(" << row << "," << col <<",";
193     for (unsigned r=0; r<row-1; ++r) {
194         os << "(";
195         for (unsigned c=0; c<col-1; ++c) {
196             os << m[r*col+c] << ",";
197         }
198         os << m[col*(r-1)-1] << "),";
199     }
200     os << "(";
201     for (unsigned c=0; c<col-1; ++c) {
202         os << m[(row-1)*col+c] << ",";
203     }
204     os << m[row*col-1] << "))";
205 }
206
207 /** nops is defined to be rows x columns. */
208 unsigned matrix::nops() const
209 {
210     return row*col;
211 }
212
213 /** returns matrix entry at position (i/col, i%col). */
214 ex matrix::op(int i) const
215 {
216     return m[i];
217 }
218
219 /** returns matrix entry at position (i/col, i%col). */
220 ex & matrix::let_op(int i)
221 {
222     return m[i];
223 }
224
225 /** expands the elements of a matrix entry by entry. */
226 ex matrix::expand(unsigned options) const
227 {
228     exvector tmp(row*col);
229     for (unsigned i=0; i<row*col; ++i) {
230         tmp[i]=m[i].expand(options);
231     }
232     return matrix(row, col, tmp);
233 }
234
235 /** Search ocurrences.  A matrix 'has' an expression if it is the expression
236  *  itself or one of the elements 'has' it. */
237 bool matrix::has(const ex & other) const
238 {
239     GINAC_ASSERT(other.bp!=0);
240     
241     // tautology: it is the expression itself
242     if (is_equal(*other.bp)) return true;
243     
244     // search all the elements
245     for (exvector::const_iterator r=m.begin(); r!=m.end(); ++r) {
246         if ((*r).has(other)) return true;
247     }
248     return false;
249 }
250
251 /** evaluate matrix entry by entry. */
252 ex matrix::eval(int level) const
253 {
254     debugmsg("matrix eval",LOGLEVEL_MEMBER_FUNCTION);
255     
256     // check if we have to do anything at all
257     if ((level==1)&&(flags & status_flags::evaluated))
258         return *this;
259     
260     // emergency break
261     if (level == -max_recursion_level)
262         throw (std::runtime_error("matrix::eval(): recursion limit exceeded"));
263     
264     // eval() entry by entry
265     exvector m2(row*col);
266     --level;    
267     for (unsigned r=0; r<row; ++r) {
268         for (unsigned c=0; c<col; ++c) {
269             m2[r*col+c] = m[r*col+c].eval(level);
270         }
271     }
272     
273     return (new matrix(row, col, m2))->setflag(status_flags::dynallocated |
274                                                status_flags::evaluated );
275 }
276
277 /** evaluate matrix numerically entry by entry. */
278 ex matrix::evalf(int level) const
279 {
280     debugmsg("matrix evalf",LOGLEVEL_MEMBER_FUNCTION);
281         
282     // check if we have to do anything at all
283     if (level==1)
284         return *this;
285     
286     // emergency break
287     if (level == -max_recursion_level) {
288         throw (std::runtime_error("matrix::evalf(): recursion limit exceeded"));
289     }
290     
291     // evalf() entry by entry
292     exvector m2(row*col);
293     --level;
294     for (unsigned r=0; r<row; ++r) {
295         for (unsigned c=0; c<col; ++c) {
296             m2[r*col+c] = m[r*col+c].evalf(level);
297         }
298     }
299     return matrix(row, col, m2);
300 }
301
302 // protected
303
304 int matrix::compare_same_type(const basic & other) const
305 {
306     GINAC_ASSERT(is_exactly_of_type(other, matrix));
307     const matrix & o = static_cast<matrix &>(const_cast<basic &>(other));
308     
309     // compare number of rows
310     if (row != o.rows())
311         return row < o.rows() ? -1 : 1;
312     
313     // compare number of columns
314     if (col != o.cols())
315         return col < o.cols() ? -1 : 1;
316     
317     // equal number of rows and columns, compare individual elements
318     int cmpval;
319     for (unsigned r=0; r<row; ++r) {
320         for (unsigned c=0; c<col; ++c) {
321             cmpval = ((*this)(r,c)).compare(o(r,c));
322             if (cmpval!=0) return cmpval;
323         }
324     }
325     // all elements are equal => matrices are equal;
326     return 0;
327 }
328
329 //////////
330 // non-virtual functions in this class
331 //////////
332
333 // public
334
335 /** Sum of matrices.
336  *
337  *  @exception logic_error (incompatible matrices) */
338 matrix matrix::add(const matrix & other) const
339 {
340     if (col != other.col || row != other.row)
341         throw (std::logic_error("matrix::add(): incompatible matrices"));
342     
343     exvector sum(this->m);
344     exvector::iterator i;
345     exvector::const_iterator ci;
346     for (i=sum.begin(), ci=other.m.begin();
347          i!=sum.end();
348          ++i, ++ci) {
349         (*i) += (*ci);
350     }
351     return matrix(row,col,sum);
352 }
353
354
355 /** Difference of matrices.
356  *
357  *  @exception logic_error (incompatible matrices) */
358 matrix matrix::sub(const matrix & other) const
359 {
360     if (col != other.col || row != other.row)
361         throw (std::logic_error("matrix::sub(): incompatible matrices"));
362     
363     exvector dif(this->m);
364     exvector::iterator i;
365     exvector::const_iterator ci;
366     for (i=dif.begin(), ci=other.m.begin();
367          i!=dif.end();
368          ++i, ++ci) {
369         (*i) -= (*ci);
370     }
371     return matrix(row,col,dif);
372 }
373
374
375 /** Product of matrices.
376  *
377  *  @exception logic_error (incompatible matrices) */
378 matrix matrix::mul(const matrix & other) const
379 {
380     if (col != other.row)
381         throw (std::logic_error("matrix::mul(): incompatible matrices"));
382     
383     exvector prod(row*other.col);
384     
385     for (unsigned r1=0; r1<row; ++r1) {
386         for (unsigned c=0; c<col; ++c) {
387             if (m[r1*col+c].is_zero())
388                 continue;
389             for (unsigned r2=0; r2<other.col; ++r2)
390                 prod[r1*other.col+r2] += m[r1*col+c] * other.m[c*other.col+r2];
391         }
392     }
393     return matrix(row, other.col, prod);
394 }
395
396
397 /** operator() to access elements.
398  *
399  *  @param ro row of element
400  *  @param co column of element 
401  *  @exception range_error (index out of range) */
402 const ex & matrix::operator() (unsigned ro, unsigned co) const
403 {
404     if (ro<0 || ro>=row || co<0 || co>=col)
405         throw (std::range_error("matrix::operator(): index out of range"));
406     
407     return m[ro*col+co];
408 }
409
410
411 /** Set individual elements manually.
412  *
413  *  @exception range_error (index out of range) */
414 matrix & matrix::set(unsigned ro, unsigned co, ex value)
415 {
416     if (ro<0 || ro>=row || co<0 || co>=col)
417         throw (std::range_error("matrix::set(): index out of range"));
418     
419     ensure_if_modifiable();
420     m[ro*col+co] = value;
421     return *this;
422 }
423
424
425 /** Transposed of an m x n matrix, producing a new n x m matrix object that
426  *  represents the transposed. */
427 matrix matrix::transpose(void) const
428 {
429     exvector trans(col*row);
430     
431     for (unsigned r=0; r<col; ++r)
432         for (unsigned c=0; c<row; ++c)
433             trans[r*row+c] = m[c*col+r];
434     
435     return matrix(col,row,trans);
436 }
437
438
439 /** Determinant of square matrix.  This routine doesn't actually calculate the
440  *  determinant, it only implements some heuristics about which algorithm to
441  *  call.  If all the elements of the matrix are elements of an integral domain
442  *  the determinant is also in that integral domain and the result is expanded
443  *  only.  If one or more elements are from a quotient field the determinant is
444  *  usually also in that quotient field and the result is normalized before it
445  *  is returned.  This implies that the determinant of the symbolic 2x2 matrix
446  *  [[a/(a-b),1],[b/(a-b),1]] is returned as unity.  (In this respect, it
447  *  behaves like MapleV and unlike Mathematica.)
448  *
449  *  @return    the determinant as a new expression
450  *  @exception logic_error (matrix not square) */
451 ex matrix::determinant(void) const
452 {
453     if (row!=col)
454         throw (std::logic_error("matrix::determinant(): matrix not square"));
455     GINAC_ASSERT(row*col==m.capacity());
456     if (this->row==1)  // continuation would be pointless
457         return m[0];
458     
459     bool numeric_flag = true;
460     bool normal_flag = false;
461     unsigned sparse_count = 0;  // count non-zero elements
462     for (exvector::const_iterator r=m.begin(); r!=m.end(); ++r) {
463         if (!(*r).is_zero()) {
464             ++sparse_count;
465         }
466         if (!(*r).info(info_flags::numeric)) {
467             numeric_flag = false;
468         }
469         if ((*r).info(info_flags::rational_function) &&
470             !(*r).info(info_flags::crational_polynomial)) {
471             normal_flag = true;
472         }
473     }
474     
475     if (numeric_flag)  // purely numeric matrix
476         return determinant_numeric();
477     
478     // Does anybody really know when a matrix is sparse?
479     if (4*sparse_count<row*col) {  // < row/2 nonzero elements average in a row
480         return determinant_bareiss(normal_flag);
481     }
482     
483     // Now come the minor expansion schemes.  We always develop such that the
484     // smallest minors (i.e, the trivial 1x1 ones) are on the rightmost column.
485     // For this to be efficient it turns out that the emptiest columns (i.e.
486     // the ones with most zeros) should be the ones on the right hand side.
487     // Therefore we presort the columns of the matrix:
488     typedef pair<unsigned,unsigned> uintpair;  // # of zeros, column
489     vector<uintpair> c_zeros;  // number of zeros in column
490     for (unsigned c=0; c<col; ++c) {
491         unsigned acc = 0;
492         for (unsigned r=0; r<row; ++r)
493             if (m[r*col+c].is_zero())
494                 ++acc;
495         c_zeros.push_back(uintpair(acc,c));
496     }
497     sort(c_zeros.begin(),c_zeros.end());
498     vector<unsigned> pre_sort;  // unfortunately vector<uintpair> can't be used
499                                 // for permutation_sign.
500     for (vector<uintpair>::iterator i=c_zeros.begin(); i!=c_zeros.end(); ++i)
501         pre_sort.push_back(i->second);
502     int sign = permutation_sign(pre_sort);
503     exvector result(row*col);  // represents sorted matrix
504     unsigned c = 0;
505     for (vector<unsigned>::iterator i=pre_sort.begin();
506          i!=pre_sort.end();
507          ++i,++c) {
508         for (unsigned r=0; r<row; ++r)
509             result[r*col+c] = m[r*col+(*i)];
510     }
511     
512     if (normal_flag)
513         return sign*matrix(row,col,result).determinant_minor().normal();
514     return sign*matrix(row,col,result).determinant_minor();
515 }
516
517
518 /** Trace of a matrix.  The result is normalized if it is in some quotient
519  *  field and expanded only otherwise.  This implies that the trace of the
520  *  symbolic 2x2 matrix [[a/(a-b),x],[y,b/(b-a)]] is recognized to be unity.
521  *
522  *  @return    the sum of diagonal elements
523  *  @exception logic_error (matrix not square) */
524 ex matrix::trace(void) const
525 {
526     if (row != col)
527         throw (std::logic_error("matrix::trace(): matrix not square"));
528     GINAC_ASSERT(row*col==m.capacity());
529     
530     ex tr;
531     for (unsigned r=0; r<col; ++r)
532         tr += m[r*col+r];
533     
534     if (tr.info(info_flags::rational_function) &&
535         !tr.info(info_flags::crational_polynomial))
536         return tr.normal();
537     else
538         return tr.expand();
539 }
540
541
542 /** Characteristic Polynomial.  Following mathematica notation the
543  *  characteristic polynomial of a matrix M is defined as the determiant of
544  *  (M - lambda * 1) where 1 stands for the unit matrix of the same dimension
545  *  as M.  Note that some CASs define it with a sign inside the determinant
546  *  which gives rise to an overall sign if the dimension is odd.  This method
547  *  returns the characteristic polynomial collected in powers of lambda as a
548  *  new expression.
549  *
550  *  @return    characteristic polynomial as new expression
551  *  @exception logic_error (matrix not square)
552  *  @see       matrix::determinant() */
553 ex matrix::charpoly(const symbol & lambda) const
554 {
555     if (row != col)
556         throw (std::logic_error("matrix::charpoly(): matrix not square"));
557     
558     bool numeric_flag = true;
559     for (exvector::const_iterator r=m.begin(); r!=m.end(); ++r) {
560         if (!(*r).info(info_flags::numeric)) {
561             numeric_flag = false;
562         }
563     }
564     
565     // The pure numeric case is traditionally rather common.  Hence, it is
566     // trapped and we use Leverrier's algorithm which goes as row^3 for
567     // every coefficient.  The expensive section is the matrix multiplication.
568     if (numeric_flag) {
569         matrix B(*this);
570         ex c = B.trace();
571         ex poly = power(lambda,row)-c*power(lambda,row-1);
572         for (unsigned i=1; i<row; ++i) {
573             for (unsigned j=0; j<row; ++j)
574                 B.m[j*col+j] -= c;
575             B = this->mul(B);
576             c = B.trace()/ex(i+1);
577             poly -= c*power(lambda,row-i-1);
578         }
579         if (row%2)
580             return -poly;
581         else
582             return poly;
583     }
584     
585     matrix M(*this);
586     for (unsigned r=0; r<col; ++r)
587         M.m[r*col+r] -= lambda;
588     
589     return M.determinant().collect(lambda);
590 }
591
592
593 /** Inverse of this matrix.
594  *
595  *  @return    the inverted matrix
596  *  @exception logic_error (matrix not square)
597  *  @exception runtime_error (singular matrix) */
598 matrix matrix::inverse(void) const
599 {
600     if (row != col)
601         throw (std::logic_error("matrix::inverse(): matrix not square"));
602     
603     matrix tmp(row,col);
604     // set tmp to the unit matrix
605     for (unsigned i=0; i<col; ++i)
606         tmp.m[i*col+i] = _ex1();
607
608     // create a copy of this matrix
609     matrix cpy(*this);
610     for (unsigned r1=0; r1<row; ++r1) {
611         int indx = cpy.pivot(r1);
612         if (indx == -1) {
613             throw (std::runtime_error("matrix::inverse(): singular matrix"));
614         }
615         if (indx != 0) {  // swap rows r and indx of matrix tmp
616             for (unsigned i=0; i<col; ++i) {
617                 tmp.m[r1*col+i].swap(tmp.m[indx*col+i]);
618             }
619         }
620         ex a1 = cpy.m[r1*col+r1];
621         for (unsigned c=0; c<col; ++c) {
622             cpy.m[r1*col+c] /= a1;
623             tmp.m[r1*col+c] /= a1;
624         }
625         for (unsigned r2=0; r2<row; ++r2) {
626             if (r2 != r1) {
627                 ex a2 = cpy.m[r2*col+r1];
628                 for (unsigned c=0; c<col; ++c) {
629                     cpy.m[r2*col+c] -= a2 * cpy.m[r1*col+c];
630                     tmp.m[r2*col+c] -= a2 * tmp.m[r1*col+c];
631                 }
632             }
633         }
634     }
635     return tmp;
636 }
637
638
639 // superfluous helper function
640 void matrix::ffe_swap(unsigned r1, unsigned c1, unsigned r2 ,unsigned c2)
641 {
642     ensure_if_modifiable();
643     
644     ex tmp = ffe_get(r1,c1);
645     ffe_set(r1,c1,ffe_get(r2,c2));
646     ffe_set(r2,c2,tmp);
647 }
648
649 // superfluous helper function
650 void matrix::ffe_set(unsigned r, unsigned c, ex e)
651 {
652     set(r-1,c-1,e);
653 }
654
655 // superfluous helper function
656 ex matrix::ffe_get(unsigned r, unsigned c) const
657 {
658     return operator()(r-1,c-1);
659 }
660
661 /** Solve a set of equations for an m x n matrix by fraction-free Gaussian
662  *  elimination.  Based on algorithm 9.1 from 'Algorithms for Computer Algebra'
663  *  by Keith O. Geddes et al.
664  *
665  *  @param vars n x p matrix
666  *  @param rhs m x p matrix
667  *  @exception logic_error (incompatible matrices)
668  *  @exception runtime_error (singular matrix) */
669 matrix matrix::fraction_free_elim(const matrix & vars,
670                                   const matrix & rhs) const
671 {
672     // FIXME: use implementation of matrix::fraction_free_elim
673     if ((row != rhs.row) || (col != vars.row) || (rhs.col != vars.col))
674         throw (std::logic_error("matrix::fraction_free_elim(): incompatible matrices"));
675     
676     matrix a(*this);  // make a copy of the matrix
677     matrix b(rhs);    // make a copy of the rhs vector
678     
679     // given an m x n matrix a, reduce it to upper echelon form
680     unsigned m = a.row;
681     unsigned n = a.col;
682     int sign = 1;
683     ex divisor = 1;
684     unsigned r = 1;
685     
686     // eliminate below row r, with pivot in column k
687     for (unsigned k=1; (k<=n)&&(r<=m); ++k) {
688         // find a nonzero pivot
689         unsigned p;
690         for (p=r; (p<=m)&&(a.ffe_get(p,k).is_equal(_ex0())); ++p) {}
691         // pivot is in row p
692         if (p<=m) {
693             if (p!=r) {
694                 // switch rows p and r
695                 for (unsigned j=k; j<=n; ++j)
696                     a.ffe_swap(p,j,r,j);
697                 b.ffe_swap(p,1,r,1);
698                 // keep track of sign changes due to row exchange
699                 sign = -sign;
700             }
701             for (unsigned i=r+1; i<=m; ++i) {
702                 for (unsigned j=k+1; j<=n; ++j) {
703                     a.ffe_set(i,j,(a.ffe_get(r,k)*a.ffe_get(i,j)
704                                   -a.ffe_get(r,j)*a.ffe_get(i,k))/divisor);
705                     a.ffe_set(i,j,a.ffe_get(i,j).normal() /*.normal() */ );
706                 }
707                 b.ffe_set(i,1,(a.ffe_get(r,k)*b.ffe_get(i,1)
708                               -b.ffe_get(r,1)*a.ffe_get(i,k))/divisor);
709                 b.ffe_set(i,1,b.ffe_get(i,1).normal() /*.normal() */ );
710                 a.ffe_set(i,k,0);
711             }
712             divisor = a.ffe_get(r,k);
713             r++;
714         }
715     }
716     // optionally compute the determinant for square or augmented matrices
717     // if (r==m+1) { det = sign*divisor; } else { det = 0; }
718     
719     /*
720     for (unsigned r=1; r<=m; ++r) {
721         for (unsigned c=1; c<=n; ++c) {
722             cout << a.ffe_get(r,c) << "\t";
723         }
724         cout << " | " <<  b.ffe_get(r,1) << endl;
725     }
726     */
727     
728 #ifdef DO_GINAC_ASSERT
729     // test if we really have an upper echelon matrix
730     int zero_in_last_row = -1;
731     for (unsigned r=1; r<=m; ++r) {
732         int zero_in_this_row=0;
733         for (unsigned c=1; c<=n; ++c) {
734             if (a.ffe_get(r,c).is_equal(_ex0()))
735                zero_in_this_row++;
736             else
737                 break;
738         }
739         GINAC_ASSERT((zero_in_this_row>zero_in_last_row)||(zero_in_this_row=n));
740         zero_in_last_row = zero_in_this_row;
741     }
742 #endif // def DO_GINAC_ASSERT
743     
744     /*
745     cout << "after" << endl;
746     cout << "a=" << a << endl;
747     cout << "b=" << b << endl;
748     */
749     
750     // assemble solution
751     matrix sol(n,1);
752     unsigned last_assigned_sol = n+1;
753     for (unsigned r=m; r>0; --r) {
754         unsigned first_non_zero = 1;
755         while ((first_non_zero<=n)&&(a.ffe_get(r,first_non_zero).is_zero()))
756             first_non_zero++;
757         if (first_non_zero>n) {
758             // row consists only of zeroes, corresponding rhs must be 0 as well
759             if (!b.ffe_get(r,1).is_zero()) {
760                 throw (std::runtime_error("matrix::fraction_free_elim(): singular matrix"));
761             }
762         } else {
763             // assign solutions for vars between first_non_zero+1 and
764             // last_assigned_sol-1: free parameters
765             for (unsigned c=first_non_zero+1; c<=last_assigned_sol-1; ++c) {
766                 sol.ffe_set(c,1,vars.ffe_get(c,1));
767             }
768             ex e = b.ffe_get(r,1);
769             for (unsigned c=first_non_zero+1; c<=n; ++c) {
770                 e=e-a.ffe_get(r,c)*sol.ffe_get(c,1);
771             }
772             sol.ffe_set(first_non_zero,1,
773                         (e/a.ffe_get(r,first_non_zero)).normal());
774             last_assigned_sol = first_non_zero;
775         }
776     }
777     // assign solutions for vars between 1 and
778     // last_assigned_sol-1: free parameters
779     for (unsigned c=1; c<=last_assigned_sol-1; ++c)
780         sol.ffe_set(c,1,vars.ffe_get(c,1));
781     
782 #ifdef DO_GINAC_ASSERT
783     // test solution with echelon matrix
784     for (unsigned r=1; r<=m; ++r) {
785         ex e = 0;
786         for (unsigned c=1; c<=n; ++c)
787             e = e+a.ffe_get(r,c)*sol.ffe_get(c,1);
788         if (!(e-b.ffe_get(r,1)).normal().is_zero()) {
789             cout << "e=" << e;
790             cout << "b.ffe_get(" << r<<",1)=" << b.ffe_get(r,1) << endl;
791             cout << "diff=" << (e-b.ffe_get(r,1)).normal() << endl;
792         }
793         GINAC_ASSERT((e-b.ffe_get(r,1)).normal().is_zero());
794     }
795     
796     // test solution with original matrix
797     for (unsigned r=1; r<=m; ++r) {
798         ex e = 0;
799         for (unsigned c=1; c<=n; ++c)
800             e = e+ffe_get(r,c)*sol.ffe_get(c,1);
801         try {
802             if (!(e-rhs.ffe_get(r,1)).normal().is_zero()) {
803                 cout << "e=" << e << endl;
804                 e.printtree(cout);
805                 ex en = e.normal();
806                 cout << "e.normal()=" << en << endl;
807                 en.printtree(cout);
808                 cout << "rhs.ffe_get(" << r<<",1)=" << rhs.ffe_get(r,1) << endl;
809                 cout << "diff=" << (e-rhs.ffe_get(r,1)).normal() << endl;
810             }
811         } catch (...) {
812             ex xxx = e - rhs.ffe_get(r,1);
813             cerr << "xxx=" << xxx << endl << endl;
814         }
815         GINAC_ASSERT((e-rhs.ffe_get(r,1)).normal().is_zero());
816     }
817 #endif // def DO_GINAC_ASSERT
818     
819     return sol;
820 }
821
822 /** Solve a set of equations for an m x n matrix.
823  *
824  *  @param vars n x p matrix
825  *  @param rhs m x p matrix
826  *  @exception logic_error (incompatible matrices)
827  *  @exception runtime_error (singular matrix) */
828 matrix matrix::solve(const matrix & vars,
829                      const matrix & rhs) const
830 {
831     if ((row != rhs.row) || (col != vars.row) || (rhs.col != vars.col))
832         throw (std::logic_error("matrix::solve(): incompatible matrices"));
833     
834     throw (std::runtime_error("FIXME: need implementation."));
835 }
836
837 /** Old and obsolete interface: */
838 matrix matrix::old_solve(const matrix & v) const
839 {
840     if ((v.row != col) || (col != v.row))
841         throw (std::logic_error("matrix::solve(): incompatible matrices"));
842     
843     // build the augmented matrix of *this with v attached to the right
844     matrix tmp(row,col+v.col);
845     for (unsigned r=0; r<row; ++r) {
846         for (unsigned c=0; c<col; ++c)
847             tmp.m[r*tmp.col+c] = this->m[r*col+c];
848         for (unsigned c=0; c<v.col; ++c)
849             tmp.m[r*tmp.col+c+col] = v.m[r*v.col+c];
850     }
851     // cout << "augmented: " << tmp << endl;
852     tmp.gauss_elimination();
853     // cout << "degaussed: " << tmp << endl;
854     // assemble the solution matrix
855     exvector sol(v.row*v.col);
856     for (unsigned c=0; c<v.col; ++c) {
857         for (unsigned r=row; r>0; --r) {
858             for (unsigned i=r; i<col; ++i)
859                 sol[(r-1)*v.col+c] -= tmp.m[(r-1)*tmp.col+i]*sol[i*v.col+c];
860             sol[(r-1)*v.col+c] += tmp.m[(r-1)*tmp.col+col+c];
861             sol[(r-1)*v.col+c] = (sol[(r-1)*v.col+c]/tmp.m[(r-1)*tmp.col+(r-1)]).normal();
862         }
863     }
864     return matrix(v.row, v.col, sol);
865 }
866
867
868 // protected
869
870 /** Determinant of purely numeric matrix, using pivoting.
871  *
872  *  @see       matrix::determinant() */
873 ex matrix::determinant_numeric(void) const
874 {
875     matrix tmp(*this);
876     ex det = _ex1();
877     ex piv;
878     
879     // standard Gauss method:
880     for (unsigned r1=0; r1<row; ++r1) {
881         int indx = tmp.pivot(r1);
882         if (indx == -1)
883             return _ex0();
884         if (indx != 0)
885             det *= _ex_1();
886         det = det * tmp.m[r1*col+r1];
887         for (unsigned r2=r1+1; r2<row; ++r2) {
888             piv = tmp.m[r2*col+r1] / tmp.m[r1*col+r1];
889             for (unsigned c=r1+1; c<col; c++) {
890                 tmp.m[r2*col+c] -= piv * tmp.m[r1*col+c];
891             }
892         }
893     }
894     
895     return det;
896 }
897
898
899 /** Recursive determinant for small matrices having at least one symbolic
900  *  entry.  The basic algorithm, known as Laplace-expansion, is enhanced by
901  *  some bookkeeping to avoid calculation of the same submatrices ("minors")
902  *  more than once.  According to W.M.Gentleman and S.C.Johnson this algorithm
903  *  is better than elimination schemes for matrices of sparse multivariate
904  *  polynomials and also for matrices of dense univariate polynomials if the
905  *  matrix' dimesion is larger than 7.
906  *
907  *  @return the determinant as a new expression (in expanded form)
908  *  @see matrix::determinant() */
909 ex matrix::determinant_minor(void) const
910 {
911     // for small matrices the algorithm does not make any sense:
912     if (this->row==1)
913         return m[0];
914     if (this->row==2)
915         return (m[0]*m[3]-m[2]*m[1]).expand();
916     if (this->row==3)
917         return (m[0]*m[4]*m[8]-m[0]*m[5]*m[7]-
918                 m[1]*m[3]*m[8]+m[2]*m[3]*m[7]+
919                 m[1]*m[5]*m[6]-m[2]*m[4]*m[6]).expand();
920     
921     // This algorithm can best be understood by looking at a naive
922     // implementation of Laplace-expansion, like this one:
923     // ex det;
924     // matrix minorM(this->row-1,this->col-1);
925     // for (unsigned r1=0; r1<this->row; ++r1) {
926     //     // shortcut if element(r1,0) vanishes
927     //     if (m[r1*col].is_zero())
928     //         continue;
929     //     // assemble the minor matrix
930     //     for (unsigned r=0; r<minorM.rows(); ++r) {
931     //         for (unsigned c=0; c<minorM.cols(); ++c) {
932     //             if (r<r1)
933     //                 minorM.set(r,c,m[r*col+c+1]);
934     //             else
935     //                 minorM.set(r,c,m[(r+1)*col+c+1]);
936     //         }
937     //     }
938     //     // recurse down and care for sign:
939     //     if (r1%2)
940     //         det -= m[r1*col] * minorM.determinant_minor();
941     //     else
942     //         det += m[r1*col] * minorM.determinant_minor();
943     // }
944     // return det.expand();
945     // What happens is that while proceeding down many of the minors are
946     // computed more than once.  In particular, there are binomial(n,k)
947     // kxk minors and each one is computed factorial(n-k) times.  Therefore
948     // it is reasonable to store the results of the minors.  We proceed from
949     // right to left.  At each column c we only need to retrieve the minors
950     // calculated in step c-1.  We therefore only have to store at most 
951     // 2*binomial(n,n/2) minors.
952     
953     // Unique flipper counter for partitioning into minors
954     vector<unsigned> Pkey;
955     Pkey.reserve(this->col);
956     // key for minor determinant (a subpartition of Pkey)
957     vector<unsigned> Mkey;
958     Mkey.reserve(this->col-1);
959     // we store our subminors in maps, keys being the rows they arise from
960     typedef map<vector<unsigned>,class ex> Rmap;
961     typedef map<vector<unsigned>,class ex>::value_type Rmap_value;
962     Rmap A;
963     Rmap B;
964     ex det;
965     // initialize A with last column:
966     for (unsigned r=0; r<this->col; ++r) {
967         Pkey.erase(Pkey.begin(),Pkey.end());
968         Pkey.push_back(r);
969         A.insert(Rmap_value(Pkey,m[this->col*r+this->col-1]));
970     }
971     // proceed from right to left through matrix
972     for (int c=this->col-2; c>=0; --c) {
973         Pkey.erase(Pkey.begin(),Pkey.end());  // don't change capacity
974         Mkey.erase(Mkey.begin(),Mkey.end());
975         for (unsigned i=0; i<this->col-c; ++i)
976             Pkey.push_back(i);
977         unsigned fc = 0;  // controls logic for our strange flipper counter
978         do {
979             det = _ex0();
980             for (unsigned r=0; r<this->col-c; ++r) {
981                 // maybe there is nothing to do?
982                 if (m[Pkey[r]*this->col+c].is_zero())
983                     continue;
984                 // create the sorted key for all possible minors
985                 Mkey.erase(Mkey.begin(),Mkey.end());
986                 for (unsigned i=0; i<this->col-c; ++i)
987                     if (i!=r)
988                         Mkey.push_back(Pkey[i]);
989                 // Fetch the minors and compute the new determinant
990                 if (r%2)
991                     det -= m[Pkey[r]*this->col+c]*A[Mkey];
992                 else
993                     det += m[Pkey[r]*this->col+c]*A[Mkey];
994             }
995             // prevent build-up of deep nesting of expressions saves time:
996             det = det.expand();
997             // store the new determinant at its place in B:
998             if (!det.is_zero())
999                 B.insert(Rmap_value(Pkey,det));
1000             // increment our strange flipper counter
1001             for (fc=this->col-c; fc>0; --fc) {
1002                 ++Pkey[fc-1];
1003                 if (Pkey[fc-1]<fc+c)
1004                     break;
1005             }
1006             if (fc<this->col-c)
1007                 for (unsigned j=fc; j<this->col-c; ++j)
1008                     Pkey[j] = Pkey[j-1]+1;
1009         } while(fc);
1010         // next column, so change the role of A and B:
1011         A = B;
1012         B.clear();
1013     }
1014     
1015     return det;
1016 }
1017
1018 /** Helper function to divide rational functions, as needed in any Bareiss
1019  *  elimination scheme over a quotient field.
1020  *  
1021  *  @see divide() */
1022 bool rat_divide(const ex & a, const ex & b, ex & q, bool check_args = true)
1023 {
1024     q = _ex0();
1025     if (b.is_zero())
1026         throw(std::overflow_error("rat_divide(): division by zero"));
1027     if (a.is_zero())
1028         return true;
1029     if (is_ex_exactly_of_type(b, numeric)) {
1030         q = a / b;
1031         return true;
1032     } else if (is_ex_exactly_of_type(a, numeric))
1033         return false;
1034     ex a_n = a.numer();
1035     ex a_d = a.denom();
1036     ex b_n = b.numer();
1037     ex b_d = b.denom();
1038     ex n;  // new numerator
1039     ex d;  // new denominator
1040     bool check = true;
1041     check &= divide(a_n, b_n, n, check_args);
1042     check &= divide(a_d, b_d, d, check_args);
1043     q = n/d;
1044     return check;
1045 }
1046
1047
1048 /** Determinant computed by using fraction free elimination.  This
1049  *  routine is only called internally by matrix::determinant().
1050  *
1051  *  @param normalize may be set to false only in integral domains. */
1052 ex matrix::determinant_bareiss(bool normalize) const
1053 {
1054     if (rows()==1)
1055         return m[0];
1056     
1057     int sign = 1;
1058     ex divisor = 1;
1059     ex dividend;
1060     
1061     // we populate a tmp matrix to subsequently operate on, it should
1062     // be normalized even though this algorithm doesn't need GCDs since
1063     // the elements of *this might be unnormalized, which complicates
1064     // things:
1065     matrix tmp(*this);
1066     exvector::const_iterator i = m.begin();
1067     exvector::iterator ti = tmp.m.begin();
1068     for (; i!= m.end(); ++i, ++ti) {
1069         if (normalize)
1070             (*ti) = (*i).normal();
1071         else
1072             (*ti) = (*i);
1073     }
1074     
1075     for (unsigned r1=0; r1<row-1; ++r1) {
1076         int indx = tmp.pivot(r1);
1077         if (indx==-1)
1078             return _ex0();
1079         if (indx>0)
1080             sign = -sign;
1081         if (r1>0) {
1082             divisor = tmp.m[(r1-1)*col+(r1-1)].expand();
1083             // delete the elements we don't need anymore:
1084             for (unsigned c=0; c<col; ++c)
1085                 tmp.m[(r1-1)*col+c] = _ex0();
1086         }
1087         for (unsigned r2=r1+1; r2<row; ++r2) {
1088             for (unsigned c=r1+1; c<col; ++c) {
1089                 lst srl;  // symbol replacement list for .to_rational()
1090                 dividend = (tmp.m[r1*tmp.col+r1]*tmp.m[r2*tmp.col+c]
1091                            -tmp.m[r2*tmp.col+r1]*tmp.m[r1*tmp.col+c]).expand();
1092                 if (normalize) {
1093 #ifdef DO_GINAC_ASSERT
1094                     GINAC_ASSERT(rat_divide(dividend.to_rational(srl),
1095                                             divisor.to_rational(srl),
1096                                             tmp.m[r2*tmp.col+c],true));
1097 #else
1098                     rat_divide(dividend.to_rational(srl),
1099                                divisor.to_rational(srl),
1100                                tmp.m[r2*tmp.col+c],false);
1101 #endif                    
1102                 }
1103                 else {
1104 #ifdef DO_GINAC_ASSERT
1105                     GINAC_ASSERT(divide(dividend.to_rational(srl),
1106                                         divisor.to_rational(srl),
1107                                         tmp.m[r2*tmp.col+c],true));
1108 #else
1109                     divide(dividend.to_rational(srl),
1110                            divisor.to_rational(srl),
1111                            tmp.m[r2*tmp.col+c],false);
1112 #endif                    
1113                 }
1114                 tmp.m[r2*tmp.col+c] = tmp.m[r2*tmp.col+c].subs(srl);
1115             }
1116             for (unsigned c=0; c<=r1; ++c)
1117                 tmp.m[r2*tmp.col+c] = _ex0();
1118         }
1119     }
1120     
1121     return sign*tmp.m[tmp.row*tmp.col-1];
1122 }
1123
1124
1125 /** Perform the steps of an ordinary Gaussian elimination to bring the matrix
1126  *  into an upper echelon form.
1127  *
1128  *  @return sign is 1 if an even number of rows was swapped, -1 if an odd
1129  *  number of rows was swapped and 0 if the matrix is singular. */
1130 int matrix::gauss_elimination(void)
1131 {
1132     int sign = 1;
1133     ensure_if_modifiable();
1134     for (unsigned r1=0; r1<row-1; ++r1) {
1135         int indx = pivot(r1);
1136         if (indx == -1)
1137             return 0;  // Note: leaves *this in a messy state.
1138         if (indx > 0)
1139             sign = -sign;
1140         for (unsigned r2=r1+1; r2<row; ++r2) {
1141             for (unsigned c=r1+1; c<col; ++c)
1142                 this->m[r2*col+c] -= this->m[r2*col+r1]*this->m[r1*col+c]/this->m[r1*col+r1];
1143             for (unsigned c=0; c<=r1; ++c)
1144                 this->m[r2*col+c] = _ex0();
1145         }
1146     }
1147     
1148     return sign;
1149 }
1150
1151
1152 /** Perform the steps of division free elimination to bring the matrix
1153  *  into an upper echelon form.
1154  *
1155  *  @return sign is 1 if an even number of rows was swapped, -1 if an odd
1156  *  number of rows was swapped and 0 if the matrix is singular. */
1157 int matrix::division_free_elimination(void)
1158 {
1159     int sign = 1;
1160     ensure_if_modifiable();
1161     for (unsigned r1=0; r1<row-1; ++r1) {
1162         int indx = pivot(r1);
1163         if (indx==-1)
1164             return 0;  // Note: leaves *this in a messy state.
1165         if (indx>0)
1166             sign = -sign;
1167         for (unsigned r2=r1+1; r2<row; ++r2) {
1168             for (unsigned c=r1+1; c<col; ++c)
1169                 this->m[r2*col+c] = this->m[r1*col+r1]*this->m[r2*col+c] - this->m[r2*col+r1]*this->m[r1*col+c];
1170             for (unsigned c=0; c<=r1; ++c)
1171                 this->m[r2*col+c] = _ex0();
1172         }
1173     }
1174     
1175     return sign;
1176 }
1177
1178
1179 /** Perform the steps of Bareiss' one-step fraction free elimination to bring
1180  *  the matrix into an upper echelon form.
1181  *
1182  *  @return sign is 1 if an even number of rows was swapped, -1 if an odd
1183  *  number of rows was swapped and 0 if the matrix is singular. */
1184 int matrix::fraction_free_elimination(void)
1185 {
1186     ensure_if_modifiable();
1187     
1188     // first normal all elements:
1189     for (exvector::iterator i=m.begin(); i!=m.end(); ++i)
1190         (*i) = (*i).normal();
1191     
1192     // FIXME: this is unfinished, once matrix::determinant_bareiss is
1193     // bulletproof, some code ought to be copy from there to here.
1194     int sign = 1;
1195     ex divisor = 1;
1196     ex dividend;
1197     lst srl;      // symbol replacement list for .to_rational()
1198     
1199     for (unsigned r1=0; r1<row-1; ++r1) {
1200         int indx = pivot(r1);
1201         if (indx==-1)
1202             return 0;  // Note: leaves *this in a messy state.
1203         if (indx>0)
1204             sign = -sign;
1205         if (r1>0)
1206             divisor = this->m[(r1-1)*col+(r1-1)].expand();
1207         for (unsigned r2=r1+1; r2<row; ++r2) {
1208             for (unsigned c=r1+1; c<col; ++c) {
1209                 dividend = (this->m[r1*col+r1]*this->m[r2*col+c]
1210                            -this->m[r2*col+r1]*this->m[r1*col+c]).expand();
1211 #ifdef DO_GINAC_ASSERT
1212                 GINAC_ASSERT(divide(dividend.to_rational(srl),
1213                                     divisor.to_rational(srl),
1214                                     this->m[r2*col+c]));
1215 #else
1216                 divide(dividend.to_rational(srl),
1217                        divisor.to_rational(srl),
1218                        this->m[r2*col+c]);
1219 #endif // DO_GINAC_ASSERT
1220                 this->m[r2*col+c] = this->m[r2*col+c].subs(srl);
1221             }
1222             for (unsigned c=0; c<=r1; ++c)
1223                 this->m[r2*col+c] = _ex0();
1224         }
1225     }
1226     
1227     return sign;
1228 }
1229
1230
1231 /** Partial pivoting method.
1232  *  Usual pivoting (symbolic==false) returns the index to the element with the
1233  *  largest absolute value in column ro and swaps the current row with the one
1234  *  where the element was found.  With (symbolic==true) it does the same thing
1235  *  with the first non-zero element.
1236  *
1237  *  @param ro is the row to be inspected
1238  *  @param symbolic signal if we want the first non-zero element to be pivoted
1239  *  (true) or the one with the largest absolute value (false).
1240  *  @return 0 if no interchange occured, -1 if all are zero (usually signaling
1241  *  a degeneracy) and positive integer k means that rows ro and k were swapped.
1242  */
1243 int matrix::pivot(unsigned ro, bool symbolic)
1244 {
1245     unsigned k = ro;
1246     
1247     if (symbolic) {  // search first non-zero
1248         for (unsigned r=ro; r<row; ++r) {
1249             if (!m[r*col+ro].is_zero()) {
1250                 k = r;
1251                 break;
1252             }
1253         }
1254     } else {  // search largest
1255         numeric tmp(0);
1256         numeric maxn(-1);
1257         for (unsigned r=ro; r<row; ++r) {
1258             GINAC_ASSERT(is_ex_of_type(m[r*col+ro],numeric));
1259             if ((tmp = abs(ex_to_numeric(m[r*col+ro]))) > maxn &&
1260                 !tmp.is_zero()) {
1261                 maxn = tmp;
1262                 k = r;
1263             }
1264         }
1265     }
1266     if (m[k*col+ro].is_zero())
1267         return -1;
1268     if (k!=ro) {  // swap rows
1269         ensure_if_modifiable();
1270         for (unsigned c=0; c<col; ++c) {
1271             m[k*col+c].swap(m[ro*col+c]);
1272         }
1273         return k;
1274     }
1275     return 0;
1276 }
1277
1278 /** Convert list of lists to matrix. */
1279 ex lst_to_matrix(const ex &l)
1280 {
1281         if (!is_ex_of_type(l, lst))
1282                 throw(std::invalid_argument("argument to lst_to_matrix() must be a lst"));
1283
1284         // Find number of rows and columns
1285         unsigned rows = l.nops(), cols = 0, i, j;
1286         for (i=0; i<rows; i++)
1287                 if (l.op(i).nops() > cols)
1288                         cols = l.op(i).nops();
1289
1290         // Allocate and fill matrix
1291         matrix &m = *new matrix(rows, cols);
1292         for (i=0; i<rows; i++)
1293                 for (j=0; j<cols; j++)
1294                         if (l.op(i).nops() > j)
1295                                 m.set(i, j, l.op(i).op(j));
1296                         else
1297                                 m.set(i, j, ex(0));
1298         return m;
1299 }
1300
1301 //////////
1302 // global constants
1303 //////////
1304
1305 const matrix some_matrix;
1306 const type_info & typeid_matrix=typeid(some_matrix);
1307
1308 #ifndef NO_NAMESPACE_GINAC
1309 } // namespace GiNaC
1310 #endif // ndef NO_NAMESPACE_GINAC