3 * Implementation of GiNaC's sums of expressions. */
6 * GiNaC Copyright (C) 1999-2007 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
30 #include "operators.h"
38 GINAC_IMPLEMENT_REGISTERED_CLASS_OPT(add, expairseq,
39 print_func<print_context>(&add::do_print).
40 print_func<print_latex>(&add::do_print_latex).
41 print_func<print_csrc>(&add::do_print_csrc).
42 print_func<print_tree>(&add::do_print_tree).
43 print_func<print_python_repr>(&add::do_print_python_repr))
46 // default constructor
51 tinfo_key = &add::tinfo_static;
60 add::add(const ex & lh, const ex & rh)
62 tinfo_key = &add::tinfo_static;
64 construct_from_2_ex(lh,rh);
65 GINAC_ASSERT(is_canonical());
68 add::add(const exvector & v)
70 tinfo_key = &add::tinfo_static;
72 construct_from_exvector(v);
73 GINAC_ASSERT(is_canonical());
76 add::add(const epvector & v)
78 tinfo_key = &add::tinfo_static;
80 construct_from_epvector(v);
81 GINAC_ASSERT(is_canonical());
84 add::add(const epvector & v, const ex & oc)
86 tinfo_key = &add::tinfo_static;
88 construct_from_epvector(v);
89 GINAC_ASSERT(is_canonical());
92 add::add(std::auto_ptr<epvector> vp, const ex & oc)
94 tinfo_key = &add::tinfo_static;
95 GINAC_ASSERT(vp.get()!=0);
97 construct_from_epvector(*vp);
98 GINAC_ASSERT(is_canonical());
105 DEFAULT_ARCHIVING(add)
108 // functions overriding virtual functions from base classes
113 void add::print_add(const print_context & c, const char *openbrace, const char *closebrace, const char *mul_sym, unsigned level) const
115 if (precedence() <= level)
116 c.s << openbrace << '(';
121 // First print the overall numeric coefficient, if present
122 if (!overall_coeff.is_zero()) {
123 overall_coeff.print(c, 0);
127 // Then proceed with the remaining factors
128 epvector::const_iterator it = seq.begin(), itend = seq.end();
129 while (it != itend) {
130 coeff = ex_to<numeric>(it->coeff);
132 if (coeff.csgn() == -1) c.s << '-'; else c.s << '+';
134 if (coeff.csgn() == -1) c.s << '-';
137 if (!coeff.is_equal(*_num1_p) &&
138 !coeff.is_equal(*_num_1_p)) {
139 if (coeff.is_rational()) {
140 if (coeff.is_negative())
145 if (coeff.csgn() == -1)
146 (-coeff).print(c, precedence());
148 coeff.print(c, precedence());
152 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 "+"
176 epvector::const_iterator it = seq.begin(), itend = seq.end();
177 while (it != itend) {
179 // If the coefficient is -1, it is replaced by a single minus sign
180 if (it->coeff.is_equal(_ex1)) {
181 it->rest.print(c, precedence());
182 } else if (it->coeff.is_equal(_ex_1)) {
184 it->rest.print(c, precedence());
185 } else if (ex_to<numeric>(it->coeff).numer().is_equal(*_num1_p)) {
186 it->rest.print(c, precedence());
188 ex_to<numeric>(it->coeff).denom().print(c, precedence());
189 } else if (ex_to<numeric>(it->coeff).numer().is_equal(*_num_1_p)) {
191 it->rest.print(c, precedence());
193 ex_to<numeric>(it->coeff).denom().print(c, precedence());
195 it->coeff.print(c, precedence());
197 it->rest.print(c, precedence());
200 // Separator is "+", except if the following expression would have a leading minus sign or the sign is sitting in parenthesis (as in a ctor)
203 && (is_a<print_csrc_cl_N>(c) || !it->coeff.info(info_flags::real) // sign inside ctor arguments
204 || !(it->coeff.info(info_flags::negative) || (it->coeff.is_equal(*_num1_p) && is_exactly_a<numeric>(it->rest) && it->rest.info(info_flags::negative)))))
208 if (!overall_coeff.is_zero()) {
209 if (overall_coeff.info(info_flags::positive)
210 || is_a<print_csrc_cl_N>(c) || !overall_coeff.info(info_flags::real)) // sign inside ctor argument
212 overall_coeff.print(c, precedence());
215 if (precedence() <= level)
219 void add::do_print_python_repr(const print_python_repr & c, unsigned level) const
221 c.s << class_name() << '(';
223 for (size_t i=1; i<nops(); ++i) {
230 bool add::info(unsigned inf) const
233 case info_flags::polynomial:
234 case info_flags::integer_polynomial:
235 case info_flags::cinteger_polynomial:
236 case info_flags::rational_polynomial:
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 return overall_coeff.info(inf);
247 case info_flags::algebraic: {
248 epvector::const_iterator i = seq.begin(), end = seq.end();
250 if ((recombine_pair_to_ex(*i).info(inf)))
257 return inherited::info(inf);
260 int add::degree(const ex & s) const
262 int deg = std::numeric_limits<int>::min();
263 if (!overall_coeff.is_zero())
266 // Find maximum of degrees of individual terms
267 epvector::const_iterator i = seq.begin(), end = seq.end();
269 int cur_deg = i->rest.degree(s);
277 int add::ldegree(const ex & s) const
279 int deg = std::numeric_limits<int>::max();
280 if (!overall_coeff.is_zero())
283 // Find minimum of degrees of individual terms
284 epvector::const_iterator i = seq.begin(), end = seq.end();
286 int cur_deg = i->rest.ldegree(s);
294 ex add::coeff(const ex & s, int n) const
296 std::auto_ptr<epvector> coeffseq(new epvector);
297 std::auto_ptr<epvector> coeffseq_cliff(new epvector);
298 char rl = clifford_max_label(s);
299 bool do_clifford = (rl != -1);
300 bool nonscalar = false;
302 // Calculate sum of coefficients in each term
303 epvector::const_iterator i = seq.begin(), end = seq.end();
305 ex restcoeff = i->rest.coeff(s, n);
306 if (!restcoeff.is_zero()) {
308 if (clifford_max_label(restcoeff) == -1) {
309 coeffseq_cliff->push_back(combine_ex_with_coeff_to_pair(ncmul(restcoeff, dirac_ONE(rl)), i->coeff));
311 coeffseq_cliff->push_back(combine_ex_with_coeff_to_pair(restcoeff, i->coeff));
315 coeffseq->push_back(combine_ex_with_coeff_to_pair(restcoeff, i->coeff));
320 return (new add(nonscalar ? coeffseq_cliff : coeffseq,
321 n==0 ? overall_coeff : _ex0))->setflag(status_flags::dynallocated);
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 std::auto_ptr<epvector> evaled_seqp = evalchildren(level);
334 if (evaled_seqp.get()) {
335 // do more evaluation later
336 return (new add(evaled_seqp, overall_coeff))->
337 setflag(status_flags::dynallocated);
340 #ifdef DO_GINAC_ASSERT
341 epvector::const_iterator i = seq.begin(), end = seq.end();
343 GINAC_ASSERT(!is_exactly_a<add>(i->rest));
344 if (is_exactly_a<numeric>(i->rest))
346 GINAC_ASSERT(!is_exactly_a<numeric>(i->rest));
349 #endif // def DO_GINAC_ASSERT
351 if (flags & status_flags::evaluated) {
352 GINAC_ASSERT(seq.size()>0);
353 GINAC_ASSERT(seq.size()>1 || !overall_coeff.is_zero());
357 int seq_size = seq.size();
360 return overall_coeff;
361 } else if (seq_size == 1 && overall_coeff.is_zero()) {
363 return recombine_pair_to_ex(*(seq.begin()));
364 } else if (!overall_coeff.is_zero() && seq[0].rest.return_type() != return_types::commutative) {
365 throw (std::logic_error("add::eval(): sum of non-commutative objects has non-zero numeric term"));
370 ex add::evalm() const
372 // Evaluate children first and add up all matrices. Stop if there's one
373 // term that is not a matrix.
374 std::auto_ptr<epvector> s(new epvector);
375 s->reserve(seq.size());
377 bool all_matrices = true;
378 bool first_term = true;
381 epvector::const_iterator it = seq.begin(), itend = seq.end();
382 while (it != itend) {
383 const ex &m = recombine_pair_to_ex(*it).evalm();
384 s->push_back(split_ex_to_pair(m));
385 if (is_a<matrix>(m)) {
387 sum = ex_to<matrix>(m);
390 sum = sum.add(ex_to<matrix>(m));
392 all_matrices = false;
397 return sum + overall_coeff;
399 return (new add(s, overall_coeff))->setflag(status_flags::dynallocated);
402 ex add::conjugate() const
405 for (size_t i=0; i<nops(); ++i) {
407 v->push_back(op(i).conjugate());
411 ex ccterm = term.conjugate();
412 if (are_ex_trivially_equal(term, ccterm))
416 for (size_t j=0; j<i; ++j)
418 v->push_back(ccterm);
428 ex add::real_part() const
431 v.reserve(seq.size());
432 for (epvector::const_iterator i=seq.begin(); i!=seq.end(); ++i)
433 if ((i->coeff).info(info_flags::real)) {
434 ex rp = (i->rest).real_part();
436 v.push_back(expair(rp, i->coeff));
438 ex rp=recombine_pair_to_ex(*i).real_part();
440 v.push_back(split_ex_to_pair(rp));
442 return (new add(v, overall_coeff.real_part()))
443 -> setflag(status_flags::dynallocated);
446 ex add::imag_part() const
449 v.reserve(seq.size());
450 for (epvector::const_iterator i=seq.begin(); i!=seq.end(); ++i)
451 if ((i->coeff).info(info_flags::real)) {
452 ex ip = (i->rest).imag_part();
454 v.push_back(expair(ip, i->coeff));
456 ex ip=recombine_pair_to_ex(*i).imag_part();
458 v.push_back(split_ex_to_pair(ip));
460 return (new add(v, overall_coeff.imag_part()))
461 -> setflag(status_flags::dynallocated);
464 ex add::eval_ncmul(const exvector & v) const
467 return inherited::eval_ncmul(v);
469 return seq.begin()->rest.eval_ncmul(v);
474 /** Implementation of ex::diff() for a sum. It differentiates each term.
476 ex add::derivative(const symbol & y) const
478 std::auto_ptr<epvector> s(new epvector);
479 s->reserve(seq.size());
481 // Only differentiate the "rest" parts of the expairs. This is faster
482 // than the default implementation in basic::derivative() although
483 // if performs the same function (differentiate each term).
484 epvector::const_iterator i = seq.begin(), end = seq.end();
486 s->push_back(combine_ex_with_coeff_to_pair(i->rest.diff(y), i->coeff));
489 return (new add(s, _ex0))->setflag(status_flags::dynallocated);
492 int add::compare_same_type(const basic & other) const
494 return inherited::compare_same_type(other);
497 unsigned add::return_type() const
500 return return_types::commutative;
502 return seq.begin()->rest.return_type();
505 tinfo_t add::return_type_tinfo() const
510 return seq.begin()->rest.return_type_tinfo();
513 // Note: do_index_renaming is ignored because it makes no sense for an add.
514 ex add::thisexpairseq(const epvector & v, const ex & oc, bool do_index_renaming) const
516 return (new add(v,oc))->setflag(status_flags::dynallocated);
519 // Note: do_index_renaming is ignored because it makes no sense for an add.
520 ex add::thisexpairseq(std::auto_ptr<epvector> vp, const ex & oc, bool do_index_renaming) const
522 return (new add(vp,oc))->setflag(status_flags::dynallocated);
525 expair add::split_ex_to_pair(const ex & e) const
527 if (is_exactly_a<mul>(e)) {
528 const mul &mulref(ex_to<mul>(e));
529 const ex &numfactor = mulref.overall_coeff;
530 mul *mulcopyp = new mul(mulref);
531 mulcopyp->overall_coeff = _ex1;
532 mulcopyp->clearflag(status_flags::evaluated);
533 mulcopyp->clearflag(status_flags::hash_calculated);
534 mulcopyp->setflag(status_flags::dynallocated);
535 return expair(*mulcopyp,numfactor);
537 return expair(e,_ex1);
540 expair add::combine_ex_with_coeff_to_pair(const ex & e,
543 GINAC_ASSERT(is_exactly_a<numeric>(c));
544 if (is_exactly_a<mul>(e)) {
545 const mul &mulref(ex_to<mul>(e));
546 const ex &numfactor = mulref.overall_coeff;
547 mul *mulcopyp = new mul(mulref);
548 mulcopyp->overall_coeff = _ex1;
549 mulcopyp->clearflag(status_flags::evaluated);
550 mulcopyp->clearflag(status_flags::hash_calculated);
551 mulcopyp->setflag(status_flags::dynallocated);
552 if (c.is_equal(_ex1))
553 return expair(*mulcopyp, numfactor);
554 else if (numfactor.is_equal(_ex1))
555 return expair(*mulcopyp, c);
557 return expair(*mulcopyp, ex_to<numeric>(numfactor).mul_dyn(ex_to<numeric>(c)));
558 } else if (is_exactly_a<numeric>(e)) {
559 if (c.is_equal(_ex1))
560 return expair(e, _ex1);
561 return expair(ex_to<numeric>(e).mul_dyn(ex_to<numeric>(c)), _ex1);
566 expair add::combine_pair_with_coeff_to_pair(const expair & p,
569 GINAC_ASSERT(is_exactly_a<numeric>(p.coeff));
570 GINAC_ASSERT(is_exactly_a<numeric>(c));
572 if (is_exactly_a<numeric>(p.rest)) {
573 GINAC_ASSERT(ex_to<numeric>(p.coeff).is_equal(*_num1_p)); // should be normalized
574 return expair(ex_to<numeric>(p.rest).mul_dyn(ex_to<numeric>(c)),_ex1);
577 return expair(p.rest,ex_to<numeric>(p.coeff).mul_dyn(ex_to<numeric>(c)));
580 ex add::recombine_pair_to_ex(const expair & p) const
582 if (ex_to<numeric>(p.coeff).is_equal(*_num1_p))
585 return (new mul(p.rest,p.coeff))->setflag(status_flags::dynallocated);
588 ex add::expand(unsigned options) const
590 std::auto_ptr<epvector> vp = expandchildren(options);
592 // the terms have not changed, so it is safe to declare this expanded
593 return (options == 0) ? setflag(status_flags::expanded) : *this;
596 return (new add(vp, overall_coeff))->setflag(status_flags::dynallocated | (options == 0 ? status_flags::expanded : 0));