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