]> www.ginac.de Git - ginac.git/blob - ginac/matrix.cpp
Use neseted initializer lists to construct matrix objects.
[ginac.git] / ginac / matrix.cpp
1 /** @file matrix.cpp
2  *
3  *  Implementation of symbolic matrices */
4
5 /*
6  *  GiNaC Copyright (C) 1999-2015 Johannes Gutenberg University Mainz, Germany
7  *
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.
12  *
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.
17  *
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., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
21  */
22
23 #include "matrix.h"
24 #include "numeric.h"
25 #include "lst.h"
26 #include "idx.h"
27 #include "indexed.h"
28 #include "add.h"
29 #include "power.h"
30 #include "symbol.h"
31 #include "operators.h"
32 #include "normal.h"
33 #include "archive.h"
34 #include "utils.h"
35
36 #include <algorithm>
37 #include <iostream>
38 #include <map>
39 #include <sstream>
40 #include <stdexcept>
41 #include <string>
42
43 namespace GiNaC {
44
45 GINAC_IMPLEMENT_REGISTERED_CLASS_OPT(matrix, basic,
46   print_func<print_context>(&matrix::do_print).
47   print_func<print_latex>(&matrix::do_print_latex).
48   print_func<print_tree>(&matrix::do_print_tree).
49   print_func<print_python_repr>(&matrix::do_print_python_repr))
50
51 //////////
52 // default constructor
53 //////////
54
55 /** Default ctor.  Initializes to 1 x 1-dimensional zero-matrix. */
56 matrix::matrix() : row(1), col(1), m(1, _ex0)
57 {
58         setflag(status_flags::not_shareable);
59 }
60
61 //////////
62 // other constructors
63 //////////
64
65 // public
66
67 /** Very common ctor.  Initializes to r x c-dimensional zero-matrix.
68  *
69  *  @param r number of rows
70  *  @param c number of cols */
71 matrix::matrix(unsigned r, unsigned c) : row(r), col(c), m(r*c, _ex0)
72 {
73         setflag(status_flags::not_shareable);
74 }
75
76 /** Construct matrix from (flat) list of elements. If the list has fewer
77  *  elements than the matrix, the remaining matrix elements are set to zero.
78  *  If the list has more elements than the matrix, the excessive elements are
79  *  thrown away. */
80 matrix::matrix(unsigned r, unsigned c, const lst & l)
81   : row(r), col(c), m(r*c, _ex0)
82 {
83         setflag(status_flags::not_shareable);
84
85         size_t i = 0;
86         for (auto & it : l) {
87                 size_t x = i % c;
88                 size_t y = i / c;
89                 if (y >= r)
90                         break; // matrix smaller than list: throw away excessive elements
91                 m[y*c+x] = it;
92                 ++i;
93         }
94 }
95
96 /** Construct a matrix from an 2 dimensional initializer list.
97  *  Throws an exception if some row has a different length than all the others.
98  */
99 matrix::matrix(std::initializer_list<std::initializer_list<ex>> l)
100   : row(l.size()), col(l.begin()->size())
101 {
102         setflag(status_flags::not_shareable);
103
104         m.reserve(row*col);
105         for (const auto & r : l) {
106                 unsigned c = 0;
107                 for (const auto & e : r) {
108                         m.push_back(e);
109                         ++c;
110                 }
111                 if (c != col)
112                         throw std::invalid_argument("matrix::matrix{{}}: wrong dimension");
113         }
114 }
115
116 // protected
117
118 /** Ctor from representation, for internal use only. */
119 matrix::matrix(unsigned r, unsigned c, const exvector & m2)
120   : row(r), col(c), m(m2)
121 {
122         setflag(status_flags::not_shareable);
123 }
124 matrix::matrix(unsigned r, unsigned c, exvector && m2)
125   : row(r), col(c), m(std::move(m2))
126 {
127         setflag(status_flags::not_shareable);
128 }
129
130 //////////
131 // archiving
132 //////////
133
134 void matrix::read_archive(const archive_node &n, lst &sym_lst)
135 {
136         inherited::read_archive(n, sym_lst);
137
138         if (!(n.find_unsigned("row", row)) || !(n.find_unsigned("col", col)))
139                 throw (std::runtime_error("unknown matrix dimensions in archive"));
140         m.reserve(row * col);
141         // XXX: default ctor inserts a zero element, we need to erase it here.
142         m.pop_back();
143         auto first = n.find_first("m");
144         auto last = n.find_last("m");
145         ++last;
146         for (auto i=first; i != last; ++i) {
147                 ex e;
148                 n.find_ex_by_loc(i, e, sym_lst);
149                 m.push_back(e);
150         }
151 }
152 GINAC_BIND_UNARCHIVER(matrix);
153
154 void matrix::archive(archive_node &n) const
155 {
156         inherited::archive(n);
157         n.add_unsigned("row", row);
158         n.add_unsigned("col", col);
159         for (auto & i : m) {
160                 n.add_ex("m", i);
161         }
162 }
163
164 //////////
165 // functions overriding virtual functions from base classes
166 //////////
167
168 // public
169
170 void matrix::print_elements(const print_context & c, const char *row_start, const char *row_end, const char *row_sep, const char *col_sep) const
171 {
172         for (unsigned ro=0; ro<row; ++ro) {
173                 c.s << row_start;
174                 for (unsigned co=0; co<col; ++co) {
175                         m[ro*col+co].print(c);
176                         if (co < col-1)
177                                 c.s << col_sep;
178                         else
179                                 c.s << row_end;
180                 }
181                 if (ro < row-1)
182                         c.s << row_sep;
183         }
184 }
185
186 void matrix::do_print(const print_context & c, unsigned level) const
187 {
188         c.s << "[";
189         print_elements(c, "[", "]", ",", ",");
190         c.s << "]";
191 }
192
193 void matrix::do_print_latex(const print_latex & c, unsigned level) const
194 {
195         c.s << "\\left(\\begin{array}{" << std::string(col,'c') << "}";
196         print_elements(c, "", "", "\\\\", "&");
197         c.s << "\\end{array}\\right)";
198 }
199
200 void matrix::do_print_python_repr(const print_python_repr & c, unsigned level) const
201 {
202         c.s << class_name() << '(';
203         print_elements(c, "[", "]", ",", ",");
204         c.s << ')';
205 }
206
207 /** nops is defined to be rows x columns. */
208 size_t matrix::nops() const
209 {
210         return static_cast<size_t>(row) * static_cast<size_t>(col);
211 }
212
213 /** returns matrix entry at position (i/col, i%col). */
214 ex matrix::op(size_t i) const
215 {
216         GINAC_ASSERT(i<nops());
217         
218         return m[i];
219 }
220
221 /** returns writable matrix entry at position (i/col, i%col). */
222 ex & matrix::let_op(size_t i)
223 {
224         GINAC_ASSERT(i<nops());
225         
226         ensure_if_modifiable();
227         return m[i];
228 }
229
230 /** Evaluate matrix entry by entry. */
231 ex matrix::eval(int level) const
232 {
233         // check if we have to do anything at all
234         if ((level==1)&&(flags & status_flags::evaluated))
235                 return *this;
236         
237         // emergency break
238         if (level == -max_recursion_level)
239                 throw (std::runtime_error("matrix::eval(): recursion limit exceeded"));
240         
241         // eval() entry by entry
242         exvector m2(row*col);
243         --level;
244         for (unsigned r=0; r<row; ++r)
245                 for (unsigned c=0; c<col; ++c)
246                         m2[r*col+c] = m[r*col+c].eval(level);
247         
248         return (new matrix(row, col, std::move(m2)))->setflag(status_flags::dynallocated |
249                                                               status_flags::evaluated);
250 }
251
252 ex matrix::subs(const exmap & mp, unsigned options) const
253 {
254         exvector m2(row * col);
255         for (unsigned r=0; r<row; ++r)
256                 for (unsigned c=0; c<col; ++c)
257                         m2[r*col+c] = m[r*col+c].subs(mp, options);
258
259         return matrix(row, col, std::move(m2)).subs_one_level(mp, options);
260 }
261
262 /** Complex conjugate every matrix entry. */
263 ex matrix::conjugate() const
264 {
265         std::unique_ptr<exvector> ev(nullptr);
266         for (auto i=m.begin(); i!=m.end(); ++i) {
267                 ex x = i->conjugate();
268                 if (ev) {
269                         ev->push_back(x);
270                         continue;
271                 }
272                 if (are_ex_trivially_equal(x, *i)) {
273                         continue;
274                 }
275                 ev.reset(new exvector);
276                 ev->reserve(m.size());
277                 for (auto j=m.begin(); j!=i; ++j) {
278                         ev->push_back(*j);
279                 }
280                 ev->push_back(x);
281         }
282         if (ev) {
283                 return matrix(row, col, std::move(*ev));
284         }
285         return *this;
286 }
287
288 ex matrix::real_part() const
289 {
290         exvector v;
291         v.reserve(m.size());
292         for (auto & i : m)
293                 v.push_back(i.real_part());
294         return matrix(row, col, std::move(v));
295 }
296
297 ex matrix::imag_part() const
298 {
299         exvector v;
300         v.reserve(m.size());
301         for (auto & i : m)
302                 v.push_back(i.imag_part());
303         return matrix(row, col, std::move(v));
304 }
305
306 // protected
307
308 int matrix::compare_same_type(const basic & other) const
309 {
310         GINAC_ASSERT(is_exactly_a<matrix>(other));
311         const matrix &o = static_cast<const matrix &>(other);
312         
313         // compare number of rows
314         if (row != o.rows())
315                 return row < o.rows() ? -1 : 1;
316         
317         // compare number of columns
318         if (col != o.cols())
319                 return col < o.cols() ? -1 : 1;
320         
321         // equal number of rows and columns, compare individual elements
322         int cmpval;
323         for (unsigned r=0; r<row; ++r) {
324                 for (unsigned c=0; c<col; ++c) {
325                         cmpval = ((*this)(r,c)).compare(o(r,c));
326                         if (cmpval!=0) return cmpval;
327                 }
328         }
329         // all elements are equal => matrices are equal;
330         return 0;
331 }
332
333 bool matrix::match_same_type(const basic & other) const
334 {
335         GINAC_ASSERT(is_exactly_a<matrix>(other));
336         const matrix & o = static_cast<const matrix &>(other);
337         
338         // The number of rows and columns must be the same. This is necessary to
339         // prevent a 2x3 matrix from matching a 3x2 one.
340         return row == o.rows() && col == o.cols();
341 }
342
343 /** Automatic symbolic evaluation of an indexed matrix. */
344 ex matrix::eval_indexed(const basic & i) const
345 {
346         GINAC_ASSERT(is_a<indexed>(i));
347         GINAC_ASSERT(is_a<matrix>(i.op(0)));
348
349         bool all_indices_unsigned = static_cast<const indexed &>(i).all_index_values_are(info_flags::nonnegint);
350
351         // Check indices
352         if (i.nops() == 2) {
353
354                 // One index, must be one-dimensional vector
355                 if (row != 1 && col != 1)
356                         throw (std::runtime_error("matrix::eval_indexed(): vector must have exactly 1 index"));
357
358                 const idx & i1 = ex_to<idx>(i.op(1));
359
360                 if (col == 1) {
361
362                         // Column vector
363                         if (!i1.get_dim().is_equal(row))
364                                 throw (std::runtime_error("matrix::eval_indexed(): dimension of index must match number of vector elements"));
365
366                         // Index numeric -> return vector element
367                         if (all_indices_unsigned) {
368                                 unsigned n1 = ex_to<numeric>(i1.get_value()).to_int();
369                                 if (n1 >= row)
370                                         throw (std::runtime_error("matrix::eval_indexed(): value of index exceeds number of vector elements"));
371                                 return (*this)(n1, 0);
372                         }
373
374                 } else {
375
376                         // Row vector
377                         if (!i1.get_dim().is_equal(col))
378                                 throw (std::runtime_error("matrix::eval_indexed(): dimension of index must match number of vector elements"));
379
380                         // Index numeric -> return vector element
381                         if (all_indices_unsigned) {
382                                 unsigned n1 = ex_to<numeric>(i1.get_value()).to_int();
383                                 if (n1 >= col)
384                                         throw (std::runtime_error("matrix::eval_indexed(): value of index exceeds number of vector elements"));
385                                 return (*this)(0, n1);
386                         }
387                 }
388
389         } else if (i.nops() == 3) {
390
391                 // Two indices
392                 const idx & i1 = ex_to<idx>(i.op(1));
393                 const idx & i2 = ex_to<idx>(i.op(2));
394
395                 if (!i1.get_dim().is_equal(row))
396                         throw (std::runtime_error("matrix::eval_indexed(): dimension of first index must match number of rows"));
397                 if (!i2.get_dim().is_equal(col))
398                         throw (std::runtime_error("matrix::eval_indexed(): dimension of second index must match number of columns"));
399
400                 // Pair of dummy indices -> compute trace
401                 if (is_dummy_pair(i1, i2))
402                         return trace();
403
404                 // Both indices numeric -> return matrix element
405                 if (all_indices_unsigned) {
406                         unsigned n1 = ex_to<numeric>(i1.get_value()).to_int(), n2 = ex_to<numeric>(i2.get_value()).to_int();
407                         if (n1 >= row)
408                                 throw (std::runtime_error("matrix::eval_indexed(): value of first index exceeds number of rows"));
409                         if (n2 >= col)
410                                 throw (std::runtime_error("matrix::eval_indexed(): value of second index exceeds number of columns"));
411                         return (*this)(n1, n2);
412                 }
413
414         } else
415                 throw (std::runtime_error("matrix::eval_indexed(): matrix must have exactly 2 indices"));
416
417         return i.hold();
418 }
419
420 /** Sum of two indexed matrices. */
421 ex matrix::add_indexed(const ex & self, const ex & other) const
422 {
423         GINAC_ASSERT(is_a<indexed>(self));
424         GINAC_ASSERT(is_a<matrix>(self.op(0)));
425         GINAC_ASSERT(is_a<indexed>(other));
426         GINAC_ASSERT(self.nops() == 2 || self.nops() == 3);
427
428         // Only add two matrices
429         if (is_a<matrix>(other.op(0))) {
430                 GINAC_ASSERT(other.nops() == 2 || other.nops() == 3);
431
432                 const matrix &self_matrix = ex_to<matrix>(self.op(0));
433                 const matrix &other_matrix = ex_to<matrix>(other.op(0));
434
435                 if (self.nops() == 2 && other.nops() == 2) { // vector + vector
436
437                         if (self_matrix.row == other_matrix.row)
438                                 return indexed(self_matrix.add(other_matrix), self.op(1));
439                         else if (self_matrix.row == other_matrix.col)
440                                 return indexed(self_matrix.add(other_matrix.transpose()), self.op(1));
441
442                 } else if (self.nops() == 3 && other.nops() == 3) { // matrix + matrix
443
444                         if (self.op(1).is_equal(other.op(1)) && self.op(2).is_equal(other.op(2)))
445                                 return indexed(self_matrix.add(other_matrix), self.op(1), self.op(2));
446                         else if (self.op(1).is_equal(other.op(2)) && self.op(2).is_equal(other.op(1)))
447                                 return indexed(self_matrix.add(other_matrix.transpose()), self.op(1), self.op(2));
448
449                 }
450         }
451
452         // Don't know what to do, return unevaluated sum
453         return self + other;
454 }
455
456 /** Product of an indexed matrix with a number. */
457 ex matrix::scalar_mul_indexed(const ex & self, const numeric & other) const
458 {
459         GINAC_ASSERT(is_a<indexed>(self));
460         GINAC_ASSERT(is_a<matrix>(self.op(0)));
461         GINAC_ASSERT(self.nops() == 2 || self.nops() == 3);
462
463         const matrix &self_matrix = ex_to<matrix>(self.op(0));
464
465         if (self.nops() == 2)
466                 return indexed(self_matrix.mul(other), self.op(1));
467         else // self.nops() == 3
468                 return indexed(self_matrix.mul(other), self.op(1), self.op(2));
469 }
470
471 /** Contraction of an indexed matrix with something else. */
472 bool matrix::contract_with(exvector::iterator self, exvector::iterator other, exvector & v) const
473 {
474         GINAC_ASSERT(is_a<indexed>(*self));
475         GINAC_ASSERT(is_a<indexed>(*other));
476         GINAC_ASSERT(self->nops() == 2 || self->nops() == 3);
477         GINAC_ASSERT(is_a<matrix>(self->op(0)));
478
479         // Only contract with other matrices
480         if (!is_a<matrix>(other->op(0)))
481                 return false;
482
483         GINAC_ASSERT(other->nops() == 2 || other->nops() == 3);
484
485         const matrix &self_matrix = ex_to<matrix>(self->op(0));
486         const matrix &other_matrix = ex_to<matrix>(other->op(0));
487
488         if (self->nops() == 2) {
489
490                 if (other->nops() == 2) { // vector * vector (scalar product)
491
492                         if (self_matrix.col == 1) {
493                                 if (other_matrix.col == 1) {
494                                         // Column vector * column vector, transpose first vector
495                                         *self = self_matrix.transpose().mul(other_matrix)(0, 0);
496                                 } else {
497                                         // Column vector * row vector, swap factors
498                                         *self = other_matrix.mul(self_matrix)(0, 0);
499                                 }
500                         } else {
501                                 if (other_matrix.col == 1) {
502                                         // Row vector * column vector, perfect
503                                         *self = self_matrix.mul(other_matrix)(0, 0);
504                                 } else {
505                                         // Row vector * row vector, transpose second vector
506                                         *self = self_matrix.mul(other_matrix.transpose())(0, 0);
507                                 }
508                         }
509                         *other = _ex1;
510                         return true;
511
512                 } else { // vector * matrix
513
514                         // B_i * A_ij = (B*A)_j (B is row vector)
515                         if (is_dummy_pair(self->op(1), other->op(1))) {
516                                 if (self_matrix.row == 1)
517                                         *self = indexed(self_matrix.mul(other_matrix), other->op(2));
518                                 else
519                                         *self = indexed(self_matrix.transpose().mul(other_matrix), other->op(2));
520                                 *other = _ex1;
521                                 return true;
522                         }
523
524                         // B_j * A_ij = (A*B)_i (B is column vector)
525                         if (is_dummy_pair(self->op(1), other->op(2))) {
526                                 if (self_matrix.col == 1)
527                                         *self = indexed(other_matrix.mul(self_matrix), other->op(1));
528                                 else
529                                         *self = indexed(other_matrix.mul(self_matrix.transpose()), other->op(1));
530                                 *other = _ex1;
531                                 return true;
532                         }
533                 }
534
535         } else if (other->nops() == 3) { // matrix * matrix
536
537                 // A_ij * B_jk = (A*B)_ik
538                 if (is_dummy_pair(self->op(2), other->op(1))) {
539                         *self = indexed(self_matrix.mul(other_matrix), self->op(1), other->op(2));
540                         *other = _ex1;
541                         return true;
542                 }
543
544                 // A_ij * B_kj = (A*Btrans)_ik
545                 if (is_dummy_pair(self->op(2), other->op(2))) {
546                         *self = indexed(self_matrix.mul(other_matrix.transpose()), self->op(1), other->op(1));
547                         *other = _ex1;
548                         return true;
549                 }
550
551                 // A_ji * B_jk = (Atrans*B)_ik
552                 if (is_dummy_pair(self->op(1), other->op(1))) {
553                         *self = indexed(self_matrix.transpose().mul(other_matrix), self->op(2), other->op(2));
554                         *other = _ex1;
555                         return true;
556                 }
557
558                 // A_ji * B_kj = (B*A)_ki
559                 if (is_dummy_pair(self->op(1), other->op(2))) {
560                         *self = indexed(other_matrix.mul(self_matrix), other->op(1), self->op(2));
561                         *other = _ex1;
562                         return true;
563                 }
564         }
565
566         return false;
567 }
568
569
570 //////////
571 // non-virtual functions in this class
572 //////////
573
574 // public
575
576 /** Sum of matrices.
577  *
578  *  @exception logic_error (incompatible matrices) */
579 matrix matrix::add(const matrix & other) const
580 {
581         if (col != other.col || row != other.row)
582                 throw std::logic_error("matrix::add(): incompatible matrices");
583         
584         exvector sum(this->m);
585         auto ci = other.m.begin();
586         for (auto & i : sum)
587                 i += *ci++;
588         
589         return matrix(row, col, std::move(sum));
590 }
591
592
593 /** Difference of matrices.
594  *
595  *  @exception logic_error (incompatible matrices) */
596 matrix matrix::sub(const matrix & other) const
597 {
598         if (col != other.col || row != other.row)
599                 throw std::logic_error("matrix::sub(): incompatible matrices");
600         
601         exvector dif(this->m);
602         auto ci = other.m.begin();
603         for (auto & i : dif)
604                 i -= *ci++;
605         
606         return matrix(row, col, std::move(dif));
607 }
608
609
610 /** Product of matrices.
611  *
612  *  @exception logic_error (incompatible matrices) */
613 matrix matrix::mul(const matrix & other) const
614 {
615         if (this->cols() != other.rows())
616                 throw std::logic_error("matrix::mul(): incompatible matrices");
617         
618         exvector prod(this->rows()*other.cols());
619         
620         for (unsigned r1=0; r1<this->rows(); ++r1) {
621                 for (unsigned c=0; c<this->cols(); ++c) {
622                         // Quick test: can we shortcut?
623                         if (m[r1*col+c].is_zero())
624                                 continue;
625                         for (unsigned r2=0; r2<other.cols(); ++r2)
626                                 prod[r1*other.col+r2] += (m[r1*col+c] * other.m[c*other.col+r2]);
627                 }
628         }
629         return matrix(row, other.col, std::move(prod));
630 }
631
632
633 /** Product of matrix and scalar. */
634 matrix matrix::mul(const numeric & other) const
635 {
636         exvector prod(row * col);
637
638         for (unsigned r=0; r<row; ++r)
639                 for (unsigned c=0; c<col; ++c)
640                         prod[r*col+c] = m[r*col+c] * other;
641
642         return matrix(row, col, std::move(prod));
643 }
644
645
646 /** Product of matrix and scalar expression. */
647 matrix matrix::mul_scalar(const ex & other) const
648 {
649         if (other.return_type() != return_types::commutative)
650                 throw std::runtime_error("matrix::mul_scalar(): non-commutative scalar");
651
652         exvector prod(row * col);
653
654         for (unsigned r=0; r<row; ++r)
655                 for (unsigned c=0; c<col; ++c)
656                         prod[r*col+c] = m[r*col+c] * other;
657
658         return matrix(row, col, std::move(prod));
659 }
660
661
662 /** Power of a matrix.  Currently handles integer exponents only. */
663 matrix matrix::pow(const ex & expn) const
664 {
665         if (col!=row)
666                 throw (std::logic_error("matrix::pow(): matrix not square"));
667         
668         if (is_exactly_a<numeric>(expn)) {
669                 // Integer cases are computed by successive multiplication, using the
670                 // obvious shortcut of storing temporaries, like A^4 == (A*A)*(A*A).
671                 if (expn.info(info_flags::integer)) {
672                         numeric b = ex_to<numeric>(expn);
673                         matrix A(row,col);
674                         if (expn.info(info_flags::negative)) {
675                                 b *= -1;
676                                 A = this->inverse();
677                         } else {
678                                 A = *this;
679                         }
680                         matrix C(row,col);
681                         for (unsigned r=0; r<row; ++r)
682                                 C(r,r) = _ex1;
683                         if (b.is_zero())
684                                 return C;
685                         // This loop computes the representation of b in base 2 from right
686                         // to left and multiplies the factors whenever needed.  Note
687                         // that this is not entirely optimal but close to optimal and
688                         // "better" algorithms are much harder to implement.  (See Knuth,
689                         // TAoCP2, section "Evaluation of Powers" for a good discussion.)
690                         while (b!=*_num1_p) {
691                                 if (b.is_odd()) {
692                                         C = C.mul(A);
693                                         --b;
694                                 }
695                                 b /= *_num2_p;  // still integer.
696                                 A = A.mul(A);
697                         }
698                         return A.mul(C);
699                 }
700         }
701         throw (std::runtime_error("matrix::pow(): don't know how to handle exponent"));
702 }
703
704
705 /** operator() to access elements for reading.
706  *
707  *  @param ro row of element
708  *  @param co column of element
709  *  @exception range_error (index out of range) */
710 const ex & matrix::operator() (unsigned ro, unsigned co) const
711 {
712         if (ro>=row || co>=col)
713                 throw (std::range_error("matrix::operator(): index out of range"));
714
715         return m[ro*col+co];
716 }
717
718
719 /** operator() to access elements for writing.
720  *
721  *  @param ro row of element
722  *  @param co column of element
723  *  @exception range_error (index out of range) */
724 ex & matrix::operator() (unsigned ro, unsigned co)
725 {
726         if (ro>=row || co>=col)
727                 throw (std::range_error("matrix::operator(): index out of range"));
728
729         ensure_if_modifiable();
730         return m[ro*col+co];
731 }
732
733
734 /** Transposed of an m x n matrix, producing a new n x m matrix object that
735  *  represents the transposed. */
736 matrix matrix::transpose() const
737 {
738         exvector trans(this->cols()*this->rows());
739         
740         for (unsigned r=0; r<this->cols(); ++r)
741                 for (unsigned c=0; c<this->rows(); ++c)
742                         trans[r*this->rows()+c] = m[c*this->cols()+r];
743         
744         return matrix(this->cols(), this->rows(), std::move(trans));
745 }
746
747 /** Determinant of square matrix.  This routine doesn't actually calculate the
748  *  determinant, it only implements some heuristics about which algorithm to
749  *  run.  If all the elements of the matrix are elements of an integral domain
750  *  the determinant is also in that integral domain and the result is expanded
751  *  only.  If one or more elements are from a quotient field the determinant is
752  *  usually also in that quotient field and the result is normalized before it
753  *  is returned.  This implies that the determinant of the symbolic 2x2 matrix
754  *  [[a/(a-b),1],[b/(a-b),1]] is returned as unity.  (In this respect, it
755  *  behaves like MapleV and unlike Mathematica.)
756  *
757  *  @param     algo allows to chose an algorithm
758  *  @return    the determinant as a new expression
759  *  @exception logic_error (matrix not square)
760  *  @see       determinant_algo */
761 ex matrix::determinant(unsigned algo) const
762 {
763         if (row!=col)
764                 throw (std::logic_error("matrix::determinant(): matrix not square"));
765         GINAC_ASSERT(row*col==m.capacity());
766         
767         // Gather some statistical information about this matrix:
768         bool numeric_flag = true;
769         bool normal_flag = false;
770         unsigned sparse_count = 0;  // counts non-zero elements
771         for (auto r : m) {
772                 if (!r.info(info_flags::numeric))
773                         numeric_flag = false;
774                 exmap srl;  // symbol replacement list
775                 ex rtest = r.to_rational(srl);
776                 if (!rtest.is_zero())
777                         ++sparse_count;
778                 if (!rtest.info(info_flags::crational_polynomial) &&
779                      rtest.info(info_flags::rational_function))
780                         normal_flag = true;
781         }
782         
783         // Here is the heuristics in case this routine has to decide:
784         if (algo == determinant_algo::automatic) {
785                 // Minor expansion is generally a good guess:
786                 algo = determinant_algo::laplace;
787                 // Does anybody know when a matrix is really sparse?
788                 // Maybe <~row/2.236 nonzero elements average in a row?
789                 if (row>3 && 5*sparse_count<=row*col)
790                         algo = determinant_algo::bareiss;
791                 // Purely numeric matrix can be handled by Gauss elimination.
792                 // This overrides any prior decisions.
793                 if (numeric_flag)
794                         algo = determinant_algo::gauss;
795         }
796         
797         // Trap the trivial case here, since some algorithms don't like it
798         if (this->row==1) {
799                 // for consistency with non-trivial determinants...
800                 if (normal_flag)
801                         return m[0].normal();
802                 else
803                         return m[0].expand();
804         }
805
806         // Compute the determinant
807         switch(algo) {
808                 case determinant_algo::gauss: {
809                         ex det = 1;
810                         matrix tmp(*this);
811                         int sign = tmp.gauss_elimination(true);
812                         for (unsigned d=0; d<row; ++d)
813                                 det *= tmp.m[d*col+d];
814                         if (normal_flag)
815                                 return (sign*det).normal();
816                         else
817                                 return (sign*det).normal().expand();
818                 }
819                 case determinant_algo::bareiss: {
820                         matrix tmp(*this);
821                         int sign;
822                         sign = tmp.fraction_free_elimination(true);
823                         if (normal_flag)
824                                 return (sign*tmp.m[row*col-1]).normal();
825                         else
826                                 return (sign*tmp.m[row*col-1]).expand();
827                 }
828                 case determinant_algo::divfree: {
829                         matrix tmp(*this);
830                         int sign;
831                         sign = tmp.division_free_elimination(true);
832                         if (sign==0)
833                                 return _ex0;
834                         ex det = tmp.m[row*col-1];
835                         // factor out accumulated bogus slag
836                         for (unsigned d=0; d<row-2; ++d)
837                                 for (unsigned j=0; j<row-d-2; ++j)
838                                         det = (det/tmp.m[d*col+d]).normal();
839                         return (sign*det);
840                 }
841                 case determinant_algo::laplace:
842                 default: {
843                         // This is the minor expansion scheme.  We always develop such
844                         // that the smallest minors (i.e, the trivial 1x1 ones) are on the
845                         // rightmost column.  For this to be efficient, empirical tests
846                         // have shown that the emptiest columns (i.e. the ones with most
847                         // zeros) should be the ones on the right hand side -- although
848                         // this might seem counter-intuitive (and in contradiction to some
849                         // literature like the FORM manual).  Please go ahead and test it
850                         // if you don't believe me!  Therefore we presort the columns of
851                         // the matrix:
852                         typedef std::pair<unsigned,unsigned> uintpair;
853                         std::vector<uintpair> c_zeros;  // number of zeros in column
854                         for (unsigned c=0; c<col; ++c) {
855                                 unsigned acc = 0;
856                                 for (unsigned r=0; r<row; ++r)
857                                         if (m[r*col+c].is_zero())
858                                                 ++acc;
859                                 c_zeros.push_back(uintpair(acc,c));
860                         }
861                         std::sort(c_zeros.begin(),c_zeros.end());
862                         std::vector<unsigned> pre_sort;
863                         for (auto & i : c_zeros)
864                                 pre_sort.push_back(i.second);
865                         std::vector<unsigned> pre_sort_test(pre_sort); // permutation_sign() modifies the vector so we make a copy here
866                         int sign = permutation_sign(pre_sort_test.begin(), pre_sort_test.end());
867                         exvector result(row*col);  // represents sorted matrix
868                         unsigned c = 0;
869                         for (auto & it : pre_sort) {
870                                 for (unsigned r=0; r<row; ++r)
871                                         result[r*col+c] = m[r*col+it];
872                                 ++c;
873                         }
874                         
875                         if (normal_flag)
876                                 return (sign*matrix(row, col, std::move(result)).determinant_minor()).normal();
877                         else
878                                 return sign*matrix(row, col, std::move(result)).determinant_minor();
879                 }
880         }
881 }
882
883
884 /** Trace of a matrix.  The result is normalized if it is in some quotient
885  *  field and expanded only otherwise.  This implies that the trace of the
886  *  symbolic 2x2 matrix [[a/(a-b),x],[y,b/(b-a)]] is recognized to be unity.
887  *
888  *  @return    the sum of diagonal elements
889  *  @exception logic_error (matrix not square) */
890 ex matrix::trace() const
891 {
892         if (row != col)
893                 throw (std::logic_error("matrix::trace(): matrix not square"));
894         
895         ex tr;
896         for (unsigned r=0; r<col; ++r)
897                 tr += m[r*col+r];
898         
899         if (tr.info(info_flags::rational_function) &&
900            !tr.info(info_flags::crational_polynomial))
901                 return tr.normal();
902         else
903                 return tr.expand();
904 }
905
906
907 /** Characteristic Polynomial.  Following mathematica notation the
908  *  characteristic polynomial of a matrix M is defined as the determinant of
909  *  (M - lambda * 1) where 1 stands for the unit matrix of the same dimension
910  *  as M.  Note that some CASs define it with a sign inside the determinant
911  *  which gives rise to an overall sign if the dimension is odd.  This method
912  *  returns the characteristic polynomial collected in powers of lambda as a
913  *  new expression.
914  *
915  *  @return    characteristic polynomial as new expression
916  *  @exception logic_error (matrix not square)
917  *  @see       matrix::determinant() */
918 ex matrix::charpoly(const ex & lambda) const
919 {
920         if (row != col)
921                 throw (std::logic_error("matrix::charpoly(): matrix not square"));
922         
923         bool numeric_flag = true;
924         for (auto & r : m) {
925                 if (!r.info(info_flags::numeric)) {
926                         numeric_flag = false;
927                         break;
928                 }
929         }
930         
931         // The pure numeric case is traditionally rather common.  Hence, it is
932         // trapped and we use Leverrier's algorithm which goes as row^3 for
933         // every coefficient.  The expensive part is the matrix multiplication.
934         if (numeric_flag) {
935
936                 matrix B(*this);
937                 ex c = B.trace();
938                 ex poly = power(lambda, row) - c*power(lambda, row-1);
939                 for (unsigned i=1; i<row; ++i) {
940                         for (unsigned j=0; j<row; ++j)
941                                 B.m[j*col+j] -= c;
942                         B = this->mul(B);
943                         c = B.trace() / ex(i+1);
944                         poly -= c*power(lambda, row-i-1);
945                 }
946                 if (row%2)
947                         return -poly;
948                 else
949                         return poly;
950
951         } else {
952         
953                 matrix M(*this);
954                 for (unsigned r=0; r<col; ++r)
955                         M.m[r*col+r] -= lambda;
956         
957                 return M.determinant().collect(lambda);
958         }
959 }
960
961
962 /** Inverse of this matrix.
963  *
964  *  @return    the inverted matrix
965  *  @exception logic_error (matrix not square)
966  *  @exception runtime_error (singular matrix) */
967 matrix matrix::inverse() const
968 {
969         if (row != col)
970                 throw (std::logic_error("matrix::inverse(): matrix not square"));
971         
972         // This routine actually doesn't do anything fancy at all.  We compute the
973         // inverse of the matrix A by solving the system A * A^{-1} == Id.
974         
975         // First populate the identity matrix supposed to become the right hand side.
976         matrix identity(row,col);
977         for (unsigned i=0; i<row; ++i)
978                 identity(i,i) = _ex1;
979         
980         // Populate a dummy matrix of variables, just because of compatibility with
981         // matrix::solve() which wants this (for compatibility with under-determined
982         // systems of equations).
983         matrix vars(row,col);
984         for (unsigned r=0; r<row; ++r)
985                 for (unsigned c=0; c<col; ++c)
986                         vars(r,c) = symbol();
987         
988         matrix sol(row,col);
989         try {
990                 sol = this->solve(vars,identity);
991         } catch (const std::runtime_error & e) {
992             if (e.what()==std::string("matrix::solve(): inconsistent linear system"))
993                         throw (std::runtime_error("matrix::inverse(): singular matrix"));
994                 else
995                         throw;
996         }
997         return sol;
998 }
999
1000
1001 /** Solve a linear system consisting of a m x n matrix and a m x p right hand
1002  *  side by applying an elimination scheme to the augmented matrix.
1003  *
1004  *  @param vars n x p matrix, all elements must be symbols 
1005  *  @param rhs m x p matrix
1006  *  @param algo selects the solving algorithm
1007  *  @return n x p solution matrix
1008  *  @exception logic_error (incompatible matrices)
1009  *  @exception invalid_argument (1st argument must be matrix of symbols)
1010  *  @exception runtime_error (inconsistent linear system)
1011  *  @see       solve_algo */
1012 matrix matrix::solve(const matrix & vars,
1013                      const matrix & rhs,
1014                      unsigned algo) const
1015 {
1016         const unsigned m = this->rows();
1017         const unsigned n = this->cols();
1018         const unsigned p = rhs.cols();
1019         
1020         // syntax checks    
1021         if ((rhs.rows() != m) || (vars.rows() != n) || (vars.col != p))
1022                 throw (std::logic_error("matrix::solve(): incompatible matrices"));
1023         for (unsigned ro=0; ro<n; ++ro)
1024                 for (unsigned co=0; co<p; ++co)
1025                         if (!vars(ro,co).info(info_flags::symbol))
1026                                 throw (std::invalid_argument("matrix::solve(): 1st argument must be matrix of symbols"));
1027         
1028         // build the augmented matrix of *this with rhs attached to the right
1029         matrix aug(m,n+p);
1030         for (unsigned r=0; r<m; ++r) {
1031                 for (unsigned c=0; c<n; ++c)
1032                         aug.m[r*(n+p)+c] = this->m[r*n+c];
1033                 for (unsigned c=0; c<p; ++c)
1034                         aug.m[r*(n+p)+c+n] = rhs.m[r*p+c];
1035         }
1036         
1037         // Gather some statistical information about the augmented matrix:
1038         bool numeric_flag = true;
1039         for (auto & r : aug.m) {
1040                 if (!r.info(info_flags::numeric)) {
1041                         numeric_flag = false;
1042                         break;
1043                 }
1044         }
1045         
1046         // Here is the heuristics in case this routine has to decide:
1047         if (algo == solve_algo::automatic) {
1048                 // Bareiss (fraction-free) elimination is generally a good guess:
1049                 algo = solve_algo::bareiss;
1050                 // For m<3, Bareiss elimination is equivalent to division free
1051                 // elimination but has more logistic overhead
1052                 if (m<3)
1053                         algo = solve_algo::divfree;
1054                 // This overrides any prior decisions.
1055                 if (numeric_flag)
1056                         algo = solve_algo::gauss;
1057         }
1058         
1059         // Eliminate the augmented matrix:
1060         switch(algo) {
1061                 case solve_algo::gauss:
1062                         aug.gauss_elimination();
1063                         break;
1064                 case solve_algo::divfree:
1065                         aug.division_free_elimination();
1066                         break;
1067                 case solve_algo::bareiss:
1068                 default:
1069                         aug.fraction_free_elimination();
1070         }
1071         
1072         // assemble the solution matrix:
1073         matrix sol(n,p);
1074         for (unsigned co=0; co<p; ++co) {
1075                 unsigned last_assigned_sol = n+1;
1076                 for (int r=m-1; r>=0; --r) {
1077                         unsigned fnz = 1;    // first non-zero in row
1078                         while ((fnz<=n) && (aug.m[r*(n+p)+(fnz-1)].is_zero()))
1079                                 ++fnz;
1080                         if (fnz>n) {
1081                                 // row consists only of zeros, corresponding rhs must be 0, too
1082                                 if (!aug.m[r*(n+p)+n+co].is_zero()) {
1083                                         throw (std::runtime_error("matrix::solve(): inconsistent linear system"));
1084                                 }
1085                         } else {
1086                                 // assign solutions for vars between fnz+1 and
1087                                 // last_assigned_sol-1: free parameters
1088                                 for (unsigned c=fnz; c<last_assigned_sol-1; ++c)
1089                                         sol(c,co) = vars.m[c*p+co];
1090                                 ex e = aug.m[r*(n+p)+n+co];
1091                                 for (unsigned c=fnz; c<n; ++c)
1092                                         e -= aug.m[r*(n+p)+c]*sol.m[c*p+co];
1093                                 sol(fnz-1,co) = (e/(aug.m[r*(n+p)+(fnz-1)])).normal();
1094                                 last_assigned_sol = fnz;
1095                         }
1096                 }
1097                 // assign solutions for vars between 1 and
1098                 // last_assigned_sol-1: free parameters
1099                 for (unsigned ro=0; ro<last_assigned_sol-1; ++ro)
1100                         sol(ro,co) = vars(ro,co);
1101         }
1102         
1103         return sol;
1104 }
1105
1106
1107 /** Compute the rank of this matrix. */
1108 unsigned matrix::rank() const
1109 {
1110         // Method:
1111         // Transform this matrix into upper echelon form and then count the
1112         // number of non-zero rows.
1113
1114         GINAC_ASSERT(row*col==m.capacity());
1115
1116         // Actually, any elimination scheme will do since we are only
1117         // interested in the echelon matrix' zeros.
1118         matrix to_eliminate = *this;
1119         to_eliminate.fraction_free_elimination();
1120
1121         unsigned r = row*col;  // index of last non-zero element
1122         while (r--) {
1123                 if (!to_eliminate.m[r].is_zero())
1124                         return 1+r/col;
1125         }
1126         return 0;
1127 }
1128
1129
1130 // protected
1131
1132 /** Recursive determinant for small matrices having at least one symbolic
1133  *  entry.  The basic algorithm, known as Laplace-expansion, is enhanced by
1134  *  some bookkeeping to avoid calculation of the same submatrices ("minors")
1135  *  more than once.  According to W.M.Gentleman and S.C.Johnson this algorithm
1136  *  is better than elimination schemes for matrices of sparse multivariate
1137  *  polynomials and also for matrices of dense univariate polynomials if the
1138  *  matrix' dimension is larger than 7.
1139  *
1140  *  @return the determinant as a new expression (in expanded form)
1141  *  @see matrix::determinant() */
1142 ex matrix::determinant_minor() const
1143 {
1144         // for small matrices the algorithm does not make any sense:
1145         const unsigned n = this->cols();
1146         if (n==1)
1147                 return m[0].expand();
1148         if (n==2)
1149                 return (m[0]*m[3]-m[2]*m[1]).expand();
1150         if (n==3)
1151                 return (m[0]*m[4]*m[8]-m[0]*m[5]*m[7]-
1152                         m[1]*m[3]*m[8]+m[2]*m[3]*m[7]+
1153                         m[1]*m[5]*m[6]-m[2]*m[4]*m[6]).expand();
1154         
1155         // This algorithm can best be understood by looking at a naive
1156         // implementation of Laplace-expansion, like this one:
1157         // ex det;
1158         // matrix minorM(this->rows()-1,this->cols()-1);
1159         // for (unsigned r1=0; r1<this->rows(); ++r1) {
1160         //     // shortcut if element(r1,0) vanishes
1161         //     if (m[r1*col].is_zero())
1162         //         continue;
1163         //     // assemble the minor matrix
1164         //     for (unsigned r=0; r<minorM.rows(); ++r) {
1165         //         for (unsigned c=0; c<minorM.cols(); ++c) {
1166         //             if (r<r1)
1167         //                 minorM(r,c) = m[r*col+c+1];
1168         //             else
1169         //                 minorM(r,c) = m[(r+1)*col+c+1];
1170         //         }
1171         //     }
1172         //     // recurse down and care for sign:
1173         //     if (r1%2)
1174         //         det -= m[r1*col] * minorM.determinant_minor();
1175         //     else
1176         //         det += m[r1*col] * minorM.determinant_minor();
1177         // }
1178         // return det.expand();
1179         // What happens is that while proceeding down many of the minors are
1180         // computed more than once.  In particular, there are binomial(n,k)
1181         // kxk minors and each one is computed factorial(n-k) times.  Therefore
1182         // it is reasonable to store the results of the minors.  We proceed from
1183         // right to left.  At each column c we only need to retrieve the minors
1184         // calculated in step c-1.  We therefore only have to store at most 
1185         // 2*binomial(n,n/2) minors.
1186         
1187         // Unique flipper counter for partitioning into minors
1188         std::vector<unsigned> Pkey;
1189         Pkey.reserve(n);
1190         // key for minor determinant (a subpartition of Pkey)
1191         std::vector<unsigned> Mkey;
1192         Mkey.reserve(n-1);
1193         // we store our subminors in maps, keys being the rows they arise from
1194         typedef std::map<std::vector<unsigned>,class ex> Rmap;
1195         typedef std::map<std::vector<unsigned>,class ex>::value_type Rmap_value;
1196         Rmap A;
1197         Rmap B;
1198         ex det;
1199         // initialize A with last column:
1200         for (unsigned r=0; r<n; ++r) {
1201                 Pkey.erase(Pkey.begin(),Pkey.end());
1202                 Pkey.push_back(r);
1203                 A.insert(Rmap_value(Pkey,m[n*(r+1)-1]));
1204         }
1205         // proceed from right to left through matrix
1206         for (int c=n-2; c>=0; --c) {
1207                 Pkey.erase(Pkey.begin(),Pkey.end());  // don't change capacity
1208                 Mkey.erase(Mkey.begin(),Mkey.end());
1209                 for (unsigned i=0; i<n-c; ++i)
1210                         Pkey.push_back(i);
1211                 unsigned fc = 0;  // controls logic for our strange flipper counter
1212                 do {
1213                         det = _ex0;
1214                         for (unsigned r=0; r<n-c; ++r) {
1215                                 // maybe there is nothing to do?
1216                                 if (m[Pkey[r]*n+c].is_zero())
1217                                         continue;
1218                                 // create the sorted key for all possible minors
1219                                 Mkey.erase(Mkey.begin(),Mkey.end());
1220                                 for (unsigned i=0; i<n-c; ++i)
1221                                         if (i!=r)
1222                                                 Mkey.push_back(Pkey[i]);
1223                                 // Fetch the minors and compute the new determinant
1224                                 if (r%2)
1225                                         det -= m[Pkey[r]*n+c]*A[Mkey];
1226                                 else
1227                                         det += m[Pkey[r]*n+c]*A[Mkey];
1228                         }
1229                         // prevent build-up of deep nesting of expressions saves time:
1230                         det = det.expand();
1231                         // store the new determinant at its place in B:
1232                         if (!det.is_zero())
1233                                 B.insert(Rmap_value(Pkey,det));
1234                         // increment our strange flipper counter
1235                         for (fc=n-c; fc>0; --fc) {
1236                                 ++Pkey[fc-1];
1237                                 if (Pkey[fc-1]<fc+c)
1238                                         break;
1239                         }
1240                         if (fc<n-c && fc>0)
1241                                 for (unsigned j=fc; j<n-c; ++j)
1242                                         Pkey[j] = Pkey[j-1]+1;
1243                 } while(fc);
1244                 // next column, clear B and change the role of A and B:
1245                 A = std::move(B);
1246         }
1247         
1248         return det;
1249 }
1250
1251
1252 /** Perform the steps of an ordinary Gaussian elimination to bring the m x n
1253  *  matrix into an upper echelon form.  The algorithm is ok for matrices
1254  *  with numeric coefficients but quite unsuited for symbolic matrices.
1255  *
1256  *  @param det may be set to true to save a lot of space if one is only
1257  *  interested in the diagonal elements (i.e. for calculating determinants).
1258  *  The others are set to zero in this case.
1259  *  @return sign is 1 if an even number of rows was swapped, -1 if an odd
1260  *  number of rows was swapped and 0 if the matrix is singular. */
1261 int matrix::gauss_elimination(const bool det)
1262 {
1263         ensure_if_modifiable();
1264         const unsigned m = this->rows();
1265         const unsigned n = this->cols();
1266         GINAC_ASSERT(!det || n==m);
1267         int sign = 1;
1268         
1269         unsigned r0 = 0;
1270         for (unsigned c0=0; c0<n && r0<m-1; ++c0) {
1271                 int indx = pivot(r0, c0, true);
1272                 if (indx == -1) {
1273                         sign = 0;
1274                         if (det)
1275                                 return 0;  // leaves *this in a messy state
1276                 }
1277                 if (indx>=0) {
1278                         if (indx > 0)
1279                                 sign = -sign;
1280                         for (unsigned r2=r0+1; r2<m; ++r2) {
1281                                 if (!this->m[r2*n+c0].is_zero()) {
1282                                         // yes, there is something to do in this row
1283                                         ex piv = this->m[r2*n+c0] / this->m[r0*n+c0];
1284                                         for (unsigned c=c0+1; c<n; ++c) {
1285                                                 this->m[r2*n+c] -= piv * this->m[r0*n+c];
1286                                                 if (!this->m[r2*n+c].info(info_flags::numeric))
1287                                                         this->m[r2*n+c] = this->m[r2*n+c].normal();
1288                                         }
1289                                 }
1290                                 // fill up left hand side with zeros
1291                                 for (unsigned c=r0; c<=c0; ++c)
1292                                         this->m[r2*n+c] = _ex0;
1293                         }
1294                         if (det) {
1295                                 // save space by deleting no longer needed elements
1296                                 for (unsigned c=r0+1; c<n; ++c)
1297                                         this->m[r0*n+c] = _ex0;
1298                         }
1299                         ++r0;
1300                 }
1301         }
1302         // clear remaining rows
1303         for (unsigned r=r0+1; r<m; ++r) {
1304                 for (unsigned c=0; c<n; ++c)
1305                         this->m[r*n+c] = _ex0;
1306         }
1307
1308         return sign;
1309 }
1310
1311
1312 /** Perform the steps of division free elimination to bring the m x n matrix
1313  *  into an upper echelon form.
1314  *
1315  *  @param det may be set to true to save a lot of space if one is only
1316  *  interested in the diagonal elements (i.e. for calculating determinants).
1317  *  The others are set to zero in this case.
1318  *  @return sign is 1 if an even number of rows was swapped, -1 if an odd
1319  *  number of rows was swapped and 0 if the matrix is singular. */
1320 int matrix::division_free_elimination(const bool det)
1321 {
1322         ensure_if_modifiable();
1323         const unsigned m = this->rows();
1324         const unsigned n = this->cols();
1325         GINAC_ASSERT(!det || n==m);
1326         int sign = 1;
1327         
1328         unsigned r0 = 0;
1329         for (unsigned c0=0; c0<n && r0<m-1; ++c0) {
1330                 int indx = pivot(r0, c0, true);
1331                 if (indx==-1) {
1332                         sign = 0;
1333                         if (det)
1334                                 return 0;  // leaves *this in a messy state
1335                 }
1336                 if (indx>=0) {
1337                         if (indx>0)
1338                                 sign = -sign;
1339                         for (unsigned r2=r0+1; r2<m; ++r2) {
1340                                 for (unsigned c=c0+1; c<n; ++c)
1341                                         this->m[r2*n+c] = (this->m[r0*n+c0]*this->m[r2*n+c] - this->m[r2*n+c0]*this->m[r0*n+c]).expand();
1342                                 // fill up left hand side with zeros
1343                                 for (unsigned c=r0; c<=c0; ++c)
1344                                         this->m[r2*n+c] = _ex0;
1345                         }
1346                         if (det) {
1347                                 // save space by deleting no longer needed elements
1348                                 for (unsigned c=r0+1; c<n; ++c)
1349                                         this->m[r0*n+c] = _ex0;
1350                         }
1351                         ++r0;
1352                 }
1353         }
1354         // clear remaining rows
1355         for (unsigned r=r0+1; r<m; ++r) {
1356                 for (unsigned c=0; c<n; ++c)
1357                         this->m[r*n+c] = _ex0;
1358         }
1359
1360         return sign;
1361 }
1362
1363
1364 /** Perform the steps of Bareiss' one-step fraction free elimination to bring
1365  *  the matrix into an upper echelon form.  Fraction free elimination means
1366  *  that divide is used straightforwardly, without computing GCDs first.  This
1367  *  is possible, since we know the divisor at each step.
1368  *  
1369  *  @param det may be set to true to save a lot of space if one is only
1370  *  interested in the last element (i.e. for calculating determinants). The
1371  *  others are set to zero in this case.
1372  *  @return sign is 1 if an even number of rows was swapped, -1 if an odd
1373  *  number of rows was swapped and 0 if the matrix is singular. */
1374 int matrix::fraction_free_elimination(const bool det)
1375 {
1376         // Method:
1377         // (single-step fraction free elimination scheme, already known to Jordan)
1378         //
1379         // Usual division-free elimination sets m[0](r,c) = m(r,c) and then sets
1380         //     m[k+1](r,c) = m[k](k,k) * m[k](r,c) - m[k](r,k) * m[k](k,c).
1381         //
1382         // Bareiss (fraction-free) elimination in addition divides that element
1383         // by m[k-1](k-1,k-1) for k>1, where it can be shown by means of the
1384         // Sylvester identity that this really divides m[k+1](r,c).
1385         //
1386         // We also allow rational functions where the original prove still holds.
1387         // However, we must care for numerator and denominator separately and
1388         // "manually" work in the integral domains because of subtle cancellations
1389         // (see below).  This blows up the bookkeeping a bit and the formula has
1390         // to be modified to expand like this (N{x} stands for numerator of x,
1391         // D{x} for denominator of x):
1392         //     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)}
1393         //                     -N{m[k](r,k)}*N{m[k](k,c)}*D{m[k](k,k)}*D{m[k](r,c)}
1394         //     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)}
1395         // where for k>1 we now divide N{m[k+1](r,c)} by
1396         //     N{m[k-1](k-1,k-1)}
1397         // and D{m[k+1](r,c)} by
1398         //     D{m[k-1](k-1,k-1)}.
1399         
1400         ensure_if_modifiable();
1401         const unsigned m = this->rows();
1402         const unsigned n = this->cols();
1403         GINAC_ASSERT(!det || n==m);
1404         int sign = 1;
1405         if (m==1)
1406                 return 1;
1407         ex divisor_n = 1;
1408         ex divisor_d = 1;
1409         ex dividend_n;
1410         ex dividend_d;
1411         
1412         // We populate temporary matrices to subsequently operate on.  There is
1413         // one holding numerators and another holding denominators of entries.
1414         // This is a must since the evaluator (or even earlier mul's constructor)
1415         // might cancel some trivial element which causes divide() to fail.  The
1416         // elements are normalized first (yes, even though this algorithm doesn't
1417         // need GCDs) since the elements of *this might be unnormalized, which
1418         // makes things more complicated than they need to be.
1419         matrix tmp_n(*this);
1420         matrix tmp_d(m,n);  // for denominators, if needed
1421         exmap srl;  // symbol replacement list
1422         auto tmp_n_it = tmp_n.m.begin(), tmp_d_it = tmp_d.m.begin();
1423         for (auto & it : this->m) {
1424                 ex nd = it.normal().to_rational(srl).numer_denom();
1425                 *tmp_n_it++ = nd.op(0);
1426                 *tmp_d_it++ = nd.op(1);
1427         }
1428         
1429         unsigned r0 = 0;
1430         for (unsigned c0=0; c0<n && r0<m-1; ++c0) {
1431                 // When trying to find a pivot, we should try a bit harder than expand().
1432                 // Searching the first non-zero element in-place here instead of calling
1433                 // pivot() allows us to do no more substitutions and back-substitutions
1434                 // than are actually necessary.
1435                 unsigned indx = r0;
1436                 while ((indx<m) &&
1437                        (tmp_n[indx*n+c0].subs(srl, subs_options::no_pattern).expand().is_zero()))
1438                         ++indx;
1439                 if (indx==m) {
1440                         // all elements in column c0 below row r0 vanish
1441                         sign = 0;
1442                         if (det)
1443                                 return 0;
1444                 } else {
1445                         if (indx>r0) {
1446                                 // Matrix needs pivoting, swap rows r0 and indx of tmp_n and tmp_d.
1447                                 sign = -sign;
1448                                 for (unsigned c=c0; c<n; ++c) {
1449                                         tmp_n.m[n*indx+c].swap(tmp_n.m[n*r0+c]);
1450                                         tmp_d.m[n*indx+c].swap(tmp_d.m[n*r0+c]);
1451                                 }
1452                         }
1453                         for (unsigned r2=r0+1; r2<m; ++r2) {
1454                                 for (unsigned c=c0+1; c<n; ++c) {
1455                                         dividend_n = (tmp_n.m[r0*n+c0]*tmp_n.m[r2*n+c]*
1456                                                       tmp_d.m[r2*n+c0]*tmp_d.m[r0*n+c]
1457                                                      -tmp_n.m[r2*n+c0]*tmp_n.m[r0*n+c]*
1458                                                       tmp_d.m[r0*n+c0]*tmp_d.m[r2*n+c]).expand();
1459                                         dividend_d = (tmp_d.m[r2*n+c0]*tmp_d.m[r0*n+c]*
1460                                                       tmp_d.m[r0*n+c0]*tmp_d.m[r2*n+c]).expand();
1461                                         bool check = divide(dividend_n, divisor_n,
1462                                                             tmp_n.m[r2*n+c], true);
1463                                         check &= divide(dividend_d, divisor_d,
1464                                                         tmp_d.m[r2*n+c], true);
1465                                         GINAC_ASSERT(check);
1466                                 }
1467                                 // fill up left hand side with zeros
1468                                 for (unsigned c=r0; c<=c0; ++c)
1469                                         tmp_n.m[r2*n+c] = _ex0;
1470                         }
1471                         if (c0<n && r0<m-1) {
1472                                 // compute next iteration's divisor
1473                                 divisor_n = tmp_n.m[r0*n+c0].expand();
1474                                 divisor_d = tmp_d.m[r0*n+c0].expand();
1475                                 if (det) {
1476                                         // save space by deleting no longer needed elements
1477                                         for (unsigned c=0; c<n; ++c) {
1478                                                 tmp_n.m[r0*n+c] = _ex0;
1479                                                 tmp_d.m[r0*n+c] = _ex1;
1480                                         }
1481                                 }
1482                         }
1483                         ++r0;
1484                 }
1485         }
1486         // clear remaining rows
1487         for (unsigned r=r0+1; r<m; ++r) {
1488                 for (unsigned c=0; c<n; ++c)
1489                         tmp_n.m[r*n+c] = _ex0;
1490         }
1491
1492         // repopulate *this matrix:
1493         tmp_n_it = tmp_n.m.begin();
1494         tmp_d_it = tmp_d.m.begin();
1495         for (auto & it : this->m)
1496                 it = ((*tmp_n_it++)/(*tmp_d_it++)).subs(srl, subs_options::no_pattern);
1497         
1498         return sign;
1499 }
1500
1501
1502 /** Partial pivoting method for matrix elimination schemes.
1503  *  Usual pivoting (symbolic==false) returns the index to the element with the
1504  *  largest absolute value in column ro and swaps the current row with the one
1505  *  where the element was found.  With (symbolic==true) it does the same thing
1506  *  with the first non-zero element.
1507  *
1508  *  @param ro is the row from where to begin
1509  *  @param co is the column to be inspected
1510  *  @param symbolic signal if we want the first non-zero element to be pivoted
1511  *  (true) or the one with the largest absolute value (false).
1512  *  @return 0 if no interchange occurred, -1 if all are zero (usually signaling
1513  *  a degeneracy) and positive integer k means that rows ro and k were swapped.
1514  */
1515 int matrix::pivot(unsigned ro, unsigned co, bool symbolic)
1516 {
1517         unsigned k = ro;
1518         if (symbolic) {
1519                 // search first non-zero element in column co beginning at row ro
1520                 while ((k<row) && (this->m[k*col+co].expand().is_zero()))
1521                         ++k;
1522         } else {
1523                 // search largest element in column co beginning at row ro
1524                 GINAC_ASSERT(is_exactly_a<numeric>(this->m[k*col+co]));
1525                 unsigned kmax = k+1;
1526                 numeric mmax = abs(ex_to<numeric>(m[kmax*col+co]));
1527                 while (kmax<row) {
1528                         GINAC_ASSERT(is_exactly_a<numeric>(this->m[kmax*col+co]));
1529                         numeric tmp = ex_to<numeric>(this->m[kmax*col+co]);
1530                         if (abs(tmp) > mmax) {
1531                                 mmax = tmp;
1532                                 k = kmax;
1533                         }
1534                         ++kmax;
1535                 }
1536                 if (!mmax.is_zero())
1537                         k = kmax;
1538         }
1539         if (k==row)
1540                 // all elements in column co below row ro vanish
1541                 return -1;
1542         if (k==ro)
1543                 // matrix needs no pivoting
1544                 return 0;
1545         // matrix needs pivoting, so swap rows k and ro
1546         ensure_if_modifiable();
1547         for (unsigned c=0; c<col; ++c)
1548                 this->m[k*col+c].swap(this->m[ro*col+c]);
1549         
1550         return k;
1551 }
1552
1553 /** Function to check that all elements of the matrix are zero.
1554  */
1555 bool matrix::is_zero_matrix() const
1556 {
1557         for (auto & i : m)
1558                 if (!i.is_zero())
1559                         return false;
1560         return true;
1561 }
1562
1563 ex lst_to_matrix(const lst & l)
1564 {
1565         // Find number of rows and columns
1566         size_t rows = l.nops(), cols = 0;
1567         for (auto & itr : l) {
1568                 if (!is_a<lst>(itr))
1569                         throw (std::invalid_argument("lst_to_matrix: argument must be a list of lists"));
1570                 if (itr.nops() > cols)
1571                         cols = itr.nops();
1572         }
1573
1574         // Allocate and fill matrix
1575         matrix &M = *new matrix(rows, cols);
1576         M.setflag(status_flags::dynallocated);
1577
1578         unsigned i = 0;
1579         for (auto & itr : l) {
1580                 unsigned j = 0;
1581                 for (auto & itc : ex_to<lst>(itr)) {
1582                         M(i, j) = itc;
1583                         ++j;
1584                 }
1585                 ++i;
1586         }
1587
1588         return M;
1589 }
1590
1591 ex diag_matrix(const lst & l)
1592 {
1593         size_t dim = l.nops();
1594
1595         // Allocate and fill matrix
1596         matrix &M = *new matrix(dim, dim);
1597         M.setflag(status_flags::dynallocated);
1598
1599         unsigned i = 0;
1600         for (auto & it : l) {
1601                 M(i, i) = it;
1602                 ++i;
1603         }
1604
1605         return M;
1606 }
1607
1608 ex diag_matrix(std::initializer_list<ex> l)
1609 {
1610         size_t dim = l.size();
1611
1612         // Allocate and fill matrix
1613         matrix &M = *new matrix(dim, dim);
1614         M.setflag(status_flags::dynallocated);
1615
1616         unsigned i = 0;
1617         for (auto & it : l) {
1618                 M(i, i) = it;
1619                 ++i;
1620         }
1621
1622         return M;
1623 }
1624
1625 ex unit_matrix(unsigned r, unsigned c)
1626 {
1627         matrix &Id = *new matrix(r, c);
1628         Id.setflag(status_flags::dynallocated | status_flags::evaluated);
1629         for (unsigned i=0; i<r && i<c; i++)
1630                 Id(i,i) = _ex1;
1631
1632         return Id;
1633 }
1634
1635 ex symbolic_matrix(unsigned r, unsigned c, const std::string & base_name, const std::string & tex_base_name)
1636 {
1637         matrix &M = *new matrix(r, c);
1638         M.setflag(status_flags::dynallocated | status_flags::evaluated);
1639
1640         bool long_format = (r > 10 || c > 10);
1641         bool single_row = (r == 1 || c == 1);
1642
1643         for (unsigned i=0; i<r; i++) {
1644                 for (unsigned j=0; j<c; j++) {
1645                         std::ostringstream s1, s2;
1646                         s1 << base_name;
1647                         s2 << tex_base_name << "_{";
1648                         if (single_row) {
1649                                 if (c == 1) {
1650                                         s1 << i;
1651                                         s2 << i << '}';
1652                                 } else {
1653                                         s1 << j;
1654                                         s2 << j << '}';
1655                                 }
1656                         } else {
1657                                 if (long_format) {
1658                                         s1 << '_' << i << '_' << j;
1659                                         s2 << i << ';' << j << "}";
1660                                 } else {
1661                                         s1 << i << j;
1662                                         s2 << i << j << '}';
1663                                 }
1664                         }
1665                         M(i, j) = symbol(s1.str(), s2.str());
1666                 }
1667         }
1668
1669         return M;
1670 }
1671
1672 ex reduced_matrix(const matrix& m, unsigned r, unsigned c)
1673 {
1674         if (r+1>m.rows() || c+1>m.cols() || m.cols()<2 || m.rows()<2)
1675                 throw std::runtime_error("minor_matrix(): index out of bounds");
1676
1677         const unsigned rows = m.rows()-1;
1678         const unsigned cols = m.cols()-1;
1679         matrix &M = *new matrix(rows, cols);
1680         M.setflag(status_flags::dynallocated | status_flags::evaluated);
1681
1682         unsigned ro = 0;
1683         unsigned ro2 = 0;
1684         while (ro2<rows) {
1685                 if (ro==r)
1686                         ++ro;
1687                 unsigned co = 0;
1688                 unsigned co2 = 0;
1689                 while (co2<cols) {
1690                         if (co==c)
1691                                 ++co;
1692                         M(ro2,co2) = m(ro, co);
1693                         ++co;
1694                         ++co2;
1695                 }
1696                 ++ro;
1697                 ++ro2;
1698         }
1699
1700         return M;
1701 }
1702
1703 ex sub_matrix(const matrix&m, unsigned r, unsigned nr, unsigned c, unsigned nc)
1704 {
1705         if (r+nr>m.rows() || c+nc>m.cols())
1706                 throw std::runtime_error("sub_matrix(): index out of bounds");
1707
1708         matrix &M = *new matrix(nr, nc);
1709         M.setflag(status_flags::dynallocated | status_flags::evaluated);
1710
1711         for (unsigned ro=0; ro<nr; ++ro) {
1712                 for (unsigned co=0; co<nc; ++co) {
1713                         M(ro,co) = m(ro+r,co+c);
1714                 }
1715         }
1716
1717         return M;
1718 }
1719
1720 } // namespace GiNaC