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