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