3 * Implementation of GiNaC's sums of expressions. */
6 * GiNaC Copyright (C) 1999-2018 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)
92 construct_from_epvector(std::move(vp));
93 GINAC_ASSERT(is_canonical());
96 add::add(epvector && vp, const ex & oc)
99 construct_from_epvector(std::move(vp));
100 GINAC_ASSERT(is_canonical());
107 GINAC_BIND_UNARCHIVER(add);
110 // functions overriding virtual functions from base classes
115 void add::print_add(const print_context & c, const char *openbrace, const char *closebrace, const char *mul_sym, unsigned level) const
117 if (precedence() <= level)
118 c.s << openbrace << '(';
123 // First print the overall numeric coefficient, if present
124 if (!overall_coeff.is_zero()) {
125 overall_coeff.print(c, 0);
129 // Then proceed with the remaining factors
130 for (auto & it : seq) {
131 coeff = ex_to<numeric>(it.coeff);
133 if (coeff.csgn() == -1) c.s << '-'; else c.s << '+';
135 if (coeff.csgn() == -1) c.s << '-';
138 if (!coeff.is_equal(*_num1_p) &&
139 !coeff.is_equal(*_num_1_p)) {
140 if (coeff.is_rational()) {
141 if (coeff.is_negative())
146 if (coeff.csgn() == -1)
147 (-coeff).print(c, precedence());
149 coeff.print(c, precedence());
153 it.rest.print(c, precedence());
156 if (precedence() <= level)
157 c.s << ')' << closebrace;
160 void add::do_print(const print_context & c, unsigned level) const
162 print_add(c, "", "", "*", level);
165 void add::do_print_latex(const print_latex & c, unsigned level) const
167 print_add(c, "{", "}", " ", level);
170 void add::do_print_csrc(const print_csrc & c, unsigned level) const
172 if (precedence() <= level)
175 // Print arguments, separated by "+" or "-"
176 char separator = ' ';
177 for (auto & it : seq) {
179 // If the coefficient is negative, separator is "-"
180 if (it.coeff.is_equal(_ex_1) ||
181 ex_to<numeric>(it.coeff).numer().is_equal(*_num_1_p))
184 if (it.coeff.is_equal(_ex1) || it.coeff.is_equal(_ex_1)) {
185 it.rest.print(c, precedence());
186 } else if (ex_to<numeric>(it.coeff).numer().is_equal(*_num1_p) ||
187 ex_to<numeric>(it.coeff).numer().is_equal(*_num_1_p))
189 it.rest.print(c, precedence());
191 ex_to<numeric>(it.coeff).denom().print(c, precedence());
193 it.coeff.print(c, precedence());
195 it.rest.print(c, precedence());
201 if (!overall_coeff.is_zero()) {
202 if (overall_coeff.info(info_flags::positive)
203 || is_a<print_csrc_cl_N>(c) || !overall_coeff.info(info_flags::real)) // sign inside ctor argument
205 overall_coeff.print(c, precedence());
208 if (precedence() <= level)
212 void add::do_print_python_repr(const print_python_repr & c, unsigned level) const
214 c.s << class_name() << '(';
216 for (size_t i=1; i<nops(); ++i) {
223 bool add::info(unsigned inf) const
226 case info_flags::polynomial:
227 case info_flags::integer_polynomial:
228 case info_flags::cinteger_polynomial:
229 case info_flags::rational_polynomial:
230 case info_flags::real:
231 case info_flags::rational:
232 case info_flags::integer:
233 case info_flags::crational:
234 case info_flags::cinteger:
235 case info_flags::positive:
236 case info_flags::nonnegative:
237 case info_flags::posint:
238 case info_flags::nonnegint:
239 case info_flags::even:
240 case info_flags::crational_polynomial:
241 case info_flags::rational_function: {
242 for (auto & i : seq) {
243 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);
251 return inherited::info(inf);
254 bool add::is_polynomial(const ex & var) const
256 for (auto & i : seq) {
257 if (!i.rest.is_polynomial(var)) {
264 int add::degree(const ex & s) const
266 int deg = std::numeric_limits<int>::min();
267 if (!overall_coeff.is_zero())
270 // Find maximum of degrees of individual terms
271 for (auto & i : seq) {
272 int cur_deg = i.rest.degree(s);
279 int add::ldegree(const ex & s) const
281 int deg = std::numeric_limits<int>::max();
282 if (!overall_coeff.is_zero())
285 // Find minimum of degrees of individual terms
286 for (auto & i : seq) {
287 int cur_deg = i.rest.ldegree(s);
294 ex add::coeff(const ex & s, int n) const
297 epvector coeffseq_cliff;
298 int rl = clifford_max_label(s);
299 bool do_clifford = (rl != -1);
300 bool nonscalar = false;
302 // Calculate sum of coefficients in each term
303 for (auto & i : seq) {
304 ex restcoeff = i.rest.coeff(s, n);
305 if (!restcoeff.is_zero()) {
307 if (clifford_max_label(restcoeff) == -1) {
308 coeffseq_cliff.push_back(expair(ncmul(restcoeff, dirac_ONE(rl)), i.coeff));
310 coeffseq_cliff.push_back(expair(restcoeff, i.coeff));
314 coeffseq.push_back(expair(restcoeff, i.coeff));
318 return dynallocate<add>(nonscalar ? std::move(coeffseq_cliff) : std::move(coeffseq),
319 n==0 ? overall_coeff : _ex0);
322 /** Perform automatic term rewriting rules in this class. In the following
323 * x stands for a symbolic variables of type ex and c stands for such
324 * an expression that contain a plain number.
330 if (flags & status_flags::evaluated) {
331 GINAC_ASSERT(seq.size()>0);
332 GINAC_ASSERT(seq.size()>1 || !overall_coeff.is_zero());
336 const epvector evaled = evalchildren();
337 if (unlikely(!evaled.empty())) {
338 // start over evaluating a new object
339 return dynallocate<add>(std::move(evaled), overall_coeff);
342 #ifdef DO_GINAC_ASSERT
343 for (auto & i : seq) {
344 GINAC_ASSERT(!is_exactly_a<add>(i.rest));
346 #endif // def DO_GINAC_ASSERT
348 size_t seq_size = seq.size();
351 return overall_coeff;
352 } else if (seq_size == 1 && overall_coeff.is_zero()) {
354 return recombine_pair_to_ex(*(seq.begin()));
355 } else if (!overall_coeff.is_zero() && seq[0].rest.return_type() != return_types::commutative) {
356 throw (std::logic_error("add::eval(): sum of non-commutative objects has non-zero numeric term"));
362 ex add::evalm() const
364 // Evaluate children first and add up all matrices. Stop if there's one
365 // term that is not a matrix.
367 s.reserve(seq.size());
369 bool all_matrices = true;
370 bool first_term = true;
373 for (auto & it : seq) {
374 const ex &m = recombine_pair_to_ex(it).evalm();
375 s.push_back(split_ex_to_pair(m));
376 if (is_a<matrix>(m)) {
378 sum = ex_to<matrix>(m);
381 sum = sum.add(ex_to<matrix>(m));
383 all_matrices = false;
387 return sum + overall_coeff;
389 return dynallocate<add>(std::move(s), overall_coeff);
392 ex add::conjugate() const
394 std::unique_ptr<exvector> v(nullptr);
395 for (size_t i=0; i<nops(); ++i) {
397 v->push_back(op(i).conjugate());
401 ex ccterm = term.conjugate();
402 if (are_ex_trivially_equal(term, ccterm))
404 v.reset(new exvector);
406 for (size_t j=0; j<i; ++j)
408 v->push_back(ccterm);
411 return add(std::move(*v));
416 ex add::real_part() const
419 v.reserve(seq.size());
420 for (auto & it : seq)
421 if (it.coeff.info(info_flags::real)) {
422 ex rp = it.rest.real_part();
424 v.push_back(expair(rp, it.coeff));
426 ex rp = recombine_pair_to_ex(it).real_part();
428 v.push_back(split_ex_to_pair(rp));
430 return dynallocate<add>(std::move(v), overall_coeff.real_part());
433 ex add::imag_part() const
436 v.reserve(seq.size());
437 for (auto & it : seq)
438 if (it.coeff.info(info_flags::real)) {
439 ex ip = it.rest.imag_part();
441 v.push_back(expair(ip, it.coeff));
443 ex ip = recombine_pair_to_ex(it).imag_part();
445 v.push_back(split_ex_to_pair(ip));
447 return dynallocate<add>(std::move(v), overall_coeff.imag_part());
450 ex add::eval_ncmul(const exvector & v) const
453 return inherited::eval_ncmul(v);
455 return seq.begin()->rest.eval_ncmul(v);
460 /** Implementation of ex::diff() for a sum. It differentiates each term.
462 ex add::derivative(const symbol & y) const
465 s.reserve(seq.size());
467 // Only differentiate the "rest" parts of the expairs. This is faster
468 // than the default implementation in basic::derivative() although
469 // if performs the same function (differentiate each term).
470 for (auto & it : seq)
471 s.push_back(expair(it.rest.diff(y), it.coeff));
473 return dynallocate<add>(std::move(s));
476 int add::compare_same_type(const basic & other) const
478 return inherited::compare_same_type(other);
481 unsigned add::return_type() const
484 return return_types::commutative;
486 return seq.begin()->rest.return_type();
489 return_type_t add::return_type_tinfo() const
492 return make_return_type_t<add>();
494 return seq.begin()->rest.return_type_tinfo();
497 // Note: do_index_renaming is ignored because it makes no sense for an add.
498 ex add::thisexpairseq(const epvector & v, const ex & oc, bool do_index_renaming) const
500 return dynallocate<add>(v, oc);
503 // Note: do_index_renaming is ignored because it makes no sense for an add.
504 ex add::thisexpairseq(epvector && vp, const ex & oc, bool do_index_renaming) const
506 return dynallocate<add>(std::move(vp), oc);
509 expair add::split_ex_to_pair(const ex & e) const
511 if (is_exactly_a<mul>(e)) {
512 const mul &mulref(ex_to<mul>(e));
513 const ex &numfactor = mulref.overall_coeff;
514 if (numfactor.is_equal(_ex1))
515 return expair(e, _ex1);
516 mul & mulcopy = dynallocate<mul>(mulref);
517 mulcopy.overall_coeff = _ex1;
518 mulcopy.clearflag(status_flags::evaluated | status_flags::hash_calculated);
519 return expair(mulcopy, numfactor);
521 return expair(e,_ex1);
524 expair add::combine_ex_with_coeff_to_pair(const ex & e,
527 GINAC_ASSERT(is_exactly_a<numeric>(c));
528 if (is_exactly_a<mul>(e)) {
529 const mul &mulref(ex_to<mul>(e));
530 const ex &numfactor = mulref.overall_coeff;
531 if (likely(numfactor.is_equal(_ex1)))
533 mul & mulcopy = dynallocate<mul>(mulref);
534 mulcopy.overall_coeff = _ex1;
535 mulcopy.clearflag(status_flags::evaluated | status_flags::hash_calculated);
536 if (c.is_equal(_ex1))
537 return expair(mulcopy, numfactor);
539 return expair(mulcopy, ex_to<numeric>(numfactor).mul_dyn(ex_to<numeric>(c)));
540 } else if (is_exactly_a<numeric>(e)) {
541 if (c.is_equal(_ex1))
542 return expair(e, _ex1);
543 if (e.is_equal(_ex1))
544 return expair(c, _ex1);
545 return expair(ex_to<numeric>(e).mul_dyn(ex_to<numeric>(c)), _ex1);
550 expair add::combine_pair_with_coeff_to_pair(const expair & p,
553 GINAC_ASSERT(is_exactly_a<numeric>(p.coeff));
554 GINAC_ASSERT(is_exactly_a<numeric>(c));
556 if (is_exactly_a<numeric>(p.rest)) {
557 GINAC_ASSERT(ex_to<numeric>(p.coeff).is_equal(*_num1_p)); // should be normalized
558 return expair(ex_to<numeric>(p.rest).mul_dyn(ex_to<numeric>(c)),_ex1);
561 return expair(p.rest,ex_to<numeric>(p.coeff).mul_dyn(ex_to<numeric>(c)));
564 ex add::recombine_pair_to_ex(const expair & p) const
566 if (ex_to<numeric>(p.coeff).is_equal(*_num1_p))
569 return dynallocate<mul>(p.rest, p.coeff);
572 ex add::expand(unsigned options) const
574 epvector expanded = expandchildren(options);
575 if (expanded.empty())
576 return (options == 0) ? setflag(status_flags::expanded) : *this;
578 return dynallocate<add>(std::move(expanded), overall_coeff).setflag(options == 0 ? status_flags::expanded : 0);