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