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