3 * Implementation of symbolic matrices */
6 * GiNaC Copyright (C) 1999-2000 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
34 #ifndef NO_NAMESPACE_GINAC
36 #endif // ndef NO_NAMESPACE_GINAC
38 GINAC_IMPLEMENT_REGISTERED_CLASS(matrix, basic)
41 // default constructor, destructor, copy constructor, assignment operator
47 /** Default ctor. Initializes to 1 x 1-dimensional zero-matrix. */
49 : inherited(TINFO_matrix), row(1), col(1)
51 debugmsg("matrix default constructor",LOGLEVEL_CONSTRUCT);
57 debugmsg("matrix destructor",LOGLEVEL_DESTRUCT);
60 matrix::matrix(const matrix & other)
62 debugmsg("matrix copy constructor",LOGLEVEL_CONSTRUCT);
66 const matrix & matrix::operator=(const matrix & other)
68 debugmsg("matrix operator=",LOGLEVEL_ASSIGNMENT);
78 void matrix::copy(const matrix & other)
80 inherited::copy(other);
83 m=other.m; // use STL's vector copying
86 void matrix::destroy(bool call_parent)
88 if (call_parent) inherited::destroy(call_parent);
97 /** Very common ctor. Initializes to r x c-dimensional zero-matrix.
99 * @param r number of rows
100 * @param c number of cols */
101 matrix::matrix(unsigned r, unsigned c)
102 : inherited(TINFO_matrix), row(r), col(c)
104 debugmsg("matrix constructor from unsigned,unsigned",LOGLEVEL_CONSTRUCT);
105 m.resize(r*c, _ex0());
110 /** Ctor from representation, for internal use only. */
111 matrix::matrix(unsigned r, unsigned c, const exvector & m2)
112 : inherited(TINFO_matrix), row(r), col(c), m(m2)
114 debugmsg("matrix constructor from unsigned,unsigned,exvector",LOGLEVEL_CONSTRUCT);
121 /** Construct object from archive_node. */
122 matrix::matrix(const archive_node &n, const lst &sym_lst) : inherited(n, sym_lst)
124 debugmsg("matrix constructor from archive_node", LOGLEVEL_CONSTRUCT);
125 if (!(n.find_unsigned("row", row)) || !(n.find_unsigned("col", col)))
126 throw (std::runtime_error("unknown matrix dimensions in archive"));
127 m.reserve(row * col);
128 for (unsigned int i=0; true; i++) {
130 if (n.find_ex("m", e, sym_lst, i))
137 /** Unarchive the object. */
138 ex matrix::unarchive(const archive_node &n, const lst &sym_lst)
140 return (new matrix(n, sym_lst))->setflag(status_flags::dynallocated);
143 /** Archive the object. */
144 void matrix::archive(archive_node &n) const
146 inherited::archive(n);
147 n.add_unsigned("row", row);
148 n.add_unsigned("col", col);
149 exvector::const_iterator i = m.begin(), iend = m.end();
157 // functions overriding virtual functions from bases classes
162 basic * matrix::duplicate() const
164 debugmsg("matrix duplicate",LOGLEVEL_DUPLICATE);
165 return new matrix(*this);
168 void matrix::print(ostream & os, unsigned upper_precedence) const
170 debugmsg("matrix print",LOGLEVEL_PRINT);
172 for (unsigned r=0; r<row-1; ++r) {
174 for (unsigned c=0; c<col-1; ++c) {
175 os << m[r*col+c] << ",";
177 os << m[col*(r+1)-1] << "]], ";
180 for (unsigned c=0; c<col-1; ++c) {
181 os << m[(row-1)*col+c] << ",";
183 os << m[row*col-1] << "]] ]]";
186 void matrix::printraw(ostream & os) const
188 debugmsg("matrix printraw",LOGLEVEL_PRINT);
189 os << "matrix(" << row << "," << col <<",";
190 for (unsigned r=0; r<row-1; ++r) {
192 for (unsigned c=0; c<col-1; ++c) {
193 os << m[r*col+c] << ",";
195 os << m[col*(r-1)-1] << "),";
198 for (unsigned c=0; c<col-1; ++c) {
199 os << m[(row-1)*col+c] << ",";
201 os << m[row*col-1] << "))";
204 /** nops is defined to be rows x columns. */
205 unsigned matrix::nops() const
210 /** returns matrix entry at position (i/col, i%col). */
211 ex matrix::op(int i) const
216 /** returns matrix entry at position (i/col, i%col). */
217 ex & matrix::let_op(int i)
222 /** expands the elements of a matrix entry by entry. */
223 ex matrix::expand(unsigned options) const
225 exvector tmp(row*col);
226 for (unsigned i=0; i<row*col; ++i) {
227 tmp[i]=m[i].expand(options);
229 return matrix(row, col, tmp);
232 /** Search ocurrences. A matrix 'has' an expression if it is the expression
233 * itself or one of the elements 'has' it. */
234 bool matrix::has(const ex & other) const
236 GINAC_ASSERT(other.bp!=0);
238 // tautology: it is the expression itself
239 if (is_equal(*other.bp)) return true;
241 // search all the elements
242 for (exvector::const_iterator r=m.begin(); r!=m.end(); ++r) {
243 if ((*r).has(other)) return true;
248 /** evaluate matrix entry by entry. */
249 ex matrix::eval(int level) const
251 debugmsg("matrix eval",LOGLEVEL_MEMBER_FUNCTION);
253 // check if we have to do anything at all
254 if ((level==1)&&(flags & status_flags::evaluated))
258 if (level == -max_recursion_level)
259 throw (std::runtime_error("matrix::eval(): recursion limit exceeded"));
261 // eval() entry by entry
262 exvector m2(row*col);
264 for (unsigned r=0; r<row; ++r) {
265 for (unsigned c=0; c<col; ++c) {
266 m2[r*col+c] = m[r*col+c].eval(level);
270 return (new matrix(row, col, m2))->setflag(status_flags::dynallocated |
271 status_flags::evaluated );
274 /** evaluate matrix numerically entry by entry. */
275 ex matrix::evalf(int level) const
277 debugmsg("matrix evalf",LOGLEVEL_MEMBER_FUNCTION);
279 // check if we have to do anything at all
284 if (level == -max_recursion_level) {
285 throw (std::runtime_error("matrix::evalf(): recursion limit exceeded"));
288 // evalf() entry by entry
289 exvector m2(row*col);
291 for (unsigned r=0; r<row; ++r) {
292 for (unsigned c=0; c<col; ++c) {
293 m2[r*col+c] = m[r*col+c].evalf(level);
296 return matrix(row, col, m2);
301 int matrix::compare_same_type(const basic & other) const
303 GINAC_ASSERT(is_exactly_of_type(other, matrix));
304 const matrix & o = static_cast<matrix &>(const_cast<basic &>(other));
306 // compare number of rows
308 return row < o.rows() ? -1 : 1;
310 // compare number of columns
312 return col < o.cols() ? -1 : 1;
314 // equal number of rows and columns, compare individual elements
316 for (unsigned r=0; r<row; ++r) {
317 for (unsigned c=0; c<col; ++c) {
318 cmpval = ((*this)(r,c)).compare(o(r,c));
319 if (cmpval!=0) return cmpval;
322 // all elements are equal => matrices are equal;
327 // non-virtual functions in this class
334 * @exception logic_error (incompatible matrices) */
335 matrix matrix::add(const matrix & other) const
337 if (col != other.col || row != other.row)
338 throw (std::logic_error("matrix::add(): incompatible matrices"));
340 exvector sum(this->m);
341 exvector::iterator i;
342 exvector::const_iterator ci;
343 for (i=sum.begin(), ci=other.m.begin();
348 return matrix(row,col,sum);
352 /** Difference of matrices.
354 * @exception logic_error (incompatible matrices) */
355 matrix matrix::sub(const matrix & other) const
357 if (col != other.col || row != other.row)
358 throw (std::logic_error("matrix::sub(): incompatible matrices"));
360 exvector dif(this->m);
361 exvector::iterator i;
362 exvector::const_iterator ci;
363 for (i=dif.begin(), ci=other.m.begin();
368 return matrix(row,col,dif);
372 /** Product of matrices.
374 * @exception logic_error (incompatible matrices) */
375 matrix matrix::mul(const matrix & other) const
377 if (col != other.row)
378 throw (std::logic_error("matrix::mul(): incompatible matrices"));
380 exvector prod(row*other.col);
381 for (unsigned i=0; i<row; ++i) {
382 for (unsigned j=0; j<other.col; ++j) {
383 for (unsigned l=0; l<col; ++l) {
384 prod[i*other.col+j] += m[i*col+l] * other.m[l*other.col+j];
388 return matrix(row, other.col, prod);
392 /** operator() to access elements.
394 * @param ro row of element
395 * @param co column of element
396 * @exception range_error (index out of range) */
397 const ex & matrix::operator() (unsigned ro, unsigned co) const
399 if (ro<0 || ro>=row || co<0 || co>=col)
400 throw (std::range_error("matrix::operator(): index out of range"));
406 /** Set individual elements manually.
408 * @exception range_error (index out of range) */
409 matrix & matrix::set(unsigned ro, unsigned co, ex value)
411 if (ro<0 || ro>=row || co<0 || co>=col)
412 throw (std::range_error("matrix::set(): index out of range"));
414 ensure_if_modifiable();
415 m[ro*col+co] = value;
420 /** Transposed of an m x n matrix, producing a new n x m matrix object that
421 * represents the transposed. */
422 matrix matrix::transpose(void) const
424 exvector trans(col*row);
426 for (unsigned r=0; r<col; ++r)
427 for (unsigned c=0; c<row; ++c)
428 trans[r*row+c] = m[c*col+r];
430 return matrix(col,row,trans);
434 /** Determinant of square matrix. This routine doesn't actually calculate the
435 * determinant, it only implements some heuristics about which algorithm to
436 * call. If all the elements of the matrix are elements of an integral domain
437 * the determinant is also in that integral domain and the result is expanded
438 * only. If one or more elements are from a quotient field the determinant is
439 * usually also in that quotient field and the result is normalized before it
440 * is returned. This implies that the determinant of the symbolic 2x2 matrix
441 * [[a/(a-b),1],[b/(a-b),1]] is returned as unity. (In this respect, it
442 * behaves like MapleV and unlike Mathematica.)
444 * @return the determinant as a new expression
445 * @exception logic_error (matrix not square) */
446 ex matrix::determinant(void) const
449 throw (std::logic_error("matrix::determinant(): matrix not square"));
450 GINAC_ASSERT(row*col==m.capacity());
451 if (this->row==1) // continuation would be pointless
454 bool numeric_flag = true;
455 bool normal_flag = false;
456 unsigned sparse_count = 0; // count non-zero elements
457 for (exvector::const_iterator r=m.begin(); r!=m.end(); ++r) {
458 if (!(*r).is_zero()) {
461 if (!(*r).info(info_flags::numeric)) {
462 numeric_flag = false;
464 if ((*r).info(info_flags::rational_function) &&
465 !(*r).info(info_flags::crational_polynomial)) {
471 return determinant_numeric();
473 if (5*sparse_count<row*col) { // MAGIC, maybe 10 some bright day?
475 // int sign = M.division_free_elimination();
476 int sign = M.fraction_free_elimination();
478 return sign*M(row-1,col-1).normal();
480 return sign*M(row-1,col-1).expand();
483 // Now come the minor expansion schemes. We always develop such that the
484 // smallest minors (i.e, the trivial 1x1 ones) are on the rightmost column.
485 // For this to be efficient it turns out that the emptiest columns (i.e.
486 // the ones with most zeros) should be the ones on the right hand side.
487 // Therefore we presort the columns of the matrix:
488 typedef pair<unsigned,unsigned> uintpair; // # of zeros, column
489 vector<uintpair> c_zeros; // number of zeros in column
490 for (unsigned c=0; c<col; ++c) {
492 for (unsigned r=0; r<row; ++r)
493 if (m[r*col+c].is_zero())
495 c_zeros.push_back(uintpair(acc,c));
497 sort(c_zeros.begin(),c_zeros.end());
498 vector<unsigned> pre_sort; // unfortunately vector<uintpair> can't be used
499 // for permutation_sign.
500 for (vector<uintpair>::iterator i=c_zeros.begin(); i!=c_zeros.end(); ++i)
501 pre_sort.push_back(i->second);
502 int sign = permutation_sign(pre_sort);
503 exvector result(row*col); // represents sorted matrix
505 for (vector<unsigned>::iterator i=pre_sort.begin();
508 for (unsigned r=0; r<row; ++r)
509 result[r*col+c] = m[r*col+(*i)];
513 return sign*matrix(row,col,result).determinant_minor_dense().normal();
514 return sign*matrix(row,col,result).determinant_minor_dense();
518 /** Trace of a matrix. The result is normalized if it is in some quotient
519 * field and expanded only otherwise. This implies that the trace of the
520 * symbolic 2x2 matrix [[a/(a-b),x],[y,b/(b-a)]] is recognized to be unity.
522 * @return the sum of diagonal elements
523 * @exception logic_error (matrix not square) */
524 ex matrix::trace(void) const
527 throw (std::logic_error("matrix::trace(): matrix not square"));
528 GINAC_ASSERT(row*col==m.capacity());
531 for (unsigned r=0; r<col; ++r)
534 if (tr.info(info_flags::rational_function) &&
535 !tr.info(info_flags::crational_polynomial))
542 /** Characteristic Polynomial. The characteristic polynomial of a matrix M is
543 * defined as the determiant of (M - lambda * 1) where 1 stands for the unit
544 * matrix of the same dimension as M. This method returns the characteristic
545 * polynomial as a new expression.
547 * @return characteristic polynomial as new expression
548 * @exception logic_error (matrix not square)
549 * @see matrix::determinant() */
550 ex matrix::charpoly(const ex & lambda) const
553 throw (std::logic_error("matrix::charpoly(): matrix not square"));
556 for (unsigned r=0; r<col; ++r)
557 M.m[r*col+r] -= lambda;
559 return (M.determinant());
563 /** Inverse of this matrix.
565 * @return the inverted matrix
566 * @exception logic_error (matrix not square)
567 * @exception runtime_error (singular matrix) */
568 matrix matrix::inverse(void) const
571 throw (std::logic_error("matrix::inverse(): matrix not square"));
574 // set tmp to the unit matrix
575 for (unsigned i=0; i<col; ++i)
576 tmp.m[i*col+i] = _ex1();
578 // create a copy of this matrix
580 for (unsigned 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 (unsigned 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 (unsigned c=0; c<col; ++c) {
592 cpy.m[r1*col+c] /= a1;
593 tmp.m[r1*col+c] /= a1;
595 for (unsigned r2=0; r2<row; ++r2) {
597 ex a2 = cpy.m[r2*col+r1];
598 for (unsigned c=0; c<col; ++c) {
599 cpy.m[r2*col+c] -= a2 * cpy.m[r1*col+c];
600 tmp.m[r2*col+c] -= a2 * tmp.m[r1*col+c];
609 // superfluous helper function
610 void matrix::ffe_swap(unsigned r1, unsigned c1, unsigned r2 ,unsigned c2)
612 ensure_if_modifiable();
614 ex tmp = ffe_get(r1,c1);
615 ffe_set(r1,c1,ffe_get(r2,c2));
619 // superfluous helper function
620 void matrix::ffe_set(unsigned r, unsigned c, ex e)
625 // superfluous helper function
626 ex matrix::ffe_get(unsigned r, unsigned c) const
628 return operator()(r-1,c-1);
631 /** Solve a set of equations for an m x n matrix by fraction-free Gaussian
632 * elimination. Based on algorithm 9.1 from 'Algorithms for Computer Algebra'
633 * by Keith O. Geddes et al.
635 * @param vars n x p matrix
636 * @param rhs m x p matrix
637 * @exception logic_error (incompatible matrices)
638 * @exception runtime_error (singular matrix) */
639 matrix matrix::fraction_free_elim(const matrix & vars,
640 const matrix & rhs) const
642 // FIXME: implement a Sasaki-Murao scheme which avoids division at all!
643 if ((row != rhs.row) || (col != vars.row) || (rhs.col != vars.col))
644 throw (std::logic_error("matrix::fraction_free_elim(): incompatible matrices"));
646 matrix a(*this); // make a copy of the matrix
647 matrix b(rhs); // make a copy of the rhs vector
649 // given an m x n matrix a, reduce it to upper echelon form
656 // eliminate below row r, with pivot in column k
657 for (unsigned k=1; (k<=n)&&(r<=m); ++k) {
658 // find a nonzero pivot
660 for (p=r; (p<=m)&&(a.ffe_get(p,k).is_equal(_ex0())); ++p) {}
664 // switch rows p and r
665 for (unsigned j=k; j<=n; ++j)
668 // keep track of sign changes due to row exchange
671 for (unsigned i=r+1; i<=m; ++i) {
672 for (unsigned j=k+1; j<=n; ++j) {
673 a.ffe_set(i,j,(a.ffe_get(r,k)*a.ffe_get(i,j)
674 -a.ffe_get(r,j)*a.ffe_get(i,k))/divisor);
675 a.ffe_set(i,j,a.ffe_get(i,j).normal() /*.normal() */ );
677 b.ffe_set(i,1,(a.ffe_get(r,k)*b.ffe_get(i,1)
678 -b.ffe_get(r,1)*a.ffe_get(i,k))/divisor);
679 b.ffe_set(i,1,b.ffe_get(i,1).normal() /*.normal() */ );
682 divisor = a.ffe_get(r,k);
686 // optionally compute the determinant for square or augmented matrices
687 // if (r==m+1) { det = sign*divisor; } else { det = 0; }
690 for (unsigned r=1; r<=m; ++r) {
691 for (unsigned c=1; c<=n; ++c) {
692 cout << a.ffe_get(r,c) << "\t";
694 cout << " | " << b.ffe_get(r,1) << endl;
698 #ifdef DO_GINAC_ASSERT
699 // test if we really have an upper echelon matrix
700 int zero_in_last_row = -1;
701 for (unsigned r=1; r<=m; ++r) {
702 int zero_in_this_row=0;
703 for (unsigned c=1; c<=n; ++c) {
704 if (a.ffe_get(r,c).is_equal(_ex0()))
709 GINAC_ASSERT((zero_in_this_row>zero_in_last_row)||(zero_in_this_row=n));
710 zero_in_last_row = zero_in_this_row;
712 #endif // def DO_GINAC_ASSERT
715 cout << "after" << endl;
716 cout << "a=" << a << endl;
717 cout << "b=" << b << endl;
722 unsigned last_assigned_sol = n+1;
723 for (unsigned r=m; r>0; --r) {
724 unsigned first_non_zero = 1;
725 while ((first_non_zero<=n)&&(a.ffe_get(r,first_non_zero).is_zero()))
727 if (first_non_zero>n) {
728 // row consists only of zeroes, corresponding rhs must be 0 as well
729 if (!b.ffe_get(r,1).is_zero()) {
730 throw (std::runtime_error("matrix::fraction_free_elim(): singular matrix"));
733 // assign solutions for vars between first_non_zero+1 and
734 // last_assigned_sol-1: free parameters
735 for (unsigned c=first_non_zero+1; c<=last_assigned_sol-1; ++c) {
736 sol.ffe_set(c,1,vars.ffe_get(c,1));
738 ex e = b.ffe_get(r,1);
739 for (unsigned c=first_non_zero+1; c<=n; ++c) {
740 e=e-a.ffe_get(r,c)*sol.ffe_get(c,1);
742 sol.ffe_set(first_non_zero,1,
743 (e/a.ffe_get(r,first_non_zero)).normal());
744 last_assigned_sol = first_non_zero;
747 // assign solutions for vars between 1 and
748 // last_assigned_sol-1: free parameters
749 for (unsigned c=1; c<=last_assigned_sol-1; ++c)
750 sol.ffe_set(c,1,vars.ffe_get(c,1));
752 #ifdef DO_GINAC_ASSERT
753 // test solution with echelon matrix
754 for (unsigned r=1; r<=m; ++r) {
756 for (unsigned c=1; c<=n; ++c)
757 e = e+a.ffe_get(r,c)*sol.ffe_get(c,1);
758 if (!(e-b.ffe_get(r,1)).normal().is_zero()) {
760 cout << "b.ffe_get(" << r<<",1)=" << b.ffe_get(r,1) << endl;
761 cout << "diff=" << (e-b.ffe_get(r,1)).normal() << endl;
763 GINAC_ASSERT((e-b.ffe_get(r,1)).normal().is_zero());
766 // test solution with original matrix
767 for (unsigned r=1; r<=m; ++r) {
769 for (unsigned c=1; c<=n; ++c)
770 e = e+ffe_get(r,c)*sol.ffe_get(c,1);
772 if (!(e-rhs.ffe_get(r,1)).normal().is_zero()) {
773 cout << "e=" << e << endl;
776 cout << "e.normal()=" << en << endl;
778 cout << "rhs.ffe_get(" << r<<",1)=" << rhs.ffe_get(r,1) << endl;
779 cout << "diff=" << (e-rhs.ffe_get(r,1)).normal() << endl;
782 ex xxx = e - rhs.ffe_get(r,1);
783 cerr << "xxx=" << xxx << endl << endl;
785 GINAC_ASSERT((e-rhs.ffe_get(r,1)).normal().is_zero());
787 #endif // def DO_GINAC_ASSERT
792 /** Solve a set of equations for an m x n matrix.
794 * @param vars n x p matrix
795 * @param rhs m x p matrix
796 * @exception logic_error (incompatible matrices)
797 * @exception runtime_error (singular matrix) */
798 matrix matrix::solve(const matrix & vars,
799 const matrix & rhs) const
801 if ((row != rhs.row) || (col != vars.row) || (rhs.col != vars.col))
802 throw (std::logic_error("matrix::solve(): incompatible matrices"));
804 throw (std::runtime_error("FIXME: need implementation."));
807 /** Old and obsolete interface: */
808 matrix matrix::old_solve(const matrix & v) const
810 if ((v.row != col) || (col != v.row))
811 throw (std::logic_error("matrix::solve(): incompatible matrices"));
813 // build the augmented matrix of *this with v attached to the right
814 matrix tmp(row,col+v.col);
815 for (unsigned r=0; r<row; ++r) {
816 for (unsigned c=0; c<col; ++c)
817 tmp.m[r*tmp.col+c] = this->m[r*col+c];
818 for (unsigned c=0; c<v.col; ++c)
819 tmp.m[r*tmp.col+c+col] = v.m[r*v.col+c];
821 // cout << "augmented: " << tmp << endl;
822 tmp.gauss_elimination();
823 // cout << "degaussed: " << tmp << endl;
824 // assemble the solution matrix
825 exvector sol(v.row*v.col);
826 for (unsigned c=0; c<v.col; ++c) {
827 for (unsigned r=row; r>0; --r) {
828 for (unsigned i=r; i<col; ++i)
829 sol[(r-1)*v.col+c] -= tmp.m[(r-1)*tmp.col+i]*sol[i*v.col+c];
830 sol[(r-1)*v.col+c] += tmp.m[(r-1)*tmp.col+col+c];
831 sol[(r-1)*v.col+c] = (sol[(r-1)*v.col+c]/tmp.m[(r-1)*tmp.col+(r-1)]).normal();
834 return matrix(v.row, v.col, sol);
840 /** Determinant of purely numeric matrix, using pivoting.
842 * @see matrix::determinant() */
843 ex matrix::determinant_numeric(void) const
849 for (unsigned r1=0; r1<row; ++r1) {
850 int indx = tmp.pivot(r1);
855 det = det * tmp.m[r1*col+r1];
856 for (unsigned r2=r1+1; r2<row; ++r2) {
857 piv = tmp.m[r2*col+r1] / tmp.m[r1*col+r1];
858 for (unsigned c=r1+1; c<col; c++) {
859 tmp.m[r2*col+c] -= piv * tmp.m[r1*col+c];
868 /* Leverrier algorithm for large matrices having at least one symbolic entry.
869 * This routine is only called internally by matrix::determinant(). The
870 * algorithm is very bad for symbolic matrices since it returns expressions
871 * that are quite hard to expand. */
872 /*ex matrix::determinant_leverrier(const matrix & M)
874 * GINAC_ASSERT(M.rows()==M.cols()); // cannot happen, just in case...
877 * matrix I(M.row, M.col);
879 * for (unsigned i=1; i<M.row; ++i) {
880 * for (unsigned j=0; j<M.row; ++j)
881 * I.m[j*M.col+j] = c;
882 * B = M.mul(B.sub(I));
883 * c = B.trace()/ex(i+1);
893 ex matrix::determinant_minor_sparse(void) const
895 // for small matrices the algorithm does not make any sense:
899 return (m[0]*m[3]-m[2]*m[1]).expand();
901 return (m[0]*m[4]*m[8]-m[0]*m[5]*m[7]-
902 m[1]*m[3]*m[8]+m[2]*m[3]*m[7]+
903 m[1]*m[5]*m[6]-m[2]*m[4]*m[6]).expand();
906 matrix minorM(this->row-1,this->col-1);
907 for (unsigned r1=0; r1<this->row; ++r1) {
908 // shortcut if element(r1,0) vanishes
909 if (m[r1*col].is_zero())
911 // assemble the minor matrix
912 for (unsigned r=0; r<minorM.rows(); ++r) {
913 for (unsigned c=0; c<minorM.cols(); ++c) {
915 minorM.set(r,c,m[r*col+c+1]);
917 minorM.set(r,c,m[(r+1)*col+c+1]);
920 // recurse down and care for sign:
922 det -= m[r1*col] * minorM.determinant_minor_sparse();
924 det += m[r1*col] * minorM.determinant_minor_sparse();
929 /** Recursive determinant for small matrices having at least one symbolic
930 * entry. The basic algorithm, known as Laplace-expansion, is enhanced by
931 * some bookkeeping to avoid calculation of the same submatrices ("minors")
932 * more than once. According to W.M.Gentleman and S.C.Johnson this algorithm
933 * is better than elimination schemes for matrices of sparse multivariate
934 * polynomials and also for matrices of dense univariate polynomials if the
935 * matrix' dimesion is larger than 7.
937 * @return the determinant as a new expression (in expanded form)
938 * @see matrix::determinant() */
939 ex matrix::determinant_minor_dense(void) const
941 // for small matrices the algorithm does not make any sense:
945 return (m[0]*m[3]-m[2]*m[1]).expand();
947 return (m[0]*m[4]*m[8]-m[0]*m[5]*m[7]-
948 m[1]*m[3]*m[8]+m[2]*m[3]*m[7]+
949 m[1]*m[5]*m[6]-m[2]*m[4]*m[6]).expand();
951 // This algorithm can best be understood by looking at a naive
952 // implementation of Laplace-expansion, like this one:
954 // matrix minorM(this->row-1,this->col-1);
955 // for (unsigned r1=0; r1<this->row; ++r1) {
956 // // shortcut if element(r1,0) vanishes
957 // if (m[r1*col].is_zero())
959 // // assemble the minor matrix
960 // for (unsigned r=0; r<minorM.rows(); ++r) {
961 // for (unsigned c=0; c<minorM.cols(); ++c) {
963 // minorM.set(r,c,m[r*col+c+1]);
965 // minorM.set(r,c,m[(r+1)*col+c+1]);
968 // // recurse down and care for sign:
970 // det -= m[r1*col] * minorM.determinant_minor();
972 // det += m[r1*col] * minorM.determinant_minor();
974 // return det.expand();
975 // What happens is that while proceeding down many of the minors are
976 // computed more than once. In particular, there are binomial(n,k)
977 // kxk minors and each one is computed factorial(n-k) times. Therefore
978 // it is reasonable to store the results of the minors. We proceed from
979 // right to left. At each column c we only need to retrieve the minors
980 // calculated in step c-1. We therefore only have to store at most
981 // 2*binomial(n,n/2) minors.
983 // Unique flipper counter for partitioning into minors
984 vector<unsigned> Pkey;
985 Pkey.reserve(this->col);
986 // key for minor determinant (a subpartition of Pkey)
987 vector<unsigned> Mkey;
988 Mkey.reserve(this->col-1);
989 // we store our subminors in maps, keys being the rows they arise from
990 typedef map<vector<unsigned>,class ex> Rmap;
991 typedef map<vector<unsigned>,class ex>::value_type Rmap_value;
995 // initialize A with last column:
996 for (unsigned r=0; r<this->col; ++r) {
997 Pkey.erase(Pkey.begin(),Pkey.end());
999 A.insert(Rmap_value(Pkey,m[this->col*r+this->col-1]));
1001 // proceed from right to left through matrix
1002 for (int c=this->col-2; c>=0; --c) {
1003 Pkey.erase(Pkey.begin(),Pkey.end()); // don't change capacity
1004 Mkey.erase(Mkey.begin(),Mkey.end());
1005 for (unsigned i=0; i<this->col-c; ++i)
1007 unsigned fc = 0; // controls logic for our strange flipper counter
1010 for (unsigned r=0; r<this->col-c; ++r) {
1011 // maybe there is nothing to do?
1012 if (m[Pkey[r]*this->col+c].is_zero())
1014 // create the sorted key for all possible minors
1015 Mkey.erase(Mkey.begin(),Mkey.end());
1016 for (unsigned i=0; i<this->col-c; ++i)
1018 Mkey.push_back(Pkey[i]);
1019 // Fetch the minors and compute the new determinant
1021 det -= m[Pkey[r]*this->col+c]*A[Mkey];
1023 det += m[Pkey[r]*this->col+c]*A[Mkey];
1025 // prevent build-up of deep nesting of expressions saves time:
1027 // store the new determinant at its place in B:
1029 B.insert(Rmap_value(Pkey,det));
1030 // increment our strange flipper counter
1031 for (fc=this->col-c; fc>0; --fc) {
1033 if (Pkey[fc-1]<fc+c)
1037 for (unsigned j=fc; j<this->col-c; ++j)
1038 Pkey[j] = Pkey[j-1]+1;
1040 // next column, so change the role of A and B:
1049 /* Determinant using a simple Bareiss elimination scheme. Suited for
1052 * @return the determinant as a new expression (in expanded form)
1053 * @see matrix::determinant() */
1054 ex matrix::determinant_bareiss(void) const
1057 int sign = M.fraction_free_elimination();
1059 return sign*M(row-1,col-1);
1065 /** Determinant built by application of the full permutation group. This
1066 * routine is only called internally by matrix::determinant().
1067 * NOTE: it is probably inefficient in all cases and may be eliminated. */
1068 ex matrix::determinant_perm(void) const
1070 if (rows()==1) // speed things up
1075 vector<unsigned> sigma(col);
1076 for (unsigned i=0; i<col; ++i)
1080 term = (*this)(sigma[0],0);
1081 for (unsigned i=1; i<col; ++i)
1082 term *= (*this)(sigma[i],i);
1083 det += permutation_sign(sigma)*term;
1084 } while (next_permutation(sigma.begin(), sigma.end()));
1090 /** Perform the steps of an ordinary Gaussian elimination to bring the matrix
1091 * into an upper echelon form.
1093 * @return sign is 1 if an even number of rows was swapped, -1 if an odd
1094 * number of rows was swapped and 0 if the matrix is singular. */
1095 int matrix::gauss_elimination(void)
1098 ensure_if_modifiable();
1099 for (unsigned r1=0; r1<row-1; ++r1) {
1100 int indx = pivot(r1);
1102 return 0; // Note: leaves *this in a messy state.
1105 for (unsigned r2=r1+1; r2<row; ++r2) {
1106 for (unsigned c=r1+1; c<col; ++c)
1107 this->m[r2*col+c] -= this->m[r2*col+r1]*this->m[r1*col+c]/this->m[r1*col+r1];
1108 for (unsigned c=0; c<=r1; ++c)
1109 this->m[r2*col+c] = _ex0();
1117 /** Perform the steps of division free elimination to bring the matrix
1118 * into an upper echelon form.
1120 * @return sign is 1 if an even number of rows was swapped, -1 if an odd
1121 * number of rows was swapped and 0 if the matrix is singular. */
1122 int matrix::division_free_elimination(void)
1125 ensure_if_modifiable();
1126 for (unsigned r1=0; r1<row-1; ++r1) {
1127 int indx = pivot(r1);
1129 return 0; // Note: leaves *this in a messy state.
1132 for (unsigned r2=r1+1; r2<row; ++r2) {
1133 for (unsigned c=r1+1; c<col; ++c)
1134 this->m[r2*col+c] = this->m[r1*col+r1]*this->m[r2*col+c] - this->m[r2*col+r1]*this->m[r1*col+c];
1135 for (unsigned c=0; c<=r1; ++c)
1136 this->m[r2*col+c] = _ex0();
1144 /** Perform the steps of Bareiss' one-step fraction free elimination to bring
1145 * the matrix into an upper echelon form.
1147 * @return sign is 1 if an even number of rows was swapped, -1 if an odd
1148 * number of rows was swapped and 0 if the matrix is singular. */
1149 int matrix::fraction_free_elimination(void)
1154 ensure_if_modifiable();
1155 for (unsigned r1=0; r1<row-1; ++r1) {
1156 int indx = pivot(r1);
1158 return 0; // Note: leaves *this in a messy state.
1162 divisor = this->m[(r1-1)*col + (r1-1)];
1163 for (unsigned r2=r1+1; r2<row; ++r2) {
1164 for (unsigned c=r1+1; c<col; ++c)
1165 this->m[r2*col+c] = ((this->m[r1*col+r1]*this->m[r2*col+c] - this->m[r2*col+r1]*this->m[r1*col+c])/divisor).normal();
1166 for (unsigned c=0; c<=r1; ++c)
1167 this->m[r2*col+c] = _ex0();
1175 /** Partial pivoting method.
1176 * Usual pivoting (symbolic==false) returns the index to the element with the
1177 * largest absolute value in column ro and swaps the current row with the one
1178 * where the element was found. With (symbolic==true) it does the same thing
1179 * with the first non-zero element.
1181 * @param ro is the row to be inspected
1182 * @param symbolic signal if we want the first non-zero element to be pivoted
1183 * (true) or the one with the largest absolute value (false).
1184 * @return 0 if no interchange occured, -1 if all are zero (usually signaling
1185 * a degeneracy) and positive integer k means that rows ro and k were swapped.
1187 int matrix::pivot(unsigned ro, bool symbolic)
1191 if (symbolic) { // search first non-zero
1192 for (unsigned r=ro; r<row; ++r) {
1193 if (!m[r*col+ro].is_zero()) {
1198 } else { // search largest
1201 for (unsigned r=ro; r<row; ++r) {
1202 GINAC_ASSERT(is_ex_of_type(m[r*col+ro],numeric));
1203 if ((tmp = abs(ex_to_numeric(m[r*col+ro]))) > maxn &&
1210 if (m[k*col+ro].is_zero())
1212 if (k!=ro) { // swap rows
1213 ensure_if_modifiable();
1214 for (unsigned c=0; c<col; ++c) {
1215 m[k*col+c].swap(m[ro*col+c]);
1222 /** Convert list of lists to matrix. */
1223 ex lst_to_matrix(const ex &l)
1225 if (!is_ex_of_type(l, lst))
1226 throw(std::invalid_argument("argument to lst_to_matrix() must be a lst"));
1228 // Find number of rows and columns
1229 unsigned rows = l.nops(), cols = 0, i, j;
1230 for (i=0; i<rows; i++)
1231 if (l.op(i).nops() > cols)
1232 cols = l.op(i).nops();
1234 // Allocate and fill matrix
1235 matrix &m = *new matrix(rows, cols);
1236 for (i=0; i<rows; i++)
1237 for (j=0; j<cols; j++)
1238 if (l.op(i).nops() > j)
1239 m.set(i, j, l.op(i).op(j));
1249 const matrix some_matrix;
1250 const type_info & typeid_matrix=typeid(some_matrix);
1252 #ifndef NO_NAMESPACE_GINAC
1253 } // namespace GiNaC
1254 #endif // ndef NO_NAMESPACE_GINAC