]> www.ginac.de Git - ginac.git/blob - ginac/matrix.cpp
c5d056c205fb002e53defba3a77a225b14945f54
[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         if (!(*r).info(info_flags::numeric))
466             numeric_flag = false;
467         if ((*r).info(info_flags::rational_function) &&
468             !(*r).info(info_flags::crational_polynomial))
469             normal_flag = true;
470     }
471     
472     if (numeric_flag)  // purely numeric matrix
473         return determinant_numeric();
474     // Does anybody really know when a matrix is sparse?
475     // Maybe <~row/2.2 nonzero elements average in a row?
476     if (5*sparse_count<=row*col) {
477         // copy *this:
478         matrix tmp(*this);
479         int sign;
480         sign = tmp.fraction_free_elimination(true);
481         if (normal_flag)
482             return (sign*tmp.m[row*col-1]).normal();
483         else
484             return (sign*tmp.m[row*col-1]).expand();
485     }
486     
487     // Now come the minor expansion schemes.  We always develop such that the
488     // smallest minors (i.e, the trivial 1x1 ones) are on the rightmost column.
489     // For this to be efficient it turns out that the emptiest columns (i.e.
490     // the ones with most zeros) should be the ones on the right hand side.
491     // Therefore we presort the columns of the matrix:
492     typedef pair<unsigned,unsigned> uintpair;  // # of zeros, column
493     vector<uintpair> c_zeros;  // number of zeros in column
494     for (unsigned c=0; c<col; ++c) {
495         unsigned acc = 0;
496         for (unsigned r=0; r<row; ++r)
497             if (m[r*col+c].is_zero())
498                 ++acc;
499         c_zeros.push_back(uintpair(acc,c));
500     }
501     sort(c_zeros.begin(),c_zeros.end());
502     vector<unsigned> pre_sort;  // unfortunately vector<uintpair> can't be used
503                                 // for permutation_sign.
504     for (vector<uintpair>::iterator i=c_zeros.begin(); i!=c_zeros.end(); ++i)
505         pre_sort.push_back(i->second);
506     int sign = permutation_sign(pre_sort);
507     exvector result(row*col);  // represents sorted matrix
508     unsigned c = 0;
509     for (vector<unsigned>::iterator i=pre_sort.begin();
510          i!=pre_sort.end();
511          ++i,++c) {
512         for (unsigned r=0; r<row; ++r)
513             result[r*col+c] = m[r*col+(*i)];
514     }
515     
516     if (normal_flag)
517         return sign*matrix(row,col,result).determinant_minor().normal();
518     return sign*matrix(row,col,result).determinant_minor();
519 }
520
521
522 /** Trace of a matrix.  The result is normalized if it is in some quotient
523  *  field and expanded only otherwise.  This implies that the trace of the
524  *  symbolic 2x2 matrix [[a/(a-b),x],[y,b/(b-a)]] is recognized to be unity.
525  *
526  *  @return    the sum of diagonal elements
527  *  @exception logic_error (matrix not square) */
528 ex matrix::trace(void) const
529 {
530     if (row != col)
531         throw (std::logic_error("matrix::trace(): matrix not square"));
532     GINAC_ASSERT(row*col==m.capacity());
533     
534     ex tr;
535     for (unsigned r=0; r<col; ++r)
536         tr += m[r*col+r];
537     
538     if (tr.info(info_flags::rational_function) &&
539         !tr.info(info_flags::crational_polynomial))
540         return tr.normal();
541     else
542         return tr.expand();
543 }
544
545
546 /** Characteristic Polynomial.  Following mathematica notation the
547  *  characteristic polynomial of a matrix M is defined as the determiant of
548  *  (M - lambda * 1) where 1 stands for the unit matrix of the same dimension
549  *  as M.  Note that some CASs define it with a sign inside the determinant
550  *  which gives rise to an overall sign if the dimension is odd.  This method
551  *  returns the characteristic polynomial collected in powers of lambda as a
552  *  new expression.
553  *
554  *  @return    characteristic polynomial as new expression
555  *  @exception logic_error (matrix not square)
556  *  @see       matrix::determinant() */
557 ex matrix::charpoly(const symbol & lambda) const
558 {
559     if (row != col)
560         throw (std::logic_error("matrix::charpoly(): matrix not square"));
561     
562     bool numeric_flag = true;
563     for (exvector::const_iterator r=m.begin(); r!=m.end(); ++r) {
564         if (!(*r).info(info_flags::numeric)) {
565             numeric_flag = false;
566         }
567     }
568     
569     // The pure numeric case is traditionally rather common.  Hence, it is
570     // trapped and we use Leverrier's algorithm which goes as row^3 for
571     // every coefficient.  The expensive part is the matrix multiplication.
572     if (numeric_flag) {
573         matrix B(*this);
574         ex c = B.trace();
575         ex poly = power(lambda,row)-c*power(lambda,row-1);
576         for (unsigned i=1; i<row; ++i) {
577             for (unsigned j=0; j<row; ++j)
578                 B.m[j*col+j] -= c;
579             B = this->mul(B);
580             c = B.trace()/ex(i+1);
581             poly -= c*power(lambda,row-i-1);
582         }
583         if (row%2)
584             return -poly;
585         else
586             return poly;
587     }
588     
589     matrix M(*this);
590     for (unsigned r=0; r<col; ++r)
591         M.m[r*col+r] -= lambda;
592     
593     return M.determinant().collect(lambda);
594 }
595
596
597 /** Inverse of this matrix.
598  *
599  *  @return    the inverted matrix
600  *  @exception logic_error (matrix not square)
601  *  @exception runtime_error (singular matrix) */
602 matrix matrix::inverse(void) const
603 {
604     if (row != col)
605         throw (std::logic_error("matrix::inverse(): matrix not square"));
606     
607     matrix tmp(row,col);
608     // set tmp to the unit matrix
609     for (unsigned i=0; i<col; ++i)
610         tmp.m[i*col+i] = _ex1();
611
612     // create a copy of this matrix
613     matrix cpy(*this);
614     for (unsigned r1=0; r1<row; ++r1) {
615         int indx = cpy.pivot(r1);
616         if (indx == -1) {
617             throw (std::runtime_error("matrix::inverse(): singular matrix"));
618         }
619         if (indx != 0) {  // swap rows r and indx of matrix tmp
620             for (unsigned i=0; i<col; ++i) {
621                 tmp.m[r1*col+i].swap(tmp.m[indx*col+i]);
622             }
623         }
624         ex a1 = cpy.m[r1*col+r1];
625         for (unsigned c=0; c<col; ++c) {
626             cpy.m[r1*col+c] /= a1;
627             tmp.m[r1*col+c] /= a1;
628         }
629         for (unsigned r2=0; r2<row; ++r2) {
630             if (r2 != r1) {
631                 ex a2 = cpy.m[r2*col+r1];
632                 for (unsigned c=0; c<col; ++c) {
633                     cpy.m[r2*col+c] -= a2 * cpy.m[r1*col+c];
634                     tmp.m[r2*col+c] -= a2 * tmp.m[r1*col+c];
635                 }
636             }
637         }
638     }
639     return tmp;
640 }
641
642
643 // superfluous helper function
644 void matrix::ffe_swap(unsigned r1, unsigned c1, unsigned r2 ,unsigned c2)
645 {
646     ensure_if_modifiable();
647     
648     ex tmp = ffe_get(r1,c1);
649     ffe_set(r1,c1,ffe_get(r2,c2));
650     ffe_set(r2,c2,tmp);
651 }
652
653 // superfluous helper function
654 void matrix::ffe_set(unsigned r, unsigned c, ex e)
655 {
656     set(r-1,c-1,e);
657 }
658
659 // superfluous helper function
660 ex matrix::ffe_get(unsigned r, unsigned c) const
661 {
662     return operator()(r-1,c-1);
663 }
664
665 /** Solve a set of equations for an m x n matrix by fraction-free Gaussian
666  *  elimination.  Based on algorithm 9.1 from 'Algorithms for Computer Algebra'
667  *  by Keith O. Geddes et al.
668  *
669  *  @param vars n x p matrix
670  *  @param rhs m x p matrix
671  *  @exception logic_error (incompatible matrices)
672  *  @exception runtime_error (singular matrix) */
673 matrix matrix::fraction_free_elim(const matrix & vars,
674                                   const matrix & rhs) const
675 {
676     // FIXME: use implementation of matrix::fraction_free_elimination
677     if ((row != rhs.row) || (col != vars.row) || (rhs.col != vars.col))
678         throw (std::logic_error("matrix::fraction_free_elim(): incompatible matrices"));
679     
680     matrix a(*this);  // make a copy of the matrix
681     matrix b(rhs);    // make a copy of the rhs vector
682     
683     // given an m x n matrix a, reduce it to upper echelon form
684     unsigned m = a.row;
685     unsigned n = a.col;
686     int sign = 1;
687     ex divisor = 1;
688     unsigned r = 1;
689     
690     // eliminate below row r, with pivot in column k
691     for (unsigned k=1; (k<=n)&&(r<=m); ++k) {
692         // find a nonzero pivot
693         unsigned p;
694         for (p=r; (p<=m)&&(a.ffe_get(p,k).is_equal(_ex0())); ++p) {}
695         // pivot is in row p
696         if (p<=m) {
697             if (p!=r) {
698                 // switch rows p and r
699                 for (unsigned j=k; j<=n; ++j)
700                     a.ffe_swap(p,j,r,j);
701                 b.ffe_swap(p,1,r,1);
702                 // keep track of sign changes due to row exchange
703                 sign = -sign;
704             }
705             for (unsigned i=r+1; i<=m; ++i) {
706                 for (unsigned j=k+1; j<=n; ++j) {
707                     a.ffe_set(i,j,(a.ffe_get(r,k)*a.ffe_get(i,j)
708                                   -a.ffe_get(r,j)*a.ffe_get(i,k))/divisor);
709                     a.ffe_set(i,j,a.ffe_get(i,j).normal() /*.normal() */ );
710                 }
711                 b.ffe_set(i,1,(a.ffe_get(r,k)*b.ffe_get(i,1)
712                               -b.ffe_get(r,1)*a.ffe_get(i,k))/divisor);
713                 b.ffe_set(i,1,b.ffe_get(i,1).normal() /*.normal() */ );
714                 a.ffe_set(i,k,0);
715             }
716             divisor = a.ffe_get(r,k);
717             r++;
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 #ifdef DO_GINAC_ASSERT
728     // test if we really have an upper echelon matrix
729     int zero_in_last_row = -1;
730     for (unsigned r=1; r<=m; ++r) {
731         int zero_in_this_row=0;
732         for (unsigned c=1; c<=n; ++c) {
733             if (a.ffe_get(r,c).is_zero())
734                zero_in_this_row++;
735             else
736                 break;
737         }
738         GINAC_ASSERT((zero_in_this_row>zero_in_last_row)||(zero_in_this_row=n));
739         zero_in_last_row = zero_in_this_row;
740     }
741 #endif // def DO_GINAC_ASSERT
742     
743     // assemble solution
744     matrix sol(n,1);
745     unsigned last_assigned_sol = n+1;
746     for (unsigned r=m; r>0; --r) {
747         unsigned first_non_zero = 1;
748         while ((first_non_zero<=n)&&(a.ffe_get(r,first_non_zero).is_zero()))
749             first_non_zero++;
750         if (first_non_zero>n) {
751             // row consists only of zeroes, corresponding rhs must be 0 as well
752             if (!b.ffe_get(r,1).is_zero()) {
753                 throw (std::runtime_error("matrix::fraction_free_elim(): singular matrix"));
754             }
755         } else {
756             // assign solutions for vars between first_non_zero+1 and
757             // last_assigned_sol-1: free parameters
758             for (unsigned c=first_non_zero+1; c<=last_assigned_sol-1; ++c) {
759                 sol.ffe_set(c,1,vars.ffe_get(c,1));
760             }
761             ex e = b.ffe_get(r,1);
762             for (unsigned c=first_non_zero+1; c<=n; ++c) {
763                 e=e-a.ffe_get(r,c)*sol.ffe_get(c,1);
764             }
765             sol.ffe_set(first_non_zero,1,
766                         (e/a.ffe_get(r,first_non_zero)).normal());
767             last_assigned_sol = first_non_zero;
768         }
769     }
770     // assign solutions for vars between 1 and
771     // last_assigned_sol-1: free parameters
772     for (unsigned c=1; c<=last_assigned_sol-1; ++c)
773         sol.ffe_set(c,1,vars.ffe_get(c,1));
774     
775 #ifdef DO_GINAC_ASSERT
776     // test solution with echelon matrix
777     for (unsigned r=1; r<=m; ++r) {
778         ex e = 0;
779         for (unsigned c=1; c<=n; ++c)
780             e = e+a.ffe_get(r,c)*sol.ffe_get(c,1);
781         if (!(e-b.ffe_get(r,1)).normal().is_zero()) {
782             cout << "e=" << e;
783             cout << "b.ffe_get(" << r<<",1)=" << b.ffe_get(r,1) << endl;
784             cout << "diff=" << (e-b.ffe_get(r,1)).normal() << endl;
785         }
786         GINAC_ASSERT((e-b.ffe_get(r,1)).normal().is_zero());
787     }
788     
789     // test solution with original matrix
790     for (unsigned r=1; r<=m; ++r) {
791         ex e = 0;
792         for (unsigned c=1; c<=n; ++c)
793             e = e+ffe_get(r,c)*sol.ffe_get(c,1);
794         try {
795             if (!(e-rhs.ffe_get(r,1)).normal().is_zero()) {
796                 cout << "e=" << e << endl;
797                 e.printtree(cout);
798                 ex en = e.normal();
799                 cout << "e.normal()=" << en << endl;
800                 en.printtree(cout);
801                 cout << "rhs.ffe_get(" << r<<",1)=" << rhs.ffe_get(r,1) << endl;
802                 cout << "diff=" << (e-rhs.ffe_get(r,1)).normal() << endl;
803             }
804         } catch (...) {
805             ex xxx = e - rhs.ffe_get(r,1);
806             cerr << "xxx=" << xxx << endl << endl;
807         }
808         GINAC_ASSERT((e-rhs.ffe_get(r,1)).normal().is_zero());
809     }
810 #endif // def DO_GINAC_ASSERT
811     
812     return sol;
813 }
814
815 /** Solve a set of equations for an m x n matrix.
816  *
817  *  @param vars n x p matrix
818  *  @param rhs m x p matrix
819  *  @exception logic_error (incompatible matrices)
820  *  @exception runtime_error (singular matrix) */
821 matrix matrix::solve(const matrix & vars,
822                      const matrix & rhs) const
823 {
824     if ((row != rhs.row) || (col != vars.row) || (rhs.col != vars.col))
825         throw (std::logic_error("matrix::solve(): incompatible matrices"));
826     
827     throw (std::runtime_error("FIXME: need implementation."));
828 }
829
830 /** Old and obsolete interface: */
831 matrix matrix::old_solve(const matrix & v) const
832 {
833     if ((v.row != col) || (col != v.row))
834         throw (std::logic_error("matrix::solve(): incompatible matrices"));
835     
836     // build the augmented matrix of *this with v attached to the right
837     matrix tmp(row,col+v.col);
838     for (unsigned r=0; r<row; ++r) {
839         for (unsigned c=0; c<col; ++c)
840             tmp.m[r*tmp.col+c] = this->m[r*col+c];
841         for (unsigned c=0; c<v.col; ++c)
842             tmp.m[r*tmp.col+c+col] = v.m[r*v.col+c];
843     }
844     // cout << "augmented: " << tmp << endl;
845     tmp.gauss_elimination();
846     // cout << "degaussed: " << tmp << endl;
847     // assemble the solution matrix
848     exvector sol(v.row*v.col);
849     for (unsigned c=0; c<v.col; ++c) {
850         for (unsigned r=row; r>0; --r) {
851             for (unsigned i=r; i<col; ++i)
852                 sol[(r-1)*v.col+c] -= tmp.m[(r-1)*tmp.col+i]*sol[i*v.col+c];
853             sol[(r-1)*v.col+c] += tmp.m[(r-1)*tmp.col+col+c];
854             sol[(r-1)*v.col+c] = (sol[(r-1)*v.col+c]/tmp.m[(r-1)*tmp.col+(r-1)]).normal();
855         }
856     }
857     return matrix(v.row, v.col, sol);
858 }
859
860
861 // protected
862
863 /** Determinant of purely numeric matrix, using pivoting.
864  *
865  *  @see       matrix::determinant() */
866 ex matrix::determinant_numeric(void) const
867 {
868     matrix tmp(*this);
869     ex det = _ex1();
870     ex piv;
871     
872     // standard Gauss method:
873     for (unsigned r1=0; r1<row; ++r1) {
874         int indx = tmp.pivot(r1);
875         if (indx == -1)
876             return _ex0();
877         if (indx != 0)
878             det *= _ex_1();
879         det = det * tmp.m[r1*col+r1];
880         for (unsigned r2=r1+1; r2<row; ++r2) {
881             piv = tmp.m[r2*col+r1] / tmp.m[r1*col+r1];
882             for (unsigned c=r1+1; c<col; c++) {
883                 tmp.m[r2*col+c] -= piv * tmp.m[r1*col+c];
884             }
885         }
886     }
887     
888     return det;
889 }
890
891
892 /** Recursive determinant for small matrices having at least one symbolic
893  *  entry.  The basic algorithm, known as Laplace-expansion, is enhanced by
894  *  some bookkeeping to avoid calculation of the same submatrices ("minors")
895  *  more than once.  According to W.M.Gentleman and S.C.Johnson this algorithm
896  *  is better than elimination schemes for matrices of sparse multivariate
897  *  polynomials and also for matrices of dense univariate polynomials if the
898  *  matrix' dimesion is larger than 7.
899  *
900  *  @return the determinant as a new expression (in expanded form)
901  *  @see matrix::determinant() */
902 ex matrix::determinant_minor(void) const
903 {
904     // for small matrices the algorithm does not make any sense:
905     if (this->row==1)
906         return m[0];
907     if (this->row==2)
908         return (m[0]*m[3]-m[2]*m[1]).expand();
909     if (this->row==3)
910         return (m[0]*m[4]*m[8]-m[0]*m[5]*m[7]-
911                 m[1]*m[3]*m[8]+m[2]*m[3]*m[7]+
912                 m[1]*m[5]*m[6]-m[2]*m[4]*m[6]).expand();
913     
914     // This algorithm can best be understood by looking at a naive
915     // implementation of Laplace-expansion, like this one:
916     // ex det;
917     // matrix minorM(this->row-1,this->col-1);
918     // for (unsigned r1=0; r1<this->row; ++r1) {
919     //     // shortcut if element(r1,0) vanishes
920     //     if (m[r1*col].is_zero())
921     //         continue;
922     //     // assemble the minor matrix
923     //     for (unsigned r=0; r<minorM.rows(); ++r) {
924     //         for (unsigned c=0; c<minorM.cols(); ++c) {
925     //             if (r<r1)
926     //                 minorM.set(r,c,m[r*col+c+1]);
927     //             else
928     //                 minorM.set(r,c,m[(r+1)*col+c+1]);
929     //         }
930     //     }
931     //     // recurse down and care for sign:
932     //     if (r1%2)
933     //         det -= m[r1*col] * minorM.determinant_minor();
934     //     else
935     //         det += m[r1*col] * minorM.determinant_minor();
936     // }
937     // return det.expand();
938     // What happens is that while proceeding down many of the minors are
939     // computed more than once.  In particular, there are binomial(n,k)
940     // kxk minors and each one is computed factorial(n-k) times.  Therefore
941     // it is reasonable to store the results of the minors.  We proceed from
942     // right to left.  At each column c we only need to retrieve the minors
943     // calculated in step c-1.  We therefore only have to store at most 
944     // 2*binomial(n,n/2) minors.
945     
946     // Unique flipper counter for partitioning into minors
947     vector<unsigned> Pkey;
948     Pkey.reserve(this->col);
949     // key for minor determinant (a subpartition of Pkey)
950     vector<unsigned> Mkey;
951     Mkey.reserve(this->col-1);
952     // we store our subminors in maps, keys being the rows they arise from
953     typedef map<vector<unsigned>,class ex> Rmap;
954     typedef map<vector<unsigned>,class ex>::value_type Rmap_value;
955     Rmap A;
956     Rmap B;
957     ex det;
958     // initialize A with last column:
959     for (unsigned r=0; r<this->col; ++r) {
960         Pkey.erase(Pkey.begin(),Pkey.end());
961         Pkey.push_back(r);
962         A.insert(Rmap_value(Pkey,m[this->col*r+this->col-1]));
963     }
964     // proceed from right to left through matrix
965     for (int c=this->col-2; c>=0; --c) {
966         Pkey.erase(Pkey.begin(),Pkey.end());  // don't change capacity
967         Mkey.erase(Mkey.begin(),Mkey.end());
968         for (unsigned i=0; i<this->col-c; ++i)
969             Pkey.push_back(i);
970         unsigned fc = 0;  // controls logic for our strange flipper counter
971         do {
972             det = _ex0();
973             for (unsigned r=0; r<this->col-c; ++r) {
974                 // maybe there is nothing to do?
975                 if (m[Pkey[r]*this->col+c].is_zero())
976                     continue;
977                 // create the sorted key for all possible minors
978                 Mkey.erase(Mkey.begin(),Mkey.end());
979                 for (unsigned i=0; i<this->col-c; ++i)
980                     if (i!=r)
981                         Mkey.push_back(Pkey[i]);
982                 // Fetch the minors and compute the new determinant
983                 if (r%2)
984                     det -= m[Pkey[r]*this->col+c]*A[Mkey];
985                 else
986                     det += m[Pkey[r]*this->col+c]*A[Mkey];
987             }
988             // prevent build-up of deep nesting of expressions saves time:
989             det = det.expand();
990             // store the new determinant at its place in B:
991             if (!det.is_zero())
992                 B.insert(Rmap_value(Pkey,det));
993             // increment our strange flipper counter
994             for (fc=this->col-c; fc>0; --fc) {
995                 ++Pkey[fc-1];
996                 if (Pkey[fc-1]<fc+c)
997                     break;
998             }
999             if (fc<this->col-c)
1000                 for (unsigned j=fc; j<this->col-c; ++j)
1001                     Pkey[j] = Pkey[j-1]+1;
1002         } while(fc);
1003         // next column, so change the role of A and B:
1004         A = B;
1005         B.clear();
1006     }
1007     
1008     return det;
1009 }
1010
1011
1012 /** Perform the steps of an ordinary Gaussian elimination to bring the matrix
1013  *  into an upper echelon form.
1014  *
1015  *  @return sign is 1 if an even number of rows was swapped, -1 if an odd
1016  *  number of rows was swapped and 0 if the matrix is singular. */
1017 int matrix::gauss_elimination(void)
1018 {
1019     int sign = 1;
1020     ensure_if_modifiable();
1021     for (unsigned r1=0; r1<row-1; ++r1) {
1022         int indx = pivot(r1);
1023         if (indx == -1)
1024             return 0;  // Note: leaves *this in a messy state.
1025         if (indx > 0)
1026             sign = -sign;
1027         for (unsigned r2=r1+1; r2<row; ++r2) {
1028             for (unsigned c=r1+1; c<col; ++c)
1029                 this->m[r2*col+c] -= this->m[r2*col+r1]*this->m[r1*col+c]/this->m[r1*col+r1];
1030             for (unsigned c=0; c<=r1; ++c)
1031                 this->m[r2*col+c] = _ex0();
1032         }
1033     }
1034     
1035     return sign;
1036 }
1037
1038
1039 /** Perform the steps of division free elimination to bring the matrix
1040  *  into an upper echelon form.
1041  *
1042  *  @return sign is 1 if an even number of rows was swapped, -1 if an odd
1043  *  number of rows was swapped and 0 if the matrix is singular. */
1044 int matrix::division_free_elimination(void)
1045 {
1046     int sign = 1;
1047     ensure_if_modifiable();
1048     for (unsigned r1=0; r1<row-1; ++r1) {
1049         int indx = pivot(r1);
1050         if (indx==-1)
1051             return 0;  // Note: leaves *this in a messy state.
1052         if (indx>0)
1053             sign = -sign;
1054         for (unsigned r2=r1+1; r2<row; ++r2) {
1055             for (unsigned c=r1+1; c<col; ++c)
1056                 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];
1057             for (unsigned c=0; c<=r1; ++c)
1058                 this->m[r2*col+c] = _ex0();
1059         }
1060     }
1061     
1062     return sign;
1063 }
1064
1065
1066 /** Perform the steps of Bareiss' one-step fraction free elimination to bring
1067  *  the matrix into an upper echelon form.  Fraction free elimination means
1068  *  that divide is used straightforwardly, without computing GCDs first.  This
1069  *  is possible, since we know the divisor at each step.
1070  *  
1071  *  @param det may be set to true to save a lot of space if one is only
1072  *  interested in the last element (i.e. for calculating determinants), the
1073  *  others are set to zero in this case.
1074  *  @return sign is 1 if an even number of rows was swapped, -1 if an odd
1075  *  number of rows was swapped and 0 if the matrix is singular. */
1076 int matrix::fraction_free_elimination(bool det)
1077 {
1078     // Method:
1079     // (single-step fraction free elimination scheme, already known to Jordan)
1080     //
1081     // Usual division-free elimination sets m[0](r,c) = m(r,c) and then sets
1082     //     m[k+1](r,c) = m[k](k,k) * m[k](r,c) - m[k](r,k) * m[k](k,c).
1083     //
1084     // Bareiss (fraction-free) elimination in addition divides that element
1085     // by m[k-1](k-1,k-1) for k>1, where it can be shown by means of the
1086     // Sylvester determinant that this really divides m[k+1](r,c).
1087     //
1088     // We also allow rational functions where the original prove still holds.
1089     // However, we must care for numerator and denominator separately and
1090     // "manually" work in the integral domains because of subtle cancellations
1091     // (see below).  This blows up the bookkeeping a bit and the formula has
1092     // to be modified to expand like this (N{x} stands for numerator of x,
1093     // D{x} for denominator of x):
1094     //     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)}
1095     //                     -N{m[k](r,k)}*N{m[k](k,c)}*D{m[k](k,k)}*D{m[k](r,c)}
1096     //     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)}
1097     // where for k>1 we now divide N{m[k+1](r,c)} by
1098     //     N{m[k-1](k-1,k-1)}
1099     // and D{m[k+1](r,c)} by
1100     //     D{m[k-1](k-1,k-1)}.
1101     
1102     GINAC_ASSERT(det || row==col);
1103     ensure_if_modifiable();
1104     if (rows()==1)
1105         return 1;
1106     
1107     int sign = 1;
1108     ex divisor_n = 1;
1109     ex divisor_d = 1;
1110     ex dividend_n;
1111     ex dividend_d;
1112     
1113     // We populate temporary matrices to subsequently operate on.  There is
1114     // one holding numerators and another holding denominators of entries.
1115     // This is a must since the evaluator (or even earlier mul's constructor)
1116     // might cancel some trivial element which causes divide() to fail.  The
1117     // elements are normalized first (yes, even though this algorithm doesn't
1118     // need GCDs) since the elements of *this might be unnormalized, which
1119     // makes things more complicated than they need to be.
1120     matrix tmp_n(*this);
1121     matrix tmp_d(row,col);  // for denominators, if needed
1122     lst srl;  // symbol replacement list
1123     exvector::iterator it = m.begin();
1124     exvector::iterator tmp_n_it = tmp_n.m.begin();
1125     exvector::iterator tmp_d_it = tmp_d.m.begin();
1126     for (; it!= m.end(); ++it, ++tmp_n_it, ++tmp_d_it) {
1127         (*tmp_n_it) = (*it).normal().to_rational(srl);
1128         (*tmp_d_it) = (*tmp_n_it).denom();
1129         (*tmp_n_it) = (*tmp_n_it).numer();
1130     }
1131     
1132     for (unsigned r1=0; r1<row-1; ++r1) {
1133 //         cout << "==<" << r1 << ">" << string(60,'=') << endl;
1134         int indx = tmp_n.pivot(r1);
1135         if (det && indx==-1)
1136             return 0;  // FIXME: what to do if det is false?
1137         if (indx>0) {
1138             sign = -sign;
1139             // rows r1 and indx were swapped, so pivot matrix tmp_d:
1140             for (unsigned c=0; c<col; ++c)
1141                 tmp_d.m[row*indx+c].swap(tmp_d.m[row*r1+c]);
1142         }
1143 //         cout << tmp_n << endl;
1144 //         cout << tmp_d << endl;
1145         if (r1>0) {
1146             divisor_n = tmp_n.m[(r1-1)*col+(r1-1)].expand();
1147             divisor_d = tmp_d.m[(r1-1)*col+(r1-1)].expand();
1148             // save space by deleting no longer needed elements:
1149             if (det) {
1150                 for (unsigned c=0; c<col; ++c) {
1151                     tmp_n.m[(r1-1)*col+c] = 0;
1152                     tmp_d.m[(r1-1)*col+c] = 1;
1153                 }
1154             }
1155         }
1156         for (unsigned r2=r1+1; r2<row; ++r2) {
1157             for (unsigned c=r1+1; c<col; ++c) {
1158                 dividend_n = (tmp_n.m[r1*col+r1]*tmp_n.m[r2*col+c]*
1159                               tmp_d.m[r2*col+r1]*tmp_d.m[r1*col+c]
1160                              -tmp_n.m[r2*col+r1]*tmp_n.m[r1*col+c]*
1161                               tmp_d.m[r1*col+r1]*tmp_d.m[r2*col+c]).expand();
1162                 dividend_d = (tmp_d.m[r2*col+r1]*tmp_d.m[r1*col+c]*
1163                               tmp_d.m[r1*col+r1]*tmp_d.m[r2*col+c]).expand();
1164 //                 cout << "Element " << r2 << ',' << c << endl;
1165 //                 cout << "dividend_n==" << dividend_n << endl;
1166 //                 cout << "dividend_d==" << dividend_d << endl;
1167 //                 cout << " divisor_n==" << divisor_n << endl;
1168 //                 cout << " divisor_d==" << divisor_d << endl;
1169 //                 cout << string(20,'-') << endl;
1170                 bool check = divide(dividend_n, divisor_n,
1171                                     tmp_n.m[r2*col+c],true);
1172                 check &= divide(dividend_d, divisor_d,
1173                                 tmp_d.m[r2*col+c],true);
1174                 GINAC_ASSERT(check);
1175             }
1176             // fill up left hand side.
1177             for (unsigned c=0; c<=r1; ++c)
1178                 tmp_n.m[r2*col+c] = _ex0();
1179         }
1180 //         cout << tmp_n << endl;
1181 //         cout << tmp_d << endl;        
1182     }
1183     // repopulate *this matrix:
1184     it = m.begin();
1185     tmp_n_it = tmp_n.m.begin();
1186     tmp_d_it = tmp_d.m.begin();
1187     for (; it!= m.end(); ++it, ++tmp_n_it, ++tmp_d_it)
1188         (*it) = ((*tmp_n_it)/(*tmp_d_it)).subs(srl);
1189     
1190     return sign;
1191 }
1192
1193
1194 /** Partial pivoting method.
1195  *  Usual pivoting (symbolic==false) returns the index to the element with the
1196  *  largest absolute value in column ro and swaps the current row with the one
1197  *  where the element was found.  With (symbolic==true) it does the same thing
1198  *  with the first non-zero element.
1199  *
1200  *  @param ro is the row to be inspected
1201  *  @param symbolic signal if we want the first non-zero element to be pivoted
1202  *  (true) or the one with the largest absolute value (false).
1203  *  @return 0 if no interchange occured, -1 if all are zero (usually signaling
1204  *  a degeneracy) and positive integer k means that rows ro and k were swapped.
1205  */
1206 int matrix::pivot(unsigned ro, bool symbolic)
1207 {
1208     unsigned k = ro;
1209     
1210     if (symbolic) {  // search first non-zero
1211         for (unsigned r=ro; r<row; ++r) {
1212             if (!m[r*col+ro].is_zero()) {
1213                 k = r;
1214                 break;
1215             }
1216         }
1217     } else {  // search largest
1218         numeric tmp(0);
1219         numeric maxn(-1);
1220         for (unsigned r=ro; r<row; ++r) {
1221             GINAC_ASSERT(is_ex_of_type(m[r*col+ro],numeric));
1222             if ((tmp = abs(ex_to_numeric(m[r*col+ro]))) > maxn &&
1223                 !tmp.is_zero()) {
1224                 maxn = tmp;
1225                 k = r;
1226             }
1227         }
1228     }
1229     if (m[k*col+ro].is_zero())
1230         return -1;
1231     if (k!=ro) {  // swap rows
1232         ensure_if_modifiable();
1233         for (unsigned c=0; c<col; ++c) {
1234             m[k*col+c].swap(m[ro*col+c]);
1235         }
1236         return k;
1237     }
1238     return 0;
1239 }
1240
1241 /** Convert list of lists to matrix. */
1242 ex lst_to_matrix(const ex &l)
1243 {
1244         if (!is_ex_of_type(l, lst))
1245                 throw(std::invalid_argument("argument to lst_to_matrix() must be a lst"));
1246
1247         // Find number of rows and columns
1248         unsigned rows = l.nops(), cols = 0, i, j;
1249         for (i=0; i<rows; i++)
1250                 if (l.op(i).nops() > cols)
1251                         cols = l.op(i).nops();
1252
1253         // Allocate and fill matrix
1254         matrix &m = *new matrix(rows, cols);
1255         for (i=0; i<rows; i++)
1256                 for (j=0; j<cols; j++)
1257                         if (l.op(i).nops() > j)
1258                                 m.set(i, j, l.op(i).op(j));
1259                         else
1260                                 m.set(i, j, ex(0));
1261         return m;
1262 }
1263
1264 //////////
1265 // global constants
1266 //////////
1267
1268 const matrix some_matrix;
1269 const type_info & typeid_matrix=typeid(some_matrix);
1270
1271 #ifndef NO_NAMESPACE_GINAC
1272 } // namespace GiNaC
1273 #endif // ndef NO_NAMESPACE_GINAC