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