]> www.ginac.de Git - ginac.git/blob - ginac/mul.cpp
Add rvalue reference ctors from epvectors for add, mul.
[ginac.git] / ginac / mul.cpp
1 /** @file mul.cpp
2  *
3  *  Implementation of GiNaC's products of expressions. */
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 "mul.h"
24 #include "add.h"
25 #include "power.h"
26 #include "operators.h"
27 #include "matrix.h"
28 #include "indexed.h"
29 #include "lst.h"
30 #include "archive.h"
31 #include "utils.h"
32 #include "symbol.h"
33 #include "compiler.h"
34
35 #include <iostream>
36 #include <limits>
37 #include <stdexcept>
38 #include <vector>
39
40 namespace GiNaC {
41
42 GINAC_IMPLEMENT_REGISTERED_CLASS_OPT(mul, expairseq,
43   print_func<print_context>(&mul::do_print).
44   print_func<print_latex>(&mul::do_print_latex).
45   print_func<print_csrc>(&mul::do_print_csrc).
46   print_func<print_tree>(&mul::do_print_tree).
47   print_func<print_python_repr>(&mul::do_print_python_repr))
48
49
50 //////////
51 // default constructor
52 //////////
53
54 mul::mul()
55 {
56 }
57
58 //////////
59 // other constructors
60 //////////
61
62 // public
63
64 mul::mul(const ex & lh, const ex & rh)
65 {
66         overall_coeff = _ex1;
67         construct_from_2_ex(lh,rh);
68         GINAC_ASSERT(is_canonical());
69 }
70
71 mul::mul(const exvector & v)
72 {
73         overall_coeff = _ex1;
74         construct_from_exvector(v);
75         GINAC_ASSERT(is_canonical());
76 }
77
78 mul::mul(const epvector & v)
79 {
80         overall_coeff = _ex1;
81         construct_from_epvector(v);
82         GINAC_ASSERT(is_canonical());
83 }
84
85 mul::mul(const epvector & v, const ex & oc, bool do_index_renaming)
86 {
87         overall_coeff = oc;
88         construct_from_epvector(v, do_index_renaming);
89         GINAC_ASSERT(is_canonical());
90 }
91
92 mul::mul(epvector && vp)
93 {
94         overall_coeff = _ex1;
95         construct_from_epvector(std::move(vp));
96         GINAC_ASSERT(is_canonical());
97 }
98
99 mul::mul(epvector && vp, const ex & oc, bool do_index_renaming)
100 {
101         overall_coeff = oc;
102         construct_from_epvector(std::move(vp), do_index_renaming);
103         GINAC_ASSERT(is_canonical());
104 }
105
106 mul::mul(const ex & lh, const ex & mh, const ex & rh)
107 {
108         exvector factors;
109         factors.reserve(3);
110         factors.push_back(lh);
111         factors.push_back(mh);
112         factors.push_back(rh);
113         overall_coeff = _ex1;
114         construct_from_exvector(factors);
115         GINAC_ASSERT(is_canonical());
116 }
117
118 //////////
119 // archiving
120 //////////
121
122 //////////
123 // functions overriding virtual functions from base classes
124 //////////
125
126 void mul::print_overall_coeff(const print_context & c, const char *mul_sym) const
127 {
128         const numeric &coeff = ex_to<numeric>(overall_coeff);
129         if (coeff.csgn() == -1)
130                 c.s << '-';
131         if (!coeff.is_equal(*_num1_p) &&
132                 !coeff.is_equal(*_num_1_p)) {
133                 if (coeff.is_rational()) {
134                         if (coeff.is_negative())
135                                 (-coeff).print(c);
136                         else
137                                 coeff.print(c);
138                 } else {
139                         if (coeff.csgn() == -1)
140                                 (-coeff).print(c, precedence());
141                         else
142                                 coeff.print(c, precedence());
143                 }
144                 c.s << mul_sym;
145         }
146 }
147
148 void mul::do_print(const print_context & c, unsigned level) const
149 {
150         if (precedence() <= level)
151                 c.s << '(';
152
153         print_overall_coeff(c, "*");
154
155         bool first = true;
156         for (auto & it : seq) {
157                 if (!first)
158                         c.s << '*';
159                 else
160                         first = false;
161                 recombine_pair_to_ex(it).print(c, precedence());
162         }
163
164         if (precedence() <= level)
165                 c.s << ')';
166 }
167
168 void mul::do_print_latex(const print_latex & c, unsigned level) const
169 {
170         if (precedence() <= level)
171                 c.s << "{(";
172
173         print_overall_coeff(c, " ");
174
175         // Separate factors into those with negative numeric exponent
176         // and all others
177         exvector neg_powers, others;
178         for (auto & it : seq) {
179                 GINAC_ASSERT(is_exactly_a<numeric>(it.coeff));
180                 if (ex_to<numeric>(it.coeff).is_negative())
181                         neg_powers.push_back(recombine_pair_to_ex(expair(it.rest, -it.coeff)));
182                 else
183                         others.push_back(recombine_pair_to_ex(it));
184         }
185
186         if (!neg_powers.empty()) {
187
188                 // Factors with negative exponent are printed as a fraction
189                 c.s << "\\frac{";
190                 mul(others).eval().print(c);
191                 c.s << "}{";
192                 mul(neg_powers).eval().print(c);
193                 c.s << "}";
194
195         } else {
196
197                 // All other factors are printed in the ordinary way
198                 for (auto & vit : others) {
199                         c.s << ' ';
200                         vit.print(c, precedence());
201                 }
202         }
203
204         if (precedence() <= level)
205                 c.s << ")}";
206 }
207
208 void mul::do_print_csrc(const print_csrc & c, unsigned level) const
209 {
210         if (precedence() <= level)
211                 c.s << "(";
212
213         if (!overall_coeff.is_equal(_ex1)) {
214                 if (overall_coeff.is_equal(_ex_1))
215                         c.s << "-";
216                 else {
217                         overall_coeff.print(c, precedence());
218                         c.s << "*";
219                 }
220         }
221
222         // Print arguments, separated by "*" or "/"
223         auto it = seq.begin(), itend = seq.end();
224         while (it != itend) {
225
226                 // If the first argument is a negative integer power, it gets printed as "1.0/<expr>"
227                 bool needclosingparenthesis = false;
228                 if (it == seq.begin() && it->coeff.info(info_flags::negint)) {
229                         if (is_a<print_csrc_cl_N>(c)) {
230                                 c.s << "recip(";
231                                 needclosingparenthesis = true;
232                         } else
233                                 c.s << "1.0/";
234                 }
235
236                 // If the exponent is 1 or -1, it is left out
237                 if (it->coeff.is_equal(_ex1) || it->coeff.is_equal(_ex_1))
238                         it->rest.print(c, precedence());
239                 else if (it->coeff.info(info_flags::negint))
240                         ex(power(it->rest, -ex_to<numeric>(it->coeff))).print(c, level);
241                 else
242                         ex(power(it->rest, ex_to<numeric>(it->coeff))).print(c, level);
243
244                 if (needclosingparenthesis)
245                         c.s << ")";
246
247                 // Separator is "/" for negative integer powers, "*" otherwise
248                 ++it;
249                 if (it != itend) {
250                         if (it->coeff.info(info_flags::negint))
251                                 c.s << "/";
252                         else
253                                 c.s << "*";
254                 }
255         }
256
257         if (precedence() <= level)
258                 c.s << ")";
259 }
260
261 void mul::do_print_python_repr(const print_python_repr & c, unsigned level) const
262 {
263         c.s << class_name() << '(';
264         op(0).print(c);
265         for (size_t i=1; i<nops(); ++i) {
266                 c.s << ',';
267                 op(i).print(c);
268         }
269         c.s << ')';
270 }
271
272 bool mul::info(unsigned inf) const
273 {
274         switch (inf) {
275                 case info_flags::polynomial:
276                 case info_flags::integer_polynomial:
277                 case info_flags::cinteger_polynomial:
278                 case info_flags::rational_polynomial:
279                 case info_flags::real:
280                 case info_flags::rational:
281                 case info_flags::integer:
282                 case info_flags::crational:
283                 case info_flags::cinteger:
284                 case info_flags::even:
285                 case info_flags::crational_polynomial:
286                 case info_flags::rational_function: {
287                         for (auto & it : seq) {
288                                 if (!recombine_pair_to_ex(it).info(inf))
289                                         return false;
290                         }
291                         if (overall_coeff.is_equal(*_num1_p) && inf == info_flags::even)
292                                 return true;
293                         return overall_coeff.info(inf);
294                 }
295                 case info_flags::algebraic: {
296                         for (auto & it : seq) {
297                                 if (recombine_pair_to_ex(it).info(inf))
298                                         return true;
299                         }
300                         return false;
301                 }
302                 case info_flags::positive:
303                 case info_flags::negative: {
304                         if ((inf==info_flags::positive) && (flags & status_flags::is_positive))
305                                 return true;
306                         else if ((inf==info_flags::negative) && (flags & status_flags::is_negative))
307                                 return true;
308                         if (flags & status_flags::purely_indefinite)
309                                 return false;
310
311                         bool pos = true;
312                         for (auto & it : seq) {
313                                 const ex& factor = recombine_pair_to_ex(it);
314                                 if (factor.info(info_flags::positive))
315                                         continue;
316                                 else if (factor.info(info_flags::negative))
317                                         pos = !pos;
318                                 else
319                                         return false;
320                         }
321                         if (overall_coeff.info(info_flags::negative))
322                                 pos = !pos;
323                         setflag(pos ? status_flags::is_positive : status_flags::is_negative);
324                         return (inf == info_flags::positive? pos : !pos);
325                 }
326                 case info_flags::nonnegative: {
327                         if  (flags & status_flags::is_positive)
328                                 return true;
329                         bool pos = true;
330                         for (auto & it : seq) {
331                                 const ex& factor = recombine_pair_to_ex(it);
332                                 if (factor.info(info_flags::nonnegative) || factor.info(info_flags::positive))
333                                         continue;
334                                 else if (factor.info(info_flags::negative))
335                                         pos = !pos;
336                                 else
337                                         return false;
338                         }
339                         return (overall_coeff.info(info_flags::negative)? !pos : pos);
340                 }
341                 case info_flags::posint:
342                 case info_flags::negint: {
343                         bool pos = true;
344                         for (auto & it : seq) {
345                                 const ex& factor = recombine_pair_to_ex(it);
346                                 if (factor.info(info_flags::posint))
347                                         continue;
348                                 else if (factor.info(info_flags::negint))
349                                         pos = !pos;
350                                 else
351                                         return false;
352                         }
353                         if (overall_coeff.info(info_flags::negint))
354                                 pos = !pos;
355                         else if (!overall_coeff.info(info_flags::posint))
356                                 return false;
357                         return (inf ==info_flags::posint? pos : !pos); 
358                 }
359                 case info_flags::nonnegint: {
360                         bool pos = true;
361                         for (auto & it : seq) {
362                                 const ex& factor = recombine_pair_to_ex(it);
363                                 if (factor.info(info_flags::nonnegint) || factor.info(info_flags::posint))
364                                         continue;
365                                 else if (factor.info(info_flags::negint))
366                                         pos = !pos;
367                                 else
368                                         return false;
369                         }
370                         if (overall_coeff.info(info_flags::negint))
371                                 pos = !pos;
372                         else if (!overall_coeff.info(info_flags::posint))
373                                 return false;
374                         return pos; 
375                 }
376                 case info_flags::indefinite: {
377                         if (flags & status_flags::purely_indefinite)
378                                 return true;
379                         if (flags & (status_flags::is_positive | status_flags::is_negative))
380                                 return false;
381                         for (auto & it : seq) {
382                                 const ex& term = recombine_pair_to_ex(it);
383                                 if (term.info(info_flags::positive) || term.info(info_flags::negative))
384                                         return false;
385                         }
386                         setflag(status_flags::purely_indefinite);
387                         return true;
388                 }
389         }
390         return inherited::info(inf);
391 }
392
393 bool mul::is_polynomial(const ex & var) const
394 {
395         for (auto & it : seq) {
396                 if (!it.rest.is_polynomial(var) ||
397                     (it.rest.has(var) && !it.coeff.info(info_flags::nonnegint))) {
398                         return false;
399                 }
400         }
401         return true;
402 }
403
404 int mul::degree(const ex & s) const
405 {
406         // Sum up degrees of factors
407         int deg_sum = 0;
408         for (auto & it : seq) {
409                 if (ex_to<numeric>(it.coeff).is_integer())
410                         deg_sum += recombine_pair_to_ex(it).degree(s);
411                 else {
412                         if (it.rest.has(s))
413                                 throw std::runtime_error("mul::degree() undefined degree because of non-integer exponent");
414                 }
415         }
416         return deg_sum;
417 }
418
419 int mul::ldegree(const ex & s) const
420 {
421         // Sum up degrees of factors
422         int deg_sum = 0;
423         for (auto & it : seq) {
424                 if (ex_to<numeric>(it.coeff).is_integer())
425                         deg_sum += recombine_pair_to_ex(it).ldegree(s);
426                 else {
427                         if (it.rest.has(s))
428                                 throw std::runtime_error("mul::ldegree() undefined degree because of non-integer exponent");
429                 }
430         }
431         return deg_sum;
432 }
433
434 ex mul::coeff(const ex & s, int n) const
435 {
436         exvector coeffseq;
437         coeffseq.reserve(seq.size()+1);
438         
439         if (n==0) {
440                 // product of individual coeffs
441                 // if a non-zero power of s is found, the resulting product will be 0
442                 for (auto & it : seq)
443                         coeffseq.push_back(recombine_pair_to_ex(it).coeff(s,n));
444                 coeffseq.push_back(overall_coeff);
445                 return dynallocate<mul>(coeffseq);
446         }
447         
448         bool coeff_found = false;
449         for (auto & it : seq) {
450                 ex t = recombine_pair_to_ex(it);
451                 ex c = t.coeff(s, n);
452                 if (!c.is_zero()) {
453                         coeffseq.push_back(c);
454                         coeff_found = 1;
455                 } else {
456                         coeffseq.push_back(t);
457                 }
458         }
459         if (coeff_found) {
460                 coeffseq.push_back(overall_coeff);
461                 return dynallocate<mul>(coeffseq);
462         }
463         
464         return _ex0;
465 }
466
467 /** Perform automatic term rewriting rules in this class.  In the following
468  *  x, x1, x2,... stand for a symbolic variables of type ex and c, c1, c2...
469  *  stand for such expressions that contain a plain number.
470  *  - *(...,x;0) -> 0
471  *  - *(+(x1,x2,...);c) -> *(+(*(x1,c),*(x2,c),...))
472  *  - *(x;1) -> x
473  *  - *(;c) -> c
474  */
475 ex mul::eval() const
476 {
477         if (flags & status_flags::evaluated) {
478                 GINAC_ASSERT(seq.size()>0);
479                 GINAC_ASSERT(seq.size()>1 || !overall_coeff.is_equal(_ex1));
480                 return *this;
481         }
482
483         const epvector evaled = evalchildren();
484         if (unlikely(!evaled.empty())) {
485                 // start over evaluating a new object
486                 return dynallocate<mul>(std::move(evaled), overall_coeff);
487         }
488
489         size_t seq_size = seq.size();
490         if (overall_coeff.is_zero()) {
491                 // *(...,x;0) -> 0
492                 return _ex0;
493         } else if (seq_size==0) {
494                 // *(;c) -> c
495                 return overall_coeff;
496         } else if (seq_size==1 && overall_coeff.is_equal(_ex1)) {
497                 // *(x;1) -> x
498                 return recombine_pair_to_ex(*(seq.begin()));
499         } else if ((seq_size==1) &&
500                    is_exactly_a<add>((*seq.begin()).rest) &&
501                    ex_to<numeric>((*seq.begin()).coeff).is_equal(*_num1_p)) {
502                 // *(+(x,y,...);c) -> +(*(x,c),*(y,c),...) (c numeric(), no powers of +())
503                 const add & addref = ex_to<add>((*seq.begin()).rest);
504                 epvector distrseq;
505                 distrseq.reserve(addref.seq.size());
506                 for (auto & it : addref.seq) {
507                         distrseq.push_back(addref.combine_pair_with_coeff_to_pair(it, overall_coeff));
508                 }
509                 return dynallocate<add>(std::move(distrseq),
510                                         ex_to<numeric>(addref.overall_coeff).mul_dyn(ex_to<numeric>(overall_coeff)))
511                         .setflag(status_flags::evaluated);
512         } else if ((seq_size >= 2) && (! (flags & status_flags::expanded))) {
513                 // Strip the content and the unit part from each term. Thus
514                 // things like (-x+a)*(3*x-3*a) automagically turn into - 3*(x-a)^2
515
516                 auto i = seq.begin(), last = seq.end();
517                 auto j = seq.begin();
518                 epvector s;
519                 numeric oc = *_num1_p;
520                 bool something_changed = false;
521                 while (i!=last) {
522                         if (likely(! (is_a<add>(i->rest) && i->coeff.is_equal(_ex1)))) {
523                                 // power::eval has such a rule, no need to handle powers here
524                                 ++i;
525                                 continue;
526                         }
527
528                         // XXX: What is the best way to check if the polynomial is a primitive? 
529                         numeric c = i->rest.integer_content();
530                         const numeric lead_coeff =
531                                 ex_to<numeric>(ex_to<add>(i->rest).seq.begin()->coeff).div(c);
532                         const bool canonicalizable = lead_coeff.is_integer();
533
534                         // XXX: The main variable is chosen in a random way, so this code 
535                         // does NOT transform the term into the canonical form (thus, in some
536                         // very unlucky event it can even loop forever). Hopefully the main
537                         // variable will be the same for all terms in *this
538                         const bool unit_normal = lead_coeff.is_pos_integer();
539                         if (likely((c == *_num1_p) && ((! canonicalizable) || unit_normal))) {
540                                 ++i;
541                                 continue;
542                         }
543
544                         if (! something_changed) {
545                                 s.reserve(seq_size);
546                                 something_changed = true;
547                         }
548
549                         while ((j!=i) && (j!=last)) {
550                                 s.push_back(*j);
551                                 ++j;
552                         }
553
554                         if (! unit_normal)
555                                 c = c.mul(*_num_1_p);
556
557                         oc = oc.mul(c);
558
559                         // divide add by the number in place to save at least 2 .eval() calls
560                         const add& addref = ex_to<add>(i->rest);
561                         add & primitive = dynallocate<add>(addref);
562                         primitive.clearflag(status_flags::hash_calculated);
563                         primitive.overall_coeff = ex_to<numeric>(primitive.overall_coeff).div_dyn(c);
564                         for (auto & ai : primitive.seq)
565                                 ai.coeff = ex_to<numeric>(ai.coeff).div_dyn(c);
566
567                         s.push_back(expair(primitive, _ex1));
568
569                         ++i;
570                         ++j;
571                 }
572                 if (something_changed) {
573                         while (j!=last) {
574                                 s.push_back(*j);
575                                 ++j;
576                         }
577                         return dynallocate<mul>(std::move(s), ex_to<numeric>(overall_coeff).mul_dyn(oc));
578                 }
579         }
580
581         return this->hold();
582 }
583
584 ex mul::evalf(int level) const
585 {
586         if (level==1)
587                 return mul(seq, overall_coeff);
588         
589         if (level==-max_recursion_level)
590                 throw(std::runtime_error("max recursion level reached"));
591         
592         epvector s;
593         s.reserve(seq.size());
594
595         --level;
596         for (auto & it : seq) {
597                 s.push_back(expair(it.rest.evalf(level), it.coeff));
598         }
599         return dynallocate<mul>(std::move(s), overall_coeff.evalf(level));
600 }
601
602 void mul::find_real_imag(ex & rp, ex & ip) const
603 {
604         rp = overall_coeff.real_part();
605         ip = overall_coeff.imag_part();
606         for (auto & it : seq) {
607                 ex factor = recombine_pair_to_ex(it);
608                 ex new_rp = factor.real_part();
609                 ex new_ip = factor.imag_part();
610                 if (new_ip.is_zero()) {
611                         rp *= new_rp;
612                         ip *= new_rp;
613                 } else {
614                         ex temp = rp*new_rp - ip*new_ip;
615                         ip = ip*new_rp + rp*new_ip;
616                         rp = temp;
617                 }
618         }
619         rp = rp.expand();
620         ip = ip.expand();
621 }
622
623 ex mul::real_part() const
624 {
625         ex rp, ip;
626         find_real_imag(rp, ip);
627         return rp;
628 }
629
630 ex mul::imag_part() const
631 {
632         ex rp, ip;
633         find_real_imag(rp, ip);
634         return ip;
635 }
636
637 ex mul::evalm() const
638 {
639         // numeric*matrix
640         if (seq.size() == 1 && seq[0].coeff.is_equal(_ex1)
641          && is_a<matrix>(seq[0].rest))
642                 return ex_to<matrix>(seq[0].rest).mul(ex_to<numeric>(overall_coeff));
643
644         // Evaluate children first, look whether there are any matrices at all
645         // (there can be either no matrices or one matrix; if there were more
646         // than one matrix, it would be a non-commutative product)
647         epvector s;
648         s.reserve(seq.size());
649
650         bool have_matrix = false;
651         epvector::iterator the_matrix;
652
653         for (auto & it : seq) {
654                 const ex &m = recombine_pair_to_ex(it).evalm();
655                 s.push_back(split_ex_to_pair(m));
656                 if (is_a<matrix>(m)) {
657                         have_matrix = true;
658                         the_matrix = s.end() - 1;
659                 }
660         }
661
662         if (have_matrix) {
663
664                 // The product contained a matrix. We will multiply all other factors
665                 // into that matrix.
666                 matrix m = ex_to<matrix>(the_matrix->rest);
667                 s.erase(the_matrix);
668                 ex scalar = dynallocate<mul>(std::move(s), overall_coeff);
669                 return m.mul_scalar(scalar);
670
671         } else
672                 return dynallocate<mul>(std::move(s), overall_coeff);
673 }
674
675 ex mul::eval_ncmul(const exvector & v) const
676 {
677         if (seq.empty())
678                 return inherited::eval_ncmul(v);
679
680         // Find first noncommutative element and call its eval_ncmul()
681         for (auto & it : seq)
682                 if (it.rest.return_type() == return_types::noncommutative)
683                         return it.rest.eval_ncmul(v);
684         return inherited::eval_ncmul(v);
685 }
686
687 bool tryfactsubs(const ex & origfactor, const ex & patternfactor, int & nummatches, exmap& repls)
688 {       
689         ex origbase;
690         int origexponent;
691         int origexpsign;
692
693         if (is_exactly_a<power>(origfactor) && origfactor.op(1).info(info_flags::integer)) {
694                 origbase = origfactor.op(0);
695                 int expon = ex_to<numeric>(origfactor.op(1)).to_int();
696                 origexponent = expon > 0 ? expon : -expon;
697                 origexpsign = expon > 0 ? 1 : -1;
698         } else {
699                 origbase = origfactor;
700                 origexponent = 1;
701                 origexpsign = 1;
702         }
703
704         ex patternbase;
705         int patternexponent;
706         int patternexpsign;
707
708         if (is_exactly_a<power>(patternfactor) && patternfactor.op(1).info(info_flags::integer)) {
709                 patternbase = patternfactor.op(0);
710                 int expon = ex_to<numeric>(patternfactor.op(1)).to_int();
711                 patternexponent = expon > 0 ? expon : -expon;
712                 patternexpsign = expon > 0 ? 1 : -1;
713         } else {
714                 patternbase = patternfactor;
715                 patternexponent = 1;
716                 patternexpsign = 1;
717         }
718
719         exmap saverepls = repls;
720         if (origexponent < patternexponent || origexpsign != patternexpsign || !origbase.match(patternbase,saverepls))
721                 return false;
722         repls = saverepls;
723
724         int newnummatches = origexponent / patternexponent;
725         if (newnummatches < nummatches)
726                 nummatches = newnummatches;
727         return true;
728 }
729
730 /** Checks whether e matches to the pattern pat and the (possibly to be updated)
731   * list of replacements repls. This matching is in the sense of algebraic
732   * substitutions. Matching starts with pat.op(factor) of the pattern because
733   * the factors before this one have already been matched. The (possibly
734   * updated) number of matches is in nummatches. subsed[i] is true for factors
735   * that already have been replaced by previous substitutions and matched[i]
736   * is true for factors that have been matched by the current match.
737   */
738 bool algebraic_match_mul_with_mul(const mul &e, const ex &pat, exmap& repls,
739                                   int factor, int &nummatches, const std::vector<bool> &subsed,
740                                   std::vector<bool> &matched)
741 {
742         GINAC_ASSERT(subsed.size() == e.nops());
743         GINAC_ASSERT(matched.size() == e.nops());
744
745         if (factor == (int)pat.nops())
746                 return true;
747
748         for (size_t i=0; i<e.nops(); ++i) {
749                 if(subsed[i] || matched[i])
750                         continue;
751                 exmap newrepls = repls;
752                 int newnummatches = nummatches;
753                 if (tryfactsubs(e.op(i), pat.op(factor), newnummatches, newrepls)) {
754                         matched[i] = true;
755                         if (algebraic_match_mul_with_mul(e, pat, newrepls, factor+1,
756                                         newnummatches, subsed, matched)) {
757                                 repls = newrepls;
758                                 nummatches = newnummatches;
759                                 return true;
760                         }
761                         else
762                                 matched[i] = false;
763                 }
764         }
765
766         return false;
767 }
768
769 bool mul::has(const ex & pattern, unsigned options) const
770 {
771         if(!(options & has_options::algebraic))
772                 return basic::has(pattern,options);
773         if(is_a<mul>(pattern)) {
774                 exmap repls;
775                 int nummatches = std::numeric_limits<int>::max();
776                 std::vector<bool> subsed(nops(), false);
777                 std::vector<bool> matched(nops(), false);
778                 if(algebraic_match_mul_with_mul(*this, pattern, repls, 0, nummatches,
779                                 subsed, matched))
780                         return true;
781         }
782         return basic::has(pattern, options);
783 }
784
785 ex mul::algebraic_subs_mul(const exmap & m, unsigned options) const
786 {       
787         std::vector<bool> subsed(nops(), false);
788         ex divide_by = 1;
789         ex multiply_by = 1;
790
791         for (auto & it : m) {
792
793                 if (is_exactly_a<mul>(it.first)) {
794 retry1:
795                         int nummatches = std::numeric_limits<int>::max();
796                         std::vector<bool> currsubsed(nops(), false);
797                         exmap repls;
798                         
799                         if (!algebraic_match_mul_with_mul(*this, it.first, repls, 0, nummatches, subsed, currsubsed))
800                                 continue;
801
802                         for (size_t j=0; j<subsed.size(); j++)
803                                 if (currsubsed[j])
804                                         subsed[j] = true;
805                         ex subsed_pattern
806                                 = it.first.subs(repls, subs_options::no_pattern);
807                         divide_by *= pow(subsed_pattern, nummatches);
808                         ex subsed_result
809                                 = it.second.subs(repls, subs_options::no_pattern);
810                         multiply_by *= pow(subsed_result, nummatches);
811                         goto retry1;
812
813                 } else {
814
815                         for (size_t j=0; j<this->nops(); j++) {
816                                 int nummatches = std::numeric_limits<int>::max();
817                                 exmap repls;
818                                 if (!subsed[j] && tryfactsubs(op(j), it.first, nummatches, repls)){
819                                         subsed[j] = true;
820                                         ex subsed_pattern
821                                                 = it.first.subs(repls, subs_options::no_pattern);
822                                         divide_by *= pow(subsed_pattern, nummatches);
823                                         ex subsed_result
824                                                 = it.second.subs(repls, subs_options::no_pattern);
825                                         multiply_by *= pow(subsed_result, nummatches);
826                                 }
827                         }
828                 }
829         }
830
831         bool subsfound = false;
832         for (size_t i=0; i<subsed.size(); i++) {
833                 if (subsed[i]) {
834                         subsfound = true;
835                         break;
836                 }
837         }
838         if (!subsfound)
839                 return subs_one_level(m, options | subs_options::algebraic);
840
841         return ((*this)/divide_by)*multiply_by;
842 }
843
844 ex mul::conjugate() const
845 {
846         // The base class' method is wrong here because we have to be careful at
847         // branch cuts. power::conjugate takes care of that already, so use it.
848         std::unique_ptr<epvector> newepv(nullptr);
849         for (auto i=seq.begin(); i!=seq.end(); ++i) {
850                 if (newepv) {
851                         newepv->push_back(split_ex_to_pair(recombine_pair_to_ex(*i).conjugate()));
852                         continue;
853                 }
854                 ex x = recombine_pair_to_ex(*i);
855                 ex c = x.conjugate();
856                 if (c.is_equal(x)) {
857                         continue;
858                 }
859                 newepv.reset(new epvector);
860                 newepv->reserve(seq.size());
861                 for (auto j=seq.begin(); j!=i; ++j) {
862                         newepv->push_back(*j);
863                 }
864                 newepv->push_back(split_ex_to_pair(c));
865         }
866         ex x = overall_coeff.conjugate();
867         if (!newepv && are_ex_trivially_equal(x, overall_coeff)) {
868                 return *this;
869         }
870         return thisexpairseq(newepv ? std::move(*newepv) : seq, x);
871 }
872
873
874 // protected
875
876 /** Implementation of ex::diff() for a product.  It applies the product rule.
877  *  @see ex::diff */
878 ex mul::derivative(const symbol & s) const
879 {
880         size_t num = seq.size();
881         exvector addseq;
882         addseq.reserve(num);
883         
884         // D(a*b*c) = D(a)*b*c + a*D(b)*c + a*b*D(c)
885         epvector mulseq = seq;
886         auto i = seq.begin(), end = seq.end();
887         auto i2 = mulseq.begin();
888         while (i != end) {
889                 expair ep = split_ex_to_pair(pow(i->rest, i->coeff - _ex1) *
890                                              i->rest.diff(s));
891                 ep.swap(*i2);
892                 addseq.push_back(dynallocate<mul>(mulseq, overall_coeff * i->coeff));
893                 ep.swap(*i2);
894                 ++i; ++i2;
895         }
896         return dynallocate<add>(addseq);
897 }
898
899 int mul::compare_same_type(const basic & other) const
900 {
901         return inherited::compare_same_type(other);
902 }
903
904 unsigned mul::return_type() const
905 {
906         if (seq.empty()) {
907                 // mul without factors: should not happen, but commutates
908                 return return_types::commutative;
909         }
910         
911         bool all_commutative = true;
912         epvector::const_iterator noncommutative_element; // point to first found nc element
913         
914         epvector::const_iterator i = seq.begin(), end = seq.end();
915         while (i != end) {
916                 unsigned rt = i->rest.return_type();
917                 if (rt == return_types::noncommutative_composite)
918                         return rt; // one ncc -> mul also ncc
919                 if ((rt == return_types::noncommutative) && (all_commutative)) {
920                         // first nc element found, remember position
921                         noncommutative_element = i;
922                         all_commutative = false;
923                 }
924                 if ((rt == return_types::noncommutative) && (!all_commutative)) {
925                         // another nc element found, compare type_infos
926                         if (noncommutative_element->rest.return_type_tinfo() != i->rest.return_type_tinfo()) {
927                                         // different types -> mul is ncc
928                                         return return_types::noncommutative_composite;
929                         }
930                 }
931                 ++i;
932         }
933         // all factors checked
934         return all_commutative ? return_types::commutative : return_types::noncommutative;
935 }
936
937 return_type_t mul::return_type_tinfo() const
938 {
939         if (seq.empty())
940                 return make_return_type_t<mul>(); // mul without factors: should not happen
941         
942         // return type_info of first noncommutative element
943         for (auto & it : seq)
944                 if (it.rest.return_type() == return_types::noncommutative)
945                         return it.rest.return_type_tinfo();
946
947         // no noncommutative element found, should not happen
948         return make_return_type_t<mul>();
949 }
950
951 ex mul::thisexpairseq(const epvector & v, const ex & oc, bool do_index_renaming) const
952 {
953         return dynallocate<mul>(v, oc, do_index_renaming);
954 }
955
956 ex mul::thisexpairseq(epvector && vp, const ex & oc, bool do_index_renaming) const
957 {
958         return dynallocate<mul>(std::move(vp), oc, do_index_renaming);
959 }
960
961 expair mul::split_ex_to_pair(const ex & e) const
962 {
963         if (is_exactly_a<power>(e)) {
964                 const power & powerref = ex_to<power>(e);
965                 if (is_exactly_a<numeric>(powerref.exponent))
966                         return expair(powerref.basis,powerref.exponent);
967         }
968         return expair(e,_ex1);
969 }
970
971 expair mul::combine_ex_with_coeff_to_pair(const ex & e,
972                                           const ex & c) const
973 {
974         GINAC_ASSERT(is_exactly_a<numeric>(c));
975
976         // First, try a common shortcut:
977         if (is_exactly_a<symbol>(e))
978                 return expair(e, c);
979
980         // to avoid duplication of power simplification rules,
981         // we create a temporary power object
982         // otherwise it would be hard to correctly evaluate
983         // expression like (4^(1/3))^(3/2)
984         if (c.is_equal(_ex1))
985                 return split_ex_to_pair(e);
986
987         return split_ex_to_pair(pow(e,c));
988 }
989
990 expair mul::combine_pair_with_coeff_to_pair(const expair & p,
991                                             const ex & c) const
992 {
993         GINAC_ASSERT(is_exactly_a<numeric>(p.coeff));
994         GINAC_ASSERT(is_exactly_a<numeric>(c));
995
996         // to avoid duplication of power simplification rules,
997         // we create a temporary power object
998         // otherwise it would be hard to correctly evaluate
999         // expression like (4^(1/3))^(3/2)
1000         if (c.is_equal(_ex1))
1001                 return p;
1002
1003         return split_ex_to_pair(pow(recombine_pair_to_ex(p),c));
1004 }
1005
1006 ex mul::recombine_pair_to_ex(const expair & p) const
1007 {
1008         if (ex_to<numeric>(p.coeff).is_equal(*_num1_p)) 
1009                 return p.rest;
1010         else
1011                 return dynallocate<power>(p.rest, p.coeff);
1012 }
1013
1014 bool mul::expair_needs_further_processing(epp it)
1015 {
1016         if (is_exactly_a<mul>(it->rest) &&
1017             ex_to<numeric>(it->coeff).is_integer()) {
1018                 // combined pair is product with integer power -> expand it
1019                 *it = split_ex_to_pair(recombine_pair_to_ex(*it));
1020                 return true;
1021         }
1022         if (is_exactly_a<numeric>(it->rest)) {
1023                 if (it->coeff.is_equal(_ex1)) {
1024                         // pair has coeff 1 and must be moved to the end
1025                         return true;
1026                 }
1027                 expair ep = split_ex_to_pair(recombine_pair_to_ex(*it));
1028                 if (!ep.is_equal(*it)) {
1029                         // combined pair is a numeric power which can be simplified
1030                         *it = ep;
1031                         return true;
1032                 }
1033         }
1034         return false;
1035 }       
1036
1037 ex mul::default_overall_coeff() const
1038 {
1039         return _ex1;
1040 }
1041
1042 void mul::combine_overall_coeff(const ex & c)
1043 {
1044         GINAC_ASSERT(is_exactly_a<numeric>(overall_coeff));
1045         GINAC_ASSERT(is_exactly_a<numeric>(c));
1046         overall_coeff = ex_to<numeric>(overall_coeff).mul_dyn(ex_to<numeric>(c));
1047 }
1048
1049 void mul::combine_overall_coeff(const ex & c1, const ex & c2)
1050 {
1051         GINAC_ASSERT(is_exactly_a<numeric>(overall_coeff));
1052         GINAC_ASSERT(is_exactly_a<numeric>(c1));
1053         GINAC_ASSERT(is_exactly_a<numeric>(c2));
1054         overall_coeff = ex_to<numeric>(overall_coeff).mul_dyn(ex_to<numeric>(c1).power(ex_to<numeric>(c2)));
1055 }
1056
1057 bool mul::can_make_flat(const expair & p) const
1058 {
1059         GINAC_ASSERT(is_exactly_a<numeric>(p.coeff));
1060
1061         // (x*y)^c == x^c*y^c  if c âˆˆ â„¤
1062         return p.coeff.info(info_flags::integer);
1063 }
1064
1065 bool mul::can_be_further_expanded(const ex & e)
1066 {
1067         if (is_exactly_a<mul>(e)) {
1068                 for (auto & it : ex_to<mul>(e).seq) {
1069                         if (is_exactly_a<add>(it.rest) && it.coeff.info(info_flags::posint))
1070                                 return true;
1071                 }
1072         } else if (is_exactly_a<power>(e)) {
1073                 if (is_exactly_a<add>(e.op(0)) && e.op(1).info(info_flags::posint))
1074                         return true;
1075         }
1076         return false;
1077 }
1078
1079 ex mul::expand(unsigned options) const
1080 {
1081         // Check for trivial case: expanding the monomial (~ 30% of all calls)
1082         bool monomial_case = true;
1083         for (const auto & i : seq) {
1084                 if (!is_a<symbol>(i.rest) || !i.coeff.info(info_flags::integer)) {
1085                         monomial_case = false;
1086                         break;
1087                 }
1088         }
1089         if (monomial_case) {
1090                 setflag(status_flags::expanded);
1091                 return *this;
1092         }
1093
1094         // do not rename indices if the object has no indices at all
1095         if ((!(options & expand_options::expand_rename_idx)) && 
1096             this->info(info_flags::has_indices))
1097                 options |= expand_options::expand_rename_idx;
1098
1099         const bool skip_idx_rename = !(options & expand_options::expand_rename_idx);
1100
1101         // First, expand the children
1102         epvector expanded = expandchildren(options);
1103         const epvector & expanded_seq = (expanded.empty() ? seq : expanded);
1104
1105         // Now, look for all the factors that are sums and multiply each one out
1106         // with the next one that is found while collecting the factors which are
1107         // not sums
1108         ex last_expanded = _ex1;
1109
1110         epvector non_adds;
1111         non_adds.reserve(expanded_seq.size());
1112
1113         for (const auto & cit : expanded_seq) {
1114                 if (is_exactly_a<add>(cit.rest) &&
1115                         (cit.coeff.is_equal(_ex1))) {
1116                         if (is_exactly_a<add>(last_expanded)) {
1117
1118                                 // Expand a product of two sums, aggressive version.
1119                                 // Caring for the overall coefficients in separate loops can
1120                                 // sometimes give a performance gain of up to 15%!
1121
1122                                 const int sizedifference = ex_to<add>(last_expanded).seq.size()-ex_to<add>(cit.rest).seq.size();
1123                                 // add2 is for the inner loop and should be the bigger of the two sums
1124                                 // in the presence of asymptotically good sorting:
1125                                 const add& add1 = (sizedifference<0 ? ex_to<add>(last_expanded) : ex_to<add>(cit.rest));
1126                                 const add& add2 = (sizedifference<0 ? ex_to<add>(cit.rest) : ex_to<add>(last_expanded));
1127                                 epvector distrseq;
1128                                 distrseq.reserve(add1.seq.size()+add2.seq.size());
1129
1130                                 // Multiply add2 with the overall coefficient of add1 and append it to distrseq:
1131                                 if (!add1.overall_coeff.is_zero()) {
1132                                         if (add1.overall_coeff.is_equal(_ex1))
1133                                                 distrseq.insert(distrseq.end(), add2.seq.begin(), add2.seq.end());
1134                                         else
1135                                                 for (const auto & i : add2.seq)
1136                                                         distrseq.push_back(expair(i.rest, ex_to<numeric>(i.coeff).mul_dyn(ex_to<numeric>(add1.overall_coeff))));
1137                                 }
1138
1139                                 // Multiply add1 with the overall coefficient of add2 and append it to distrseq:
1140                                 if (!add2.overall_coeff.is_zero()) {
1141                                         if (add2.overall_coeff.is_equal(_ex1))
1142                                                 distrseq.insert(distrseq.end(), add1.seq.begin(), add1.seq.end());
1143                                         else
1144                                                 for (const auto & i : add1.seq)
1145                                                         distrseq.push_back(expair(i.rest, ex_to<numeric>(i.coeff).mul_dyn(ex_to<numeric>(add2.overall_coeff))));
1146                                 }
1147
1148                                 // Compute the new overall coefficient and put it together:
1149                                 ex tmp_accu = dynallocate<add>(distrseq, add1.overall_coeff*add2.overall_coeff);
1150
1151                                 exvector add1_dummy_indices, add2_dummy_indices, add_indices;
1152                                 lst dummy_subs;
1153
1154                                 if (!skip_idx_rename) {
1155                                         for (const auto & i : add1.seq) {
1156                                                 add_indices = get_all_dummy_indices_safely(i.rest);
1157                                                 add1_dummy_indices.insert(add1_dummy_indices.end(), add_indices.begin(), add_indices.end());
1158                                         }
1159                                         for (const auto & i : add2.seq) {
1160                                                 add_indices = get_all_dummy_indices_safely(i.rest);
1161                                                 add2_dummy_indices.insert(add2_dummy_indices.end(), add_indices.begin(), add_indices.end());
1162                                         }
1163
1164                                         sort(add1_dummy_indices.begin(), add1_dummy_indices.end(), ex_is_less());
1165                                         sort(add2_dummy_indices.begin(), add2_dummy_indices.end(), ex_is_less());
1166                                         dummy_subs = rename_dummy_indices_uniquely(add1_dummy_indices, add2_dummy_indices);
1167                                 }
1168
1169                                 // Multiply explicitly all non-numeric terms of add1 and add2:
1170                                 for (const auto & i2 : add2.seq) {
1171                                         // We really have to combine terms here in order to compactify
1172                                         // the result.  Otherwise it would become waayy tooo bigg.
1173                                         numeric oc(*_num0_p);
1174                                         epvector distrseq2;
1175                                         distrseq2.reserve(add1.seq.size());
1176                                         const ex i2_new = (skip_idx_rename || (dummy_subs.op(0).nops() == 0) ?
1177                                                         i2.rest :
1178                                                         i2.rest.subs(ex_to<lst>(dummy_subs.op(0)),
1179                                                                      ex_to<lst>(dummy_subs.op(1)), subs_options::no_pattern));
1180                                         for (const auto & i1 : add1.seq) {
1181                                                 // Don't push_back expairs which might have a rest that evaluates to a numeric,
1182                                                 // since that would violate an invariant of expairseq:
1183                                                 const ex rest = dynallocate<mul>(i1.rest, i2_new);
1184                                                 if (is_exactly_a<numeric>(rest)) {
1185                                                         oc += ex_to<numeric>(rest).mul(ex_to<numeric>(i1.coeff).mul(ex_to<numeric>(i2.coeff)));
1186                                                 } else {
1187                                                         distrseq2.push_back(expair(rest, ex_to<numeric>(i1.coeff).mul_dyn(ex_to<numeric>(i2.coeff))));
1188                                                 }
1189                                         }
1190                                         tmp_accu += dynallocate<add>(std::move(distrseq2), oc);
1191                                 }
1192                                 last_expanded = tmp_accu;
1193                         } else {
1194                                 if (!last_expanded.is_equal(_ex1))
1195                                         non_adds.push_back(split_ex_to_pair(last_expanded));
1196                                 last_expanded = cit.rest;
1197                         }
1198
1199                 } else {
1200                         non_adds.push_back(cit);
1201                 }
1202         }
1203
1204         // Now the only remaining thing to do is to multiply the factors which
1205         // were not sums into the "last_expanded" sum
1206         if (is_exactly_a<add>(last_expanded)) {
1207                 size_t n = last_expanded.nops();
1208                 exvector distrseq;
1209                 distrseq.reserve(n);
1210                 exvector va;
1211                 if (! skip_idx_rename) {
1212                         va = get_all_dummy_indices_safely(mul(non_adds));
1213                         sort(va.begin(), va.end(), ex_is_less());
1214                 }
1215
1216                 for (size_t i=0; i<n; ++i) {
1217                         epvector factors = non_adds;
1218                         if (skip_idx_rename)
1219                                 factors.push_back(split_ex_to_pair(last_expanded.op(i)));
1220                         else
1221                                 factors.push_back(split_ex_to_pair(rename_dummy_indices_uniquely(va, last_expanded.op(i))));
1222                         ex term = dynallocate<mul>(factors, overall_coeff);
1223                         if (can_be_further_expanded(term)) {
1224                                 distrseq.push_back(term.expand());
1225                         } else {
1226                                 if (options == 0)
1227                                         ex_to<basic>(term).setflag(status_flags::expanded);
1228                                 distrseq.push_back(term);
1229                         }
1230                 }
1231
1232                 return dynallocate<add>(distrseq).setflag(options == 0 ? status_flags::expanded : 0);
1233         }
1234
1235         non_adds.push_back(split_ex_to_pair(last_expanded));
1236         ex result = dynallocate<mul>(non_adds, overall_coeff);
1237         if (can_be_further_expanded(result)) {
1238                 return result.expand();
1239         } else {
1240                 if (options == 0)
1241                         ex_to<basic>(result).setflag(status_flags::expanded);
1242                 return result;
1243         }
1244 }
1245
1246   
1247 //////////
1248 // new virtual functions which can be overridden by derived classes
1249 //////////
1250
1251 // none
1252
1253 //////////
1254 // non-virtual functions in this class
1255 //////////
1256
1257
1258 /** Member-wise expand the expairs representing this sequence.  This must be
1259  *  overridden from expairseq::expandchildren() and done iteratively in order
1260  *  to allow for early cancellations and thus safe memory.
1261  *
1262  *  @see mul::expand()
1263  *  @return epvector containing expanded pairs, empty if no members
1264  *    had to be changed. */
1265 epvector mul::expandchildren(unsigned options) const
1266 {
1267         auto cit = seq.begin(), last = seq.end();
1268         while (cit!=last) {
1269                 const ex & factor = recombine_pair_to_ex(*cit);
1270                 const ex & expanded_factor = factor.expand(options);
1271                 if (!are_ex_trivially_equal(factor,expanded_factor)) {
1272                         
1273                         // something changed, copy seq, eval and return it
1274                         epvector s;
1275                         s.reserve(seq.size());
1276                         
1277                         // copy parts of seq which are known not to have changed
1278                         auto cit2 = seq.begin();
1279                         while (cit2!=cit) {
1280                                 s.push_back(*cit2);
1281                                 ++cit2;
1282                         }
1283
1284                         // copy first changed element
1285                         s.push_back(split_ex_to_pair(expanded_factor));
1286                         ++cit2;
1287
1288                         // copy rest
1289                         while (cit2!=last) {
1290                                 s.push_back(split_ex_to_pair(recombine_pair_to_ex(*cit2).expand(options)));
1291                                 ++cit2;
1292                         }
1293                         return s;
1294                 }
1295                 ++cit;
1296         }
1297
1298         return epvector(); // nothing has changed
1299 }
1300
1301 GINAC_BIND_UNARCHIVER(mul);
1302
1303 } // namespace GiNaC