3 * Implementation of GiNaC's products of expressions. */
6 * GiNaC Copyright (C) 1999-2006 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
33 #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)
91 tinfo_key = &mul::tinfo_static;
93 construct_from_epvector(v);
94 GINAC_ASSERT(is_canonical());
97 mul::mul(std::auto_ptr<epvector> vp, const ex & oc)
99 tinfo_key = &mul::tinfo_static;
100 GINAC_ASSERT(vp.get()!=0);
102 construct_from_epvector(*vp);
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 overall_coeff.print(c, precedence());
227 // Print arguments, separated by "*" or "/"
228 epvector::const_iterator it = seq.begin(), itend = seq.end();
229 while (it != itend) {
231 // If the first argument is a negative integer power, it gets printed as "1.0/<expr>"
232 bool needclosingparenthesis = false;
233 if (it == seq.begin() && it->coeff.info(info_flags::negint)) {
234 if (is_a<print_csrc_cl_N>(c)) {
236 needclosingparenthesis = true;
241 // If the exponent is 1 or -1, it is left out
242 if (it->coeff.is_equal(_ex1) || it->coeff.is_equal(_ex_1))
243 it->rest.print(c, precedence());
244 else if (it->coeff.info(info_flags::negint))
245 // Outer parens around ex needed for broken GCC parser:
246 (ex(power(it->rest, -ex_to<numeric>(it->coeff)))).print(c, level);
248 // Outer parens around ex needed for broken GCC parser:
249 (ex(power(it->rest, ex_to<numeric>(it->coeff)))).print(c, level);
251 if (needclosingparenthesis)
254 // Separator is "/" for negative integer powers, "*" otherwise
257 if (it->coeff.info(info_flags::negint))
264 if (precedence() <= level)
268 void mul::do_print_python_repr(const print_python_repr & c, unsigned level) const
270 c.s << class_name() << '(';
272 for (size_t i=1; i<nops(); ++i) {
279 bool mul::info(unsigned inf) const
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();
290 if (!(recombine_pair_to_ex(*i).info(inf)))
294 return overall_coeff.info(inf);
296 case info_flags::algebraic: {
297 epvector::const_iterator i = seq.begin(), end = seq.end();
299 if ((recombine_pair_to_ex(*i).info(inf)))
306 return inherited::info(inf);
309 int mul::degree(const ex & s) const
311 // Sum up degrees of factors
313 epvector::const_iterator i = seq.begin(), end = seq.end();
315 if (ex_to<numeric>(i->coeff).is_integer())
316 deg_sum += i->rest.degree(s) * ex_to<numeric>(i->coeff).to_int();
322 int mul::ldegree(const ex & s) const
324 // Sum up degrees of factors
326 epvector::const_iterator i = seq.begin(), end = seq.end();
328 if (ex_to<numeric>(i->coeff).is_integer())
329 deg_sum += i->rest.ldegree(s) * ex_to<numeric>(i->coeff).to_int();
335 ex mul::coeff(const ex & s, int n) const
338 coeffseq.reserve(seq.size()+1);
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();
345 coeffseq.push_back(recombine_pair_to_ex(*i).coeff(s,n));
348 coeffseq.push_back(overall_coeff);
349 return (new mul(coeffseq))->setflag(status_flags::dynallocated);
352 epvector::const_iterator i = seq.begin(), end = seq.end();
353 bool coeff_found = false;
355 ex t = recombine_pair_to_ex(*i);
356 ex c = t.coeff(s, n);
358 coeffseq.push_back(c);
361 coeffseq.push_back(t);
366 coeffseq.push_back(overall_coeff);
367 return (new mul(coeffseq))->setflag(status_flags::dynallocated);
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.
377 * - *(+(x1,x2,...);c) -> *(+(*(x1,c),*(x2,c),...))
381 * @param level cut-off in recursive evaluation */
382 ex mul::eval(int level) const
384 std::auto_ptr<epvector> evaled_seqp = evalchildren(level);
385 if (evaled_seqp.get()) {
386 // do more evaluation later
387 return (new mul(evaled_seqp, overall_coeff))->
388 setflag(status_flags::dynallocated);
391 #ifdef DO_GINAC_ASSERT
392 epvector::const_iterator i = seq.begin(), end = seq.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)));
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));
407 #endif // def DO_GINAC_ASSERT
409 if (flags & status_flags::evaluated) {
410 GINAC_ASSERT(seq.size()>0);
411 GINAC_ASSERT(seq.size()>1 || !overall_coeff.is_equal(_ex1));
415 int seq_size = seq.size();
416 if (overall_coeff.is_zero()) {
419 } else if (seq_size==0) {
421 return overall_coeff;
422 } else if (seq_size==1 && overall_coeff.is_equal(_ex1)) {
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_p)) {
428 // *(+(x,y,...);c) -> +(*(x,c),*(y,c),...) (c numeric(), no powers of +())
429 const add & addref = ex_to<add>((*seq.begin()).rest);
430 std::auto_ptr<epvector> distrseq(new epvector);
431 distrseq->reserve(addref.seq.size());
432 epvector::const_iterator i = addref.seq.begin(), end = addref.seq.end();
434 distrseq->push_back(addref.combine_pair_with_coeff_to_pair(*i, overall_coeff));
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);
445 ex mul::evalf(int level) const
448 return mul(seq,overall_coeff);
450 if (level==-max_recursion_level)
451 throw(std::runtime_error("max recursion level reached"));
453 std::auto_ptr<epvector> s(new epvector);
454 s->reserve(seq.size());
457 epvector::const_iterator i = seq.begin(), end = seq.end();
459 s->push_back(combine_ex_with_coeff_to_pair(i->rest.evalf(level),
463 return mul(s, overall_coeff.evalf(level));
466 ex mul::evalm() const
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));
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 std::auto_ptr<epvector> s(new epvector);
477 s->reserve(seq.size());
479 bool have_matrix = false;
480 epvector::iterator the_matrix;
482 epvector::const_iterator i = seq.begin(), end = seq.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)) {
488 the_matrix = s->end() - 1;
495 // The product contained a matrix. We will multiply all other factors
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);
503 return (new mul(s, overall_coeff))->setflag(status_flags::dynallocated);
506 ex mul::eval_ncmul(const exvector & v) const
509 return inherited::eval_ncmul(v);
511 // Find first noncommutative element and call its eval_ncmul()
512 epvector::const_iterator i = seq.begin(), end = seq.end();
514 if (i->rest.return_type() == return_types::noncommutative)
515 return i->rest.eval_ncmul(v);
518 return inherited::eval_ncmul(v);
521 bool tryfactsubs(const ex & origfactor, const ex & patternfactor, int & nummatches, lst & repls)
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;
533 origbase = origfactor;
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;
548 patternbase = patternfactor;
553 lst saverepls = repls;
554 if (origexponent < patternexponent || origexpsign != patternexpsign || !origbase.match(patternbase,saverepls))
558 int newnummatches = origexponent / patternexponent;
559 if (newnummatches < nummatches)
560 nummatches = newnummatches;
564 /** Checks wheter e matches to the pattern pat and the (possibly to be updated
565 * list of replacements repls. This matching is in the sense of algebraic
566 * substitutions. Matching starts with pat.op(factor) of the pattern because
567 * the factors before this one have already been matched. The (possibly
568 * updated) number of matches is in nummatches. subsed[i] is true for factors
569 * that already have been replaced by previous substitutions and matched[i]
570 * is true for factors that have been matched by the current match.
572 bool algebraic_match_mul_with_mul(const mul &e, const ex &pat, lst &repls,
573 int factor, int &nummatches, const std::vector<bool> &subsed,
574 std::vector<bool> &matched)
576 if (factor == pat.nops())
579 for (size_t i=0; i<e.nops(); ++i) {
580 if(subsed[i] || matched[i])
582 lst newrepls = repls;
583 int newnummatches = nummatches;
584 if (tryfactsubs(e.op(i), pat.op(factor), newnummatches, newrepls)) {
586 if (algebraic_match_mul_with_mul(e, pat, newrepls, factor+1,
587 newnummatches, subsed, matched)) {
589 nummatches = newnummatches;
600 bool mul::has(const ex & pattern, unsigned options) const
602 if(!(options&has_options::algebraic))
603 return basic::has(pattern,options);
604 if(is_a<mul>(pattern)) {
606 int nummatches = std::numeric_limits<int>::max();
607 std::vector<bool> subsed(seq.size(), false);
608 std::vector<bool> matched(seq.size(), false);
609 if(algebraic_match_mul_with_mul(*this, pattern, repls, 0, nummatches,
613 return basic::has(pattern, options);
616 ex mul::algebraic_subs_mul(const exmap & m, unsigned options) const
618 std::vector<bool> subsed(seq.size(), false);
619 exvector subsresult(seq.size());
621 for (exmap::const_iterator it = m.begin(); it != m.end(); ++it) {
623 if (is_exactly_a<mul>(it->first)) {
625 int nummatches = std::numeric_limits<int>::max();
626 std::vector<bool> currsubsed(seq.size(), false);
630 if(!algebraic_match_mul_with_mul(*this, it->first, repls, 0, nummatches, subsed, currsubsed))
633 bool foundfirstsubsedfactor = false;
634 for (size_t j=0; j<subsed.size(); j++) {
636 if (foundfirstsubsedfactor)
637 subsresult[j] = op(j);
639 foundfirstsubsedfactor = true;
640 subsresult[j] = op(j) * power(it->second.subs(ex(repls), subs_options::no_pattern) / it->first.subs(ex(repls), subs_options::no_pattern), nummatches);
649 int nummatches = std::numeric_limits<int>::max();
652 for (size_t j=0; j<this->nops(); j++) {
653 if (!subsed[j] && tryfactsubs(op(j), it->first, nummatches, repls)) {
655 subsresult[j] = op(j) * power(it->second.subs(ex(repls), subs_options::no_pattern) / it->first.subs(ex(repls), subs_options::no_pattern), nummatches);
662 bool subsfound = false;
663 for (size_t i=0; i<subsed.size(); i++) {
670 return subs_one_level(m, options | subs_options::algebraic);
672 exvector ev; ev.reserve(nops());
673 for (size_t i=0; i<nops(); i++) {
675 ev.push_back(subsresult[i]);
680 return (new mul(ev))->setflag(status_flags::dynallocated);
685 /** Implementation of ex::diff() for a product. It applies the product rule.
687 ex mul::derivative(const symbol & s) const
689 size_t num = seq.size();
693 // D(a*b*c) = D(a)*b*c + a*D(b)*c + a*b*D(c)
694 epvector mulseq = seq;
695 epvector::const_iterator i = seq.begin(), end = seq.end();
696 epvector::iterator i2 = mulseq.begin();
698 expair ep = split_ex_to_pair(power(i->rest, i->coeff - _ex1) *
701 addseq.push_back((new mul(mulseq, overall_coeff * i->coeff))->setflag(status_flags::dynallocated));
705 return (new add(addseq))->setflag(status_flags::dynallocated);
708 int mul::compare_same_type(const basic & other) const
710 return inherited::compare_same_type(other);
713 unsigned mul::return_type() const
716 // mul without factors: should not happen, but commutates
717 return return_types::commutative;
720 bool all_commutative = true;
721 epvector::const_iterator noncommutative_element; // point to first found nc element
723 epvector::const_iterator i = seq.begin(), end = seq.end();
725 unsigned rt = i->rest.return_type();
726 if (rt == return_types::noncommutative_composite)
727 return rt; // one ncc -> mul also ncc
728 if ((rt == return_types::noncommutative) && (all_commutative)) {
729 // first nc element found, remember position
730 noncommutative_element = i;
731 all_commutative = false;
733 if ((rt == return_types::noncommutative) && (!all_commutative)) {
734 // another nc element found, compare type_infos
735 if (noncommutative_element->rest.return_type_tinfo()->tinfo() == &clifford::tinfo_static) {
736 if (i->rest.return_type_tinfo()->tinfo() != &clifford::tinfo_static ||
737 ((clifford*)(noncommutative_element->rest.return_type_tinfo()))->get_representation_label() !=
738 ((clifford*)(i->rest.return_type_tinfo()))->get_representation_label()) {
739 // diffent types -> mul is ncc
740 return return_types::noncommutative_composite;
742 } else if (noncommutative_element->rest.return_type_tinfo()->tinfo() == &color::tinfo_static) {
743 if (i->rest.return_type_tinfo()->tinfo() != &color::tinfo_static ||
744 ((color*)(noncommutative_element->rest.return_type_tinfo()))->get_representation_label() !=
745 ((color*)(i->rest.return_type_tinfo()))->get_representation_label()) {
746 // diffent types -> mul is ncc
747 return return_types::noncommutative_composite;
749 } else if (noncommutative_element->rest.return_type_tinfo()->tinfo() != i->rest.return_type_tinfo()->tinfo()) {
750 return return_types::noncommutative_composite;
755 // all factors checked
756 return all_commutative ? return_types::commutative : return_types::noncommutative;
759 const basic* mul::return_type_tinfo() const
762 return this; // mul without factors: should not happen
764 // return type_info of first noncommutative element
765 epvector::const_iterator i = seq.begin(), end = seq.end();
767 if (i->rest.return_type() == return_types::noncommutative)
768 return i->rest.return_type_tinfo();
771 // no noncommutative element found, should not happen
775 ex mul::thisexpairseq(const epvector & v, const ex & oc) const
777 return (new mul(v, oc))->setflag(status_flags::dynallocated);
780 ex mul::thisexpairseq(std::auto_ptr<epvector> vp, const ex & oc) const
782 return (new mul(vp, oc))->setflag(status_flags::dynallocated);
785 expair mul::split_ex_to_pair(const ex & e) const
787 if (is_exactly_a<power>(e)) {
788 const power & powerref = ex_to<power>(e);
789 if (is_exactly_a<numeric>(powerref.exponent))
790 return expair(powerref.basis,powerref.exponent);
792 return expair(e,_ex1);
795 expair mul::combine_ex_with_coeff_to_pair(const ex & e,
798 // to avoid duplication of power simplification rules,
799 // we create a temporary power object
800 // otherwise it would be hard to correctly evaluate
801 // expression like (4^(1/3))^(3/2)
802 if (c.is_equal(_ex1))
803 return split_ex_to_pair(e);
805 return split_ex_to_pair(power(e,c));
808 expair mul::combine_pair_with_coeff_to_pair(const expair & p,
811 // to avoid duplication of power simplification rules,
812 // we create a temporary power object
813 // otherwise it would be hard to correctly evaluate
814 // expression like (4^(1/3))^(3/2)
815 if (c.is_equal(_ex1))
818 return split_ex_to_pair(power(recombine_pair_to_ex(p),c));
821 ex mul::recombine_pair_to_ex(const expair & p) const
823 if (ex_to<numeric>(p.coeff).is_equal(*_num1_p))
826 return (new power(p.rest,p.coeff))->setflag(status_flags::dynallocated);
829 bool mul::expair_needs_further_processing(epp it)
831 if (is_exactly_a<mul>(it->rest) &&
832 ex_to<numeric>(it->coeff).is_integer()) {
833 // combined pair is product with integer power -> expand it
834 *it = split_ex_to_pair(recombine_pair_to_ex(*it));
837 if (is_exactly_a<numeric>(it->rest)) {
838 expair ep = split_ex_to_pair(recombine_pair_to_ex(*it));
839 if (!ep.is_equal(*it)) {
840 // combined pair is a numeric power which can be simplified
844 if (it->coeff.is_equal(_ex1)) {
845 // combined pair has coeff 1 and must be moved to the end
852 ex mul::default_overall_coeff() const
857 void mul::combine_overall_coeff(const ex & c)
859 GINAC_ASSERT(is_exactly_a<numeric>(overall_coeff));
860 GINAC_ASSERT(is_exactly_a<numeric>(c));
861 overall_coeff = ex_to<numeric>(overall_coeff).mul_dyn(ex_to<numeric>(c));
864 void mul::combine_overall_coeff(const ex & c1, const ex & c2)
866 GINAC_ASSERT(is_exactly_a<numeric>(overall_coeff));
867 GINAC_ASSERT(is_exactly_a<numeric>(c1));
868 GINAC_ASSERT(is_exactly_a<numeric>(c2));
869 overall_coeff = ex_to<numeric>(overall_coeff).mul_dyn(ex_to<numeric>(c1).power(ex_to<numeric>(c2)));
872 bool mul::can_make_flat(const expair & p) const
874 GINAC_ASSERT(is_exactly_a<numeric>(p.coeff));
875 // this assertion will probably fail somewhere
876 // it would require a more careful make_flat, obeying the power laws
877 // probably should return true only if p.coeff is integer
878 return ex_to<numeric>(p.coeff).is_equal(*_num1_p);
881 bool mul::can_be_further_expanded(const ex & e)
883 if (is_exactly_a<mul>(e)) {
884 for (epvector::const_iterator cit = ex_to<mul>(e).seq.begin(); cit != ex_to<mul>(e).seq.end(); ++cit) {
885 if (is_exactly_a<add>(cit->rest) && cit->coeff.info(info_flags::posint))
888 } else if (is_exactly_a<power>(e)) {
889 if (is_exactly_a<add>(e.op(0)) && e.op(1).info(info_flags::posint))
895 ex mul::expand(unsigned options) const
897 // First, expand the children
898 std::auto_ptr<epvector> expanded_seqp = expandchildren(options);
899 const epvector & expanded_seq = (expanded_seqp.get() ? *expanded_seqp : seq);
901 // Now, look for all the factors that are sums and multiply each one out
902 // with the next one that is found while collecting the factors which are
904 ex last_expanded = _ex1;
907 non_adds.reserve(expanded_seq.size());
909 for (epvector::const_iterator cit = expanded_seq.begin(); cit != expanded_seq.end(); ++cit) {
910 if (is_exactly_a<add>(cit->rest) &&
911 (cit->coeff.is_equal(_ex1))) {
912 if (is_exactly_a<add>(last_expanded)) {
914 // Expand a product of two sums, aggressive version.
915 // Caring for the overall coefficients in separate loops can
916 // sometimes give a performance gain of up to 15%!
918 const int sizedifference = ex_to<add>(last_expanded).seq.size()-ex_to<add>(cit->rest).seq.size();
919 // add2 is for the inner loop and should be the bigger of the two sums
920 // in the presence of asymptotically good sorting:
921 const add& add1 = (sizedifference<0 ? ex_to<add>(last_expanded) : ex_to<add>(cit->rest));
922 const add& add2 = (sizedifference<0 ? ex_to<add>(cit->rest) : ex_to<add>(last_expanded));
923 const epvector::const_iterator add1begin = add1.seq.begin();
924 const epvector::const_iterator add1end = add1.seq.end();
925 const epvector::const_iterator add2begin = add2.seq.begin();
926 const epvector::const_iterator add2end = add2.seq.end();
928 distrseq.reserve(add1.seq.size()+add2.seq.size());
930 // Multiply add2 with the overall coefficient of add1 and append it to distrseq:
931 if (!add1.overall_coeff.is_zero()) {
932 if (add1.overall_coeff.is_equal(_ex1))
933 distrseq.insert(distrseq.end(),add2begin,add2end);
935 for (epvector::const_iterator i=add2begin; i!=add2end; ++i)
936 distrseq.push_back(expair(i->rest, ex_to<numeric>(i->coeff).mul_dyn(ex_to<numeric>(add1.overall_coeff))));
939 // Multiply add1 with the overall coefficient of add2 and append it to distrseq:
940 if (!add2.overall_coeff.is_zero()) {
941 if (add2.overall_coeff.is_equal(_ex1))
942 distrseq.insert(distrseq.end(),add1begin,add1end);
944 for (epvector::const_iterator i=add1begin; i!=add1end; ++i)
945 distrseq.push_back(expair(i->rest, ex_to<numeric>(i->coeff).mul_dyn(ex_to<numeric>(add2.overall_coeff))));
948 // Compute the new overall coefficient and put it together:
949 ex tmp_accu = (new add(distrseq, add1.overall_coeff*add2.overall_coeff))->setflag(status_flags::dynallocated);
951 exvector add1_dummy_indices, add2_dummy_indices, add_indices;
953 for (epvector::const_iterator i=add1begin; i!=add1end; ++i) {
954 add_indices = get_all_dummy_indices(i->rest);
955 add1_dummy_indices.insert(add1_dummy_indices.end(), add_indices.begin(), add_indices.end());
957 for (epvector::const_iterator i=add2begin; i!=add2end; ++i) {
958 add_indices = get_all_dummy_indices(i->rest);
959 add2_dummy_indices.insert(add2_dummy_indices.end(), add_indices.begin(), add_indices.end());
962 sort(add1_dummy_indices.begin(), add1_dummy_indices.end(), ex_is_less());
963 sort(add2_dummy_indices.begin(), add2_dummy_indices.end(), ex_is_less());
964 lst dummy_subs = rename_dummy_indices_uniquely(add1_dummy_indices, add2_dummy_indices);
966 // Multiply explicitly all non-numeric terms of add1 and add2:
967 for (epvector::const_iterator i2=add2begin; i2!=add2end; ++i2) {
968 // We really have to combine terms here in order to compactify
969 // the result. Otherwise it would become waayy tooo bigg.
972 ex i2_new = (dummy_subs.op(0).nops()>0?
973 i2->rest.subs((lst)dummy_subs.op(0), (lst)dummy_subs.op(1), subs_options::no_pattern) : i2->rest);
974 for (epvector::const_iterator i1=add1begin; i1!=add1end; ++i1) {
975 // Don't push_back expairs which might have a rest that evaluates to a numeric,
976 // since that would violate an invariant of expairseq:
977 const ex rest = (new mul(i1->rest, i2_new))->setflag(status_flags::dynallocated);
978 if (is_exactly_a<numeric>(rest)) {
979 oc += ex_to<numeric>(rest).mul(ex_to<numeric>(i1->coeff).mul(ex_to<numeric>(i2->coeff)));
981 distrseq.push_back(expair(rest, ex_to<numeric>(i1->coeff).mul_dyn(ex_to<numeric>(i2->coeff))));
984 tmp_accu += (new add(distrseq, oc))->setflag(status_flags::dynallocated);
986 last_expanded = tmp_accu;
989 if (!last_expanded.is_equal(_ex1))
990 non_adds.push_back(split_ex_to_pair(last_expanded));
991 last_expanded = cit->rest;
995 non_adds.push_back(*cit);
999 // Now the only remaining thing to do is to multiply the factors which
1000 // were not sums into the "last_expanded" sum
1001 if (is_exactly_a<add>(last_expanded)) {
1002 size_t n = last_expanded.nops();
1004 distrseq.reserve(n);
1005 exvector va = get_all_dummy_indices(mul(non_adds));
1006 sort(va.begin(), va.end(), ex_is_less());
1008 for (size_t i=0; i<n; ++i) {
1009 epvector factors = non_adds;
1010 factors.push_back(split_ex_to_pair(rename_dummy_indices_uniquely(va, last_expanded.op(i))));
1011 ex term = (new mul(factors, overall_coeff))->setflag(status_flags::dynallocated);
1012 if (can_be_further_expanded(term)) {
1013 distrseq.push_back(term.expand());
1016 ex_to<basic>(term).setflag(status_flags::expanded);
1017 distrseq.push_back(term);
1021 return ((new add(distrseq))->
1022 setflag(status_flags::dynallocated | (options == 0 ? status_flags::expanded : 0)));
1025 non_adds.push_back(split_ex_to_pair(last_expanded));
1026 ex result = (new mul(non_adds, overall_coeff))->setflag(status_flags::dynallocated);
1027 if (can_be_further_expanded(result)) {
1028 return result.expand();
1031 ex_to<basic>(result).setflag(status_flags::expanded);
1038 // new virtual functions which can be overridden by derived classes
1044 // non-virtual functions in this class
1048 /** Member-wise expand the expairs representing this sequence. This must be
1049 * overridden from expairseq::expandchildren() and done iteratively in order
1050 * to allow for early cancallations and thus safe memory.
1052 * @see mul::expand()
1053 * @return pointer to epvector containing expanded representation or zero
1054 * pointer, if sequence is unchanged. */
1055 std::auto_ptr<epvector> mul::expandchildren(unsigned options) const
1057 const epvector::const_iterator last = seq.end();
1058 epvector::const_iterator cit = seq.begin();
1060 const ex & factor = recombine_pair_to_ex(*cit);
1061 const ex & expanded_factor = factor.expand(options);
1062 if (!are_ex_trivially_equal(factor,expanded_factor)) {
1064 // something changed, copy seq, eval and return it
1065 std::auto_ptr<epvector> s(new epvector);
1066 s->reserve(seq.size());
1068 // copy parts of seq which are known not to have changed
1069 epvector::const_iterator cit2 = seq.begin();
1071 s->push_back(*cit2);
1075 // copy first changed element
1076 s->push_back(split_ex_to_pair(expanded_factor));
1080 while (cit2!=last) {
1081 s->push_back(split_ex_to_pair(recombine_pair_to_ex(*cit2).expand(options)));
1089 return std::auto_ptr<epvector>(0); // nothing has changed
1092 } // namespace GiNaC