3 * Implementation of GiNaC's products of expressions. */
6 * GiNaC Copyright (C) 1999-2008 Johannes Gutenberg University Mainz, Germany
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.
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.
18 * You should have received a copy of the GNU General Public License
19 * along with this program; if not, write to the Free Software
20 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
31 #include "operators.h"
42 GINAC_IMPLEMENT_REGISTERED_CLASS_OPT(mul, expairseq,
43 print_func<print_context>(&mul::do_print).
44 print_func<print_latex>(&mul::do_print_latex).
45 print_func<print_csrc>(&mul::do_print_csrc).
46 print_func<print_tree>(&mul::do_print_tree).
47 print_func<print_python_repr>(&mul::do_print_python_repr))
51 // default constructor
56 tinfo_key = &mul::tinfo_static;
65 mul::mul(const ex & lh, const ex & rh)
67 tinfo_key = &mul::tinfo_static;
69 construct_from_2_ex(lh,rh);
70 GINAC_ASSERT(is_canonical());
73 mul::mul(const exvector & v)
75 tinfo_key = &mul::tinfo_static;
77 construct_from_exvector(v);
78 GINAC_ASSERT(is_canonical());
81 mul::mul(const epvector & v)
83 tinfo_key = &mul::tinfo_static;
85 construct_from_epvector(v);
86 GINAC_ASSERT(is_canonical());
89 mul::mul(const epvector & v, const ex & oc, bool do_index_renaming)
91 tinfo_key = &mul::tinfo_static;
93 construct_from_epvector(v, do_index_renaming);
94 GINAC_ASSERT(is_canonical());
97 mul::mul(std::auto_ptr<epvector> vp, const ex & oc, bool do_index_renaming)
99 tinfo_key = &mul::tinfo_static;
100 GINAC_ASSERT(vp.get()!=0);
102 construct_from_epvector(*vp, do_index_renaming);
103 GINAC_ASSERT(is_canonical());
106 mul::mul(const ex & lh, const ex & mh, const ex & rh)
108 tinfo_key = &mul::tinfo_static;
111 factors.push_back(lh);
112 factors.push_back(mh);
113 factors.push_back(rh);
114 overall_coeff = _ex1;
115 construct_from_exvector(factors);
116 GINAC_ASSERT(is_canonical());
123 DEFAULT_ARCHIVING(mul)
126 // functions overriding virtual functions from base classes
129 void mul::print_overall_coeff(const print_context & c, const char *mul_sym) const
131 const numeric &coeff = ex_to<numeric>(overall_coeff);
132 if (coeff.csgn() == -1)
134 if (!coeff.is_equal(*_num1_p) &&
135 !coeff.is_equal(*_num_1_p)) {
136 if (coeff.is_rational()) {
137 if (coeff.is_negative())
142 if (coeff.csgn() == -1)
143 (-coeff).print(c, precedence());
145 coeff.print(c, precedence());
151 void mul::do_print(const print_context & c, unsigned level) const
153 if (precedence() <= level)
156 print_overall_coeff(c, "*");
158 epvector::const_iterator it = seq.begin(), itend = seq.end();
160 while (it != itend) {
165 recombine_pair_to_ex(*it).print(c, precedence());
169 if (precedence() <= level)
173 void mul::do_print_latex(const print_latex & c, unsigned level) const
175 if (precedence() <= level)
178 print_overall_coeff(c, " ");
180 // Separate factors into those with negative numeric exponent
182 epvector::const_iterator it = seq.begin(), itend = seq.end();
183 exvector neg_powers, others;
184 while (it != itend) {
185 GINAC_ASSERT(is_exactly_a<numeric>(it->coeff));
186 if (ex_to<numeric>(it->coeff).is_negative())
187 neg_powers.push_back(recombine_pair_to_ex(expair(it->rest, -(it->coeff))));
189 others.push_back(recombine_pair_to_ex(*it));
193 if (!neg_powers.empty()) {
195 // Factors with negative exponent are printed as a fraction
197 mul(others).eval().print(c);
199 mul(neg_powers).eval().print(c);
204 // All other factors are printed in the ordinary way
205 exvector::const_iterator vit = others.begin(), vitend = others.end();
206 while (vit != vitend) {
208 vit->print(c, precedence());
213 if (precedence() <= level)
217 void mul::do_print_csrc(const print_csrc & c, unsigned level) const
219 if (precedence() <= level)
222 if (!overall_coeff.is_equal(_ex1)) {
223 if (overall_coeff.is_equal(_ex_1))
226 overall_coeff.print(c, precedence());
231 // Print arguments, separated by "*" or "/"
232 epvector::const_iterator it = seq.begin(), itend = seq.end();
233 while (it != itend) {
235 // If the first argument is a negative integer power, it gets printed as "1.0/<expr>"
236 bool needclosingparenthesis = false;
237 if (it == seq.begin() && it->coeff.info(info_flags::negint)) {
238 if (is_a<print_csrc_cl_N>(c)) {
240 needclosingparenthesis = true;
245 // If the exponent is 1 or -1, it is left out
246 if (it->coeff.is_equal(_ex1) || it->coeff.is_equal(_ex_1))
247 it->rest.print(c, precedence());
248 else if (it->coeff.info(info_flags::negint))
249 // Outer parens around ex needed for broken GCC parser:
250 (ex(power(it->rest, -ex_to<numeric>(it->coeff)))).print(c, level);
252 // Outer parens around ex needed for broken GCC parser:
253 (ex(power(it->rest, ex_to<numeric>(it->coeff)))).print(c, level);
255 if (needclosingparenthesis)
258 // Separator is "/" for negative integer powers, "*" otherwise
261 if (it->coeff.info(info_flags::negint))
268 if (precedence() <= level)
272 void mul::do_print_python_repr(const print_python_repr & c, unsigned level) const
274 c.s << class_name() << '(';
276 for (size_t i=1; i<nops(); ++i) {
283 bool mul::info(unsigned inf) const
286 case info_flags::polynomial:
287 case info_flags::integer_polynomial:
288 case info_flags::cinteger_polynomial:
289 case info_flags::rational_polynomial:
290 case info_flags::crational_polynomial:
291 case info_flags::rational_function: {
292 epvector::const_iterator i = seq.begin(), end = seq.end();
294 if (!(recombine_pair_to_ex(*i).info(inf)))
298 return overall_coeff.info(inf);
300 case info_flags::algebraic: {
301 epvector::const_iterator i = seq.begin(), end = seq.end();
303 if ((recombine_pair_to_ex(*i).info(inf)))
310 return inherited::info(inf);
313 int mul::degree(const ex & s) const
315 // Sum up degrees of factors
317 epvector::const_iterator i = seq.begin(), end = seq.end();
319 if (ex_to<numeric>(i->coeff).is_integer())
320 deg_sum += recombine_pair_to_ex(*i).degree(s);
323 throw std::runtime_error("mul::degree() undefined degree because of non-integer exponent");
330 int mul::ldegree(const ex & s) const
332 // Sum up degrees of factors
334 epvector::const_iterator i = seq.begin(), end = seq.end();
336 if (ex_to<numeric>(i->coeff).is_integer())
337 deg_sum += recombine_pair_to_ex(*i).ldegree(s);
340 throw std::runtime_error("mul::ldegree() undefined degree because of non-integer exponent");
347 ex mul::coeff(const ex & s, int n) const
350 coeffseq.reserve(seq.size()+1);
353 // product of individual coeffs
354 // if a non-zero power of s is found, the resulting product will be 0
355 epvector::const_iterator i = seq.begin(), end = seq.end();
357 coeffseq.push_back(recombine_pair_to_ex(*i).coeff(s,n));
360 coeffseq.push_back(overall_coeff);
361 return (new mul(coeffseq))->setflag(status_flags::dynallocated);
364 epvector::const_iterator i = seq.begin(), end = seq.end();
365 bool coeff_found = false;
367 ex t = recombine_pair_to_ex(*i);
368 ex c = t.coeff(s, n);
370 coeffseq.push_back(c);
373 coeffseq.push_back(t);
378 coeffseq.push_back(overall_coeff);
379 return (new mul(coeffseq))->setflag(status_flags::dynallocated);
385 /** Perform automatic term rewriting rules in this class. In the following
386 * x, x1, x2,... stand for a symbolic variables of type ex and c, c1, c2...
387 * stand for such expressions that contain a plain number.
389 * - *(+(x1,x2,...);c) -> *(+(*(x1,c),*(x2,c),...))
393 * @param level cut-off in recursive evaluation */
394 ex mul::eval(int level) const
396 std::auto_ptr<epvector> evaled_seqp = evalchildren(level);
397 if (evaled_seqp.get()) {
398 // do more evaluation later
399 return (new mul(evaled_seqp, overall_coeff))->
400 setflag(status_flags::dynallocated);
403 #ifdef DO_GINAC_ASSERT
404 epvector::const_iterator i = seq.begin(), end = seq.end();
406 GINAC_ASSERT((!is_exactly_a<mul>(i->rest)) ||
407 (!(ex_to<numeric>(i->coeff).is_integer())));
408 GINAC_ASSERT(!(i->is_canonical_numeric()));
409 if (is_exactly_a<numeric>(recombine_pair_to_ex(*i)))
410 print(print_tree(std::cerr));
411 GINAC_ASSERT(!is_exactly_a<numeric>(recombine_pair_to_ex(*i)));
413 expair p = split_ex_to_pair(recombine_pair_to_ex(*i));
414 GINAC_ASSERT(p.rest.is_equal(i->rest));
415 GINAC_ASSERT(p.coeff.is_equal(i->coeff));
419 #endif // def DO_GINAC_ASSERT
421 if (flags & status_flags::evaluated) {
422 GINAC_ASSERT(seq.size()>0);
423 GINAC_ASSERT(seq.size()>1 || !overall_coeff.is_equal(_ex1));
427 size_t seq_size = seq.size();
428 if (overall_coeff.is_zero()) {
431 } else if (seq_size==0) {
433 return overall_coeff;
434 } else if (seq_size==1 && overall_coeff.is_equal(_ex1)) {
436 return recombine_pair_to_ex(*(seq.begin()));
437 } else if ((seq_size==1) &&
438 is_exactly_a<add>((*seq.begin()).rest) &&
439 ex_to<numeric>((*seq.begin()).coeff).is_equal(*_num1_p)) {
440 // *(+(x,y,...);c) -> +(*(x,c),*(y,c),...) (c numeric(), no powers of +())
441 const add & addref = ex_to<add>((*seq.begin()).rest);
442 std::auto_ptr<epvector> distrseq(new epvector);
443 distrseq->reserve(addref.seq.size());
444 epvector::const_iterator i = addref.seq.begin(), end = addref.seq.end();
446 distrseq->push_back(addref.combine_pair_with_coeff_to_pair(*i, overall_coeff));
449 return (new add(distrseq,
450 ex_to<numeric>(addref.overall_coeff).
451 mul_dyn(ex_to<numeric>(overall_coeff)))
452 )->setflag(status_flags::dynallocated | status_flags::evaluated);
453 } else if ((seq_size >= 2) && (! (flags & status_flags::expanded))) {
454 // Strip the content and the unit part from each term. Thus
455 // things like (-x+a)*(3*x-3*a) automagically turn into - 3*(x-a)2
457 epvector::const_iterator last = seq.end();
458 epvector::const_iterator i = seq.begin();
459 epvector::const_iterator j = seq.begin();
460 std::auto_ptr<epvector> s(new epvector);
461 numeric oc = *_num1_p;
462 bool something_changed = false;
464 if (likely(! (is_a<add>(i->rest) && i->coeff.is_equal(_ex1)))) {
465 // power::eval has such a rule, no need to handle powers here
470 // XXX: What is the best way to check if the polynomial is a primitive?
471 numeric c = i->rest.integer_content();
472 const numeric lead_coeff =
473 ex_to<numeric>(ex_to<add>(i->rest).seq.begin()->coeff).div(c);
474 const bool canonicalizable = lead_coeff.is_integer();
476 // XXX: The main variable is chosen in a random way, so this code
477 // does NOT transform the term into the canonical form (thus, in some
478 // very unlucky event it can even loop forever). Hopefully the main
479 // variable will be the same for all terms in *this
480 const bool unit_normal = lead_coeff.is_pos_integer();
481 if (likely((c == *_num1_p) && ((! canonicalizable) || unit_normal))) {
486 if (! something_changed) {
487 s->reserve(seq_size);
488 something_changed = true;
491 while ((j!=i) && (j!=last)) {
497 c = c.mul(*_num_1_p);
501 // divide add by the number in place to save at least 2 .eval() calls
502 const add& addref = ex_to<add>(i->rest);
503 add* primitive = new add(addref);
504 primitive->setflag(status_flags::dynallocated);
505 primitive->clearflag(status_flags::hash_calculated);
506 primitive->overall_coeff = ex_to<numeric>(primitive->overall_coeff).div_dyn(c);
507 for (epvector::iterator ai = primitive->seq.begin();
508 ai != primitive->seq.end(); ++ai)
509 ai->coeff = ex_to<numeric>(ai->coeff).div_dyn(c);
511 s->push_back(expair(*primitive, _ex1));
516 if (something_changed) {
521 return (new mul(s, ex_to<numeric>(overall_coeff).mul_dyn(oc))
522 )->setflag(status_flags::dynallocated);
529 ex mul::evalf(int level) const
532 return mul(seq,overall_coeff);
534 if (level==-max_recursion_level)
535 throw(std::runtime_error("max recursion level reached"));
537 std::auto_ptr<epvector> s(new epvector);
538 s->reserve(seq.size());
541 epvector::const_iterator i = seq.begin(), end = seq.end();
543 s->push_back(combine_ex_with_coeff_to_pair(i->rest.evalf(level),
547 return mul(s, overall_coeff.evalf(level));
550 void mul::find_real_imag(ex & rp, ex & ip) const
552 rp = overall_coeff.real_part();
553 ip = overall_coeff.imag_part();
554 for (epvector::const_iterator i=seq.begin(); i!=seq.end(); ++i) {
555 ex factor = recombine_pair_to_ex(*i);
556 ex new_rp = factor.real_part();
557 ex new_ip = factor.imag_part();
558 if(new_ip.is_zero()) {
562 ex temp = rp*new_rp - ip*new_ip;
563 ip = ip*new_rp + rp*new_ip;
571 ex mul::real_part() const
574 find_real_imag(rp, ip);
578 ex mul::imag_part() const
581 find_real_imag(rp, ip);
585 ex mul::evalm() const
588 if (seq.size() == 1 && seq[0].coeff.is_equal(_ex1)
589 && is_a<matrix>(seq[0].rest))
590 return ex_to<matrix>(seq[0].rest).mul(ex_to<numeric>(overall_coeff));
592 // Evaluate children first, look whether there are any matrices at all
593 // (there can be either no matrices or one matrix; if there were more
594 // than one matrix, it would be a non-commutative product)
595 std::auto_ptr<epvector> s(new epvector);
596 s->reserve(seq.size());
598 bool have_matrix = false;
599 epvector::iterator the_matrix;
601 epvector::const_iterator i = seq.begin(), end = seq.end();
603 const ex &m = recombine_pair_to_ex(*i).evalm();
604 s->push_back(split_ex_to_pair(m));
605 if (is_a<matrix>(m)) {
607 the_matrix = s->end() - 1;
614 // The product contained a matrix. We will multiply all other factors
616 matrix m = ex_to<matrix>(the_matrix->rest);
617 s->erase(the_matrix);
618 ex scalar = (new mul(s, overall_coeff))->setflag(status_flags::dynallocated);
619 return m.mul_scalar(scalar);
622 return (new mul(s, overall_coeff))->setflag(status_flags::dynallocated);
625 ex mul::eval_ncmul(const exvector & v) const
628 return inherited::eval_ncmul(v);
630 // Find first noncommutative element and call its eval_ncmul()
631 epvector::const_iterator i = seq.begin(), end = seq.end();
633 if (i->rest.return_type() == return_types::noncommutative)
634 return i->rest.eval_ncmul(v);
637 return inherited::eval_ncmul(v);
640 bool tryfactsubs(const ex & origfactor, const ex & patternfactor, int & nummatches, lst & repls)
646 if (is_exactly_a<power>(origfactor) && origfactor.op(1).info(info_flags::integer)) {
647 origbase = origfactor.op(0);
648 int expon = ex_to<numeric>(origfactor.op(1)).to_int();
649 origexponent = expon > 0 ? expon : -expon;
650 origexpsign = expon > 0 ? 1 : -1;
652 origbase = origfactor;
661 if (is_exactly_a<power>(patternfactor) && patternfactor.op(1).info(info_flags::integer)) {
662 patternbase = patternfactor.op(0);
663 int expon = ex_to<numeric>(patternfactor.op(1)).to_int();
664 patternexponent = expon > 0 ? expon : -expon;
665 patternexpsign = expon > 0 ? 1 : -1;
667 patternbase = patternfactor;
672 lst saverepls = repls;
673 if (origexponent < patternexponent || origexpsign != patternexpsign || !origbase.match(patternbase,saverepls))
677 int newnummatches = origexponent / patternexponent;
678 if (newnummatches < nummatches)
679 nummatches = newnummatches;
683 /** Checks wheter e matches to the pattern pat and the (possibly to be updated)
684 * list of replacements repls. This matching is in the sense of algebraic
685 * substitutions. Matching starts with pat.op(factor) of the pattern because
686 * the factors before this one have already been matched. The (possibly
687 * updated) number of matches is in nummatches. subsed[i] is true for factors
688 * that already have been replaced by previous substitutions and matched[i]
689 * is true for factors that have been matched by the current match.
691 bool algebraic_match_mul_with_mul(const mul &e, const ex &pat, lst &repls,
692 int factor, int &nummatches, const std::vector<bool> &subsed,
693 std::vector<bool> &matched)
695 if (factor == pat.nops())
698 for (size_t i=0; i<e.nops(); ++i) {
699 if(subsed[i] || matched[i])
701 lst newrepls = repls;
702 int newnummatches = nummatches;
703 if (tryfactsubs(e.op(i), pat.op(factor), newnummatches, newrepls)) {
705 if (algebraic_match_mul_with_mul(e, pat, newrepls, factor+1,
706 newnummatches, subsed, matched)) {
708 nummatches = newnummatches;
719 bool mul::has(const ex & pattern, unsigned options) const
721 if(!(options&has_options::algebraic))
722 return basic::has(pattern,options);
723 if(is_a<mul>(pattern)) {
725 int nummatches = std::numeric_limits<int>::max();
726 std::vector<bool> subsed(seq.size(), false);
727 std::vector<bool> matched(seq.size(), false);
728 if(algebraic_match_mul_with_mul(*this, pattern, repls, 0, nummatches,
732 return basic::has(pattern, options);
735 ex mul::algebraic_subs_mul(const exmap & m, unsigned options) const
737 std::vector<bool> subsed(seq.size(), false);
738 exvector subsresult(seq.size());
742 for (exmap::const_iterator it = m.begin(); it != m.end(); ++it) {
744 if (is_exactly_a<mul>(it->first)) {
746 int nummatches = std::numeric_limits<int>::max();
747 std::vector<bool> currsubsed(seq.size(), false);
750 if(!algebraic_match_mul_with_mul(*this, it->first, repls, 0, nummatches, subsed, currsubsed))
753 for (size_t j=0; j<subsed.size(); j++)
757 = it->first.subs(ex(repls), subs_options::no_pattern);
758 divide_by *= power(subsed_pattern, nummatches);
760 = it->second.subs(ex(repls), subs_options::no_pattern);
761 multiply_by *= power(subsed_result, nummatches);
766 for (size_t j=0; j<this->nops(); j++) {
767 int nummatches = std::numeric_limits<int>::max();
769 if (!subsed[j] && tryfactsubs(op(j), it->first, nummatches, repls)){
772 = it->first.subs(ex(repls), subs_options::no_pattern);
773 divide_by *= power(subsed_pattern, nummatches);
775 = it->second.subs(ex(repls), subs_options::no_pattern);
776 multiply_by *= power(subsed_result, nummatches);
782 bool subsfound = false;
783 for (size_t i=0; i<subsed.size(); i++) {
790 return subs_one_level(m, options | subs_options::algebraic);
792 return ((*this)/divide_by)*multiply_by;
797 /** Implementation of ex::diff() for a product. It applies the product rule.
799 ex mul::derivative(const symbol & s) const
801 size_t num = seq.size();
805 // D(a*b*c) = D(a)*b*c + a*D(b)*c + a*b*D(c)
806 epvector mulseq = seq;
807 epvector::const_iterator i = seq.begin(), end = seq.end();
808 epvector::iterator i2 = mulseq.begin();
810 expair ep = split_ex_to_pair(power(i->rest, i->coeff - _ex1) *
813 addseq.push_back((new mul(mulseq, overall_coeff * i->coeff))->setflag(status_flags::dynallocated));
817 return (new add(addseq))->setflag(status_flags::dynallocated);
820 int mul::compare_same_type(const basic & other) const
822 return inherited::compare_same_type(other);
825 unsigned mul::return_type() const
828 // mul without factors: should not happen, but commutates
829 return return_types::commutative;
832 bool all_commutative = true;
833 epvector::const_iterator noncommutative_element; // point to first found nc element
835 epvector::const_iterator i = seq.begin(), end = seq.end();
837 unsigned rt = i->rest.return_type();
838 if (rt == return_types::noncommutative_composite)
839 return rt; // one ncc -> mul also ncc
840 if ((rt == return_types::noncommutative) && (all_commutative)) {
841 // first nc element found, remember position
842 noncommutative_element = i;
843 all_commutative = false;
845 if ((rt == return_types::noncommutative) && (!all_commutative)) {
846 // another nc element found, compare type_infos
847 if (noncommutative_element->rest.return_type_tinfo() != i->rest.return_type_tinfo()) {
848 // different types -> mul is ncc
849 return return_types::noncommutative_composite;
854 // all factors checked
855 return all_commutative ? return_types::commutative : return_types::noncommutative;
858 tinfo_t mul::return_type_tinfo() const
861 return this; // mul without factors: should not happen
863 // return type_info of first noncommutative element
864 epvector::const_iterator i = seq.begin(), end = seq.end();
866 if (i->rest.return_type() == return_types::noncommutative)
867 return i->rest.return_type_tinfo();
870 // no noncommutative element found, should not happen
874 ex mul::thisexpairseq(const epvector & v, const ex & oc, bool do_index_renaming) const
876 return (new mul(v, oc, do_index_renaming))->setflag(status_flags::dynallocated);
879 ex mul::thisexpairseq(std::auto_ptr<epvector> vp, const ex & oc, bool do_index_renaming) const
881 return (new mul(vp, oc, do_index_renaming))->setflag(status_flags::dynallocated);
884 expair mul::split_ex_to_pair(const ex & e) const
886 if (is_exactly_a<power>(e)) {
887 const power & powerref = ex_to<power>(e);
888 if (is_exactly_a<numeric>(powerref.exponent))
889 return expair(powerref.basis,powerref.exponent);
891 return expair(e,_ex1);
894 expair mul::combine_ex_with_coeff_to_pair(const ex & e,
897 // to avoid duplication of power simplification rules,
898 // we create a temporary power object
899 // otherwise it would be hard to correctly evaluate
900 // expression like (4^(1/3))^(3/2)
901 if (c.is_equal(_ex1))
902 return split_ex_to_pair(e);
904 return split_ex_to_pair(power(e,c));
907 expair mul::combine_pair_with_coeff_to_pair(const expair & p,
910 // to avoid duplication of power simplification rules,
911 // we create a temporary power object
912 // otherwise it would be hard to correctly evaluate
913 // expression like (4^(1/3))^(3/2)
914 if (c.is_equal(_ex1))
917 return split_ex_to_pair(power(recombine_pair_to_ex(p),c));
920 ex mul::recombine_pair_to_ex(const expair & p) const
922 if (ex_to<numeric>(p.coeff).is_equal(*_num1_p))
925 return (new power(p.rest,p.coeff))->setflag(status_flags::dynallocated);
928 bool mul::expair_needs_further_processing(epp it)
930 if (is_exactly_a<mul>(it->rest) &&
931 ex_to<numeric>(it->coeff).is_integer()) {
932 // combined pair is product with integer power -> expand it
933 *it = split_ex_to_pair(recombine_pair_to_ex(*it));
936 if (is_exactly_a<numeric>(it->rest)) {
937 expair ep = split_ex_to_pair(recombine_pair_to_ex(*it));
938 if (!ep.is_equal(*it)) {
939 // combined pair is a numeric power which can be simplified
943 if (it->coeff.is_equal(_ex1)) {
944 // combined pair has coeff 1 and must be moved to the end
951 ex mul::default_overall_coeff() const
956 void mul::combine_overall_coeff(const ex & c)
958 GINAC_ASSERT(is_exactly_a<numeric>(overall_coeff));
959 GINAC_ASSERT(is_exactly_a<numeric>(c));
960 overall_coeff = ex_to<numeric>(overall_coeff).mul_dyn(ex_to<numeric>(c));
963 void mul::combine_overall_coeff(const ex & c1, const ex & c2)
965 GINAC_ASSERT(is_exactly_a<numeric>(overall_coeff));
966 GINAC_ASSERT(is_exactly_a<numeric>(c1));
967 GINAC_ASSERT(is_exactly_a<numeric>(c2));
968 overall_coeff = ex_to<numeric>(overall_coeff).mul_dyn(ex_to<numeric>(c1).power(ex_to<numeric>(c2)));
971 bool mul::can_make_flat(const expair & p) const
973 GINAC_ASSERT(is_exactly_a<numeric>(p.coeff));
974 // this assertion will probably fail somewhere
975 // it would require a more careful make_flat, obeying the power laws
976 // probably should return true only if p.coeff is integer
977 return ex_to<numeric>(p.coeff).is_equal(*_num1_p);
980 bool mul::can_be_further_expanded(const ex & e)
982 if (is_exactly_a<mul>(e)) {
983 for (epvector::const_iterator cit = ex_to<mul>(e).seq.begin(); cit != ex_to<mul>(e).seq.end(); ++cit) {
984 if (is_exactly_a<add>(cit->rest) && cit->coeff.info(info_flags::posint))
987 } else if (is_exactly_a<power>(e)) {
988 if (is_exactly_a<add>(e.op(0)) && e.op(1).info(info_flags::posint))
994 ex mul::expand(unsigned options) const
997 // trivial case: expanding the monomial (~ 30% of all calls)
998 epvector::const_iterator i = seq.begin(), seq_end = seq.end();
999 while ((i != seq.end()) && is_a<symbol>(i->rest) && i->coeff.info(info_flags::integer))
1002 setflag(status_flags::expanded);
1007 // do not rename indices if the object has no indices at all
1008 if ((!(options & expand_options::expand_rename_idx)) &&
1009 this->info(info_flags::has_indices))
1010 options |= expand_options::expand_rename_idx;
1012 const bool skip_idx_rename = !(options & expand_options::expand_rename_idx);
1014 // First, expand the children
1015 std::auto_ptr<epvector> expanded_seqp = expandchildren(options);
1016 const epvector & expanded_seq = (expanded_seqp.get() ? *expanded_seqp : seq);
1018 // Now, look for all the factors that are sums and multiply each one out
1019 // with the next one that is found while collecting the factors which are
1021 ex last_expanded = _ex1;
1024 non_adds.reserve(expanded_seq.size());
1026 for (epvector::const_iterator cit = expanded_seq.begin(); cit != expanded_seq.end(); ++cit) {
1027 if (is_exactly_a<add>(cit->rest) &&
1028 (cit->coeff.is_equal(_ex1))) {
1029 if (is_exactly_a<add>(last_expanded)) {
1031 // Expand a product of two sums, aggressive version.
1032 // Caring for the overall coefficients in separate loops can
1033 // sometimes give a performance gain of up to 15%!
1035 const int sizedifference = ex_to<add>(last_expanded).seq.size()-ex_to<add>(cit->rest).seq.size();
1036 // add2 is for the inner loop and should be the bigger of the two sums
1037 // in the presence of asymptotically good sorting:
1038 const add& add1 = (sizedifference<0 ? ex_to<add>(last_expanded) : ex_to<add>(cit->rest));
1039 const add& add2 = (sizedifference<0 ? ex_to<add>(cit->rest) : ex_to<add>(last_expanded));
1040 const epvector::const_iterator add1begin = add1.seq.begin();
1041 const epvector::const_iterator add1end = add1.seq.end();
1042 const epvector::const_iterator add2begin = add2.seq.begin();
1043 const epvector::const_iterator add2end = add2.seq.end();
1045 distrseq.reserve(add1.seq.size()+add2.seq.size());
1047 // Multiply add2 with the overall coefficient of add1 and append it to distrseq:
1048 if (!add1.overall_coeff.is_zero()) {
1049 if (add1.overall_coeff.is_equal(_ex1))
1050 distrseq.insert(distrseq.end(),add2begin,add2end);
1052 for (epvector::const_iterator i=add2begin; i!=add2end; ++i)
1053 distrseq.push_back(expair(i->rest, ex_to<numeric>(i->coeff).mul_dyn(ex_to<numeric>(add1.overall_coeff))));
1056 // Multiply add1 with the overall coefficient of add2 and append it to distrseq:
1057 if (!add2.overall_coeff.is_zero()) {
1058 if (add2.overall_coeff.is_equal(_ex1))
1059 distrseq.insert(distrseq.end(),add1begin,add1end);
1061 for (epvector::const_iterator i=add1begin; i!=add1end; ++i)
1062 distrseq.push_back(expair(i->rest, ex_to<numeric>(i->coeff).mul_dyn(ex_to<numeric>(add2.overall_coeff))));
1065 // Compute the new overall coefficient and put it together:
1066 ex tmp_accu = (new add(distrseq, add1.overall_coeff*add2.overall_coeff))->setflag(status_flags::dynallocated);
1068 exvector add1_dummy_indices, add2_dummy_indices, add_indices;
1071 if (!skip_idx_rename) {
1072 for (epvector::const_iterator i=add1begin; i!=add1end; ++i) {
1073 add_indices = get_all_dummy_indices_safely(i->rest);
1074 add1_dummy_indices.insert(add1_dummy_indices.end(), add_indices.begin(), add_indices.end());
1076 for (epvector::const_iterator i=add2begin; i!=add2end; ++i) {
1077 add_indices = get_all_dummy_indices_safely(i->rest);
1078 add2_dummy_indices.insert(add2_dummy_indices.end(), add_indices.begin(), add_indices.end());
1081 sort(add1_dummy_indices.begin(), add1_dummy_indices.end(), ex_is_less());
1082 sort(add2_dummy_indices.begin(), add2_dummy_indices.end(), ex_is_less());
1083 dummy_subs = rename_dummy_indices_uniquely(add1_dummy_indices, add2_dummy_indices);
1086 // Multiply explicitly all non-numeric terms of add1 and add2:
1087 for (epvector::const_iterator i2=add2begin; i2!=add2end; ++i2) {
1088 // We really have to combine terms here in order to compactify
1089 // the result. Otherwise it would become waayy tooo bigg.
1090 numeric oc(*_num0_p);
1092 distrseq2.reserve(add1.seq.size());
1093 const ex i2_new = (skip_idx_rename || (dummy_subs.op(0).nops() == 0) ?
1095 i2->rest.subs(ex_to<lst>(dummy_subs.op(0)),
1096 ex_to<lst>(dummy_subs.op(1)), subs_options::no_pattern));
1097 for (epvector::const_iterator i1=add1begin; i1!=add1end; ++i1) {
1098 // Don't push_back expairs which might have a rest that evaluates to a numeric,
1099 // since that would violate an invariant of expairseq:
1100 const ex rest = (new mul(i1->rest, i2_new))->setflag(status_flags::dynallocated);
1101 if (is_exactly_a<numeric>(rest)) {
1102 oc += ex_to<numeric>(rest).mul(ex_to<numeric>(i1->coeff).mul(ex_to<numeric>(i2->coeff)));
1104 distrseq2.push_back(expair(rest, ex_to<numeric>(i1->coeff).mul_dyn(ex_to<numeric>(i2->coeff))));
1107 tmp_accu += (new add(distrseq2, oc))->setflag(status_flags::dynallocated);
1109 last_expanded = tmp_accu;
1111 if (!last_expanded.is_equal(_ex1))
1112 non_adds.push_back(split_ex_to_pair(last_expanded));
1113 last_expanded = cit->rest;
1117 non_adds.push_back(*cit);
1121 // Now the only remaining thing to do is to multiply the factors which
1122 // were not sums into the "last_expanded" sum
1123 if (is_exactly_a<add>(last_expanded)) {
1124 size_t n = last_expanded.nops();
1126 distrseq.reserve(n);
1128 if (! skip_idx_rename) {
1129 va = get_all_dummy_indices_safely(mul(non_adds));
1130 sort(va.begin(), va.end(), ex_is_less());
1133 for (size_t i=0; i<n; ++i) {
1134 epvector factors = non_adds;
1135 if (skip_idx_rename)
1136 factors.push_back(split_ex_to_pair(last_expanded.op(i)));
1138 factors.push_back(split_ex_to_pair(rename_dummy_indices_uniquely(va, last_expanded.op(i))));
1139 ex term = (new mul(factors, overall_coeff))->setflag(status_flags::dynallocated);
1140 if (can_be_further_expanded(term)) {
1141 distrseq.push_back(term.expand());
1144 ex_to<basic>(term).setflag(status_flags::expanded);
1145 distrseq.push_back(term);
1149 return ((new add(distrseq))->
1150 setflag(status_flags::dynallocated | (options == 0 ? status_flags::expanded : 0)));
1153 non_adds.push_back(split_ex_to_pair(last_expanded));
1154 ex result = (new mul(non_adds, overall_coeff))->setflag(status_flags::dynallocated);
1155 if (can_be_further_expanded(result)) {
1156 return result.expand();
1159 ex_to<basic>(result).setflag(status_flags::expanded);
1166 // new virtual functions which can be overridden by derived classes
1172 // non-virtual functions in this class
1176 /** Member-wise expand the expairs representing this sequence. This must be
1177 * overridden from expairseq::expandchildren() and done iteratively in order
1178 * to allow for early cancallations and thus safe memory.
1180 * @see mul::expand()
1181 * @return pointer to epvector containing expanded representation or zero
1182 * pointer, if sequence is unchanged. */
1183 std::auto_ptr<epvector> mul::expandchildren(unsigned options) const
1185 const epvector::const_iterator last = seq.end();
1186 epvector::const_iterator cit = seq.begin();
1188 const ex & factor = recombine_pair_to_ex(*cit);
1189 const ex & expanded_factor = factor.expand(options);
1190 if (!are_ex_trivially_equal(factor,expanded_factor)) {
1192 // something changed, copy seq, eval and return it
1193 std::auto_ptr<epvector> s(new epvector);
1194 s->reserve(seq.size());
1196 // copy parts of seq which are known not to have changed
1197 epvector::const_iterator cit2 = seq.begin();
1199 s->push_back(*cit2);
1203 // copy first changed element
1204 s->push_back(split_ex_to_pair(expanded_factor));
1208 while (cit2!=last) {
1209 s->push_back(split_ex_to_pair(recombine_pair_to_ex(*cit2).expand(options)));
1217 return std::auto_ptr<epvector>(0); // nothing has changed
1220 } // namespace GiNaC