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