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