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