]> www.ginac.de Git - ginac.git/blob - ginac/mul.cpp
- New tinfo mechanism
[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-2006 Johannes Gutenberg University Mainz, Germany
7  *
8  *  This program is free software; you can redistribute it and/or modify
9  *  it under the terms of the GNU General Public License as published by
10  *  the Free Software Foundation; either version 2 of the License, or
11  *  (at your option) any later version.
12  *
13  *  This program is distributed in the hope that it will be useful,
14  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
15  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  *  GNU General Public License for more details.
17  *
18  *  You should have received a copy of the GNU General Public License
19  *  along with this program; if not, write to the Free Software
20  *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
21  */
22
23 #include <iostream>
24 #include <vector>
25 #include <stdexcept>
26 #include <limits>
27
28 #include "mul.h"
29 #include "add.h"
30 #include "color.h"
31 #include "clifford.h"
32 #include "power.h"
33 #include "operators.h"
34 #include "matrix.h"
35 #include "indexed.h"
36 #include "lst.h"
37 #include "archive.h"
38 #include "utils.h"
39
40 namespace GiNaC {
41
42 GINAC_IMPLEMENT_REGISTERED_CLASS_OPT(mul, expairseq,
43   print_func<print_context>(&mul::do_print).
44   print_func<print_latex>(&mul::do_print_latex).
45   print_func<print_csrc>(&mul::do_print_csrc).
46   print_func<print_tree>(&mul::do_print_tree).
47   print_func<print_python_repr>(&mul::do_print_python_repr))
48
49
50 //////////
51 // default constructor
52 //////////
53
54 mul::mul()
55 {
56         tinfo_key = &mul::tinfo_static;
57 }
58
59 //////////
60 // other constructors
61 //////////
62
63 // public
64
65 mul::mul(const ex & lh, const ex & rh)
66 {
67         tinfo_key = &mul::tinfo_static;
68         overall_coeff = _ex1;
69         construct_from_2_ex(lh,rh);
70         GINAC_ASSERT(is_canonical());
71 }
72
73 mul::mul(const exvector & v)
74 {
75         tinfo_key = &mul::tinfo_static;
76         overall_coeff = _ex1;
77         construct_from_exvector(v);
78         GINAC_ASSERT(is_canonical());
79 }
80
81 mul::mul(const epvector & v)
82 {
83         tinfo_key = &mul::tinfo_static;
84         overall_coeff = _ex1;
85         construct_from_epvector(v);
86         GINAC_ASSERT(is_canonical());
87 }
88
89 mul::mul(const epvector & v, const ex & oc)
90 {
91         tinfo_key = &mul::tinfo_static;
92         overall_coeff = oc;
93         construct_from_epvector(v);
94         GINAC_ASSERT(is_canonical());
95 }
96
97 mul::mul(std::auto_ptr<epvector> vp, const ex & oc)
98 {
99         tinfo_key = &mul::tinfo_static;
100         GINAC_ASSERT(vp.get()!=0);
101         overall_coeff = oc;
102         construct_from_epvector(*vp);
103         GINAC_ASSERT(is_canonical());
104 }
105
106 mul::mul(const ex & lh, const ex & mh, const ex & rh)
107 {
108         tinfo_key = &mul::tinfo_static;
109         exvector factors;
110         factors.reserve(3);
111         factors.push_back(lh);
112         factors.push_back(mh);
113         factors.push_back(rh);
114         overall_coeff = _ex1;
115         construct_from_exvector(factors);
116         GINAC_ASSERT(is_canonical());
117 }
118
119 //////////
120 // archiving
121 //////////
122
123 DEFAULT_ARCHIVING(mul)
124
125 //////////
126 // functions overriding virtual functions from base classes
127 //////////
128
129 void mul::print_overall_coeff(const print_context & c, const char *mul_sym) const
130 {
131         const numeric &coeff = ex_to<numeric>(overall_coeff);
132         if (coeff.csgn() == -1)
133                 c.s << '-';
134         if (!coeff.is_equal(*_num1_p) &&
135                 !coeff.is_equal(*_num_1_p)) {
136                 if (coeff.is_rational()) {
137                         if (coeff.is_negative())
138                                 (-coeff).print(c);
139                         else
140                                 coeff.print(c);
141                 } else {
142                         if (coeff.csgn() == -1)
143                                 (-coeff).print(c, precedence());
144                         else
145                                 coeff.print(c, precedence());
146                 }
147                 c.s << mul_sym;
148         }
149 }
150
151 void mul::do_print(const print_context & c, unsigned level) const
152 {
153         if (precedence() <= level)
154                 c.s << '(';
155
156         print_overall_coeff(c, "*");
157
158         epvector::const_iterator it = seq.begin(), itend = seq.end();
159         bool first = true;
160         while (it != itend) {
161                 if (!first)
162                         c.s << '*';
163                 else
164                         first = false;
165                 recombine_pair_to_ex(*it).print(c, precedence());
166                 ++it;
167         }
168
169         if (precedence() <= level)
170                 c.s << ')';
171 }
172
173 void mul::do_print_latex(const print_latex & c, unsigned level) const
174 {
175         if (precedence() <= level)
176                 c.s << "{(";
177
178         print_overall_coeff(c, " ");
179
180         // Separate factors into those with negative numeric exponent
181         // and all others
182         epvector::const_iterator it = seq.begin(), itend = seq.end();
183         exvector neg_powers, others;
184         while (it != itend) {
185                 GINAC_ASSERT(is_exactly_a<numeric>(it->coeff));
186                 if (ex_to<numeric>(it->coeff).is_negative())
187                         neg_powers.push_back(recombine_pair_to_ex(expair(it->rest, -(it->coeff))));
188                 else
189                         others.push_back(recombine_pair_to_ex(*it));
190                 ++it;
191         }
192
193         if (!neg_powers.empty()) {
194
195                 // Factors with negative exponent are printed as a fraction
196                 c.s << "\\frac{";
197                 mul(others).eval().print(c);
198                 c.s << "}{";
199                 mul(neg_powers).eval().print(c);
200                 c.s << "}";
201
202         } else {
203
204                 // All other factors are printed in the ordinary way
205                 exvector::const_iterator vit = others.begin(), vitend = others.end();
206                 while (vit != vitend) {
207                         c.s << ' ';
208                         vit->print(c, precedence());
209                         ++vit;
210                 }
211         }
212
213         if (precedence() <= level)
214                 c.s << ")}";
215 }
216
217 void mul::do_print_csrc(const print_csrc & c, unsigned level) const
218 {
219         if (precedence() <= level)
220                 c.s << "(";
221
222         if (!overall_coeff.is_equal(_ex1)) {
223                 overall_coeff.print(c, precedence());
224                 c.s << "*";
225         }
226
227         // Print arguments, separated by "*" or "/"
228         epvector::const_iterator it = seq.begin(), itend = seq.end();
229         while (it != itend) {
230
231                 // If the first argument is a negative integer power, it gets printed as "1.0/<expr>"
232                 bool needclosingparenthesis = false;
233                 if (it == seq.begin() && it->coeff.info(info_flags::negint)) {
234                         if (is_a<print_csrc_cl_N>(c)) {
235                                 c.s << "recip(";
236                                 needclosingparenthesis = true;
237                         } else
238                                 c.s << "1.0/";
239                 }
240
241                 // If the exponent is 1 or -1, it is left out
242                 if (it->coeff.is_equal(_ex1) || it->coeff.is_equal(_ex_1))
243                         it->rest.print(c, precedence());
244                 else if (it->coeff.info(info_flags::negint))
245                         // Outer parens around ex needed for broken GCC parser:
246                         (ex(power(it->rest, -ex_to<numeric>(it->coeff)))).print(c, level);
247                 else
248                         // Outer parens around ex needed for broken GCC parser:
249                         (ex(power(it->rest, ex_to<numeric>(it->coeff)))).print(c, level);
250
251                 if (needclosingparenthesis)
252                         c.s << ")";
253
254                 // Separator is "/" for negative integer powers, "*" otherwise
255                 ++it;
256                 if (it != itend) {
257                         if (it->coeff.info(info_flags::negint))
258                                 c.s << "/";
259                         else
260                                 c.s << "*";
261                 }
262         }
263
264         if (precedence() <= level)
265                 c.s << ")";
266 }
267
268 void mul::do_print_python_repr(const print_python_repr & c, unsigned level) const
269 {
270         c.s << class_name() << '(';
271         op(0).print(c);
272         for (size_t i=1; i<nops(); ++i) {
273                 c.s << ',';
274                 op(i).print(c);
275         }
276         c.s << ')';
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         std::auto_ptr<epvector> evaled_seqp = evalchildren(level);
385         if (evaled_seqp.get()) {
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_p)) {
428                 // *(+(x,y,...);c) -> +(*(x,c),*(y,c),...) (c numeric(), no powers of +())
429                 const add & addref = ex_to<add>((*seq.begin()).rest);
430                 std::auto_ptr<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         std::auto_ptr<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() 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         std::auto_ptr<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 /** Checks wheter e matches to the pattern pat and the (possibly to be updated
565   * list of replacements repls. This matching is in the sense of algebraic
566   * substitutions. Matching starts with pat.op(factor) of the pattern because
567   * the factors before this one have already been matched. The (possibly
568   * updated) number of matches is in nummatches. subsed[i] is true for factors
569   * that already have been replaced by previous substitutions and matched[i]
570   * is true for factors that have been matched by the current match.
571   */
572 bool algebraic_match_mul_with_mul(const mul &e, const ex &pat, lst &repls,
573                 int factor, int &nummatches, const std::vector<bool> &subsed,
574                 std::vector<bool> &matched)
575 {
576         if (factor == pat.nops())
577                 return true;
578
579         for (size_t i=0; i<e.nops(); ++i) {
580                 if(subsed[i] || matched[i])
581                         continue;
582                 lst newrepls = repls;
583                 int newnummatches = nummatches;
584                 if (tryfactsubs(e.op(i), pat.op(factor), newnummatches, newrepls)) {
585                         matched[i] = true;
586                         if (algebraic_match_mul_with_mul(e, pat, newrepls, factor+1,
587                                         newnummatches, subsed, matched)) {
588                                 repls = newrepls;
589                                 nummatches = newnummatches;
590                                 return true;
591                         }
592                         else
593                                 matched[i] = false;
594                 }
595         }
596
597         return false;
598 }
599
600 ex mul::algebraic_subs_mul(const exmap & m, unsigned options) const
601 {       
602         std::vector<bool> subsed(seq.size(), false);
603         exvector subsresult(seq.size());
604
605         for (exmap::const_iterator it = m.begin(); it != m.end(); ++it) {
606
607                 if (is_exactly_a<mul>(it->first)) {
608 retry1:
609                         int nummatches = std::numeric_limits<int>::max();
610                         std::vector<bool> currsubsed(seq.size(), false);
611                         bool succeed = true;
612                         lst repls;
613                         
614                         if(!algebraic_match_mul_with_mul(*this, it->first, repls, 0, nummatches, subsed, currsubsed))
615                                 continue;
616
617                         bool foundfirstsubsedfactor = false;
618                         for (size_t j=0; j<subsed.size(); j++) {
619                                 if (currsubsed[j]) {
620                                         if (foundfirstsubsedfactor)
621                                                 subsresult[j] = op(j);
622                                         else {
623                                                 foundfirstsubsedfactor = true;
624                                                 subsresult[j] = op(j) * power(it->second.subs(ex(repls), subs_options::no_pattern) / it->first.subs(ex(repls), subs_options::no_pattern), nummatches);
625                                         }
626                                         subsed[j] = true;
627                                 }
628                         }
629                         goto retry1;
630
631                 } else {
632 retry2:
633                         int nummatches = std::numeric_limits<int>::max();
634                         lst repls;
635
636                         for (size_t j=0; j<this->nops(); j++) {
637                                 if (!subsed[j] && tryfactsubs(op(j), it->first, nummatches, repls)) {
638                                         subsed[j] = true;
639                                         subsresult[j] = op(j) * power(it->second.subs(ex(repls), subs_options::no_pattern) / it->first.subs(ex(repls), subs_options::no_pattern), nummatches);
640                                         goto retry2;
641                                 }
642                         }
643                 }
644         }
645
646         bool subsfound = false;
647         for (size_t i=0; i<subsed.size(); i++) {
648                 if (subsed[i]) {
649                         subsfound = true;
650                         break;
651                 }
652         }
653         if (!subsfound)
654                 return subs_one_level(m, options | subs_options::algebraic);
655
656         exvector ev; ev.reserve(nops());
657         for (size_t i=0; i<nops(); i++) {
658                 if (subsed[i])
659                         ev.push_back(subsresult[i]);
660                 else
661                         ev.push_back(op(i));
662         }
663
664         return (new mul(ev))->setflag(status_flags::dynallocated);
665 }
666
667 // protected
668
669 /** Implementation of ex::diff() for a product.  It applies the product rule.
670  *  @see ex::diff */
671 ex mul::derivative(const symbol & s) const
672 {
673         size_t num = seq.size();
674         exvector addseq;
675         addseq.reserve(num);
676         
677         // D(a*b*c) = D(a)*b*c + a*D(b)*c + a*b*D(c)
678         epvector mulseq = seq;
679         epvector::const_iterator i = seq.begin(), end = seq.end();
680         epvector::iterator i2 = mulseq.begin();
681         while (i != end) {
682                 expair ep = split_ex_to_pair(power(i->rest, i->coeff - _ex1) *
683                                              i->rest.diff(s));
684                 ep.swap(*i2);
685                 addseq.push_back((new mul(mulseq, overall_coeff * i->coeff))->setflag(status_flags::dynallocated));
686                 ep.swap(*i2);
687                 ++i; ++i2;
688         }
689         return (new add(addseq))->setflag(status_flags::dynallocated);
690 }
691
692 int mul::compare_same_type(const basic & other) const
693 {
694         return inherited::compare_same_type(other);
695 }
696
697 unsigned mul::return_type() const
698 {
699         if (seq.empty()) {
700                 // mul without factors: should not happen, but commutates
701                 return return_types::commutative;
702         }
703         
704         bool all_commutative = true;
705         epvector::const_iterator noncommutative_element; // point to first found nc element
706         
707         epvector::const_iterator i = seq.begin(), end = seq.end();
708         while (i != end) {
709                 unsigned rt = i->rest.return_type();
710                 if (rt == return_types::noncommutative_composite)
711                         return rt; // one ncc -> mul also ncc
712                 if ((rt == return_types::noncommutative) && (all_commutative)) {
713                         // first nc element found, remember position
714                         noncommutative_element = i;
715                         all_commutative = false;
716                 }
717                 if ((rt == return_types::noncommutative) && (!all_commutative)) {
718                         // another nc element found, compare type_infos
719                         if (noncommutative_element->rest.return_type_tinfo()->tinfo() == &clifford::tinfo_static) {
720                                 if (i->rest.return_type_tinfo()->tinfo() != &clifford::tinfo_static ||
721                                     ((clifford*)(noncommutative_element->rest.return_type_tinfo()))->get_representation_label() !=
722                                     ((clifford*)(i->rest.return_type_tinfo()))->get_representation_label()) {
723                                         // diffent types -> mul is ncc
724                                         return return_types::noncommutative_composite;
725                                 }
726                         } else if (noncommutative_element->rest.return_type_tinfo()->tinfo() == &color::tinfo_static) {
727                                 if (i->rest.return_type_tinfo()->tinfo() != &color::tinfo_static ||
728                                     ((color*)(noncommutative_element->rest.return_type_tinfo()))->get_representation_label() !=
729                                     ((color*)(i->rest.return_type_tinfo()))->get_representation_label()) {
730                                         // diffent types -> mul is ncc
731                                         return return_types::noncommutative_composite;
732                                 }
733                         } else if (noncommutative_element->rest.return_type_tinfo()->tinfo() != i->rest.return_type_tinfo()->tinfo()) {
734                                         return return_types::noncommutative_composite;
735                         }
736                 }
737                 ++i;
738         }
739         // all factors checked
740         return all_commutative ? return_types::commutative : return_types::noncommutative;
741 }
742    
743 const basic* mul::return_type_tinfo() const
744 {
745         if (seq.empty())
746                 return this;  // mul without factors: should not happen
747         
748         // return type_info of first noncommutative element
749         epvector::const_iterator i = seq.begin(), end = seq.end();
750         while (i != end) {
751                 if (i->rest.return_type() == return_types::noncommutative)
752                         return i->rest.return_type_tinfo();
753                 ++i;
754         }
755         // no noncommutative element found, should not happen
756         return this;
757 }
758
759 ex mul::thisexpairseq(const epvector & v, const ex & oc) const
760 {
761         return (new mul(v, oc))->setflag(status_flags::dynallocated);
762 }
763
764 ex mul::thisexpairseq(std::auto_ptr<epvector> vp, const ex & oc) const
765 {
766         return (new mul(vp, oc))->setflag(status_flags::dynallocated);
767 }
768
769 expair mul::split_ex_to_pair(const ex & e) const
770 {
771         if (is_exactly_a<power>(e)) {
772                 const power & powerref = ex_to<power>(e);
773                 if (is_exactly_a<numeric>(powerref.exponent))
774                         return expair(powerref.basis,powerref.exponent);
775         }
776         return expair(e,_ex1);
777 }
778         
779 expair mul::combine_ex_with_coeff_to_pair(const ex & e,
780                                           const ex & c) const
781 {
782         // to avoid duplication of power simplification rules,
783         // we create a temporary power object
784         // otherwise it would be hard to correctly evaluate
785         // expression like (4^(1/3))^(3/2)
786         if (c.is_equal(_ex1))
787                 return split_ex_to_pair(e);
788
789         return split_ex_to_pair(power(e,c));
790 }
791         
792 expair mul::combine_pair_with_coeff_to_pair(const expair & p,
793                                             const ex & c) const
794 {
795         // to avoid duplication of power simplification rules,
796         // we create a temporary power object
797         // otherwise it would be hard to correctly evaluate
798         // expression like (4^(1/3))^(3/2)
799         if (c.is_equal(_ex1))
800                 return p;
801
802         return split_ex_to_pair(power(recombine_pair_to_ex(p),c));
803 }
804         
805 ex mul::recombine_pair_to_ex(const expair & p) const
806 {
807         if (ex_to<numeric>(p.coeff).is_equal(*_num1_p)) 
808                 return p.rest;
809         else
810                 return (new power(p.rest,p.coeff))->setflag(status_flags::dynallocated);
811 }
812
813 bool mul::expair_needs_further_processing(epp it)
814 {
815         if (is_exactly_a<mul>(it->rest) &&
816                 ex_to<numeric>(it->coeff).is_integer()) {
817                 // combined pair is product with integer power -> expand it
818                 *it = split_ex_to_pair(recombine_pair_to_ex(*it));
819                 return true;
820         }
821         if (is_exactly_a<numeric>(it->rest)) {
822                 expair ep = split_ex_to_pair(recombine_pair_to_ex(*it));
823                 if (!ep.is_equal(*it)) {
824                         // combined pair is a numeric power which can be simplified
825                         *it = ep;
826                         return true;
827                 }
828                 if (it->coeff.is_equal(_ex1)) {
829                         // combined pair has coeff 1 and must be moved to the end
830                         return true;
831                 }
832         }
833         return false;
834 }       
835
836 ex mul::default_overall_coeff() const
837 {
838         return _ex1;
839 }
840
841 void mul::combine_overall_coeff(const ex & c)
842 {
843         GINAC_ASSERT(is_exactly_a<numeric>(overall_coeff));
844         GINAC_ASSERT(is_exactly_a<numeric>(c));
845         overall_coeff = ex_to<numeric>(overall_coeff).mul_dyn(ex_to<numeric>(c));
846 }
847
848 void mul::combine_overall_coeff(const ex & c1, const ex & c2)
849 {
850         GINAC_ASSERT(is_exactly_a<numeric>(overall_coeff));
851         GINAC_ASSERT(is_exactly_a<numeric>(c1));
852         GINAC_ASSERT(is_exactly_a<numeric>(c2));
853         overall_coeff = ex_to<numeric>(overall_coeff).mul_dyn(ex_to<numeric>(c1).power(ex_to<numeric>(c2)));
854 }
855
856 bool mul::can_make_flat(const expair & p) const
857 {
858         GINAC_ASSERT(is_exactly_a<numeric>(p.coeff));
859         // this assertion will probably fail somewhere
860         // it would require a more careful make_flat, obeying the power laws
861         // probably should return true only if p.coeff is integer
862         return ex_to<numeric>(p.coeff).is_equal(*_num1_p);
863 }
864
865 bool mul::can_be_further_expanded(const ex & e)
866 {
867         if (is_exactly_a<mul>(e)) {
868                 for (epvector::const_iterator cit = ex_to<mul>(e).seq.begin(); cit != ex_to<mul>(e).seq.end(); ++cit) {
869                         if (is_exactly_a<add>(cit->rest) && cit->coeff.info(info_flags::posint))
870                                 return true;
871                 }
872         } else if (is_exactly_a<power>(e)) {
873                 if (is_exactly_a<add>(e.op(0)) && e.op(1).info(info_flags::posint))
874                         return true;
875         }
876         return false;
877 }
878
879 ex mul::expand(unsigned options) const
880 {
881         // First, expand the children
882         std::auto_ptr<epvector> expanded_seqp = expandchildren(options);
883         const epvector & expanded_seq = (expanded_seqp.get() ? *expanded_seqp : seq);
884
885         // Now, look for all the factors that are sums and multiply each one out
886         // with the next one that is found while collecting the factors which are
887         // not sums
888         ex last_expanded = _ex1;
889
890         epvector non_adds;
891         non_adds.reserve(expanded_seq.size());
892
893         for (epvector::const_iterator cit = expanded_seq.begin(); cit != expanded_seq.end(); ++cit) {
894                 if (is_exactly_a<add>(cit->rest) &&
895                         (cit->coeff.is_equal(_ex1))) {
896                         if (is_exactly_a<add>(last_expanded)) {
897
898                                 // Expand a product of two sums, aggressive version.
899                                 // Caring for the overall coefficients in separate loops can
900                                 // sometimes give a performance gain of up to 15%!
901
902                                 const int sizedifference = ex_to<add>(last_expanded).seq.size()-ex_to<add>(cit->rest).seq.size();
903                                 // add2 is for the inner loop and should be the bigger of the two sums
904                                 // in the presence of asymptotically good sorting:
905                                 const add& add1 = (sizedifference<0 ? ex_to<add>(last_expanded) : ex_to<add>(cit->rest));
906                                 const add& add2 = (sizedifference<0 ? ex_to<add>(cit->rest) : ex_to<add>(last_expanded));
907                                 const epvector::const_iterator add1begin = add1.seq.begin();
908                                 const epvector::const_iterator add1end   = add1.seq.end();
909                                 const epvector::const_iterator add2begin = add2.seq.begin();
910                                 const epvector::const_iterator add2end   = add2.seq.end();
911                                 epvector distrseq;
912                                 distrseq.reserve(add1.seq.size()+add2.seq.size());
913
914                                 // Multiply add2 with the overall coefficient of add1 and append it to distrseq:
915                                 if (!add1.overall_coeff.is_zero()) {
916                                         if (add1.overall_coeff.is_equal(_ex1))
917                                                 distrseq.insert(distrseq.end(),add2begin,add2end);
918                                         else
919                                                 for (epvector::const_iterator i=add2begin; i!=add2end; ++i)
920                                                         distrseq.push_back(expair(i->rest, ex_to<numeric>(i->coeff).mul_dyn(ex_to<numeric>(add1.overall_coeff))));
921                                 }
922
923                                 // Multiply add1 with the overall coefficient of add2 and append it to distrseq:
924                                 if (!add2.overall_coeff.is_zero()) {
925                                         if (add2.overall_coeff.is_equal(_ex1))
926                                                 distrseq.insert(distrseq.end(),add1begin,add1end);
927                                         else
928                                                 for (epvector::const_iterator i=add1begin; i!=add1end; ++i)
929                                                         distrseq.push_back(expair(i->rest, ex_to<numeric>(i->coeff).mul_dyn(ex_to<numeric>(add2.overall_coeff))));
930                                 }
931
932                                 // Compute the new overall coefficient and put it together:
933                                 ex tmp_accu = (new add(distrseq, add1.overall_coeff*add2.overall_coeff))->setflag(status_flags::dynallocated);
934
935                                 exvector add1_dummy_indices, add2_dummy_indices, add_indices;
936
937                                 for (epvector::const_iterator i=add1begin; i!=add1end; ++i) {
938                                         add_indices = get_all_dummy_indices(i->rest);
939                                         add1_dummy_indices.insert(add1_dummy_indices.end(), add_indices.begin(), add_indices.end());
940                                 }
941                                 for (epvector::const_iterator i=add2begin; i!=add2end; ++i) {
942                                         add_indices = get_all_dummy_indices(i->rest);
943                                         add2_dummy_indices.insert(add2_dummy_indices.end(), add_indices.begin(), add_indices.end());
944                                 }
945
946                                 sort(add1_dummy_indices.begin(), add1_dummy_indices.end(), ex_is_less());
947                                 sort(add2_dummy_indices.begin(), add2_dummy_indices.end(), ex_is_less());
948                                 lst dummy_subs = rename_dummy_indices_uniquely(add1_dummy_indices, add2_dummy_indices);
949
950                                 // Multiply explicitly all non-numeric terms of add1 and add2:
951                                 for (epvector::const_iterator i2=add2begin; i2!=add2end; ++i2) {
952                                         // We really have to combine terms here in order to compactify
953                                         // the result.  Otherwise it would become waayy tooo bigg.
954                                         numeric oc;
955                                         distrseq.clear();
956                                         ex i2_new = (dummy_subs.op(0).nops()>0? 
957                                                                  i2->rest.subs((lst)dummy_subs.op(0), (lst)dummy_subs.op(1), subs_options::no_pattern) : i2->rest);
958                                         for (epvector::const_iterator i1=add1begin; i1!=add1end; ++i1) {
959                                                 // Don't push_back expairs which might have a rest that evaluates to a numeric,
960                                                 // since that would violate an invariant of expairseq:
961                                                 const ex rest = (new mul(i1->rest, i2_new))->setflag(status_flags::dynallocated);
962                                                 if (is_exactly_a<numeric>(rest)) {
963                                                         oc += ex_to<numeric>(rest).mul(ex_to<numeric>(i1->coeff).mul(ex_to<numeric>(i2->coeff)));
964                                                 } else {
965                                                         distrseq.push_back(expair(rest, ex_to<numeric>(i1->coeff).mul_dyn(ex_to<numeric>(i2->coeff))));
966                                                 }
967                                         }
968                                         tmp_accu += (new add(distrseq, oc))->setflag(status_flags::dynallocated);
969                                 }
970                                 last_expanded = tmp_accu;
971
972                         } else {
973                                 if (!last_expanded.is_equal(_ex1))
974                                         non_adds.push_back(split_ex_to_pair(last_expanded));
975                                 last_expanded = cit->rest;
976                         }
977
978                 } else {
979                         non_adds.push_back(*cit);
980                 }
981         }
982
983         // Now the only remaining thing to do is to multiply the factors which
984         // were not sums into the "last_expanded" sum
985         if (is_exactly_a<add>(last_expanded)) {
986                 size_t n = last_expanded.nops();
987                 exvector distrseq;
988                 distrseq.reserve(n);
989                 exvector va = get_all_dummy_indices(mul(non_adds));
990                 sort(va.begin(), va.end(), ex_is_less());
991
992                 for (size_t i=0; i<n; ++i) {
993                         epvector factors = non_adds;
994                         factors.push_back(split_ex_to_pair(rename_dummy_indices_uniquely(va, last_expanded.op(i))));
995                         ex term = (new mul(factors, overall_coeff))->setflag(status_flags::dynallocated);
996                         if (can_be_further_expanded(term)) {
997                                 distrseq.push_back(term.expand());
998                         } else {
999                                 if (options == 0)
1000                                         ex_to<basic>(term).setflag(status_flags::expanded);
1001                                 distrseq.push_back(term);
1002                         }
1003                 }
1004
1005                 return ((new add(distrseq))->
1006                         setflag(status_flags::dynallocated | (options == 0 ? status_flags::expanded : 0)));
1007         }
1008
1009         non_adds.push_back(split_ex_to_pair(last_expanded));
1010         ex result = (new mul(non_adds, overall_coeff))->setflag(status_flags::dynallocated);
1011         if (can_be_further_expanded(result)) {
1012                 return result.expand();
1013         } else {
1014                 if (options == 0)
1015                         ex_to<basic>(result).setflag(status_flags::expanded);
1016                 return result;
1017         }
1018 }
1019
1020   
1021 //////////
1022 // new virtual functions which can be overridden by derived classes
1023 //////////
1024
1025 // none
1026
1027 //////////
1028 // non-virtual functions in this class
1029 //////////
1030
1031
1032 /** Member-wise expand the expairs representing this sequence.  This must be
1033  *  overridden from expairseq::expandchildren() and done iteratively in order
1034  *  to allow for early cancallations and thus safe memory.
1035  *
1036  *  @see mul::expand()
1037  *  @return pointer to epvector containing expanded representation or zero
1038  *  pointer, if sequence is unchanged. */
1039 std::auto_ptr<epvector> mul::expandchildren(unsigned options) const
1040 {
1041         const epvector::const_iterator last = seq.end();
1042         epvector::const_iterator cit = seq.begin();
1043         while (cit!=last) {
1044                 const ex & factor = recombine_pair_to_ex(*cit);
1045                 const ex & expanded_factor = factor.expand(options);
1046                 if (!are_ex_trivially_equal(factor,expanded_factor)) {
1047                         
1048                         // something changed, copy seq, eval and return it
1049                         std::auto_ptr<epvector> s(new epvector);
1050                         s->reserve(seq.size());
1051                         
1052                         // copy parts of seq which are known not to have changed
1053                         epvector::const_iterator cit2 = seq.begin();
1054                         while (cit2!=cit) {
1055                                 s->push_back(*cit2);
1056                                 ++cit2;
1057                         }
1058
1059                         // copy first changed element
1060                         s->push_back(split_ex_to_pair(expanded_factor));
1061                         ++cit2;
1062
1063                         // copy rest
1064                         while (cit2!=last) {
1065                                 s->push_back(split_ex_to_pair(recombine_pair_to_ex(*cit2).expand(options)));
1066                                 ++cit2;
1067                         }
1068                         return s;
1069                 }
1070                 ++cit;
1071         }
1072         
1073         return std::auto_ptr<epvector>(0); // nothing has changed
1074 }
1075
1076 } // namespace GiNaC