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