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