3 * Implementation of GiNaC's sums of expressions. */
6 * GiNaC Copyright (C) 1999-2008 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
31 #include "operators.h"
39 GINAC_IMPLEMENT_REGISTERED_CLASS_OPT(add, expairseq,
40 print_func<print_context>(&add::do_print).
41 print_func<print_latex>(&add::do_print_latex).
42 print_func<print_csrc>(&add::do_print_csrc).
43 print_func<print_tree>(&add::do_print_tree).
44 print_func<print_python_repr>(&add::do_print_python_repr))
47 // default constructor
60 add::add(const ex & lh, const ex & rh)
63 construct_from_2_ex(lh,rh);
64 GINAC_ASSERT(is_canonical());
67 add::add(const exvector & v)
70 construct_from_exvector(v);
71 GINAC_ASSERT(is_canonical());
74 add::add(const epvector & v)
77 construct_from_epvector(v);
78 GINAC_ASSERT(is_canonical());
81 add::add(const epvector & v, const ex & oc)
84 construct_from_epvector(v);
85 GINAC_ASSERT(is_canonical());
88 add::add(std::auto_ptr<epvector> vp, const ex & oc)
90 GINAC_ASSERT(vp.get()!=0);
92 construct_from_epvector(*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::crational_polynomial:
228 case info_flags::rational_function: {
229 epvector::const_iterator i = seq.begin(), end = seq.end();
231 if (!(recombine_pair_to_ex(*i).info(inf)))
235 return overall_coeff.info(inf);
237 case info_flags::algebraic: {
238 epvector::const_iterator i = seq.begin(), end = seq.end();
240 if ((recombine_pair_to_ex(*i).info(inf)))
247 return inherited::info(inf);
250 int add::degree(const ex & s) const
252 int deg = std::numeric_limits<int>::min();
253 if (!overall_coeff.is_zero())
256 // Find maximum of degrees of individual terms
257 epvector::const_iterator i = seq.begin(), end = seq.end();
259 int cur_deg = i->rest.degree(s);
267 int add::ldegree(const ex & s) const
269 int deg = std::numeric_limits<int>::max();
270 if (!overall_coeff.is_zero())
273 // Find minimum of degrees of individual terms
274 epvector::const_iterator i = seq.begin(), end = seq.end();
276 int cur_deg = i->rest.ldegree(s);
284 ex add::coeff(const ex & s, int n) const
286 std::auto_ptr<epvector> coeffseq(new epvector);
287 std::auto_ptr<epvector> coeffseq_cliff(new epvector);
288 char rl = clifford_max_label(s);
289 bool do_clifford = (rl != -1);
290 bool nonscalar = false;
292 // Calculate sum of coefficients in each term
293 epvector::const_iterator i = seq.begin(), end = seq.end();
295 ex restcoeff = i->rest.coeff(s, n);
296 if (!restcoeff.is_zero()) {
298 if (clifford_max_label(restcoeff) == -1) {
299 coeffseq_cliff->push_back(combine_ex_with_coeff_to_pair(ncmul(restcoeff, dirac_ONE(rl)), i->coeff));
301 coeffseq_cliff->push_back(combine_ex_with_coeff_to_pair(restcoeff, i->coeff));
305 coeffseq->push_back(combine_ex_with_coeff_to_pair(restcoeff, i->coeff));
310 return (new add(nonscalar ? coeffseq_cliff : coeffseq,
311 n==0 ? overall_coeff : _ex0))->setflag(status_flags::dynallocated);
314 /** Perform automatic term rewriting rules in this class. In the following
315 * x stands for a symbolic variables of type ex and c stands for such
316 * an expression that contain a plain number.
320 * @param level cut-off in recursive evaluation */
321 ex add::eval(int level) const
323 std::auto_ptr<epvector> evaled_seqp = evalchildren(level);
324 if (evaled_seqp.get()) {
325 // do more evaluation later
326 return (new add(evaled_seqp, overall_coeff))->
327 setflag(status_flags::dynallocated);
330 #ifdef DO_GINAC_ASSERT
331 epvector::const_iterator i = seq.begin(), end = seq.end();
333 GINAC_ASSERT(!is_exactly_a<add>(i->rest));
334 if (is_exactly_a<numeric>(i->rest))
336 GINAC_ASSERT(!is_exactly_a<numeric>(i->rest));
339 #endif // def DO_GINAC_ASSERT
341 if (flags & status_flags::evaluated) {
342 GINAC_ASSERT(seq.size()>0);
343 GINAC_ASSERT(seq.size()>1 || !overall_coeff.is_zero());
347 int seq_size = seq.size();
350 return overall_coeff;
351 } else if (seq_size == 1 && overall_coeff.is_zero()) {
353 return recombine_pair_to_ex(*(seq.begin()));
354 } else if (!overall_coeff.is_zero() && seq[0].rest.return_type() != return_types::commutative) {
355 throw (std::logic_error("add::eval(): sum of non-commutative objects has non-zero numeric term"));
360 ex add::evalm() const
362 // Evaluate children first and add up all matrices. Stop if there's one
363 // term that is not a matrix.
364 std::auto_ptr<epvector> s(new epvector);
365 s->reserve(seq.size());
367 bool all_matrices = true;
368 bool first_term = true;
371 epvector::const_iterator it = seq.begin(), itend = seq.end();
372 while (it != itend) {
373 const ex &m = recombine_pair_to_ex(*it).evalm();
374 s->push_back(split_ex_to_pair(m));
375 if (is_a<matrix>(m)) {
377 sum = ex_to<matrix>(m);
380 sum = sum.add(ex_to<matrix>(m));
382 all_matrices = false;
387 return sum + overall_coeff;
389 return (new add(s, overall_coeff))->setflag(status_flags::dynallocated);
392 ex add::conjugate() const
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))
406 for (size_t j=0; j<i; ++j)
408 v->push_back(ccterm);
418 ex add::real_part() const
421 v.reserve(seq.size());
422 for (epvector::const_iterator i=seq.begin(); i!=seq.end(); ++i)
423 if ((i->coeff).info(info_flags::real)) {
424 ex rp = (i->rest).real_part();
426 v.push_back(expair(rp, i->coeff));
428 ex rp=recombine_pair_to_ex(*i).real_part();
430 v.push_back(split_ex_to_pair(rp));
432 return (new add(v, overall_coeff.real_part()))
433 -> setflag(status_flags::dynallocated);
436 ex add::imag_part() const
439 v.reserve(seq.size());
440 for (epvector::const_iterator i=seq.begin(); i!=seq.end(); ++i)
441 if ((i->coeff).info(info_flags::real)) {
442 ex ip = (i->rest).imag_part();
444 v.push_back(expair(ip, i->coeff));
446 ex ip=recombine_pair_to_ex(*i).imag_part();
448 v.push_back(split_ex_to_pair(ip));
450 return (new add(v, overall_coeff.imag_part()))
451 -> setflag(status_flags::dynallocated);
454 ex add::eval_ncmul(const exvector & v) const
457 return inherited::eval_ncmul(v);
459 return seq.begin()->rest.eval_ncmul(v);
464 /** Implementation of ex::diff() for a sum. It differentiates each term.
466 ex add::derivative(const symbol & y) const
468 std::auto_ptr<epvector> s(new epvector);
469 s->reserve(seq.size());
471 // Only differentiate the "rest" parts of the expairs. This is faster
472 // than the default implementation in basic::derivative() although
473 // if performs the same function (differentiate each term).
474 epvector::const_iterator i = seq.begin(), end = seq.end();
476 s->push_back(combine_ex_with_coeff_to_pair(i->rest.diff(y), i->coeff));
479 return (new add(s, _ex0))->setflag(status_flags::dynallocated);
482 int add::compare_same_type(const basic & other) const
484 return inherited::compare_same_type(other);
487 unsigned add::return_type() const
490 return return_types::commutative;
492 return seq.begin()->rest.return_type();
495 return_type_t add::return_type_tinfo() const
498 return make_return_type_t<add>();
500 return seq.begin()->rest.return_type_tinfo();
503 // Note: do_index_renaming is ignored because it makes no sense for an add.
504 ex add::thisexpairseq(const epvector & v, const ex & oc, bool do_index_renaming) const
506 return (new add(v,oc))->setflag(status_flags::dynallocated);
509 // Note: do_index_renaming is ignored because it makes no sense for an add.
510 ex add::thisexpairseq(std::auto_ptr<epvector> vp, const ex & oc, bool do_index_renaming) const
512 return (new add(vp,oc))->setflag(status_flags::dynallocated);
515 expair add::split_ex_to_pair(const ex & e) const
517 if (is_exactly_a<mul>(e)) {
518 const mul &mulref(ex_to<mul>(e));
519 const ex &numfactor = mulref.overall_coeff;
520 mul *mulcopyp = new mul(mulref);
521 mulcopyp->overall_coeff = _ex1;
522 mulcopyp->clearflag(status_flags::evaluated);
523 mulcopyp->clearflag(status_flags::hash_calculated);
524 mulcopyp->setflag(status_flags::dynallocated);
525 return expair(*mulcopyp,numfactor);
527 return expair(e,_ex1);
530 expair add::combine_ex_with_coeff_to_pair(const ex & e,
533 GINAC_ASSERT(is_exactly_a<numeric>(c));
534 if (is_exactly_a<mul>(e)) {
535 const mul &mulref(ex_to<mul>(e));
536 const ex &numfactor = mulref.overall_coeff;
537 mul *mulcopyp = new mul(mulref);
538 mulcopyp->overall_coeff = _ex1;
539 mulcopyp->clearflag(status_flags::evaluated);
540 mulcopyp->clearflag(status_flags::hash_calculated);
541 mulcopyp->setflag(status_flags::dynallocated);
542 if (c.is_equal(_ex1))
543 return expair(*mulcopyp, numfactor);
544 else if (numfactor.is_equal(_ex1))
545 return expair(*mulcopyp, c);
547 return expair(*mulcopyp, ex_to<numeric>(numfactor).mul_dyn(ex_to<numeric>(c)));
548 } else if (is_exactly_a<numeric>(e)) {
549 if (c.is_equal(_ex1))
550 return expair(e, _ex1);
551 return expair(ex_to<numeric>(e).mul_dyn(ex_to<numeric>(c)), _ex1);
556 expair add::combine_pair_with_coeff_to_pair(const expair & p,
559 GINAC_ASSERT(is_exactly_a<numeric>(p.coeff));
560 GINAC_ASSERT(is_exactly_a<numeric>(c));
562 if (is_exactly_a<numeric>(p.rest)) {
563 GINAC_ASSERT(ex_to<numeric>(p.coeff).is_equal(*_num1_p)); // should be normalized
564 return expair(ex_to<numeric>(p.rest).mul_dyn(ex_to<numeric>(c)),_ex1);
567 return expair(p.rest,ex_to<numeric>(p.coeff).mul_dyn(ex_to<numeric>(c)));
570 ex add::recombine_pair_to_ex(const expair & p) const
572 if (ex_to<numeric>(p.coeff).is_equal(*_num1_p))
575 return (new mul(p.rest,p.coeff))->setflag(status_flags::dynallocated);
578 ex add::expand(unsigned options) const
580 std::auto_ptr<epvector> vp = expandchildren(options);
582 // the terms have not changed, so it is safe to declare this expanded
583 return (options == 0) ? setflag(status_flags::expanded) : *this;
586 return (new add(vp, overall_coeff))->setflag(status_flags::dynallocated | (options == 0 ? status_flags::expanded : 0));