]> www.ginac.de Git - ginac.git/blob - ginac/add.cpp
Needed to call get_all_dummy_indices_safely more often.
[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-2006 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
26 #include "add.h"
27 #include "mul.h"
28 #include "archive.h"
29 #include "operators.h"
30 #include "matrix.h"
31 #include "utils.h"
32 #include "clifford.h"
33 #include "ncmul.h"
34
35 namespace GiNaC {
36
37 GINAC_IMPLEMENT_REGISTERED_CLASS_OPT(add, expairseq,
38   print_func<print_context>(&add::do_print).
39   print_func<print_latex>(&add::do_print_latex).
40   print_func<print_csrc>(&add::do_print_csrc).
41   print_func<print_tree>(&add::do_print_tree).
42   print_func<print_python_repr>(&add::do_print_python_repr))
43
44 //////////
45 // default constructor
46 //////////
47
48 add::add()
49 {
50         tinfo_key = &add::tinfo_static;
51 }
52
53 //////////
54 // other constructors
55 //////////
56
57 // public
58
59 add::add(const ex & lh, const ex & rh)
60 {
61         tinfo_key = &add::tinfo_static;
62         overall_coeff = _ex0;
63         construct_from_2_ex(lh,rh);
64         GINAC_ASSERT(is_canonical());
65 }
66
67 add::add(const exvector & v)
68 {
69         tinfo_key = &add::tinfo_static;
70         overall_coeff = _ex0;
71         construct_from_exvector(v);
72         GINAC_ASSERT(is_canonical());
73 }
74
75 add::add(const epvector & v)
76 {
77         tinfo_key = &add::tinfo_static;
78         overall_coeff = _ex0;
79         construct_from_epvector(v);
80         GINAC_ASSERT(is_canonical());
81 }
82
83 add::add(const epvector & v, const ex & oc)
84 {
85         tinfo_key = &add::tinfo_static;
86         overall_coeff = oc;
87         construct_from_epvector(v);
88         GINAC_ASSERT(is_canonical());
89 }
90
91 add::add(std::auto_ptr<epvector> vp, const ex & oc)
92 {
93         tinfo_key = &add::tinfo_static;
94         GINAC_ASSERT(vp.get()!=0);
95         overall_coeff = oc;
96         construct_from_epvector(*vp);
97         GINAC_ASSERT(is_canonical());
98 }
99
100 //////////
101 // archiving
102 //////////
103
104 DEFAULT_ARCHIVING(add)
105
106 //////////
107 // functions overriding virtual functions from base classes
108 //////////
109
110 // public
111
112 void add::print_add(const print_context & c, const char *openbrace, const char *closebrace, const char *mul_sym, unsigned level) const
113 {
114         if (precedence() <= level)
115                 c.s << openbrace << '(';
116
117         numeric coeff;
118         bool first = true;
119
120         // First print the overall numeric coefficient, if present
121         if (!overall_coeff.is_zero()) {
122                 overall_coeff.print(c, 0);
123                 first = false;
124         }
125
126         // Then proceed with the remaining factors
127         epvector::const_iterator it = seq.begin(), itend = seq.end();
128         while (it != itend) {
129                 coeff = ex_to<numeric>(it->coeff);
130                 if (!first) {
131                         if (coeff.csgn() == -1) c.s << '-'; else c.s << '+';
132                 } else {
133                         if (coeff.csgn() == -1) c.s << '-';
134                         first = false;
135                 }
136                 if (!coeff.is_equal(*_num1_p) &&
137                     !coeff.is_equal(*_num_1_p)) {
138                         if (coeff.is_rational()) {
139                                 if (coeff.is_negative())
140                                         (-coeff).print(c);
141                                 else
142                                         coeff.print(c);
143                         } else {
144                                 if (coeff.csgn() == -1)
145                                         (-coeff).print(c, precedence());
146                                 else
147                                         coeff.print(c, precedence());
148                         }
149                         c.s << mul_sym;
150                 }
151                 it->rest.print(c, precedence());
152                 ++it;
153         }
154
155         if (precedence() <= level)
156                 c.s << ')' << closebrace;
157 }
158
159 void add::do_print(const print_context & c, unsigned level) const
160 {
161         print_add(c, "", "", "*", level);
162 }
163
164 void add::do_print_latex(const print_latex & c, unsigned level) const
165 {
166         print_add(c, "{", "}", " ", level);
167 }
168
169 void add::do_print_csrc(const print_csrc & c, unsigned level) const
170 {
171         if (precedence() <= level)
172                 c.s << "(";
173         
174         // Print arguments, separated by "+"
175         epvector::const_iterator it = seq.begin(), itend = seq.end();
176         while (it != itend) {
177                 
178                 // If the coefficient is -1, it is replaced by a single minus sign
179                 if (it->coeff.is_equal(_ex1)) {
180                         it->rest.print(c, precedence());
181                 } else if (it->coeff.is_equal(_ex_1)) {
182                         c.s << "-";
183                         it->rest.print(c, precedence());
184                 } else if (ex_to<numeric>(it->coeff).numer().is_equal(*_num1_p)) {
185                         it->rest.print(c, precedence());
186                         c.s << "/";
187                         ex_to<numeric>(it->coeff).denom().print(c, precedence());
188                 } else if (ex_to<numeric>(it->coeff).numer().is_equal(*_num_1_p)) {
189                         c.s << "-";
190                         it->rest.print(c, precedence());
191                         c.s << "/";
192                         ex_to<numeric>(it->coeff).denom().print(c, precedence());
193                 } else {
194                         it->coeff.print(c, precedence());
195                         c.s << "*";
196                         it->rest.print(c, precedence());
197                 }
198                 
199                 // Separator is "+", except if the following expression would have a leading minus sign or the sign is sitting in parenthesis (as in a ctor)
200                 ++it;
201                 if (it != itend
202                  && (is_a<print_csrc_cl_N>(c) || !it->coeff.info(info_flags::real)  // sign inside ctor arguments
203                   || !(it->coeff.info(info_flags::negative) || (it->coeff.is_equal(*_num1_p) && is_exactly_a<numeric>(it->rest) && it->rest.info(info_flags::negative)))))
204                         c.s << "+";
205         }
206         
207         if (!overall_coeff.is_zero()) {
208                 if (overall_coeff.info(info_flags::positive)
209                  || is_a<print_csrc_cl_N>(c) || !overall_coeff.info(info_flags::real))  // sign inside ctor argument
210                         c.s << '+';
211                 overall_coeff.print(c, precedence());
212         }
213                 
214         if (precedence() <= level)
215                 c.s << ")";
216 }
217
218 void add::do_print_python_repr(const print_python_repr & c, unsigned level) const
219 {
220         c.s << class_name() << '(';
221         op(0).print(c);
222         for (size_t i=1; i<nops(); ++i) {
223                 c.s << ',';
224                 op(i).print(c);
225         }
226         c.s << ')';
227 }
228
229 bool add::info(unsigned inf) const
230 {
231         switch (inf) {
232                 case info_flags::polynomial:
233                 case info_flags::integer_polynomial:
234                 case info_flags::cinteger_polynomial:
235                 case info_flags::rational_polynomial:
236                 case info_flags::crational_polynomial:
237                 case info_flags::rational_function: {
238                         epvector::const_iterator i = seq.begin(), end = seq.end();
239                         while (i != end) {
240                                 if (!(recombine_pair_to_ex(*i).info(inf)))
241                                         return false;
242                                 ++i;
243                         }
244                         return overall_coeff.info(inf);
245                 }
246                 case info_flags::algebraic: {
247                         epvector::const_iterator i = seq.begin(), end = seq.end();
248                         while (i != end) {
249                                 if ((recombine_pair_to_ex(*i).info(inf)))
250                                         return true;
251                                 ++i;
252                         }
253                         return false;
254                 }
255         }
256         return inherited::info(inf);
257 }
258
259 int add::degree(const ex & s) const
260 {
261         int deg = INT_MIN;
262         if (!overall_coeff.is_zero())
263                 deg = 0;
264         
265         // Find maximum of degrees of individual terms
266         epvector::const_iterator i = seq.begin(), end = seq.end();
267         while (i != end) {
268                 int cur_deg = i->rest.degree(s);
269                 if (cur_deg > deg)
270                         deg = cur_deg;
271                 ++i;
272         }
273         return deg;
274 }
275
276 int add::ldegree(const ex & s) const
277 {
278         int deg = INT_MAX;
279         if (!overall_coeff.is_zero())
280                 deg = 0;
281         
282         // Find minimum of degrees of individual terms
283         epvector::const_iterator i = seq.begin(), end = seq.end();
284         while (i != end) {
285                 int cur_deg = i->rest.ldegree(s);
286                 if (cur_deg < deg)
287                         deg = cur_deg;
288                 ++i;
289         }
290         return deg;
291 }
292
293 ex add::coeff(const ex & s, int n) const
294 {
295         std::auto_ptr<epvector> coeffseq(new epvector);
296         std::auto_ptr<epvector> coeffseq_cliff(new epvector);
297         char rl = clifford_max_label(s);
298         bool do_clifford = (rl != -1);
299         bool nonscalar = false;
300
301         // Calculate sum of coefficients in each term
302         epvector::const_iterator i = seq.begin(), end = seq.end();
303         while (i != end) {
304                 ex restcoeff = i->rest.coeff(s, n);
305                 if (!restcoeff.is_zero()) {
306                         if (do_clifford) {
307                                 if (clifford_max_label(restcoeff) == -1) {
308                                         coeffseq_cliff->push_back(combine_ex_with_coeff_to_pair(ncmul(restcoeff, dirac_ONE(rl)), i->coeff));
309                                 } else {
310                                         coeffseq_cliff->push_back(combine_ex_with_coeff_to_pair(restcoeff, i->coeff));
311                                         nonscalar = true;
312                                 }
313                         }
314                         coeffseq->push_back(combine_ex_with_coeff_to_pair(restcoeff, i->coeff));
315                 }
316                 ++i;
317         }
318
319         return (new add(nonscalar ? coeffseq_cliff : coeffseq,
320                         n==0 ? overall_coeff : _ex0))->setflag(status_flags::dynallocated);
321 }
322
323 /** Perform automatic term rewriting rules in this class.  In the following
324  *  x stands for a symbolic variables of type ex and c stands for such
325  *  an expression that contain a plain number.
326  *  - +(;c) -> c
327  *  - +(x;0) -> x
328  *
329  *  @param level cut-off in recursive evaluation */
330 ex add::eval(int level) const
331 {
332         std::auto_ptr<epvector> evaled_seqp = evalchildren(level);
333         if (evaled_seqp.get()) {
334                 // do more evaluation later
335                 return (new add(evaled_seqp, overall_coeff))->
336                        setflag(status_flags::dynallocated);
337         }
338         
339 #ifdef DO_GINAC_ASSERT
340         epvector::const_iterator i = seq.begin(), end = seq.end();
341         while (i != end) {
342                 GINAC_ASSERT(!is_exactly_a<add>(i->rest));
343                 if (is_exactly_a<numeric>(i->rest))
344                         dbgprint();
345                 GINAC_ASSERT(!is_exactly_a<numeric>(i->rest));
346                 ++i;
347         }
348 #endif // def DO_GINAC_ASSERT
349         
350         if (flags & status_flags::evaluated) {
351                 GINAC_ASSERT(seq.size()>0);
352                 GINAC_ASSERT(seq.size()>1 || !overall_coeff.is_zero());
353                 return *this;
354         }
355         
356         int seq_size = seq.size();
357         if (seq_size == 0) {
358                 // +(;c) -> c
359                 return overall_coeff;
360         } else if (seq_size == 1 && overall_coeff.is_zero()) {
361                 // +(x;0) -> x
362                 return recombine_pair_to_ex(*(seq.begin()));
363         } else if (!overall_coeff.is_zero() && seq[0].rest.return_type() != return_types::commutative) {
364                 throw (std::logic_error("add::eval(): sum of non-commutative objects has non-zero numeric term"));
365         }
366         return this->hold();
367 }
368
369 ex add::evalm() const
370 {
371         // Evaluate children first and add up all matrices. Stop if there's one
372         // term that is not a matrix.
373         std::auto_ptr<epvector> s(new epvector);
374         s->reserve(seq.size());
375
376         bool all_matrices = true;
377         bool first_term = true;
378         matrix sum;
379
380         epvector::const_iterator it = seq.begin(), itend = seq.end();
381         while (it != itend) {
382                 const ex &m = recombine_pair_to_ex(*it).evalm();
383                 s->push_back(split_ex_to_pair(m));
384                 if (is_a<matrix>(m)) {
385                         if (first_term) {
386                                 sum = ex_to<matrix>(m);
387                                 first_term = false;
388                         } else
389                                 sum = sum.add(ex_to<matrix>(m));
390                 } else
391                         all_matrices = false;
392                 ++it;
393         }
394
395         if (all_matrices)
396                 return sum + overall_coeff;
397         else
398                 return (new add(s, overall_coeff))->setflag(status_flags::dynallocated);
399 }
400
401 ex add::conjugate() const
402 {
403         exvector *v = 0;
404         for (size_t i=0; i<nops(); ++i) {
405                 if (v) {
406                         v->push_back(op(i).conjugate());
407                         continue;
408                 }
409                 ex term = op(i);
410                 ex ccterm = term.conjugate();
411                 if (are_ex_trivially_equal(term, ccterm))
412                         continue;
413                 v = new exvector;
414                 v->reserve(nops());
415                 for (size_t j=0; j<i; ++j)
416                         v->push_back(op(j));
417                 v->push_back(ccterm);
418         }
419         if (v) {
420                 ex result = add(*v);
421                 delete v;
422                 return result;
423         }
424         return *this;
425 }
426
427 ex add::real_part() const
428 {
429         epvector v;
430         v.reserve(seq.size());
431         for (epvector::const_iterator i=seq.begin(); i!=seq.end(); ++i)
432                 if ((i->coeff).info(info_flags::real))
433                         v.push_back(expair((i->rest).real_part(), i->coeff));
434                 else {
435                         ex rp=recombine_pair_to_ex(*i).real_part();
436                         v.push_back(split_ex_to_pair(rp));
437                 }
438         return (new add(v, overall_coeff.real_part()))
439                 -> setflag(status_flags::dynallocated);
440 }
441
442 ex add::imag_part() const
443 {
444         epvector v;
445         v.reserve(seq.size());
446         for (epvector::const_iterator i=seq.begin(); i!=seq.end(); ++i)
447                 if ((i->coeff).info(info_flags::real))
448                         v.push_back(expair((i->rest).imag_part(), i->coeff));
449                 else {
450                         ex ip=recombine_pair_to_ex(*i).imag_part();
451                         v.push_back(split_ex_to_pair(ip));
452                 }
453         return (new add(v, overall_coeff.imag_part()))
454                 -> setflag(status_flags::dynallocated);
455 }
456
457 ex add::eval_ncmul(const exvector & v) const
458 {
459         if (seq.empty())
460                 return inherited::eval_ncmul(v);
461         else
462                 return seq.begin()->rest.eval_ncmul(v);
463 }    
464
465 // protected
466
467 /** Implementation of ex::diff() for a sum. It differentiates each term.
468  *  @see ex::diff */
469 ex add::derivative(const symbol & y) const
470 {
471         std::auto_ptr<epvector> s(new epvector);
472         s->reserve(seq.size());
473         
474         // Only differentiate the "rest" parts of the expairs. This is faster
475         // than the default implementation in basic::derivative() although
476         // if performs the same function (differentiate each term).
477         epvector::const_iterator i = seq.begin(), end = seq.end();
478         while (i != end) {
479                 s->push_back(combine_ex_with_coeff_to_pair(i->rest.diff(y), i->coeff));
480                 ++i;
481         }
482         return (new add(s, _ex0))->setflag(status_flags::dynallocated);
483 }
484
485 int add::compare_same_type(const basic & other) const
486 {
487         return inherited::compare_same_type(other);
488 }
489
490 unsigned add::return_type() const
491 {
492         if (seq.empty())
493                 return return_types::commutative;
494         else
495                 return seq.begin()->rest.return_type();
496 }
497
498 tinfo_t add::return_type_tinfo() const
499 {
500         if (seq.empty())
501                 return this;
502         else
503                 return seq.begin()->rest.return_type_tinfo();
504 }
505
506 ex add::thisexpairseq(const epvector & v, const ex & oc) const
507 {
508         return (new add(v,oc))->setflag(status_flags::dynallocated);
509 }
510
511 ex add::thisexpairseq(std::auto_ptr<epvector> vp, const ex & oc) const
512 {
513         return (new add(vp,oc))->setflag(status_flags::dynallocated);
514 }
515
516 expair add::split_ex_to_pair(const ex & e) const
517 {
518         if (is_exactly_a<mul>(e)) {
519                 const mul &mulref(ex_to<mul>(e));
520                 const ex &numfactor = mulref.overall_coeff;
521                 mul *mulcopyp = new mul(mulref);
522                 mulcopyp->overall_coeff = _ex1;
523                 mulcopyp->clearflag(status_flags::evaluated);
524                 mulcopyp->clearflag(status_flags::hash_calculated);
525                 mulcopyp->setflag(status_flags::dynallocated);
526                 return expair(*mulcopyp,numfactor);
527         }
528         return expair(e,_ex1);
529 }
530
531 expair add::combine_ex_with_coeff_to_pair(const ex & e,
532                                                                                   const ex & c) const
533 {
534         GINAC_ASSERT(is_exactly_a<numeric>(c));
535         if (is_exactly_a<mul>(e)) {
536                 const mul &mulref(ex_to<mul>(e));
537                 const ex &numfactor = mulref.overall_coeff;
538                 mul *mulcopyp = new mul(mulref);
539                 mulcopyp->overall_coeff = _ex1;
540                 mulcopyp->clearflag(status_flags::evaluated);
541                 mulcopyp->clearflag(status_flags::hash_calculated);
542                 mulcopyp->setflag(status_flags::dynallocated);
543                 if (c.is_equal(_ex1))
544                         return expair(*mulcopyp, numfactor);
545                 else if (numfactor.is_equal(_ex1))
546                         return expair(*mulcopyp, c);
547                 else
548                         return expair(*mulcopyp, ex_to<numeric>(numfactor).mul_dyn(ex_to<numeric>(c)));
549         } else if (is_exactly_a<numeric>(e)) {
550                 if (c.is_equal(_ex1))
551                         return expair(e, _ex1);
552                 return expair(ex_to<numeric>(e).mul_dyn(ex_to<numeric>(c)), _ex1);
553         }
554         return expair(e, c);
555 }
556
557 expair add::combine_pair_with_coeff_to_pair(const expair & p,
558                                                                                         const ex & c) const
559 {
560         GINAC_ASSERT(is_exactly_a<numeric>(p.coeff));
561         GINAC_ASSERT(is_exactly_a<numeric>(c));
562
563         if (is_exactly_a<numeric>(p.rest)) {
564                 GINAC_ASSERT(ex_to<numeric>(p.coeff).is_equal(*_num1_p)); // should be normalized
565                 return expair(ex_to<numeric>(p.rest).mul_dyn(ex_to<numeric>(c)),_ex1);
566         }
567
568         return expair(p.rest,ex_to<numeric>(p.coeff).mul_dyn(ex_to<numeric>(c)));
569 }
570         
571 ex add::recombine_pair_to_ex(const expair & p) const
572 {
573         if (ex_to<numeric>(p.coeff).is_equal(*_num1_p))
574                 return p.rest;
575         else
576                 return (new mul(p.rest,p.coeff))->setflag(status_flags::dynallocated);
577 }
578
579 ex add::expand(unsigned options) const
580 {
581         std::auto_ptr<epvector> vp = expandchildren(options);
582         if (vp.get() == 0) {
583                 // the terms have not changed, so it is safe to declare this expanded
584                 return (options == 0) ? setflag(status_flags::expanded) : *this;
585         }
586
587         return (new add(vp, overall_coeff))->setflag(status_flags::dynallocated | (options == 0 ? status_flags::expanded : 0));
588 }
589
590 } // namespace GiNaC