]> www.ginac.de Git - ginac.git/blob - ginac/matrix.cpp
1f4ed18b0a54e0e29ae2fd69aeb02a666add0c0d
[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     
451     ex det;
452     bool numeric_flag = true;
453     bool normal_flag = false;
454     for (exvector::const_iterator r=m.begin(); r!=m.end(); ++r) {
455         if (!(*r).info(info_flags::numeric))
456             numeric_flag = false;
457         if ((*r).info(info_flags::rational_function) &&
458             !(*r).info(info_flags::crational_polynomial))
459             normal_flag = true;
460     }
461     
462     if (numeric_flag)
463         det = determinant_numeric();
464     else
465         if (normal_flag)
466             det = determinant_minor().normal();
467         else
468             det = determinant_minor(); // is already expanded!
469     
470     return det;
471 }
472
473
474 /** Trace of a matrix.  The result is normalized if it is in some quotient
475  *  field and expanded only otherwise.  This implies that the trace of the
476  *  symbolic 2x2 matrix [[a/(a-b),x],[y,b/(b-a)]] is recognized to be unity.
477  *
478  *  @return    the sum of diagonal elements
479  *  @exception logic_error (matrix not square) */
480 ex matrix::trace(void) const
481 {
482     if (row != col)
483         throw (std::logic_error("matrix::trace(): matrix not square"));
484     GINAC_ASSERT(row*col==m.capacity());
485     
486     ex tr;
487     for (unsigned r=0; r<col; ++r)
488         tr += m[r*col+r];
489     
490     if (tr.info(info_flags::rational_function) &&
491         !tr.info(info_flags::crational_polynomial))
492         return tr.normal();
493     else
494         return tr.expand();
495 }
496
497
498 /** Characteristic Polynomial.  The characteristic polynomial of a matrix M is
499  *  defined as the determiant of (M - lambda * 1) where 1 stands for the unit
500  *  matrix of the same dimension as M.  This method returns the characteristic
501  *  polynomial as a new expression.
502  *
503  *  @return    characteristic polynomial as new expression
504  *  @exception logic_error (matrix not square)
505  *  @see       matrix::determinant() */
506 ex matrix::charpoly(const ex & lambda) const
507 {
508     if (row != col)
509         throw (std::logic_error("matrix::charpoly(): matrix not square"));
510     
511     matrix M(*this);
512     for (unsigned r=0; r<col; ++r)
513         M.m[r*col+r] -= lambda;
514     
515     return (M.determinant());
516 }
517
518
519 /** Inverse of this matrix.
520  *
521  *  @return    the inverted matrix
522  *  @exception logic_error (matrix not square)
523  *  @exception runtime_error (singular matrix) */
524 matrix matrix::inverse(void) const
525 {
526     if (row != col)
527         throw (std::logic_error("matrix::inverse(): matrix not square"));
528     
529     matrix tmp(row,col);
530     // set tmp to the unit matrix
531     for (unsigned i=0; i<col; ++i)
532         tmp.m[i*col+i] = _ex1();
533
534     // create a copy of this matrix
535     matrix cpy(*this);
536     for (unsigned r1=0; r1<row; ++r1) {
537         int indx = cpy.pivot(r1);
538         if (indx == -1) {
539             throw (std::runtime_error("matrix::inverse(): singular matrix"));
540         }
541         if (indx != 0) {  // swap rows r and indx of matrix tmp
542             for (unsigned i=0; i<col; ++i) {
543                 tmp.m[r1*col+i].swap(tmp.m[indx*col+i]);
544             }
545         }
546         ex a1 = cpy.m[r1*col+r1];
547         for (unsigned c=0; c<col; ++c) {
548             cpy.m[r1*col+c] /= a1;
549             tmp.m[r1*col+c] /= a1;
550         }
551         for (unsigned r2=0; r2<row; ++r2) {
552             if (r2 != r1) {
553                 ex a2 = cpy.m[r2*col+r1];
554                 for (unsigned c=0; c<col; ++c) {
555                     cpy.m[r2*col+c] -= a2 * cpy.m[r1*col+c];
556                     tmp.m[r2*col+c] -= a2 * tmp.m[r1*col+c];
557                 }
558             }
559         }
560     }
561     return tmp;
562 }
563
564
565 // superfluous helper function
566 void matrix::ffe_swap(unsigned r1, unsigned c1, unsigned r2 ,unsigned c2)
567 {
568     ensure_if_modifiable();
569     
570     ex tmp = ffe_get(r1,c1);
571     ffe_set(r1,c1,ffe_get(r2,c2));
572     ffe_set(r2,c2,tmp);
573 }
574
575 // superfluous helper function
576 void matrix::ffe_set(unsigned r, unsigned c, ex e)
577 {
578     set(r-1,c-1,e);
579 }
580
581 // superfluous helper function
582 ex matrix::ffe_get(unsigned r, unsigned c) const
583 {
584     return operator()(r-1,c-1);
585 }
586
587 /** Solve a set of equations for an m x n matrix by fraction-free Gaussian
588  *  elimination.  Based on algorithm 9.1 from 'Algorithms for Computer Algebra'
589  *  by Keith O. Geddes et al.
590  *
591  *  @param vars n x p matrix
592  *  @param rhs m x p matrix
593  *  @exception logic_error (incompatible matrices)
594  *  @exception runtime_error (singular matrix) */
595 matrix matrix::fraction_free_elim(const matrix & vars,
596                                   const matrix & rhs) const
597 {
598     // FIXME: implement a Sasaki-Murao scheme which avoids division at all!
599     if ((row != rhs.row) || (col != vars.row) || (rhs.col != vars.col))
600         throw (std::logic_error("matrix::fraction_free_elim(): incompatible matrices"));
601     
602     matrix a(*this);  // make a copy of the matrix
603     matrix b(rhs);    // make a copy of the rhs vector
604     
605     // given an m x n matrix a, reduce it to upper echelon form
606     unsigned m = a.row;
607     unsigned n = a.col;
608     int sign = 1;
609     ex divisor = 1;
610     unsigned r = 1;
611     
612     // eliminate below row r, with pivot in column k
613     for (unsigned k=1; (k<=n)&&(r<=m); ++k) {
614         // find a nonzero pivot
615         unsigned p;
616         for (p=r; (p<=m)&&(a.ffe_get(p,k).is_equal(_ex0())); ++p) {}
617         // pivot is in row p
618         if (p<=m) {
619             if (p!=r) {
620                 // switch rows p and r
621                 for (unsigned j=k; j<=n; ++j)
622                     a.ffe_swap(p,j,r,j);
623                 b.ffe_swap(p,1,r,1);
624                 // keep track of sign changes due to row exchange
625                 sign = -sign;
626             }
627             for (unsigned i=r+1; i<=m; ++i) {
628                 for (unsigned j=k+1; j<=n; ++j) {
629                     a.ffe_set(i,j,(a.ffe_get(r,k)*a.ffe_get(i,j)
630                                   -a.ffe_get(r,j)*a.ffe_get(i,k))/divisor);
631                     a.ffe_set(i,j,a.ffe_get(i,j).normal() /*.normal() */ );
632                 }
633                 b.ffe_set(i,1,(a.ffe_get(r,k)*b.ffe_get(i,1)
634                               -b.ffe_get(r,1)*a.ffe_get(i,k))/divisor);
635                 b.ffe_set(i,1,b.ffe_get(i,1).normal() /*.normal() */ );
636                 a.ffe_set(i,k,0);
637             }
638             divisor = a.ffe_get(r,k);
639             r++;
640         }
641     }
642     // optionally compute the determinant for square or augmented matrices
643     // if (r==m+1) { det = sign*divisor; } else { det = 0; }
644     
645     /*
646     for (unsigned r=1; r<=m; ++r) {
647         for (unsigned c=1; c<=n; ++c) {
648             cout << a.ffe_get(r,c) << "\t";
649         }
650         cout << " | " <<  b.ffe_get(r,1) << endl;
651     }
652     */
653     
654 #ifdef DO_GINAC_ASSERT
655     // test if we really have an upper echelon matrix
656     int zero_in_last_row = -1;
657     for (unsigned r=1; r<=m; ++r) {
658         int zero_in_this_row=0;
659         for (unsigned c=1; c<=n; ++c) {
660             if (a.ffe_get(r,c).is_equal(_ex0()))
661                zero_in_this_row++;
662             else
663                 break;
664         }
665         GINAC_ASSERT((zero_in_this_row>zero_in_last_row)||(zero_in_this_row=n));
666         zero_in_last_row = zero_in_this_row;
667     }
668 #endif // def DO_GINAC_ASSERT
669     
670     /*
671     cout << "after" << endl;
672     cout << "a=" << a << endl;
673     cout << "b=" << b << endl;
674     */
675     
676     // assemble solution
677     matrix sol(n,1);
678     unsigned last_assigned_sol = n+1;
679     for (unsigned r=m; r>0; --r) {
680         unsigned first_non_zero = 1;
681         while ((first_non_zero<=n)&&(a.ffe_get(r,first_non_zero).is_zero()))
682             first_non_zero++;
683         if (first_non_zero>n) {
684             // row consists only of zeroes, corresponding rhs must be 0 as well
685             if (!b.ffe_get(r,1).is_zero()) {
686                 throw (std::runtime_error("matrix::fraction_free_elim(): singular matrix"));
687             }
688         } else {
689             // assign solutions for vars between first_non_zero+1 and
690             // last_assigned_sol-1: free parameters
691             for (unsigned c=first_non_zero+1; c<=last_assigned_sol-1; ++c) {
692                 sol.ffe_set(c,1,vars.ffe_get(c,1));
693             }
694             ex e = b.ffe_get(r,1);
695             for (unsigned c=first_non_zero+1; c<=n; ++c) {
696                 e=e-a.ffe_get(r,c)*sol.ffe_get(c,1);
697             }
698             sol.ffe_set(first_non_zero,1,
699                         (e/a.ffe_get(r,first_non_zero)).normal());
700             last_assigned_sol = first_non_zero;
701         }
702     }
703     // assign solutions for vars between 1 and
704     // last_assigned_sol-1: free parameters
705     for (unsigned c=1; c<=last_assigned_sol-1; ++c)
706         sol.ffe_set(c,1,vars.ffe_get(c,1));
707     
708 #ifdef DO_GINAC_ASSERT
709     // test solution with echelon matrix
710     for (unsigned r=1; r<=m; ++r) {
711         ex e = 0;
712         for (unsigned c=1; c<=n; ++c)
713             e = e+a.ffe_get(r,c)*sol.ffe_get(c,1);
714         if (!(e-b.ffe_get(r,1)).normal().is_zero()) {
715             cout << "e=" << e;
716             cout << "b.ffe_get(" << r<<",1)=" << b.ffe_get(r,1) << endl;
717             cout << "diff=" << (e-b.ffe_get(r,1)).normal() << endl;
718         }
719         GINAC_ASSERT((e-b.ffe_get(r,1)).normal().is_zero());
720     }
721     
722     // test solution with original matrix
723     for (unsigned r=1; r<=m; ++r) {
724         ex e = 0;
725         for (unsigned c=1; c<=n; ++c)
726             e = e+ffe_get(r,c)*sol.ffe_get(c,1);
727         try {
728             if (!(e-rhs.ffe_get(r,1)).normal().is_zero()) {
729                 cout << "e=" << e << endl;
730                 e.printtree(cout);
731                 ex en = e.normal();
732                 cout << "e.normal()=" << en << endl;
733                 en.printtree(cout);
734                 cout << "rhs.ffe_get(" << r<<",1)=" << rhs.ffe_get(r,1) << endl;
735                 cout << "diff=" << (e-rhs.ffe_get(r,1)).normal() << endl;
736             }
737         } catch (...) {
738             ex xxx = e - rhs.ffe_get(r,1);
739             cerr << "xxx=" << xxx << endl << endl;
740         }
741         GINAC_ASSERT((e-rhs.ffe_get(r,1)).normal().is_zero());
742     }
743 #endif // def DO_GINAC_ASSERT
744     
745     return sol;
746 }
747
748 /** Solve a set of equations for an m x n matrix.
749  *
750  *  @param vars n x p matrix
751  *  @param rhs m x p matrix
752  *  @exception logic_error (incompatible matrices)
753  *  @exception runtime_error (singular matrix) */
754 matrix matrix::solve(const matrix & vars,
755                      const matrix & rhs) const
756 {
757     if ((row != rhs.row) || (col != vars.row) || (rhs.col != vars.col))
758         throw (std::logic_error("matrix::solve(): incompatible matrices"));
759     
760     throw (std::runtime_error("FIXME: need implementation."));
761 }
762
763 /** Old and obsolete interface: */
764 matrix matrix::old_solve(const matrix & v) const
765 {
766     if ((v.row != col) || (col != v.row))
767         throw (std::logic_error("matrix::solve(): incompatible matrices"));
768     
769     // build the augmented matrix of *this with v attached to the right
770     matrix tmp(row,col+v.col);
771     for (unsigned r=0; r<row; ++r) {
772         for (unsigned c=0; c<col; ++c)
773             tmp.m[r*tmp.col+c] = this->m[r*col+c];
774         for (unsigned c=0; c<v.col; ++c)
775             tmp.m[r*tmp.col+c+col] = v.m[r*v.col+c];
776     }
777     // cout << "augmented: " << tmp << endl;
778     tmp.gauss_elimination();
779     // cout << "degaussed: " << tmp << endl;
780     // assemble the solution matrix
781     exvector sol(v.row*v.col);
782     for (unsigned c=0; c<v.col; ++c) {
783         for (unsigned r=row; r>0; --r) {
784             for (unsigned i=r; i<col; ++i)
785                 sol[(r-1)*v.col+c] -= tmp.m[(r-1)*tmp.col+i]*sol[i*v.col+c];
786             sol[(r-1)*v.col+c] += tmp.m[(r-1)*tmp.col+col+c];
787             sol[(r-1)*v.col+c] = (sol[(r-1)*v.col+c]/tmp.m[(r-1)*tmp.col+(r-1)]).normal();
788         }
789     }
790     return matrix(v.row, v.col, sol);
791 }
792
793
794 // protected
795
796 /** Determinant of purely numeric matrix, using pivoting.
797  *
798  *  @see       matrix::determinant() */
799 ex matrix::determinant_numeric(void) const
800 {
801     matrix tmp(*this);
802     ex det = _ex1();
803     ex piv;
804     
805     for (unsigned r1=0; r1<row; ++r1) {
806         int indx = tmp.pivot(r1);
807         if (indx == -1)
808             return _ex0();
809         if (indx != 0)
810             det *= _ex_1();
811         det = det * tmp.m[r1*col+r1];
812         for (unsigned r2=r1+1; r2<row; ++r2) {
813             piv = tmp.m[r2*col+r1] / tmp.m[r1*col+r1];
814             for (unsigned c=r1+1; c<col; c++) {
815                 tmp.m[r2*col+c] -= piv * tmp.m[r1*col+c];
816             }
817         }
818     }
819     
820     return det;
821 }
822
823
824 /*  Leverrier algorithm for large matrices having at least one symbolic entry.
825  *  This routine is only called internally by matrix::determinant(). The
826  *  algorithm is very bad for symbolic matrices since it returns expressions
827  *  that are quite hard to expand. */
828 /*ex matrix::determinant_leverrier(const matrix & M)
829  *{
830  *    GINAC_ASSERT(M.rows()==M.cols());  // cannot happen, just in case...
831  *    
832  *    matrix B(M);
833  *    matrix I(M.row, M.col);
834  *    ex c=B.trace();
835  *    for (unsigned i=1; i<M.row; ++i) {
836  *        for (unsigned j=0; j<M.row; ++j)
837  *            I.m[j*M.col+j] = c;
838  *        B = M.mul(B.sub(I));
839  *        c = B.trace()/ex(i+1);
840  *    }
841  *    if (M.row%2) {
842  *        return c;
843  *    } else {
844  *        return -c;
845  *    }
846  *}*/
847
848
849 /** Recursive determinant for small matrices having at least one symbolic
850  *  entry.  The basic algorithm, known as Laplace-expansion, is enhanced by
851  *  some bookkeeping to avoid calculation of the same submatrices ("minors")
852  *  more than once.  According to W.M.Gentleman and S.C.Johnson this algorithm
853  *  is better than elimination schemes for matrices of sparse multivariate
854  *  polynomials and also for matrices of dense univariate polynomials if the
855  *  matrix' dimesion is larger than 7.
856  *
857  *  @return the determinant as a new expression (in expanded form)
858  *  @see matrix::determinant() */
859 ex matrix::determinant_minor(void) const
860 {
861     // for small matrices the algorithm does not make any sense:
862     if (this->row==1)
863         return m[0];
864     if (this->row==2)
865         return (m[0]*m[3]-m[2]*m[1]).expand();
866     if (this->row==3)
867         return (m[0]*m[4]*m[8]-m[0]*m[5]*m[7]-
868                 m[1]*m[3]*m[8]+m[2]*m[3]*m[7]+
869                 m[1]*m[5]*m[6]-m[2]*m[4]*m[6]).expand();
870     
871     // This algorithm can best be understood by looking at a naive
872     // implementation of Laplace-expansion, like this one:
873     // ex det;
874     // matrix minorM(this->row-1,this->col-1);
875     // for (unsigned r1=0; r1<this->row; ++r1) {
876     //     // shortcut if element(r1,0) vanishes
877     //     if (m[r1*col].is_zero())
878     //         continue;
879     //     // assemble the minor matrix
880     //     for (unsigned r=0; r<minorM.rows(); ++r) {
881     //         for (unsigned c=0; c<minorM.cols(); ++c) {
882     //             if (r<r1)
883     //                 minorM.set(r,c,m[r*col+c+1]);
884     //             else
885     //                 minorM.set(r,c,m[(r+1)*col+c+1]);
886     //         }
887     //     }
888     //     // recurse down and care for sign:
889     //     if (r1%2)
890     //         det -= m[r1*col] * minorM.determinant_minor();
891     //     else
892     //         det += m[r1*col] * minorM.determinant_minor();
893     // }
894     // return det.expand();
895     // What happens is that while proceeding down many of the minors are
896     // computed more than once.  In particular, there are binomial(n,k)
897     // kxk minors and each one is computed factorial(n-k) times.  Therefore
898     // it is reasonable to store the results of the minors.  We proceed from
899     // right to left.  At each column c we only need to retrieve the minors
900     // calculated in step c-1.  We therefore only have to store at most 
901     // 2*binomial(n,n/2) minors.
902     
903     // Unique flipper counter for partitioning into minors
904     vector<unsigned> Pkey;
905     Pkey.reserve(this->col);
906     // key for minor determinant (a subpartition of Pkey)
907     vector<unsigned> Mkey;
908     Mkey.reserve(this->col-1);
909     // we store our subminors in maps, keys being the rows they arise from
910     typedef map<vector<unsigned>,class ex> Rmap;
911     typedef map<vector<unsigned>,class ex>::value_type Rmap_value;
912     Rmap A;
913     Rmap B;
914     ex det;
915     // initialize A with last column:
916     for (unsigned r=0; r<this->col; ++r) {
917         Pkey.erase(Pkey.begin(),Pkey.end());
918         Pkey.push_back(r);
919         A.insert(Rmap_value(Pkey,m[this->col*r+this->col-1]));
920     }
921     // proceed from right to left through matrix
922     for (int c=this->col-2; c>=0; --c) {
923         Pkey.erase(Pkey.begin(),Pkey.end());  // don't change capacity
924         Mkey.erase(Mkey.begin(),Mkey.end());
925         for (unsigned i=0; i<this->col-c; ++i)
926             Pkey.push_back(i);
927         unsigned fc = 0;  // controls logic for our strange flipper counter
928         do {
929             A.insert(Rmap_value(Pkey,_ex0()));
930             det = _ex0();
931             for (unsigned r=0; r<this->col-c; ++r) {
932                 // maybe there is nothing to do?
933                 if (m[Pkey[r]*this->col+c].is_zero())
934                     continue;
935                 // create the sorted key for all possible minors
936                 Mkey.erase(Mkey.begin(),Mkey.end());
937                 for (unsigned i=0; i<this->col-c; ++i)
938                     if (i!=r)
939                         Mkey.push_back(Pkey[i]);
940                 // Fetch the minors and compute the new determinant
941                 if (r%2)
942                     det -= m[Pkey[r]*this->col+c]*A[Mkey];
943                 else
944                     det += m[Pkey[r]*this->col+c]*A[Mkey];
945             }
946             // prevent build-up of deep nesting of expressions saves time:
947             det = det.expand();
948             // store the new determinant at its place in B:
949             B.insert(Rmap_value(Pkey,det));
950             // increment our strange flipper counter
951             for (fc=this->col-c; fc>0; --fc) {
952                 ++Pkey[fc-1];
953                 if (Pkey[fc-1]<fc+c)
954                     break;
955             }
956             if (fc<this->col-c)
957                 for (unsigned j=fc; j<this->col-c; ++j)
958                     Pkey[j] = Pkey[j-1]+1;
959         } while(fc);
960         // next column, so change the role of A and B:
961         A = B;
962         B.clear();
963     }
964     
965     return det;
966 }
967
968
969 /** Determinant built by application of the full permutation group.  This
970  *  routine is only called internally by matrix::determinant(). */
971 ex matrix::determinant_perm(void) const
972 {
973     if (rows()==1)  // speed things up
974         return m[0];
975     
976     ex det;
977     ex term;
978     vector<unsigned> sigma(col);
979     for (unsigned i=0; i<col; ++i)
980         sigma[i]=i;
981     
982     do {
983         term = (*this)(sigma[0],0);
984         for (unsigned i=1; i<col; ++i)
985             term *= (*this)(sigma[i],i);
986         det += permutation_sign(sigma)*term;
987     } while (next_permutation(sigma.begin(), sigma.end()));
988     
989     return det;
990 }
991
992
993 /** Perform the steps of an ordinary Gaussian elimination to bring the matrix
994  *  into an upper echelon form.
995  *
996  *  @return sign is 1 if an even number of rows was swapped, -1 if an odd
997  *  number of rows was swapped and 0 if the matrix is singular. */
998 int matrix::gauss_elimination(void)
999 {
1000     int sign = 1;
1001     ensure_if_modifiable();
1002     for (unsigned r1=0; r1<row-1; ++r1) {
1003         int indx = pivot(r1);
1004         if (indx == -1)
1005             return 0;  // Note: leaves *this in a messy state.
1006         if (indx > 0)
1007             sign = -sign;
1008         for (unsigned r2=r1+1; r2<row; ++r2) {
1009             for (unsigned c=r1+1; c<col; ++c)
1010                 this->m[r2*col+c] -= this->m[r2*col+r1]*this->m[r1*col+c]/this->m[r1*col+r1];
1011             for (unsigned c=0; c<=r1; ++c)
1012                 this->m[r2*col+c] = _ex0();
1013         }
1014     }
1015     
1016     return sign;
1017 }
1018
1019
1020 /** Partial pivoting method.
1021  *  Usual pivoting (symbolic==false) returns the index to the element with the
1022  *  largest absolute value in column ro and swaps the current row with the one
1023  *  where the element was found.  With (symbolic==true) it does the same thing
1024  *  with the first non-zero element.
1025  *
1026  *  @param ro is the row to be inspected
1027  *  @param symbolic signal if we want the first non-zero element to be pivoted
1028  *  (true) or the one with the largest absolute value (false).
1029  *  @return 0 if no interchange occured, -1 if all are zero (usually signaling
1030  *  a degeneracy) and positive integer k means that rows ro and k were swapped.
1031  */
1032 int matrix::pivot(unsigned ro, bool symbolic)
1033 {
1034     unsigned k = ro;
1035     
1036     if (symbolic) {  // search first non-zero
1037         for (unsigned r=ro; r<row; ++r) {
1038             if (!m[r*col+ro].is_zero()) {
1039                 k = r;
1040                 break;
1041             }
1042         }
1043     } else {  // search largest
1044         numeric tmp(0);
1045         numeric maxn(-1);
1046         for (unsigned r=ro; r<row; ++r) {
1047             GINAC_ASSERT(is_ex_of_type(m[r*col+ro],numeric));
1048             if ((tmp = abs(ex_to_numeric(m[r*col+ro]))) > maxn &&
1049                 !tmp.is_zero()) {
1050                 maxn = tmp;
1051                 k = r;
1052             }
1053         }
1054     }
1055     if (m[k*col+ro].is_zero())
1056         return -1;
1057     if (k!=ro) {  // swap rows
1058         ensure_if_modifiable();
1059         for (unsigned c=0; c<col; ++c) {
1060             m[k*col+c].swap(m[ro*col+c]);
1061         }
1062         return k;
1063     }
1064     return 0;
1065 }
1066
1067 //////////
1068 // global constants
1069 //////////
1070
1071 const matrix some_matrix;
1072 const type_info & typeid_matrix=typeid(some_matrix);
1073
1074 #ifndef NO_NAMESPACE_GINAC
1075 } // namespace GiNaC
1076 #endif // ndef NO_NAMESPACE_GINAC