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