8fe739987274e6d93dc8449f6fa5be1ed5992881
[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 constructor
43 //////////
44
45 mul::mul()
46 {
47         tinfo_key = TINFO_mul;
48 }
49
50 //////////
51 // other constructors
52 //////////
53
54 // public
55
56 mul::mul(const ex & lh, const ex & rh)
57 {
58         tinfo_key = TINFO_mul;
59         overall_coeff = _ex1;
60         construct_from_2_ex(lh,rh);
61         GINAC_ASSERT(is_canonical());
62 }
63
64 mul::mul(const exvector & v)
65 {
66         tinfo_key = TINFO_mul;
67         overall_coeff = _ex1;
68         construct_from_exvector(v);
69         GINAC_ASSERT(is_canonical());
70 }
71
72 mul::mul(const epvector & v)
73 {
74         tinfo_key = TINFO_mul;
75         overall_coeff = _ex1;
76         construct_from_epvector(v);
77         GINAC_ASSERT(is_canonical());
78 }
79
80 mul::mul(const epvector & v, const ex & oc)
81 {
82         tinfo_key = TINFO_mul;
83         overall_coeff = oc;
84         construct_from_epvector(v);
85         GINAC_ASSERT(is_canonical());
86 }
87
88 mul::mul(epvector * vp, const ex & oc)
89 {
90         tinfo_key = TINFO_mul;
91         GINAC_ASSERT(vp!=0);
92         overall_coeff = oc;
93         construct_from_epvector(*vp);
94         delete vp;
95         GINAC_ASSERT(is_canonical());
96 }
97
98 mul::mul(const ex & lh, const ex & mh, const ex & rh)
99 {
100         tinfo_key = TINFO_mul;
101         exvector factors;
102         factors.reserve(3);
103         factors.push_back(lh);
104         factors.push_back(mh);
105         factors.push_back(rh);
106         overall_coeff = _ex1;
107         construct_from_exvector(factors);
108         GINAC_ASSERT(is_canonical());
109 }
110
111 //////////
112 // archiving
113 //////////
114
115 DEFAULT_ARCHIVING(mul)
116
117 //////////
118 // functions overriding virtual functions from base classes
119 //////////
120
121 // public
122 void mul::print(const print_context & c, unsigned level) const
123 {
124         if (is_a<print_tree>(c)) {
125
126                 inherited::print(c, level);
127
128         } else if (is_a<print_csrc>(c)) {
129
130                 if (precedence() <= level)
131                         c.s << "(";
132
133                 if (!overall_coeff.is_equal(_ex1)) {
134                         overall_coeff.print(c, precedence());
135                         c.s << "*";
136                 }
137
138                 // Print arguments, separated by "*" or "/"
139                 epvector::const_iterator it = seq.begin(), itend = seq.end();
140                 while (it != itend) {
141
142                         // If the first argument is a negative integer power, it gets printed as "1.0/<expr>"
143                         bool needclosingparenthesis = false;
144                         if (it == seq.begin() && it->coeff.info(info_flags::negint)) {
145                                 if (is_a<print_csrc_cl_N>(c)) {
146                                         c.s << "recip(";
147                                         needclosingparenthesis = true;
148                                 } else
149                                         c.s << "1.0/";
150                         }
151
152                         // If the exponent is 1 or -1, it is left out
153                         if (it->coeff.is_equal(_ex1) || it->coeff.is_equal(_ex_1))
154                                 it->rest.print(c, precedence());
155                         else if (it->coeff.info(info_flags::negint))
156                                 // Outer parens around ex needed for broken GCC parser:
157                                 (ex(power(it->rest, -ex_to<numeric>(it->coeff)))).print(c, level);
158                         else
159                                 // Outer parens around ex needed for broken GCC parser:
160                                 (ex(power(it->rest, ex_to<numeric>(it->coeff)))).print(c, level);
161
162                         if (needclosingparenthesis)
163                                 c.s << ")";
164
165                         // Separator is "/" for negative integer powers, "*" otherwise
166                         ++it;
167                         if (it != itend) {
168                                 if (it->coeff.info(info_flags::negint))
169                                         c.s << "/";
170                                 else
171                                         c.s << "*";
172                         }
173                 }
174
175                 if (precedence() <= level)
176                         c.s << ")";
177
178         } else if (is_a<print_python_repr>(c)) {
179                 c.s << class_name() << '(';
180                 op(0).print(c);
181                 for (size_t i=1; i<nops(); ++i) {
182                         c.s << ',';
183                         op(i).print(c);
184                 }
185                 c.s << ')';
186         } else {
187
188                 if (precedence() <= level) {
189                         if (is_a<print_latex>(c))
190                                 c.s << "{(";
191                         else
192                                 c.s << "(";
193                 }
194
195                 // First print the overall numeric coefficient
196                 const numeric &coeff = ex_to<numeric>(overall_coeff);
197                 if (coeff.csgn() == -1)
198                         c.s << '-';
199                 if (!coeff.is_equal(_num1) &&
200                         !coeff.is_equal(_num_1)) {
201                         if (coeff.is_rational()) {
202                                 if (coeff.is_negative())
203                                         (-coeff).print(c);
204                                 else
205                                         coeff.print(c);
206                         } else {
207                                 if (coeff.csgn() == -1)
208                                         (-coeff).print(c, precedence());
209                                 else
210                                         coeff.print(c, precedence());
211                         }
212                         if (is_a<print_latex>(c))
213                                 c.s << ' ';
214                         else
215                                 c.s << '*';
216                 }
217
218                 // Then proceed with the remaining factors
219                 epvector::const_iterator it = seq.begin(), itend = seq.end();
220                 if (is_a<print_latex>(c)) {
221
222                         // Separate factors into those with negative numeric exponent
223                         // and all others
224                         exvector neg_powers, others;
225                         while (it != itend) {
226                                 GINAC_ASSERT(is_exactly_a<numeric>(it->coeff));
227                                 if (ex_to<numeric>(it->coeff).is_negative())
228                                         neg_powers.push_back(recombine_pair_to_ex(expair(it->rest, -(it->coeff))));
229                                 else
230                                         others.push_back(recombine_pair_to_ex(*it));
231                                 ++it;
232                         }
233
234                         if (!neg_powers.empty()) {
235
236                                 // Factors with negative exponent are printed as a fraction
237                                 c.s << "\\frac{";
238                                 mul(others).eval().print(c);
239                                 c.s << "}{";
240                                 mul(neg_powers).eval().print(c);
241                                 c.s << "}";
242
243                         } else {
244
245                                 // All other factors are printed in the ordinary way
246                                 exvector::const_iterator vit = others.begin(), vitend = others.end();
247                                 while (vit != vitend) {
248                                         c.s << ' ';
249                                         vit->print(c, precedence());
250                                         ++vit;
251                                 }
252                         }
253
254                 } else {
255
256                         bool first = true;
257                         while (it != itend) {
258                                 if (!first)
259                                         c.s << '*';
260                                 else
261                                         first = false;
262                                 recombine_pair_to_ex(*it).print(c, precedence());
263                                 ++it;
264                         }
265                 }
266
267                 if (precedence() <= level) {
268                         if (is_a<print_latex>(c))
269                                 c.s << ")}";
270                         else
271                                 c.s << ")";
272                 }
273         }
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         epvector *evaled_seqp = evalchildren(level);
382         if (evaled_seqp) {
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                 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         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         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 lst & ls, const lst & lr, unsigned options) const
562 {       
563         std::vector<bool> subsed(seq.size(), false);
564         exvector subsresult(seq.size());
565
566         lst::const_iterator its, itr;
567         for (its = ls.begin(), itr = lr.begin(); its != ls.end(); ++its, ++itr) {
568
569                 if (is_exactly_a<mul>(*its)) {
570
571                         int nummatches = std::numeric_limits<int>::max();
572                         std::vector<bool> currsubsed(seq.size(), false);
573                         bool succeed = true;
574                         lst repls;
575
576                         for (size_t j=0; j<its->nops(); j++) {
577                                 bool found=false;
578                                 for (size_t k=0; k<nops(); k++) {
579                                         if (currsubsed[k] || subsed[k])
580                                                 continue;
581                                         if (tryfactsubs(op(k), its->op(j), nummatches, repls)) {
582                                                 currsubsed[k] = true;
583                                                 found = true;
584                                                 break;
585                                         }
586                                 }
587                                 if (!found) {
588                                         succeed = false;
589                                         break;
590                                 }
591                         }
592                         if (!succeed)
593                                 continue;
594
595                         bool foundfirstsubsedfactor = false;
596                         for (size_t j=0; j<subsed.size(); j++) {
597                                 if (currsubsed[j]) {
598                                         if (foundfirstsubsedfactor)
599                                                 subsresult[j] = op(j);
600                                         else {
601                                                 foundfirstsubsedfactor = true;
602                                                 subsresult[j] = op(j) * power(itr->subs(ex(repls), subs_options::subs_no_pattern) / its->subs(ex(repls), subs_options::subs_no_pattern), nummatches);
603                                         }
604                                         subsed[j] = true;
605                                 }
606                         }
607
608                 } else {
609
610                         int nummatches = std::numeric_limits<int>::max();
611                         lst repls;
612
613                         for (size_t j=0; j<this->nops(); j++) {
614                                 if (!subsed[j] && tryfactsubs(op(j), *its, nummatches, repls)) {
615                                         subsed[j] = true;
616                                         subsresult[j] = op(j) * power(itr->subs(ex(repls), subs_options::subs_no_pattern) / its->subs(ex(repls), subs_options::subs_no_pattern), nummatches);
617                                 }
618                         }
619                 }
620         }
621
622         bool subsfound = false;
623         for (size_t i=0; i<subsed.size(); i++) {
624                 if (subsed[i]) {
625                         subsfound = true;
626                         break;
627                 }
628         }
629         if (!subsfound)
630                 return subs_one_level(ls, lr, options | subs_options::subs_algebraic);
631
632         exvector ev; ev.reserve(nops());
633         for (size_t i=0; i<nops(); i++) {
634                 if (subsed[i])
635                         ev.push_back(subsresult[i]);
636                 else
637                         ev.push_back(op(i));
638         }
639
640         return (new mul(ev))->setflag(status_flags::dynallocated);
641 }
642
643 // protected
644
645 /** Implementation of ex::diff() for a product.  It applies the product rule.
646  *  @see ex::diff */
647 ex mul::derivative(const symbol & s) const
648 {
649         size_t num = seq.size();
650         exvector addseq;
651         addseq.reserve(num);
652         
653         // D(a*b*c) = D(a)*b*c + a*D(b)*c + a*b*D(c)
654         epvector mulseq = seq;
655         epvector::const_iterator i = seq.begin(), end = seq.end();
656         epvector::iterator i2 = mulseq.begin();
657         while (i != end) {
658                 expair ep = split_ex_to_pair(power(i->rest, i->coeff - _ex1) *
659                                              i->rest.diff(s));
660                 ep.swap(*i2);
661                 addseq.push_back((new mul(mulseq, overall_coeff * i->coeff))->setflag(status_flags::dynallocated));
662                 ep.swap(*i2);
663                 ++i; ++i2;
664         }
665         return (new add(addseq))->setflag(status_flags::dynallocated);
666 }
667
668 int mul::compare_same_type(const basic & other) const
669 {
670         return inherited::compare_same_type(other);
671 }
672
673 unsigned mul::return_type() const
674 {
675         if (seq.empty()) {
676                 // mul without factors: should not happen, but commutes
677                 return return_types::commutative;
678         }
679         
680         bool all_commutative = true;
681         epvector::const_iterator noncommutative_element; // point to first found nc element
682         
683         epvector::const_iterator i = seq.begin(), end = seq.end();
684         while (i != end) {
685                 unsigned rt = i->rest.return_type();
686                 if (rt == return_types::noncommutative_composite)
687                         return rt; // one ncc -> mul also ncc
688                 if ((rt == return_types::noncommutative) && (all_commutative)) {
689                         // first nc element found, remember position
690                         noncommutative_element = i;
691                         all_commutative = false;
692                 }
693                 if ((rt == return_types::noncommutative) && (!all_commutative)) {
694                         // another nc element found, compare type_infos
695                         if (noncommutative_element->rest.return_type_tinfo() != i->rest.return_type_tinfo()) {
696                                 // diffent types -> mul is ncc
697                                 return return_types::noncommutative_composite;
698                         }
699                 }
700                 ++i;
701         }
702         // all factors checked
703         return all_commutative ? return_types::commutative : return_types::noncommutative;
704 }
705    
706 unsigned mul::return_type_tinfo() const
707 {
708         if (seq.empty())
709                 return tinfo_key;  // mul without factors: should not happen
710         
711         // return type_info of first noncommutative element
712         epvector::const_iterator i = seq.begin(), end = seq.end();
713         while (i != end) {
714                 if (i->rest.return_type() == return_types::noncommutative)
715                         return i->rest.return_type_tinfo();
716                 ++i;
717         }
718         // no noncommutative element found, should not happen
719         return tinfo_key;
720 }
721
722 ex mul::thisexpairseq(const epvector & v, const ex & oc) const
723 {
724         return (new mul(v, oc))->setflag(status_flags::dynallocated);
725 }
726
727 ex mul::thisexpairseq(epvector * vp, const ex & oc) const
728 {
729         return (new mul(vp, oc))->setflag(status_flags::dynallocated);
730 }
731
732 expair mul::split_ex_to_pair(const ex & e) const
733 {
734         if (is_exactly_a<power>(e)) {
735                 const power & powerref = ex_to<power>(e);
736                 if (is_exactly_a<numeric>(powerref.exponent))
737                         return expair(powerref.basis,powerref.exponent);
738         }
739         return expair(e,_ex1);
740 }
741         
742 expair mul::combine_ex_with_coeff_to_pair(const ex & e,
743                                           const ex & c) const
744 {
745         // to avoid duplication of power simplification rules,
746         // we create a temporary power object
747         // otherwise it would be hard to correctly evaluate
748         // expression like (4^(1/3))^(3/2)
749         if (c.is_equal(_ex1))
750                 return split_ex_to_pair(e);
751
752         return split_ex_to_pair(power(e,c));
753 }
754         
755 expair mul::combine_pair_with_coeff_to_pair(const expair & p,
756                                             const ex & c) const
757 {
758         // to avoid duplication of power simplification rules,
759         // we create a temporary power object
760         // otherwise it would be hard to correctly evaluate
761         // expression like (4^(1/3))^(3/2)
762         if (c.is_equal(_ex1))
763                 return p;
764
765         return split_ex_to_pair(power(recombine_pair_to_ex(p),c));
766 }
767         
768 ex mul::recombine_pair_to_ex(const expair & p) const
769 {
770         if (ex_to<numeric>(p.coeff).is_equal(_num1)) 
771                 return p.rest;
772         else
773                 return (new power(p.rest,p.coeff))->setflag(status_flags::dynallocated);
774 }
775
776 bool mul::expair_needs_further_processing(epp it)
777 {
778         if (is_exactly_a<mul>(it->rest) &&
779                 ex_to<numeric>(it->coeff).is_integer()) {
780                 // combined pair is product with integer power -> expand it
781                 *it = split_ex_to_pair(recombine_pair_to_ex(*it));
782                 return true;
783         }
784         if (is_exactly_a<numeric>(it->rest)) {
785                 expair ep = split_ex_to_pair(recombine_pair_to_ex(*it));
786                 if (!ep.is_equal(*it)) {
787                         // combined pair is a numeric power which can be simplified
788                         *it = ep;
789                         return true;
790                 }
791                 if (it->coeff.is_equal(_ex1)) {
792                         // combined pair has coeff 1 and must be moved to the end
793                         return true;
794                 }
795         }
796         return false;
797 }       
798
799 ex mul::default_overall_coeff() const
800 {
801         return _ex1;
802 }
803
804 void mul::combine_overall_coeff(const ex & c)
805 {
806         GINAC_ASSERT(is_exactly_a<numeric>(overall_coeff));
807         GINAC_ASSERT(is_exactly_a<numeric>(c));
808         overall_coeff = ex_to<numeric>(overall_coeff).mul_dyn(ex_to<numeric>(c));
809 }
810
811 void mul::combine_overall_coeff(const ex & c1, const ex & c2)
812 {
813         GINAC_ASSERT(is_exactly_a<numeric>(overall_coeff));
814         GINAC_ASSERT(is_exactly_a<numeric>(c1));
815         GINAC_ASSERT(is_exactly_a<numeric>(c2));
816         overall_coeff = ex_to<numeric>(overall_coeff).mul_dyn(ex_to<numeric>(c1).power(ex_to<numeric>(c2)));
817 }
818
819 bool mul::can_make_flat(const expair & p) const
820 {
821         GINAC_ASSERT(is_exactly_a<numeric>(p.coeff));
822         // this assertion will probably fail somewhere
823         // it would require a more careful make_flat, obeying the power laws
824         // probably should return true only if p.coeff is integer
825         return ex_to<numeric>(p.coeff).is_equal(_num1);
826 }
827
828 ex mul::expand(unsigned options) const
829 {
830         // First, expand the children
831         epvector * expanded_seqp = expandchildren(options);
832         const epvector & expanded_seq = (expanded_seqp == NULL) ? seq : *expanded_seqp;
833
834         // Now, look for all the factors that are sums and multiply each one out
835         // with the next one that is found while collecting the factors which are
836         // not sums
837         int number_of_adds = 0;
838         ex last_expanded = _ex1;
839         epvector non_adds;
840         non_adds.reserve(expanded_seq.size());
841         epvector::const_iterator cit = expanded_seq.begin(), last = expanded_seq.end();
842         while (cit != last) {
843                 if (is_exactly_a<add>(cit->rest) &&
844                         (cit->coeff.is_equal(_ex1))) {
845                         ++number_of_adds;
846                         if (is_exactly_a<add>(last_expanded)) {
847
848                                 // Expand a product of two sums, aggressive version.
849                                 // Caring for the overall coefficients in separate loops can
850                                 // sometimes give a performance gain of up to 15%!
851
852                                 const int sizedifference = ex_to<add>(last_expanded).seq.size()-ex_to<add>(cit->rest).seq.size();
853                                 // add2 is for the inner loop and should be the bigger of the two sums
854                                 // in the presence of asymptotically good sorting:
855                                 const add& add1 = (sizedifference<0 ? ex_to<add>(last_expanded) : ex_to<add>(cit->rest));
856                                 const add& add2 = (sizedifference<0 ? ex_to<add>(cit->rest) : ex_to<add>(last_expanded));
857                                 const epvector::const_iterator add1begin = add1.seq.begin();
858                                 const epvector::const_iterator add1end   = add1.seq.end();
859                                 const epvector::const_iterator add2begin = add2.seq.begin();
860                                 const epvector::const_iterator add2end   = add2.seq.end();
861                                 epvector distrseq;
862                                 distrseq.reserve(add1.seq.size()+add2.seq.size());
863                                 // Multiply add2 with the overall coefficient of add1 and append it to distrseq:
864                                 if (!add1.overall_coeff.is_zero()) {
865                                         if (add1.overall_coeff.is_equal(_ex1))
866                                                 distrseq.insert(distrseq.end(),add2begin,add2end);
867                                         else
868                                                 for (epvector::const_iterator i=add2begin; i!=add2end; ++i)
869                                                         distrseq.push_back(expair(i->rest, ex_to<numeric>(i->coeff).mul_dyn(ex_to<numeric>(add1.overall_coeff))));
870                                 }
871                                 // Multiply add1 with the overall coefficient of add2 and append it to distrseq:
872                                 if (!add2.overall_coeff.is_zero()) {
873                                         if (add2.overall_coeff.is_equal(_ex1))
874                                                 distrseq.insert(distrseq.end(),add1begin,add1end);
875                                         else
876                                                 for (epvector::const_iterator i=add1begin; i!=add1end; ++i)
877                                                         distrseq.push_back(expair(i->rest, ex_to<numeric>(i->coeff).mul_dyn(ex_to<numeric>(add2.overall_coeff))));
878                                 }
879                                 // Compute the new overall coefficient and put it together:
880                                 ex tmp_accu = (new add(distrseq, add1.overall_coeff*add2.overall_coeff))->setflag(status_flags::dynallocated);
881                                 // Multiply explicitly all non-numeric terms of add1 and add2:
882                                 for (epvector::const_iterator i1=add1begin; i1!=add1end; ++i1) {
883                                         // We really have to combine terms here in order to compactify
884                                         // the result.  Otherwise it would become waayy tooo bigg.
885                                         numeric oc;
886                                         distrseq.clear();
887                                         for (epvector::const_iterator i2=add2begin; i2!=add2end; ++i2) {
888                                                 // Don't push_back expairs which might have a rest that evaluates to a numeric,
889                                                 // since that would violate an invariant of expairseq:
890                                                 const ex rest = (new mul(i1->rest, i2->rest))->setflag(status_flags::dynallocated);
891                                                 if (is_exactly_a<numeric>(rest))
892                                                         oc += ex_to<numeric>(rest).mul(ex_to<numeric>(i1->coeff).mul(ex_to<numeric>(i2->coeff)));
893                                                 else
894                                                         distrseq.push_back(expair(rest, ex_to<numeric>(i1->coeff).mul_dyn(ex_to<numeric>(i2->coeff))));
895                                         }
896                                         tmp_accu += (new add(distrseq, oc))->setflag(status_flags::dynallocated);
897                                 }
898                                 last_expanded = tmp_accu;
899
900                         } else {
901                                 non_adds.push_back(split_ex_to_pair(last_expanded));
902                                 last_expanded = cit->rest;
903                         }
904                 } else {
905                         non_adds.push_back(*cit);
906                 }
907                 ++cit;
908         }
909         if (expanded_seqp)
910                 delete expanded_seqp;
911         
912         // Now the only remaining thing to do is to multiply the factors which
913         // were not sums into the "last_expanded" sum
914         if (is_exactly_a<add>(last_expanded)) {
915                 const add & finaladd = ex_to<add>(last_expanded);
916                 exvector distrseq;
917                 size_t n = finaladd.nops();
918                 distrseq.reserve(n);
919                 for (size_t i=0; i<n; ++i) {
920                         epvector factors = non_adds;
921                         factors.push_back(split_ex_to_pair(finaladd.op(i)));
922                         distrseq.push_back((new mul(factors, overall_coeff))->
923                                             setflag(status_flags::dynallocated | (options == 0 ? status_flags::expanded : 0)));
924                 }
925                 return ((new add(distrseq))->
926                         setflag(status_flags::dynallocated | (options == 0 ? status_flags::expanded : 0)));
927         }
928         non_adds.push_back(split_ex_to_pair(last_expanded));
929         return (new mul(non_adds, overall_coeff))->
930                 setflag(status_flags::dynallocated | (options == 0 ? status_flags::expanded : 0));
931 }
932
933   
934 //////////
935 // new virtual functions which can be overridden by derived classes
936 //////////
937
938 // none
939
940 //////////
941 // non-virtual functions in this class
942 //////////
943
944
945 /** Member-wise expand the expairs representing this sequence.  This must be
946  *  overridden from expairseq::expandchildren() and done iteratively in order
947  *  to allow for early cancallations and thus safe memory.
948  *
949  *  @see mul::expand()
950  *  @return pointer to epvector containing expanded representation or zero
951  *  pointer, if sequence is unchanged. */
952 epvector * mul::expandchildren(unsigned options) const
953 {
954         const epvector::const_iterator last = seq.end();
955         epvector::const_iterator cit = seq.begin();
956         while (cit!=last) {
957                 const ex & factor = recombine_pair_to_ex(*cit);
958                 const ex & expanded_factor = factor.expand(options);
959                 if (!are_ex_trivially_equal(factor,expanded_factor)) {
960                         
961                         // something changed, copy seq, eval and return it
962                         epvector *s = new epvector;
963                         s->reserve(seq.size());
964                         
965                         // copy parts of seq which are known not to have changed
966                         epvector::const_iterator cit2 = seq.begin();
967                         while (cit2!=cit) {
968                                 s->push_back(*cit2);
969                                 ++cit2;
970                         }
971                         // copy first changed element
972                         s->push_back(split_ex_to_pair(expanded_factor));
973                         ++cit2;
974                         // copy rest
975                         while (cit2!=last) {
976                                 s->push_back(split_ex_to_pair(recombine_pair_to_ex(*cit2).expand(options)));
977                                 ++cit2;
978                         }
979                         return s;
980                 }
981                 ++cit;
982         }
983         
984         return 0; // nothing has changed
985 }
986
987 } // namespace GiNaC