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