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