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(std::auto_ptr<epvector> vp, const ex & oc)
91 GINAC_ASSERT(vp.get()!=0);
93 construct_from_epvector(*vp);
94 GINAC_ASSERT(is_canonical());
101 GINAC_BIND_UNARCHIVER(add);
104 // functions overriding virtual functions from base classes
109 void add::print_add(const print_context & c, const char *openbrace, const char *closebrace, const char *mul_sym, unsigned level) const
111 if (precedence() <= level)
112 c.s << openbrace << '(';
117 // First print the overall numeric coefficient, if present
118 if (!overall_coeff.is_zero()) {
119 overall_coeff.print(c, 0);
123 // Then proceed with the remaining factors
124 epvector::const_iterator it = seq.begin(), itend = seq.end();
125 while (it != itend) {
126 coeff = ex_to<numeric>(it->coeff);
128 if (coeff.csgn() == -1) c.s << '-'; else c.s << '+';
130 if (coeff.csgn() == -1) c.s << '-';
133 if (!coeff.is_equal(*_num1_p) &&
134 !coeff.is_equal(*_num_1_p)) {
135 if (coeff.is_rational()) {
136 if (coeff.is_negative())
141 if (coeff.csgn() == -1)
142 (-coeff).print(c, precedence());
144 coeff.print(c, precedence());
148 it->rest.print(c, precedence());
152 if (precedence() <= level)
153 c.s << ')' << closebrace;
156 void add::do_print(const print_context & c, unsigned level) const
158 print_add(c, "", "", "*", level);
161 void add::do_print_latex(const print_latex & c, unsigned level) const
163 print_add(c, "{", "}", " ", level);
166 void add::do_print_csrc(const print_csrc & c, unsigned level) const
168 if (precedence() <= level)
171 // Print arguments, separated by "+" or "-"
172 epvector::const_iterator it = seq.begin(), itend = seq.end();
173 char separator = ' ';
174 while (it != itend) {
176 // If the coefficient is negative, separator is "-"
177 if (it->coeff.is_equal(_ex_1) ||
178 ex_to<numeric>(it->coeff).numer().is_equal(*_num_1_p))
181 if (it->coeff.is_equal(_ex1) || it->coeff.is_equal(_ex_1)) {
182 it->rest.print(c, precedence());
183 } else if (ex_to<numeric>(it->coeff).numer().is_equal(*_num1_p) ||
184 ex_to<numeric>(it->coeff).numer().is_equal(*_num_1_p))
186 it->rest.print(c, precedence());
188 ex_to<numeric>(it->coeff).denom().print(c, precedence());
190 it->coeff.print(c, precedence());
192 it->rest.print(c, precedence());
199 if (!overall_coeff.is_zero()) {
200 if (overall_coeff.info(info_flags::positive)
201 || is_a<print_csrc_cl_N>(c) || !overall_coeff.info(info_flags::real)) // sign inside ctor argument
203 overall_coeff.print(c, precedence());
206 if (precedence() <= level)
210 void add::do_print_python_repr(const print_python_repr & c, unsigned level) const
212 c.s << class_name() << '(';
214 for (size_t i=1; i<nops(); ++i) {
221 bool add::info(unsigned inf) const
224 case info_flags::polynomial:
225 case info_flags::integer_polynomial:
226 case info_flags::cinteger_polynomial:
227 case info_flags::rational_polynomial:
228 case info_flags::real:
229 case info_flags::rational:
230 case info_flags::integer:
231 case info_flags::crational:
232 case info_flags::cinteger:
233 case info_flags::positive:
234 case info_flags::nonnegative:
235 case info_flags::posint:
236 case info_flags::nonnegint:
237 case info_flags::even:
238 case info_flags::crational_polynomial:
239 case info_flags::rational_function: {
240 epvector::const_iterator i = seq.begin(), end = seq.end();
242 if (!(recombine_pair_to_ex(*i).info(inf)))
246 if (overall_coeff.is_zero() && (inf == info_flags::positive || inf == info_flags::posint))
248 return overall_coeff.info(inf);
250 case info_flags::algebraic: {
251 epvector::const_iterator i = seq.begin(), end = seq.end();
253 if ((recombine_pair_to_ex(*i).info(inf)))
260 return inherited::info(inf);
263 bool add::is_polynomial(const ex & var) const
265 for (epvector::const_iterator i=seq.begin(); i!=seq.end(); ++i) {
266 if (!(i->rest).is_polynomial(var)) {
273 int add::degree(const ex & s) const
275 int deg = std::numeric_limits<int>::min();
276 if (!overall_coeff.is_zero())
279 // Find maximum of degrees of individual terms
280 epvector::const_iterator i = seq.begin(), end = seq.end();
282 int cur_deg = i->rest.degree(s);
290 int add::ldegree(const ex & s) const
292 int deg = std::numeric_limits<int>::max();
293 if (!overall_coeff.is_zero())
296 // Find minimum of degrees of individual terms
297 epvector::const_iterator i = seq.begin(), end = seq.end();
299 int cur_deg = i->rest.ldegree(s);
307 ex add::coeff(const ex & s, int n) const
309 std::auto_ptr<epvector> coeffseq(new epvector);
310 std::auto_ptr<epvector> coeffseq_cliff(new epvector);
311 int rl = clifford_max_label(s);
312 bool do_clifford = (rl != -1);
313 bool nonscalar = false;
315 // Calculate sum of coefficients in each term
316 epvector::const_iterator i = seq.begin(), end = seq.end();
318 ex restcoeff = i->rest.coeff(s, n);
319 if (!restcoeff.is_zero()) {
321 if (clifford_max_label(restcoeff) == -1) {
322 coeffseq_cliff->push_back(combine_ex_with_coeff_to_pair(ncmul(restcoeff, dirac_ONE(rl)), i->coeff));
324 coeffseq_cliff->push_back(combine_ex_with_coeff_to_pair(restcoeff, i->coeff));
328 coeffseq->push_back(combine_ex_with_coeff_to_pair(restcoeff, i->coeff));
333 return (new add(nonscalar ? coeffseq_cliff : coeffseq,
334 n==0 ? overall_coeff : _ex0))->setflag(status_flags::dynallocated);
337 /** Perform automatic term rewriting rules in this class. In the following
338 * x stands for a symbolic variables of type ex and c stands for such
339 * an expression that contain a plain number.
343 * @param level cut-off in recursive evaluation */
344 ex add::eval(int level) const
346 std::auto_ptr<epvector> evaled_seqp = evalchildren(level);
347 if (unlikely(evaled_seqp.get() != 0)) {
348 // do more evaluation later
349 return (new add(evaled_seqp, overall_coeff))->
350 setflag(status_flags::dynallocated);
353 #ifdef DO_GINAC_ASSERT
354 epvector::const_iterator i = seq.begin(), end = seq.end();
356 GINAC_ASSERT(!is_exactly_a<add>(i->rest));
359 #endif // def DO_GINAC_ASSERT
361 if (flags & status_flags::evaluated) {
362 GINAC_ASSERT(seq.size()>0);
363 GINAC_ASSERT(seq.size()>1 || !overall_coeff.is_zero());
367 int seq_size = seq.size();
370 return overall_coeff;
371 } else if (seq_size == 1 && overall_coeff.is_zero()) {
373 return recombine_pair_to_ex(*(seq.begin()));
374 } else if (!overall_coeff.is_zero() && seq[0].rest.return_type() != return_types::commutative) {
375 throw (std::logic_error("add::eval(): sum of non-commutative objects has non-zero numeric term"));
378 // if any terms in the sum still are purely numeric, then they are more
379 // appropriately collected into the overall coefficient
380 epvector::const_iterator last = seq.end();
381 epvector::const_iterator j = seq.begin();
382 int terms_to_collect = 0;
384 if (unlikely(is_a<numeric>(j->rest)))
388 if (terms_to_collect) {
389 std::auto_ptr<epvector> s(new epvector);
390 s->reserve(seq_size - terms_to_collect);
391 numeric oc = *_num0_p;
394 if (unlikely(is_a<numeric>(j->rest)))
395 oc = oc.add(ex_to<numeric>(j->rest).mul(ex_to<numeric>(j->coeff)));
400 return (new add(s, ex_to<numeric>(overall_coeff).add_dyn(oc)))
401 ->setflag(status_flags::dynallocated);
407 ex add::evalm() const
409 // Evaluate children first and add up all matrices. Stop if there's one
410 // term that is not a matrix.
411 std::auto_ptr<epvector> s(new epvector);
412 s->reserve(seq.size());
414 bool all_matrices = true;
415 bool first_term = true;
418 epvector::const_iterator it = seq.begin(), itend = seq.end();
419 while (it != itend) {
420 const ex &m = recombine_pair_to_ex(*it).evalm();
421 s->push_back(split_ex_to_pair(m));
422 if (is_a<matrix>(m)) {
424 sum = ex_to<matrix>(m);
427 sum = sum.add(ex_to<matrix>(m));
429 all_matrices = false;
434 return sum + overall_coeff;
436 return (new add(s, overall_coeff))->setflag(status_flags::dynallocated);
439 ex add::conjugate() const
442 for (size_t i=0; i<nops(); ++i) {
444 v->push_back(op(i).conjugate());
448 ex ccterm = term.conjugate();
449 if (are_ex_trivially_equal(term, ccterm))
453 for (size_t j=0; j<i; ++j)
455 v->push_back(ccterm);
465 ex add::real_part() const
468 v.reserve(seq.size());
469 for (epvector::const_iterator i=seq.begin(); i!=seq.end(); ++i)
470 if ((i->coeff).info(info_flags::real)) {
471 ex rp = (i->rest).real_part();
473 v.push_back(expair(rp, i->coeff));
475 ex rp=recombine_pair_to_ex(*i).real_part();
477 v.push_back(split_ex_to_pair(rp));
479 return (new add(v, overall_coeff.real_part()))
480 -> setflag(status_flags::dynallocated);
483 ex add::imag_part() const
486 v.reserve(seq.size());
487 for (epvector::const_iterator i=seq.begin(); i!=seq.end(); ++i)
488 if ((i->coeff).info(info_flags::real)) {
489 ex ip = (i->rest).imag_part();
491 v.push_back(expair(ip, i->coeff));
493 ex ip=recombine_pair_to_ex(*i).imag_part();
495 v.push_back(split_ex_to_pair(ip));
497 return (new add(v, overall_coeff.imag_part()))
498 -> setflag(status_flags::dynallocated);
501 ex add::eval_ncmul(const exvector & v) const
504 return inherited::eval_ncmul(v);
506 return seq.begin()->rest.eval_ncmul(v);
511 /** Implementation of ex::diff() for a sum. It differentiates each term.
513 ex add::derivative(const symbol & y) const
515 std::auto_ptr<epvector> s(new epvector);
516 s->reserve(seq.size());
518 // Only differentiate the "rest" parts of the expairs. This is faster
519 // than the default implementation in basic::derivative() although
520 // if performs the same function (differentiate each term).
521 epvector::const_iterator i = seq.begin(), end = seq.end();
523 s->push_back(combine_ex_with_coeff_to_pair(i->rest.diff(y), i->coeff));
526 return (new add(s, _ex0))->setflag(status_flags::dynallocated);
529 int add::compare_same_type(const basic & other) const
531 return inherited::compare_same_type(other);
534 unsigned add::return_type() const
537 return return_types::commutative;
539 return seq.begin()->rest.return_type();
542 return_type_t add::return_type_tinfo() const
545 return make_return_type_t<add>();
547 return seq.begin()->rest.return_type_tinfo();
550 // Note: do_index_renaming is ignored because it makes no sense for an add.
551 ex add::thisexpairseq(const epvector & v, const ex & oc, bool do_index_renaming) const
553 return (new add(v,oc))->setflag(status_flags::dynallocated);
556 // Note: do_index_renaming is ignored because it makes no sense for an add.
557 ex add::thisexpairseq(std::auto_ptr<epvector> vp, const ex & oc, bool do_index_renaming) const
559 return (new add(vp,oc))->setflag(status_flags::dynallocated);
562 expair add::split_ex_to_pair(const ex & e) const
564 if (is_exactly_a<mul>(e)) {
565 const mul &mulref(ex_to<mul>(e));
566 const ex &numfactor = mulref.overall_coeff;
567 if (numfactor.is_equal(_ex1))
568 return expair(e, _ex1);
569 mul *mulcopyp = new mul(mulref);
570 mulcopyp->overall_coeff = _ex1;
571 mulcopyp->clearflag(status_flags::evaluated);
572 mulcopyp->clearflag(status_flags::hash_calculated);
573 mulcopyp->setflag(status_flags::dynallocated);
574 return expair(*mulcopyp,numfactor);
576 return expair(e,_ex1);
579 expair add::combine_ex_with_coeff_to_pair(const ex & e,
582 GINAC_ASSERT(is_exactly_a<numeric>(c));
583 if (is_exactly_a<mul>(e)) {
584 const mul &mulref(ex_to<mul>(e));
585 const ex &numfactor = mulref.overall_coeff;
586 if (numfactor.is_equal(_ex1))
588 mul *mulcopyp = new mul(mulref);
589 mulcopyp->overall_coeff = _ex1;
590 mulcopyp->clearflag(status_flags::evaluated);
591 mulcopyp->clearflag(status_flags::hash_calculated);
592 mulcopyp->setflag(status_flags::dynallocated);
593 if (c.is_equal(_ex1))
594 return expair(*mulcopyp, numfactor);
596 return expair(*mulcopyp, ex_to<numeric>(numfactor).mul_dyn(ex_to<numeric>(c)));
597 } else if (is_exactly_a<numeric>(e)) {
598 if (c.is_equal(_ex1))
599 return expair(e, _ex1);
600 if (e.is_equal(_ex1))
601 return expair(c, _ex1);
602 return expair(ex_to<numeric>(e).mul_dyn(ex_to<numeric>(c)), _ex1);
607 expair add::combine_pair_with_coeff_to_pair(const expair & p,
610 GINAC_ASSERT(is_exactly_a<numeric>(p.coeff));
611 GINAC_ASSERT(is_exactly_a<numeric>(c));
613 if (is_exactly_a<numeric>(p.rest)) {
614 GINAC_ASSERT(ex_to<numeric>(p.coeff).is_equal(*_num1_p)); // should be normalized
615 return expair(ex_to<numeric>(p.rest).mul_dyn(ex_to<numeric>(c)),_ex1);
618 return expair(p.rest,ex_to<numeric>(p.coeff).mul_dyn(ex_to<numeric>(c)));
621 ex add::recombine_pair_to_ex(const expair & p) const
623 if (ex_to<numeric>(p.coeff).is_equal(*_num1_p))
626 return (new mul(p.rest,p.coeff))->setflag(status_flags::dynallocated);
629 ex add::expand(unsigned options) const
631 std::auto_ptr<epvector> vp = expandchildren(options);
633 // the terms have not changed, so it is safe to declare this expanded
634 return (options == 0) ? setflag(status_flags::expanded) : *this;
637 return (new add(vp, overall_coeff))->setflag(status_flags::dynallocated | (options == 0 ? status_flags::expanded : 0));