3 * Implementation of symbolic matrices */
6 * GiNaC Copyright (C) 1999 Johannes Gutenberg University Mainz, Germany
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.
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.
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
29 #ifndef NO_GINAC_NAMESPACE
31 #endif // ndef NO_GINAC_NAMESPACE
34 // default constructor, destructor, copy constructor, assignment operator
40 /** Default ctor. Initializes to 1 x 1-dimensional zero-matrix. */
42 : basic(TINFO_matrix), row(1), col(1)
44 debugmsg("matrix default constructor",LOGLEVEL_CONSTRUCT);
45 m.push_back(exZERO());
50 debugmsg("matrix destructor",LOGLEVEL_DESTRUCT);
53 matrix::matrix(matrix const & other)
55 debugmsg("matrix copy constructor",LOGLEVEL_CONSTRUCT);
59 matrix const & matrix::operator=(matrix const & other)
61 debugmsg("matrix operator=",LOGLEVEL_ASSIGNMENT);
71 void matrix::copy(matrix const & other)
76 m=other.m; // use STL's vector copying
79 void matrix::destroy(bool call_parent)
81 if (call_parent) basic::destroy(call_parent);
90 /** Very common ctor. Initializes to r x c-dimensional zero-matrix.
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)
97 debugmsg("matrix constructor from int,int",LOGLEVEL_CONSTRUCT);
98 m.resize(r*c, exZERO());
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)
107 debugmsg("matrix constructor from int,int,vector<ex>",LOGLEVEL_CONSTRUCT);
111 // functions overriding virtual functions from bases classes
116 basic * matrix::duplicate() const
118 debugmsg("matrix duplicate",LOGLEVEL_DUPLICATE);
119 return new matrix(*this);
122 /** nops is defined to be rows x columns. */
123 int matrix::nops() const
128 /** returns matrix entry at position (i/col, i%col). */
129 ex & matrix::let_op(int const i)
134 /** expands the elements of a matrix entry by entry. */
135 ex matrix::expand(unsigned options) const
137 vector<ex> tmp(row*col);
138 for (int i=0; i<row*col; ++i) {
139 tmp[i]=m[i].expand(options);
141 return matrix(row, col, tmp);
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
148 GINAC_ASSERT(other.bp!=0);
150 // tautology: it is the expression itself
151 if (is_equal(*other.bp)) return true;
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;
160 /** evaluate matrix entry by entry. */
161 ex matrix::eval(int level) const
163 debugmsg("matrix eval",LOGLEVEL_MEMBER_FUNCTION);
165 // check if we have to do anything at all
166 if ((level==1)&&(flags & status_flags::evaluated)) {
171 if (level == -max_recursion_level) {
172 throw (std::runtime_error("matrix::eval(): recursion limit exceeded"));
175 // eval() entry by entry
176 vector<ex> m2(row*col);
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);
184 return (new matrix(row, col, m2))->setflag(status_flags::dynallocated |
185 status_flags::evaluated );
188 /** evaluate matrix numerically entry by entry. */
189 ex matrix::evalf(int level) const
191 debugmsg("matrix evalf",LOGLEVEL_MEMBER_FUNCTION);
193 // check if we have to do anything at all
199 if (level == -max_recursion_level) {
200 throw (std::runtime_error("matrix::evalf(): recursion limit exceeded"));
203 // evalf() entry by entry
204 vector<ex> m2(row*col);
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);
211 return matrix(row, col, m2);
216 int matrix::compare_same_type(basic const & other) const
218 GINAC_ASSERT(is_exactly_of_type(other, matrix));
219 matrix const & o=static_cast<matrix &>(const_cast<basic &>(other));
221 // compare number of rows
222 if (row != o.rows()) {
223 return row < o.rows() ? -1 : 1;
226 // compare number of columns
227 if (col != o.cols()) {
228 return col < o.cols() ? -1 : 1;
231 // equal number of rows and columns, compare individual elements
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;
239 // all elements are equal => matrices are equal;
244 // non-virtual functions in this class
251 * @exception logic_error (incompatible matrices) */
252 matrix matrix::add(matrix const & other) const
254 if (col != other.col || row != other.row) {
255 throw (std::logic_error("matrix::add(): incompatible matrices"));
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();
266 return matrix(row,col,sum);
269 /** Difference of matrices.
271 * @exception logic_error (incompatible matrices) */
272 matrix matrix::sub(matrix const & other) const
274 if (col != other.col || row != other.row) {
275 throw (std::logic_error("matrix::sub(): incompatible matrices"));
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();
286 return matrix(row,col,dif);
289 /** Product of matrices.
291 * @exception logic_error (incompatible matrices) */
292 matrix matrix::mul(matrix const & other) const
294 if (col != other.row) {
295 throw (std::logic_error("matrix::mul(): incompatible matrices"));
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];
306 return matrix(row, other.col, prod);
309 /** operator() to access elements.
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
316 if (ro<0 || ro>=row || co<0 || co>=col) {
317 throw (std::range_error("matrix::operator(): index out of range"));
323 /** Set individual elements manually.
325 * @exception range_error (index out of range) */
326 matrix & matrix::set(int ro, int co, ex value)
328 if (ro<0 || ro>=row || co<0 || co>=col) {
329 throw (std::range_error("matrix::set(): index out of range"));
332 ensure_if_modifiable();
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
341 vector<ex> trans(col*row);
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];
348 return matrix(col,row,trans);
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)
355 GINAC_ASSERT(M.rows()==M.cols()); // cannot happen, just in case...
360 for (int r1=0; r1<M.rows(); ++r1) {
361 int indx = tmp.pivot(r1);
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];
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.
382 int permutation_sign(vector<T> s)
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) {
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)
404 GINAC_ASSERT(M.rows()==M.cols()); // cannot happen, just in case...
406 if (M.rows()==1) { // speed things up
412 vector<int> sigma(M.cols());
413 for (int i=0; i<M.cols(); ++i) sigma[i]=i;
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()));
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)
429 GINAC_ASSERT(M.rows()==M.cols()); // cannot happen, just in case...
431 if (M.rows()==1) { // end of recursion
434 if (M.rows()==2) { // speed things up
435 return (M(0,0)*M(1,1)-
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));
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) {
451 minorM.set(r,c,M(r,c+1));
453 minorM.set(r,c,M(r+1,c+1));
459 det -= M(r1,0) * determinant_symbolic_minor(minorM);
461 det += M(r1,0) * determinant_symbolic_minor(minorM);
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)
473 * GINAC_ASSERT(M.rows()==M.cols()); // cannot happen, just in case...
476 * matrix I(M.row, M.col);
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);
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.)
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
507 throw (std::logic_error("matrix::determinant(): matrix not square"));
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)) {
514 return determinant_symbolic_minor(*this).normal();
516 return determinant_symbolic_perm(*this);
520 // if it turns out that all elements are numeric
521 return determinant_numeric(*this);
524 /** Trace of a matrix.
526 * @return the sum of diagonal elements
527 * @exception logic_error (matrix not square) */
528 ex matrix::trace(void) const
531 throw (std::logic_error("matrix::trace(): matrix not square"));
535 for (int r=0; r<col; ++r) {
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.
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
552 throw (std::logic_error("matrix::charpoly(): matrix not square"));
556 for (int r=0; r<col; ++r) {
557 M.m[r*col+r] -= lambda;
559 return (M.determinant());
562 /** Inverse of this matrix.
564 * @return the inverted matrix
565 * @exception logic_error (matrix not square)
566 * @exception runtime_error (singular matrix) */
567 matrix matrix::inverse(void) const
570 throw (std::logic_error("matrix::inverse(): matrix not square"));
574 // set tmp to the unit matrix
575 for (int i=0; i<col; ++i) {
576 tmp.m[i*col+i] = exONE();
578 // create a copy of this matrix
580 for (int r1=0; r1<row; ++r1) {
581 int indx = cpy.pivot(r1);
583 throw (std::runtime_error("matrix::inverse(): singular matrix"));
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]);
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;
595 for (int r2=0; r2<row; ++r2) {
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];
608 void matrix::ffe_swap(int r1, int c1, int r2 ,int c2)
610 ensure_if_modifiable();
612 ex tmp=ffe_get(r1,c1);
613 ffe_set(r1,c1,ffe_get(r2,c2));
617 void matrix::ffe_set(int r, int c, ex e)
622 ex matrix::ffe_get(int r, int c) const
624 return operator()(r-1,c-1);
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.
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
638 if ((row != rhs.row) || (col != vars.row) || (rhs.col != vars.col)) {
639 throw (std::logic_error("matrix::solve(): incompatible matrices"));
642 matrix a(*this); // make a copy of the matrix
643 matrix b(rhs); // make a copy of the rhs vector
645 // given an m x n matrix a, reduce it to upper echelon form
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
656 for (p=r; (p<=m)&&(a.ffe_get(p,k).is_equal(exZERO())); ++p) {}
660 // switch rows p and r
661 for (int j=k; j<=n; ++j) {
665 // keep track of sign changes due to row exchange
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() */ );
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() */ );
679 divisor=a.ffe_get(r,k);
683 // optionally compute the determinant for square or augmented matrices
684 // if (r==m+1) { det=sign*divisor; } else { det=0; }
687 for (int r=1; r<=m; ++r) {
688 for (int c=1; c<=n; ++c) {
689 cout << a.ffe_get(r,c) << "\t";
691 cout << " | " << b.ffe_get(r,1) << endl;
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())) {
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;
710 #endif // def DO_GINAC_ASSERT
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())) {
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"));
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));
732 for (int c=first_non_zero+1; c<=n; ++c) {
733 e=e-a.ffe_get(r,c)*sol.ffe_get(c,1);
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;
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));
747 for (int c=1; c<=n; ++c) {
748 cout << vars.ffe_get(c,1) << "->" << sol.ffe_get(c,1) << endl;
752 #ifdef DO_GINAC_ASSERT
753 // test solution with echelon matrix
754 for (int r=1; r<=m; ++r) {
756 for (int c=1; c<=n; ++c) {
757 e=e+a.ffe_get(r,c)*sol.ffe_get(c,1);
759 if (!(e-b.ffe_get(r,1)).normal().is_zero()) {
761 cout << "b.ffe_get(" << r<<",1)=" << b.ffe_get(r,1) << endl;
762 cout << "diff=" << (e-b.ffe_get(r,1)).normal() << endl;
764 GINAC_ASSERT((e-b.ffe_get(r,1)).normal().is_zero());
767 // test solution with original matrix
768 for (int r=1; r<=m; ++r) {
770 for (int c=1; c<=n; ++c) {
771 e=e+ffe_get(r,c)*sol.ffe_get(c,1);
774 if (!(e-rhs.ffe_get(r,1)).normal().is_zero()) {
775 cout << "e=" << e << endl;
778 cout << "e.normal()=" << en << endl;
780 cout << "rhs.ffe_get(" << r<<",1)=" << rhs.ffe_get(r,1) << endl;
781 cout << "diff=" << (e-rhs.ffe_get(r,1)).normal() << endl;
784 ex xxx=e-rhs.ffe_get(r,1);
785 cerr << "xxx=" << xxx << endl << endl;
787 GINAC_ASSERT((e-rhs.ffe_get(r,1)).normal().is_zero());
789 #endif // def DO_GINAC_ASSERT
794 /** Solve simultaneous set of equations. */
795 matrix matrix::solve(matrix const & v) const
797 if (!(row == col && col == v.row)) {
798 throw (std::logic_error("matrix::solve(): incompatible matrices"));
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];
807 for (int c=0; c<v.col; ++c) {
808 tmp.m[r*tmp.col+c+col] = v.m[r*v.col+c];
811 for (int r1=0; r1<row; ++r1) {
812 int indx = tmp.pivot(r1);
814 throw (std::runtime_error("matrix::solve(): singular matrix"));
816 for (int c=r1; c<tmp.col; ++c) {
817 tmp.m[r1*tmp.col+c] /= tmp.m[r1*tmp.col+r1];
819 for (int r2=r1+1; r2<row; ++r2) {
820 for (int c=r1; c<tmp.col; ++c) {
822 -= tmp.m[r2*tmp.col+r1] * tmp.m[r1*tmp.col+c];
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) {
834 -= tmp[r*tmp.col+i] * sol[i*v.col+c];
838 return matrix(v.row, v.col, sol);
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)
852 for (int r=ro; r<row; ++r) {
853 if (!m[r*col+ro].is_zero()) {
858 if (m[k*col+ro].is_zero()) {
861 if (k!=ro) { // swap rows
862 for (int c=0; c<col; ++c) {
863 m[k*col+c].swap(m[ro*col+c]);
874 const matrix some_matrix;
875 type_info const & typeid_matrix=typeid(some_matrix);
877 #ifndef NO_GINAC_NAMESPACE
879 #endif // ndef NO_GINAC_NAMESPACE