3 * Implementation of GiNaC's products of expressions. */
6 * GiNaC Copyright (C) 1999-2015 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
26 #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
64 mul::mul(const ex & lh, const ex & rh)
67 construct_from_2_ex(lh,rh);
68 GINAC_ASSERT(is_canonical());
71 mul::mul(const exvector & v)
74 construct_from_exvector(v);
75 GINAC_ASSERT(is_canonical());
78 mul::mul(const epvector & v)
81 construct_from_epvector(v);
82 GINAC_ASSERT(is_canonical());
85 mul::mul(const epvector & v, const ex & oc, bool do_index_renaming)
88 construct_from_epvector(v, do_index_renaming);
89 GINAC_ASSERT(is_canonical());
92 mul::mul(epvector && vp, const ex & oc, bool do_index_renaming)
95 construct_from_epvector(std::move(vp), do_index_renaming);
96 GINAC_ASSERT(is_canonical());
99 mul::mul(const ex & lh, const ex & mh, const ex & rh)
103 factors.push_back(lh);
104 factors.push_back(mh);
105 factors.push_back(rh);
106 overall_coeff = _ex1;
107 construct_from_exvector(factors);
108 GINAC_ASSERT(is_canonical());
116 // functions overriding virtual functions from base classes
119 void mul::print_overall_coeff(const print_context & c, const char *mul_sym) const
121 const numeric &coeff = ex_to<numeric>(overall_coeff);
122 if (coeff.csgn() == -1)
124 if (!coeff.is_equal(*_num1_p) &&
125 !coeff.is_equal(*_num_1_p)) {
126 if (coeff.is_rational()) {
127 if (coeff.is_negative())
132 if (coeff.csgn() == -1)
133 (-coeff).print(c, precedence());
135 coeff.print(c, precedence());
141 void mul::do_print(const print_context & c, unsigned level) const
143 if (precedence() <= level)
146 print_overall_coeff(c, "*");
148 epvector::const_iterator it = seq.begin(), itend = seq.end();
150 while (it != itend) {
155 recombine_pair_to_ex(*it).print(c, precedence());
159 if (precedence() <= level)
163 void mul::do_print_latex(const print_latex & c, unsigned level) const
165 if (precedence() <= level)
168 print_overall_coeff(c, " ");
170 // Separate factors into those with negative numeric exponent
172 epvector::const_iterator it = seq.begin(), itend = seq.end();
173 exvector neg_powers, others;
174 while (it != itend) {
175 GINAC_ASSERT(is_exactly_a<numeric>(it->coeff));
176 if (ex_to<numeric>(it->coeff).is_negative())
177 neg_powers.push_back(recombine_pair_to_ex(expair(it->rest, -(it->coeff))));
179 others.push_back(recombine_pair_to_ex(*it));
183 if (!neg_powers.empty()) {
185 // Factors with negative exponent are printed as a fraction
187 mul(others).eval().print(c);
189 mul(neg_powers).eval().print(c);
194 // All other factors are printed in the ordinary way
195 exvector::const_iterator vit = others.begin(), vitend = others.end();
196 while (vit != vitend) {
198 vit->print(c, precedence());
203 if (precedence() <= level)
207 void mul::do_print_csrc(const print_csrc & c, unsigned level) const
209 if (precedence() <= level)
212 if (!overall_coeff.is_equal(_ex1)) {
213 if (overall_coeff.is_equal(_ex_1))
216 overall_coeff.print(c, precedence());
221 // Print arguments, separated by "*" or "/"
222 epvector::const_iterator it = seq.begin(), itend = seq.end();
223 while (it != itend) {
225 // If the first argument is a negative integer power, it gets printed as "1.0/<expr>"
226 bool needclosingparenthesis = false;
227 if (it == seq.begin() && it->coeff.info(info_flags::negint)) {
228 if (is_a<print_csrc_cl_N>(c)) {
230 needclosingparenthesis = true;
235 // If the exponent is 1 or -1, it is left out
236 if (it->coeff.is_equal(_ex1) || it->coeff.is_equal(_ex_1))
237 it->rest.print(c, precedence());
238 else if (it->coeff.info(info_flags::negint))
239 // Outer parens around ex needed for broken GCC parser:
240 (ex(power(it->rest, -ex_to<numeric>(it->coeff)))).print(c, level);
242 // Outer parens around ex needed for broken GCC parser:
243 (ex(power(it->rest, ex_to<numeric>(it->coeff)))).print(c, level);
245 if (needclosingparenthesis)
248 // Separator is "/" for negative integer powers, "*" otherwise
251 if (it->coeff.info(info_flags::negint))
258 if (precedence() <= level)
262 void mul::do_print_python_repr(const print_python_repr & c, unsigned level) const
264 c.s << class_name() << '(';
266 for (size_t i=1; i<nops(); ++i) {
273 bool mul::info(unsigned inf) const
276 case info_flags::polynomial:
277 case info_flags::integer_polynomial:
278 case info_flags::cinteger_polynomial:
279 case info_flags::rational_polynomial:
280 case info_flags::real:
281 case info_flags::rational:
282 case info_flags::integer:
283 case info_flags::crational:
284 case info_flags::cinteger:
285 case info_flags::even:
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 if (overall_coeff.is_equal(*_num1_p) && inf == info_flags::even)
296 return overall_coeff.info(inf);
298 case info_flags::algebraic: {
299 epvector::const_iterator i = seq.begin(), end = seq.end();
301 if ((recombine_pair_to_ex(*i).info(inf)))
307 case info_flags::positive:
308 case info_flags::negative: {
309 if ((inf==info_flags::positive) && (flags & status_flags::is_positive))
311 else if ((inf==info_flags::negative) && (flags & status_flags::is_negative))
313 if (flags & status_flags::purely_indefinite)
317 epvector::const_iterator i = seq.begin(), end = seq.end();
319 const ex& factor = recombine_pair_to_ex(*i++);
320 if (factor.info(info_flags::positive))
322 else if (factor.info(info_flags::negative))
327 if (overall_coeff.info(info_flags::negative))
329 setflag(pos ? status_flags::is_positive : status_flags::is_negative);
330 return (inf == info_flags::positive? pos : !pos);
332 case info_flags::nonnegative: {
333 if (flags & status_flags::is_positive)
336 epvector::const_iterator i = seq.begin(), end = seq.end();
338 const ex& factor = recombine_pair_to_ex(*i++);
339 if (factor.info(info_flags::nonnegative) || factor.info(info_flags::positive))
341 else if (factor.info(info_flags::negative))
346 return (overall_coeff.info(info_flags::negative)? !pos : pos);
348 case info_flags::posint:
349 case info_flags::negint: {
351 epvector::const_iterator i = seq.begin(), end = seq.end();
353 const ex& factor = recombine_pair_to_ex(*i++);
354 if (factor.info(info_flags::posint))
356 else if (factor.info(info_flags::negint))
361 if (overall_coeff.info(info_flags::negint))
363 else if (!overall_coeff.info(info_flags::posint))
365 return (inf ==info_flags::posint? pos : !pos);
367 case info_flags::nonnegint: {
369 epvector::const_iterator i = seq.begin(), end = seq.end();
371 const ex& factor = recombine_pair_to_ex(*i++);
372 if (factor.info(info_flags::nonnegint) || factor.info(info_flags::posint))
374 else if (factor.info(info_flags::negint))
379 if (overall_coeff.info(info_flags::negint))
381 else if (!overall_coeff.info(info_flags::posint))
385 case info_flags::indefinite: {
386 if (flags & status_flags::purely_indefinite)
388 if (flags & (status_flags::is_positive | status_flags::is_negative))
390 epvector::const_iterator i = seq.begin(), end = seq.end();
392 const ex& term = recombine_pair_to_ex(*i);
393 if (term.info(info_flags::positive) || term.info(info_flags::negative))
397 setflag(status_flags::purely_indefinite);
401 return inherited::info(inf);
404 bool mul::is_polynomial(const ex & var) const
406 for (epvector::const_iterator i=seq.begin(); i!=seq.end(); ++i) {
407 if (!i->rest.is_polynomial(var) ||
408 (i->rest.has(var) && !i->coeff.info(info_flags::nonnegint))) {
415 int mul::degree(const ex & s) const
417 // Sum up degrees of factors
419 epvector::const_iterator i = seq.begin(), end = seq.end();
421 if (ex_to<numeric>(i->coeff).is_integer())
422 deg_sum += recombine_pair_to_ex(*i).degree(s);
425 throw std::runtime_error("mul::degree() undefined degree because of non-integer exponent");
432 int mul::ldegree(const ex & s) const
434 // Sum up degrees of factors
436 epvector::const_iterator i = seq.begin(), end = seq.end();
438 if (ex_to<numeric>(i->coeff).is_integer())
439 deg_sum += recombine_pair_to_ex(*i).ldegree(s);
442 throw std::runtime_error("mul::ldegree() undefined degree because of non-integer exponent");
449 ex mul::coeff(const ex & s, int n) const
452 coeffseq.reserve(seq.size()+1);
455 // product of individual coeffs
456 // if a non-zero power of s is found, the resulting product will be 0
457 epvector::const_iterator i = seq.begin(), end = seq.end();
459 coeffseq.push_back(recombine_pair_to_ex(*i).coeff(s,n));
462 coeffseq.push_back(overall_coeff);
463 return (new mul(coeffseq))->setflag(status_flags::dynallocated);
466 epvector::const_iterator i = seq.begin(), end = seq.end();
467 bool coeff_found = false;
469 ex t = recombine_pair_to_ex(*i);
470 ex c = t.coeff(s, n);
472 coeffseq.push_back(c);
475 coeffseq.push_back(t);
480 coeffseq.push_back(overall_coeff);
481 return (new mul(coeffseq))->setflag(status_flags::dynallocated);
487 /** Perform automatic term rewriting rules in this class. In the following
488 * x, x1, x2,... stand for a symbolic variables of type ex and c, c1, c2...
489 * stand for such expressions that contain a plain number.
491 * - *(+(x1,x2,...);c) -> *(+(*(x1,c),*(x2,c),...))
495 * @param level cut-off in recursive evaluation */
496 ex mul::eval(int level) const
498 epvector evaled = evalchildren(level);
499 if (!evaled.empty()) {
500 // do more evaluation later
501 return (new mul(std::move(evaled), overall_coeff))->
502 setflag(status_flags::dynallocated);
505 if (flags & status_flags::evaluated) {
506 GINAC_ASSERT(seq.size()>0);
507 GINAC_ASSERT(seq.size()>1 || !overall_coeff.is_equal(_ex1));
511 size_t seq_size = seq.size();
512 if (overall_coeff.is_zero()) {
515 } else if (seq_size==0) {
517 return overall_coeff;
518 } else if (seq_size==1 && overall_coeff.is_equal(_ex1)) {
520 return recombine_pair_to_ex(*(seq.begin()));
521 } else if ((seq_size==1) &&
522 is_exactly_a<add>((*seq.begin()).rest) &&
523 ex_to<numeric>((*seq.begin()).coeff).is_equal(*_num1_p)) {
524 // *(+(x,y,...);c) -> +(*(x,c),*(y,c),...) (c numeric(), no powers of +())
525 const add & addref = ex_to<add>((*seq.begin()).rest);
527 distrseq.reserve(addref.seq.size());
528 epvector::const_iterator i = addref.seq.begin(), end = addref.seq.end();
530 distrseq.push_back(addref.combine_pair_with_coeff_to_pair(*i, overall_coeff));
533 return (new add(std::move(distrseq),
534 ex_to<numeric>(addref.overall_coeff).
535 mul_dyn(ex_to<numeric>(overall_coeff)))
536 )->setflag(status_flags::dynallocated | status_flags::evaluated);
537 } else if ((seq_size >= 2) && (! (flags & status_flags::expanded))) {
538 // Strip the content and the unit part from each term. Thus
539 // things like (-x+a)*(3*x-3*a) automagically turn into - 3*(x-a)^2
541 epvector::const_iterator last = seq.end();
542 epvector::const_iterator i = seq.begin();
543 epvector::const_iterator j = seq.begin();
545 numeric oc = *_num1_p;
546 bool something_changed = false;
548 if (likely(! (is_a<add>(i->rest) && i->coeff.is_equal(_ex1)))) {
549 // power::eval has such a rule, no need to handle powers here
554 // XXX: What is the best way to check if the polynomial is a primitive?
555 numeric c = i->rest.integer_content();
556 const numeric lead_coeff =
557 ex_to<numeric>(ex_to<add>(i->rest).seq.begin()->coeff).div(c);
558 const bool canonicalizable = lead_coeff.is_integer();
560 // XXX: The main variable is chosen in a random way, so this code
561 // does NOT transform the term into the canonical form (thus, in some
562 // very unlucky event it can even loop forever). Hopefully the main
563 // variable will be the same for all terms in *this
564 const bool unit_normal = lead_coeff.is_pos_integer();
565 if (likely((c == *_num1_p) && ((! canonicalizable) || unit_normal))) {
570 if (! something_changed) {
572 something_changed = true;
575 while ((j!=i) && (j!=last)) {
581 c = c.mul(*_num_1_p);
585 // divide add by the number in place to save at least 2 .eval() calls
586 const add& addref = ex_to<add>(i->rest);
587 add* primitive = new add(addref);
588 primitive->setflag(status_flags::dynallocated);
589 primitive->clearflag(status_flags::hash_calculated);
590 primitive->overall_coeff = ex_to<numeric>(primitive->overall_coeff).div_dyn(c);
591 for (epvector::iterator ai = primitive->seq.begin(); ai != primitive->seq.end(); ++ai)
592 ai->coeff = ex_to<numeric>(ai->coeff).div_dyn(c);
594 s.push_back(expair(*primitive, _ex1));
599 if (something_changed) {
604 return (new mul(std::move(s), ex_to<numeric>(overall_coeff).mul_dyn(oc))
605 )->setflag(status_flags::dynallocated);
612 ex mul::evalf(int level) const
615 return mul(seq,overall_coeff);
617 if (level==-max_recursion_level)
618 throw(std::runtime_error("max recursion level reached"));
621 s.reserve(seq.size());
624 epvector::const_iterator i = seq.begin(), end = seq.end();
626 s.push_back(combine_ex_with_coeff_to_pair(i->rest.evalf(level),
630 return mul(std::move(s), overall_coeff.evalf(level));
633 void mul::find_real_imag(ex & rp, ex & ip) const
635 rp = overall_coeff.real_part();
636 ip = overall_coeff.imag_part();
637 for (epvector::const_iterator i=seq.begin(); i!=seq.end(); ++i) {
638 ex factor = recombine_pair_to_ex(*i);
639 ex new_rp = factor.real_part();
640 ex new_ip = factor.imag_part();
641 if(new_ip.is_zero()) {
645 ex temp = rp*new_rp - ip*new_ip;
646 ip = ip*new_rp + rp*new_ip;
654 ex mul::real_part() const
657 find_real_imag(rp, ip);
661 ex mul::imag_part() const
664 find_real_imag(rp, ip);
668 ex mul::evalm() const
671 if (seq.size() == 1 && seq[0].coeff.is_equal(_ex1)
672 && is_a<matrix>(seq[0].rest))
673 return ex_to<matrix>(seq[0].rest).mul(ex_to<numeric>(overall_coeff));
675 // Evaluate children first, look whether there are any matrices at all
676 // (there can be either no matrices or one matrix; if there were more
677 // than one matrix, it would be a non-commutative product)
679 s.reserve(seq.size());
681 bool have_matrix = false;
682 epvector::iterator the_matrix;
684 epvector::const_iterator i = seq.begin(), end = seq.end();
686 const ex &m = recombine_pair_to_ex(*i).evalm();
687 s.push_back(split_ex_to_pair(m));
688 if (is_a<matrix>(m)) {
690 the_matrix = s.end() - 1;
697 // The product contained a matrix. We will multiply all other factors
699 matrix m = ex_to<matrix>(the_matrix->rest);
701 ex scalar = (new mul(std::move(s), overall_coeff))->setflag(status_flags::dynallocated);
702 return m.mul_scalar(scalar);
705 return (new mul(std::move(s), overall_coeff))->setflag(status_flags::dynallocated);
708 ex mul::eval_ncmul(const exvector & v) const
711 return inherited::eval_ncmul(v);
713 // Find first noncommutative element and call its eval_ncmul()
714 epvector::const_iterator i = seq.begin(), end = seq.end();
716 if (i->rest.return_type() == return_types::noncommutative)
717 return i->rest.eval_ncmul(v);
720 return inherited::eval_ncmul(v);
723 bool tryfactsubs(const ex & origfactor, const ex & patternfactor, int & nummatches, exmap& repls)
729 if (is_exactly_a<power>(origfactor) && origfactor.op(1).info(info_flags::integer)) {
730 origbase = origfactor.op(0);
731 int expon = ex_to<numeric>(origfactor.op(1)).to_int();
732 origexponent = expon > 0 ? expon : -expon;
733 origexpsign = expon > 0 ? 1 : -1;
735 origbase = origfactor;
744 if (is_exactly_a<power>(patternfactor) && patternfactor.op(1).info(info_flags::integer)) {
745 patternbase = patternfactor.op(0);
746 int expon = ex_to<numeric>(patternfactor.op(1)).to_int();
747 patternexponent = expon > 0 ? expon : -expon;
748 patternexpsign = expon > 0 ? 1 : -1;
750 patternbase = patternfactor;
755 exmap saverepls = repls;
756 if (origexponent < patternexponent || origexpsign != patternexpsign || !origbase.match(patternbase,saverepls))
760 int newnummatches = origexponent / patternexponent;
761 if (newnummatches < nummatches)
762 nummatches = newnummatches;
766 /** Checks whether e matches to the pattern pat and the (possibly to be updated)
767 * list of replacements repls. This matching is in the sense of algebraic
768 * substitutions. Matching starts with pat.op(factor) of the pattern because
769 * the factors before this one have already been matched. The (possibly
770 * updated) number of matches is in nummatches. subsed[i] is true for factors
771 * that already have been replaced by previous substitutions and matched[i]
772 * is true for factors that have been matched by the current match.
774 bool algebraic_match_mul_with_mul(const mul &e, const ex &pat, exmap& repls,
775 int factor, int &nummatches, const std::vector<bool> &subsed,
776 std::vector<bool> &matched)
778 GINAC_ASSERT(subsed.size() == e.nops());
779 GINAC_ASSERT(matched.size() == e.nops());
781 if (factor == (int)pat.nops())
784 for (size_t i=0; i<e.nops(); ++i) {
785 if(subsed[i] || matched[i])
787 exmap newrepls = repls;
788 int newnummatches = nummatches;
789 if (tryfactsubs(e.op(i), pat.op(factor), newnummatches, newrepls)) {
791 if (algebraic_match_mul_with_mul(e, pat, newrepls, factor+1,
792 newnummatches, subsed, matched)) {
794 nummatches = newnummatches;
805 bool mul::has(const ex & pattern, unsigned options) const
807 if(!(options & has_options::algebraic))
808 return basic::has(pattern,options);
809 if(is_a<mul>(pattern)) {
811 int nummatches = std::numeric_limits<int>::max();
812 std::vector<bool> subsed(nops(), false);
813 std::vector<bool> matched(nops(), false);
814 if(algebraic_match_mul_with_mul(*this, pattern, repls, 0, nummatches,
818 return basic::has(pattern, options);
821 ex mul::algebraic_subs_mul(const exmap & m, unsigned options) const
823 std::vector<bool> subsed(nops(), false);
827 for (exmap::const_iterator it = m.begin(); it != m.end(); ++it) {
829 if (is_exactly_a<mul>(it->first)) {
831 int nummatches = std::numeric_limits<int>::max();
832 std::vector<bool> currsubsed(nops(), false);
835 if(!algebraic_match_mul_with_mul(*this, it->first, repls, 0, nummatches, subsed, currsubsed))
838 for (size_t j=0; j<subsed.size(); j++)
842 = it->first.subs(repls, subs_options::no_pattern);
843 divide_by *= power(subsed_pattern, nummatches);
845 = it->second.subs(repls, subs_options::no_pattern);
846 multiply_by *= power(subsed_result, nummatches);
851 for (size_t j=0; j<this->nops(); j++) {
852 int nummatches = std::numeric_limits<int>::max();
854 if (!subsed[j] && tryfactsubs(op(j), it->first, nummatches, repls)){
857 = it->first.subs(repls, subs_options::no_pattern);
858 divide_by *= power(subsed_pattern, nummatches);
860 = it->second.subs(repls, subs_options::no_pattern);
861 multiply_by *= power(subsed_result, nummatches);
867 bool subsfound = false;
868 for (size_t i=0; i<subsed.size(); i++) {
875 return subs_one_level(m, options | subs_options::algebraic);
877 return ((*this)/divide_by)*multiply_by;
880 ex mul::conjugate() const
882 // The base class' method is wrong here because we have to be careful at
883 // branch cuts. power::conjugate takes care of that already, so use it.
884 epvector *newepv = 0;
885 for (epvector::const_iterator i=seq.begin(); i!=seq.end(); ++i) {
887 newepv->push_back(split_ex_to_pair(recombine_pair_to_ex(*i).conjugate()));
890 ex x = recombine_pair_to_ex(*i);
891 ex c = x.conjugate();
895 newepv = new epvector;
896 newepv->reserve(seq.size());
897 for (epvector::const_iterator j=seq.begin(); j!=i; ++j) {
898 newepv->push_back(*j);
900 newepv->push_back(split_ex_to_pair(c));
902 ex x = overall_coeff.conjugate();
903 if (!newepv && are_ex_trivially_equal(x, overall_coeff)) {
906 ex result = thisexpairseq(newepv ? *newepv : seq, x);
914 /** Implementation of ex::diff() for a product. It applies the product rule.
916 ex mul::derivative(const symbol & s) const
918 size_t num = seq.size();
922 // D(a*b*c) = D(a)*b*c + a*D(b)*c + a*b*D(c)
923 epvector mulseq = seq;
924 epvector::const_iterator i = seq.begin(), end = seq.end();
925 epvector::iterator i2 = mulseq.begin();
927 expair ep = split_ex_to_pair(power(i->rest, i->coeff - _ex1) *
930 addseq.push_back((new mul(mulseq, overall_coeff * i->coeff))->setflag(status_flags::dynallocated));
934 return (new add(addseq))->setflag(status_flags::dynallocated);
937 int mul::compare_same_type(const basic & other) const
939 return inherited::compare_same_type(other);
942 unsigned mul::return_type() const
945 // mul without factors: should not happen, but commutates
946 return return_types::commutative;
949 bool all_commutative = true;
950 epvector::const_iterator noncommutative_element; // point to first found nc element
952 epvector::const_iterator i = seq.begin(), end = seq.end();
954 unsigned rt = i->rest.return_type();
955 if (rt == return_types::noncommutative_composite)
956 return rt; // one ncc -> mul also ncc
957 if ((rt == return_types::noncommutative) && (all_commutative)) {
958 // first nc element found, remember position
959 noncommutative_element = i;
960 all_commutative = false;
962 if ((rt == return_types::noncommutative) && (!all_commutative)) {
963 // another nc element found, compare type_infos
964 if (noncommutative_element->rest.return_type_tinfo() != i->rest.return_type_tinfo()) {
965 // different types -> mul is ncc
966 return return_types::noncommutative_composite;
971 // all factors checked
972 return all_commutative ? return_types::commutative : return_types::noncommutative;
975 return_type_t mul::return_type_tinfo() const
978 return make_return_type_t<mul>(); // mul without factors: should not happen
980 // return type_info of first noncommutative element
981 epvector::const_iterator i = seq.begin(), end = seq.end();
983 if (i->rest.return_type() == return_types::noncommutative)
984 return i->rest.return_type_tinfo();
987 // no noncommutative element found, should not happen
988 return make_return_type_t<mul>();
991 ex mul::thisexpairseq(const epvector & v, const ex & oc, bool do_index_renaming) const
993 return (new mul(v, oc, do_index_renaming))->setflag(status_flags::dynallocated);
996 ex mul::thisexpairseq(epvector && vp, const ex & oc, bool do_index_renaming) const
998 return (new mul(std::move(vp), oc, do_index_renaming))->setflag(status_flags::dynallocated);
1001 expair mul::split_ex_to_pair(const ex & e) const
1003 if (is_exactly_a<power>(e)) {
1004 const power & powerref = ex_to<power>(e);
1005 if (is_exactly_a<numeric>(powerref.exponent))
1006 return expair(powerref.basis,powerref.exponent);
1008 return expair(e,_ex1);
1011 expair mul::combine_ex_with_coeff_to_pair(const ex & e,
1014 // to avoid duplication of power simplification rules,
1015 // we create a temporary power object
1016 // otherwise it would be hard to correctly evaluate
1017 // expression like (4^(1/3))^(3/2)
1018 if (c.is_equal(_ex1))
1019 return split_ex_to_pair(e);
1021 return split_ex_to_pair(power(e,c));
1024 expair mul::combine_pair_with_coeff_to_pair(const expair & p,
1027 // to avoid duplication of power simplification rules,
1028 // we create a temporary power object
1029 // otherwise it would be hard to correctly evaluate
1030 // expression like (4^(1/3))^(3/2)
1031 if (c.is_equal(_ex1))
1034 return split_ex_to_pair(power(recombine_pair_to_ex(p),c));
1037 ex mul::recombine_pair_to_ex(const expair & p) const
1039 if (ex_to<numeric>(p.coeff).is_equal(*_num1_p))
1042 return (new power(p.rest,p.coeff))->setflag(status_flags::dynallocated);
1045 bool mul::expair_needs_further_processing(epp it)
1047 if (is_exactly_a<mul>(it->rest) &&
1048 ex_to<numeric>(it->coeff).is_integer()) {
1049 // combined pair is product with integer power -> expand it
1050 *it = split_ex_to_pair(recombine_pair_to_ex(*it));
1053 if (is_exactly_a<numeric>(it->rest)) {
1054 if (it->coeff.is_equal(_ex1)) {
1055 // pair has coeff 1 and must be moved to the end
1058 expair ep = split_ex_to_pair(recombine_pair_to_ex(*it));
1059 if (!ep.is_equal(*it)) {
1060 // combined pair is a numeric power which can be simplified
1068 ex mul::default_overall_coeff() const
1073 void mul::combine_overall_coeff(const ex & c)
1075 GINAC_ASSERT(is_exactly_a<numeric>(overall_coeff));
1076 GINAC_ASSERT(is_exactly_a<numeric>(c));
1077 overall_coeff = ex_to<numeric>(overall_coeff).mul_dyn(ex_to<numeric>(c));
1080 void mul::combine_overall_coeff(const ex & c1, const ex & c2)
1082 GINAC_ASSERT(is_exactly_a<numeric>(overall_coeff));
1083 GINAC_ASSERT(is_exactly_a<numeric>(c1));
1084 GINAC_ASSERT(is_exactly_a<numeric>(c2));
1085 overall_coeff = ex_to<numeric>(overall_coeff).mul_dyn(ex_to<numeric>(c1).power(ex_to<numeric>(c2)));
1088 bool mul::can_make_flat(const expair & p) const
1090 GINAC_ASSERT(is_exactly_a<numeric>(p.coeff));
1091 // this assertion will probably fail somewhere
1092 // it would require a more careful make_flat, obeying the power laws
1093 // probably should return true only if p.coeff is integer
1094 return ex_to<numeric>(p.coeff).is_equal(*_num1_p);
1097 bool mul::can_be_further_expanded(const ex & e)
1099 if (is_exactly_a<mul>(e)) {
1100 for (epvector::const_iterator cit = ex_to<mul>(e).seq.begin(); cit != ex_to<mul>(e).seq.end(); ++cit) {
1101 if (is_exactly_a<add>(cit->rest) && cit->coeff.info(info_flags::posint))
1104 } else if (is_exactly_a<power>(e)) {
1105 if (is_exactly_a<add>(e.op(0)) && e.op(1).info(info_flags::posint))
1111 ex mul::expand(unsigned options) const
1114 // trivial case: expanding the monomial (~ 30% of all calls)
1115 epvector::const_iterator i = seq.begin(), seq_end = seq.end();
1116 while ((i != seq.end()) && is_a<symbol>(i->rest) && i->coeff.info(info_flags::integer))
1119 setflag(status_flags::expanded);
1124 // do not rename indices if the object has no indices at all
1125 if ((!(options & expand_options::expand_rename_idx)) &&
1126 this->info(info_flags::has_indices))
1127 options |= expand_options::expand_rename_idx;
1129 const bool skip_idx_rename = !(options & expand_options::expand_rename_idx);
1131 // First, expand the children
1132 epvector expanded = expandchildren(options);
1133 const epvector & expanded_seq = (expanded.empty() ? seq : expanded);
1135 // Now, look for all the factors that are sums and multiply each one out
1136 // with the next one that is found while collecting the factors which are
1138 ex last_expanded = _ex1;
1141 non_adds.reserve(expanded_seq.size());
1143 for (epvector::const_iterator cit = expanded_seq.begin(); cit != expanded_seq.end(); ++cit) {
1144 if (is_exactly_a<add>(cit->rest) &&
1145 (cit->coeff.is_equal(_ex1))) {
1146 if (is_exactly_a<add>(last_expanded)) {
1148 // Expand a product of two sums, aggressive version.
1149 // Caring for the overall coefficients in separate loops can
1150 // sometimes give a performance gain of up to 15%!
1152 const int sizedifference = ex_to<add>(last_expanded).seq.size()-ex_to<add>(cit->rest).seq.size();
1153 // add2 is for the inner loop and should be the bigger of the two sums
1154 // in the presence of asymptotically good sorting:
1155 const add& add1 = (sizedifference<0 ? ex_to<add>(last_expanded) : ex_to<add>(cit->rest));
1156 const add& add2 = (sizedifference<0 ? ex_to<add>(cit->rest) : ex_to<add>(last_expanded));
1157 const epvector::const_iterator add1begin = add1.seq.begin();
1158 const epvector::const_iterator add1end = add1.seq.end();
1159 const epvector::const_iterator add2begin = add2.seq.begin();
1160 const epvector::const_iterator add2end = add2.seq.end();
1162 distrseq.reserve(add1.seq.size()+add2.seq.size());
1164 // Multiply add2 with the overall coefficient of add1 and append it to distrseq:
1165 if (!add1.overall_coeff.is_zero()) {
1166 if (add1.overall_coeff.is_equal(_ex1))
1167 distrseq.insert(distrseq.end(),add2begin,add2end);
1169 for (epvector::const_iterator i=add2begin; i!=add2end; ++i)
1170 distrseq.push_back(expair(i->rest, ex_to<numeric>(i->coeff).mul_dyn(ex_to<numeric>(add1.overall_coeff))));
1173 // Multiply add1 with the overall coefficient of add2 and append it to distrseq:
1174 if (!add2.overall_coeff.is_zero()) {
1175 if (add2.overall_coeff.is_equal(_ex1))
1176 distrseq.insert(distrseq.end(),add1begin,add1end);
1178 for (epvector::const_iterator i=add1begin; i!=add1end; ++i)
1179 distrseq.push_back(expair(i->rest, ex_to<numeric>(i->coeff).mul_dyn(ex_to<numeric>(add2.overall_coeff))));
1182 // Compute the new overall coefficient and put it together:
1183 ex tmp_accu = (new add(distrseq, add1.overall_coeff*add2.overall_coeff))->setflag(status_flags::dynallocated);
1185 exvector add1_dummy_indices, add2_dummy_indices, add_indices;
1188 if (!skip_idx_rename) {
1189 for (epvector::const_iterator i=add1begin; i!=add1end; ++i) {
1190 add_indices = get_all_dummy_indices_safely(i->rest);
1191 add1_dummy_indices.insert(add1_dummy_indices.end(), add_indices.begin(), add_indices.end());
1193 for (epvector::const_iterator i=add2begin; i!=add2end; ++i) {
1194 add_indices = get_all_dummy_indices_safely(i->rest);
1195 add2_dummy_indices.insert(add2_dummy_indices.end(), add_indices.begin(), add_indices.end());
1198 sort(add1_dummy_indices.begin(), add1_dummy_indices.end(), ex_is_less());
1199 sort(add2_dummy_indices.begin(), add2_dummy_indices.end(), ex_is_less());
1200 dummy_subs = rename_dummy_indices_uniquely(add1_dummy_indices, add2_dummy_indices);
1203 // Multiply explicitly all non-numeric terms of add1 and add2:
1204 for (epvector::const_iterator i2=add2begin; i2!=add2end; ++i2) {
1205 // We really have to combine terms here in order to compactify
1206 // the result. Otherwise it would become waayy tooo bigg.
1207 numeric oc(*_num0_p);
1209 distrseq2.reserve(add1.seq.size());
1210 const ex i2_new = (skip_idx_rename || (dummy_subs.op(0).nops() == 0) ?
1212 i2->rest.subs(ex_to<lst>(dummy_subs.op(0)),
1213 ex_to<lst>(dummy_subs.op(1)), subs_options::no_pattern));
1214 for (epvector::const_iterator i1=add1begin; i1!=add1end; ++i1) {
1215 // Don't push_back expairs which might have a rest that evaluates to a numeric,
1216 // since that would violate an invariant of expairseq:
1217 const ex rest = (new mul(i1->rest, i2_new))->setflag(status_flags::dynallocated);
1218 if (is_exactly_a<numeric>(rest)) {
1219 oc += ex_to<numeric>(rest).mul(ex_to<numeric>(i1->coeff).mul(ex_to<numeric>(i2->coeff)));
1221 distrseq2.push_back(expair(rest, ex_to<numeric>(i1->coeff).mul_dyn(ex_to<numeric>(i2->coeff))));
1224 tmp_accu += (new add(distrseq2, oc))->setflag(status_flags::dynallocated);
1226 last_expanded = tmp_accu;
1228 if (!last_expanded.is_equal(_ex1))
1229 non_adds.push_back(split_ex_to_pair(last_expanded));
1230 last_expanded = cit->rest;
1234 non_adds.push_back(*cit);
1238 // Now the only remaining thing to do is to multiply the factors which
1239 // were not sums into the "last_expanded" sum
1240 if (is_exactly_a<add>(last_expanded)) {
1241 size_t n = last_expanded.nops();
1243 distrseq.reserve(n);
1245 if (! skip_idx_rename) {
1246 va = get_all_dummy_indices_safely(mul(non_adds));
1247 sort(va.begin(), va.end(), ex_is_less());
1250 for (size_t i=0; i<n; ++i) {
1251 epvector factors = non_adds;
1252 if (skip_idx_rename)
1253 factors.push_back(split_ex_to_pair(last_expanded.op(i)));
1255 factors.push_back(split_ex_to_pair(rename_dummy_indices_uniquely(va, last_expanded.op(i))));
1256 ex term = (new mul(factors, overall_coeff))->setflag(status_flags::dynallocated);
1257 if (can_be_further_expanded(term)) {
1258 distrseq.push_back(term.expand());
1261 ex_to<basic>(term).setflag(status_flags::expanded);
1262 distrseq.push_back(term);
1266 return ((new add(distrseq))->
1267 setflag(status_flags::dynallocated | (options == 0 ? status_flags::expanded : 0)));
1270 non_adds.push_back(split_ex_to_pair(last_expanded));
1271 ex result = (new mul(non_adds, overall_coeff))->setflag(status_flags::dynallocated);
1272 if (can_be_further_expanded(result)) {
1273 return result.expand();
1276 ex_to<basic>(result).setflag(status_flags::expanded);
1283 // new virtual functions which can be overridden by derived classes
1289 // non-virtual functions in this class
1293 /** Member-wise expand the expairs representing this sequence. This must be
1294 * overridden from expairseq::expandchildren() and done iteratively in order
1295 * to allow for early cancellations and thus safe memory.
1297 * @see mul::expand()
1298 * @return epvector containing expanded pairs, empty if no members
1299 * had to be changed. */
1300 epvector mul::expandchildren(unsigned options) const
1302 const epvector::const_iterator last = seq.end();
1303 epvector::const_iterator cit = seq.begin();
1305 const ex & factor = recombine_pair_to_ex(*cit);
1306 const ex & expanded_factor = factor.expand(options);
1307 if (!are_ex_trivially_equal(factor,expanded_factor)) {
1309 // something changed, copy seq, eval and return it
1311 s.reserve(seq.size());
1313 // copy parts of seq which are known not to have changed
1314 epvector::const_iterator cit2 = seq.begin();
1320 // copy first changed element
1321 s.push_back(split_ex_to_pair(expanded_factor));
1325 while (cit2!=last) {
1326 s.push_back(split_ex_to_pair(recombine_pair_to_ex(*cit2).expand(options)));
1334 return epvector(); // nothing has changed
1337 GINAC_BIND_UNARCHIVER(mul);
1339 } // namespace GiNaC