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 for (auto & it : seq) {
124 coeff = ex_to<numeric>(it.coeff);
126 if (coeff.csgn() == -1) c.s << '-'; else c.s << '+';
128 if (coeff.csgn() == -1) c.s << '-';
131 if (!coeff.is_equal(*_num1_p) &&
132 !coeff.is_equal(*_num_1_p)) {
133 if (coeff.is_rational()) {
134 if (coeff.is_negative())
139 if (coeff.csgn() == -1)
140 (-coeff).print(c, precedence());
142 coeff.print(c, precedence());
146 it.rest.print(c, precedence());
149 if (precedence() <= level)
150 c.s << ')' << closebrace;
153 void add::do_print(const print_context & c, unsigned level) const
155 print_add(c, "", "", "*", level);
158 void add::do_print_latex(const print_latex & c, unsigned level) const
160 print_add(c, "{", "}", " ", level);
163 void add::do_print_csrc(const print_csrc & c, unsigned level) const
165 if (precedence() <= level)
168 // Print arguments, separated by "+" or "-"
169 char separator = ' ';
170 for (auto & it : seq) {
172 // If the coefficient is negative, separator is "-"
173 if (it.coeff.is_equal(_ex_1) ||
174 ex_to<numeric>(it.coeff).numer().is_equal(*_num_1_p))
177 if (it.coeff.is_equal(_ex1) || it.coeff.is_equal(_ex_1)) {
178 it.rest.print(c, precedence());
179 } else if (ex_to<numeric>(it.coeff).numer().is_equal(*_num1_p) ||
180 ex_to<numeric>(it.coeff).numer().is_equal(*_num_1_p))
182 it.rest.print(c, precedence());
184 ex_to<numeric>(it.coeff).denom().print(c, precedence());
186 it.coeff.print(c, precedence());
188 it.rest.print(c, precedence());
194 if (!overall_coeff.is_zero()) {
195 if (overall_coeff.info(info_flags::positive)
196 || is_a<print_csrc_cl_N>(c) || !overall_coeff.info(info_flags::real)) // sign inside ctor argument
198 overall_coeff.print(c, precedence());
201 if (precedence() <= level)
205 void add::do_print_python_repr(const print_python_repr & c, unsigned level) const
207 c.s << class_name() << '(';
209 for (size_t i=1; i<nops(); ++i) {
216 bool add::info(unsigned inf) const
219 case info_flags::polynomial:
220 case info_flags::integer_polynomial:
221 case info_flags::cinteger_polynomial:
222 case info_flags::rational_polynomial:
223 case info_flags::real:
224 case info_flags::rational:
225 case info_flags::integer:
226 case info_flags::crational:
227 case info_flags::cinteger:
228 case info_flags::positive:
229 case info_flags::nonnegative:
230 case info_flags::posint:
231 case info_flags::nonnegint:
232 case info_flags::even:
233 case info_flags::crational_polynomial:
234 case info_flags::rational_function: {
235 for (auto & i : seq) {
236 if (!(recombine_pair_to_ex(i).info(inf)))
239 if (overall_coeff.is_zero() && (inf == info_flags::positive || inf == info_flags::posint))
241 return overall_coeff.info(inf);
243 case info_flags::algebraic: {
244 epvector::const_iterator i = seq.begin(), end = seq.end();
246 if ((recombine_pair_to_ex(*i).info(inf)))
253 return inherited::info(inf);
256 bool add::is_polynomial(const ex & var) const
258 for (auto & i : seq) {
259 if (!i.rest.is_polynomial(var)) {
266 int add::degree(const ex & s) const
268 int deg = std::numeric_limits<int>::min();
269 if (!overall_coeff.is_zero())
272 // Find maximum of degrees of individual terms
273 for (auto & i : seq) {
274 int cur_deg = i.rest.degree(s);
281 int add::ldegree(const ex & s) const
283 int deg = std::numeric_limits<int>::max();
284 if (!overall_coeff.is_zero())
287 // Find minimum of degrees of individual terms
288 for (auto & i : seq) {
289 int cur_deg = i.rest.ldegree(s);
296 ex add::coeff(const ex & s, int n) const
299 epvector coeffseq_cliff;
300 int rl = clifford_max_label(s);
301 bool do_clifford = (rl != -1);
302 bool nonscalar = false;
304 // Calculate sum of coefficients in each term
305 for (auto & i : seq) {
306 ex restcoeff = i.rest.coeff(s, n);
307 if (!restcoeff.is_zero()) {
309 if (clifford_max_label(restcoeff) == -1) {
310 coeffseq_cliff.push_back(expair(ncmul(restcoeff, dirac_ONE(rl)), i.coeff));
312 coeffseq_cliff.push_back(expair(restcoeff, i.coeff));
316 coeffseq.push_back(expair(restcoeff, i.coeff));
320 return dynallocate<add>(nonscalar ? std::move(coeffseq_cliff) : std::move(coeffseq),
321 n==0 ? overall_coeff : _ex0);
324 /** Perform automatic term rewriting rules in this class. In the following
325 * x stands for a symbolic variables of type ex and c stands for such
326 * an expression that contain a plain number.
330 * @param level cut-off in recursive evaluation */
331 ex add::eval(int level) const
333 if ((level == 1) && (flags & status_flags::evaluated)) {
334 GINAC_ASSERT(seq.size()>0);
335 GINAC_ASSERT(seq.size()>1 || !overall_coeff.is_zero());
339 const epvector evaled = evalchildren(level);
340 if (unlikely(!evaled.empty())) {
341 // start over evaluating a new object
342 return dynallocate<add>(std::move(evaled), overall_coeff);
345 #ifdef DO_GINAC_ASSERT
346 for (auto & i : seq) {
347 GINAC_ASSERT(!is_exactly_a<add>(i.rest));
349 #endif // def DO_GINAC_ASSERT
351 int seq_size = seq.size();
354 return overall_coeff;
355 } else if (seq_size == 1 && overall_coeff.is_zero()) {
357 return recombine_pair_to_ex(*(seq.begin()));
358 } else if (!overall_coeff.is_zero() && seq[0].rest.return_type() != return_types::commutative) {
359 throw (std::logic_error("add::eval(): sum of non-commutative objects has non-zero numeric term"));
362 // if any terms in the sum still are purely numeric, then they are more
363 // appropriately collected into the overall coefficient
364 int terms_to_collect = 0;
365 for (auto & it : seq) {
366 if (unlikely(is_a<numeric>(it.rest)))
369 if (terms_to_collect) {
371 s.reserve(seq_size - terms_to_collect);
372 numeric oc = *_num1_p;
373 for (auto & it : seq) {
374 if (unlikely(is_a<numeric>(it.rest)))
375 oc = oc.mul(ex_to<numeric>(it.rest)).mul(ex_to<numeric>(it.coeff));
379 return dynallocate<add>(std::move(s), ex_to<numeric>(overall_coeff).add_dyn(oc));
385 ex add::evalm() const
387 // Evaluate children first and add up all matrices. Stop if there's one
388 // term that is not a matrix.
390 s.reserve(seq.size());
392 bool all_matrices = true;
393 bool first_term = true;
396 for (auto & it : seq) {
397 const ex &m = recombine_pair_to_ex(it).evalm();
398 s.push_back(split_ex_to_pair(m));
399 if (is_a<matrix>(m)) {
401 sum = ex_to<matrix>(m);
404 sum = sum.add(ex_to<matrix>(m));
406 all_matrices = false;
410 return sum + overall_coeff;
412 return dynallocate<add>(std::move(s), overall_coeff);
415 ex add::conjugate() const
417 std::unique_ptr<exvector> v(nullptr);
418 for (size_t i=0; i<nops(); ++i) {
420 v->push_back(op(i).conjugate());
424 ex ccterm = term.conjugate();
425 if (are_ex_trivially_equal(term, ccterm))
427 v.reset(new exvector);
429 for (size_t j=0; j<i; ++j)
431 v->push_back(ccterm);
434 return add(std::move(*v));
439 ex add::real_part() const
442 v.reserve(seq.size());
443 for (auto & it : seq)
444 if (it.coeff.info(info_flags::real)) {
445 ex rp = it.rest.real_part();
447 v.push_back(expair(rp, it.coeff));
449 ex rp = recombine_pair_to_ex(it).real_part();
451 v.push_back(split_ex_to_pair(rp));
453 return dynallocate<add>(std::move(v), overall_coeff.real_part());
456 ex add::imag_part() const
459 v.reserve(seq.size());
460 for (auto & it : seq)
461 if (it.coeff.info(info_flags::real)) {
462 ex ip = it.rest.imag_part();
464 v.push_back(expair(ip, it.coeff));
466 ex ip = recombine_pair_to_ex(it).imag_part();
468 v.push_back(split_ex_to_pair(ip));
470 return dynallocate<add>(std::move(v), overall_coeff.imag_part());
473 ex add::eval_ncmul(const exvector & v) const
476 return inherited::eval_ncmul(v);
478 return seq.begin()->rest.eval_ncmul(v);
483 /** Implementation of ex::diff() for a sum. It differentiates each term.
485 ex add::derivative(const symbol & y) const
488 s.reserve(seq.size());
490 // Only differentiate the "rest" parts of the expairs. This is faster
491 // than the default implementation in basic::derivative() although
492 // if performs the same function (differentiate each term).
493 for (auto & it : seq)
494 s.push_back(expair(it.rest.diff(y), it.coeff));
496 return dynallocate<add>(std::move(s), _ex0);
499 int add::compare_same_type(const basic & other) const
501 return inherited::compare_same_type(other);
504 unsigned add::return_type() const
507 return return_types::commutative;
509 return seq.begin()->rest.return_type();
512 return_type_t add::return_type_tinfo() const
515 return make_return_type_t<add>();
517 return seq.begin()->rest.return_type_tinfo();
520 // Note: do_index_renaming is ignored because it makes no sense for an add.
521 ex add::thisexpairseq(const epvector & v, const ex & oc, bool do_index_renaming) const
523 return dynallocate<add>(v, oc);
526 // Note: do_index_renaming is ignored because it makes no sense for an add.
527 ex add::thisexpairseq(epvector && vp, const ex & oc, bool do_index_renaming) const
529 return dynallocate<add>(std::move(vp), oc);
532 expair add::split_ex_to_pair(const ex & e) const
534 if (is_exactly_a<mul>(e)) {
535 const mul &mulref(ex_to<mul>(e));
536 const ex &numfactor = mulref.overall_coeff;
537 if (numfactor.is_equal(_ex1))
538 return expair(e, _ex1);
539 mul & mulcopy = dynallocate<mul>(mulref);
540 mulcopy.overall_coeff = _ex1;
541 mulcopy.clearflag(status_flags::evaluated | status_flags::hash_calculated);
542 return expair(mulcopy, numfactor);
544 return expair(e,_ex1);
547 expair add::combine_ex_with_coeff_to_pair(const ex & e,
550 GINAC_ASSERT(is_exactly_a<numeric>(c));
551 if (is_exactly_a<mul>(e)) {
552 const mul &mulref(ex_to<mul>(e));
553 const ex &numfactor = mulref.overall_coeff;
554 if (likely(numfactor.is_equal(_ex1)))
556 mul & mulcopy = dynallocate<mul>(mulref);
557 mulcopy.overall_coeff = _ex1;
558 mulcopy.clearflag(status_flags::evaluated | status_flags::hash_calculated);
559 if (c.is_equal(_ex1))
560 return expair(mulcopy, numfactor);
562 return expair(mulcopy, ex_to<numeric>(numfactor).mul_dyn(ex_to<numeric>(c)));
563 } else if (is_exactly_a<numeric>(e)) {
564 if (c.is_equal(_ex1))
565 return expair(e, _ex1);
566 if (e.is_equal(_ex1))
567 return expair(c, _ex1);
568 return expair(ex_to<numeric>(e).mul_dyn(ex_to<numeric>(c)), _ex1);
573 expair add::combine_pair_with_coeff_to_pair(const expair & p,
576 GINAC_ASSERT(is_exactly_a<numeric>(p.coeff));
577 GINAC_ASSERT(is_exactly_a<numeric>(c));
579 if (is_exactly_a<numeric>(p.rest)) {
580 GINAC_ASSERT(ex_to<numeric>(p.coeff).is_equal(*_num1_p)); // should be normalized
581 return expair(ex_to<numeric>(p.rest).mul_dyn(ex_to<numeric>(c)),_ex1);
584 return expair(p.rest,ex_to<numeric>(p.coeff).mul_dyn(ex_to<numeric>(c)));
587 ex add::recombine_pair_to_ex(const expair & p) const
589 if (ex_to<numeric>(p.coeff).is_equal(*_num1_p))
592 return dynallocate<mul>(p.rest, p.coeff);
595 ex add::expand(unsigned options) const
597 epvector expanded = expandchildren(options);
598 if (expanded.empty())
599 return (options == 0) ? setflag(status_flags::expanded) : *this;
601 return dynallocate<add>(std::move(expanded), overall_coeff).setflag(options == 0 ? status_flags::expanded : 0);