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