Univariate Hensel lifting now uses upoly.
[ginac.git] / ginac / power.cpp
1 /** @file power.cpp
2  *
3  *  Implementation of GiNaC's symbolic exponentiation (basis^exponent). */
4
5 /*
6  *  GiNaC Copyright (C) 1999-2008 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 <vector>
24 #include <iostream>
25 #include <stdexcept>
26 #include <limits>
27
28 #include "power.h"
29 #include "expairseq.h"
30 #include "add.h"
31 #include "mul.h"
32 #include "ncmul.h"
33 #include "numeric.h"
34 #include "constant.h"
35 #include "operators.h"
36 #include "inifcns.h" // for log() in power::derivative()
37 #include "matrix.h"
38 #include "indexed.h"
39 #include "symbol.h"
40 #include "lst.h"
41 #include "archive.h"
42 #include "utils.h"
43 #include "relational.h"
44 #include "compiler.h"
45
46 namespace GiNaC {
47
48 GINAC_IMPLEMENT_REGISTERED_CLASS_OPT(power, basic,
49   print_func<print_dflt>(&power::do_print_dflt).
50   print_func<print_latex>(&power::do_print_latex).
51   print_func<print_csrc>(&power::do_print_csrc).
52   print_func<print_python>(&power::do_print_python).
53   print_func<print_python_repr>(&power::do_print_python_repr).
54   print_func<print_csrc_cl_N>(&power::do_print_csrc_cl_N))
55
56 typedef std::vector<int> intvector;
57
58 //////////
59 // default constructor
60 //////////
61
62 power::power() { }
63
64 //////////
65 // other constructors
66 //////////
67
68 // all inlined
69
70 //////////
71 // archiving
72 //////////
73
74 void power::read_archive(const archive_node &n, lst &sym_lst)
75 {
76         inherited::read_archive(n, sym_lst);
77         n.find_ex("basis", basis, sym_lst);
78         n.find_ex("exponent", exponent, sym_lst);
79 }
80
81 void power::archive(archive_node &n) const
82 {
83         inherited::archive(n);
84         n.add_ex("basis", basis);
85         n.add_ex("exponent", exponent);
86 }
87
88 //////////
89 // functions overriding virtual functions from base classes
90 //////////
91
92 // public
93
94 void power::print_power(const print_context & c, const char *powersymbol, const char *openbrace, const char *closebrace, unsigned level) const
95 {
96         // Ordinary output of powers using '^' or '**'
97         if (precedence() <= level)
98                 c.s << openbrace << '(';
99         basis.print(c, precedence());
100         c.s << powersymbol;
101         c.s << openbrace;
102         exponent.print(c, precedence());
103         c.s << closebrace;
104         if (precedence() <= level)
105                 c.s << ')' << closebrace;
106 }
107
108 void power::do_print_dflt(const print_dflt & c, unsigned level) const
109 {
110         if (exponent.is_equal(_ex1_2)) {
111
112                 // Square roots are printed in a special way
113                 c.s << "sqrt(";
114                 basis.print(c);
115                 c.s << ')';
116
117         } else
118                 print_power(c, "^", "", "", level);
119 }
120
121 void power::do_print_latex(const print_latex & c, unsigned level) const
122 {
123         if (is_exactly_a<numeric>(exponent) && ex_to<numeric>(exponent).is_negative()) {
124
125                 // Powers with negative numeric exponents are printed as fractions
126                 c.s << "\\frac{1}{";
127                 power(basis, -exponent).eval().print(c);
128                 c.s << '}';
129
130         } else if (exponent.is_equal(_ex1_2)) {
131
132                 // Square roots are printed in a special way
133                 c.s << "\\sqrt{";
134                 basis.print(c);
135                 c.s << '}';
136
137         } else
138                 print_power(c, "^", "{", "}", level);
139 }
140
141 static void print_sym_pow(const print_context & c, const symbol &x, int exp)
142 {
143         // Optimal output of integer powers of symbols to aid compiler CSE.
144         // C.f. ISO/IEC 14882:1998, section 1.9 [intro execution], paragraph 15
145         // to learn why such a parenthesation is really necessary.
146         if (exp == 1) {
147                 x.print(c);
148         } else if (exp == 2) {
149                 x.print(c);
150                 c.s << "*";
151                 x.print(c);
152         } else if (exp & 1) {
153                 x.print(c);
154                 c.s << "*";
155                 print_sym_pow(c, x, exp-1);
156         } else {
157                 c.s << "(";
158                 print_sym_pow(c, x, exp >> 1);
159                 c.s << ")*(";
160                 print_sym_pow(c, x, exp >> 1);
161                 c.s << ")";
162         }
163 }
164
165 void power::do_print_csrc_cl_N(const print_csrc_cl_N& c, unsigned level) const
166 {
167         if (exponent.is_equal(_ex_1)) {
168                 c.s << "recip(";
169                 basis.print(c);
170                 c.s << ')';
171                 return;
172         }
173         c.s << "expt(";
174         basis.print(c);
175         c.s << ", ";
176         exponent.print(c);
177         c.s << ')';
178 }
179
180 void power::do_print_csrc(const print_csrc & c, unsigned level) const
181 {
182         // Integer powers of symbols are printed in a special, optimized way
183         if (exponent.info(info_flags::integer)
184          && (is_a<symbol>(basis) || is_a<constant>(basis))) {
185                 int exp = ex_to<numeric>(exponent).to_int();
186                 if (exp > 0)
187                         c.s << '(';
188                 else {
189                         exp = -exp;
190                         c.s << "1.0/(";
191                 }
192                 print_sym_pow(c, ex_to<symbol>(basis), exp);
193                 c.s << ')';
194
195         // <expr>^-1 is printed as "1.0/<expr>" or with the recip() function of CLN
196         } else if (exponent.is_equal(_ex_1)) {
197                 c.s << "1.0/(";
198                 basis.print(c);
199                 c.s << ')';
200
201         // Otherwise, use the pow() function
202         } else {
203                 c.s << "pow(";
204                 basis.print(c);
205                 c.s << ',';
206                 exponent.print(c);
207                 c.s << ')';
208         }
209 }
210
211 void power::do_print_python(const print_python & c, unsigned level) const
212 {
213         print_power(c, "**", "", "", level);
214 }
215
216 void power::do_print_python_repr(const print_python_repr & c, unsigned level) const
217 {
218         c.s << class_name() << '(';
219         basis.print(c);
220         c.s << ',';
221         exponent.print(c);
222         c.s << ')';
223 }
224
225 bool power::info(unsigned inf) const
226 {
227         switch (inf) {
228                 case info_flags::polynomial:
229                 case info_flags::integer_polynomial:
230                 case info_flags::cinteger_polynomial:
231                 case info_flags::rational_polynomial:
232                 case info_flags::crational_polynomial:
233                         return exponent.info(info_flags::nonnegint) &&
234                                basis.info(inf);
235                 case info_flags::rational_function:
236                         return exponent.info(info_flags::integer) &&
237                                basis.info(inf);
238                 case info_flags::algebraic:
239                         return !exponent.info(info_flags::integer) ||
240                                basis.info(inf);
241                 case info_flags::expanded:
242                         return (flags & status_flags::expanded);
243                 case info_flags::has_indices: {
244                         if (flags & status_flags::has_indices)
245                                 return true;
246                         else if (flags & status_flags::has_no_indices)
247                                 return false;
248                         else if (basis.info(info_flags::has_indices)) {
249                                 setflag(status_flags::has_indices);
250                                 clearflag(status_flags::has_no_indices);
251                                 return true;
252                         } else {
253                                 clearflag(status_flags::has_indices);
254                                 setflag(status_flags::has_no_indices);
255                                 return false;
256                         }
257                 }
258         }
259         return inherited::info(inf);
260 }
261
262 size_t power::nops() const
263 {
264         return 2;
265 }
266
267 ex power::op(size_t i) const
268 {
269         GINAC_ASSERT(i<2);
270
271         return i==0 ? basis : exponent;
272 }
273
274 ex power::map(map_function & f) const
275 {
276         const ex &mapped_basis = f(basis);
277         const ex &mapped_exponent = f(exponent);
278
279         if (!are_ex_trivially_equal(basis, mapped_basis)
280          || !are_ex_trivially_equal(exponent, mapped_exponent))
281                 return (new power(mapped_basis, mapped_exponent))->setflag(status_flags::dynallocated);
282         else
283                 return *this;
284 }
285
286 bool power::is_polynomial(const ex & var) const
287 {
288         if (exponent.has(var))
289                 return false;
290         if (!exponent.info(info_flags::nonnegint))
291                 return false;
292         return basis.is_polynomial(var);
293 }
294
295 int power::degree(const ex & s) const
296 {
297         if (is_equal(ex_to<basic>(s)))
298                 return 1;
299         else if (is_exactly_a<numeric>(exponent) && ex_to<numeric>(exponent).is_integer()) {
300                 if (basis.is_equal(s))
301                         return ex_to<numeric>(exponent).to_int();
302                 else
303                         return basis.degree(s) * ex_to<numeric>(exponent).to_int();
304         } else if (basis.has(s))
305                 throw(std::runtime_error("power::degree(): undefined degree because of non-integer exponent"));
306         else
307                 return 0;
308 }
309
310 int power::ldegree(const ex & s) const 
311 {
312         if (is_equal(ex_to<basic>(s)))
313                 return 1;
314         else if (is_exactly_a<numeric>(exponent) && ex_to<numeric>(exponent).is_integer()) {
315                 if (basis.is_equal(s))
316                         return ex_to<numeric>(exponent).to_int();
317                 else
318                         return basis.ldegree(s) * ex_to<numeric>(exponent).to_int();
319         } else if (basis.has(s))
320                 throw(std::runtime_error("power::ldegree(): undefined degree because of non-integer exponent"));
321         else
322                 return 0;
323 }
324
325 ex power::coeff(const ex & s, int n) const
326 {
327         if (is_equal(ex_to<basic>(s)))
328                 return n==1 ? _ex1 : _ex0;
329         else if (!basis.is_equal(s)) {
330                 // basis not equal to s
331                 if (n == 0)
332                         return *this;
333                 else
334                         return _ex0;
335         } else {
336                 // basis equal to s
337                 if (is_exactly_a<numeric>(exponent) && ex_to<numeric>(exponent).is_integer()) {
338                         // integer exponent
339                         int int_exp = ex_to<numeric>(exponent).to_int();
340                         if (n == int_exp)
341                                 return _ex1;
342                         else
343                                 return _ex0;
344                 } else {
345                         // non-integer exponents are treated as zero
346                         if (n == 0)
347                                 return *this;
348                         else
349                                 return _ex0;
350                 }
351         }
352 }
353
354 /** Perform automatic term rewriting rules in this class.  In the following
355  *  x, x1, x2,... stand for a symbolic variables of type ex and c, c1, c2...
356  *  stand for such expressions that contain a plain number.
357  *  - ^(x,0) -> 1  (also handles ^(0,0))
358  *  - ^(x,1) -> x
359  *  - ^(0,c) -> 0 or exception  (depending on the real part of c)
360  *  - ^(1,x) -> 1
361  *  - ^(c1,c2) -> *(c1^n,c1^(c2-n))  (so that 0<(c2-n)<1, try to evaluate roots, possibly in numerator and denominator of c1)
362  *  - ^(^(x,c1),c2) -> ^(x,c1*c2)  if x is positive and c1 is real.
363  *  - ^(^(x,c1),c2) -> ^(x,c1*c2)  (c2 integer or -1 < c1 <= 1, case c1=1 should not happen, see below!)
364  *  - ^(*(x,y,z),c) -> *(x^c,y^c,z^c)  (if c integer)
365  *  - ^(*(x,c1),c2) -> ^(x,c2)*c1^c2  (c1>0)
366  *  - ^(*(x,c1),c2) -> ^(-x,c2)*c1^c2  (c1<0)
367  *
368  *  @param level cut-off in recursive evaluation */
369 ex power::eval(int level) const
370 {
371         if ((level==1) && (flags & status_flags::evaluated))
372                 return *this;
373         else if (level == -max_recursion_level)
374                 throw(std::runtime_error("max recursion level reached"));
375         
376         const ex & ebasis    = level==1 ? basis    : basis.eval(level-1);
377         const ex & eexponent = level==1 ? exponent : exponent.eval(level-1);
378         
379         bool basis_is_numerical = false;
380         bool exponent_is_numerical = false;
381         const numeric *num_basis;
382         const numeric *num_exponent;
383         
384         if (is_exactly_a<numeric>(ebasis)) {
385                 basis_is_numerical = true;
386                 num_basis = &ex_to<numeric>(ebasis);
387         }
388         if (is_exactly_a<numeric>(eexponent)) {
389                 exponent_is_numerical = true;
390                 num_exponent = &ex_to<numeric>(eexponent);
391         }
392         
393         // ^(x,0) -> 1  (0^0 also handled here)
394         if (eexponent.is_zero()) {
395                 if (ebasis.is_zero())
396                         throw (std::domain_error("power::eval(): pow(0,0) is undefined"));
397                 else
398                         return _ex1;
399         }
400         
401         // ^(x,1) -> x
402         if (eexponent.is_equal(_ex1))
403                 return ebasis;
404
405         // ^(0,c1) -> 0 or exception  (depending on real value of c1)
406         if (ebasis.is_zero() && exponent_is_numerical) {
407                 if ((num_exponent->real()).is_zero())
408                         throw (std::domain_error("power::eval(): pow(0,I) is undefined"));
409                 else if ((num_exponent->real()).is_negative())
410                         throw (pole_error("power::eval(): division by zero",1));
411                 else
412                         return _ex0;
413         }
414
415         // ^(1,x) -> 1
416         if (ebasis.is_equal(_ex1))
417                 return _ex1;
418
419         // power of a function calculated by separate rules defined for this function
420         if (is_exactly_a<function>(ebasis))
421                 return ex_to<function>(ebasis).power(eexponent);
422
423         // Turn (x^c)^d into x^(c*d) in the case that x is positive and c is real.
424         if (is_exactly_a<power>(ebasis) && ebasis.op(0).info(info_flags::positive) && ebasis.op(1).info(info_flags::real))
425                 return power(ebasis.op(0), ebasis.op(1) * eexponent);
426
427         if (exponent_is_numerical) {
428
429                 // ^(c1,c2) -> c1^c2  (c1, c2 numeric(),
430                 // except if c1,c2 are rational, but c1^c2 is not)
431                 if (basis_is_numerical) {
432                         const bool basis_is_crational = num_basis->is_crational();
433                         const bool exponent_is_crational = num_exponent->is_crational();
434                         if (!basis_is_crational || !exponent_is_crational) {
435                                 // return a plain float
436                                 return (new numeric(num_basis->power(*num_exponent)))->setflag(status_flags::dynallocated |
437                                                                                                status_flags::evaluated |
438                                                                                                status_flags::expanded);
439                         }
440
441                         const numeric res = num_basis->power(*num_exponent);
442                         if (res.is_crational()) {
443                                 return res;
444                         }
445                         GINAC_ASSERT(!num_exponent->is_integer());  // has been handled by now
446
447                         // ^(c1,n/m) -> *(c1^q,c1^(n/m-q)), 0<(n/m-q)<1, q integer
448                         if (basis_is_crational && exponent_is_crational
449                             && num_exponent->is_real()
450                             && !num_exponent->is_integer()) {
451                                 const numeric n = num_exponent->numer();
452                                 const numeric m = num_exponent->denom();
453                                 numeric r;
454                                 numeric q = iquo(n, m, r);
455                                 if (r.is_negative()) {
456                                         r += m;
457                                         --q;
458                                 }
459                                 if (q.is_zero()) {  // the exponent was in the allowed range 0<(n/m)<1
460                                         if (num_basis->is_rational() && !num_basis->is_integer()) {
461                                                 // try it for numerator and denominator separately, in order to
462                                                 // partially simplify things like (5/8)^(1/3) -> 1/2*5^(1/3)
463                                                 const numeric bnum = num_basis->numer();
464                                                 const numeric bden = num_basis->denom();
465                                                 const numeric res_bnum = bnum.power(*num_exponent);
466                                                 const numeric res_bden = bden.power(*num_exponent);
467                                                 if (res_bnum.is_integer())
468                                                         return (new mul(power(bden,-*num_exponent),res_bnum))->setflag(status_flags::dynallocated | status_flags::evaluated);
469                                                 if (res_bden.is_integer())
470                                                         return (new mul(power(bnum,*num_exponent),res_bden.inverse()))->setflag(status_flags::dynallocated | status_flags::evaluated);
471                                         }
472                                         return this->hold();
473                                 } else {
474                                         // assemble resulting product, but allowing for a re-evaluation,
475                                         // because otherwise we'll end up with something like
476                                         //    (7/8)^(4/3)  ->  7/8*(1/2*7^(1/3))
477                                         // instead of 7/16*7^(1/3).
478                                         ex prod = power(*num_basis,r.div(m));
479                                         return prod*power(*num_basis,q);
480                                 }
481                         }
482                 }
483         
484                 // ^(^(x,c1),c2) -> ^(x,c1*c2)
485                 // (c1, c2 numeric(), c2 integer or -1 < c1 <= 1,
486                 // case c1==1 should not happen, see below!)
487                 if (is_exactly_a<power>(ebasis)) {
488                         const power & sub_power = ex_to<power>(ebasis);
489                         const ex & sub_basis = sub_power.basis;
490                         const ex & sub_exponent = sub_power.exponent;
491                         if (is_exactly_a<numeric>(sub_exponent)) {
492                                 const numeric & num_sub_exponent = ex_to<numeric>(sub_exponent);
493                                 GINAC_ASSERT(num_sub_exponent!=numeric(1));
494                                 if (num_exponent->is_integer() || (abs(num_sub_exponent) - (*_num1_p)).is_negative()) {
495                                         return power(sub_basis,num_sub_exponent.mul(*num_exponent));
496                                 }
497                         }
498                 }
499         
500                 // ^(*(x,y,z),c1) -> *(x^c1,y^c1,z^c1) (c1 integer)
501                 if (num_exponent->is_integer() && is_exactly_a<mul>(ebasis)) {
502                         return expand_mul(ex_to<mul>(ebasis), *num_exponent, 0);
503                 }
504
505                 // (2*x + 6*y)^(-4) -> 1/16*(x + 3*y)^(-4)
506                 if (num_exponent->is_integer() && is_exactly_a<add>(ebasis)) {
507                         numeric icont = ebasis.integer_content();
508                         const numeric lead_coeff = 
509                                 ex_to<numeric>(ex_to<add>(ebasis).seq.begin()->coeff).div(icont);
510
511                         const bool canonicalizable = lead_coeff.is_integer();
512                         const bool unit_normal = lead_coeff.is_pos_integer();
513                         if (canonicalizable && (! unit_normal))
514                                 icont = icont.mul(*_num_1_p);
515                         
516                         if (canonicalizable && (icont != *_num1_p)) {
517                                 const add& addref = ex_to<add>(ebasis);
518                                 add* addp = new add(addref);
519                                 addp->setflag(status_flags::dynallocated);
520                                 addp->clearflag(status_flags::hash_calculated);
521                                 addp->overall_coeff = ex_to<numeric>(addp->overall_coeff).div_dyn(icont);
522                                 for (epvector::iterator i = addp->seq.begin(); i != addp->seq.end(); ++i)
523                                         i->coeff = ex_to<numeric>(i->coeff).div_dyn(icont);
524
525                                 const numeric c = icont.power(*num_exponent);
526                                 if (likely(c != *_num1_p))
527                                         return (new mul(power(*addp, *num_exponent), c))->setflag(status_flags::dynallocated);
528                                 else
529                                         return power(*addp, *num_exponent);
530                         }
531                 }
532
533                 // ^(*(...,x;c1),c2) -> *(^(*(...,x;1),c2),c1^c2)  (c1, c2 numeric(), c1>0)
534                 // ^(*(...,x;c1),c2) -> *(^(*(...,x;-1),c2),(-c1)^c2)  (c1, c2 numeric(), c1<0)
535                 if (is_exactly_a<mul>(ebasis)) {
536                         GINAC_ASSERT(!num_exponent->is_integer()); // should have been handled above
537                         const mul & mulref = ex_to<mul>(ebasis);
538                         if (!mulref.overall_coeff.is_equal(_ex1)) {
539                                 const numeric & num_coeff = ex_to<numeric>(mulref.overall_coeff);
540                                 if (num_coeff.is_real()) {
541                                         if (num_coeff.is_positive()) {
542                                                 mul *mulp = new mul(mulref);
543                                                 mulp->overall_coeff = _ex1;
544                                                 mulp->clearflag(status_flags::evaluated);
545                                                 mulp->clearflag(status_flags::hash_calculated);
546                                                 return (new mul(power(*mulp,exponent),
547                                                                 power(num_coeff,*num_exponent)))->setflag(status_flags::dynallocated);
548                                         } else {
549                                                 GINAC_ASSERT(num_coeff.compare(*_num0_p)<0);
550                                                 if (!num_coeff.is_equal(*_num_1_p)) {
551                                                         mul *mulp = new mul(mulref);
552                                                         mulp->overall_coeff = _ex_1;
553                                                         mulp->clearflag(status_flags::evaluated);
554                                                         mulp->clearflag(status_flags::hash_calculated);
555                                                         return (new mul(power(*mulp,exponent),
556                                                                         power(abs(num_coeff),*num_exponent)))->setflag(status_flags::dynallocated);
557                                                 }
558                                         }
559                                 }
560                         }
561                 }
562
563                 // ^(nc,c1) -> ncmul(nc,nc,...) (c1 positive integer, unless nc is a matrix)
564                 if (num_exponent->is_pos_integer() &&
565                     ebasis.return_type() != return_types::commutative &&
566                     !is_a<matrix>(ebasis)) {
567                         return ncmul(exvector(num_exponent->to_int(), ebasis), true);
568                 }
569         }
570         
571         if (are_ex_trivially_equal(ebasis,basis) &&
572             are_ex_trivially_equal(eexponent,exponent)) {
573                 return this->hold();
574         }
575         return (new power(ebasis, eexponent))->setflag(status_flags::dynallocated |
576                                                        status_flags::evaluated);
577 }
578
579 ex power::evalf(int level) const
580 {
581         ex ebasis;
582         ex eexponent;
583         
584         if (level==1) {
585                 ebasis = basis;
586                 eexponent = exponent;
587         } else if (level == -max_recursion_level) {
588                 throw(std::runtime_error("max recursion level reached"));
589         } else {
590                 ebasis = basis.evalf(level-1);
591                 if (!is_exactly_a<numeric>(exponent))
592                         eexponent = exponent.evalf(level-1);
593                 else
594                         eexponent = exponent;
595         }
596
597         return power(ebasis,eexponent);
598 }
599
600 ex power::evalm() const
601 {
602         const ex ebasis = basis.evalm();
603         const ex eexponent = exponent.evalm();
604         if (is_a<matrix>(ebasis)) {
605                 if (is_exactly_a<numeric>(eexponent)) {
606                         return (new matrix(ex_to<matrix>(ebasis).pow(eexponent)))->setflag(status_flags::dynallocated);
607                 }
608         }
609         return (new power(ebasis, eexponent))->setflag(status_flags::dynallocated);
610 }
611
612 bool power::has(const ex & other, unsigned options) const
613 {
614         if (!(options & has_options::algebraic))
615                 return basic::has(other, options);
616         if (!is_a<power>(other))
617                 return basic::has(other, options);
618         if (!exponent.info(info_flags::integer)
619                         || !other.op(1).info(info_flags::integer))
620                 return basic::has(other, options);
621         if (exponent.info(info_flags::posint)
622                         && other.op(1).info(info_flags::posint)
623                         && ex_to<numeric>(exponent).to_int()
624                                         > ex_to<numeric>(other.op(1)).to_int()
625                         && basis.match(other.op(0)))
626                 return true;
627         if (exponent.info(info_flags::negint)
628                         && other.op(1).info(info_flags::negint)
629                         && ex_to<numeric>(exponent).to_int()
630                                         < ex_to<numeric>(other.op(1)).to_int()
631                         && basis.match(other.op(0)))
632                 return true;
633         return basic::has(other, options);
634 }
635
636 // from mul.cpp
637 extern bool tryfactsubs(const ex &, const ex &, int &, exmap&);
638
639 ex power::subs(const exmap & m, unsigned options) const
640 {       
641         const ex &subsed_basis = basis.subs(m, options);
642         const ex &subsed_exponent = exponent.subs(m, options);
643
644         if (!are_ex_trivially_equal(basis, subsed_basis)
645          || !are_ex_trivially_equal(exponent, subsed_exponent)) 
646                 return power(subsed_basis, subsed_exponent).subs_one_level(m, options);
647
648         if (!(options & subs_options::algebraic))
649                 return subs_one_level(m, options);
650
651         for (exmap::const_iterator it = m.begin(); it != m.end(); ++it) {
652                 int nummatches = std::numeric_limits<int>::max();
653                 exmap repls;
654                 if (tryfactsubs(*this, it->first, nummatches, repls)) {
655                         ex anum = it->second.subs(repls, subs_options::no_pattern);
656                         ex aden = it->first.subs(repls, subs_options::no_pattern);
657                         ex result = (*this)*power(anum/aden, nummatches);
658                         return (ex_to<basic>(result)).subs_one_level(m, options);
659                 }
660         }
661
662         return subs_one_level(m, options);
663 }
664
665 ex power::eval_ncmul(const exvector & v) const
666 {
667         return inherited::eval_ncmul(v);
668 }
669
670 ex power::conjugate() const
671 {
672         ex newbasis = basis.conjugate();
673         ex newexponent = exponent.conjugate();
674         if (are_ex_trivially_equal(basis, newbasis) && are_ex_trivially_equal(exponent, newexponent)) {
675                 return *this;
676         }
677         return (new power(newbasis, newexponent))->setflag(status_flags::dynallocated);
678 }
679
680 ex power::real_part() const
681 {
682         if (exponent.info(info_flags::integer)) {
683                 ex basis_real = basis.real_part();
684                 if (basis_real == basis)
685                         return *this;
686                 realsymbol a("a"),b("b");
687                 ex result;
688                 if (exponent.info(info_flags::posint))
689                         result = power(a+I*b,exponent);
690                 else
691                         result = power(a/(a*a+b*b)-I*b/(a*a+b*b),-exponent);
692                 result = result.expand();
693                 result = result.real_part();
694                 result = result.subs(lst( a==basis_real, b==basis.imag_part() ));
695                 return result;
696         }
697         
698         ex a = basis.real_part();
699         ex b = basis.imag_part();
700         ex c = exponent.real_part();
701         ex d = exponent.imag_part();
702         return power(abs(basis),c)*exp(-d*atan2(b,a))*cos(c*atan2(b,a)+d*log(abs(basis)));
703 }
704
705 ex power::imag_part() const
706 {
707         if (exponent.info(info_flags::integer)) {
708                 ex basis_real = basis.real_part();
709                 if (basis_real == basis)
710                         return 0;
711                 realsymbol a("a"),b("b");
712                 ex result;
713                 if (exponent.info(info_flags::posint))
714                         result = power(a+I*b,exponent);
715                 else
716                         result = power(a/(a*a+b*b)-I*b/(a*a+b*b),-exponent);
717                 result = result.expand();
718                 result = result.imag_part();
719                 result = result.subs(lst( a==basis_real, b==basis.imag_part() ));
720                 return result;
721         }
722         
723         ex a=basis.real_part();
724         ex b=basis.imag_part();
725         ex c=exponent.real_part();
726         ex d=exponent.imag_part();
727         return
728                 power(abs(basis),c)*exp(-d*atan2(b,a))*sin(c*atan2(b,a)+d*log(abs(basis)));
729 }
730
731 // protected
732
733 // protected
734
735 /** Implementation of ex::diff() for a power.
736  *  @see ex::diff */
737 ex power::derivative(const symbol & s) const
738 {
739         if (is_a<numeric>(exponent)) {
740                 // D(b^r) = r * b^(r-1) * D(b) (faster than the formula below)
741                 epvector newseq;
742                 newseq.reserve(2);
743                 newseq.push_back(expair(basis, exponent - _ex1));
744                 newseq.push_back(expair(basis.diff(s), _ex1));
745                 return mul(newseq, exponent);
746         } else {
747                 // D(b^e) = b^e * (D(e)*ln(b) + e*D(b)/b)
748                 return mul(*this,
749                            add(mul(exponent.diff(s), log(basis)),
750                            mul(mul(exponent, basis.diff(s)), power(basis, _ex_1))));
751         }
752 }
753
754 int power::compare_same_type(const basic & other) const
755 {
756         GINAC_ASSERT(is_exactly_a<power>(other));
757         const power &o = static_cast<const power &>(other);
758
759         int cmpval = basis.compare(o.basis);
760         if (cmpval)
761                 return cmpval;
762         else
763                 return exponent.compare(o.exponent);
764 }
765
766 unsigned power::return_type() const
767 {
768         return basis.return_type();
769 }
770
771 return_type_t power::return_type_tinfo() const
772 {
773         return basis.return_type_tinfo();
774 }
775
776 ex power::expand(unsigned options) const
777 {
778         if (is_a<symbol>(basis) && exponent.info(info_flags::integer)) {
779                 // A special case worth optimizing.
780                 setflag(status_flags::expanded);
781                 return *this;
782         }
783
784         const ex expanded_basis = basis.expand(options);
785         const ex expanded_exponent = exponent.expand(options);
786         
787         // x^(a+b) -> x^a * x^b
788         if (is_exactly_a<add>(expanded_exponent)) {
789                 const add &a = ex_to<add>(expanded_exponent);
790                 exvector distrseq;
791                 distrseq.reserve(a.seq.size() + 1);
792                 epvector::const_iterator last = a.seq.end();
793                 epvector::const_iterator cit = a.seq.begin();
794                 while (cit!=last) {
795                         distrseq.push_back(power(expanded_basis, a.recombine_pair_to_ex(*cit)));
796                         ++cit;
797                 }
798                 
799                 // Make sure that e.g. (x+y)^(2+a) expands the (x+y)^2 factor
800                 if (ex_to<numeric>(a.overall_coeff).is_integer()) {
801                         const numeric &num_exponent = ex_to<numeric>(a.overall_coeff);
802                         int int_exponent = num_exponent.to_int();
803                         if (int_exponent > 0 && is_exactly_a<add>(expanded_basis))
804                                 distrseq.push_back(expand_add(ex_to<add>(expanded_basis), int_exponent, options));
805                         else
806                                 distrseq.push_back(power(expanded_basis, a.overall_coeff));
807                 } else
808                         distrseq.push_back(power(expanded_basis, a.overall_coeff));
809                 
810                 // Make sure that e.g. (x+y)^(1+a) -> x*(x+y)^a + y*(x+y)^a
811                 ex r = (new mul(distrseq))->setflag(status_flags::dynallocated);
812                 return r.expand(options);
813         }
814         
815         if (!is_exactly_a<numeric>(expanded_exponent) ||
816                 !ex_to<numeric>(expanded_exponent).is_integer()) {
817                 if (are_ex_trivially_equal(basis,expanded_basis) && are_ex_trivially_equal(exponent,expanded_exponent)) {
818                         return this->hold();
819                 } else {
820                         return (new power(expanded_basis,expanded_exponent))->setflag(status_flags::dynallocated | (options == 0 ? status_flags::expanded : 0));
821                 }
822         }
823         
824         // integer numeric exponent
825         const numeric & num_exponent = ex_to<numeric>(expanded_exponent);
826         int int_exponent = num_exponent.to_int();
827         
828         // (x+y)^n, n>0
829         if (int_exponent > 0 && is_exactly_a<add>(expanded_basis))
830                 return expand_add(ex_to<add>(expanded_basis), int_exponent, options);
831         
832         // (x*y)^n -> x^n * y^n
833         if (is_exactly_a<mul>(expanded_basis))
834                 return expand_mul(ex_to<mul>(expanded_basis), num_exponent, options, true);
835         
836         // cannot expand further
837         if (are_ex_trivially_equal(basis,expanded_basis) && are_ex_trivially_equal(exponent,expanded_exponent))
838                 return this->hold();
839         else
840                 return (new power(expanded_basis,expanded_exponent))->setflag(status_flags::dynallocated | (options == 0 ? status_flags::expanded : 0));
841 }
842
843 //////////
844 // new virtual functions which can be overridden by derived classes
845 //////////
846
847 // none
848
849 //////////
850 // non-virtual functions in this class
851 //////////
852
853 /** expand a^n where a is an add and n is a positive integer.
854  *  @see power::expand */
855 ex power::expand_add(const add & a, int n, unsigned options) const
856 {
857         if (n==2)
858                 return expand_add_2(a, options);
859
860         const size_t m = a.nops();
861         exvector result;
862         // The number of terms will be the number of combinatorial compositions,
863         // i.e. the number of unordered arrangements of m nonnegative integers
864         // which sum up to n.  It is frequently written as C_n(m) and directly
865         // related with binomial coefficients:
866         result.reserve(binomial(numeric(n+m-1), numeric(m-1)).to_int());
867         intvector k(m-1);
868         intvector k_cum(m-1); // k_cum[l]:=sum(i=0,l,k[l]);
869         intvector upper_limit(m-1);
870
871         for (size_t l=0; l<m-1; ++l) {
872                 k[l] = 0;
873                 k_cum[l] = 0;
874                 upper_limit[l] = n;
875         }
876
877         while (true) {
878                 exvector term;
879                 term.reserve(m+1);
880                 for (std::size_t l = 0; l < m - 1; ++l) {
881                         const ex & b = a.op(l);
882                         GINAC_ASSERT(!is_exactly_a<add>(b));
883                         GINAC_ASSERT(!is_exactly_a<power>(b) ||
884                                      !is_exactly_a<numeric>(ex_to<power>(b).exponent) ||
885                                      !ex_to<numeric>(ex_to<power>(b).exponent).is_pos_integer() ||
886                                      !is_exactly_a<add>(ex_to<power>(b).basis) ||
887                                      !is_exactly_a<mul>(ex_to<power>(b).basis) ||
888                                      !is_exactly_a<power>(ex_to<power>(b).basis));
889                         if (is_exactly_a<mul>(b))
890                                 term.push_back(expand_mul(ex_to<mul>(b), numeric(k[l]), options, true));
891                         else
892                                 term.push_back(power(b,k[l]));
893                 }
894
895                 const ex & b = a.op(m - 1);
896                 GINAC_ASSERT(!is_exactly_a<add>(b));
897                 GINAC_ASSERT(!is_exactly_a<power>(b) ||
898                              !is_exactly_a<numeric>(ex_to<power>(b).exponent) ||
899                              !ex_to<numeric>(ex_to<power>(b).exponent).is_pos_integer() ||
900                              !is_exactly_a<add>(ex_to<power>(b).basis) ||
901                              !is_exactly_a<mul>(ex_to<power>(b).basis) ||
902                              !is_exactly_a<power>(ex_to<power>(b).basis));
903                 if (is_exactly_a<mul>(b))
904                         term.push_back(expand_mul(ex_to<mul>(b), numeric(n-k_cum[m-2]), options, true));
905                 else
906                         term.push_back(power(b,n-k_cum[m-2]));
907
908                 numeric f = binomial(numeric(n),numeric(k[0]));
909                 for (std::size_t l = 1; l < m - 1; ++l)
910                         f *= binomial(numeric(n-k_cum[l-1]),numeric(k[l]));
911
912                 term.push_back(f);
913
914                 result.push_back(ex((new mul(term))->setflag(status_flags::dynallocated)).expand(options));
915
916                 // increment k[]
917                 bool done = false;
918                 std::size_t l = m - 2;
919                 while ((++k[l]) > upper_limit[l]) {
920                         k[l] = 0;
921                         if (l != 0)
922                                 --l;
923                         else {
924                                 done = true;
925                                 break;
926                         }
927                 }
928                 if (done)
929                         break;
930
931                 // recalc k_cum[] and upper_limit[]
932                 k_cum[l] = (l==0 ? k[0] : k_cum[l-1]+k[l]);
933
934                 for (size_t i=l+1; i<m-1; ++i)
935                         k_cum[i] = k_cum[i-1]+k[i];
936
937                 for (size_t i=l+1; i<m-1; ++i)
938                         upper_limit[i] = n-k_cum[i-1];
939         }
940
941         return (new add(result))->setflag(status_flags::dynallocated |
942                                           status_flags::expanded);
943 }
944
945
946 /** Special case of power::expand_add. Expands a^2 where a is an add.
947  *  @see power::expand_add */
948 ex power::expand_add_2(const add & a, unsigned options) const
949 {
950         epvector sum;
951         size_t a_nops = a.nops();
952         sum.reserve((a_nops*(a_nops+1))/2);
953         epvector::const_iterator last = a.seq.end();
954
955         // power(+(x,...,z;c),2)=power(+(x,...,z;0),2)+2*c*+(x,...,z;0)+c*c
956         // first part: ignore overall_coeff and expand other terms
957         for (epvector::const_iterator cit0=a.seq.begin(); cit0!=last; ++cit0) {
958                 const ex & r = cit0->rest;
959                 const ex & c = cit0->coeff;
960                 
961                 GINAC_ASSERT(!is_exactly_a<add>(r));
962                 GINAC_ASSERT(!is_exactly_a<power>(r) ||
963                              !is_exactly_a<numeric>(ex_to<power>(r).exponent) ||
964                              !ex_to<numeric>(ex_to<power>(r).exponent).is_pos_integer() ||
965                              !is_exactly_a<add>(ex_to<power>(r).basis) ||
966                              !is_exactly_a<mul>(ex_to<power>(r).basis) ||
967                              !is_exactly_a<power>(ex_to<power>(r).basis));
968                 
969                 if (c.is_equal(_ex1)) {
970                         if (is_exactly_a<mul>(r)) {
971                                 sum.push_back(expair(expand_mul(ex_to<mul>(r), *_num2_p, options, true),
972                                                      _ex1));
973                         } else {
974                                 sum.push_back(expair((new power(r,_ex2))->setflag(status_flags::dynallocated),
975                                                      _ex1));
976                         }
977                 } else {
978                         if (is_exactly_a<mul>(r)) {
979                                 sum.push_back(a.combine_ex_with_coeff_to_pair(expand_mul(ex_to<mul>(r), *_num2_p, options, true),
980                                                      ex_to<numeric>(c).power_dyn(*_num2_p)));
981                         } else {
982                                 sum.push_back(a.combine_ex_with_coeff_to_pair((new power(r,_ex2))->setflag(status_flags::dynallocated),
983                                                      ex_to<numeric>(c).power_dyn(*_num2_p)));
984                         }
985                 }
986
987                 for (epvector::const_iterator cit1=cit0+1; cit1!=last; ++cit1) {
988                         const ex & r1 = cit1->rest;
989                         const ex & c1 = cit1->coeff;
990                         sum.push_back(a.combine_ex_with_coeff_to_pair((new mul(r,r1))->setflag(status_flags::dynallocated),
991                                                                       _num2_p->mul(ex_to<numeric>(c)).mul_dyn(ex_to<numeric>(c1))));
992                 }
993         }
994         
995         GINAC_ASSERT(sum.size()==(a.seq.size()*(a.seq.size()+1))/2);
996         
997         // second part: add terms coming from overall_factor (if != 0)
998         if (!a.overall_coeff.is_zero()) {
999                 epvector::const_iterator i = a.seq.begin(), end = a.seq.end();
1000                 while (i != end) {
1001                         sum.push_back(a.combine_pair_with_coeff_to_pair(*i, ex_to<numeric>(a.overall_coeff).mul_dyn(*_num2_p)));
1002                         ++i;
1003                 }
1004                 sum.push_back(expair(ex_to<numeric>(a.overall_coeff).power_dyn(*_num2_p),_ex1));
1005         }
1006         
1007         GINAC_ASSERT(sum.size()==(a_nops*(a_nops+1))/2);
1008         
1009         return (new add(sum))->setflag(status_flags::dynallocated | status_flags::expanded);
1010 }
1011
1012 /** Expand factors of m in m^n where m is a mul and n is an integer.
1013  *  @see power::expand */
1014 ex power::expand_mul(const mul & m, const numeric & n, unsigned options, bool from_expand) const
1015 {
1016         GINAC_ASSERT(n.is_integer());
1017
1018         if (n.is_zero()) {
1019                 return _ex1;
1020         }
1021
1022         // do not bother to rename indices if there are no any.
1023         if ((!(options & expand_options::expand_rename_idx)) 
1024                         && m.info(info_flags::has_indices))
1025                 options |= expand_options::expand_rename_idx;
1026         // Leave it to multiplication since dummy indices have to be renamed
1027         if ((options & expand_options::expand_rename_idx) &&
1028                 (get_all_dummy_indices(m).size() > 0) && n.is_positive()) {
1029                 ex result = m;
1030                 exvector va = get_all_dummy_indices(m);
1031                 sort(va.begin(), va.end(), ex_is_less());
1032
1033                 for (int i=1; i < n.to_int(); i++)
1034                         result *= rename_dummy_indices_uniquely(va, m);
1035                 return result;
1036         }
1037
1038         epvector distrseq;
1039         distrseq.reserve(m.seq.size());
1040         bool need_reexpand = false;
1041
1042         epvector::const_iterator last = m.seq.end();
1043         epvector::const_iterator cit = m.seq.begin();
1044         while (cit!=last) {
1045                 expair p = m.combine_pair_with_coeff_to_pair(*cit, n);
1046                 if (from_expand && is_exactly_a<add>(cit->rest) && ex_to<numeric>(p.coeff).is_pos_integer()) {
1047                         // this happens when e.g. (a+b)^(1/2) gets squared and
1048                         // the resulting product needs to be reexpanded
1049                         need_reexpand = true;
1050                 }
1051                 distrseq.push_back(p);
1052                 ++cit;
1053         }
1054
1055         const mul & result = static_cast<const mul &>((new mul(distrseq, ex_to<numeric>(m.overall_coeff).power_dyn(n)))->setflag(status_flags::dynallocated));
1056         if (need_reexpand)
1057                 return ex(result).expand(options);
1058         if (from_expand)
1059                 return result.setflag(status_flags::expanded);
1060         return result;
1061 }
1062
1063 GINAC_BIND_UNARCHIVER(power);
1064
1065 } // namespace GiNaC