2c8456510a44d35201f5659dec50f27f32206e02
[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 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::subs_no_pattern) / it->first.subs(ex(repls), subs_options::subs_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::subs_no_pattern) / it->first.subs(ex(repls), subs_options::subs_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::subs_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(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 ex mul::expand(unsigned options) const
828 {
829         // First, expand the children
830         epvector * expanded_seqp = expandchildren(options);
831         const epvector & expanded_seq = (expanded_seqp == NULL) ? seq : *expanded_seqp;
832
833         // Now, look for all the factors that are sums and multiply each one out
834         // with the next one that is found while collecting the factors which are
835         // not sums
836         int number_of_adds = 0;
837         ex last_expanded = _ex1;
838         epvector non_adds;
839         non_adds.reserve(expanded_seq.size());
840         epvector::const_iterator cit = expanded_seq.begin(), last = expanded_seq.end();
841         while (cit != last) {
842                 if (is_exactly_a<add>(cit->rest) &&
843                         (cit->coeff.is_equal(_ex1))) {
844                         ++number_of_adds;
845                         if (is_exactly_a<add>(last_expanded)) {
846
847                                 // Expand a product of two sums, aggressive version.
848                                 // Caring for the overall coefficients in separate loops can
849                                 // sometimes give a performance gain of up to 15%!
850
851                                 const int sizedifference = ex_to<add>(last_expanded).seq.size()-ex_to<add>(cit->rest).seq.size();
852                                 // add2 is for the inner loop and should be the bigger of the two sums
853                                 // in the presence of asymptotically good sorting:
854                                 const add& add1 = (sizedifference<0 ? ex_to<add>(last_expanded) : ex_to<add>(cit->rest));
855                                 const add& add2 = (sizedifference<0 ? ex_to<add>(cit->rest) : ex_to<add>(last_expanded));
856                                 const epvector::const_iterator add1begin = add1.seq.begin();
857                                 const epvector::const_iterator add1end   = add1.seq.end();
858                                 const epvector::const_iterator add2begin = add2.seq.begin();
859                                 const epvector::const_iterator add2end   = add2.seq.end();
860                                 epvector distrseq;
861                                 distrseq.reserve(add1.seq.size()+add2.seq.size());
862                                 // Multiply add2 with the overall coefficient of add1 and append it to distrseq:
863                                 if (!add1.overall_coeff.is_zero()) {
864                                         if (add1.overall_coeff.is_equal(_ex1))
865                                                 distrseq.insert(distrseq.end(),add2begin,add2end);
866                                         else
867                                                 for (epvector::const_iterator i=add2begin; i!=add2end; ++i)
868                                                         distrseq.push_back(expair(i->rest, ex_to<numeric>(i->coeff).mul_dyn(ex_to<numeric>(add1.overall_coeff))));
869                                 }
870                                 // Multiply add1 with the overall coefficient of add2 and append it to distrseq:
871                                 if (!add2.overall_coeff.is_zero()) {
872                                         if (add2.overall_coeff.is_equal(_ex1))
873                                                 distrseq.insert(distrseq.end(),add1begin,add1end);
874                                         else
875                                                 for (epvector::const_iterator i=add1begin; i!=add1end; ++i)
876                                                         distrseq.push_back(expair(i->rest, ex_to<numeric>(i->coeff).mul_dyn(ex_to<numeric>(add2.overall_coeff))));
877                                 }
878                                 // Compute the new overall coefficient and put it together:
879                                 ex tmp_accu = (new add(distrseq, add1.overall_coeff*add2.overall_coeff))->setflag(status_flags::dynallocated);
880                                 // Multiply explicitly all non-numeric terms of add1 and add2:
881                                 for (epvector::const_iterator i1=add1begin; i1!=add1end; ++i1) {
882                                         // We really have to combine terms here in order to compactify
883                                         // the result.  Otherwise it would become waayy tooo bigg.
884                                         numeric oc;
885                                         distrseq.clear();
886                                         for (epvector::const_iterator i2=add2begin; i2!=add2end; ++i2) {
887                                                 // Don't push_back expairs which might have a rest that evaluates to a numeric,
888                                                 // since that would violate an invariant of expairseq:
889                                                 const ex rest = (new mul(i1->rest, i2->rest))->setflag(status_flags::dynallocated);
890                                                 if (is_exactly_a<numeric>(rest))
891                                                         oc += ex_to<numeric>(rest).mul(ex_to<numeric>(i1->coeff).mul(ex_to<numeric>(i2->coeff)));
892                                                 else
893                                                         distrseq.push_back(expair(rest, ex_to<numeric>(i1->coeff).mul_dyn(ex_to<numeric>(i2->coeff))));
894                                         }
895                                         tmp_accu += (new add(distrseq, oc))->setflag(status_flags::dynallocated);
896                                 }
897                                 last_expanded = tmp_accu;
898
899                         } else {
900                                 non_adds.push_back(split_ex_to_pair(last_expanded));
901                                 last_expanded = cit->rest;
902                         }
903                 } else {
904                         non_adds.push_back(*cit);
905                 }
906                 ++cit;
907         }
908         if (expanded_seqp)
909                 delete expanded_seqp;
910         
911         // Now the only remaining thing to do is to multiply the factors which
912         // were not sums into the "last_expanded" sum
913         if (is_exactly_a<add>(last_expanded)) {
914                 const add & finaladd = ex_to<add>(last_expanded);
915                 exvector distrseq;
916                 size_t n = finaladd.nops();
917                 distrseq.reserve(n);
918                 for (size_t i=0; i<n; ++i) {
919                         epvector factors = non_adds;
920                         factors.push_back(split_ex_to_pair(finaladd.op(i)));
921                         distrseq.push_back((new mul(factors, overall_coeff))->
922                                             setflag(status_flags::dynallocated | (options == 0 ? status_flags::expanded : 0)));
923                 }
924                 return ((new add(distrseq))->
925                         setflag(status_flags::dynallocated | (options == 0 ? status_flags::expanded : 0)));
926         }
927         non_adds.push_back(split_ex_to_pair(last_expanded));
928         return (new mul(non_adds, overall_coeff))->
929                 setflag(status_flags::dynallocated | (options == 0 ? status_flags::expanded : 0));
930 }
931
932   
933 //////////
934 // new virtual functions which can be overridden by derived classes
935 //////////
936
937 // none
938
939 //////////
940 // non-virtual functions in this class
941 //////////
942
943
944 /** Member-wise expand the expairs representing this sequence.  This must be
945  *  overridden from expairseq::expandchildren() and done iteratively in order
946  *  to allow for early cancallations and thus safe memory.
947  *
948  *  @see mul::expand()
949  *  @return pointer to epvector containing expanded representation or zero
950  *  pointer, if sequence is unchanged. */
951 epvector * mul::expandchildren(unsigned options) const
952 {
953         const epvector::const_iterator last = seq.end();
954         epvector::const_iterator cit = seq.begin();
955         while (cit!=last) {
956                 const ex & factor = recombine_pair_to_ex(*cit);
957                 const ex & expanded_factor = factor.expand(options);
958                 if (!are_ex_trivially_equal(factor,expanded_factor)) {
959                         
960                         // something changed, copy seq, eval and return it
961                         epvector *s = new epvector;
962                         s->reserve(seq.size());
963                         
964                         // copy parts of seq which are known not to have changed
965                         epvector::const_iterator cit2 = seq.begin();
966                         while (cit2!=cit) {
967                                 s->push_back(*cit2);
968                                 ++cit2;
969                         }
970                         // copy first changed element
971                         s->push_back(split_ex_to_pair(expanded_factor));
972                         ++cit2;
973                         // copy rest
974                         while (cit2!=last) {
975                                 s->push_back(split_ex_to_pair(recombine_pair_to_ex(*cit2).expand(options)));
976                                 ++cit2;
977                         }
978                         return s;
979                 }
980                 ++cit;
981         }
982         
983         return 0; // nothing has changed
984 }
985
986 } // namespace GiNaC