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
33 #ifndef NO_NAMESPACE_GINAC
35 #endif // ndef NO_NAMESPACE_GINAC
37 GINAC_IMPLEMENT_REGISTERED_CLASS(matrix, basic)
40 // default constructor, destructor, copy constructor, assignment operator
46 /** Default ctor. Initializes to 1 x 1-dimensional zero-matrix. */
48 : inherited(TINFO_matrix), row(1), col(1)
50 debugmsg("matrix default constructor",LOGLEVEL_CONSTRUCT);
56 debugmsg("matrix destructor",LOGLEVEL_DESTRUCT);
59 matrix::matrix(const matrix & other)
61 debugmsg("matrix copy constructor",LOGLEVEL_CONSTRUCT);
65 const matrix & matrix::operator=(const matrix & other)
67 debugmsg("matrix operator=",LOGLEVEL_ASSIGNMENT);
77 void matrix::copy(const matrix & other)
79 inherited::copy(other);
82 m=other.m; // use STL's vector copying
85 void matrix::destroy(bool call_parent)
87 if (call_parent) inherited::destroy(call_parent);
96 /** Very common ctor. Initializes to r x c-dimensional zero-matrix.
98 * @param r number of rows
99 * @param c number of cols */
100 matrix::matrix(unsigned r, unsigned c)
101 : inherited(TINFO_matrix), row(r), col(c)
103 debugmsg("matrix constructor from unsigned,unsigned",LOGLEVEL_CONSTRUCT);
104 m.resize(r*c, _ex0());
109 /** Ctor from representation, for internal use only. */
110 matrix::matrix(unsigned r, unsigned c, const exvector & m2)
111 : inherited(TINFO_matrix), row(r), col(c), m(m2)
113 debugmsg("matrix constructor from unsigned,unsigned,exvector",LOGLEVEL_CONSTRUCT);
120 /** Construct object from archive_node. */
121 matrix::matrix(const archive_node &n, const lst &sym_lst) : inherited(n, sym_lst)
123 debugmsg("matrix constructor from archive_node", LOGLEVEL_CONSTRUCT);
124 if (!(n.find_unsigned("row", row)) || !(n.find_unsigned("col", col)))
125 throw (std::runtime_error("unknown matrix dimensions in archive"));
126 m.reserve(row * col);
127 for (unsigned int i=0; true; i++) {
129 if (n.find_ex("m", e, sym_lst, i))
136 /** Unarchive the object. */
137 ex matrix::unarchive(const archive_node &n, const lst &sym_lst)
139 return (new matrix(n, sym_lst))->setflag(status_flags::dynallocated);
142 /** Archive the object. */
143 void matrix::archive(archive_node &n) const
145 inherited::archive(n);
146 n.add_unsigned("row", row);
147 n.add_unsigned("col", col);
148 exvector::const_iterator i = m.begin(), iend = m.end();
156 // functions overriding virtual functions from bases classes
161 basic * matrix::duplicate() const
163 debugmsg("matrix duplicate",LOGLEVEL_DUPLICATE);
164 return new matrix(*this);
167 void matrix::print(ostream & os, unsigned upper_precedence) const
169 debugmsg("matrix print",LOGLEVEL_PRINT);
171 for (unsigned r=0; r<row-1; ++r) {
173 for (unsigned c=0; c<col-1; ++c) {
174 os << m[r*col+c] << ",";
176 os << m[col*(r+1)-1] << "]], ";
179 for (unsigned c=0; c<col-1; ++c) {
180 os << m[(row-1)*col+c] << ",";
182 os << m[row*col-1] << "]] ]]";
185 void matrix::printraw(ostream & os) const
187 debugmsg("matrix printraw",LOGLEVEL_PRINT);
188 os << "matrix(" << row << "," << col <<",";
189 for (unsigned r=0; r<row-1; ++r) {
191 for (unsigned c=0; c<col-1; ++c) {
192 os << m[r*col+c] << ",";
194 os << m[col*(r-1)-1] << "),";
197 for (unsigned c=0; c<col-1; ++c) {
198 os << m[(row-1)*col+c] << ",";
200 os << m[row*col-1] << "))";
203 /** nops is defined to be rows x columns. */
204 unsigned matrix::nops() const
209 /** returns matrix entry at position (i/col, i%col). */
210 ex matrix::op(int i) const
215 /** returns matrix entry at position (i/col, i%col). */
216 ex & matrix::let_op(int i)
221 /** expands the elements of a matrix entry by entry. */
222 ex matrix::expand(unsigned options) const
224 exvector tmp(row*col);
225 for (unsigned i=0; i<row*col; ++i) {
226 tmp[i]=m[i].expand(options);
228 return matrix(row, col, tmp);
231 /** Search ocurrences. A matrix 'has' an expression if it is the expression
232 * itself or one of the elements 'has' it. */
233 bool matrix::has(const ex & other) const
235 GINAC_ASSERT(other.bp!=0);
237 // tautology: it is the expression itself
238 if (is_equal(*other.bp)) return true;
240 // search all the elements
241 for (exvector::const_iterator r=m.begin(); r!=m.end(); ++r) {
242 if ((*r).has(other)) return true;
247 /** evaluate matrix entry by entry. */
248 ex matrix::eval(int level) const
250 debugmsg("matrix eval",LOGLEVEL_MEMBER_FUNCTION);
252 // check if we have to do anything at all
253 if ((level==1)&&(flags & status_flags::evaluated))
257 if (level == -max_recursion_level)
258 throw (std::runtime_error("matrix::eval(): recursion limit exceeded"));
260 // eval() entry by entry
261 exvector m2(row*col);
263 for (unsigned r=0; r<row; ++r) {
264 for (unsigned c=0; c<col; ++c) {
265 m2[r*col+c] = m[r*col+c].eval(level);
269 return (new matrix(row, col, m2))->setflag(status_flags::dynallocated |
270 status_flags::evaluated );
273 /** evaluate matrix numerically entry by entry. */
274 ex matrix::evalf(int level) const
276 debugmsg("matrix evalf",LOGLEVEL_MEMBER_FUNCTION);
278 // check if we have to do anything at all
283 if (level == -max_recursion_level) {
284 throw (std::runtime_error("matrix::evalf(): recursion limit exceeded"));
287 // evalf() entry by entry
288 exvector m2(row*col);
290 for (unsigned r=0; r<row; ++r) {
291 for (unsigned c=0; c<col; ++c) {
292 m2[r*col+c] = m[r*col+c].evalf(level);
295 return matrix(row, col, m2);
300 int matrix::compare_same_type(const basic & other) const
302 GINAC_ASSERT(is_exactly_of_type(other, matrix));
303 const matrix & o = static_cast<matrix &>(const_cast<basic &>(other));
305 // compare number of rows
307 return row < o.rows() ? -1 : 1;
309 // compare number of columns
311 return col < o.cols() ? -1 : 1;
313 // equal number of rows and columns, compare individual elements
315 for (unsigned r=0; r<row; ++r) {
316 for (unsigned c=0; c<col; ++c) {
317 cmpval = ((*this)(r,c)).compare(o(r,c));
318 if (cmpval!=0) return cmpval;
321 // all elements are equal => matrices are equal;
326 // non-virtual functions in this class
333 * @exception logic_error (incompatible matrices) */
334 matrix matrix::add(const matrix & other) const
336 if (col != other.col || row != other.row)
337 throw (std::logic_error("matrix::add(): incompatible matrices"));
339 exvector sum(this->m);
340 exvector::iterator i;
341 exvector::const_iterator ci;
342 for (i=sum.begin(), ci=other.m.begin();
347 return matrix(row,col,sum);
351 /** Difference of matrices.
353 * @exception logic_error (incompatible matrices) */
354 matrix matrix::sub(const matrix & other) const
356 if (col != other.col || row != other.row)
357 throw (std::logic_error("matrix::sub(): incompatible matrices"));
359 exvector dif(this->m);
360 exvector::iterator i;
361 exvector::const_iterator ci;
362 for (i=dif.begin(), ci=other.m.begin();
367 return matrix(row,col,dif);
371 /** Product of matrices.
373 * @exception logic_error (incompatible matrices) */
374 matrix matrix::mul(const matrix & other) const
376 if (col != other.row)
377 throw (std::logic_error("matrix::mul(): incompatible matrices"));
379 exvector prod(row*other.col);
380 for (unsigned i=0; i<row; ++i) {
381 for (unsigned j=0; j<other.col; ++j) {
382 for (unsigned l=0; l<col; ++l) {
383 prod[i*other.col+j] += m[i*col+l] * other.m[l*other.col+j];
387 return matrix(row, other.col, prod);
391 /** operator() to access elements.
393 * @param ro row of element
394 * @param co column of element
395 * @exception range_error (index out of range) */
396 const ex & matrix::operator() (unsigned ro, unsigned co) const
398 if (ro<0 || ro>=row || co<0 || co>=col)
399 throw (std::range_error("matrix::operator(): index out of range"));
405 /** Set individual elements manually.
407 * @exception range_error (index out of range) */
408 matrix & matrix::set(unsigned ro, unsigned co, ex value)
410 if (ro<0 || ro>=row || co<0 || co>=col)
411 throw (std::range_error("matrix::set(): index out of range"));
413 ensure_if_modifiable();
414 m[ro*col+co] = value;
419 /** Transposed of an m x n matrix, producing a new n x m matrix object that
420 * represents the transposed. */
421 matrix matrix::transpose(void) const
423 exvector trans(col*row);
425 for (unsigned r=0; r<col; ++r)
426 for (unsigned c=0; c<row; ++c)
427 trans[r*row+c] = m[c*col+r];
429 return matrix(col,row,trans);
433 /** Determinant of square matrix. This routine doesn't actually calculate the
434 * determinant, it only implements some heuristics about which algorithm to
435 * call. If all the elements of the matrix are elements of an integral domain
436 * the determinant is also in that integral domain and the result is expanded
437 * only. If one or more elements are from a quotient field the determinant is
438 * usually also in that quotient field and the result is normalized before it
439 * is returned. This implies that the determinant of the symbolic 2x2 matrix
440 * [[a/(a-b),1],[b/(a-b),1]] is returned as unity. (In this respect, it
441 * behaves like MapleV and unlike Mathematica.)
443 * @return the determinant as a new expression
444 * @exception logic_error (matrix not square) */
445 ex matrix::determinant(void) const
448 throw (std::logic_error("matrix::determinant(): matrix not square"));
449 GINAC_ASSERT(row*col==m.capacity());
450 if (this->row==1) // continuation would be pointless
453 bool numeric_flag = true;
454 bool normal_flag = false;
455 unsigned sparse_count = 0; // count non-zero elements
456 for (exvector::const_iterator r=m.begin(); r!=m.end(); ++r) {
457 if (!(*r).is_zero()) {
460 if (!(*r).info(info_flags::numeric)) {
461 numeric_flag = false;
463 if ((*r).info(info_flags::rational_function) &&
464 !(*r).info(info_flags::crational_polynomial)) {
470 return determinant_numeric();
472 // Now come the minor expansion schemes. We always develop such that the
473 // smallest minors (i.e, the trivial 1x1 ones) are on the rightmost column.
474 // For this to be efficient it turns out that the emptiest columns (i.e.
475 // the ones with most zeros) should be the ones on the right hand side.
476 // Therefore we presort the columns of the matrix:
477 typedef pair<unsigned,unsigned> uintpair; // # of zeros, column
478 vector<uintpair> c_zeros; // number of zeros in column
479 for (unsigned c=0; c<col; ++c) {
481 for (unsigned r=0; r<row; ++r)
482 if (m[r*col+c].is_zero())
484 c_zeros.push_back(uintpair(acc,c));
486 sort(c_zeros.begin(),c_zeros.end());
487 vector<unsigned> pre_sort; // unfortunately vector<uintpair> can't be used
488 // for permutation_sign.
489 for (vector<uintpair>::iterator i=c_zeros.begin(); i!=c_zeros.end(); ++i)
490 pre_sort.push_back(i->second);
491 int sign = permutation_sign(pre_sort);
492 exvector result(row*col); // represents sorted matrix
494 for (vector<unsigned>::iterator i=pre_sort.begin();
497 for (unsigned r=0; r<row; ++r)
498 result[r*col+c] = m[r*col+(*i)];
501 if (0*sparse_count>row*col) { // MAGIC, maybe 10 some day?
503 return sign*matrix(row,col,result).determinant_minor_sparse().normal();
504 return sign*matrix(row,col,result).determinant_minor_sparse();
507 return sign*matrix(row,col,result).determinant_minor_dense().normal();
508 return sign*matrix(row,col,result).determinant_minor_dense();
512 /** Trace of a matrix. The result is normalized if it is in some quotient
513 * field and expanded only otherwise. This implies that the trace of the
514 * symbolic 2x2 matrix [[a/(a-b),x],[y,b/(b-a)]] is recognized to be unity.
516 * @return the sum of diagonal elements
517 * @exception logic_error (matrix not square) */
518 ex matrix::trace(void) const
521 throw (std::logic_error("matrix::trace(): matrix not square"));
522 GINAC_ASSERT(row*col==m.capacity());
525 for (unsigned r=0; r<col; ++r)
528 if (tr.info(info_flags::rational_function) &&
529 !tr.info(info_flags::crational_polynomial))
536 /** Characteristic Polynomial. The characteristic polynomial of a matrix M is
537 * defined as the determiant of (M - lambda * 1) where 1 stands for the unit
538 * matrix of the same dimension as M. This method returns the characteristic
539 * polynomial as a new expression.
541 * @return characteristic polynomial as new expression
542 * @exception logic_error (matrix not square)
543 * @see matrix::determinant() */
544 ex matrix::charpoly(const ex & lambda) const
547 throw (std::logic_error("matrix::charpoly(): matrix not square"));
550 for (unsigned r=0; r<col; ++r)
551 M.m[r*col+r] -= lambda;
553 return (M.determinant());
557 /** Inverse of this matrix.
559 * @return the inverted matrix
560 * @exception logic_error (matrix not square)
561 * @exception runtime_error (singular matrix) */
562 matrix matrix::inverse(void) const
565 throw (std::logic_error("matrix::inverse(): matrix not square"));
568 // set tmp to the unit matrix
569 for (unsigned i=0; i<col; ++i)
570 tmp.m[i*col+i] = _ex1();
572 // create a copy of this matrix
574 for (unsigned r1=0; r1<row; ++r1) {
575 int indx = cpy.pivot(r1);
577 throw (std::runtime_error("matrix::inverse(): singular matrix"));
579 if (indx != 0) { // swap rows r and indx of matrix tmp
580 for (unsigned i=0; i<col; ++i) {
581 tmp.m[r1*col+i].swap(tmp.m[indx*col+i]);
584 ex a1 = cpy.m[r1*col+r1];
585 for (unsigned c=0; c<col; ++c) {
586 cpy.m[r1*col+c] /= a1;
587 tmp.m[r1*col+c] /= a1;
589 for (unsigned r2=0; r2<row; ++r2) {
591 ex a2 = cpy.m[r2*col+r1];
592 for (unsigned c=0; c<col; ++c) {
593 cpy.m[r2*col+c] -= a2 * cpy.m[r1*col+c];
594 tmp.m[r2*col+c] -= a2 * tmp.m[r1*col+c];
603 // superfluous helper function
604 void matrix::ffe_swap(unsigned r1, unsigned c1, unsigned r2 ,unsigned c2)
606 ensure_if_modifiable();
608 ex tmp = ffe_get(r1,c1);
609 ffe_set(r1,c1,ffe_get(r2,c2));
613 // superfluous helper function
614 void matrix::ffe_set(unsigned r, unsigned c, ex e)
619 // superfluous helper function
620 ex matrix::ffe_get(unsigned r, unsigned c) const
622 return operator()(r-1,c-1);
625 /** Solve a set of equations for an m x n matrix by fraction-free Gaussian
626 * elimination. Based on algorithm 9.1 from 'Algorithms for Computer Algebra'
627 * by Keith O. Geddes et al.
629 * @param vars n x p matrix
630 * @param rhs m x p matrix
631 * @exception logic_error (incompatible matrices)
632 * @exception runtime_error (singular matrix) */
633 matrix matrix::fraction_free_elim(const matrix & vars,
634 const matrix & rhs) const
636 // FIXME: implement a Sasaki-Murao scheme which avoids division at all!
637 if ((row != rhs.row) || (col != vars.row) || (rhs.col != vars.col))
638 throw (std::logic_error("matrix::fraction_free_elim(): incompatible matrices"));
640 matrix a(*this); // make a copy of the matrix
641 matrix b(rhs); // make a copy of the rhs vector
643 // given an m x n matrix a, reduce it to upper echelon form
650 // eliminate below row r, with pivot in column k
651 for (unsigned k=1; (k<=n)&&(r<=m); ++k) {
652 // find a nonzero pivot
654 for (p=r; (p<=m)&&(a.ffe_get(p,k).is_equal(_ex0())); ++p) {}
658 // switch rows p and r
659 for (unsigned j=k; j<=n; ++j)
662 // keep track of sign changes due to row exchange
665 for (unsigned i=r+1; i<=m; ++i) {
666 for (unsigned j=k+1; j<=n; ++j) {
667 a.ffe_set(i,j,(a.ffe_get(r,k)*a.ffe_get(i,j)
668 -a.ffe_get(r,j)*a.ffe_get(i,k))/divisor);
669 a.ffe_set(i,j,a.ffe_get(i,j).normal() /*.normal() */ );
671 b.ffe_set(i,1,(a.ffe_get(r,k)*b.ffe_get(i,1)
672 -b.ffe_get(r,1)*a.ffe_get(i,k))/divisor);
673 b.ffe_set(i,1,b.ffe_get(i,1).normal() /*.normal() */ );
676 divisor = a.ffe_get(r,k);
680 // optionally compute the determinant for square or augmented matrices
681 // if (r==m+1) { det = sign*divisor; } else { det = 0; }
684 for (unsigned r=1; r<=m; ++r) {
685 for (unsigned c=1; c<=n; ++c) {
686 cout << a.ffe_get(r,c) << "\t";
688 cout << " | " << b.ffe_get(r,1) << endl;
692 #ifdef DO_GINAC_ASSERT
693 // test if we really have an upper echelon matrix
694 int zero_in_last_row = -1;
695 for (unsigned r=1; r<=m; ++r) {
696 int zero_in_this_row=0;
697 for (unsigned c=1; c<=n; ++c) {
698 if (a.ffe_get(r,c).is_equal(_ex0()))
703 GINAC_ASSERT((zero_in_this_row>zero_in_last_row)||(zero_in_this_row=n));
704 zero_in_last_row = zero_in_this_row;
706 #endif // def DO_GINAC_ASSERT
709 cout << "after" << endl;
710 cout << "a=" << a << endl;
711 cout << "b=" << b << endl;
716 unsigned last_assigned_sol = n+1;
717 for (unsigned r=m; r>0; --r) {
718 unsigned first_non_zero = 1;
719 while ((first_non_zero<=n)&&(a.ffe_get(r,first_non_zero).is_zero()))
721 if (first_non_zero>n) {
722 // row consists only of zeroes, corresponding rhs must be 0 as well
723 if (!b.ffe_get(r,1).is_zero()) {
724 throw (std::runtime_error("matrix::fraction_free_elim(): singular matrix"));
727 // assign solutions for vars between first_non_zero+1 and
728 // last_assigned_sol-1: free parameters
729 for (unsigned c=first_non_zero+1; c<=last_assigned_sol-1; ++c) {
730 sol.ffe_set(c,1,vars.ffe_get(c,1));
732 ex e = b.ffe_get(r,1);
733 for (unsigned c=first_non_zero+1; c<=n; ++c) {
734 e=e-a.ffe_get(r,c)*sol.ffe_get(c,1);
736 sol.ffe_set(first_non_zero,1,
737 (e/a.ffe_get(r,first_non_zero)).normal());
738 last_assigned_sol = first_non_zero;
741 // assign solutions for vars between 1 and
742 // last_assigned_sol-1: free parameters
743 for (unsigned c=1; c<=last_assigned_sol-1; ++c)
744 sol.ffe_set(c,1,vars.ffe_get(c,1));
746 #ifdef DO_GINAC_ASSERT
747 // test solution with echelon matrix
748 for (unsigned r=1; r<=m; ++r) {
750 for (unsigned c=1; c<=n; ++c)
751 e = e+a.ffe_get(r,c)*sol.ffe_get(c,1);
752 if (!(e-b.ffe_get(r,1)).normal().is_zero()) {
754 cout << "b.ffe_get(" << r<<",1)=" << b.ffe_get(r,1) << endl;
755 cout << "diff=" << (e-b.ffe_get(r,1)).normal() << endl;
757 GINAC_ASSERT((e-b.ffe_get(r,1)).normal().is_zero());
760 // test solution with original matrix
761 for (unsigned r=1; r<=m; ++r) {
763 for (unsigned c=1; c<=n; ++c)
764 e = e+ffe_get(r,c)*sol.ffe_get(c,1);
766 if (!(e-rhs.ffe_get(r,1)).normal().is_zero()) {
767 cout << "e=" << e << endl;
770 cout << "e.normal()=" << en << endl;
772 cout << "rhs.ffe_get(" << r<<",1)=" << rhs.ffe_get(r,1) << endl;
773 cout << "diff=" << (e-rhs.ffe_get(r,1)).normal() << endl;
776 ex xxx = e - rhs.ffe_get(r,1);
777 cerr << "xxx=" << xxx << endl << endl;
779 GINAC_ASSERT((e-rhs.ffe_get(r,1)).normal().is_zero());
781 #endif // def DO_GINAC_ASSERT
786 /** Solve a set of equations for an m x n matrix.
788 * @param vars n x p matrix
789 * @param rhs m x p matrix
790 * @exception logic_error (incompatible matrices)
791 * @exception runtime_error (singular matrix) */
792 matrix matrix::solve(const matrix & vars,
793 const matrix & rhs) const
795 if ((row != rhs.row) || (col != vars.row) || (rhs.col != vars.col))
796 throw (std::logic_error("matrix::solve(): incompatible matrices"));
798 throw (std::runtime_error("FIXME: need implementation."));
801 /** Old and obsolete interface: */
802 matrix matrix::old_solve(const matrix & v) const
804 if ((v.row != col) || (col != v.row))
805 throw (std::logic_error("matrix::solve(): incompatible matrices"));
807 // build the augmented matrix of *this with v attached to the right
808 matrix tmp(row,col+v.col);
809 for (unsigned r=0; r<row; ++r) {
810 for (unsigned c=0; c<col; ++c)
811 tmp.m[r*tmp.col+c] = this->m[r*col+c];
812 for (unsigned c=0; c<v.col; ++c)
813 tmp.m[r*tmp.col+c+col] = v.m[r*v.col+c];
815 // cout << "augmented: " << tmp << endl;
816 tmp.gauss_elimination();
817 // cout << "degaussed: " << tmp << endl;
818 // assemble the solution matrix
819 exvector sol(v.row*v.col);
820 for (unsigned c=0; c<v.col; ++c) {
821 for (unsigned r=row; r>0; --r) {
822 for (unsigned i=r; i<col; ++i)
823 sol[(r-1)*v.col+c] -= tmp.m[(r-1)*tmp.col+i]*sol[i*v.col+c];
824 sol[(r-1)*v.col+c] += tmp.m[(r-1)*tmp.col+col+c];
825 sol[(r-1)*v.col+c] = (sol[(r-1)*v.col+c]/tmp.m[(r-1)*tmp.col+(r-1)]).normal();
828 return matrix(v.row, v.col, sol);
834 /** Determinant of purely numeric matrix, using pivoting.
836 * @see matrix::determinant() */
837 ex matrix::determinant_numeric(void) const
843 for (unsigned r1=0; r1<row; ++r1) {
844 int indx = tmp.pivot(r1);
849 det = det * tmp.m[r1*col+r1];
850 for (unsigned r2=r1+1; r2<row; ++r2) {
851 piv = tmp.m[r2*col+r1] / tmp.m[r1*col+r1];
852 for (unsigned c=r1+1; c<col; c++) {
853 tmp.m[r2*col+c] -= piv * tmp.m[r1*col+c];
862 /* Leverrier algorithm for large matrices having at least one symbolic entry.
863 * This routine is only called internally by matrix::determinant(). The
864 * algorithm is very bad for symbolic matrices since it returns expressions
865 * that are quite hard to expand. */
866 /*ex matrix::determinant_leverrier(const matrix & M)
868 * GINAC_ASSERT(M.rows()==M.cols()); // cannot happen, just in case...
871 * matrix I(M.row, M.col);
873 * for (unsigned i=1; i<M.row; ++i) {
874 * for (unsigned j=0; j<M.row; ++j)
875 * I.m[j*M.col+j] = c;
876 * B = M.mul(B.sub(I));
877 * c = B.trace()/ex(i+1);
887 ex matrix::determinant_minor_sparse(void) const
889 // for small matrices the algorithm does not make any sense:
893 return (m[0]*m[3]-m[2]*m[1]).expand();
895 return (m[0]*m[4]*m[8]-m[0]*m[5]*m[7]-
896 m[1]*m[3]*m[8]+m[2]*m[3]*m[7]+
897 m[1]*m[5]*m[6]-m[2]*m[4]*m[6]).expand();
900 matrix minorM(this->row-1,this->col-1);
901 for (unsigned r1=0; r1<this->row; ++r1) {
902 // shortcut if element(r1,0) vanishes
903 if (m[r1*col].is_zero())
905 // assemble the minor matrix
906 for (unsigned r=0; r<minorM.rows(); ++r) {
907 for (unsigned c=0; c<minorM.cols(); ++c) {
909 minorM.set(r,c,m[r*col+c+1]);
911 minorM.set(r,c,m[(r+1)*col+c+1]);
914 // recurse down and care for sign:
916 det -= m[r1*col] * minorM.determinant_minor_sparse();
918 det += m[r1*col] * minorM.determinant_minor_sparse();
923 /** Recursive determinant for small matrices having at least one symbolic
924 * entry. The basic algorithm, known as Laplace-expansion, is enhanced by
925 * some bookkeeping to avoid calculation of the same submatrices ("minors")
926 * more than once. According to W.M.Gentleman and S.C.Johnson this algorithm
927 * is better than elimination schemes for matrices of sparse multivariate
928 * polynomials and also for matrices of dense univariate polynomials if the
929 * matrix' dimesion is larger than 7.
931 * @return the determinant as a new expression (in expanded form)
932 * @see matrix::determinant() */
933 ex matrix::determinant_minor_dense(void) const
935 // for small matrices the algorithm does not make any sense:
939 return (m[0]*m[3]-m[2]*m[1]).expand();
941 return (m[0]*m[4]*m[8]-m[0]*m[5]*m[7]-
942 m[1]*m[3]*m[8]+m[2]*m[3]*m[7]+
943 m[1]*m[5]*m[6]-m[2]*m[4]*m[6]).expand();
945 // This algorithm can best be understood by looking at a naive
946 // implementation of Laplace-expansion, like this one:
948 // matrix minorM(this->row-1,this->col-1);
949 // for (unsigned r1=0; r1<this->row; ++r1) {
950 // // shortcut if element(r1,0) vanishes
951 // if (m[r1*col].is_zero())
953 // // assemble the minor matrix
954 // for (unsigned r=0; r<minorM.rows(); ++r) {
955 // for (unsigned c=0; c<minorM.cols(); ++c) {
957 // minorM.set(r,c,m[r*col+c+1]);
959 // minorM.set(r,c,m[(r+1)*col+c+1]);
962 // // recurse down and care for sign:
964 // det -= m[r1*col] * minorM.determinant_minor();
966 // det += m[r1*col] * minorM.determinant_minor();
968 // return det.expand();
969 // What happens is that while proceeding down many of the minors are
970 // computed more than once. In particular, there are binomial(n,k)
971 // kxk minors and each one is computed factorial(n-k) times. Therefore
972 // it is reasonable to store the results of the minors. We proceed from
973 // right to left. At each column c we only need to retrieve the minors
974 // calculated in step c-1. We therefore only have to store at most
975 // 2*binomial(n,n/2) minors.
977 // Unique flipper counter for partitioning into minors
978 vector<unsigned> Pkey;
979 Pkey.reserve(this->col);
980 // key for minor determinant (a subpartition of Pkey)
981 vector<unsigned> Mkey;
982 Mkey.reserve(this->col-1);
983 // we store our subminors in maps, keys being the rows they arise from
984 typedef map<vector<unsigned>,class ex> Rmap;
985 typedef map<vector<unsigned>,class ex>::value_type Rmap_value;
989 // initialize A with last column:
990 for (unsigned r=0; r<this->col; ++r) {
991 Pkey.erase(Pkey.begin(),Pkey.end());
993 A.insert(Rmap_value(Pkey,m[this->col*r+this->col-1]));
995 // proceed from right to left through matrix
996 for (int c=this->col-2; c>=0; --c) {
997 Pkey.erase(Pkey.begin(),Pkey.end()); // don't change capacity
998 Mkey.erase(Mkey.begin(),Mkey.end());
999 for (unsigned i=0; i<this->col-c; ++i)
1001 unsigned fc = 0; // controls logic for our strange flipper counter
1004 for (unsigned r=0; r<this->col-c; ++r) {
1005 // maybe there is nothing to do?
1006 if (m[Pkey[r]*this->col+c].is_zero())
1008 // create the sorted key for all possible minors
1009 Mkey.erase(Mkey.begin(),Mkey.end());
1010 for (unsigned i=0; i<this->col-c; ++i)
1012 Mkey.push_back(Pkey[i]);
1013 // Fetch the minors and compute the new determinant
1015 det -= m[Pkey[r]*this->col+c]*A[Mkey];
1017 det += m[Pkey[r]*this->col+c]*A[Mkey];
1019 // prevent build-up of deep nesting of expressions saves time:
1021 // store the new determinant at its place in B:
1023 B.insert(Rmap_value(Pkey,det));
1024 // increment our strange flipper counter
1025 for (fc=this->col-c; fc>0; --fc) {
1027 if (Pkey[fc-1]<fc+c)
1031 for (unsigned j=fc; j<this->col-c; ++j)
1032 Pkey[j] = Pkey[j-1]+1;
1034 // next column, so change the role of A and B:
1043 /* Determinant using a simple Bareiss elimination scheme. Suited for
1046 * @return the determinant as a new expression (in expanded form)
1047 * @see matrix::determinant() */
1048 ex matrix::determinant_bareiss(void) const
1051 int sign = M.fraction_free_elimination();
1053 return sign*M(row-1,col-1);
1059 /** Determinant built by application of the full permutation group. This
1060 * routine is only called internally by matrix::determinant().
1061 * NOTE: it is probably inefficient in all cases and may be eliminated. */
1062 ex matrix::determinant_perm(void) const
1064 if (rows()==1) // speed things up
1069 vector<unsigned> sigma(col);
1070 for (unsigned i=0; i<col; ++i)
1074 term = (*this)(sigma[0],0);
1075 for (unsigned i=1; i<col; ++i)
1076 term *= (*this)(sigma[i],i);
1077 det += permutation_sign(sigma)*term;
1078 } while (next_permutation(sigma.begin(), sigma.end()));
1084 /** Perform the steps of an ordinary Gaussian elimination to bring the matrix
1085 * into an upper echelon form.
1087 * @return sign is 1 if an even number of rows was swapped, -1 if an odd
1088 * number of rows was swapped and 0 if the matrix is singular. */
1089 int matrix::gauss_elimination(void)
1092 ensure_if_modifiable();
1093 for (unsigned r1=0; r1<row-1; ++r1) {
1094 int indx = pivot(r1);
1096 return 0; // Note: leaves *this in a messy state.
1099 for (unsigned r2=r1+1; r2<row; ++r2) {
1100 for (unsigned c=r1+1; c<col; ++c)
1101 this->m[r2*col+c] -= this->m[r2*col+r1]*this->m[r1*col+c]/this->m[r1*col+r1];
1102 for (unsigned c=0; c<=r1; ++c)
1103 this->m[r2*col+c] = _ex0();
1111 /** Perform the steps of division free elimination to bring the matrix
1112 * into an upper echelon form.
1114 * @return sign is 1 if an even number of rows was swapped, -1 if an odd
1115 * number of rows was swapped and 0 if the matrix is singular. */
1116 int matrix::division_free_elimination(void)
1119 ensure_if_modifiable();
1120 for (unsigned r1=0; r1<row-1; ++r1) {
1121 int indx = pivot(r1);
1123 return 0; // Note: leaves *this in a messy state.
1126 for (unsigned r2=r1+1; r2<row; ++r2) {
1127 for (unsigned c=r1+1; c<col; ++c)
1128 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];
1129 for (unsigned c=0; c<=r1; ++c)
1130 this->m[r2*col+c] = _ex0();
1138 /** Perform the steps of Bareiss' one-step fraction free elimination to bring
1139 * the matrix into an upper echelon form.
1141 * @return sign is 1 if an even number of rows was swapped, -1 if an odd
1142 * number of rows was swapped and 0 if the matrix is singular. */
1143 int matrix::fraction_free_elimination(void)
1148 ensure_if_modifiable();
1149 for (unsigned r1=0; r1<row-1; ++r1) {
1150 int indx = pivot(r1);
1152 return 0; // Note: leaves *this in a messy state.
1156 divisor = this->m[(r1-1)*col + (r1-1)];
1157 for (unsigned r2=r1+1; r2<row; ++r2) {
1158 for (unsigned c=r1+1; c<col; ++c)
1159 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();
1160 for (unsigned c=0; c<=r1; ++c)
1161 this->m[r2*col+c] = _ex0();
1169 /** Partial pivoting method.
1170 * Usual pivoting (symbolic==false) returns the index to the element with the
1171 * largest absolute value in column ro and swaps the current row with the one
1172 * where the element was found. With (symbolic==true) it does the same thing
1173 * with the first non-zero element.
1175 * @param ro is the row to be inspected
1176 * @param symbolic signal if we want the first non-zero element to be pivoted
1177 * (true) or the one with the largest absolute value (false).
1178 * @return 0 if no interchange occured, -1 if all are zero (usually signaling
1179 * a degeneracy) and positive integer k means that rows ro and k were swapped.
1181 int matrix::pivot(unsigned ro, bool symbolic)
1185 if (symbolic) { // search first non-zero
1186 for (unsigned r=ro; r<row; ++r) {
1187 if (!m[r*col+ro].is_zero()) {
1192 } else { // search largest
1195 for (unsigned r=ro; r<row; ++r) {
1196 GINAC_ASSERT(is_ex_of_type(m[r*col+ro],numeric));
1197 if ((tmp = abs(ex_to_numeric(m[r*col+ro]))) > maxn &&
1204 if (m[k*col+ro].is_zero())
1206 if (k!=ro) { // swap rows
1207 ensure_if_modifiable();
1208 for (unsigned c=0; c<col; ++c) {
1209 m[k*col+c].swap(m[ro*col+c]);
1220 const matrix some_matrix;
1221 const type_info & typeid_matrix=typeid(some_matrix);
1223 #ifndef NO_NAMESPACE_GINAC
1224 } // namespace GiNaC
1225 #endif // ndef NO_NAMESPACE_GINAC