]> www.ginac.de Git - ginac.git/blob - ginac/mul.cpp
Fixed problems on 64-bit machines and introduced has_options::algebraic.
[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 bool mul::has(const ex & pattern, unsigned options) const
601 {
602         if(!(options&has_options::algebraic))
603                 return basic::has(pattern,options);
604         if(is_a<mul>(pattern)) {
605                 lst repls;
606                 int nummatches = std::numeric_limits<int>::max();
607                 std::vector<bool> subsed(seq.size(), false);
608                 std::vector<bool> matched(seq.size(), false);
609                 if(algebraic_match_mul_with_mul(*this, pattern, repls, 0, nummatches,
610                                 subsed, matched))
611                         return true;
612         }
613         return basic::has(pattern, options);
614 }
615
616 ex mul::algebraic_subs_mul(const exmap & m, unsigned options) const
617 {       
618         std::vector<bool> subsed(seq.size(), false);
619         exvector subsresult(seq.size());
620
621         for (exmap::const_iterator it = m.begin(); it != m.end(); ++it) {
622
623                 if (is_exactly_a<mul>(it->first)) {
624 retry1:
625                         int nummatches = std::numeric_limits<int>::max();
626                         std::vector<bool> currsubsed(seq.size(), false);
627                         bool succeed = true;
628                         lst repls;
629                         
630                         if(!algebraic_match_mul_with_mul(*this, it->first, repls, 0, nummatches, subsed, currsubsed))
631                                 continue;
632
633                         bool foundfirstsubsedfactor = false;
634                         for (size_t j=0; j<subsed.size(); j++) {
635                                 if (currsubsed[j]) {
636                                         if (foundfirstsubsedfactor)
637                                                 subsresult[j] = op(j);
638                                         else {
639                                                 foundfirstsubsedfactor = true;
640                                                 subsresult[j] = op(j) * power(it->second.subs(ex(repls), subs_options::no_pattern) / it->first.subs(ex(repls), subs_options::no_pattern), nummatches);
641                                         }
642                                         subsed[j] = true;
643                                 }
644                         }
645                         goto retry1;
646
647                 } else {
648 retry2:
649                         int nummatches = std::numeric_limits<int>::max();
650                         lst repls;
651
652                         for (size_t j=0; j<this->nops(); j++) {
653                                 if (!subsed[j] && tryfactsubs(op(j), it->first, nummatches, repls)) {
654                                         subsed[j] = true;
655                                         subsresult[j] = op(j) * power(it->second.subs(ex(repls), subs_options::no_pattern) / it->first.subs(ex(repls), subs_options::no_pattern), nummatches);
656                                         goto retry2;
657                                 }
658                         }
659                 }
660         }
661
662         bool subsfound = false;
663         for (size_t i=0; i<subsed.size(); i++) {
664                 if (subsed[i]) {
665                         subsfound = true;
666                         break;
667                 }
668         }
669         if (!subsfound)
670                 return subs_one_level(m, options | subs_options::algebraic);
671
672         exvector ev; ev.reserve(nops());
673         for (size_t i=0; i<nops(); i++) {
674                 if (subsed[i])
675                         ev.push_back(subsresult[i]);
676                 else
677                         ev.push_back(op(i));
678         }
679
680         return (new mul(ev))->setflag(status_flags::dynallocated);
681 }
682
683 // protected
684
685 /** Implementation of ex::diff() for a product.  It applies the product rule.
686  *  @see ex::diff */
687 ex mul::derivative(const symbol & s) const
688 {
689         size_t num = seq.size();
690         exvector addseq;
691         addseq.reserve(num);
692         
693         // D(a*b*c) = D(a)*b*c + a*D(b)*c + a*b*D(c)
694         epvector mulseq = seq;
695         epvector::const_iterator i = seq.begin(), end = seq.end();
696         epvector::iterator i2 = mulseq.begin();
697         while (i != end) {
698                 expair ep = split_ex_to_pair(power(i->rest, i->coeff - _ex1) *
699                                              i->rest.diff(s));
700                 ep.swap(*i2);
701                 addseq.push_back((new mul(mulseq, overall_coeff * i->coeff))->setflag(status_flags::dynallocated));
702                 ep.swap(*i2);
703                 ++i; ++i2;
704         }
705         return (new add(addseq))->setflag(status_flags::dynallocated);
706 }
707
708 int mul::compare_same_type(const basic & other) const
709 {
710         return inherited::compare_same_type(other);
711 }
712
713 unsigned mul::return_type() const
714 {
715         if (seq.empty()) {
716                 // mul without factors: should not happen, but commutates
717                 return return_types::commutative;
718         }
719         
720         bool all_commutative = true;
721         epvector::const_iterator noncommutative_element; // point to first found nc element
722         
723         epvector::const_iterator i = seq.begin(), end = seq.end();
724         while (i != end) {
725                 unsigned rt = i->rest.return_type();
726                 if (rt == return_types::noncommutative_composite)
727                         return rt; // one ncc -> mul also ncc
728                 if ((rt == return_types::noncommutative) && (all_commutative)) {
729                         // first nc element found, remember position
730                         noncommutative_element = i;
731                         all_commutative = false;
732                 }
733                 if ((rt == return_types::noncommutative) && (!all_commutative)) {
734                         // another nc element found, compare type_infos
735                         if (noncommutative_element->rest.return_type_tinfo()->tinfo() == &clifford::tinfo_static) {
736                                 if (i->rest.return_type_tinfo()->tinfo() != &clifford::tinfo_static ||
737                                     ((clifford*)(noncommutative_element->rest.return_type_tinfo()))->get_representation_label() !=
738                                     ((clifford*)(i->rest.return_type_tinfo()))->get_representation_label()) {
739                                         // diffent types -> mul is ncc
740                                         return return_types::noncommutative_composite;
741                                 }
742                         } else if (noncommutative_element->rest.return_type_tinfo()->tinfo() == &color::tinfo_static) {
743                                 if (i->rest.return_type_tinfo()->tinfo() != &color::tinfo_static ||
744                                     ((color*)(noncommutative_element->rest.return_type_tinfo()))->get_representation_label() !=
745                                     ((color*)(i->rest.return_type_tinfo()))->get_representation_label()) {
746                                         // diffent types -> mul is ncc
747                                         return return_types::noncommutative_composite;
748                                 }
749                         } else if (noncommutative_element->rest.return_type_tinfo()->tinfo() != i->rest.return_type_tinfo()->tinfo()) {
750                                         return return_types::noncommutative_composite;
751                         }
752                 }
753                 ++i;
754         }
755         // all factors checked
756         return all_commutative ? return_types::commutative : return_types::noncommutative;
757 }
758    
759 const basic* mul::return_type_tinfo() const
760 {
761         if (seq.empty())
762                 return this;  // mul without factors: should not happen
763         
764         // return type_info of first noncommutative element
765         epvector::const_iterator i = seq.begin(), end = seq.end();
766         while (i != end) {
767                 if (i->rest.return_type() == return_types::noncommutative)
768                         return i->rest.return_type_tinfo();
769                 ++i;
770         }
771         // no noncommutative element found, should not happen
772         return this;
773 }
774
775 ex mul::thisexpairseq(const epvector & v, const ex & oc) const
776 {
777         return (new mul(v, oc))->setflag(status_flags::dynallocated);
778 }
779
780 ex mul::thisexpairseq(std::auto_ptr<epvector> vp, const ex & oc) const
781 {
782         return (new mul(vp, oc))->setflag(status_flags::dynallocated);
783 }
784
785 expair mul::split_ex_to_pair(const ex & e) const
786 {
787         if (is_exactly_a<power>(e)) {
788                 const power & powerref = ex_to<power>(e);
789                 if (is_exactly_a<numeric>(powerref.exponent))
790                         return expair(powerref.basis,powerref.exponent);
791         }
792         return expair(e,_ex1);
793 }
794         
795 expair mul::combine_ex_with_coeff_to_pair(const ex & e,
796                                           const ex & c) const
797 {
798         // to avoid duplication of power simplification rules,
799         // we create a temporary power object
800         // otherwise it would be hard to correctly evaluate
801         // expression like (4^(1/3))^(3/2)
802         if (c.is_equal(_ex1))
803                 return split_ex_to_pair(e);
804
805         return split_ex_to_pair(power(e,c));
806 }
807         
808 expair mul::combine_pair_with_coeff_to_pair(const expair & p,
809                                             const ex & c) const
810 {
811         // to avoid duplication of power simplification rules,
812         // we create a temporary power object
813         // otherwise it would be hard to correctly evaluate
814         // expression like (4^(1/3))^(3/2)
815         if (c.is_equal(_ex1))
816                 return p;
817
818         return split_ex_to_pair(power(recombine_pair_to_ex(p),c));
819 }
820         
821 ex mul::recombine_pair_to_ex(const expair & p) const
822 {
823         if (ex_to<numeric>(p.coeff).is_equal(*_num1_p)) 
824                 return p.rest;
825         else
826                 return (new power(p.rest,p.coeff))->setflag(status_flags::dynallocated);
827 }
828
829 bool mul::expair_needs_further_processing(epp it)
830 {
831         if (is_exactly_a<mul>(it->rest) &&
832                 ex_to<numeric>(it->coeff).is_integer()) {
833                 // combined pair is product with integer power -> expand it
834                 *it = split_ex_to_pair(recombine_pair_to_ex(*it));
835                 return true;
836         }
837         if (is_exactly_a<numeric>(it->rest)) {
838                 expair ep = split_ex_to_pair(recombine_pair_to_ex(*it));
839                 if (!ep.is_equal(*it)) {
840                         // combined pair is a numeric power which can be simplified
841                         *it = ep;
842                         return true;
843                 }
844                 if (it->coeff.is_equal(_ex1)) {
845                         // combined pair has coeff 1 and must be moved to the end
846                         return true;
847                 }
848         }
849         return false;
850 }       
851
852 ex mul::default_overall_coeff() const
853 {
854         return _ex1;
855 }
856
857 void mul::combine_overall_coeff(const ex & c)
858 {
859         GINAC_ASSERT(is_exactly_a<numeric>(overall_coeff));
860         GINAC_ASSERT(is_exactly_a<numeric>(c));
861         overall_coeff = ex_to<numeric>(overall_coeff).mul_dyn(ex_to<numeric>(c));
862 }
863
864 void mul::combine_overall_coeff(const ex & c1, const ex & c2)
865 {
866         GINAC_ASSERT(is_exactly_a<numeric>(overall_coeff));
867         GINAC_ASSERT(is_exactly_a<numeric>(c1));
868         GINAC_ASSERT(is_exactly_a<numeric>(c2));
869         overall_coeff = ex_to<numeric>(overall_coeff).mul_dyn(ex_to<numeric>(c1).power(ex_to<numeric>(c2)));
870 }
871
872 bool mul::can_make_flat(const expair & p) const
873 {
874         GINAC_ASSERT(is_exactly_a<numeric>(p.coeff));
875         // this assertion will probably fail somewhere
876         // it would require a more careful make_flat, obeying the power laws
877         // probably should return true only if p.coeff is integer
878         return ex_to<numeric>(p.coeff).is_equal(*_num1_p);
879 }
880
881 bool mul::can_be_further_expanded(const ex & e)
882 {
883         if (is_exactly_a<mul>(e)) {
884                 for (epvector::const_iterator cit = ex_to<mul>(e).seq.begin(); cit != ex_to<mul>(e).seq.end(); ++cit) {
885                         if (is_exactly_a<add>(cit->rest) && cit->coeff.info(info_flags::posint))
886                                 return true;
887                 }
888         } else if (is_exactly_a<power>(e)) {
889                 if (is_exactly_a<add>(e.op(0)) && e.op(1).info(info_flags::posint))
890                         return true;
891         }
892         return false;
893 }
894
895 ex mul::expand(unsigned options) const
896 {
897         // First, expand the children
898         std::auto_ptr<epvector> expanded_seqp = expandchildren(options);
899         const epvector & expanded_seq = (expanded_seqp.get() ? *expanded_seqp : seq);
900
901         // Now, look for all the factors that are sums and multiply each one out
902         // with the next one that is found while collecting the factors which are
903         // not sums
904         ex last_expanded = _ex1;
905
906         epvector non_adds;
907         non_adds.reserve(expanded_seq.size());
908
909         for (epvector::const_iterator cit = expanded_seq.begin(); cit != expanded_seq.end(); ++cit) {
910                 if (is_exactly_a<add>(cit->rest) &&
911                         (cit->coeff.is_equal(_ex1))) {
912                         if (is_exactly_a<add>(last_expanded)) {
913
914                                 // Expand a product of two sums, aggressive version.
915                                 // Caring for the overall coefficients in separate loops can
916                                 // sometimes give a performance gain of up to 15%!
917
918                                 const int sizedifference = ex_to<add>(last_expanded).seq.size()-ex_to<add>(cit->rest).seq.size();
919                                 // add2 is for the inner loop and should be the bigger of the two sums
920                                 // in the presence of asymptotically good sorting:
921                                 const add& add1 = (sizedifference<0 ? ex_to<add>(last_expanded) : ex_to<add>(cit->rest));
922                                 const add& add2 = (sizedifference<0 ? ex_to<add>(cit->rest) : ex_to<add>(last_expanded));
923                                 const epvector::const_iterator add1begin = add1.seq.begin();
924                                 const epvector::const_iterator add1end   = add1.seq.end();
925                                 const epvector::const_iterator add2begin = add2.seq.begin();
926                                 const epvector::const_iterator add2end   = add2.seq.end();
927                                 epvector distrseq;
928                                 distrseq.reserve(add1.seq.size()+add2.seq.size());
929
930                                 // Multiply add2 with the overall coefficient of add1 and append it to distrseq:
931                                 if (!add1.overall_coeff.is_zero()) {
932                                         if (add1.overall_coeff.is_equal(_ex1))
933                                                 distrseq.insert(distrseq.end(),add2begin,add2end);
934                                         else
935                                                 for (epvector::const_iterator i=add2begin; i!=add2end; ++i)
936                                                         distrseq.push_back(expair(i->rest, ex_to<numeric>(i->coeff).mul_dyn(ex_to<numeric>(add1.overall_coeff))));
937                                 }
938
939                                 // Multiply add1 with the overall coefficient of add2 and append it to distrseq:
940                                 if (!add2.overall_coeff.is_zero()) {
941                                         if (add2.overall_coeff.is_equal(_ex1))
942                                                 distrseq.insert(distrseq.end(),add1begin,add1end);
943                                         else
944                                                 for (epvector::const_iterator i=add1begin; i!=add1end; ++i)
945                                                         distrseq.push_back(expair(i->rest, ex_to<numeric>(i->coeff).mul_dyn(ex_to<numeric>(add2.overall_coeff))));
946                                 }
947
948                                 // Compute the new overall coefficient and put it together:
949                                 ex tmp_accu = (new add(distrseq, add1.overall_coeff*add2.overall_coeff))->setflag(status_flags::dynallocated);
950
951                                 exvector add1_dummy_indices, add2_dummy_indices, add_indices;
952
953                                 for (epvector::const_iterator i=add1begin; i!=add1end; ++i) {
954                                         add_indices = get_all_dummy_indices(i->rest);
955                                         add1_dummy_indices.insert(add1_dummy_indices.end(), add_indices.begin(), add_indices.end());
956                                 }
957                                 for (epvector::const_iterator i=add2begin; i!=add2end; ++i) {
958                                         add_indices = get_all_dummy_indices(i->rest);
959                                         add2_dummy_indices.insert(add2_dummy_indices.end(), add_indices.begin(), add_indices.end());
960                                 }
961
962                                 sort(add1_dummy_indices.begin(), add1_dummy_indices.end(), ex_is_less());
963                                 sort(add2_dummy_indices.begin(), add2_dummy_indices.end(), ex_is_less());
964                                 lst dummy_subs = rename_dummy_indices_uniquely(add1_dummy_indices, add2_dummy_indices);
965
966                                 // Multiply explicitly all non-numeric terms of add1 and add2:
967                                 for (epvector::const_iterator i2=add2begin; i2!=add2end; ++i2) {
968                                         // We really have to combine terms here in order to compactify
969                                         // the result.  Otherwise it would become waayy tooo bigg.
970                                         numeric oc;
971                                         distrseq.clear();
972                                         ex i2_new = (dummy_subs.op(0).nops()>0? 
973                                                                  i2->rest.subs((lst)dummy_subs.op(0), (lst)dummy_subs.op(1), subs_options::no_pattern) : i2->rest);
974                                         for (epvector::const_iterator i1=add1begin; i1!=add1end; ++i1) {
975                                                 // Don't push_back expairs which might have a rest that evaluates to a numeric,
976                                                 // since that would violate an invariant of expairseq:
977                                                 const ex rest = (new mul(i1->rest, i2_new))->setflag(status_flags::dynallocated);
978                                                 if (is_exactly_a<numeric>(rest)) {
979                                                         oc += ex_to<numeric>(rest).mul(ex_to<numeric>(i1->coeff).mul(ex_to<numeric>(i2->coeff)));
980                                                 } else {
981                                                         distrseq.push_back(expair(rest, ex_to<numeric>(i1->coeff).mul_dyn(ex_to<numeric>(i2->coeff))));
982                                                 }
983                                         }
984                                         tmp_accu += (new add(distrseq, oc))->setflag(status_flags::dynallocated);
985                                 }
986                                 last_expanded = tmp_accu;
987
988                         } else {
989                                 if (!last_expanded.is_equal(_ex1))
990                                         non_adds.push_back(split_ex_to_pair(last_expanded));
991                                 last_expanded = cit->rest;
992                         }
993
994                 } else {
995                         non_adds.push_back(*cit);
996                 }
997         }
998
999         // Now the only remaining thing to do is to multiply the factors which
1000         // were not sums into the "last_expanded" sum
1001         if (is_exactly_a<add>(last_expanded)) {
1002                 size_t n = last_expanded.nops();
1003                 exvector distrseq;
1004                 distrseq.reserve(n);
1005                 exvector va = get_all_dummy_indices(mul(non_adds));
1006                 sort(va.begin(), va.end(), ex_is_less());
1007
1008                 for (size_t i=0; i<n; ++i) {
1009                         epvector factors = non_adds;
1010                         factors.push_back(split_ex_to_pair(rename_dummy_indices_uniquely(va, last_expanded.op(i))));
1011                         ex term = (new mul(factors, overall_coeff))->setflag(status_flags::dynallocated);
1012                         if (can_be_further_expanded(term)) {
1013                                 distrseq.push_back(term.expand());
1014                         } else {
1015                                 if (options == 0)
1016                                         ex_to<basic>(term).setflag(status_flags::expanded);
1017                                 distrseq.push_back(term);
1018                         }
1019                 }
1020
1021                 return ((new add(distrseq))->
1022                         setflag(status_flags::dynallocated | (options == 0 ? status_flags::expanded : 0)));
1023         }
1024
1025         non_adds.push_back(split_ex_to_pair(last_expanded));
1026         ex result = (new mul(non_adds, overall_coeff))->setflag(status_flags::dynallocated);
1027         if (can_be_further_expanded(result)) {
1028                 return result.expand();
1029         } else {
1030                 if (options == 0)
1031                         ex_to<basic>(result).setflag(status_flags::expanded);
1032                 return result;
1033         }
1034 }
1035
1036   
1037 //////////
1038 // new virtual functions which can be overridden by derived classes
1039 //////////
1040
1041 // none
1042
1043 //////////
1044 // non-virtual functions in this class
1045 //////////
1046
1047
1048 /** Member-wise expand the expairs representing this sequence.  This must be
1049  *  overridden from expairseq::expandchildren() and done iteratively in order
1050  *  to allow for early cancallations and thus safe memory.
1051  *
1052  *  @see mul::expand()
1053  *  @return pointer to epvector containing expanded representation or zero
1054  *  pointer, if sequence is unchanged. */
1055 std::auto_ptr<epvector> mul::expandchildren(unsigned options) const
1056 {
1057         const epvector::const_iterator last = seq.end();
1058         epvector::const_iterator cit = seq.begin();
1059         while (cit!=last) {
1060                 const ex & factor = recombine_pair_to_ex(*cit);
1061                 const ex & expanded_factor = factor.expand(options);
1062                 if (!are_ex_trivially_equal(factor,expanded_factor)) {
1063                         
1064                         // something changed, copy seq, eval and return it
1065                         std::auto_ptr<epvector> s(new epvector);
1066                         s->reserve(seq.size());
1067                         
1068                         // copy parts of seq which are known not to have changed
1069                         epvector::const_iterator cit2 = seq.begin();
1070                         while (cit2!=cit) {
1071                                 s->push_back(*cit2);
1072                                 ++cit2;
1073                         }
1074
1075                         // copy first changed element
1076                         s->push_back(split_ex_to_pair(expanded_factor));
1077                         ++cit2;
1078
1079                         // copy rest
1080                         while (cit2!=last) {
1081                                 s->push_back(split_ex_to_pair(recombine_pair_to_ex(*cit2).expand(options)));
1082                                 ++cit2;
1083                         }
1084                         return s;
1085                 }
1086                 ++cit;
1087         }
1088         
1089         return std::auto_ptr<epvector>(0); // nothing has changed
1090 }
1091
1092 } // namespace GiNaC