]> www.ginac.de Git - ginac.git/blob - ginac/matrix.cpp
43288df46ab90ecd6c6ad6fc13c12dd7915839af
[ginac.git] / ginac / matrix.cpp
1 /** @file matrix.cpp
2  *
3  *  Implementation of symbolic matrices */
4
5 /*
6  *  GiNaC Copyright (C) 1999 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 <stdexcept>
25
26 #include "matrix.h"
27 #include "debugmsg.h"
28
29 #ifndef NO_GINAC_NAMESPACE
30 namespace GiNaC {
31 #endif // ndef NO_GINAC_NAMESPACE
32
33 //////////
34 // default constructor, destructor, copy constructor, assignment operator
35 // and helpers:
36 //////////
37
38 // public
39
40 /** Default ctor.  Initializes to 1 x 1-dimensional zero-matrix. */
41 matrix::matrix()
42     : basic(TINFO_matrix), row(1), col(1)
43 {
44     debugmsg("matrix default constructor",LOGLEVEL_CONSTRUCT);
45     m.push_back(exZERO());
46 }
47
48 matrix::~matrix()
49 {
50     debugmsg("matrix destructor",LOGLEVEL_DESTRUCT);
51 }
52
53 matrix::matrix(matrix const & other)
54 {
55     debugmsg("matrix copy constructor",LOGLEVEL_CONSTRUCT);
56     copy(other);
57 }
58
59 matrix const & matrix::operator=(matrix const & other)
60 {
61     debugmsg("matrix operator=",LOGLEVEL_ASSIGNMENT);
62     if (this != &other) {
63         destroy(1);
64         copy(other);
65     }
66     return *this;
67 }
68
69 // protected
70
71 void matrix::copy(matrix const & other)
72 {
73     basic::copy(other);
74     row=other.row;
75     col=other.col;
76     m=other.m;  // use STL's vector copying
77 }
78
79 void matrix::destroy(bool call_parent)
80 {
81     if (call_parent) basic::destroy(call_parent);
82 }
83
84 //////////
85 // other constructors
86 //////////
87
88 // public
89
90 /** Very common ctor.  Initializes to r x c-dimensional zero-matrix.
91  *
92  *  @param r number of rows
93  *  @param c number of cols */
94 matrix::matrix(int r, int c)
95     : basic(TINFO_matrix), row(r), col(c)
96 {
97     debugmsg("matrix constructor from int,int",LOGLEVEL_CONSTRUCT);
98     m.resize(r*c, exZERO());
99 }
100
101 // protected
102
103 /** Ctor from representation, for internal use only. */
104 matrix::matrix(int r, int c, vector<ex> const & m2)
105     : basic(TINFO_matrix), row(r), col(c), m(m2)
106 {
107     debugmsg("matrix constructor from int,int,vector<ex>",LOGLEVEL_CONSTRUCT);
108 }
109
110 //////////
111 // functions overriding virtual functions from bases classes
112 //////////
113
114 // public
115
116 basic * matrix::duplicate() const
117 {
118     debugmsg("matrix duplicate",LOGLEVEL_DUPLICATE);
119     return new matrix(*this);
120 }
121
122 /** nops is defined to be rows x columns. */
123 int matrix::nops() const
124 {
125     return row*col;
126 }
127
128 /** returns matrix entry at position (i/col, i%col). */
129 ex & matrix::let_op(int const i)
130 {
131     return m[i];
132 }
133
134 /** expands the elements of a matrix entry by entry. */
135 ex matrix::expand(unsigned options) const
136 {
137     vector<ex> tmp(row*col);
138     for (int i=0; i<row*col; ++i) {
139         tmp[i]=m[i].expand(options);
140     }
141     return matrix(row, col, tmp);
142 }
143
144 /** Search ocurrences.  A matrix 'has' an expression if it is the expression
145  *  itself or one of the elements 'has' it. */
146 bool matrix::has(ex const & other) const
147 {
148     GINAC_ASSERT(other.bp!=0);
149     
150     // tautology: it is the expression itself
151     if (is_equal(*other.bp)) return true;
152     
153     // search all the elements
154     for (vector<ex>::const_iterator r=m.begin(); r!=m.end(); ++r) {
155         if ((*r).has(other)) return true;
156     }
157     return false;
158 }
159
160 /** evaluate matrix entry by entry. */
161 ex matrix::eval(int level) const
162 {
163     debugmsg("matrix eval",LOGLEVEL_MEMBER_FUNCTION);
164     
165     // check if we have to do anything at all
166     if ((level==1)&&(flags & status_flags::evaluated)) {
167         return *this;
168     }
169     
170     // emergency break
171     if (level == -max_recursion_level) {
172         throw (std::runtime_error("matrix::eval(): recursion limit exceeded"));
173     }
174     
175     // eval() entry by entry
176     vector<ex> m2(row*col);
177     --level;    
178     for (int r=0; r<row; ++r) {
179         for (int c=0; c<col; ++c) {
180             m2[r*col+c] = m[r*col+c].eval(level);
181         }
182     }
183     
184     return (new matrix(row, col, m2))->setflag(status_flags::dynallocated |
185                                                status_flags::evaluated );
186 }
187
188 /** evaluate matrix numerically entry by entry. */
189 ex matrix::evalf(int level) const
190 {
191     debugmsg("matrix evalf",LOGLEVEL_MEMBER_FUNCTION);
192         
193     // check if we have to do anything at all
194     if (level==1) {
195         return *this;
196     }
197     
198     // emergency break
199     if (level == -max_recursion_level) {
200         throw (std::runtime_error("matrix::evalf(): recursion limit exceeded"));
201     }
202     
203     // evalf() entry by entry
204     vector<ex> m2(row*col);
205     --level;
206     for (int r=0; r<row; ++r) {
207         for (int c=0; c<col; ++c) {
208             m2[r*col+c] = m[r*col+c].evalf(level);
209         }
210     }
211     return matrix(row, col, m2);
212 }
213
214 // protected
215
216 int matrix::compare_same_type(basic const & other) const
217 {
218     GINAC_ASSERT(is_exactly_of_type(other, matrix));
219     matrix const & o=static_cast<matrix &>(const_cast<basic &>(other));
220     
221     // compare number of rows
222     if (row != o.rows()) {
223         return row < o.rows() ? -1 : 1;
224     }
225     
226     // compare number of columns
227     if (col != o.cols()) {
228         return col < o.cols() ? -1 : 1;
229     }
230     
231     // equal number of rows and columns, compare individual elements
232     int cmpval;
233     for (int r=0; r<row; ++r) {
234         for (int c=0; c<col; ++c) {
235             cmpval=((*this)(r,c)).compare(o(r,c));
236             if (cmpval!=0) return cmpval;
237         }
238     }
239     // all elements are equal => matrices are equal;
240     return 0;
241 }
242
243 //////////
244 // non-virtual functions in this class
245 //////////
246
247 // public
248
249 /** Sum of matrices.
250  *
251  *  @exception logic_error (incompatible matrices) */
252 matrix matrix::add(matrix const & other) const
253 {
254     if (col != other.col || row != other.row) {
255         throw (std::logic_error("matrix::add(): incompatible matrices"));
256     }
257     
258     vector<ex> sum(this->m);
259     vector<ex>::iterator i;
260     vector<ex>::const_iterator ci;
261     for (i=sum.begin(), ci=other.m.begin();
262          i!=sum.end();
263          ++i, ++ci) {
264         (*i) += (*ci);
265     }
266     return matrix(row,col,sum);
267 }
268
269 /** Difference of matrices.
270  *
271  *  @exception logic_error (incompatible matrices) */
272 matrix matrix::sub(matrix const & other) const
273 {
274     if (col != other.col || row != other.row) {
275         throw (std::logic_error("matrix::sub(): incompatible matrices"));
276     }
277     
278     vector<ex> dif(this->m);
279     vector<ex>::iterator i;
280     vector<ex>::const_iterator ci;
281     for (i=dif.begin(), ci=other.m.begin();
282          i!=dif.end();
283          ++i, ++ci) {
284         (*i) -= (*ci);
285     }
286     return matrix(row,col,dif);
287 }
288
289 /** Product of matrices.
290  *
291  *  @exception logic_error (incompatible matrices) */
292 matrix matrix::mul(matrix const & other) const
293 {
294     if (col != other.row) {
295         throw (std::logic_error("matrix::mul(): incompatible matrices"));
296     }
297     
298     vector<ex> prod(row*other.col);
299     for (int i=0; i<row; ++i) {
300         for (int j=0; j<other.col; ++j) {
301             for (int l=0; l<col; ++l) {
302                 prod[i*other.col+j] += m[i*col+l] * other.m[l*other.col+j];
303             }
304         }
305     }
306     return matrix(row, other.col, prod);
307 }
308
309 /** operator() to access elements.
310  *
311  *  @param ro row of element
312  *  @param co column of element 
313  *  @exception range_error (index out of range) */
314 ex const & matrix::operator() (int ro, int co) const
315 {
316     if (ro<0 || ro>=row || co<0 || co>=col) {
317         throw (std::range_error("matrix::operator(): index out of range"));
318     }
319     
320     return m[ro*col+co];
321 }
322
323 /** Set individual elements manually.
324  *
325  *  @exception range_error (index out of range) */
326 matrix & matrix::set(int ro, int co, ex value)
327 {
328     if (ro<0 || ro>=row || co<0 || co>=col) {
329         throw (std::range_error("matrix::set(): index out of range"));
330     }
331     
332     ensure_if_modifiable();
333     m[ro*col+co]=value;
334     return *this;
335 }
336
337 /** Transposed of an m x n matrix, producing a new n x m matrix object that
338  *  represents the transposed. */
339 matrix matrix::transpose(void) const
340 {
341     vector<ex> trans(col*row);
342     
343     for (int r=0; r<col; ++r) {
344         for (int c=0; c<row; ++c) {
345             trans[r*row+c] = m[c*col+r];
346         }
347     }
348     return matrix(col,row,trans);
349 }
350
351 /* Determiant of purely numeric matrix, using pivoting. This routine is only
352  * called internally by matrix::determinant(). */
353 ex determinant_numeric(const matrix & M)
354 {
355     GINAC_ASSERT(M.rows()==M.cols());  // cannot happen, just in case...
356     matrix tmp(M);
357     ex det=exONE();
358     ex piv;
359     
360     for (int r1=0; r1<M.rows(); ++r1) {
361         int indx = tmp.pivot(r1);
362         if (indx == -1) {
363             return exZERO();
364         }
365         if (indx != 0) {
366             det *= exMINUSONE();
367         }
368         det = det * tmp.m[r1*M.cols()+r1];
369         for (int r2=r1+1; r2<M.rows(); ++r2) {
370             piv = tmp.m[r2*M.cols()+r1] / tmp.m[r1*M.cols()+r1];
371             for (int c=r1+1; c<M.cols(); c++) {
372                 tmp.m[r2*M.cols()+c] -= piv * tmp.m[r1*M.cols()+c];
373             }
374         }
375     }
376     return det;
377 }
378
379 // Compute the sign of a permutation of a vector of things, used internally
380 // by determinant_symbolic_perm() where it is instantiated for int.
381 template <class T>
382 int permutation_sign(vector<T> s)
383 {
384     if (s.size() < 2)
385         return 0;
386     int sigma=1;
387     for (typename vector<T>::iterator i=s.begin(); i!=s.end()-1; ++i) {
388         for (typename vector<T>::iterator j=i+1; j!=s.end(); ++j) {
389             if (*i == *j)
390                 return 0;
391             if (*i > *j) {
392                 iter_swap(i,j);
393                 sigma = -sigma;
394             }
395         }
396     }
397     return sigma;
398 }
399
400 /** Determinant built by application of the full permutation group. This
401  *  routine is only called internally by matrix::determinant(). */
402 ex determinant_symbolic_perm(const matrix & M)
403 {
404     GINAC_ASSERT(M.rows()==M.cols());  // cannot happen, just in case...
405     
406     if (M.rows()==1) {  // speed things up
407         return M(0,0);
408     }
409     
410     ex det;
411     ex term;
412     vector<int> sigma(M.cols());
413     for (int i=0; i<M.cols(); ++i) sigma[i]=i;
414     
415     do {
416         term = M(sigma[0],0);
417         for (int i=1; i<M.cols(); ++i) term *= M(sigma[i],i);
418         det += permutation_sign(sigma)*term;
419     } while (next_permutation(sigma.begin(), sigma.end()));
420     
421     return det;
422 }
423
424 /** Recursive determiant for small matrices having at least one symbolic entry.
425  *  This algorithm is also known as Laplace-expansion. This routine is only
426  *  called internally by matrix::determinant(). */
427 ex determinant_symbolic_minor(const matrix & M)
428 {
429     GINAC_ASSERT(M.rows()==M.cols());  // cannot happen, just in case...
430     
431     if (M.rows()==1) {  // end of recursion
432         return M(0,0);
433     }
434     if (M.rows()==2) {  // speed things up
435         return (M(0,0)*M(1,1)-
436                 M(1,0)*M(0,1));
437     }
438     if (M.rows()==3) {  // speed things up even a little more
439         return ((M(2,1)*M(0,2)-M(2,2)*M(0,1))*M(1,0)+
440                 (M(1,2)*M(0,1)-M(1,1)*M(0,2))*M(2,0)+
441                 (M(2,2)*M(1,1)-M(2,1)*M(1,2))*M(0,0));
442     }
443     
444     ex det;
445     matrix minorM(M.rows()-1,M.cols()-1);
446     for (int r1=0; r1<M.rows(); ++r1) {
447         // assemble the minor matrix
448         for (int r=0; r<minorM.rows(); ++r) {
449             for (int c=0; c<minorM.cols(); ++c) {
450                 if (r<r1) {
451                     minorM.set(r,c,M(r,c+1));
452                 } else {
453                     minorM.set(r,c,M(r+1,c+1));
454                 }
455             }
456         }
457         // recurse down
458         if (r1%2) {
459             det -= M(r1,0) * determinant_symbolic_minor(minorM);
460         } else {
461             det += M(r1,0) * determinant_symbolic_minor(minorM);
462         }
463     }
464     return det;
465 }
466
467 /*  Leverrier algorithm for large matrices having at least one symbolic entry.
468  *  This routine is only called internally by matrix::determinant(). The
469  *  algorithm is deemed bad for symbolic matrices since it returns expressions
470  *  that are very hard to canonicalize. */
471 /*ex determinant_symbolic_leverrier(const matrix & M)
472  *{
473  *    GINAC_ASSERT(M.rows()==M.cols());  // cannot happen, just in case...
474  *    
475  *    matrix B(M);
476  *    matrix I(M.row, M.col);
477  *    ex c=B.trace();
478  *    for (int i=1; i<M.row; ++i) {
479  *        for (int j=0; j<M.row; ++j)
480  *            I.m[j*M.col+j] = c;
481  *        B = M.mul(B.sub(I));
482  *        c = B.trace()/ex(i+1);
483  *    }
484  *    if (M.row%2) {
485  *        return c;
486  *    } else {
487  *        return -c;
488  *    }
489  *}*/
490
491 /** Determinant of square matrix.  This routine doesn't actually calculate the
492  *  determinant, it only implements some heuristics about which algorithm to
493  *  call.  When the parameter for normalization is explicitly turned off this
494  *  method does not normalize its result at the end, which might imply that
495  *  the symbolic 2x2 matrix [[a/(a-b),1],[b/(a-b),1]] is not immediatly
496  *  recognized to be unity.  (This is Mathematica's default behaviour, it
497  *  should be used with care.)
498  *
499  *  @param     normalized may be set to false if no normalization of the
500  *             result is desired (i.e. to force Mathematica behavior, Maple
501  *             does normalize the result).
502  *  @return    the determinant as a new expression
503  *  @exception logic_error (matrix not square) */
504 ex matrix::determinant(bool normalized) const
505 {
506     if (row != col) {
507         throw (std::logic_error("matrix::determinant(): matrix not square"));
508     }
509
510     // check, if there are non-numeric entries in the matrix:
511     for (vector<ex>::const_iterator r=m.begin(); r!=m.end(); ++r) {
512         if (!(*r).info(info_flags::numeric)) {
513             if (normalized) {
514                 return determinant_symbolic_minor(*this).normal();
515             } else {
516                 return determinant_symbolic_perm(*this);
517             }
518         }
519     }
520     // if it turns out that all elements are numeric
521     return determinant_numeric(*this);
522 }
523
524 /** Trace of a matrix.
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     }
533     
534     ex tr;
535     for (int r=0; r<col; ++r) {
536         tr += m[r*col+r];
537     }
538     return tr;
539 }
540
541 /** Characteristic Polynomial.  The characteristic polynomial of a matrix M is
542  *  defined as the determiant of (M - lambda * 1) where 1 stands for the unit
543  *  matrix of the same dimension as M.  This method returns the characteristic
544  *  polynomial as a new expression.
545  *
546  *  @return    characteristic polynomial as new expression
547  *  @exception logic_error (matrix not square)
548  *  @see       matrix::determinant() */
549 ex matrix::charpoly(ex const & lambda) const
550 {
551     if (row != col) {
552         throw (std::logic_error("matrix::charpoly(): matrix not square"));
553     }
554     
555     matrix M(*this);
556     for (int r=0; r<col; ++r) {
557         M.m[r*col+r] -= lambda;
558     }
559     return (M.determinant());
560 }
561
562 /** Inverse of this matrix.
563  *
564  *  @return    the inverted matrix
565  *  @exception logic_error (matrix not square)
566  *  @exception runtime_error (singular matrix) */
567 matrix matrix::inverse(void) const
568 {
569     if (row != col) {
570         throw (std::logic_error("matrix::inverse(): matrix not square"));
571     }
572     
573     matrix tmp(row,col);
574     // set tmp to the unit matrix
575     for (int i=0; i<col; ++i) {
576         tmp.m[i*col+i] = exONE();
577     }
578     // create a copy of this matrix
579     matrix cpy(*this);
580     for (int 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 (int 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 (int c=0; c<col; ++c) {
592             cpy.m[r1*col+c] /= a1;
593             tmp.m[r1*col+c] /= a1;
594         }
595         for (int r2=0; r2<row; ++r2) {
596             if (r2 != r1) {
597                 ex a2 = cpy.m[r2*col+r1];
598                 for (int 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 void matrix::ffe_swap(int r1, int c1, int r2 ,int c2)
609 {
610     ensure_if_modifiable();
611     
612     ex tmp=ffe_get(r1,c1);
613     ffe_set(r1,c1,ffe_get(r2,c2));
614     ffe_set(r2,c2,tmp);
615 }
616
617 void matrix::ffe_set(int r, int c, ex e)
618 {
619     set(r-1,c-1,e);
620 }
621
622 ex matrix::ffe_get(int r, int c) const
623 {
624     return operator()(r-1,c-1);
625 }
626
627 /** Solve a set of equations for an m x n matrix by fraction-free Gaussian
628  *  elimination. Based on algorithm 9.1 from 'Algorithms for Computer Algebra'
629  *  by Keith O. Geddes et al.
630  *
631  *  @param vars n x p matrix
632  *  @param rhs m x p matrix
633  *  @exception logic_error (incompatible matrices)
634  *  @exception runtime_error (singular matrix) */
635 matrix matrix::fraction_free_elim(matrix const & vars,
636                                   matrix const & rhs) const
637 {
638     if ((row != rhs.row) || (col != vars.row) || (rhs.col != vars.col)) {
639         throw (std::logic_error("matrix::solve(): incompatible matrices"));
640     }
641     
642     matrix a(*this); // make a copy of the matrix
643     matrix b(rhs);     // make a copy of the rhs vector
644     
645     // given an m x n matrix a, reduce it to upper echelon form
646     int m=a.row;
647     int n=a.col;
648     int sign=1;
649     ex divisor=1;
650     int r=1;
651     
652     // eliminate below row r, with pivot in column k
653     for (int k=1; (k<=n)&&(r<=m); ++k) {
654         // find a nonzero pivot
655         int p;
656         for (p=r; (p<=m)&&(a.ffe_get(p,k).is_equal(exZERO())); ++p) {}
657         // pivot is in row p
658         if (p<=m) {
659             if (p!=r) {
660                 // switch rows p and r
661                 for (int j=k; j<=n; ++j) {
662                     a.ffe_swap(p,j,r,j);
663                 }
664                 b.ffe_swap(p,1,r,1);
665                 // keep track of sign changes due to row exchange
666                 sign=-sign;
667             }
668             for (int i=r+1; i<=m; ++i) {
669                 for (int j=k+1; j<=n; ++j) {
670                     a.ffe_set(i,j,(a.ffe_get(r,k)*a.ffe_get(i,j)
671                                   -a.ffe_get(r,j)*a.ffe_get(i,k))/divisor);
672                     a.ffe_set(i,j,a.ffe_get(i,j).normal() /*.normal() */ );
673                 }
674                 b.ffe_set(i,1,(a.ffe_get(r,k)*b.ffe_get(i,1)
675                               -b.ffe_get(r,1)*a.ffe_get(i,k))/divisor);
676                 b.ffe_set(i,1,b.ffe_get(i,1).normal() /*.normal() */ );
677                 a.ffe_set(i,k,0);
678             }
679             divisor=a.ffe_get(r,k);
680             r++;
681         }
682     }
683     // optionally compute the determinant for square or augmented matrices
684     // if (r==m+1) { det=sign*divisor; } else { det=0; }
685     
686     /*
687     for (int r=1; r<=m; ++r) {
688         for (int c=1; c<=n; ++c) {
689             cout << a.ffe_get(r,c) << "\t";
690         }
691         cout << " | " <<  b.ffe_get(r,1) << endl;
692     }
693     */
694     
695 #ifdef DO_GINAC_ASSERT
696     // test if we really have an upper echelon matrix
697     int zero_in_last_row=-1;
698     for (int r=1; r<=m; ++r) {
699         int zero_in_this_row=0;
700         for (int c=1; c<=n; ++c) {
701             if (a.ffe_get(r,c).is_equal(exZERO())) {
702                zero_in_this_row++;
703             } else {
704                 break;
705             }
706         }
707         GINAC_ASSERT((zero_in_this_row>zero_in_last_row)||(zero_in_this_row=n));
708         zero_in_last_row=zero_in_this_row;
709     }
710 #endif // def DO_GINAC_ASSERT
711     
712     // assemble solution
713     matrix sol(n,1);
714     int last_assigned_sol=n+1;
715     for (int r=m; r>0; --r) {
716         int first_non_zero=1;
717         while ((first_non_zero<=n)&&(a.ffe_get(r,first_non_zero).is_zero())) {
718             first_non_zero++;
719         }
720         if (first_non_zero>n) {
721             // row consists only of zeroes, corresponding rhs must be 0 as well
722             if (!b.ffe_get(r,1).is_zero()) {
723                 throw (std::runtime_error("matrix::fraction_free_elim(): singular matrix"));
724             }
725         } else {
726             // assign solutions for vars between first_non_zero+1 and
727             // last_assigned_sol-1: free parameters
728             for (int c=first_non_zero+1; c<=last_assigned_sol-1; ++c) {
729                 sol.ffe_set(c,1,vars.ffe_get(c,1));
730             }
731             ex e=b.ffe_get(r,1);
732             for (int c=first_non_zero+1; c<=n; ++c) {
733                 e=e-a.ffe_get(r,c)*sol.ffe_get(c,1);
734             }
735             sol.ffe_set(first_non_zero,1,
736                         (e/a.ffe_get(r,first_non_zero)).normal());
737             last_assigned_sol=first_non_zero;
738         }
739     }
740     // assign solutions for vars between 1 and
741     // last_assigned_sol-1: free parameters
742     for (int c=1; c<=last_assigned_sol-1; ++c) {
743         sol.ffe_set(c,1,vars.ffe_get(c,1));
744     }
745
746     /*
747     for (int c=1; c<=n; ++c) {
748         cout << vars.ffe_get(c,1) << "->" << sol.ffe_get(c,1) << endl;
749     }
750     */
751     
752 #ifdef DO_GINAC_ASSERT
753     // test solution with echelon matrix
754     for (int r=1; r<=m; ++r) {
755         ex e=0;
756         for (int c=1; c<=n; ++c) {
757             e=e+a.ffe_get(r,c)*sol.ffe_get(c,1);
758         }
759         if (!(e-b.ffe_get(r,1)).normal().is_zero()) {
760             cout << "e=" << e;
761             cout << "b.ffe_get(" << r<<",1)=" << b.ffe_get(r,1) << endl;
762             cout << "diff=" << (e-b.ffe_get(r,1)).normal() << endl;
763         }
764         GINAC_ASSERT((e-b.ffe_get(r,1)).normal().is_zero());
765     }
766
767     // test solution with original matrix
768     for (int r=1; r<=m; ++r) {
769         ex e=0;
770         for (int c=1; c<=n; ++c) {
771             e=e+ffe_get(r,c)*sol.ffe_get(c,1);
772         }
773         try {
774         if (!(e-rhs.ffe_get(r,1)).normal().is_zero()) {
775             cout << "e=" << e << endl;
776             e.printtree(cout);
777             ex en=e.normal();
778             cout << "e.normal()=" << en << endl;
779             en.printtree(cout);
780             cout << "rhs.ffe_get(" << r<<",1)=" << rhs.ffe_get(r,1) << endl;
781             cout << "diff=" << (e-rhs.ffe_get(r,1)).normal() << endl;
782         }
783         } catch (...) {
784             ex xxx=e-rhs.ffe_get(r,1);
785             cerr << "xxx=" << xxx << endl << endl;
786         }
787         GINAC_ASSERT((e-rhs.ffe_get(r,1)).normal().is_zero());
788     }
789 #endif // def DO_GINAC_ASSERT
790     
791     return sol;
792 }   
793     
794 /** Solve simultaneous set of equations. */
795 matrix matrix::solve(matrix const & v) const
796 {
797     if (!(row == col && col == v.row)) {
798         throw (std::logic_error("matrix::solve(): incompatible matrices"));
799     }
800     
801     // build the extended matrix of *this with v attached to the right
802     matrix tmp(row,col+v.col);
803     for (int r=0; r<row; ++r) {
804         for (int c=0; c<col; ++c) {
805             tmp.m[r*tmp.col+c] = m[r*col+c];
806         }
807         for (int c=0; c<v.col; ++c) {
808             tmp.m[r*tmp.col+c+col] = v.m[r*v.col+c];
809         }
810     }
811     for (int r1=0; r1<row; ++r1) {
812         int indx = tmp.pivot(r1);
813         if (indx == -1) {
814             throw (std::runtime_error("matrix::solve(): singular matrix"));
815         }
816         for (int c=r1; c<tmp.col; ++c) {
817             tmp.m[r1*tmp.col+c] /= tmp.m[r1*tmp.col+r1];
818         }
819         for (int r2=r1+1; r2<row; ++r2) {
820             for (int c=r1; c<tmp.col; ++c) {
821                 tmp.m[r2*tmp.col+c]
822                     -= tmp.m[r2*tmp.col+r1] * tmp.m[r1*tmp.col+c];
823             }
824         }
825     }
826     
827     // assemble the solution matrix
828     vector<ex> sol(v.row*v.col);
829     for (int c=0; c<v.col; ++c) {
830         for (int r=col-1; r>=0; --r) {
831             sol[r*v.col+c] = tmp[r*tmp.col+c];
832             for (int i=r+1; i<col; ++i) {
833                 sol[r*v.col+c]
834                     -= tmp[r*tmp.col+i] * sol[i*v.col+c];
835             }
836         }
837     }
838     return matrix(v.row, v.col, sol);
839 }
840
841 // protected
842
843 /** Partial pivoting method.
844  *  Usual pivoting returns the index to the element with the largest absolute
845  *  value and swaps the current row with the one where the element was found.
846  *  Here it does the same with the first non-zero element. (This works fine,
847  *  but may be far from optimal for numerics.) */
848 int matrix::pivot(int ro)
849 {
850     int k=ro;
851     
852     for (int r=ro; r<row; ++r) {
853         if (!m[r*col+ro].is_zero()) {
854             k = r;
855             break;
856         }
857     }
858     if (m[k*col+ro].is_zero()) {
859         return -1;
860     }
861     if (k!=ro) {  // swap rows
862         for (int c=0; c<col; ++c) {
863             m[k*col+c].swap(m[ro*col+c]);
864         }
865         return k;
866     }
867     return 0;
868 }
869
870 //////////
871 // global constants
872 //////////
873
874 const matrix some_matrix;
875 type_info const & typeid_matrix=typeid(some_matrix);
876
877 #ifndef NO_GINAC_NAMESPACE
878 } // namespace GiNaC
879 #endif // ndef NO_GINAC_NAMESPACE