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