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