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