- prepared for 1.0.13 release
[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-2003 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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
21  */
22
23 #include <iostream>
24 #include <vector>
25 #include <stdexcept>
26
27 #include "mul.h"
28 #include "add.h"
29 #include "power.h"
30 #include "matrix.h"
31 #include "archive.h"
32 #include "utils.h"
33
34 namespace GiNaC {
35
36 GINAC_IMPLEMENT_REGISTERED_CLASS(mul, expairseq)
37
38 //////////
39 // default ctor, dtor, copy ctor, assignment operator and helpers
40 //////////
41
42 mul::mul()
43 {
44         tinfo_key = TINFO_mul;
45 }
46
47 DEFAULT_COPY(mul)
48 DEFAULT_DESTROY(mul)
49
50 //////////
51 // other ctors
52 //////////
53
54 // public
55
56 mul::mul(const ex & lh, const ex & rh)
57 {
58         tinfo_key = TINFO_mul;
59         overall_coeff = _ex1;
60         construct_from_2_ex(lh,rh);
61         GINAC_ASSERT(is_canonical());
62 }
63
64 mul::mul(const exvector & v)
65 {
66         tinfo_key = TINFO_mul;
67         overall_coeff = _ex1;
68         construct_from_exvector(v);
69         GINAC_ASSERT(is_canonical());
70 }
71
72 mul::mul(const epvector & v)
73 {
74         tinfo_key = TINFO_mul;
75         overall_coeff = _ex1;
76         construct_from_epvector(v);
77         GINAC_ASSERT(is_canonical());
78 }
79
80 mul::mul(const epvector & v, const ex & oc)
81 {
82         tinfo_key = TINFO_mul;
83         overall_coeff = oc;
84         construct_from_epvector(v);
85         GINAC_ASSERT(is_canonical());
86 }
87
88 mul::mul(epvector * vp, const ex & oc)
89 {
90         tinfo_key = TINFO_mul;
91         GINAC_ASSERT(vp!=0);
92         overall_coeff = oc;
93         construct_from_epvector(*vp);
94         delete vp;
95         GINAC_ASSERT(is_canonical());
96 }
97
98 mul::mul(const ex & lh, const ex & mh, const ex & rh)
99 {
100         tinfo_key = TINFO_mul;
101         exvector factors;
102         factors.reserve(3);
103         factors.push_back(lh);
104         factors.push_back(mh);
105         factors.push_back(rh);
106         overall_coeff = _ex1;
107         construct_from_exvector(factors);
108         GINAC_ASSERT(is_canonical());
109 }
110
111 //////////
112 // archiving
113 //////////
114
115 DEFAULT_ARCHIVING(mul)
116
117 //////////
118 // functions overriding virtual functions from base classes
119 //////////
120
121 // public
122
123 void mul::print(const print_context & c, unsigned level) const
124 {
125         if (is_a<print_tree>(c)) {
126
127                 inherited::print(c, level);
128
129         } else if (is_a<print_csrc>(c)) {
130
131                 if (precedence() <= level)
132                         c.s << "(";
133
134                 if (!overall_coeff.is_equal(_ex1)) {
135                         overall_coeff.print(c, precedence());
136                         c.s << "*";
137                 }
138
139                 // Print arguments, separated by "*" or "/"
140                 epvector::const_iterator it = seq.begin(), itend = seq.end();
141                 while (it != itend) {
142
143                         // If the first argument is a negative integer power, it gets printed as "1.0/<expr>"
144                         bool needclosingparenthesis = false;
145                         if (it == seq.begin() && it->coeff.info(info_flags::negint)) {
146                                 if (is_a<print_csrc_cl_N>(c)) {
147                                         c.s << "recip(";
148                                         needclosingparenthesis = true;
149                                 } else
150                                         c.s << "1.0/";
151                         }
152
153                         // If the exponent is 1 or -1, it is left out
154                         if (it->coeff.is_equal(_ex1) || it->coeff.is_equal(_ex_1))
155                                 it->rest.print(c, precedence());
156                         else if (it->coeff.info(info_flags::negint))
157                                 // Outer parens around ex needed for broken gcc-2.95 parser:
158                                 (ex(power(it->rest, -ex_to<numeric>(it->coeff)))).print(c, level);
159                         else
160                                 // Outer parens around ex needed for broken gcc-2.95 parser:
161                                 (ex(power(it->rest, ex_to<numeric>(it->coeff)))).print(c, level);
162
163                         if (needclosingparenthesis)
164                                 c.s << ")";
165
166                         // Separator is "/" for negative integer powers, "*" otherwise
167                         ++it;
168                         if (it != itend) {
169                                 if (it->coeff.info(info_flags::negint))
170                                         c.s << "/";
171                                 else
172                                         c.s << "*";
173                         }
174                 }
175
176                 if (precedence() <= level)
177                         c.s << ")";
178
179         } else if (is_a<print_python_repr>(c)) {
180                 c.s << class_name() << '(';
181                 op(0).print(c);
182                 for (unsigned i=1; i<nops(); ++i) {
183                         c.s << ',';
184                         op(i).print(c);
185                 }
186                 c.s << ')';
187         } else {
188
189                 if (precedence() <= level) {
190                         if (is_a<print_latex>(c))
191                                 c.s << "{(";
192                         else
193                                 c.s << "(";
194                 }
195
196                 // First print the overall numeric coefficient
197                 numeric coeff = ex_to<numeric>(overall_coeff);
198                 if (coeff.csgn() == -1)
199                         c.s << '-';
200                 if (!coeff.is_equal(_num1) &&
201                         !coeff.is_equal(_num_1)) {
202                         if (coeff.is_rational()) {
203                                 if (coeff.is_negative())
204                                         (-coeff).print(c);
205                                 else
206                                         coeff.print(c);
207                         } else {
208                                 if (coeff.csgn() == -1)
209                                         (-coeff).print(c, precedence());
210                                 else
211                                         coeff.print(c, precedence());
212                         }
213                         if (is_a<print_latex>(c))
214                                 c.s << ' ';
215                         else
216                                 c.s << '*';
217                 }
218
219                 // Then proceed with the remaining factors
220                 epvector::const_iterator it = seq.begin(), itend = seq.end();
221                 if (is_a<print_latex>(c)) {
222
223                         // Separate factors into those with negative numeric exponent
224                         // and all others
225                         exvector neg_powers, others;
226                         while (it != itend) {
227                                 GINAC_ASSERT(is_exactly_a<numeric>(it->coeff));
228                                 if (ex_to<numeric>(it->coeff).is_negative())
229                                         neg_powers.push_back(recombine_pair_to_ex(expair(it->rest, -(it->coeff))));
230                                 else
231                                         others.push_back(recombine_pair_to_ex(*it));
232                                 ++it;
233                         }
234
235                         if (!neg_powers.empty()) {
236
237                                 // Factors with negative exponent are printed as a fraction
238                                 c.s << "\\frac{";
239                                 mul(others).eval().print(c);
240                                 c.s << "}{";
241                                 mul(neg_powers).eval().print(c);
242                                 c.s << "}";
243
244                         } else {
245
246                                 // All other factors are printed in the ordinary way
247                                 exvector::const_iterator vit = others.begin(), vitend = others.end();
248                                 while (vit != vitend) {
249                                         c.s << ' ';
250                                         vit->print(c, precedence());
251                                         ++vit;
252                                 }
253                         }
254
255                 } else {
256
257                         bool first = true;
258                         while (it != itend) {
259                                 if (!first)
260                                         c.s << '*';
261                                 else
262                                         first = false;
263                                 recombine_pair_to_ex(*it).print(c, precedence());
264                                 ++it;
265                         }
266                 }
267
268                 if (precedence() <= level) {
269                         if (is_a<print_latex>(c))
270                                 c.s << ")}";
271                         else
272                                 c.s << ")";
273                 }
274         }
275 }
276
277 bool mul::info(unsigned inf) const
278 {
279         switch (inf) {
280                 case info_flags::polynomial:
281                 case info_flags::integer_polynomial:
282                 case info_flags::cinteger_polynomial:
283                 case info_flags::rational_polynomial:
284                 case info_flags::crational_polynomial:
285                 case info_flags::rational_function: {
286                         epvector::const_iterator i = seq.begin(), end = seq.end();
287                         while (i != end) {
288                                 if (!(recombine_pair_to_ex(*i).info(inf)))
289                                         return false;
290                                 ++i;
291                         }
292                         return overall_coeff.info(inf);
293                 }
294                 case info_flags::algebraic: {
295                         epvector::const_iterator i = seq.begin(), end = seq.end();
296                         while (i != end) {
297                                 if ((recombine_pair_to_ex(*i).info(inf)))
298                                         return true;
299                                 ++i;
300                         }
301                         return false;
302                 }
303         }
304         return inherited::info(inf);
305 }
306
307 int mul::degree(const ex & s) const
308 {
309         // Sum up degrees of factors
310         int deg_sum = 0;
311         epvector::const_iterator i = seq.begin(), end = seq.end();
312         while (i != end) {
313                 if (ex_to<numeric>(i->coeff).is_integer())
314                         deg_sum += i->rest.degree(s) * ex_to<numeric>(i->coeff).to_int();
315                 ++i;
316         }
317         return deg_sum;
318 }
319
320 int mul::ldegree(const ex & s) const
321 {
322         // Sum up degrees of factors
323         int deg_sum = 0;
324         epvector::const_iterator i = seq.begin(), end = seq.end();
325         while (i != end) {
326                 if (ex_to<numeric>(i->coeff).is_integer())
327                         deg_sum += i->rest.ldegree(s) * ex_to<numeric>(i->coeff).to_int();
328                 ++i;
329         }
330         return deg_sum;
331 }
332
333 ex mul::coeff(const ex & s, int n) const
334 {
335         exvector coeffseq;
336         coeffseq.reserve(seq.size()+1);
337         
338         if (n==0) {
339                 // product of individual coeffs
340                 // if a non-zero power of s is found, the resulting product will be 0
341                 epvector::const_iterator i = seq.begin(), end = seq.end();
342                 while (i != end) {
343                         coeffseq.push_back(recombine_pair_to_ex(*i).coeff(s,n));
344                         ++i;
345                 }
346                 coeffseq.push_back(overall_coeff);
347                 return (new mul(coeffseq))->setflag(status_flags::dynallocated);
348         }
349         
350         epvector::const_iterator i = seq.begin(), end = seq.end();
351         bool coeff_found = false;
352         while (i != end) {
353                 ex t = recombine_pair_to_ex(*i);
354                 ex c = t.coeff(s, n);
355                 if (!c.is_zero()) {
356                         coeffseq.push_back(c);
357                         coeff_found = 1;
358                 } else {
359                         coeffseq.push_back(t);
360                 }
361                 ++i;
362         }
363         if (coeff_found) {
364                 coeffseq.push_back(overall_coeff);
365                 return (new mul(coeffseq))->setflag(status_flags::dynallocated);
366         }
367         
368         return _ex0;
369 }
370
371 /** Perform automatic term rewriting rules in this class.  In the following
372  *  x, x1, x2,... stand for a symbolic variables of type ex and c, c1, c2...
373  *  stand for such expressions that contain a plain number.
374  *  - *(...,x;0) -> 0
375  *  - *(+(x1,x2,...);c) -> *(+(*(x1,c),*(x2,c),...))
376  *  - *(x;1) -> x
377  *  - *(;c) -> c
378  *
379  *  @param level cut-off in recursive evaluation */
380 ex mul::eval(int level) const
381 {
382         epvector *evaled_seqp = evalchildren(level);
383         if (evaled_seqp) {
384                 // do more evaluation later
385                 return (new mul(evaled_seqp,overall_coeff))->
386                            setflag(status_flags::dynallocated);
387         }
388         
389 #ifdef DO_GINAC_ASSERT
390         epvector::const_iterator i = seq.begin(), end = seq.end();
391         while (i != end) {
392                 GINAC_ASSERT((!is_exactly_a<mul>(i->rest)) ||
393                              (!(ex_to<numeric>(i->coeff).is_integer())));
394                 GINAC_ASSERT(!(i->is_canonical_numeric()));
395                 if (is_ex_exactly_of_type(recombine_pair_to_ex(*i), numeric))
396                     print(print_tree(std::cerr));
397                 GINAC_ASSERT(!is_exactly_a<numeric>(recombine_pair_to_ex(*i)));
398                 /* for paranoia */
399                 expair p = split_ex_to_pair(recombine_pair_to_ex(*i));
400                 GINAC_ASSERT(p.rest.is_equal(i->rest));
401                 GINAC_ASSERT(p.coeff.is_equal(i->coeff));
402                 /* end paranoia */
403                 ++i;
404         }
405 #endif // def DO_GINAC_ASSERT
406         
407         if (flags & status_flags::evaluated) {
408                 GINAC_ASSERT(seq.size()>0);
409                 GINAC_ASSERT(seq.size()>1 || !overall_coeff.is_equal(_ex1));
410                 return *this;
411         }
412         
413         int seq_size = seq.size();
414         if (overall_coeff.is_zero()) {
415                 // *(...,x;0) -> 0
416                 return _ex0;
417         } else if (seq_size==0) {
418                 // *(;c) -> c
419                 return overall_coeff;
420         } else if (seq_size==1 && overall_coeff.is_equal(_ex1)) {
421                 // *(x;1) -> x
422                 return recombine_pair_to_ex(*(seq.begin()));
423         } else if ((seq_size==1) &&
424                    is_ex_exactly_of_type((*seq.begin()).rest,add) &&
425                    ex_to<numeric>((*seq.begin()).coeff).is_equal(_num1)) {
426                 // *(+(x,y,...);c) -> +(*(x,c),*(y,c),...) (c numeric(), no powers of +())
427                 const add & addref = ex_to<add>((*seq.begin()).rest);
428                 epvector *distrseq = new epvector();
429                 distrseq->reserve(addref.seq.size());
430                 epvector::const_iterator i = addref.seq.begin(), end = addref.seq.end();
431                 while (i != end) {
432                         distrseq->push_back(addref.combine_pair_with_coeff_to_pair(*i, overall_coeff));
433                         ++i;
434                 }
435                 return (new add(distrseq,
436                                 ex_to<numeric>(addref.overall_coeff).
437                                 mul_dyn(ex_to<numeric>(overall_coeff))))
438                       ->setflag(status_flags::dynallocated | status_flags::evaluated);
439         }
440         return this->hold();
441 }
442
443 ex mul::evalf(int level) const
444 {
445         if (level==1)
446                 return mul(seq,overall_coeff);
447         
448         if (level==-max_recursion_level)
449                 throw(std::runtime_error("max recursion level reached"));
450         
451         epvector *s = new epvector();
452         s->reserve(seq.size());
453
454         --level;
455         epvector::const_iterator i = seq.begin(), end = seq.end();
456         while (i != end) {
457                 s->push_back(combine_ex_with_coeff_to_pair(i->rest.evalf(level),
458                                                            i->coeff));
459                 ++i;
460         }
461         return mul(s, overall_coeff.evalf(level));
462 }
463
464 ex mul::evalm(void) const
465 {
466         // numeric*matrix
467         if (seq.size() == 1 && seq[0].coeff.is_equal(_ex1)
468          && is_ex_of_type(seq[0].rest, matrix))
469                 return ex_to<matrix>(seq[0].rest).mul(ex_to<numeric>(overall_coeff));
470
471         // Evaluate children first, look whether there are any matrices at all
472         // (there can be either no matrices or one matrix; if there were more
473         // than one matrix, it would be a non-commutative product)
474         epvector *s = new epvector;
475         s->reserve(seq.size());
476
477         bool have_matrix = false;
478         epvector::iterator the_matrix;
479
480         epvector::const_iterator i = seq.begin(), end = seq.end();
481         while (i != end) {
482                 const ex &m = recombine_pair_to_ex(*i).evalm();
483                 s->push_back(split_ex_to_pair(m));
484                 if (is_ex_of_type(m, matrix)) {
485                         have_matrix = true;
486                         the_matrix = s->end() - 1;
487                 }
488                 ++i;
489         }
490
491         if (have_matrix) {
492
493                 // The product contained a matrix. We will multiply all other factors
494                 // into that matrix.
495                 matrix m = ex_to<matrix>(the_matrix->rest);
496                 s->erase(the_matrix);
497                 ex scalar = (new mul(s, overall_coeff))->setflag(status_flags::dynallocated);
498                 return m.mul_scalar(scalar);
499
500         } else
501                 return (new mul(s, overall_coeff))->setflag(status_flags::dynallocated);
502 }
503
504 ex mul::simplify_ncmul(const exvector & v) const
505 {
506         if (seq.empty())
507                 return inherited::simplify_ncmul(v);
508
509         // Find first noncommutative element and call its simplify_ncmul()
510         epvector::const_iterator i = seq.begin(), end = seq.end();
511         while (i != end) {
512                 if (i->rest.return_type() == return_types::noncommutative)
513                         return i->rest.simplify_ncmul(v);
514                 ++i;
515         }
516         return inherited::simplify_ncmul(v);
517 }
518
519 // protected
520
521 /** Implementation of ex::diff() for a product.  It applies the product rule.
522  *  @see ex::diff */
523 ex mul::derivative(const symbol & s) const
524 {
525         unsigned num = seq.size();
526         exvector addseq;
527         addseq.reserve(num);
528         
529         // D(a*b*c) = D(a)*b*c + a*D(b)*c + a*b*D(c)
530         epvector mulseq = seq;
531         epvector::const_iterator i = seq.begin(), end = seq.end();
532         epvector::iterator i2 = mulseq.begin();
533         while (i != end) {
534                 expair ep = split_ex_to_pair(power(i->rest, i->coeff - _ex1) *
535                                              i->rest.diff(s));
536                 ep.swap(*i2);
537                 addseq.push_back((new mul(mulseq, overall_coeff * i->coeff))->setflag(status_flags::dynallocated));
538                 ep.swap(*i2);
539                 ++i; ++i2;
540         }
541         return (new add(addseq))->setflag(status_flags::dynallocated);
542 }
543
544 int mul::compare_same_type(const basic & other) const
545 {
546         return inherited::compare_same_type(other);
547 }
548
549 bool mul::is_equal_same_type(const basic & other) const
550 {
551         return inherited::is_equal_same_type(other);
552 }
553
554 unsigned mul::return_type(void) const
555 {
556         if (seq.empty()) {
557                 // mul without factors: should not happen, but commutes
558                 return return_types::commutative;
559         }
560         
561         bool all_commutative = true;
562         epvector::const_iterator noncommutative_element; // point to first found nc element
563         
564         epvector::const_iterator i = seq.begin(), end = seq.end();
565         while (i != end) {
566                 unsigned rt = i->rest.return_type();
567                 if (rt == return_types::noncommutative_composite)
568                         return rt; // one ncc -> mul also ncc
569                 if ((rt == return_types::noncommutative) && (all_commutative)) {
570                         // first nc element found, remember position
571                         noncommutative_element = i;
572                         all_commutative = false;
573                 }
574                 if ((rt == return_types::noncommutative) && (!all_commutative)) {
575                         // another nc element found, compare type_infos
576                         if (noncommutative_element->rest.return_type_tinfo() != i->rest.return_type_tinfo()) {
577                                 // diffent types -> mul is ncc
578                                 return return_types::noncommutative_composite;
579                         }
580                 }
581                 ++i;
582         }
583         // all factors checked
584         return all_commutative ? return_types::commutative : return_types::noncommutative;
585 }
586    
587 unsigned mul::return_type_tinfo(void) const
588 {
589         if (seq.empty())
590                 return tinfo_key;  // mul without factors: should not happen
591         
592         // return type_info of first noncommutative element
593         epvector::const_iterator i = seq.begin(), end = seq.end();
594         while (i != end) {
595                 if (i->rest.return_type() == return_types::noncommutative)
596                         return i->rest.return_type_tinfo();
597                 ++i;
598         }
599         // no noncommutative element found, should not happen
600         return tinfo_key;
601 }
602
603 ex mul::thisexpairseq(const epvector & v, const ex & oc) const
604 {
605         return (new mul(v, oc))->setflag(status_flags::dynallocated);
606 }
607
608 ex mul::thisexpairseq(epvector * vp, const ex & oc) const
609 {
610         return (new mul(vp, oc))->setflag(status_flags::dynallocated);
611 }
612
613 expair mul::split_ex_to_pair(const ex & e) const
614 {
615         if (is_ex_exactly_of_type(e,power)) {
616                 const power & powerref = ex_to<power>(e);
617                 if (is_ex_exactly_of_type(powerref.exponent,numeric))
618                         return expair(powerref.basis,powerref.exponent);
619         }
620         return expair(e,_ex1);
621 }
622         
623 expair mul::combine_ex_with_coeff_to_pair(const ex & e,
624                                           const ex & c) const
625 {
626         // to avoid duplication of power simplification rules,
627         // we create a temporary power object
628         // otherwise it would be hard to correctly simplify
629         // expression like (4^(1/3))^(3/2)
630         if (are_ex_trivially_equal(c,_ex1))
631                 return split_ex_to_pair(e);
632         
633         return split_ex_to_pair(power(e,c));
634 }
635         
636 expair mul::combine_pair_with_coeff_to_pair(const expair & p,
637                                             const ex & c) const
638 {
639         // to avoid duplication of power simplification rules,
640         // we create a temporary power object
641         // otherwise it would be hard to correctly simplify
642         // expression like (4^(1/3))^(3/2)
643         if (are_ex_trivially_equal(c,_ex1))
644                 return p;
645         
646         return split_ex_to_pair(power(recombine_pair_to_ex(p),c));
647 }
648         
649 ex mul::recombine_pair_to_ex(const expair & p) const
650 {
651         if (ex_to<numeric>(p.coeff).is_equal(_num1)) 
652                 return p.rest;
653         else
654                 return power(p.rest,p.coeff);
655 }
656
657 bool mul::expair_needs_further_processing(epp it)
658 {
659         if (is_ex_exactly_of_type((*it).rest,mul) &&
660                 ex_to<numeric>((*it).coeff).is_integer()) {
661                 // combined pair is product with integer power -> expand it
662                 *it = split_ex_to_pair(recombine_pair_to_ex(*it));
663                 return true;
664         }
665         if (is_ex_exactly_of_type((*it).rest,numeric)) {
666                 expair ep=split_ex_to_pair(recombine_pair_to_ex(*it));
667                 if (!ep.is_equal(*it)) {
668                         // combined pair is a numeric power which can be simplified
669                         *it = ep;
670                         return true;
671                 }
672                 if (ex_to<numeric>((*it).coeff).is_equal(_num1)) {
673                         // combined pair has coeff 1 and must be moved to the end
674                         return true;
675                 }
676         }
677         return false;
678 }       
679
680 ex mul::default_overall_coeff(void) const
681 {
682         return _ex1;
683 }
684
685 void mul::combine_overall_coeff(const ex & c)
686 {
687         GINAC_ASSERT(is_exactly_a<numeric>(overall_coeff));
688         GINAC_ASSERT(is_exactly_a<numeric>(c));
689         overall_coeff = ex_to<numeric>(overall_coeff).mul_dyn(ex_to<numeric>(c));
690 }
691
692 void mul::combine_overall_coeff(const ex & c1, const ex & c2)
693 {
694         GINAC_ASSERT(is_exactly_a<numeric>(overall_coeff));
695         GINAC_ASSERT(is_exactly_a<numeric>(c1));
696         GINAC_ASSERT(is_exactly_a<numeric>(c2));
697         overall_coeff = ex_to<numeric>(overall_coeff).mul_dyn(ex_to<numeric>(c1).power(ex_to<numeric>(c2)));
698 }
699
700 bool mul::can_make_flat(const expair & p) const
701 {
702         GINAC_ASSERT(is_exactly_a<numeric>(p.coeff));
703         // this assertion will probably fail somewhere
704         // it would require a more careful make_flat, obeying the power laws
705         // probably should return true only if p.coeff is integer
706         return ex_to<numeric>(p.coeff).is_equal(_num1);
707 }
708
709 ex mul::expand(unsigned options) const
710 {
711         // First, expand the children
712         epvector * expanded_seqp = expandchildren(options);
713         const epvector & expanded_seq = (expanded_seqp == NULL) ? seq : *expanded_seqp;
714
715         // Now, look for all the factors that are sums and multiply each one out
716         // with the next one that is found while collecting the factors which are
717         // not sums
718         int number_of_adds = 0;
719         ex last_expanded = _ex1;
720         epvector non_adds;
721         non_adds.reserve(expanded_seq.size());
722         epvector::const_iterator cit = expanded_seq.begin(), last = expanded_seq.end();
723         while (cit != last) {
724                 if (is_ex_exactly_of_type(cit->rest, add) &&
725                         (cit->coeff.is_equal(_ex1))) {
726                         ++number_of_adds;
727                         if (is_ex_exactly_of_type(last_expanded, add)) {
728 #if 0
729                                 // Expand a product of two sums, simple and robust version.
730                                 const add & add1 = ex_to<add>(last_expanded);
731                                 const add & add2 = ex_to<add>(cit->rest);
732                                 const int n1 = add1.nops();
733                                 const int n2 = add2.nops();
734                                 ex tmp_accu;
735                                 exvector distrseq;
736                                 distrseq.reserve(n2);
737                                 for (int i1=0; i1<n1; ++i1) {
738                                         distrseq.clear();
739                                         // cache the first operand (for efficiency):
740                                         const ex op1 = add1.op(i1);
741                                         for (int i2=0; i2<n2; ++i2)
742                                                 distrseq.push_back(op1 * add2.op(i2));
743                                         tmp_accu += (new add(distrseq))->
744                                                      setflag(status_flags::dynallocated);
745                                 }
746                                 last_expanded = tmp_accu;
747 #else
748                                 // Expand a product of two sums, aggressive version.
749                                 // Caring for the overall coefficients in separate loops can
750                                 // sometimes give a performance gain of up to 15%!
751
752                                 const int sizedifference = ex_to<add>(last_expanded).seq.size()-ex_to<add>(cit->rest).seq.size();
753                                 // add2 is for the inner loop and should be the bigger of the two sums
754                                 // in the presence of asymptotically good sorting:
755                                 const add& add1 = (sizedifference<0 ? ex_to<add>(last_expanded) : ex_to<add>(cit->rest));
756                                 const add& add2 = (sizedifference<0 ? ex_to<add>(cit->rest) : ex_to<add>(last_expanded));
757                                 const epvector::const_iterator add1begin = add1.seq.begin();
758                                 const epvector::const_iterator add1end   = add1.seq.end();
759                                 const epvector::const_iterator add2begin = add2.seq.begin();
760                                 const epvector::const_iterator add2end   = add2.seq.end();
761                                 epvector distrseq;
762                                 distrseq.reserve(add1.seq.size()+add2.seq.size());
763                                 // Multiply add2 with the overall coefficient of add1 and append it to distrseq:
764                                 if (!add1.overall_coeff.is_zero()) {
765                                         if (add1.overall_coeff.is_equal(_ex1))
766                                                 distrseq.insert(distrseq.end(),add2begin,add2end);
767                                         else
768                                                 for (epvector::const_iterator i=add2begin; i!=add2end; ++i)
769                                                         distrseq.push_back(expair(i->rest, ex_to<numeric>(i->coeff).mul_dyn(ex_to<numeric>(add1.overall_coeff))));
770                                 }
771                                 // Multiply add1 with the overall coefficient of add2 and append it to distrseq:
772                                 if (!add2.overall_coeff.is_zero()) {
773                                         if (add2.overall_coeff.is_equal(_ex1))
774                                                 distrseq.insert(distrseq.end(),add1begin,add1end);
775                                         else
776                                                 for (epvector::const_iterator i=add1begin; i!=add1end; ++i)
777                                                         distrseq.push_back(expair(i->rest, ex_to<numeric>(i->coeff).mul_dyn(ex_to<numeric>(add2.overall_coeff))));
778                                 }
779                                 // Compute the new overall coefficient and put it together:
780                                 ex tmp_accu = (new add(distrseq, add1.overall_coeff*add2.overall_coeff))->setflag(status_flags::dynallocated);
781                                 // Multiply explicitly all non-numeric terms of add1 and add2:
782                                 for (epvector::const_iterator i1=add1begin; i1!=add1end; ++i1) {
783                                         // We really have to combine terms here in order to compactify
784                                         // the result.  Otherwise it would become waayy tooo bigg.
785                                         numeric oc;
786                                         distrseq.clear();
787                                         for (epvector::const_iterator i2=add2begin; i2!=add2end; ++i2) {
788                                                 // Don't push_back expairs which might have a rest that evaluates to a numeric,
789                                                 // since that would violate an invariant of expairseq:
790                                                 const ex rest = (new mul(i1->rest, i2->rest))->setflag(status_flags::dynallocated);
791                                                 if (is_ex_exactly_of_type(rest, numeric))
792                                                         oc += ex_to<numeric>(rest).mul(ex_to<numeric>(i1->coeff).mul(ex_to<numeric>(i2->coeff)));
793                                                 else
794                                                         distrseq.push_back(expair(rest, ex_to<numeric>(i1->coeff).mul_dyn(ex_to<numeric>(i2->coeff))));
795                                         }
796                                         tmp_accu += (new add(distrseq, oc))->setflag(status_flags::dynallocated);
797                                 }
798                                 last_expanded = tmp_accu;
799 #endif
800                         } else {
801                                 non_adds.push_back(split_ex_to_pair(last_expanded));
802                                 last_expanded = cit->rest;
803                         }
804                 } else {
805                         non_adds.push_back(*cit);
806                 }
807                 ++cit;
808         }
809         if (expanded_seqp)
810                 delete expanded_seqp;
811         
812         // Now the only remaining thing to do is to multiply the factors which
813         // were not sums into the "last_expanded" sum
814         if (is_ex_exactly_of_type(last_expanded, add)) {
815                 const add & finaladd = ex_to<add>(last_expanded);
816                 exvector distrseq;
817                 int n = finaladd.nops();
818                 distrseq.reserve(n);
819                 for (int i=0; i<n; ++i) {
820                         epvector factors = non_adds;
821                         factors.push_back(split_ex_to_pair(finaladd.op(i)));
822                         distrseq.push_back((new mul(factors, overall_coeff))->
823                                             setflag(status_flags::dynallocated | (options == 0 ? status_flags::expanded : 0)));
824                 }
825                 return ((new add(distrseq))->
826                         setflag(status_flags::dynallocated | (options == 0 ? status_flags::expanded : 0)));
827         }
828         non_adds.push_back(split_ex_to_pair(last_expanded));
829         return (new mul(non_adds, overall_coeff))->
830                 setflag(status_flags::dynallocated | (options == 0 ? status_flags::expanded : 0));
831 }
832
833   
834 //////////
835 // new virtual functions which can be overridden by derived classes
836 //////////
837
838 // none
839
840 //////////
841 // non-virtual functions in this class
842 //////////
843
844
845 /** Member-wise expand the expairs representing this sequence.  This must be
846  *  overridden from expairseq::expandchildren() and done iteratively in order
847  *  to allow for early cancallations and thus safe memory.
848  *
849  *  @see mul::expand()
850  *  @return pointer to epvector containing expanded representation or zero
851  *  pointer, if sequence is unchanged. */
852 epvector * mul::expandchildren(unsigned options) const
853 {
854         const epvector::const_iterator last = seq.end();
855         epvector::const_iterator cit = seq.begin();
856         while (cit!=last) {
857                 const ex & factor = recombine_pair_to_ex(*cit);
858                 const ex & expanded_factor = factor.expand(options);
859                 if (!are_ex_trivially_equal(factor,expanded_factor)) {
860                         
861                         // something changed, copy seq, eval and return it
862                         epvector *s = new epvector;
863                         s->reserve(seq.size());
864                         
865                         // copy parts of seq which are known not to have changed
866                         epvector::const_iterator cit2 = seq.begin();
867                         while (cit2!=cit) {
868                                 s->push_back(*cit2);
869                                 ++cit2;
870                         }
871                         // copy first changed element
872                         s->push_back(split_ex_to_pair(expanded_factor));
873                         ++cit2;
874                         // copy rest
875                         while (cit2!=last) {
876                                 s->push_back(split_ex_to_pair(recombine_pair_to_ex(*cit2).expand(options)));
877                                 ++cit2;
878                         }
879                         return s;
880                 }
881                 ++cit;
882         }
883         
884         return 0; // nothing has changed
885 }
886
887 } // namespace GiNaC