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