3 * Implementation of GiNaC's sums 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"
40 GINAC_IMPLEMENT_REGISTERED_CLASS_OPT(add, expairseq,
41 print_func<print_context>(&add::do_print).
42 print_func<print_latex>(&add::do_print_latex).
43 print_func<print_csrc>(&add::do_print_csrc).
44 print_func<print_tree>(&add::do_print_tree).
45 print_func<print_python_repr>(&add::do_print_python_repr))
48 // default constructor
61 add::add(const ex & lh, const ex & rh)
64 construct_from_2_ex(lh,rh);
65 GINAC_ASSERT(is_canonical());
68 add::add(const exvector & v)
71 construct_from_exvector(v);
72 GINAC_ASSERT(is_canonical());
75 add::add(const epvector & v)
78 construct_from_epvector(v);
79 GINAC_ASSERT(is_canonical());
82 add::add(const epvector & v, const ex & oc)
85 construct_from_epvector(v);
86 GINAC_ASSERT(is_canonical());
89 add::add(epvector && vp, const ex & oc)
92 construct_from_epvector(std::move(vp));
93 GINAC_ASSERT(is_canonical());
100 GINAC_BIND_UNARCHIVER(add);
103 // functions overriding virtual functions from base classes
108 void add::print_add(const print_context & c, const char *openbrace, const char *closebrace, const char *mul_sym, unsigned level) const
110 if (precedence() <= level)
111 c.s << openbrace << '(';
116 // First print the overall numeric coefficient, if present
117 if (!overall_coeff.is_zero()) {
118 overall_coeff.print(c, 0);
122 // Then proceed with the remaining factors
123 epvector::const_iterator it = seq.begin(), itend = seq.end();
124 while (it != itend) {
125 coeff = ex_to<numeric>(it->coeff);
127 if (coeff.csgn() == -1) c.s << '-'; else c.s << '+';
129 if (coeff.csgn() == -1) c.s << '-';
132 if (!coeff.is_equal(*_num1_p) &&
133 !coeff.is_equal(*_num_1_p)) {
134 if (coeff.is_rational()) {
135 if (coeff.is_negative())
140 if (coeff.csgn() == -1)
141 (-coeff).print(c, precedence());
143 coeff.print(c, precedence());
147 it->rest.print(c, precedence());
151 if (precedence() <= level)
152 c.s << ')' << closebrace;
155 void add::do_print(const print_context & c, unsigned level) const
157 print_add(c, "", "", "*", level);
160 void add::do_print_latex(const print_latex & c, unsigned level) const
162 print_add(c, "{", "}", " ", level);
165 void add::do_print_csrc(const print_csrc & c, unsigned level) const
167 if (precedence() <= level)
170 // Print arguments, separated by "+" or "-"
171 epvector::const_iterator it = seq.begin(), itend = seq.end();
172 char separator = ' ';
173 while (it != itend) {
175 // If the coefficient is negative, separator is "-"
176 if (it->coeff.is_equal(_ex_1) ||
177 ex_to<numeric>(it->coeff).numer().is_equal(*_num_1_p))
180 if (it->coeff.is_equal(_ex1) || it->coeff.is_equal(_ex_1)) {
181 it->rest.print(c, precedence());
182 } else if (ex_to<numeric>(it->coeff).numer().is_equal(*_num1_p) ||
183 ex_to<numeric>(it->coeff).numer().is_equal(*_num_1_p))
185 it->rest.print(c, precedence());
187 ex_to<numeric>(it->coeff).denom().print(c, precedence());
189 it->coeff.print(c, precedence());
191 it->rest.print(c, precedence());
198 if (!overall_coeff.is_zero()) {
199 if (overall_coeff.info(info_flags::positive)
200 || is_a<print_csrc_cl_N>(c) || !overall_coeff.info(info_flags::real)) // sign inside ctor argument
202 overall_coeff.print(c, precedence());
205 if (precedence() <= level)
209 void add::do_print_python_repr(const print_python_repr & c, unsigned level) const
211 c.s << class_name() << '(';
213 for (size_t i=1; i<nops(); ++i) {
220 bool add::info(unsigned inf) const
223 case info_flags::polynomial:
224 case info_flags::integer_polynomial:
225 case info_flags::cinteger_polynomial:
226 case info_flags::rational_polynomial:
227 case info_flags::real:
228 case info_flags::rational:
229 case info_flags::integer:
230 case info_flags::crational:
231 case info_flags::cinteger:
232 case info_flags::positive:
233 case info_flags::nonnegative:
234 case info_flags::posint:
235 case info_flags::nonnegint:
236 case info_flags::even:
237 case info_flags::crational_polynomial:
238 case info_flags::rational_function: {
239 epvector::const_iterator i = seq.begin(), end = seq.end();
241 if (!(recombine_pair_to_ex(*i).info(inf)))
245 if (overall_coeff.is_zero() && (inf == info_flags::positive || inf == info_flags::posint))
247 return overall_coeff.info(inf);
249 case info_flags::algebraic: {
250 epvector::const_iterator i = seq.begin(), end = seq.end();
252 if ((recombine_pair_to_ex(*i).info(inf)))
259 return inherited::info(inf);
262 bool add::is_polynomial(const ex & var) const
264 for (epvector::const_iterator i=seq.begin(); i!=seq.end(); ++i) {
265 if (!(i->rest).is_polynomial(var)) {
272 int add::degree(const ex & s) const
274 int deg = std::numeric_limits<int>::min();
275 if (!overall_coeff.is_zero())
278 // Find maximum of degrees of individual terms
279 epvector::const_iterator i = seq.begin(), end = seq.end();
281 int cur_deg = i->rest.degree(s);
289 int add::ldegree(const ex & s) const
291 int deg = std::numeric_limits<int>::max();
292 if (!overall_coeff.is_zero())
295 // Find minimum of degrees of individual terms
296 epvector::const_iterator i = seq.begin(), end = seq.end();
298 int cur_deg = i->rest.ldegree(s);
306 ex add::coeff(const ex & s, int n) const
309 epvector coeffseq_cliff;
310 int rl = clifford_max_label(s);
311 bool do_clifford = (rl != -1);
312 bool nonscalar = false;
314 // Calculate sum of coefficients in each term
315 epvector::const_iterator i = seq.begin(), end = seq.end();
317 ex restcoeff = i->rest.coeff(s, n);
318 if (!restcoeff.is_zero()) {
320 if (clifford_max_label(restcoeff) == -1) {
321 coeffseq_cliff.push_back(combine_ex_with_coeff_to_pair(ncmul(restcoeff, dirac_ONE(rl)), i->coeff));
323 coeffseq_cliff.push_back(combine_ex_with_coeff_to_pair(restcoeff, i->coeff));
327 coeffseq.push_back(combine_ex_with_coeff_to_pair(restcoeff, i->coeff));
332 return (new add(nonscalar ? std::move(coeffseq_cliff) : std::move(coeffseq),
333 n==0 ? overall_coeff : _ex0))->setflag(status_flags::dynallocated);
336 /** Perform automatic term rewriting rules in this class. In the following
337 * x stands for a symbolic variables of type ex and c stands for such
338 * an expression that contain a plain number.
342 * @param level cut-off in recursive evaluation */
343 ex add::eval(int level) const
345 epvector evaled = evalchildren(level);
346 if (!evaled.empty()) {
347 // do more evaluation later
348 return (new add(std::move(evaled), overall_coeff))->
349 setflag(status_flags::dynallocated);
352 #ifdef DO_GINAC_ASSERT
353 epvector::const_iterator i = seq.begin(), end = seq.end();
355 GINAC_ASSERT(!is_exactly_a<add>(i->rest));
358 #endif // def DO_GINAC_ASSERT
360 if (flags & status_flags::evaluated) {
361 GINAC_ASSERT(seq.size()>0);
362 GINAC_ASSERT(seq.size()>1 || !overall_coeff.is_zero());
366 int seq_size = seq.size();
369 return overall_coeff;
370 } else if (seq_size == 1 && overall_coeff.is_zero()) {
372 return recombine_pair_to_ex(*(seq.begin()));
373 } else if (!overall_coeff.is_zero() && seq[0].rest.return_type() != return_types::commutative) {
374 throw (std::logic_error("add::eval(): sum of non-commutative objects has non-zero numeric term"));
377 // if any terms in the sum still are purely numeric, then they are more
378 // appropriately collected into the overall coefficient
379 epvector::const_iterator last = seq.end();
380 epvector::const_iterator j = seq.begin();
381 int terms_to_collect = 0;
383 if (unlikely(is_a<numeric>(j->rest)))
387 if (terms_to_collect) {
389 s.reserve(seq_size - terms_to_collect);
390 numeric oc = *_num1_p;
393 if (unlikely(is_a<numeric>(j->rest)))
394 oc = oc.mul(ex_to<numeric>(j->rest)).mul(ex_to<numeric>(j->coeff));
399 return (new add(std::move(s), ex_to<numeric>(overall_coeff).add_dyn(oc)))
400 ->setflag(status_flags::dynallocated);
406 ex add::evalm() const
408 // Evaluate children first and add up all matrices. Stop if there's one
409 // term that is not a matrix.
411 s.reserve(seq.size());
413 bool all_matrices = true;
414 bool first_term = true;
417 epvector::const_iterator it = seq.begin(), itend = seq.end();
418 while (it != itend) {
419 const ex &m = recombine_pair_to_ex(*it).evalm();
420 s.push_back(split_ex_to_pair(m));
421 if (is_a<matrix>(m)) {
423 sum = ex_to<matrix>(m);
426 sum = sum.add(ex_to<matrix>(m));
428 all_matrices = false;
433 return sum + overall_coeff;
435 return (new add(std::move(s), overall_coeff))->setflag(status_flags::dynallocated);
438 ex add::conjugate() const
441 for (size_t i=0; i<nops(); ++i) {
443 v->push_back(op(i).conjugate());
447 ex ccterm = term.conjugate();
448 if (are_ex_trivially_equal(term, ccterm))
452 for (size_t j=0; j<i; ++j)
454 v->push_back(ccterm);
464 ex add::real_part() const
467 v.reserve(seq.size());
468 for (epvector::const_iterator i=seq.begin(); i!=seq.end(); ++i)
469 if ((i->coeff).info(info_flags::real)) {
470 ex rp = (i->rest).real_part();
472 v.push_back(expair(rp, i->coeff));
474 ex rp=recombine_pair_to_ex(*i).real_part();
476 v.push_back(split_ex_to_pair(rp));
478 return (new add(v, overall_coeff.real_part()))
479 -> setflag(status_flags::dynallocated);
482 ex add::imag_part() const
485 v.reserve(seq.size());
486 for (epvector::const_iterator i=seq.begin(); i!=seq.end(); ++i)
487 if ((i->coeff).info(info_flags::real)) {
488 ex ip = (i->rest).imag_part();
490 v.push_back(expair(ip, i->coeff));
492 ex ip=recombine_pair_to_ex(*i).imag_part();
494 v.push_back(split_ex_to_pair(ip));
496 return (new add(v, overall_coeff.imag_part()))
497 -> setflag(status_flags::dynallocated);
500 ex add::eval_ncmul(const exvector & v) const
503 return inherited::eval_ncmul(v);
505 return seq.begin()->rest.eval_ncmul(v);
510 /** Implementation of ex::diff() for a sum. It differentiates each term.
512 ex add::derivative(const symbol & y) const
515 s.reserve(seq.size());
517 // Only differentiate the "rest" parts of the expairs. This is faster
518 // than the default implementation in basic::derivative() although
519 // if performs the same function (differentiate each term).
520 epvector::const_iterator i = seq.begin(), end = seq.end();
522 s.push_back(combine_ex_with_coeff_to_pair(i->rest.diff(y), i->coeff));
525 return (new add(std::move(s), _ex0))->setflag(status_flags::dynallocated);
528 int add::compare_same_type(const basic & other) const
530 return inherited::compare_same_type(other);
533 unsigned add::return_type() const
536 return return_types::commutative;
538 return seq.begin()->rest.return_type();
541 return_type_t add::return_type_tinfo() const
544 return make_return_type_t<add>();
546 return seq.begin()->rest.return_type_tinfo();
549 // Note: do_index_renaming is ignored because it makes no sense for an add.
550 ex add::thisexpairseq(const epvector & v, const ex & oc, bool do_index_renaming) const
552 return (new add(v,oc))->setflag(status_flags::dynallocated);
555 // Note: do_index_renaming is ignored because it makes no sense for an add.
556 ex add::thisexpairseq(epvector && vp, const ex & oc, bool do_index_renaming) const
558 return (new add(std::move(vp), oc))->setflag(status_flags::dynallocated);
561 expair add::split_ex_to_pair(const ex & e) const
563 if (is_exactly_a<mul>(e)) {
564 const mul &mulref(ex_to<mul>(e));
565 const ex &numfactor = mulref.overall_coeff;
566 mul *mulcopyp = new mul(mulref);
567 mulcopyp->overall_coeff = _ex1;
568 mulcopyp->clearflag(status_flags::evaluated);
569 mulcopyp->clearflag(status_flags::hash_calculated);
570 mulcopyp->setflag(status_flags::dynallocated);
571 return expair(*mulcopyp,numfactor);
573 return expair(e,_ex1);
576 expair add::combine_ex_with_coeff_to_pair(const ex & e,
579 GINAC_ASSERT(is_exactly_a<numeric>(c));
580 if (is_exactly_a<mul>(e)) {
581 const mul &mulref(ex_to<mul>(e));
582 const ex &numfactor = mulref.overall_coeff;
583 mul *mulcopyp = new mul(mulref);
584 mulcopyp->overall_coeff = _ex1;
585 mulcopyp->clearflag(status_flags::evaluated);
586 mulcopyp->clearflag(status_flags::hash_calculated);
587 mulcopyp->setflag(status_flags::dynallocated);
588 if (c.is_equal(_ex1))
589 return expair(*mulcopyp, numfactor);
590 else if (numfactor.is_equal(_ex1))
591 return expair(*mulcopyp, c);
593 return expair(*mulcopyp, ex_to<numeric>(numfactor).mul_dyn(ex_to<numeric>(c)));
594 } else if (is_exactly_a<numeric>(e)) {
595 if (c.is_equal(_ex1))
596 return expair(e, _ex1);
597 return expair(ex_to<numeric>(e).mul_dyn(ex_to<numeric>(c)), _ex1);
602 expair add::combine_pair_with_coeff_to_pair(const expair & p,
605 GINAC_ASSERT(is_exactly_a<numeric>(p.coeff));
606 GINAC_ASSERT(is_exactly_a<numeric>(c));
608 if (is_exactly_a<numeric>(p.rest)) {
609 GINAC_ASSERT(ex_to<numeric>(p.coeff).is_equal(*_num1_p)); // should be normalized
610 return expair(ex_to<numeric>(p.rest).mul_dyn(ex_to<numeric>(c)),_ex1);
613 return expair(p.rest,ex_to<numeric>(p.coeff).mul_dyn(ex_to<numeric>(c)));
616 ex add::recombine_pair_to_ex(const expair & p) const
618 if (ex_to<numeric>(p.coeff).is_equal(*_num1_p))
621 return (new mul(p.rest,p.coeff))->setflag(status_flags::dynallocated);
624 ex add::expand(unsigned options) const
626 epvector expanded = expandchildren(options);
627 if (expanded.empty())
628 return (options == 0) ? setflag(status_flags::expanded) : *this;
630 return (new add(std::move(expanded), overall_coeff))->setflag(status_flags::dynallocated |
631 (options == 0 ? status_flags::expanded : 0));