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
37 #ifndef NO_NAMESPACE_GINAC
39 #endif // ndef NO_NAMESPACE_GINAC
41 GINAC_IMPLEMENT_REGISTERED_CLASS(matrix, basic)
44 // default constructor, destructor, copy constructor, assignment operator
50 /** Default ctor. Initializes to 1 x 1-dimensional zero-matrix. */
52 : inherited(TINFO_matrix), row(1), col(1)
54 debugmsg("matrix default constructor",LOGLEVEL_CONSTRUCT);
60 debugmsg("matrix destructor",LOGLEVEL_DESTRUCT);
63 matrix::matrix(const matrix & other)
65 debugmsg("matrix copy constructor",LOGLEVEL_CONSTRUCT);
69 const matrix & matrix::operator=(const matrix & other)
71 debugmsg("matrix operator=",LOGLEVEL_ASSIGNMENT);
81 void matrix::copy(const matrix & other)
83 inherited::copy(other);
86 m = other.m; // STL's vector copying invoked here
89 void matrix::destroy(bool call_parent)
91 if (call_parent) inherited::destroy(call_parent);
100 /** Very common ctor. Initializes to r x c-dimensional zero-matrix.
102 * @param r number of rows
103 * @param c number of cols */
104 matrix::matrix(unsigned r, unsigned c)
105 : inherited(TINFO_matrix), row(r), col(c)
107 debugmsg("matrix constructor from unsigned,unsigned",LOGLEVEL_CONSTRUCT);
108 m.resize(r*c, _ex0());
113 /** Ctor from representation, for internal use only. */
114 matrix::matrix(unsigned r, unsigned c, const exvector & m2)
115 : inherited(TINFO_matrix), row(r), col(c), m(m2)
117 debugmsg("matrix constructor from unsigned,unsigned,exvector",LOGLEVEL_CONSTRUCT);
124 /** Construct object from archive_node. */
125 matrix::matrix(const archive_node &n, const lst &sym_lst) : inherited(n, sym_lst)
127 debugmsg("matrix constructor from archive_node", LOGLEVEL_CONSTRUCT);
128 if (!(n.find_unsigned("row", row)) || !(n.find_unsigned("col", col)))
129 throw (std::runtime_error("unknown matrix dimensions in archive"));
130 m.reserve(row * col);
131 for (unsigned int i=0; true; i++) {
133 if (n.find_ex("m", e, sym_lst, i))
140 /** Unarchive the object. */
141 ex matrix::unarchive(const archive_node &n, const lst &sym_lst)
143 return (new matrix(n, sym_lst))->setflag(status_flags::dynallocated);
146 /** Archive the object. */
147 void matrix::archive(archive_node &n) const
149 inherited::archive(n);
150 n.add_unsigned("row", row);
151 n.add_unsigned("col", col);
152 exvector::const_iterator i = m.begin(), iend = m.end();
160 // functions overriding virtual functions from bases classes
165 basic * matrix::duplicate() const
167 debugmsg("matrix duplicate",LOGLEVEL_DUPLICATE);
168 return new matrix(*this);
171 void matrix::print(std::ostream & os, unsigned upper_precedence) const
173 debugmsg("matrix print",LOGLEVEL_PRINT);
175 for (unsigned r=0; r<row-1; ++r) {
177 for (unsigned c=0; c<col-1; ++c)
178 os << m[r*col+c] << ",";
179 os << m[col*(r+1)-1] << "]], ";
182 for (unsigned c=0; c<col-1; ++c)
183 os << m[(row-1)*col+c] << ",";
184 os << m[row*col-1] << "]] ]]";
187 void matrix::printraw(std::ostream & os) const
189 debugmsg("matrix printraw",LOGLEVEL_PRINT);
190 os << "matrix(" << row << "," << col <<",";
191 for (unsigned r=0; r<row-1; ++r) {
193 for (unsigned c=0; c<col-1; ++c)
194 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] << ",";
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)
219 GINAC_ASSERT(i<nops());
224 /** expands the elements of a matrix entry by entry. */
225 ex matrix::expand(unsigned options) const
227 exvector tmp(row*col);
228 for (unsigned i=0; i<row*col; ++i)
229 tmp[i] = m[i].expand(options);
231 return matrix(row, col, tmp);
234 /** Search ocurrences. A matrix 'has' an expression if it is the expression
235 * itself or one of the elements 'has' it. */
236 bool matrix::has(const ex & other) const
238 GINAC_ASSERT(other.bp!=0);
240 // tautology: it is the expression itself
241 if (is_equal(*other.bp)) return true;
243 // search all the elements
244 for (exvector::const_iterator r=m.begin(); r!=m.end(); ++r)
245 if ((*r).has(other)) return true;
250 /** evaluate matrix entry by entry. */
251 ex matrix::eval(int level) const
253 debugmsg("matrix eval",LOGLEVEL_MEMBER_FUNCTION);
255 // check if we have to do anything at all
256 if ((level==1)&&(flags & status_flags::evaluated))
260 if (level == -max_recursion_level)
261 throw (std::runtime_error("matrix::eval(): recursion limit exceeded"));
263 // eval() entry by entry
264 exvector m2(row*col);
266 for (unsigned r=0; r<row; ++r)
267 for (unsigned c=0; c<col; ++c)
268 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);
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(); i!=sum.end(); ++i, ++ci)
345 return matrix(row,col,sum);
349 /** Difference of matrices.
351 * @exception logic_error (incompatible matrices) */
352 matrix matrix::sub(const matrix & other) const
354 if (col != other.col || row != other.row)
355 throw (std::logic_error("matrix::sub(): incompatible matrices"));
357 exvector dif(this->m);
358 exvector::iterator i;
359 exvector::const_iterator ci;
360 for (i=dif.begin(), ci=other.m.begin(); i!=dif.end(); ++i, ++ci)
363 return matrix(row,col,dif);
367 /** Product of matrices.
369 * @exception logic_error (incompatible matrices) */
370 matrix matrix::mul(const matrix & other) const
372 if (col != other.row)
373 throw (std::logic_error("matrix::mul(): incompatible matrices"));
375 exvector prod(row*other.col);
377 for (unsigned r1=0; r1<rows(); ++r1) {
378 for (unsigned c=0; c<cols(); ++c) {
379 if (m[r1*col+c].is_zero())
381 for (unsigned r2=0; r2<other.col; ++r2)
382 prod[r1*other.col+r2] += m[r1*col+c] * other.m[c*other.col+r2];
385 return matrix(row, other.col, prod);
389 /** operator() to access elements.
391 * @param ro row of element
392 * @param co column of element
393 * @exception range_error (index out of range) */
394 const ex & matrix::operator() (unsigned ro, unsigned co) const
396 if (ro<0 || ro>=row || co<0 || co>=col)
397 throw (std::range_error("matrix::operator(): index out of range"));
403 /** Set individual elements manually.
405 * @exception range_error (index out of range) */
406 matrix & matrix::set(unsigned ro, unsigned co, ex value)
408 if (ro<0 || ro>=row || co<0 || co>=col)
409 throw (std::range_error("matrix::set(): index out of range"));
411 ensure_if_modifiable();
412 m[ro*col+co] = value;
417 /** Transposed of an m x n matrix, producing a new n x m matrix object that
418 * represents the transposed. */
419 matrix matrix::transpose(void) const
421 exvector trans(col*row);
423 for (unsigned r=0; r<col; ++r)
424 for (unsigned c=0; c<row; ++c)
425 trans[r*row+c] = m[c*col+r];
427 return matrix(col,row,trans);
431 /** Determinant of square matrix. This routine doesn't actually calculate the
432 * determinant, it only implements some heuristics about which algorithm to
433 * run. If all the elements of the matrix are elements of an integral domain
434 * the determinant is also in that integral domain and the result is expanded
435 * only. If one or more elements are from a quotient field the determinant is
436 * usually also in that quotient field and the result is normalized before it
437 * is returned. This implies that the determinant of the symbolic 2x2 matrix
438 * [[a/(a-b),1],[b/(a-b),1]] is returned as unity. (In this respect, it
439 * behaves like MapleV and unlike Mathematica.)
441 * @param algo allows to chose an algorithm
442 * @return the determinant as a new expression
443 * @exception logic_error (matrix not square)
444 * @see determinant_algo */
445 ex matrix::determinant(unsigned algo) 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 // Gather some statistical information about this matrix:
454 bool numeric_flag = true;
455 bool normal_flag = false;
456 unsigned sparse_count = 0; // counts non-zero elements
457 for (exvector::const_iterator r=m.begin(); r!=m.end(); ++r) {
458 lst srl; // symbol replacement list
459 ex rtest = (*r).to_rational(srl);
460 if (!rtest.is_zero())
462 if (!rtest.info(info_flags::numeric))
463 numeric_flag = false;
464 if (!rtest.info(info_flags::crational_polynomial) &&
465 rtest.info(info_flags::rational_function))
469 // Here is the heuristics in case this routine has to decide:
470 if (algo == determinant_algo::automatic) {
471 // Minor expansion is generally a good starting point:
472 algo = determinant_algo::laplace;
473 // Does anybody know when a matrix is really sparse?
474 // Maybe <~row/2.236 nonzero elements average in a row?
475 if (5*sparse_count<=row*col)
476 algo = determinant_algo::bareiss;
477 // Purely numeric matrix can be handled by Gauss elimination.
478 // This overrides any prior decisions.
480 algo = determinant_algo::gauss;
484 case determinant_algo::gauss: {
487 int sign = tmp.gauss_elimination();
488 for (unsigned d=0; d<row; ++d)
489 det *= tmp.m[d*col+d];
491 return (sign*det).normal();
493 return (sign*det).expand();
495 case determinant_algo::bareiss: {
498 sign = tmp.fraction_free_elimination(true);
500 return (sign*tmp.m[row*col-1]).normal();
502 return (sign*tmp.m[row*col-1]).expand();
504 case determinant_algo::laplace:
506 // This is the minor expansion scheme. We always develop such
507 // that the smallest minors (i.e, the trivial 1x1 ones) are on the
508 // rightmost column. For this to be efficient it turns out that
509 // the emptiest columns (i.e. the ones with most zeros) should be
510 // the ones on the right hand side. Therefore we presort the
511 // columns of the matrix:
512 typedef std::pair<unsigned,unsigned> uintpair;
513 std::vector<uintpair> c_zeros; // number of zeros in column
514 for (unsigned c=0; c<col; ++c) {
516 for (unsigned r=0; r<row; ++r)
517 if (m[r*col+c].is_zero())
519 c_zeros.push_back(uintpair(acc,c));
521 sort(c_zeros.begin(),c_zeros.end());
522 std::vector<unsigned> pre_sort;
523 for (std::vector<uintpair>::iterator i=c_zeros.begin(); i!=c_zeros.end(); ++i)
524 pre_sort.push_back(i->second);
525 int sign = permutation_sign(pre_sort);
526 exvector result(row*col); // represents sorted matrix
528 for (std::vector<unsigned>::iterator i=pre_sort.begin();
531 for (unsigned r=0; r<row; ++r)
532 result[r*col+c] = m[r*col+(*i)];
536 return sign*matrix(row,col,result).determinant_minor().normal();
537 return sign*matrix(row,col,result).determinant_minor();
543 /** Trace of a matrix. The result is normalized if it is in some quotient
544 * field and expanded only otherwise. This implies that the trace of the
545 * symbolic 2x2 matrix [[a/(a-b),x],[y,b/(b-a)]] is recognized to be unity.
547 * @return the sum of diagonal elements
548 * @exception logic_error (matrix not square) */
549 ex matrix::trace(void) const
552 throw (std::logic_error("matrix::trace(): matrix not square"));
553 GINAC_ASSERT(row*col==m.capacity());
556 for (unsigned r=0; r<col; ++r)
559 if (tr.info(info_flags::rational_function) &&
560 !tr.info(info_flags::crational_polynomial))
567 /** Characteristic Polynomial. Following mathematica notation the
568 * characteristic polynomial of a matrix M is defined as the determiant of
569 * (M - lambda * 1) where 1 stands for the unit matrix of the same dimension
570 * as M. Note that some CASs define it with a sign inside the determinant
571 * which gives rise to an overall sign if the dimension is odd. This method
572 * returns the characteristic polynomial collected in powers of lambda as a
575 * @return characteristic polynomial as new expression
576 * @exception logic_error (matrix not square)
577 * @see matrix::determinant() */
578 ex matrix::charpoly(const symbol & lambda) const
581 throw (std::logic_error("matrix::charpoly(): matrix not square"));
583 bool numeric_flag = true;
584 for (exvector::const_iterator r=m.begin(); r!=m.end(); ++r) {
585 if (!(*r).info(info_flags::numeric)) {
586 numeric_flag = false;
590 // The pure numeric case is traditionally rather common. Hence, it is
591 // trapped and we use Leverrier's algorithm which goes as row^3 for
592 // every coefficient. The expensive part is the matrix multiplication.
596 ex poly = power(lambda,row)-c*power(lambda,row-1);
597 for (unsigned i=1; i<row; ++i) {
598 for (unsigned j=0; j<row; ++j)
601 c = B.trace()/ex(i+1);
602 poly -= c*power(lambda,row-i-1);
611 for (unsigned r=0; r<col; ++r)
612 M.m[r*col+r] -= lambda;
614 return M.determinant().collect(lambda);
618 /** Inverse of this matrix.
620 * @return the inverted matrix
621 * @exception logic_error (matrix not square)
622 * @exception runtime_error (singular matrix) */
623 matrix matrix::inverse(void) const
626 throw (std::logic_error("matrix::inverse(): matrix not square"));
629 // set tmp to the unit matrix
630 for (unsigned i=0; i<col; ++i)
631 tmp.m[i*col+i] = _ex1();
633 // create a copy of this matrix
635 for (unsigned r1=0; r1<row; ++r1) {
636 int indx = cpy.pivot(r1);
638 throw (std::runtime_error("matrix::inverse(): singular matrix"));
640 if (indx != 0) { // swap rows r and indx of matrix tmp
641 for (unsigned i=0; i<col; ++i)
642 tmp.m[r1*col+i].swap(tmp.m[indx*col+i]);
644 ex a1 = cpy.m[r1*col+r1];
645 for (unsigned c=0; c<col; ++c) {
646 cpy.m[r1*col+c] /= a1;
647 tmp.m[r1*col+c] /= a1;
649 for (unsigned r2=0; r2<row; ++r2) {
651 ex a2 = cpy.m[r2*col+r1];
652 for (unsigned c=0; c<col; ++c) {
653 cpy.m[r2*col+c] -= a2 * cpy.m[r1*col+c];
654 tmp.m[r2*col+c] -= a2 * tmp.m[r1*col+c];
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(const matrix & vars,
672 const matrix & rhs) const
674 // FIXME: use implementation of matrix::fraction_free_elimination instead!
675 if ((row != rhs.row) || (col != vars.row) || (rhs.col != vars.col))
676 throw (std::logic_error("matrix::fraction_free_elim(): 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 (unsigned k=0; (k<n)&&(r<m); ++k) {
690 // find a nonzero pivot
692 for (p=r; (p<m)&&(a.m[p*a.cols()+k].is_zero()); ++p) {}
697 for (unsigned j=k; j<n; ++j)
698 a.m[p*a.cols()+j].swap(a.m[r*a.cols()+j]);
699 b.m[p*b.cols()].swap(b.m[r*b.cols()]);
700 // keep track of sign changes due to row exchange
703 for (unsigned i=r+1; i<m; ++i) {
704 for (unsigned j=k+1; j<n; ++j) {
705 a.set(i,j,(a.m[r*a.cols()+k]*a.m[i*a.cols()+j]
706 -a.m[r*a.cols()+j]*a.m[i*a.cols()+k])/divisor);
707 a.set(i,j,a.m[i*a.cols()+j].normal());
709 b.set(i,0,(a.m[r*a.cols()+k]*b.m[i*b.cols()]
710 -b.m[r*b.cols()]*a.m[i*a.cols()+k])/divisor);
711 b.set(i,0,b.m[i*b.cols()].normal());
714 divisor = a.m[r*a.cols()+k];
719 #ifdef DO_GINAC_ASSERT
720 // test if we really have an upper echelon matrix
721 int zero_in_last_row = -1;
722 for (unsigned r=0; r<m; ++r) {
723 int zero_in_this_row=0;
724 for (unsigned c=0; c<n; ++c) {
725 if (a.m[r*a.cols()+c].is_zero())
730 GINAC_ASSERT((zero_in_this_row>zero_in_last_row)||(zero_in_this_row=n));
731 zero_in_last_row = zero_in_this_row;
733 #endif // def DO_GINAC_ASSERT
737 unsigned last_assigned_sol = n+1;
738 for (int r=m-1; r>=0; --r) {
739 unsigned first_non_zero = 1;
740 while ((first_non_zero<=n)&&(a(r,first_non_zero-1).is_zero()))
742 if (first_non_zero>n) {
743 // row consists only of zeroes, corresponding rhs must be 0 as well
744 if (!b.m[r*b.cols()].is_zero()) {
745 throw (std::runtime_error("matrix::fraction_free_elim(): singular matrix"));
748 // assign solutions for vars between first_non_zero+1 and
749 // last_assigned_sol-1: free parameters
750 for (unsigned c=first_non_zero; c<last_assigned_sol-1; ++c)
751 sol.set(c,0,vars.m[c*vars.cols()]);
752 ex e = b.m[r*b.cols()];
753 for (unsigned c=first_non_zero; c<n; ++c)
754 e -= a.m[r*a.cols()+c]*sol.m[c*sol.cols()];
755 sol.set(first_non_zero-1,0,
756 (e/(a.m[r*a.cols()+(first_non_zero-1)])).normal());
757 last_assigned_sol = first_non_zero;
760 // assign solutions for vars between 1 and
761 // last_assigned_sol-1: free parameters
762 for (unsigned c=0; c<last_assigned_sol-1; ++c)
763 sol.set(c,0,vars.m[c*vars.cols()]);
765 #ifdef DO_GINAC_ASSERT
766 // test solution with echelon matrix
767 for (unsigned r=0; r<m; ++r) {
769 for (unsigned c=0; c<n; ++c)
770 e += a(r,c)*sol(c,0);
771 if (!(e-b(r,0)).normal().is_zero()) {
773 cout << "b(" << r <<",0)=" << b(r,0) << endl;
774 cout << "diff=" << (e-b(r,0)).normal() << endl;
776 GINAC_ASSERT((e-b(r,0)).normal().is_zero());
779 // test solution with original matrix
780 for (unsigned r=0; r<m; ++r) {
782 for (unsigned c=0; c<n; ++c)
783 e += this->m[r*cols()+c]*sol(c,0);
785 if (!(e-rhs(r,0)).normal().is_zero()) {
786 cout << "e==" << e << endl;
789 cout << "e.normal()=" << en << endl;
791 cout << "rhs(" << r <<",0)=" << rhs(r,0) << endl;
792 cout << "diff=" << (e-rhs(r,0)).normal() << endl;
795 ex xxx = e - rhs(r,0);
796 cerr << "xxx=" << xxx << endl << endl;
798 GINAC_ASSERT((e-rhs(r,0)).normal().is_zero());
800 #endif // def DO_GINAC_ASSERT
805 /** Solve a set of equations for an m x n matrix.
807 * @param vars n x p matrix
808 * @param rhs m x p matrix
809 * @exception logic_error (incompatible matrices)
810 * @exception runtime_error (singular matrix) */
811 matrix matrix::solve(const matrix & vars,
812 const matrix & rhs) const
814 if ((row != rhs.row) || (col != vars.row) || (rhs.col != vars.col))
815 throw (std::logic_error("matrix::solve(): incompatible matrices"));
817 throw (std::runtime_error("FIXME: need implementation."));
820 /** Old and obsolete interface: */
821 matrix matrix::old_solve(const matrix & v) const
823 if ((v.row != col) || (col != v.row))
824 throw (std::logic_error("matrix::solve(): incompatible matrices"));
826 // build the augmented matrix of *this with v attached to the right
827 matrix tmp(row,col+v.col);
828 for (unsigned r=0; r<row; ++r) {
829 for (unsigned c=0; c<col; ++c)
830 tmp.m[r*tmp.col+c] = this->m[r*col+c];
831 for (unsigned c=0; c<v.col; ++c)
832 tmp.m[r*tmp.col+c+col] = v.m[r*v.col+c];
834 // cout << "augmented: " << tmp << endl;
835 tmp.gauss_elimination();
836 // cout << "degaussed: " << tmp << endl;
837 // assemble the solution matrix
838 exvector sol(v.row*v.col);
839 for (unsigned c=0; c<v.col; ++c) {
840 for (unsigned r=row; r>0; --r) {
841 for (unsigned i=r; i<col; ++i)
842 sol[(r-1)*v.col+c] -= tmp.m[(r-1)*tmp.col+i]*sol[i*v.col+c];
843 sol[(r-1)*v.col+c] += tmp.m[(r-1)*tmp.col+col+c];
844 sol[(r-1)*v.col+c] = (sol[(r-1)*v.col+c]/tmp.m[(r-1)*tmp.col+(r-1)]).normal();
847 return matrix(v.row, v.col, sol);
853 /** Recursive determinant for small matrices having at least one symbolic
854 * entry. The basic algorithm, known as Laplace-expansion, is enhanced by
855 * some bookkeeping to avoid calculation of the same submatrices ("minors")
856 * more than once. According to W.M.Gentleman and S.C.Johnson this algorithm
857 * is better than elimination schemes for matrices of sparse multivariate
858 * polynomials and also for matrices of dense univariate polynomials if the
859 * matrix' dimesion is larger than 7.
861 * @return the determinant as a new expression (in expanded form)
862 * @see matrix::determinant() */
863 ex matrix::determinant_minor(void) const
865 // for small matrices the algorithm does not make any sense:
869 return (m[0]*m[3]-m[2]*m[1]).expand();
871 return (m[0]*m[4]*m[8]-m[0]*m[5]*m[7]-
872 m[1]*m[3]*m[8]+m[2]*m[3]*m[7]+
873 m[1]*m[5]*m[6]-m[2]*m[4]*m[6]).expand();
875 // This algorithm can best be understood by looking at a naive
876 // implementation of Laplace-expansion, like this one:
878 // matrix minorM(this->row-1,this->col-1);
879 // for (unsigned r1=0; r1<this->row; ++r1) {
880 // // shortcut if element(r1,0) vanishes
881 // if (m[r1*col].is_zero())
883 // // assemble the minor matrix
884 // for (unsigned r=0; r<minorM.rows(); ++r) {
885 // for (unsigned c=0; c<minorM.cols(); ++c) {
887 // minorM.set(r,c,m[r*col+c+1]);
889 // minorM.set(r,c,m[(r+1)*col+c+1]);
892 // // recurse down and care for sign:
894 // det -= m[r1*col] * minorM.determinant_minor();
896 // det += m[r1*col] * minorM.determinant_minor();
898 // return det.expand();
899 // What happens is that while proceeding down many of the minors are
900 // computed more than once. In particular, there are binomial(n,k)
901 // kxk minors and each one is computed factorial(n-k) times. Therefore
902 // it is reasonable to store the results of the minors. We proceed from
903 // right to left. At each column c we only need to retrieve the minors
904 // calculated in step c-1. We therefore only have to store at most
905 // 2*binomial(n,n/2) minors.
907 // Unique flipper counter for partitioning into minors
908 std::vector<unsigned> Pkey;
909 Pkey.reserve(this->col);
910 // key for minor determinant (a subpartition of Pkey)
911 std::vector<unsigned> Mkey;
912 Mkey.reserve(this->col-1);
913 // we store our subminors in maps, keys being the rows they arise from
914 typedef std::map<std::vector<unsigned>,class ex> Rmap;
915 typedef std::map<std::vector<unsigned>,class ex>::value_type Rmap_value;
919 // initialize A with last column:
920 for (unsigned r=0; r<this->col; ++r) {
921 Pkey.erase(Pkey.begin(),Pkey.end());
923 A.insert(Rmap_value(Pkey,m[this->col*r+this->col-1]));
925 // proceed from right to left through matrix
926 for (int c=this->col-2; c>=0; --c) {
927 Pkey.erase(Pkey.begin(),Pkey.end()); // don't change capacity
928 Mkey.erase(Mkey.begin(),Mkey.end());
929 for (unsigned i=0; i<this->col-c; ++i)
931 unsigned fc = 0; // controls logic for our strange flipper counter
934 for (unsigned r=0; r<this->col-c; ++r) {
935 // maybe there is nothing to do?
936 if (m[Pkey[r]*this->col+c].is_zero())
938 // create the sorted key for all possible minors
939 Mkey.erase(Mkey.begin(),Mkey.end());
940 for (unsigned i=0; i<this->col-c; ++i)
942 Mkey.push_back(Pkey[i]);
943 // Fetch the minors and compute the new determinant
945 det -= m[Pkey[r]*this->col+c]*A[Mkey];
947 det += m[Pkey[r]*this->col+c]*A[Mkey];
949 // prevent build-up of deep nesting of expressions saves time:
951 // store the new determinant at its place in B:
953 B.insert(Rmap_value(Pkey,det));
954 // increment our strange flipper counter
955 for (fc=this->col-c; fc>0; --fc) {
961 for (unsigned j=fc; j<this->col-c; ++j)
962 Pkey[j] = Pkey[j-1]+1;
964 // next column, so change the role of A and B:
973 /** Perform the steps of an ordinary Gaussian elimination to bring the matrix
974 * into an upper echelon form.
976 * @return sign is 1 if an even number of rows was swapped, -1 if an odd
977 * number of rows was swapped and 0 if the matrix is singular. */
978 int matrix::gauss_elimination(void)
980 ensure_if_modifiable();
983 for (unsigned r1=0; r1<row-1; ++r1) {
984 int indx = pivot(r1);
986 return 0; // Note: leaves *this in a messy state.
989 for (unsigned r2=r1+1; r2<row; ++r2) {
990 piv = this->m[r2*col+r1] / this->m[r1*col+r1];
991 for (unsigned c=r1+1; c<col; ++c)
992 this->m[r2*col+c] -= piv * this->m[r1*col+c];
993 for (unsigned c=0; c<=r1; ++c)
994 this->m[r2*col+c] = _ex0();
1002 /** Perform the steps of division free elimination to bring the matrix
1003 * into an upper echelon form.
1005 * @return sign is 1 if an even number of rows was swapped, -1 if an odd
1006 * number of rows was swapped and 0 if the matrix is singular. */
1007 int matrix::division_free_elimination(void)
1010 ensure_if_modifiable();
1011 for (unsigned r1=0; r1<row-1; ++r1) {
1012 int indx = pivot(r1);
1014 return 0; // Note: leaves *this in a messy state.
1017 for (unsigned r2=r1+1; r2<row; ++r2) {
1018 for (unsigned c=r1+1; c<col; ++c)
1019 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];
1020 for (unsigned c=0; c<=r1; ++c)
1021 this->m[r2*col+c] = _ex0();
1029 /** Perform the steps of Bareiss' one-step fraction free elimination to bring
1030 * the matrix into an upper echelon form. Fraction free elimination means
1031 * that divide is used straightforwardly, without computing GCDs first. This
1032 * is possible, since we know the divisor at each step.
1034 * @param det may be set to true to save a lot of space if one is only
1035 * interested in the last element (i.e. for calculating determinants), the
1036 * others are set to zero in this case.
1037 * @return sign is 1 if an even number of rows was swapped, -1 if an odd
1038 * number of rows was swapped and 0 if the matrix is singular. */
1039 int matrix::fraction_free_elimination(bool det)
1042 // (single-step fraction free elimination scheme, already known to Jordan)
1044 // Usual division-free elimination sets m[0](r,c) = m(r,c) and then sets
1045 // m[k+1](r,c) = m[k](k,k) * m[k](r,c) - m[k](r,k) * m[k](k,c).
1047 // Bareiss (fraction-free) elimination in addition divides that element
1048 // by m[k-1](k-1,k-1) for k>1, where it can be shown by means of the
1049 // Sylvester determinant that this really divides m[k+1](r,c).
1051 // We also allow rational functions where the original prove still holds.
1052 // However, we must care for numerator and denominator separately and
1053 // "manually" work in the integral domains because of subtle cancellations
1054 // (see below). This blows up the bookkeeping a bit and the formula has
1055 // to be modified to expand like this (N{x} stands for numerator of x,
1056 // D{x} for denominator of x):
1057 // N{m[k+1](r,c)} = N{m[k](k,k)}*N{m[k](r,c)}*D{m[k](r,k)}*D{m[k](k,c)}
1058 // -N{m[k](r,k)}*N{m[k](k,c)}*D{m[k](k,k)}*D{m[k](r,c)}
1059 // D{m[k+1](r,c)} = D{m[k](k,k)}*D{m[k](r,c)}*D{m[k](r,k)}*D{m[k](k,c)}
1060 // where for k>1 we now divide N{m[k+1](r,c)} by
1061 // N{m[k-1](k-1,k-1)}
1062 // and D{m[k+1](r,c)} by
1063 // D{m[k-1](k-1,k-1)}.
1065 GINAC_ASSERT(!det || row==col);
1066 ensure_if_modifiable();
1076 // We populate temporary matrices to subsequently operate on. There is
1077 // one holding numerators and another holding denominators of entries.
1078 // This is a must since the evaluator (or even earlier mul's constructor)
1079 // might cancel some trivial element which causes divide() to fail. The
1080 // elements are normalized first (yes, even though this algorithm doesn't
1081 // need GCDs) since the elements of *this might be unnormalized, which
1082 // makes things more complicated than they need to be.
1083 matrix tmp_n(*this);
1084 matrix tmp_d(row,col); // for denominators, if needed
1085 lst srl; // symbol replacement list
1086 exvector::iterator it = m.begin();
1087 exvector::iterator tmp_n_it = tmp_n.m.begin();
1088 exvector::iterator tmp_d_it = tmp_d.m.begin();
1089 for (; it!= m.end(); ++it, ++tmp_n_it, ++tmp_d_it) {
1090 (*tmp_n_it) = (*it).normal().to_rational(srl);
1091 (*tmp_d_it) = (*tmp_n_it).denom();
1092 (*tmp_n_it) = (*tmp_n_it).numer();
1095 for (unsigned r1=0; r1<row-1; ++r1) {
1096 int indx = tmp_n.pivot(r1);
1097 if (det && indx==-1)
1098 return 0; // FIXME: what to do if det is false, some day?
1101 // rows r1 and indx were swapped, so pivot matrix tmp_d:
1102 for (unsigned c=0; c<col; ++c)
1103 tmp_d.m[row*indx+c].swap(tmp_d.m[row*r1+c]);
1106 divisor_n = tmp_n.m[(r1-1)*col+(r1-1)].expand();
1107 divisor_d = tmp_d.m[(r1-1)*col+(r1-1)].expand();
1108 // save space by deleting no longer needed elements:
1110 for (unsigned c=0; c<col; ++c) {
1111 tmp_n.m[(r1-1)*col+c] = 0;
1112 tmp_d.m[(r1-1)*col+c] = 1;
1116 for (unsigned r2=r1+1; r2<row; ++r2) {
1117 for (unsigned c=r1+1; c<col; ++c) {
1118 dividend_n = (tmp_n.m[r1*col+r1]*tmp_n.m[r2*col+c]*
1119 tmp_d.m[r2*col+r1]*tmp_d.m[r1*col+c]
1120 -tmp_n.m[r2*col+r1]*tmp_n.m[r1*col+c]*
1121 tmp_d.m[r1*col+r1]*tmp_d.m[r2*col+c]).expand();
1122 dividend_d = (tmp_d.m[r2*col+r1]*tmp_d.m[r1*col+c]*
1123 tmp_d.m[r1*col+r1]*tmp_d.m[r2*col+c]).expand();
1124 bool check = divide(dividend_n, divisor_n,
1125 tmp_n.m[r2*col+c],true);
1126 check &= divide(dividend_d, divisor_d,
1127 tmp_d.m[r2*col+c],true);
1128 GINAC_ASSERT(check);
1130 // fill up left hand side.
1131 for (unsigned c=0; c<=r1; ++c)
1132 tmp_n.m[r2*col+c] = _ex0();
1135 // repopulate *this matrix:
1137 tmp_n_it = tmp_n.m.begin();
1138 tmp_d_it = tmp_d.m.begin();
1139 for (; it!= m.end(); ++it, ++tmp_n_it, ++tmp_d_it)
1140 (*it) = ((*tmp_n_it)/(*tmp_d_it)).subs(srl);
1146 /** Partial pivoting method for matrix elimination schemes.
1147 * Usual pivoting (symbolic==false) returns the index to the element with the
1148 * largest absolute value in column ro and swaps the current row with the one
1149 * where the element was found. With (symbolic==true) it does the same thing
1150 * with the first non-zero element.
1152 * @param ro is the row to be inspected
1153 * @param symbolic signal if we want the first non-zero element to be pivoted
1154 * (true) or the one with the largest absolute value (false).
1155 * @return 0 if no interchange occured, -1 if all are zero (usually signaling
1156 * a degeneracy) and positive integer k means that rows ro and k were swapped.
1158 int matrix::pivot(unsigned ro, bool symbolic)
1162 if (symbolic) { // search first non-zero
1163 for (unsigned r=ro; r<row; ++r) {
1164 if (!m[r*col+ro].expand().is_zero()) {
1169 } else { // search largest
1172 for (unsigned r=ro; r<row; ++r) {
1173 GINAC_ASSERT(is_ex_of_type(m[r*col+ro],numeric));
1174 if ((tmp = abs(ex_to_numeric(m[r*col+ro]))) > maxn &&
1181 if (m[k*col+ro].is_zero())
1183 if (k!=ro) { // swap rows
1184 ensure_if_modifiable();
1185 for (unsigned c=0; c<col; ++c) {
1186 m[k*col+c].swap(m[ro*col+c]);
1193 /** Convert list of lists to matrix. */
1194 ex lst_to_matrix(const ex &l)
1196 if (!is_ex_of_type(l, lst))
1197 throw(std::invalid_argument("argument to lst_to_matrix() must be a lst"));
1199 // Find number of rows and columns
1200 unsigned rows = l.nops(), cols = 0, i, j;
1201 for (i=0; i<rows; i++)
1202 if (l.op(i).nops() > cols)
1203 cols = l.op(i).nops();
1205 // Allocate and fill matrix
1206 matrix &m = *new matrix(rows, cols);
1207 for (i=0; i<rows; i++)
1208 for (j=0; j<cols; j++)
1209 if (l.op(i).nops() > j)
1210 m.set(i, j, l.op(i).op(j));
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