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