]> www.ginac.de Git - ginac.git/blob - ginac/mul.cpp
4e95a638310e313444c45736af5b1d090a8f6076
[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-2007 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 #include "symbol.h"
38 #include "compiler.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, bool do_index_renaming)
90 {
91         tinfo_key = &mul::tinfo_static;
92         overall_coeff = oc;
93         construct_from_epvector(v, do_index_renaming);
94         GINAC_ASSERT(is_canonical());
95 }
96
97 mul::mul(std::auto_ptr<epvector> vp, const ex & oc, bool do_index_renaming)
98 {
99         tinfo_key = &mul::tinfo_static;
100         GINAC_ASSERT(vp.get()!=0);
101         overall_coeff = oc;
102         construct_from_epvector(*vp, do_index_renaming);
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                 if (overall_coeff.is_equal(_ex_1))
224                         c.s << "-";
225                 else {
226                         overall_coeff.print(c, precedence());
227                         c.s << "*";
228                 }
229         }
230
231         // Print arguments, separated by "*" or "/"
232         epvector::const_iterator it = seq.begin(), itend = seq.end();
233         while (it != itend) {
234
235                 // If the first argument is a negative integer power, it gets printed as "1.0/<expr>"
236                 bool needclosingparenthesis = false;
237                 if (it == seq.begin() && it->coeff.info(info_flags::negint)) {
238                         if (is_a<print_csrc_cl_N>(c)) {
239                                 c.s << "recip(";
240                                 needclosingparenthesis = true;
241                         } else
242                                 c.s << "1.0/";
243                 }
244
245                 // If the exponent is 1 or -1, it is left out
246                 if (it->coeff.is_equal(_ex1) || it->coeff.is_equal(_ex_1))
247                         it->rest.print(c, precedence());
248                 else if (it->coeff.info(info_flags::negint))
249                         // Outer parens around ex needed for broken GCC parser:
250                         (ex(power(it->rest, -ex_to<numeric>(it->coeff)))).print(c, level);
251                 else
252                         // Outer parens around ex needed for broken GCC parser:
253                         (ex(power(it->rest, ex_to<numeric>(it->coeff)))).print(c, level);
254
255                 if (needclosingparenthesis)
256                         c.s << ")";
257
258                 // Separator is "/" for negative integer powers, "*" otherwise
259                 ++it;
260                 if (it != itend) {
261                         if (it->coeff.info(info_flags::negint))
262                                 c.s << "/";
263                         else
264                                 c.s << "*";
265                 }
266         }
267
268         if (precedence() <= level)
269                 c.s << ")";
270 }
271
272 void mul::do_print_python_repr(const print_python_repr & c, unsigned level) const
273 {
274         c.s << class_name() << '(';
275         op(0).print(c);
276         for (size_t i=1; i<nops(); ++i) {
277                 c.s << ',';
278                 op(i).print(c);
279         }
280         c.s << ')';
281 }
282
283 bool mul::info(unsigned inf) const
284 {
285         switch (inf) {
286                 case info_flags::polynomial:
287                 case info_flags::integer_polynomial:
288                 case info_flags::cinteger_polynomial:
289                 case info_flags::rational_polynomial:
290                 case info_flags::crational_polynomial:
291                 case info_flags::rational_function: {
292                         epvector::const_iterator i = seq.begin(), end = seq.end();
293                         while (i != end) {
294                                 if (!(recombine_pair_to_ex(*i).info(inf)))
295                                         return false;
296                                 ++i;
297                         }
298                         return overall_coeff.info(inf);
299                 }
300                 case info_flags::algebraic: {
301                         epvector::const_iterator i = seq.begin(), end = seq.end();
302                         while (i != end) {
303                                 if ((recombine_pair_to_ex(*i).info(inf)))
304                                         return true;
305                                 ++i;
306                         }
307                         return false;
308                 }
309         }
310         return inherited::info(inf);
311 }
312
313 int mul::degree(const ex & s) const
314 {
315         // Sum up degrees of factors
316         int deg_sum = 0;
317         epvector::const_iterator i = seq.begin(), end = seq.end();
318         while (i != end) {
319                 if (ex_to<numeric>(i->coeff).is_integer())
320                         deg_sum += recombine_pair_to_ex(*i).degree(s);
321                 else {
322                         if (i->rest.has(s))
323                                 throw std::runtime_error("mul::degree() undefined degree because of non-integer exponent");
324                 }
325                 ++i;
326         }
327         return deg_sum;
328 }
329
330 int mul::ldegree(const ex & s) const
331 {
332         // Sum up degrees of factors
333         int deg_sum = 0;
334         epvector::const_iterator i = seq.begin(), end = seq.end();
335         while (i != end) {
336                 if (ex_to<numeric>(i->coeff).is_integer())
337                         deg_sum += recombine_pair_to_ex(*i).ldegree(s);
338                 else {
339                         if (i->rest.has(s))
340                                 throw std::runtime_error("mul::ldegree() undefined degree because of non-integer exponent");
341                 }
342                 ++i;
343         }
344         return deg_sum;
345 }
346
347 ex mul::coeff(const ex & s, int n) const
348 {
349         exvector coeffseq;
350         coeffseq.reserve(seq.size()+1);
351         
352         if (n==0) {
353                 // product of individual coeffs
354                 // if a non-zero power of s is found, the resulting product will be 0
355                 epvector::const_iterator i = seq.begin(), end = seq.end();
356                 while (i != end) {
357                         coeffseq.push_back(recombine_pair_to_ex(*i).coeff(s,n));
358                         ++i;
359                 }
360                 coeffseq.push_back(overall_coeff);
361                 return (new mul(coeffseq))->setflag(status_flags::dynallocated);
362         }
363         
364         epvector::const_iterator i = seq.begin(), end = seq.end();
365         bool coeff_found = false;
366         while (i != end) {
367                 ex t = recombine_pair_to_ex(*i);
368                 ex c = t.coeff(s, n);
369                 if (!c.is_zero()) {
370                         coeffseq.push_back(c);
371                         coeff_found = 1;
372                 } else {
373                         coeffseq.push_back(t);
374                 }
375                 ++i;
376         }
377         if (coeff_found) {
378                 coeffseq.push_back(overall_coeff);
379                 return (new mul(coeffseq))->setflag(status_flags::dynallocated);
380         }
381         
382         return _ex0;
383 }
384
385 /** Perform automatic term rewriting rules in this class.  In the following
386  *  x, x1, x2,... stand for a symbolic variables of type ex and c, c1, c2...
387  *  stand for such expressions that contain a plain number.
388  *  - *(...,x;0) -> 0
389  *  - *(+(x1,x2,...);c) -> *(+(*(x1,c),*(x2,c),...))
390  *  - *(x;1) -> x
391  *  - *(;c) -> c
392  *
393  *  @param level cut-off in recursive evaluation */
394 ex mul::eval(int level) const
395 {
396         std::auto_ptr<epvector> evaled_seqp = evalchildren(level);
397         if (evaled_seqp.get()) {
398                 // do more evaluation later
399                 return (new mul(evaled_seqp, overall_coeff))->
400                            setflag(status_flags::dynallocated);
401         }
402         
403 #ifdef DO_GINAC_ASSERT
404         epvector::const_iterator i = seq.begin(), end = seq.end();
405         while (i != end) {
406                 GINAC_ASSERT((!is_exactly_a<mul>(i->rest)) ||
407                              (!(ex_to<numeric>(i->coeff).is_integer())));
408                 GINAC_ASSERT(!(i->is_canonical_numeric()));
409                 if (is_exactly_a<numeric>(recombine_pair_to_ex(*i)))
410                     print(print_tree(std::cerr));
411                 GINAC_ASSERT(!is_exactly_a<numeric>(recombine_pair_to_ex(*i)));
412                 /* for paranoia */
413                 expair p = split_ex_to_pair(recombine_pair_to_ex(*i));
414                 GINAC_ASSERT(p.rest.is_equal(i->rest));
415                 GINAC_ASSERT(p.coeff.is_equal(i->coeff));
416                 /* end paranoia */
417                 ++i;
418         }
419 #endif // def DO_GINAC_ASSERT
420         
421         if (flags & status_flags::evaluated) {
422                 GINAC_ASSERT(seq.size()>0);
423                 GINAC_ASSERT(seq.size()>1 || !overall_coeff.is_equal(_ex1));
424                 return *this;
425         }
426         
427         size_t seq_size = seq.size();
428         if (overall_coeff.is_zero()) {
429                 // *(...,x;0) -> 0
430                 return _ex0;
431         } else if (seq_size==0) {
432                 // *(;c) -> c
433                 return overall_coeff;
434         } else if (seq_size==1 && overall_coeff.is_equal(_ex1)) {
435                 // *(x;1) -> x
436                 return recombine_pair_to_ex(*(seq.begin()));
437         } else if ((seq_size==1) &&
438                    is_exactly_a<add>((*seq.begin()).rest) &&
439                    ex_to<numeric>((*seq.begin()).coeff).is_equal(*_num1_p)) {
440                 // *(+(x,y,...);c) -> +(*(x,c),*(y,c),...) (c numeric(), no powers of +())
441                 const add & addref = ex_to<add>((*seq.begin()).rest);
442                 std::auto_ptr<epvector> distrseq(new epvector);
443                 distrseq->reserve(addref.seq.size());
444                 epvector::const_iterator i = addref.seq.begin(), end = addref.seq.end();
445                 while (i != end) {
446                         distrseq->push_back(addref.combine_pair_with_coeff_to_pair(*i, overall_coeff));
447                         ++i;
448                 }
449                 return (new add(distrseq,
450                                 ex_to<numeric>(addref.overall_coeff).
451                                 mul_dyn(ex_to<numeric>(overall_coeff)))
452                        )->setflag(status_flags::dynallocated | status_flags::evaluated);
453         } else if ((seq_size >= 2) && (! (flags & status_flags::expanded))) {
454                 // Strip the content and the unit part from each term. Thus
455                 // things like (-x+a)*(3*x-3*a) automagically turn into - 3*(x-a)2
456
457                 epvector::const_iterator last = seq.end();
458                 epvector::const_iterator i = seq.begin();
459                 epvector::const_iterator j = seq.begin();
460                 std::auto_ptr<epvector> s(new epvector);
461                 numeric oc = *_num1_p;
462                 bool something_changed = false;
463                 while (i!=last) {
464                         if (likely(! (is_a<add>(i->rest) && i->coeff.is_equal(_ex1)))) {
465                                 // power::eval has such a rule, no need to handle powers here
466                                 ++i;
467                                 continue;
468                         }
469
470                         // XXX: What is the best way to check if the polynomial is a primitive? 
471                         numeric c = i->rest.integer_content();
472                         const numeric& lead_coeff =
473                                 ex_to<numeric>(ex_to<add>(i->rest).seq.begin()->coeff).div_dyn(c);
474                         const bool canonicalizable = lead_coeff.is_integer();
475
476                         // XXX: The main variable is chosen in a random way, so this code 
477                         // does NOT transform the term into the canonical form (thus, in some
478                         // very unlucky event it can even loop forever). Hopefully the main
479                         // variable will be the same for all terms in *this
480                         const bool unit_normal = lead_coeff.is_pos_integer();
481                         if (likely((c == *_num1_p) && ((! canonicalizable) || unit_normal))) {
482                                 ++i;
483                                 continue;
484                         }
485
486                         if (! something_changed) {
487                                 s->reserve(seq_size);
488                                 something_changed = true;
489                         }
490
491                         while ((j!=i) && (j!=last)) {
492                                 s->push_back(*j);
493                                 ++j;
494                         }
495
496                         if (! unit_normal)
497                                 c = c.mul(*_num_1_p);
498
499                         oc = oc.mul(c);
500
501                         // divide add by the number in place to save at least 2 .eval() calls
502                         const add& addref = ex_to<add>(i->rest);
503                         add* primitive = new add(addref);
504                         primitive->setflag(status_flags::dynallocated);
505                         primitive->clearflag(status_flags::hash_calculated);
506                         primitive->overall_coeff = ex_to<numeric>(primitive->overall_coeff).div_dyn(c);
507                         for (epvector::iterator ai = primitive->seq.begin();
508                                         ai != primitive->seq.end(); ++ai)
509                                 ai->coeff = ex_to<numeric>(ai->coeff).div_dyn(c);
510                         
511                         s->push_back(expair(*primitive, _ex1));
512
513                         ++i;
514                         ++j;
515                 }
516                 if (something_changed) {
517                         while (j!=last) {
518                                 s->push_back(*j);
519                                 ++j;
520                         }
521                         return (new mul(s, ex_to<numeric>(overall_coeff).mul_dyn(oc))
522                                )->setflag(status_flags::dynallocated);
523                 }
524         }
525
526         return this->hold();
527 }
528
529 ex mul::evalf(int level) const
530 {
531         if (level==1)
532                 return mul(seq,overall_coeff);
533         
534         if (level==-max_recursion_level)
535                 throw(std::runtime_error("max recursion level reached"));
536         
537         std::auto_ptr<epvector> s(new epvector);
538         s->reserve(seq.size());
539
540         --level;
541         epvector::const_iterator i = seq.begin(), end = seq.end();
542         while (i != end) {
543                 s->push_back(combine_ex_with_coeff_to_pair(i->rest.evalf(level),
544                                                            i->coeff));
545                 ++i;
546         }
547         return mul(s, overall_coeff.evalf(level));
548 }
549
550 void mul::find_real_imag(ex & rp, ex & ip) const
551 {
552         rp = overall_coeff.real_part();
553         ip = overall_coeff.imag_part();
554         for (epvector::const_iterator i=seq.begin(); i!=seq.end(); ++i) {
555                 ex factor = recombine_pair_to_ex(*i);
556                 ex new_rp = factor.real_part();
557                 ex new_ip = factor.imag_part();
558                 if(new_ip.is_zero()) {
559                         rp *= new_rp;
560                         ip *= new_rp;
561                 } else {
562                         ex temp = rp*new_rp - ip*new_ip;
563                         ip = ip*new_rp + rp*new_ip;
564                         rp = temp;
565                 }
566         }
567         rp = rp.expand();
568         ip = ip.expand();
569 }
570
571 ex mul::real_part() const
572 {
573         ex rp, ip;
574         find_real_imag(rp, ip);
575         return rp;
576 }
577
578 ex mul::imag_part() const
579 {
580         ex rp, ip;
581         find_real_imag(rp, ip);
582         return ip;
583 }
584
585 ex mul::evalm() const
586 {
587         // numeric*matrix
588         if (seq.size() == 1 && seq[0].coeff.is_equal(_ex1)
589          && is_a<matrix>(seq[0].rest))
590                 return ex_to<matrix>(seq[0].rest).mul(ex_to<numeric>(overall_coeff));
591
592         // Evaluate children first, look whether there are any matrices at all
593         // (there can be either no matrices or one matrix; if there were more
594         // than one matrix, it would be a non-commutative product)
595         std::auto_ptr<epvector> s(new epvector);
596         s->reserve(seq.size());
597
598         bool have_matrix = false;
599         epvector::iterator the_matrix;
600
601         epvector::const_iterator i = seq.begin(), end = seq.end();
602         while (i != end) {
603                 const ex &m = recombine_pair_to_ex(*i).evalm();
604                 s->push_back(split_ex_to_pair(m));
605                 if (is_a<matrix>(m)) {
606                         have_matrix = true;
607                         the_matrix = s->end() - 1;
608                 }
609                 ++i;
610         }
611
612         if (have_matrix) {
613
614                 // The product contained a matrix. We will multiply all other factors
615                 // into that matrix.
616                 matrix m = ex_to<matrix>(the_matrix->rest);
617                 s->erase(the_matrix);
618                 ex scalar = (new mul(s, overall_coeff))->setflag(status_flags::dynallocated);
619                 return m.mul_scalar(scalar);
620
621         } else
622                 return (new mul(s, overall_coeff))->setflag(status_flags::dynallocated);
623 }
624
625 ex mul::eval_ncmul(const exvector & v) const
626 {
627         if (seq.empty())
628                 return inherited::eval_ncmul(v);
629
630         // Find first noncommutative element and call its eval_ncmul()
631         epvector::const_iterator i = seq.begin(), end = seq.end();
632         while (i != end) {
633                 if (i->rest.return_type() == return_types::noncommutative)
634                         return i->rest.eval_ncmul(v);
635                 ++i;
636         }
637         return inherited::eval_ncmul(v);
638 }
639
640 bool tryfactsubs(const ex & origfactor, const ex & patternfactor, int & nummatches, lst & repls)
641 {       
642         ex origbase;
643         int origexponent;
644         int origexpsign;
645
646         if (is_exactly_a<power>(origfactor) && origfactor.op(1).info(info_flags::integer)) {
647                 origbase = origfactor.op(0);
648                 int expon = ex_to<numeric>(origfactor.op(1)).to_int();
649                 origexponent = expon > 0 ? expon : -expon;
650                 origexpsign = expon > 0 ? 1 : -1;
651         } else {
652                 origbase = origfactor;
653                 origexponent = 1;
654                 origexpsign = 1;
655         }
656
657         ex patternbase;
658         int patternexponent;
659         int patternexpsign;
660
661         if (is_exactly_a<power>(patternfactor) && patternfactor.op(1).info(info_flags::integer)) {
662                 patternbase = patternfactor.op(0);
663                 int expon = ex_to<numeric>(patternfactor.op(1)).to_int();
664                 patternexponent = expon > 0 ? expon : -expon;
665                 patternexpsign = expon > 0 ? 1 : -1;
666         } else {
667                 patternbase = patternfactor;
668                 patternexponent = 1;
669                 patternexpsign = 1;
670         }
671
672         lst saverepls = repls;
673         if (origexponent < patternexponent || origexpsign != patternexpsign || !origbase.match(patternbase,saverepls))
674                 return false;
675         repls = saverepls;
676
677         int newnummatches = origexponent / patternexponent;
678         if (newnummatches < nummatches)
679                 nummatches = newnummatches;
680         return true;
681 }
682
683 /** Checks wheter e matches to the pattern pat and the (possibly to be updated)
684   * list of replacements repls. This matching is in the sense of algebraic
685   * substitutions. Matching starts with pat.op(factor) of the pattern because
686   * the factors before this one have already been matched. The (possibly
687   * updated) number of matches is in nummatches. subsed[i] is true for factors
688   * that already have been replaced by previous substitutions and matched[i]
689   * is true for factors that have been matched by the current match.
690   */
691 bool algebraic_match_mul_with_mul(const mul &e, const ex &pat, lst &repls,
692                 int factor, int &nummatches, const std::vector<bool> &subsed,
693                 std::vector<bool> &matched)
694 {
695         if (factor == pat.nops())
696                 return true;
697
698         for (size_t i=0; i<e.nops(); ++i) {
699                 if(subsed[i] || matched[i])
700                         continue;
701                 lst newrepls = repls;
702                 int newnummatches = nummatches;
703                 if (tryfactsubs(e.op(i), pat.op(factor), newnummatches, newrepls)) {
704                         matched[i] = true;
705                         if (algebraic_match_mul_with_mul(e, pat, newrepls, factor+1,
706                                         newnummatches, subsed, matched)) {
707                                 repls = newrepls;
708                                 nummatches = newnummatches;
709                                 return true;
710                         }
711                         else
712                                 matched[i] = false;
713                 }
714         }
715
716         return false;
717 }
718
719 bool mul::has(const ex & pattern, unsigned options) const
720 {
721         if(!(options&has_options::algebraic))
722                 return basic::has(pattern,options);
723         if(is_a<mul>(pattern)) {
724                 lst repls;
725                 int nummatches = std::numeric_limits<int>::max();
726                 std::vector<bool> subsed(seq.size(), false);
727                 std::vector<bool> matched(seq.size(), false);
728                 if(algebraic_match_mul_with_mul(*this, pattern, repls, 0, nummatches,
729                                 subsed, matched))
730                         return true;
731         }
732         return basic::has(pattern, options);
733 }
734
735 ex mul::algebraic_subs_mul(const exmap & m, unsigned options) const
736 {       
737         std::vector<bool> subsed(seq.size(), false);
738         exvector subsresult(seq.size());
739         ex divide_by = 1;
740         ex multiply_by = 1;
741
742         for (exmap::const_iterator it = m.begin(); it != m.end(); ++it) {
743
744                 if (is_exactly_a<mul>(it->first)) {
745 retry1:
746                         int nummatches = std::numeric_limits<int>::max();
747                         std::vector<bool> currsubsed(seq.size(), false);
748                         lst repls;
749                         
750                         if(!algebraic_match_mul_with_mul(*this, it->first, repls, 0, nummatches, subsed, currsubsed))
751                                 continue;
752
753                         for (size_t j=0; j<subsed.size(); j++)
754                                 if (currsubsed[j])
755                                         subsed[j] = true;
756                         ex subsed_pattern
757                                 = it->first.subs(ex(repls), subs_options::no_pattern);
758                         divide_by *= power(subsed_pattern, nummatches);
759                         ex subsed_result
760                                 = it->second.subs(ex(repls), subs_options::no_pattern);
761                         multiply_by *= power(subsed_result, nummatches);
762                         goto retry1;
763
764                 } else {
765
766                         for (size_t j=0; j<this->nops(); j++) {
767                                 int nummatches = std::numeric_limits<int>::max();
768                                 lst repls;
769                                 if (!subsed[j] && tryfactsubs(op(j), it->first, nummatches, repls)){
770                                         subsed[j] = true;
771                                         ex subsed_pattern
772                                                 = it->first.subs(ex(repls), subs_options::no_pattern);
773                                         divide_by *= power(subsed_pattern, nummatches);
774                                         ex subsed_result
775                                                 = it->second.subs(ex(repls), subs_options::no_pattern);
776                                         multiply_by *= power(subsed_result, nummatches);
777                                 }
778                         }
779                 }
780         }
781
782         bool subsfound = false;
783         for (size_t i=0; i<subsed.size(); i++) {
784                 if (subsed[i]) {
785                         subsfound = true;
786                         break;
787                 }
788         }
789         if (!subsfound)
790                 return subs_one_level(m, options | subs_options::algebraic);
791
792         return ((*this)/divide_by)*multiply_by;
793 }
794
795 // protected
796
797 /** Implementation of ex::diff() for a product.  It applies the product rule.
798  *  @see ex::diff */
799 ex mul::derivative(const symbol & s) const
800 {
801         size_t num = seq.size();
802         exvector addseq;
803         addseq.reserve(num);
804         
805         // D(a*b*c) = D(a)*b*c + a*D(b)*c + a*b*D(c)
806         epvector mulseq = seq;
807         epvector::const_iterator i = seq.begin(), end = seq.end();
808         epvector::iterator i2 = mulseq.begin();
809         while (i != end) {
810                 expair ep = split_ex_to_pair(power(i->rest, i->coeff - _ex1) *
811                                              i->rest.diff(s));
812                 ep.swap(*i2);
813                 addseq.push_back((new mul(mulseq, overall_coeff * i->coeff))->setflag(status_flags::dynallocated));
814                 ep.swap(*i2);
815                 ++i; ++i2;
816         }
817         return (new add(addseq))->setflag(status_flags::dynallocated);
818 }
819
820 int mul::compare_same_type(const basic & other) const
821 {
822         return inherited::compare_same_type(other);
823 }
824
825 unsigned mul::return_type() const
826 {
827         if (seq.empty()) {
828                 // mul without factors: should not happen, but commutates
829                 return return_types::commutative;
830         }
831         
832         bool all_commutative = true;
833         epvector::const_iterator noncommutative_element; // point to first found nc element
834         
835         epvector::const_iterator i = seq.begin(), end = seq.end();
836         while (i != end) {
837                 unsigned rt = i->rest.return_type();
838                 if (rt == return_types::noncommutative_composite)
839                         return rt; // one ncc -> mul also ncc
840                 if ((rt == return_types::noncommutative) && (all_commutative)) {
841                         // first nc element found, remember position
842                         noncommutative_element = i;
843                         all_commutative = false;
844                 }
845                 if ((rt == return_types::noncommutative) && (!all_commutative)) {
846                         // another nc element found, compare type_infos
847                         if (noncommutative_element->rest.return_type_tinfo() != i->rest.return_type_tinfo()) {
848                                         // different types -> mul is ncc
849                                         return return_types::noncommutative_composite;
850                         }
851                 }
852                 ++i;
853         }
854         // all factors checked
855         return all_commutative ? return_types::commutative : return_types::noncommutative;
856 }
857    
858 tinfo_t mul::return_type_tinfo() const
859 {
860         if (seq.empty())
861                 return this;  // mul without factors: should not happen
862         
863         // return type_info of first noncommutative element
864         epvector::const_iterator i = seq.begin(), end = seq.end();
865         while (i != end) {
866                 if (i->rest.return_type() == return_types::noncommutative)
867                         return i->rest.return_type_tinfo();
868                 ++i;
869         }
870         // no noncommutative element found, should not happen
871         return this;
872 }
873
874 ex mul::thisexpairseq(const epvector & v, const ex & oc, bool do_index_renaming) const
875 {
876         return (new mul(v, oc, do_index_renaming))->setflag(status_flags::dynallocated);
877 }
878
879 ex mul::thisexpairseq(std::auto_ptr<epvector> vp, const ex & oc, bool do_index_renaming) const
880 {
881         return (new mul(vp, oc, do_index_renaming))->setflag(status_flags::dynallocated);
882 }
883
884 expair mul::split_ex_to_pair(const ex & e) const
885 {
886         if (is_exactly_a<power>(e)) {
887                 const power & powerref = ex_to<power>(e);
888                 if (is_exactly_a<numeric>(powerref.exponent))
889                         return expair(powerref.basis,powerref.exponent);
890         }
891         return expair(e,_ex1);
892 }
893         
894 expair mul::combine_ex_with_coeff_to_pair(const ex & e,
895                                           const ex & c) const
896 {
897         // to avoid duplication of power simplification rules,
898         // we create a temporary power object
899         // otherwise it would be hard to correctly evaluate
900         // expression like (4^(1/3))^(3/2)
901         if (c.is_equal(_ex1))
902                 return split_ex_to_pair(e);
903
904         return split_ex_to_pair(power(e,c));
905 }
906         
907 expair mul::combine_pair_with_coeff_to_pair(const expair & p,
908                                             const ex & c) const
909 {
910         // to avoid duplication of power simplification rules,
911         // we create a temporary power object
912         // otherwise it would be hard to correctly evaluate
913         // expression like (4^(1/3))^(3/2)
914         if (c.is_equal(_ex1))
915                 return p;
916
917         return split_ex_to_pair(power(recombine_pair_to_ex(p),c));
918 }
919         
920 ex mul::recombine_pair_to_ex(const expair & p) const
921 {
922         if (ex_to<numeric>(p.coeff).is_equal(*_num1_p)) 
923                 return p.rest;
924         else
925                 return (new power(p.rest,p.coeff))->setflag(status_flags::dynallocated);
926 }
927
928 bool mul::expair_needs_further_processing(epp it)
929 {
930         if (is_exactly_a<mul>(it->rest) &&
931                 ex_to<numeric>(it->coeff).is_integer()) {
932                 // combined pair is product with integer power -> expand it
933                 *it = split_ex_to_pair(recombine_pair_to_ex(*it));
934                 return true;
935         }
936         if (is_exactly_a<numeric>(it->rest)) {
937                 expair ep = split_ex_to_pair(recombine_pair_to_ex(*it));
938                 if (!ep.is_equal(*it)) {
939                         // combined pair is a numeric power which can be simplified
940                         *it = ep;
941                         return true;
942                 }
943                 if (it->coeff.is_equal(_ex1)) {
944                         // combined pair has coeff 1 and must be moved to the end
945                         return true;
946                 }
947         }
948         return false;
949 }       
950
951 ex mul::default_overall_coeff() const
952 {
953         return _ex1;
954 }
955
956 void mul::combine_overall_coeff(const ex & c)
957 {
958         GINAC_ASSERT(is_exactly_a<numeric>(overall_coeff));
959         GINAC_ASSERT(is_exactly_a<numeric>(c));
960         overall_coeff = ex_to<numeric>(overall_coeff).mul_dyn(ex_to<numeric>(c));
961 }
962
963 void mul::combine_overall_coeff(const ex & c1, const ex & c2)
964 {
965         GINAC_ASSERT(is_exactly_a<numeric>(overall_coeff));
966         GINAC_ASSERT(is_exactly_a<numeric>(c1));
967         GINAC_ASSERT(is_exactly_a<numeric>(c2));
968         overall_coeff = ex_to<numeric>(overall_coeff).mul_dyn(ex_to<numeric>(c1).power(ex_to<numeric>(c2)));
969 }
970
971 bool mul::can_make_flat(const expair & p) const
972 {
973         GINAC_ASSERT(is_exactly_a<numeric>(p.coeff));
974         // this assertion will probably fail somewhere
975         // it would require a more careful make_flat, obeying the power laws
976         // probably should return true only if p.coeff is integer
977         return ex_to<numeric>(p.coeff).is_equal(*_num1_p);
978 }
979
980 bool mul::can_be_further_expanded(const ex & e)
981 {
982         if (is_exactly_a<mul>(e)) {
983                 for (epvector::const_iterator cit = ex_to<mul>(e).seq.begin(); cit != ex_to<mul>(e).seq.end(); ++cit) {
984                         if (is_exactly_a<add>(cit->rest) && cit->coeff.info(info_flags::posint))
985                                 return true;
986                 }
987         } else if (is_exactly_a<power>(e)) {
988                 if (is_exactly_a<add>(e.op(0)) && e.op(1).info(info_flags::posint))
989                         return true;
990         }
991         return false;
992 }
993
994 ex mul::expand(unsigned options) const
995 {
996         {
997         // trivial case: expanding the monomial (~ 30% of all calls)
998                 epvector::const_iterator i = seq.begin(), seq_end = seq.end();
999                 while ((i != seq.end()) &&  is_a<symbol>(i->rest) && i->coeff.info(info_flags::integer))
1000                         ++i;
1001                 if (i == seq_end)
1002                         return (new mul(*this))->setflag(status_flags::dynallocated | status_flags::expanded);
1003         }
1004
1005         // do not rename indices if the object has no indices at all
1006         if ((!(options & expand_options::expand_rename_idx)) && 
1007                         this->info(info_flags::has_indices))
1008                 options |= expand_options::expand_rename_idx;
1009
1010         const bool skip_idx_rename = !(options & expand_options::expand_rename_idx);
1011
1012         // First, expand the children
1013         std::auto_ptr<epvector> expanded_seqp = expandchildren(options);
1014         const epvector & expanded_seq = (expanded_seqp.get() ? *expanded_seqp : seq);
1015
1016         // Now, look for all the factors that are sums and multiply each one out
1017         // with the next one that is found while collecting the factors which are
1018         // not sums
1019         ex last_expanded = _ex1;
1020
1021         epvector non_adds;
1022         non_adds.reserve(expanded_seq.size());
1023
1024         for (epvector::const_iterator cit = expanded_seq.begin(); cit != expanded_seq.end(); ++cit) {
1025                 if (is_exactly_a<add>(cit->rest) &&
1026                         (cit->coeff.is_equal(_ex1))) {
1027                         if (is_exactly_a<add>(last_expanded)) {
1028
1029                                 // Expand a product of two sums, aggressive version.
1030                                 // Caring for the overall coefficients in separate loops can
1031                                 // sometimes give a performance gain of up to 15%!
1032
1033                                 const int sizedifference = ex_to<add>(last_expanded).seq.size()-ex_to<add>(cit->rest).seq.size();
1034                                 // add2 is for the inner loop and should be the bigger of the two sums
1035                                 // in the presence of asymptotically good sorting:
1036                                 const add& add1 = (sizedifference<0 ? ex_to<add>(last_expanded) : ex_to<add>(cit->rest));
1037                                 const add& add2 = (sizedifference<0 ? ex_to<add>(cit->rest) : ex_to<add>(last_expanded));
1038                                 const epvector::const_iterator add1begin = add1.seq.begin();
1039                                 const epvector::const_iterator add1end   = add1.seq.end();
1040                                 const epvector::const_iterator add2begin = add2.seq.begin();
1041                                 const epvector::const_iterator add2end   = add2.seq.end();
1042                                 epvector distrseq;
1043                                 distrseq.reserve(add1.seq.size()+add2.seq.size());
1044
1045                                 // Multiply add2 with the overall coefficient of add1 and append it to distrseq:
1046                                 if (!add1.overall_coeff.is_zero()) {
1047                                         if (add1.overall_coeff.is_equal(_ex1))
1048                                                 distrseq.insert(distrseq.end(),add2begin,add2end);
1049                                         else
1050                                                 for (epvector::const_iterator i=add2begin; i!=add2end; ++i)
1051                                                         distrseq.push_back(expair(i->rest, ex_to<numeric>(i->coeff).mul_dyn(ex_to<numeric>(add1.overall_coeff))));
1052                                 }
1053
1054                                 // Multiply add1 with the overall coefficient of add2 and append it to distrseq:
1055                                 if (!add2.overall_coeff.is_zero()) {
1056                                         if (add2.overall_coeff.is_equal(_ex1))
1057                                                 distrseq.insert(distrseq.end(),add1begin,add1end);
1058                                         else
1059                                                 for (epvector::const_iterator i=add1begin; i!=add1end; ++i)
1060                                                         distrseq.push_back(expair(i->rest, ex_to<numeric>(i->coeff).mul_dyn(ex_to<numeric>(add2.overall_coeff))));
1061                                 }
1062
1063                                 // Compute the new overall coefficient and put it together:
1064                                 ex tmp_accu = (new add(distrseq, add1.overall_coeff*add2.overall_coeff))->setflag(status_flags::dynallocated);
1065
1066                                 exvector add1_dummy_indices, add2_dummy_indices, add_indices;
1067                                 lst dummy_subs;
1068
1069                                 if (!skip_idx_rename) {
1070                                         for (epvector::const_iterator i=add1begin; i!=add1end; ++i) {
1071                                                 add_indices = get_all_dummy_indices_safely(i->rest);
1072                                                 add1_dummy_indices.insert(add1_dummy_indices.end(), add_indices.begin(), add_indices.end());
1073                                         }
1074                                         for (epvector::const_iterator i=add2begin; i!=add2end; ++i) {
1075                                                 add_indices = get_all_dummy_indices_safely(i->rest);
1076                                                 add2_dummy_indices.insert(add2_dummy_indices.end(), add_indices.begin(), add_indices.end());
1077                                         }
1078
1079                                         sort(add1_dummy_indices.begin(), add1_dummy_indices.end(), ex_is_less());
1080                                         sort(add2_dummy_indices.begin(), add2_dummy_indices.end(), ex_is_less());
1081                                         dummy_subs = rename_dummy_indices_uniquely(add1_dummy_indices, add2_dummy_indices);
1082                                 }
1083
1084                                 // Multiply explicitly all non-numeric terms of add1 and add2:
1085                                 for (epvector::const_iterator i2=add2begin; i2!=add2end; ++i2) {
1086                                         // We really have to combine terms here in order to compactify
1087                                         // the result.  Otherwise it would become waayy tooo bigg.
1088                                         numeric oc(*_num0_p);
1089                                         epvector distrseq2;
1090                                         distrseq2.reserve(add1.seq.size());
1091                                         const ex i2_new = (skip_idx_rename || (dummy_subs.op(0).nops() == 0) ?
1092                                                         i2->rest :
1093                                                         i2->rest.subs(ex_to<lst>(dummy_subs.op(0)), 
1094                                                                 ex_to<lst>(dummy_subs.op(1)), subs_options::no_pattern));
1095                                         for (epvector::const_iterator i1=add1begin; i1!=add1end; ++i1) {
1096                                                 // Don't push_back expairs which might have a rest that evaluates to a numeric,
1097                                                 // since that would violate an invariant of expairseq:
1098                                                 const ex rest = (new mul(i1->rest, i2_new))->setflag(status_flags::dynallocated);
1099                                                 if (is_exactly_a<numeric>(rest)) {
1100                                                         oc += ex_to<numeric>(rest).mul(ex_to<numeric>(i1->coeff).mul(ex_to<numeric>(i2->coeff)));
1101                                                 } else {
1102                                                         distrseq2.push_back(expair(rest, ex_to<numeric>(i1->coeff).mul_dyn(ex_to<numeric>(i2->coeff))));
1103                                                 }
1104                                         }
1105                                         tmp_accu += (new add(distrseq2, oc))->setflag(status_flags::dynallocated);
1106                                 } 
1107                                 last_expanded = tmp_accu;
1108                         } else {
1109                                 if (!last_expanded.is_equal(_ex1))
1110                                         non_adds.push_back(split_ex_to_pair(last_expanded));
1111                                 last_expanded = cit->rest;
1112                         }
1113
1114                 } else {
1115                         non_adds.push_back(*cit);
1116                 }
1117         }
1118
1119         // Now the only remaining thing to do is to multiply the factors which
1120         // were not sums into the "last_expanded" sum
1121         if (is_exactly_a<add>(last_expanded)) {
1122                 size_t n = last_expanded.nops();
1123                 exvector distrseq;
1124                 distrseq.reserve(n);
1125                 exvector va;
1126                 if (! skip_idx_rename) {
1127                         va = get_all_dummy_indices_safely(mul(non_adds));
1128                         sort(va.begin(), va.end(), ex_is_less());
1129                 }
1130
1131                 for (size_t i=0; i<n; ++i) {
1132                         epvector factors = non_adds;
1133                         if (skip_idx_rename)
1134                                 factors.push_back(split_ex_to_pair(last_expanded.op(i)));
1135                         else
1136                                 factors.push_back(split_ex_to_pair(rename_dummy_indices_uniquely(va, last_expanded.op(i))));
1137                         ex term = (new mul(factors, overall_coeff))->setflag(status_flags::dynallocated);
1138                         if (can_be_further_expanded(term)) {
1139                                 distrseq.push_back(term.expand());
1140                         } else {
1141                                 if (options == 0)
1142                                         ex_to<basic>(term).setflag(status_flags::expanded);
1143                                 distrseq.push_back(term);
1144                         }
1145                 }
1146
1147                 return ((new add(distrseq))->
1148                         setflag(status_flags::dynallocated | (options == 0 ? status_flags::expanded : 0)));
1149         }
1150
1151         non_adds.push_back(split_ex_to_pair(last_expanded));
1152         ex result = (new mul(non_adds, overall_coeff))->setflag(status_flags::dynallocated);
1153         if (can_be_further_expanded(result)) {
1154                 return result.expand();
1155         } else {
1156                 if (options == 0)
1157                         ex_to<basic>(result).setflag(status_flags::expanded);
1158                 return result;
1159         }
1160 }
1161
1162   
1163 //////////
1164 // new virtual functions which can be overridden by derived classes
1165 //////////
1166
1167 // none
1168
1169 //////////
1170 // non-virtual functions in this class
1171 //////////
1172
1173
1174 /** Member-wise expand the expairs representing this sequence.  This must be
1175  *  overridden from expairseq::expandchildren() and done iteratively in order
1176  *  to allow for early cancallations and thus safe memory.
1177  *
1178  *  @see mul::expand()
1179  *  @return pointer to epvector containing expanded representation or zero
1180  *  pointer, if sequence is unchanged. */
1181 std::auto_ptr<epvector> mul::expandchildren(unsigned options) const
1182 {
1183         const epvector::const_iterator last = seq.end();
1184         epvector::const_iterator cit = seq.begin();
1185         while (cit!=last) {
1186                 const ex & factor = recombine_pair_to_ex(*cit);
1187                 const ex & expanded_factor = factor.expand(options);
1188                 if (!are_ex_trivially_equal(factor,expanded_factor)) {
1189                         
1190                         // something changed, copy seq, eval and return it
1191                         std::auto_ptr<epvector> s(new epvector);
1192                         s->reserve(seq.size());
1193                         
1194                         // copy parts of seq which are known not to have changed
1195                         epvector::const_iterator cit2 = seq.begin();
1196                         while (cit2!=cit) {
1197                                 s->push_back(*cit2);
1198                                 ++cit2;
1199                         }
1200
1201                         // copy first changed element
1202                         s->push_back(split_ex_to_pair(expanded_factor));
1203                         ++cit2;
1204
1205                         // copy rest
1206                         while (cit2!=last) {
1207                                 s->push_back(split_ex_to_pair(recombine_pair_to_ex(*cit2).expand(options)));
1208                                 ++cit2;
1209                         }
1210                         return s;
1211                 }
1212                 ++cit;
1213         }
1214         
1215         return std::auto_ptr<epvector>(0); // nothing has changed
1216 }
1217
1218 } // namespace GiNaC