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