* Fix compilation issues with prereleases of GCC 4.3, at least in theory.
[ginac.git] / ginac / add.cpp
1 /** @file add.cpp
2  *
3  *  Implementation of GiNaC's sums of expressions. */
4
5 /*
6  *  GiNaC Copyright (C) 1999-2007 Johannes Gutenberg University Mainz, Germany
7  *
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.
12  *
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.
17  *
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
21  */
22
23 #include <iostream>
24 #include <stdexcept>
25 #include <limits>
26
27 #include "add.h"
28 #include "mul.h"
29 #include "archive.h"
30 #include "operators.h"
31 #include "matrix.h"
32 #include "utils.h"
33 #include "clifford.h"
34 #include "ncmul.h"
35
36 namespace GiNaC {
37
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))
44
45 //////////
46 // default constructor
47 //////////
48
49 add::add()
50 {
51         tinfo_key = &add::tinfo_static;
52 }
53
54 //////////
55 // other constructors
56 //////////
57
58 // public
59
60 add::add(const ex & lh, const ex & rh)
61 {
62         tinfo_key = &add::tinfo_static;
63         overall_coeff = _ex0;
64         construct_from_2_ex(lh,rh);
65         GINAC_ASSERT(is_canonical());
66 }
67
68 add::add(const exvector & v)
69 {
70         tinfo_key = &add::tinfo_static;
71         overall_coeff = _ex0;
72         construct_from_exvector(v);
73         GINAC_ASSERT(is_canonical());
74 }
75
76 add::add(const epvector & v)
77 {
78         tinfo_key = &add::tinfo_static;
79         overall_coeff = _ex0;
80         construct_from_epvector(v);
81         GINAC_ASSERT(is_canonical());
82 }
83
84 add::add(const epvector & v, const ex & oc)
85 {
86         tinfo_key = &add::tinfo_static;
87         overall_coeff = oc;
88         construct_from_epvector(v);
89         GINAC_ASSERT(is_canonical());
90 }
91
92 add::add(std::auto_ptr<epvector> vp, const ex & oc)
93 {
94         tinfo_key = &add::tinfo_static;
95         GINAC_ASSERT(vp.get()!=0);
96         overall_coeff = oc;
97         construct_from_epvector(*vp);
98         GINAC_ASSERT(is_canonical());
99 }
100
101 //////////
102 // archiving
103 //////////
104
105 DEFAULT_ARCHIVING(add)
106
107 //////////
108 // functions overriding virtual functions from base classes
109 //////////
110
111 // public
112
113 void add::print_add(const print_context & c, const char *openbrace, const char *closebrace, const char *mul_sym, unsigned level) const
114 {
115         if (precedence() <= level)
116                 c.s << openbrace << '(';
117
118         numeric coeff;
119         bool first = true;
120
121         // First print the overall numeric coefficient, if present
122         if (!overall_coeff.is_zero()) {
123                 overall_coeff.print(c, 0);
124                 first = false;
125         }
126
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);
131                 if (!first) {
132                         if (coeff.csgn() == -1) c.s << '-'; else c.s << '+';
133                 } else {
134                         if (coeff.csgn() == -1) c.s << '-';
135                         first = false;
136                 }
137                 if (!coeff.is_equal(*_num1_p) &&
138                     !coeff.is_equal(*_num_1_p)) {
139                         if (coeff.is_rational()) {
140                                 if (coeff.is_negative())
141                                         (-coeff).print(c);
142                                 else
143                                         coeff.print(c);
144                         } else {
145                                 if (coeff.csgn() == -1)
146                                         (-coeff).print(c, precedence());
147                                 else
148                                         coeff.print(c, precedence());
149                         }
150                         c.s << mul_sym;
151                 }
152                 it->rest.print(c, precedence());
153                 ++it;
154         }
155
156         if (precedence() <= level)
157                 c.s << ')' << closebrace;
158 }
159
160 void add::do_print(const print_context & c, unsigned level) const
161 {
162         print_add(c, "", "", "*", level);
163 }
164
165 void add::do_print_latex(const print_latex & c, unsigned level) const
166 {
167         print_add(c, "{", "}", " ", level);
168 }
169
170 void add::do_print_csrc(const print_csrc & c, unsigned level) const
171 {
172         if (precedence() <= level)
173                 c.s << "(";
174         
175         // Print arguments, separated by "+"
176         epvector::const_iterator it = seq.begin(), itend = seq.end();
177         while (it != itend) {
178                 
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)) {
183                         c.s << "-";
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());
187                         c.s << "/";
188                         ex_to<numeric>(it->coeff).denom().print(c, precedence());
189                 } else if (ex_to<numeric>(it->coeff).numer().is_equal(*_num_1_p)) {
190                         c.s << "-";
191                         it->rest.print(c, precedence());
192                         c.s << "/";
193                         ex_to<numeric>(it->coeff).denom().print(c, precedence());
194                 } else {
195                         it->coeff.print(c, precedence());
196                         c.s << "*";
197                         it->rest.print(c, precedence());
198                 }
199                 
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)
201                 ++it;
202                 if (it != itend
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)))))
205                         c.s << "+";
206         }
207         
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
211                         c.s << '+';
212                 overall_coeff.print(c, precedence());
213         }
214                 
215         if (precedence() <= level)
216                 c.s << ")";
217 }
218
219 void add::do_print_python_repr(const print_python_repr & c, unsigned level) const
220 {
221         c.s << class_name() << '(';
222         op(0).print(c);
223         for (size_t i=1; i<nops(); ++i) {
224                 c.s << ',';
225                 op(i).print(c);
226         }
227         c.s << ')';
228 }
229
230 bool add::info(unsigned inf) const
231 {
232         switch (inf) {
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();
240                         while (i != end) {
241                                 if (!(recombine_pair_to_ex(*i).info(inf)))
242                                         return false;
243                                 ++i;
244                         }
245                         return overall_coeff.info(inf);
246                 }
247                 case info_flags::algebraic: {
248                         epvector::const_iterator i = seq.begin(), end = seq.end();
249                         while (i != end) {
250                                 if ((recombine_pair_to_ex(*i).info(inf)))
251                                         return true;
252                                 ++i;
253                         }
254                         return false;
255                 }
256         }
257         return inherited::info(inf);
258 }
259
260 int add::degree(const ex & s) const
261 {
262         int deg = std::numeric_limits<int>::min();
263         if (!overall_coeff.is_zero())
264                 deg = 0;
265         
266         // Find maximum of degrees of individual terms
267         epvector::const_iterator i = seq.begin(), end = seq.end();
268         while (i != end) {
269                 int cur_deg = i->rest.degree(s);
270                 if (cur_deg > deg)
271                         deg = cur_deg;
272                 ++i;
273         }
274         return deg;
275 }
276
277 int add::ldegree(const ex & s) const
278 {
279         int deg = std::numeric_limits<int>::max();
280         if (!overall_coeff.is_zero())
281                 deg = 0;
282         
283         // Find minimum of degrees of individual terms
284         epvector::const_iterator i = seq.begin(), end = seq.end();
285         while (i != end) {
286                 int cur_deg = i->rest.ldegree(s);
287                 if (cur_deg < deg)
288                         deg = cur_deg;
289                 ++i;
290         }
291         return deg;
292 }
293
294 ex add::coeff(const ex & s, int n) const
295 {
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;
301
302         // Calculate sum of coefficients in each term
303         epvector::const_iterator i = seq.begin(), end = seq.end();
304         while (i != end) {
305                 ex restcoeff = i->rest.coeff(s, n);
306                 if (!restcoeff.is_zero()) {
307                         if (do_clifford) {
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));
310                                 } else {
311                                         coeffseq_cliff->push_back(combine_ex_with_coeff_to_pair(restcoeff, i->coeff));
312                                         nonscalar = true;
313                                 }
314                         }
315                         coeffseq->push_back(combine_ex_with_coeff_to_pair(restcoeff, i->coeff));
316                 }
317                 ++i;
318         }
319
320         return (new add(nonscalar ? coeffseq_cliff : coeffseq,
321                         n==0 ? overall_coeff : _ex0))->setflag(status_flags::dynallocated);
322 }
323
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.
327  *  - +(;c) -> c
328  *  - +(x;0) -> x
329  *
330  *  @param level cut-off in recursive evaluation */
331 ex add::eval(int level) const
332 {
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);
338         }
339         
340 #ifdef DO_GINAC_ASSERT
341         epvector::const_iterator i = seq.begin(), end = seq.end();
342         while (i != end) {
343                 GINAC_ASSERT(!is_exactly_a<add>(i->rest));
344                 if (is_exactly_a<numeric>(i->rest))
345                         dbgprint();
346                 GINAC_ASSERT(!is_exactly_a<numeric>(i->rest));
347                 ++i;
348         }
349 #endif // def DO_GINAC_ASSERT
350         
351         if (flags & status_flags::evaluated) {
352                 GINAC_ASSERT(seq.size()>0);
353                 GINAC_ASSERT(seq.size()>1 || !overall_coeff.is_zero());
354                 return *this;
355         }
356         
357         int seq_size = seq.size();
358         if (seq_size == 0) {
359                 // +(;c) -> c
360                 return overall_coeff;
361         } else if (seq_size == 1 && overall_coeff.is_zero()) {
362                 // +(x;0) -> x
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"));
366         }
367         return this->hold();
368 }
369
370 ex add::evalm() const
371 {
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());
376
377         bool all_matrices = true;
378         bool first_term = true;
379         matrix sum;
380
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)) {
386                         if (first_term) {
387                                 sum = ex_to<matrix>(m);
388                                 first_term = false;
389                         } else
390                                 sum = sum.add(ex_to<matrix>(m));
391                 } else
392                         all_matrices = false;
393                 ++it;
394         }
395
396         if (all_matrices)
397                 return sum + overall_coeff;
398         else
399                 return (new add(s, overall_coeff))->setflag(status_flags::dynallocated);
400 }
401
402 ex add::conjugate() const
403 {
404         exvector *v = 0;
405         for (size_t i=0; i<nops(); ++i) {
406                 if (v) {
407                         v->push_back(op(i).conjugate());
408                         continue;
409                 }
410                 ex term = op(i);
411                 ex ccterm = term.conjugate();
412                 if (are_ex_trivially_equal(term, ccterm))
413                         continue;
414                 v = new exvector;
415                 v->reserve(nops());
416                 for (size_t j=0; j<i; ++j)
417                         v->push_back(op(j));
418                 v->push_back(ccterm);
419         }
420         if (v) {
421                 ex result = add(*v);
422                 delete v;
423                 return result;
424         }
425         return *this;
426 }
427
428 ex add::real_part() const
429 {
430         epvector v;
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();
435                         if (!rp.is_zero())
436                                 v.push_back(expair(rp, i->coeff));
437                 } else {
438                         ex rp=recombine_pair_to_ex(*i).real_part();
439                         if (!rp.is_zero())
440                                 v.push_back(split_ex_to_pair(rp));
441                 }
442         return (new add(v, overall_coeff.real_part()))
443                 -> setflag(status_flags::dynallocated);
444 }
445
446 ex add::imag_part() const
447 {
448         epvector v;
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();
453                         if (!ip.is_zero())
454                                 v.push_back(expair(ip, i->coeff));
455                 } else {
456                         ex ip=recombine_pair_to_ex(*i).imag_part();
457                         if (!ip.is_zero())
458                                 v.push_back(split_ex_to_pair(ip));
459                 }
460         return (new add(v, overall_coeff.imag_part()))
461                 -> setflag(status_flags::dynallocated);
462 }
463
464 ex add::eval_ncmul(const exvector & v) const
465 {
466         if (seq.empty())
467                 return inherited::eval_ncmul(v);
468         else
469                 return seq.begin()->rest.eval_ncmul(v);
470 }    
471
472 // protected
473
474 /** Implementation of ex::diff() for a sum. It differentiates each term.
475  *  @see ex::diff */
476 ex add::derivative(const symbol & y) const
477 {
478         std::auto_ptr<epvector> s(new epvector);
479         s->reserve(seq.size());
480         
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();
485         while (i != end) {
486                 s->push_back(combine_ex_with_coeff_to_pair(i->rest.diff(y), i->coeff));
487                 ++i;
488         }
489         return (new add(s, _ex0))->setflag(status_flags::dynallocated);
490 }
491
492 int add::compare_same_type(const basic & other) const
493 {
494         return inherited::compare_same_type(other);
495 }
496
497 unsigned add::return_type() const
498 {
499         if (seq.empty())
500                 return return_types::commutative;
501         else
502                 return seq.begin()->rest.return_type();
503 }
504
505 tinfo_t add::return_type_tinfo() const
506 {
507         if (seq.empty())
508                 return this;
509         else
510                 return seq.begin()->rest.return_type_tinfo();
511 }
512
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
515 {
516         return (new add(v,oc))->setflag(status_flags::dynallocated);
517 }
518
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
521 {
522         return (new add(vp,oc))->setflag(status_flags::dynallocated);
523 }
524
525 expair add::split_ex_to_pair(const ex & e) const
526 {
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);
536         }
537         return expair(e,_ex1);
538 }
539
540 expair add::combine_ex_with_coeff_to_pair(const ex & e,
541                                                                                   const ex & c) const
542 {
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);
556                 else
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);
562         }
563         return expair(e, c);
564 }
565
566 expair add::combine_pair_with_coeff_to_pair(const expair & p,
567                                                                                         const ex & c) const
568 {
569         GINAC_ASSERT(is_exactly_a<numeric>(p.coeff));
570         GINAC_ASSERT(is_exactly_a<numeric>(c));
571
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);
575         }
576
577         return expair(p.rest,ex_to<numeric>(p.coeff).mul_dyn(ex_to<numeric>(c)));
578 }
579         
580 ex add::recombine_pair_to_ex(const expair & p) const
581 {
582         if (ex_to<numeric>(p.coeff).is_equal(*_num1_p))
583                 return p.rest;
584         else
585                 return (new mul(p.rest,p.coeff))->setflag(status_flags::dynallocated);
586 }
587
588 ex add::expand(unsigned options) const
589 {
590         std::auto_ptr<epvector> vp = expandchildren(options);
591         if (vp.get() == 0) {
592                 // the terms have not changed, so it is safe to declare this expanded
593                 return (options == 0) ? setflag(status_flags::expanded) : *this;
594         }
595
596         return (new add(vp, overall_coeff))->setflag(status_flags::dynallocated | (options == 0 ? status_flags::expanded : 0));
597 }
598
599 } // namespace GiNaC