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