acced780a596e5eea340365b1b26e058f44d31b6
[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::eval_ncmul(const exvector & v) const
428 {
429         if (seq.empty())
430                 return inherited::eval_ncmul(v);
431         else
432                 return seq.begin()->rest.eval_ncmul(v);
433 }    
434
435 // protected
436
437 /** Implementation of ex::diff() for a sum. It differentiates each term.
438  *  @see ex::diff */
439 ex add::derivative(const symbol & y) const
440 {
441         std::auto_ptr<epvector> s(new epvector);
442         s->reserve(seq.size());
443         
444         // Only differentiate the "rest" parts of the expairs. This is faster
445         // than the default implementation in basic::derivative() although
446         // if performs the same function (differentiate each term).
447         epvector::const_iterator i = seq.begin(), end = seq.end();
448         while (i != end) {
449                 s->push_back(combine_ex_with_coeff_to_pair(i->rest.diff(y), i->coeff));
450                 ++i;
451         }
452         return (new add(s, _ex0))->setflag(status_flags::dynallocated);
453 }
454
455 int add::compare_same_type(const basic & other) const
456 {
457         return inherited::compare_same_type(other);
458 }
459
460 unsigned add::return_type() const
461 {
462         if (seq.empty())
463                 return return_types::commutative;
464         else
465                 return seq.begin()->rest.return_type();
466 }
467
468 tinfo_t add::return_type_tinfo() const
469 {
470         if (seq.empty())
471                 return this;
472         else
473                 return seq.begin()->rest.return_type_tinfo();
474 }
475
476 ex add::thisexpairseq(const epvector & v, const ex & oc) const
477 {
478         return (new add(v,oc))->setflag(status_flags::dynallocated);
479 }
480
481 ex add::thisexpairseq(std::auto_ptr<epvector> vp, const ex & oc) const
482 {
483         return (new add(vp,oc))->setflag(status_flags::dynallocated);
484 }
485
486 expair add::split_ex_to_pair(const ex & e) const
487 {
488         if (is_exactly_a<mul>(e)) {
489                 const mul &mulref(ex_to<mul>(e));
490                 const ex &numfactor = mulref.overall_coeff;
491                 mul *mulcopyp = new mul(mulref);
492                 mulcopyp->overall_coeff = _ex1;
493                 mulcopyp->clearflag(status_flags::evaluated);
494                 mulcopyp->clearflag(status_flags::hash_calculated);
495                 mulcopyp->setflag(status_flags::dynallocated);
496                 return expair(*mulcopyp,numfactor);
497         }
498         return expair(e,_ex1);
499 }
500
501 expair add::combine_ex_with_coeff_to_pair(const ex & e,
502                                                                                   const ex & c) const
503 {
504         GINAC_ASSERT(is_exactly_a<numeric>(c));
505         if (is_exactly_a<mul>(e)) {
506                 const mul &mulref(ex_to<mul>(e));
507                 const ex &numfactor = mulref.overall_coeff;
508                 mul *mulcopyp = new mul(mulref);
509                 mulcopyp->overall_coeff = _ex1;
510                 mulcopyp->clearflag(status_flags::evaluated);
511                 mulcopyp->clearflag(status_flags::hash_calculated);
512                 mulcopyp->setflag(status_flags::dynallocated);
513                 if (c.is_equal(_ex1))
514                         return expair(*mulcopyp, numfactor);
515                 else if (numfactor.is_equal(_ex1))
516                         return expair(*mulcopyp, c);
517                 else
518                         return expair(*mulcopyp, ex_to<numeric>(numfactor).mul_dyn(ex_to<numeric>(c)));
519         } else if (is_exactly_a<numeric>(e)) {
520                 if (c.is_equal(_ex1))
521                         return expair(e, _ex1);
522                 return expair(ex_to<numeric>(e).mul_dyn(ex_to<numeric>(c)), _ex1);
523         }
524         return expair(e, c);
525 }
526
527 expair add::combine_pair_with_coeff_to_pair(const expair & p,
528                                                                                         const ex & c) const
529 {
530         GINAC_ASSERT(is_exactly_a<numeric>(p.coeff));
531         GINAC_ASSERT(is_exactly_a<numeric>(c));
532
533         if (is_exactly_a<numeric>(p.rest)) {
534                 GINAC_ASSERT(ex_to<numeric>(p.coeff).is_equal(*_num1_p)); // should be normalized
535                 return expair(ex_to<numeric>(p.rest).mul_dyn(ex_to<numeric>(c)),_ex1);
536         }
537
538         return expair(p.rest,ex_to<numeric>(p.coeff).mul_dyn(ex_to<numeric>(c)));
539 }
540         
541 ex add::recombine_pair_to_ex(const expair & p) const
542 {
543         if (ex_to<numeric>(p.coeff).is_equal(*_num1_p))
544                 return p.rest;
545         else
546                 return (new mul(p.rest,p.coeff))->setflag(status_flags::dynallocated);
547 }
548
549 ex add::expand(unsigned options) const
550 {
551         std::auto_ptr<epvector> vp = expandchildren(options);
552         if (vp.get() == 0) {
553                 // the terms have not changed, so it is safe to declare this expanded
554                 return (options == 0) ? setflag(status_flags::expanded) : *this;
555         }
556
557         return (new add(vp, overall_coeff))->setflag(status_flags::dynallocated | (options == 0 ? status_flags::expanded : 0));
558 }
559
560 } // namespace GiNaC