62c02d2432aaeface643b1b4330ae564acf2a3fd
[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-2015 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 "add.h"
24 #include "mul.h"
25 #include "archive.h"
26 #include "operators.h"
27 #include "matrix.h"
28 #include "utils.h"
29 #include "clifford.h"
30 #include "ncmul.h"
31 #include "compiler.h"
32
33 #include <iostream>
34 #include <limits>
35 #include <stdexcept>
36 #include <string>
37
38 namespace GiNaC {
39
40 GINAC_IMPLEMENT_REGISTERED_CLASS_OPT(add, expairseq,
41   print_func<print_context>(&add::do_print).
42   print_func<print_latex>(&add::do_print_latex).
43   print_func<print_csrc>(&add::do_print_csrc).
44   print_func<print_tree>(&add::do_print_tree).
45   print_func<print_python_repr>(&add::do_print_python_repr))
46
47 //////////
48 // default constructor
49 //////////
50
51 add::add()
52 {
53 }
54
55 //////////
56 // other constructors
57 //////////
58
59 // public
60
61 add::add(const ex & lh, const ex & rh)
62 {
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         overall_coeff = _ex0;
71         construct_from_exvector(v);
72         GINAC_ASSERT(is_canonical());
73 }
74
75 add::add(const epvector & v)
76 {
77         overall_coeff = _ex0;
78         construct_from_epvector(v);
79         GINAC_ASSERT(is_canonical());
80 }
81
82 add::add(const epvector & v, const ex & oc)
83 {
84         overall_coeff = oc;
85         construct_from_epvector(v);
86         GINAC_ASSERT(is_canonical());
87 }
88
89 add::add(epvector && vp)
90 {
91         overall_coeff = _ex0;
92         construct_from_epvector(std::move(vp));
93         GINAC_ASSERT(is_canonical());
94 }
95
96 add::add(epvector && vp, const ex & oc)
97 {
98         overall_coeff = oc;
99         construct_from_epvector(std::move(vp));
100         GINAC_ASSERT(is_canonical());
101 }
102
103 //////////
104 // archiving
105 //////////
106
107 GINAC_BIND_UNARCHIVER(add);
108
109 //////////
110 // functions overriding virtual functions from base classes
111 //////////
112
113 // public
114
115 void add::print_add(const print_context & c, const char *openbrace, const char *closebrace, const char *mul_sym, unsigned level) const
116 {
117         if (precedence() <= level)
118                 c.s << openbrace << '(';
119
120         numeric coeff;
121         bool first = true;
122
123         // First print the overall numeric coefficient, if present
124         if (!overall_coeff.is_zero()) {
125                 overall_coeff.print(c, 0);
126                 first = false;
127         }
128
129         // Then proceed with the remaining factors
130         for (auto & it : seq) {
131                 coeff = ex_to<numeric>(it.coeff);
132                 if (!first) {
133                         if (coeff.csgn() == -1) c.s << '-'; else c.s << '+';
134                 } else {
135                         if (coeff.csgn() == -1) c.s << '-';
136                         first = false;
137                 }
138                 if (!coeff.is_equal(*_num1_p) &&
139                     !coeff.is_equal(*_num_1_p)) {
140                         if (coeff.is_rational()) {
141                                 if (coeff.is_negative())
142                                         (-coeff).print(c);
143                                 else
144                                         coeff.print(c);
145                         } else {
146                                 if (coeff.csgn() == -1)
147                                         (-coeff).print(c, precedence());
148                                 else
149                                         coeff.print(c, precedence());
150                         }
151                         c.s << mul_sym;
152                 }
153                 it.rest.print(c, precedence());
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 "+" or "-"
176         char separator = ' ';
177         for (auto & it : seq) {
178                 
179                 // If the coefficient is negative, separator is "-"
180                 if (it.coeff.is_equal(_ex_1) ||
181                         ex_to<numeric>(it.coeff).numer().is_equal(*_num_1_p))
182                         separator = '-';
183                 c.s << separator;
184                 if (it.coeff.is_equal(_ex1) || it.coeff.is_equal(_ex_1)) {
185                         it.rest.print(c, precedence());
186                 } else if (ex_to<numeric>(it.coeff).numer().is_equal(*_num1_p) ||
187                                  ex_to<numeric>(it.coeff).numer().is_equal(*_num_1_p))
188                 {
189                         it.rest.print(c, precedence());
190                         c.s << '/';
191                         ex_to<numeric>(it.coeff).denom().print(c, precedence());
192                 } else {
193                         it.coeff.print(c, precedence());
194                         c.s << '*';
195                         it.rest.print(c, precedence());
196                 }
197                 
198                 separator = '+';
199         }
200         
201         if (!overall_coeff.is_zero()) {
202                 if (overall_coeff.info(info_flags::positive)
203                  || is_a<print_csrc_cl_N>(c) || !overall_coeff.info(info_flags::real))  // sign inside ctor argument
204                         c.s << '+';
205                 overall_coeff.print(c, precedence());
206         }
207                 
208         if (precedence() <= level)
209                 c.s << ")";
210 }
211
212 void add::do_print_python_repr(const print_python_repr & c, unsigned level) const
213 {
214         c.s << class_name() << '(';
215         op(0).print(c);
216         for (size_t i=1; i<nops(); ++i) {
217                 c.s << ',';
218                 op(i).print(c);
219         }
220         c.s << ')';
221 }
222
223 bool add::info(unsigned inf) const
224 {
225         switch (inf) {
226                 case info_flags::polynomial:
227                 case info_flags::integer_polynomial:
228                 case info_flags::cinteger_polynomial:
229                 case info_flags::rational_polynomial:
230                 case info_flags::real:
231                 case info_flags::rational:
232                 case info_flags::integer:
233                 case info_flags::crational:
234                 case info_flags::cinteger:
235                 case info_flags::positive:
236                 case info_flags::nonnegative:
237                 case info_flags::posint:
238                 case info_flags::nonnegint:
239                 case info_flags::even:
240                 case info_flags::crational_polynomial:
241                 case info_flags::rational_function: {
242                         for (auto & i : seq) {
243                                 if (!(recombine_pair_to_ex(i).info(inf)))
244                                         return false;
245                         }
246                         if (overall_coeff.is_zero() && (inf == info_flags::positive || inf == info_flags::posint))
247                                 return true;
248                         return overall_coeff.info(inf);
249                 }
250                 case info_flags::algebraic: {
251                         epvector::const_iterator i = seq.begin(), end = seq.end();
252                         while (i != end) {
253                                 if ((recombine_pair_to_ex(*i).info(inf)))
254                                         return true;
255                                 ++i;
256                         }
257                         return false;
258                 }
259         }
260         return inherited::info(inf);
261 }
262
263 bool add::is_polynomial(const ex & var) const
264 {
265         for (auto & i : seq) {
266                 if (!i.rest.is_polynomial(var)) {
267                         return false;
268                 }
269         }
270         return true;
271 }
272
273 int add::degree(const ex & s) const
274 {
275         int deg = std::numeric_limits<int>::min();
276         if (!overall_coeff.is_zero())
277                 deg = 0;
278         
279         // Find maximum of degrees of individual terms
280         for (auto & i : seq) {
281                 int cur_deg = i.rest.degree(s);
282                 if (cur_deg > deg)
283                         deg = cur_deg;
284         }
285         return deg;
286 }
287
288 int add::ldegree(const ex & s) const
289 {
290         int deg = std::numeric_limits<int>::max();
291         if (!overall_coeff.is_zero())
292                 deg = 0;
293         
294         // Find minimum of degrees of individual terms
295         for (auto & i : seq) {
296                 int cur_deg = i.rest.ldegree(s);
297                 if (cur_deg < deg)
298                         deg = cur_deg;
299         }
300         return deg;
301 }
302
303 ex add::coeff(const ex & s, int n) const
304 {
305         epvector coeffseq;
306         epvector coeffseq_cliff;
307         int rl = clifford_max_label(s);
308         bool do_clifford = (rl != -1);
309         bool nonscalar = false;
310
311         // Calculate sum of coefficients in each term
312         for (auto & i : seq) {
313                 ex restcoeff = i.rest.coeff(s, n);
314                 if (!restcoeff.is_zero()) {
315                         if (do_clifford) {
316                                 if (clifford_max_label(restcoeff) == -1) {
317                                         coeffseq_cliff.push_back(expair(ncmul(restcoeff, dirac_ONE(rl)), i.coeff));
318                                 } else {
319                                         coeffseq_cliff.push_back(expair(restcoeff, i.coeff));
320                                         nonscalar = true;
321                                 }
322                         }
323                         coeffseq.push_back(expair(restcoeff, i.coeff));
324                 }
325         }
326
327         return dynallocate<add>(nonscalar ? std::move(coeffseq_cliff) : std::move(coeffseq),
328                                 n==0 ? overall_coeff : _ex0);
329 }
330
331 /** Perform automatic term rewriting rules in this class.  In the following
332  *  x stands for a symbolic variables of type ex and c stands for such
333  *  an expression that contain a plain number.
334  *  - +(;c) -> c
335  *  - +(x;0) -> x
336  */
337 ex add::eval() const
338 {
339         if (flags & status_flags::evaluated) {
340                 GINAC_ASSERT(seq.size()>0);
341                 GINAC_ASSERT(seq.size()>1 || !overall_coeff.is_zero());
342                 return *this;
343         }
344
345         const epvector evaled = evalchildren();
346         if (unlikely(!evaled.empty())) {
347                 // start over evaluating a new object
348                 return dynallocate<add>(std::move(evaled), overall_coeff);
349         }
350
351 #ifdef DO_GINAC_ASSERT
352         for (auto & i : seq) {
353                 GINAC_ASSERT(!is_exactly_a<add>(i.rest));
354         }
355 #endif // def DO_GINAC_ASSERT
356
357         size_t 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
368         return this->hold();
369 }
370
371 ex add::evalm() const
372 {
373         // Evaluate children first and add up all matrices. Stop if there's one
374         // term that is not a matrix.
375         epvector s;
376         s.reserve(seq.size());
377
378         bool all_matrices = true;
379         bool first_term = true;
380         matrix sum;
381
382         for (auto & it : seq) {
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         }
394
395         if (all_matrices)
396                 return sum + overall_coeff;
397         else
398                 return dynallocate<add>(std::move(s), overall_coeff);
399 }
400
401 ex add::conjugate() const
402 {
403         std::unique_ptr<exvector> v(nullptr);
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.reset(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                 return add(std::move(*v));
421         }
422         return *this;
423 }
424
425 ex add::real_part() const
426 {
427         epvector v;
428         v.reserve(seq.size());
429         for (auto & it : seq)
430                 if (it.coeff.info(info_flags::real)) {
431                         ex rp = it.rest.real_part();
432                         if (!rp.is_zero())
433                                 v.push_back(expair(rp, it.coeff));
434                 } else {
435                         ex rp = recombine_pair_to_ex(it).real_part();
436                         if (!rp.is_zero())
437                                 v.push_back(split_ex_to_pair(rp));
438                 }
439         return dynallocate<add>(std::move(v), overall_coeff.real_part());
440 }
441
442 ex add::imag_part() const
443 {
444         epvector v;
445         v.reserve(seq.size());
446         for (auto & it : seq)
447                 if (it.coeff.info(info_flags::real)) {
448                         ex ip = it.rest.imag_part();
449                         if (!ip.is_zero())
450                                 v.push_back(expair(ip, it.coeff));
451                 } else {
452                         ex ip = recombine_pair_to_ex(it).imag_part();
453                         if (!ip.is_zero())
454                                 v.push_back(split_ex_to_pair(ip));
455                 }
456         return dynallocate<add>(std::move(v), overall_coeff.imag_part());
457 }
458
459 ex add::eval_ncmul(const exvector & v) const
460 {
461         if (seq.empty())
462                 return inherited::eval_ncmul(v);
463         else
464                 return seq.begin()->rest.eval_ncmul(v);
465 }    
466
467 // protected
468
469 /** Implementation of ex::diff() for a sum. It differentiates each term.
470  *  @see ex::diff */
471 ex add::derivative(const symbol & y) const
472 {
473         epvector s;
474         s.reserve(seq.size());
475         
476         // Only differentiate the "rest" parts of the expairs. This is faster
477         // than the default implementation in basic::derivative() although
478         // if performs the same function (differentiate each term).
479         for (auto & it : seq)
480                 s.push_back(expair(it.rest.diff(y), it.coeff));
481
482         return dynallocate<add>(std::move(s));
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 return_type_t add::return_type_tinfo() const
499 {
500         if (seq.empty())
501                 return make_return_type_t<add>();
502         else
503                 return seq.begin()->rest.return_type_tinfo();
504 }
505
506 // Note: do_index_renaming is ignored because it makes no sense for an add.
507 ex add::thisexpairseq(const epvector & v, const ex & oc, bool do_index_renaming) const
508 {
509         return dynallocate<add>(v, oc);
510 }
511
512 // Note: do_index_renaming is ignored because it makes no sense for an add.
513 ex add::thisexpairseq(epvector && vp, const ex & oc, bool do_index_renaming) const
514 {
515         return dynallocate<add>(std::move(vp), oc);
516 }
517
518 expair add::split_ex_to_pair(const ex & e) const
519 {
520         if (is_exactly_a<mul>(e)) {
521                 const mul &mulref(ex_to<mul>(e));
522                 const ex &numfactor = mulref.overall_coeff;
523                 if (numfactor.is_equal(_ex1))
524                         return expair(e, _ex1);
525                 mul & mulcopy = dynallocate<mul>(mulref);
526                 mulcopy.overall_coeff = _ex1;
527                 mulcopy.clearflag(status_flags::evaluated | status_flags::hash_calculated);
528                 return expair(mulcopy, numfactor);
529         }
530         return expair(e,_ex1);
531 }
532
533 expair add::combine_ex_with_coeff_to_pair(const ex & e,
534                                           const ex & c) const
535 {
536         GINAC_ASSERT(is_exactly_a<numeric>(c));
537         if (is_exactly_a<mul>(e)) {
538                 const mul &mulref(ex_to<mul>(e));
539                 const ex &numfactor = mulref.overall_coeff;
540                 if (likely(numfactor.is_equal(_ex1)))
541                         return expair(e, c);
542                 mul & mulcopy = dynallocate<mul>(mulref);
543                 mulcopy.overall_coeff = _ex1;
544                 mulcopy.clearflag(status_flags::evaluated | status_flags::hash_calculated);
545                 if (c.is_equal(_ex1))
546                         return expair(mulcopy, numfactor);
547                 else
548                         return expair(mulcopy, 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                 if (e.is_equal(_ex1))
553                         return expair(c, _ex1);
554                 return expair(ex_to<numeric>(e).mul_dyn(ex_to<numeric>(c)), _ex1);
555         }
556         return expair(e, c);
557 }
558
559 expair add::combine_pair_with_coeff_to_pair(const expair & p,
560                                             const ex & c) const
561 {
562         GINAC_ASSERT(is_exactly_a<numeric>(p.coeff));
563         GINAC_ASSERT(is_exactly_a<numeric>(c));
564
565         if (is_exactly_a<numeric>(p.rest)) {
566                 GINAC_ASSERT(ex_to<numeric>(p.coeff).is_equal(*_num1_p)); // should be normalized
567                 return expair(ex_to<numeric>(p.rest).mul_dyn(ex_to<numeric>(c)),_ex1);
568         }
569
570         return expair(p.rest,ex_to<numeric>(p.coeff).mul_dyn(ex_to<numeric>(c)));
571 }
572
573 ex add::recombine_pair_to_ex(const expair & p) const
574 {
575         if (ex_to<numeric>(p.coeff).is_equal(*_num1_p))
576                 return p.rest;
577         else
578                 return dynallocate<mul>(p.rest, p.coeff);
579 }
580
581 ex add::expand(unsigned options) const
582 {
583         epvector expanded = expandchildren(options);
584         if (expanded.empty())
585                 return (options == 0) ? setflag(status_flags::expanded) : *this;
586
587         return dynallocate<add>(std::move(expanded), overall_coeff).setflag(options == 0 ? status_flags::expanded : 0);
588 }
589
590 } // namespace GiNaC