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, exvector const & m2)
105 : basic(TINFO_matrix), row(r), col(c), m(m2)
107 debugmsg("matrix constructor from int,int,exvector",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 void matrix::print(ostream & os, unsigned upper_precedence) const
124 debugmsg("matrix print",LOGLEVEL_PRINT);
126 for (int r=0; r<row-1; ++r) {
128 for (int c=0; c<col-1; ++c) {
129 os << m[r*col+c] << ",";
131 os << m[col*(r+1)-1] << "]], ";
134 for (int c=0; c<col-1; ++c) {
135 os << m[(row-1)*col+c] << ",";
137 os << m[row*col-1] << "]] ]]";
140 void matrix::printraw(ostream & os) const
142 debugmsg("matrix printraw",LOGLEVEL_PRINT);
143 os << "matrix(" << row << "," << col <<",";
144 for (int r=0; r<row-1; ++r) {
146 for (int c=0; c<col-1; ++c) {
147 os << m[r*col+c] << ",";
149 os << m[col*(r-1)-1] << "),";
152 for (int c=0; c<col-1; ++c) {
153 os << m[(row-1)*col+c] << ",";
155 os << m[row*col-1] << "))";
158 /** nops is defined to be rows x columns. */
159 int matrix::nops() const
164 /** returns matrix entry at position (i/col, i%col). */
165 ex & matrix::let_op(int const i)
170 /** expands the elements of a matrix entry by entry. */
171 ex matrix::expand(unsigned options) const
173 exvector tmp(row*col);
174 for (int i=0; i<row*col; ++i) {
175 tmp[i]=m[i].expand(options);
177 return matrix(row, col, tmp);
180 /** Search ocurrences. A matrix 'has' an expression if it is the expression
181 * itself or one of the elements 'has' it. */
182 bool matrix::has(ex const & other) const
184 GINAC_ASSERT(other.bp!=0);
186 // tautology: it is the expression itself
187 if (is_equal(*other.bp)) return true;
189 // search all the elements
190 for (exvector::const_iterator r=m.begin(); r!=m.end(); ++r) {
191 if ((*r).has(other)) return true;
196 /** evaluate matrix entry by entry. */
197 ex matrix::eval(int level) const
199 debugmsg("matrix eval",LOGLEVEL_MEMBER_FUNCTION);
201 // check if we have to do anything at all
202 if ((level==1)&&(flags & status_flags::evaluated)) {
207 if (level == -max_recursion_level) {
208 throw (std::runtime_error("matrix::eval(): recursion limit exceeded"));
211 // eval() entry by entry
212 exvector m2(row*col);
214 for (int r=0; r<row; ++r) {
215 for (int c=0; c<col; ++c) {
216 m2[r*col+c] = m[r*col+c].eval(level);
220 return (new matrix(row, col, m2))->setflag(status_flags::dynallocated |
221 status_flags::evaluated );
224 /** evaluate matrix numerically entry by entry. */
225 ex matrix::evalf(int level) const
227 debugmsg("matrix evalf",LOGLEVEL_MEMBER_FUNCTION);
229 // check if we have to do anything at all
235 if (level == -max_recursion_level) {
236 throw (std::runtime_error("matrix::evalf(): recursion limit exceeded"));
239 // evalf() entry by entry
240 exvector m2(row*col);
242 for (int r=0; r<row; ++r) {
243 for (int c=0; c<col; ++c) {
244 m2[r*col+c] = m[r*col+c].evalf(level);
247 return matrix(row, col, m2);
252 int matrix::compare_same_type(basic const & other) const
254 GINAC_ASSERT(is_exactly_of_type(other, matrix));
255 matrix const & o=static_cast<matrix &>(const_cast<basic &>(other));
257 // compare number of rows
258 if (row != o.rows()) {
259 return row < o.rows() ? -1 : 1;
262 // compare number of columns
263 if (col != o.cols()) {
264 return col < o.cols() ? -1 : 1;
267 // equal number of rows and columns, compare individual elements
269 for (int r=0; r<row; ++r) {
270 for (int c=0; c<col; ++c) {
271 cmpval=((*this)(r,c)).compare(o(r,c));
272 if (cmpval!=0) return cmpval;
275 // all elements are equal => matrices are equal;
280 // non-virtual functions in this class
287 * @exception logic_error (incompatible matrices) */
288 matrix matrix::add(matrix const & other) const
290 if (col != other.col || row != other.row) {
291 throw (std::logic_error("matrix::add(): incompatible matrices"));
294 exvector sum(this->m);
295 exvector::iterator i;
296 exvector::const_iterator ci;
297 for (i=sum.begin(), ci=other.m.begin();
302 return matrix(row,col,sum);
305 /** Difference of matrices.
307 * @exception logic_error (incompatible matrices) */
308 matrix matrix::sub(matrix const & other) const
310 if (col != other.col || row != other.row) {
311 throw (std::logic_error("matrix::sub(): incompatible matrices"));
314 exvector dif(this->m);
315 exvector::iterator i;
316 exvector::const_iterator ci;
317 for (i=dif.begin(), ci=other.m.begin();
322 return matrix(row,col,dif);
325 /** Product of matrices.
327 * @exception logic_error (incompatible matrices) */
328 matrix matrix::mul(matrix const & other) const
330 if (col != other.row) {
331 throw (std::logic_error("matrix::mul(): incompatible matrices"));
334 exvector prod(row*other.col);
335 for (int i=0; i<row; ++i) {
336 for (int j=0; j<other.col; ++j) {
337 for (int l=0; l<col; ++l) {
338 prod[i*other.col+j] += m[i*col+l] * other.m[l*other.col+j];
342 return matrix(row, other.col, prod);
345 /** operator() to access elements.
347 * @param ro row of element
348 * @param co column of element
349 * @exception range_error (index out of range) */
350 ex const & matrix::operator() (int ro, int co) const
352 if (ro<0 || ro>=row || co<0 || co>=col) {
353 throw (std::range_error("matrix::operator(): index out of range"));
359 /** Set individual elements manually.
361 * @exception range_error (index out of range) */
362 matrix & matrix::set(int ro, int co, ex value)
364 if (ro<0 || ro>=row || co<0 || co>=col) {
365 throw (std::range_error("matrix::set(): index out of range"));
368 ensure_if_modifiable();
373 /** Transposed of an m x n matrix, producing a new n x m matrix object that
374 * represents the transposed. */
375 matrix matrix::transpose(void) const
377 exvector trans(col*row);
379 for (int r=0; r<col; ++r) {
380 for (int c=0; c<row; ++c) {
381 trans[r*row+c] = m[c*col+r];
384 return matrix(col,row,trans);
387 /* Determiant of purely numeric matrix, using pivoting. This routine is only
388 * called internally by matrix::determinant(). */
389 ex determinant_numeric(const matrix & M)
391 GINAC_ASSERT(M.rows()==M.cols()); // cannot happen, just in case...
396 for (int r1=0; r1<M.rows(); ++r1) {
397 int indx = tmp.pivot(r1);
404 det = det * tmp.m[r1*M.cols()+r1];
405 for (int r2=r1+1; r2<M.rows(); ++r2) {
406 piv = tmp.m[r2*M.cols()+r1] / tmp.m[r1*M.cols()+r1];
407 for (int c=r1+1; c<M.cols(); c++) {
408 tmp.m[r2*M.cols()+c] -= piv * tmp.m[r1*M.cols()+c];
415 // Compute the sign of a permutation of a vector of things, used internally
416 // by determinant_symbolic_perm() where it is instantiated for int.
418 int permutation_sign(vector<T> s)
423 for (typename vector<T>::iterator i=s.begin(); i!=s.end()-1; ++i) {
424 for (typename vector<T>::iterator j=i+1; j!=s.end(); ++j) {
436 /** Determinant built by application of the full permutation group. This
437 * routine is only called internally by matrix::determinant(). */
438 ex determinant_symbolic_perm(const matrix & M)
440 GINAC_ASSERT(M.rows()==M.cols()); // cannot happen, just in case...
442 if (M.rows()==1) { // speed things up
448 vector<int> sigma(M.cols());
449 for (int i=0; i<M.cols(); ++i) sigma[i]=i;
452 term = M(sigma[0],0);
453 for (int i=1; i<M.cols(); ++i) term *= M(sigma[i],i);
454 det += permutation_sign(sigma)*term;
455 } while (next_permutation(sigma.begin(), sigma.end()));
460 /** Recursive determiant for small matrices having at least one symbolic entry.
461 * This algorithm is also known as Laplace-expansion. This routine is only
462 * called internally by matrix::determinant(). */
463 ex determinant_symbolic_minor(const matrix & M)
465 GINAC_ASSERT(M.rows()==M.cols()); // cannot happen, just in case...
467 if (M.rows()==1) { // end of recursion
470 if (M.rows()==2) { // speed things up
471 return (M(0,0)*M(1,1)-
474 if (M.rows()==3) { // speed things up even a little more
475 return ((M(2,1)*M(0,2)-M(2,2)*M(0,1))*M(1,0)+
476 (M(1,2)*M(0,1)-M(1,1)*M(0,2))*M(2,0)+
477 (M(2,2)*M(1,1)-M(2,1)*M(1,2))*M(0,0));
481 matrix minorM(M.rows()-1,M.cols()-1);
482 for (int r1=0; r1<M.rows(); ++r1) {
483 // assemble the minor matrix
484 for (int r=0; r<minorM.rows(); ++r) {
485 for (int c=0; c<minorM.cols(); ++c) {
487 minorM.set(r,c,M(r,c+1));
489 minorM.set(r,c,M(r+1,c+1));
495 det -= M(r1,0) * determinant_symbolic_minor(minorM);
497 det += M(r1,0) * determinant_symbolic_minor(minorM);
503 /* Leverrier algorithm for large matrices having at least one symbolic entry.
504 * This routine is only called internally by matrix::determinant(). The
505 * algorithm is deemed bad for symbolic matrices since it returns expressions
506 * that are very hard to canonicalize. */
507 /*ex determinant_symbolic_leverrier(const matrix & M)
509 * GINAC_ASSERT(M.rows()==M.cols()); // cannot happen, just in case...
512 * matrix I(M.row, M.col);
514 * for (int i=1; i<M.row; ++i) {
515 * for (int j=0; j<M.row; ++j)
516 * I.m[j*M.col+j] = c;
517 * B = M.mul(B.sub(I));
518 * c = B.trace()/ex(i+1);
527 /** Determinant of square matrix. This routine doesn't actually calculate the
528 * determinant, it only implements some heuristics about which algorithm to
529 * call. When the parameter for normalization is explicitly turned off this
530 * method does not normalize its result at the end, which might imply that
531 * the symbolic 2x2 matrix [[a/(a-b),1],[b/(a-b),1]] is not immediatly
532 * recognized to be unity. (This is Mathematica's default behaviour, it
533 * should be used with care.)
535 * @param normalized may be set to false if no normalization of the
536 * result is desired (i.e. to force Mathematica behavior, Maple
537 * does normalize the result).
538 * @return the determinant as a new expression
539 * @exception logic_error (matrix not square) */
540 ex matrix::determinant(bool normalized) const
543 throw (std::logic_error("matrix::determinant(): matrix not square"));
546 // check, if there are non-numeric entries in the matrix:
547 for (exvector::const_iterator r=m.begin(); r!=m.end(); ++r) {
548 if (!(*r).info(info_flags::numeric)) {
550 return determinant_symbolic_minor(*this).normal();
552 return determinant_symbolic_perm(*this);
556 // if it turns out that all elements are numeric
557 return determinant_numeric(*this);
560 /** Trace of a matrix.
562 * @return the sum of diagonal elements
563 * @exception logic_error (matrix not square) */
564 ex matrix::trace(void) const
567 throw (std::logic_error("matrix::trace(): matrix not square"));
571 for (int r=0; r<col; ++r) {
577 /** Characteristic Polynomial. The characteristic polynomial of a matrix M is
578 * defined as the determiant of (M - lambda * 1) where 1 stands for the unit
579 * matrix of the same dimension as M. This method returns the characteristic
580 * polynomial as a new expression.
582 * @return characteristic polynomial as new expression
583 * @exception logic_error (matrix not square)
584 * @see matrix::determinant() */
585 ex matrix::charpoly(ex const & lambda) const
588 throw (std::logic_error("matrix::charpoly(): matrix not square"));
592 for (int r=0; r<col; ++r) {
593 M.m[r*col+r] -= lambda;
595 return (M.determinant());
598 /** Inverse of this matrix.
600 * @return the inverted matrix
601 * @exception logic_error (matrix not square)
602 * @exception runtime_error (singular matrix) */
603 matrix matrix::inverse(void) const
606 throw (std::logic_error("matrix::inverse(): matrix not square"));
610 // set tmp to the unit matrix
611 for (int i=0; i<col; ++i) {
612 tmp.m[i*col+i] = exONE();
614 // create a copy of this matrix
616 for (int r1=0; r1<row; ++r1) {
617 int indx = cpy.pivot(r1);
619 throw (std::runtime_error("matrix::inverse(): singular matrix"));
621 if (indx != 0) { // swap rows r and indx of matrix tmp
622 for (int i=0; i<col; ++i) {
623 tmp.m[r1*col+i].swap(tmp.m[indx*col+i]);
626 ex a1 = cpy.m[r1*col+r1];
627 for (int c=0; c<col; ++c) {
628 cpy.m[r1*col+c] /= a1;
629 tmp.m[r1*col+c] /= a1;
631 for (int r2=0; r2<row; ++r2) {
633 ex a2 = cpy.m[r2*col+r1];
634 for (int c=0; c<col; ++c) {
635 cpy.m[r2*col+c] -= a2 * cpy.m[r1*col+c];
636 tmp.m[r2*col+c] -= a2 * tmp.m[r1*col+c];
644 void matrix::ffe_swap(int r1, int c1, int r2 ,int c2)
646 ensure_if_modifiable();
648 ex tmp=ffe_get(r1,c1);
649 ffe_set(r1,c1,ffe_get(r2,c2));
653 void matrix::ffe_set(int r, int c, ex e)
658 ex matrix::ffe_get(int r, int c) const
660 return operator()(r-1,c-1);
663 /** Solve a set of equations for an m x n matrix by fraction-free Gaussian
664 * elimination. Based on algorithm 9.1 from 'Algorithms for Computer Algebra'
665 * by Keith O. Geddes et al.
667 * @param vars n x p matrix
668 * @param rhs m x p matrix
669 * @exception logic_error (incompatible matrices)
670 * @exception runtime_error (singular matrix) */
671 matrix matrix::fraction_free_elim(matrix const & vars,
672 matrix const & rhs) const
674 if ((row != rhs.row) || (col != vars.row) || (rhs.col != vars.col)) {
675 throw (std::logic_error("matrix::solve(): incompatible matrices"));
678 matrix a(*this); // make a copy of the matrix
679 matrix b(rhs); // make a copy of the rhs vector
681 // given an m x n matrix a, reduce it to upper echelon form
688 // eliminate below row r, with pivot in column k
689 for (int k=1; (k<=n)&&(r<=m); ++k) {
690 // find a nonzero pivot
692 for (p=r; (p<=m)&&(a.ffe_get(p,k).is_equal(exZERO())); ++p) {}
696 // switch rows p and r
697 for (int j=k; j<=n; ++j) {
701 // keep track of sign changes due to row exchange
704 for (int i=r+1; i<=m; ++i) {
705 for (int j=k+1; j<=n; ++j) {
706 a.ffe_set(i,j,(a.ffe_get(r,k)*a.ffe_get(i,j)
707 -a.ffe_get(r,j)*a.ffe_get(i,k))/divisor);
708 a.ffe_set(i,j,a.ffe_get(i,j).normal() /*.normal() */ );
710 b.ffe_set(i,1,(a.ffe_get(r,k)*b.ffe_get(i,1)
711 -b.ffe_get(r,1)*a.ffe_get(i,k))/divisor);
712 b.ffe_set(i,1,b.ffe_get(i,1).normal() /*.normal() */ );
715 divisor=a.ffe_get(r,k);
719 // optionally compute the determinant for square or augmented matrices
720 // if (r==m+1) { det=sign*divisor; } else { det=0; }
723 for (int r=1; r<=m; ++r) {
724 for (int c=1; c<=n; ++c) {
725 cout << a.ffe_get(r,c) << "\t";
727 cout << " | " << b.ffe_get(r,1) << endl;
731 #ifdef DO_GINAC_ASSERT
732 // test if we really have an upper echelon matrix
733 int zero_in_last_row=-1;
734 for (int r=1; r<=m; ++r) {
735 int zero_in_this_row=0;
736 for (int c=1; c<=n; ++c) {
737 if (a.ffe_get(r,c).is_equal(exZERO())) {
743 GINAC_ASSERT((zero_in_this_row>zero_in_last_row)||(zero_in_this_row=n));
744 zero_in_last_row=zero_in_this_row;
746 #endif // def DO_GINAC_ASSERT
750 int last_assigned_sol=n+1;
751 for (int r=m; r>0; --r) {
752 int first_non_zero=1;
753 while ((first_non_zero<=n)&&(a.ffe_get(r,first_non_zero).is_zero())) {
756 if (first_non_zero>n) {
757 // row consists only of zeroes, corresponding rhs must be 0 as well
758 if (!b.ffe_get(r,1).is_zero()) {
759 throw (std::runtime_error("matrix::fraction_free_elim(): singular matrix"));
762 // assign solutions for vars between first_non_zero+1 and
763 // last_assigned_sol-1: free parameters
764 for (int c=first_non_zero+1; c<=last_assigned_sol-1; ++c) {
765 sol.ffe_set(c,1,vars.ffe_get(c,1));
768 for (int c=first_non_zero+1; c<=n; ++c) {
769 e=e-a.ffe_get(r,c)*sol.ffe_get(c,1);
771 sol.ffe_set(first_non_zero,1,
772 (e/a.ffe_get(r,first_non_zero)).normal());
773 last_assigned_sol=first_non_zero;
776 // assign solutions for vars between 1 and
777 // last_assigned_sol-1: free parameters
778 for (int c=1; c<=last_assigned_sol-1; ++c) {
779 sol.ffe_set(c,1,vars.ffe_get(c,1));
783 for (int c=1; c<=n; ++c) {
784 cout << vars.ffe_get(c,1) << "->" << sol.ffe_get(c,1) << endl;
788 #ifdef DO_GINAC_ASSERT
789 // test solution with echelon matrix
790 for (int r=1; r<=m; ++r) {
792 for (int c=1; c<=n; ++c) {
793 e=e+a.ffe_get(r,c)*sol.ffe_get(c,1);
795 if (!(e-b.ffe_get(r,1)).normal().is_zero()) {
797 cout << "b.ffe_get(" << r<<",1)=" << b.ffe_get(r,1) << endl;
798 cout << "diff=" << (e-b.ffe_get(r,1)).normal() << endl;
800 GINAC_ASSERT((e-b.ffe_get(r,1)).normal().is_zero());
803 // test solution with original matrix
804 for (int r=1; r<=m; ++r) {
806 for (int c=1; c<=n; ++c) {
807 e=e+ffe_get(r,c)*sol.ffe_get(c,1);
810 if (!(e-rhs.ffe_get(r,1)).normal().is_zero()) {
811 cout << "e=" << e << endl;
814 cout << "e.normal()=" << en << endl;
816 cout << "rhs.ffe_get(" << r<<",1)=" << rhs.ffe_get(r,1) << endl;
817 cout << "diff=" << (e-rhs.ffe_get(r,1)).normal() << endl;
820 ex xxx=e-rhs.ffe_get(r,1);
821 cerr << "xxx=" << xxx << endl << endl;
823 GINAC_ASSERT((e-rhs.ffe_get(r,1)).normal().is_zero());
825 #endif // def DO_GINAC_ASSERT
830 /** Solve simultaneous set of equations. */
831 matrix matrix::solve(matrix const & v) const
833 if (!(row == col && col == v.row)) {
834 throw (std::logic_error("matrix::solve(): incompatible matrices"));
837 // build the extended matrix of *this with v attached to the right
838 matrix tmp(row,col+v.col);
839 for (int r=0; r<row; ++r) {
840 for (int c=0; c<col; ++c) {
841 tmp.m[r*tmp.col+c] = m[r*col+c];
843 for (int c=0; c<v.col; ++c) {
844 tmp.m[r*tmp.col+c+col] = v.m[r*v.col+c];
847 for (int r1=0; r1<row; ++r1) {
848 int indx = tmp.pivot(r1);
850 throw (std::runtime_error("matrix::solve(): singular matrix"));
852 for (int c=r1; c<tmp.col; ++c) {
853 tmp.m[r1*tmp.col+c] /= tmp.m[r1*tmp.col+r1];
855 for (int r2=r1+1; r2<row; ++r2) {
856 for (int c=r1; c<tmp.col; ++c) {
858 -= tmp.m[r2*tmp.col+r1] * tmp.m[r1*tmp.col+c];
863 // assemble the solution matrix
864 exvector sol(v.row*v.col);
865 for (int c=0; c<v.col; ++c) {
866 for (int r=col-1; r>=0; --r) {
867 sol[r*v.col+c] = tmp[r*tmp.col+c];
868 for (int i=r+1; i<col; ++i) {
870 -= tmp[r*tmp.col+i] * sol[i*v.col+c];
874 return matrix(v.row, v.col, sol);
879 /** Partial pivoting method.
880 * Usual pivoting returns the index to the element with the largest absolute
881 * value and swaps the current row with the one where the element was found.
882 * Here it does the same with the first non-zero element. (This works fine,
883 * but may be far from optimal for numerics.) */
884 int matrix::pivot(int ro)
888 for (int r=ro; r<row; ++r) {
889 if (!m[r*col+ro].is_zero()) {
894 if (m[k*col+ro].is_zero()) {
897 if (k!=ro) { // swap rows
898 for (int c=0; c<col; ++c) {
899 m[k*col+c].swap(m[ro*col+c]);
910 const matrix some_matrix;
911 type_info const & typeid_matrix=typeid(some_matrix);
913 #ifndef NO_GINAC_NAMESPACE
915 #endif // ndef NO_GINAC_NAMESPACE