]> www.ginac.de Git - ginac.git/blob - ginac/integral.cpp
81e7adefcb3208f72af6e61746a1ec1ba239bd46
[ginac.git] / ginac / integral.cpp
1 /** @file integral.cpp
2  *
3  *  Implementation of GiNaC's symbolic  integral. */
4
5 /*
6  *  GiNaC Copyright (C) 1999-2015 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 "integral.h"
24 #include "numeric.h"
25 #include "symbol.h"
26 #include "add.h"
27 #include "mul.h"
28 #include "power.h"
29 #include "inifcns.h"
30 #include "wildcard.h"
31 #include "archive.h"
32 #include "registrar.h"
33 #include "utils.h"
34 #include "operators.h"
35 #include "relational.h"
36
37 using namespace std;
38
39 namespace GiNaC {
40
41 GINAC_IMPLEMENT_REGISTERED_CLASS_OPT(integral, basic,
42   print_func<print_dflt>(&integral::do_print).
43   print_func<print_latex>(&integral::do_print_latex))
44
45
46 //////////
47 // default constructor
48 //////////
49
50 integral::integral()
51                 : x(dynallocate<symbol>())
52 {}
53
54 //////////
55 // other constructors
56 //////////
57
58 // public
59
60 integral::integral(const ex & x_, const ex & a_, const ex & b_, const ex & f_)
61                 :  x(x_), a(a_), b(b_), f(f_)
62 {
63         if (!is_a<symbol>(x)) {
64                 throw(std::invalid_argument("first argument of integral must be of type symbol"));
65         }
66 }
67
68 //////////
69 // archiving
70 //////////
71
72 void integral::read_archive(const archive_node& n, lst& sym_lst)
73 {
74         inherited::read_archive(n, sym_lst);
75         n.find_ex("x", x, sym_lst);
76         n.find_ex("a", a, sym_lst);
77         n.find_ex("b", b, sym_lst);
78         n.find_ex("f", f, sym_lst);
79 }
80
81 void integral::archive(archive_node & n) const
82 {
83         inherited::archive(n);
84         n.add_ex("x", x);
85         n.add_ex("a", a);
86         n.add_ex("b", b);
87         n.add_ex("f", f);
88 }
89
90 //////////
91 // functions overriding virtual functions from base classes
92 //////////
93
94 void integral::do_print(const print_context & c, unsigned level) const
95 {
96         c.s << "integral(";
97         x.print(c);
98         c.s << ",";
99         a.print(c);
100         c.s << ",";
101         b.print(c);
102         c.s << ",";
103         f.print(c);
104         c.s << ")";
105 }
106
107 void integral::do_print_latex(const print_latex & c, unsigned level) const
108 {
109         string varname = ex_to<symbol>(x).get_name();
110         if (level > precedence())
111                 c.s << "\\left(";
112         c.s << "\\int_{";
113         a.print(c);
114         c.s << "}^{";
115         b.print(c);
116         c.s << "} d";
117         if (varname.size() > 1)
118                 c.s << "\\," << varname << "\\:";
119         else
120                 c.s << varname << "\\,";
121         f.print(c,precedence());
122         if (level > precedence())
123                 c.s << "\\right)";
124 }
125
126 int integral::compare_same_type(const basic & other) const
127 {
128         GINAC_ASSERT(is_exactly_a<integral>(other));
129         const integral &o = static_cast<const integral &>(other);
130
131         int cmpval = x.compare(o.x);
132         if (cmpval)
133                 return cmpval;
134         cmpval = a.compare(o.a);
135         if (cmpval)
136                 return cmpval;
137         cmpval = b.compare(o.b);
138         if (cmpval)
139                 return cmpval;
140         return f.compare(o.f);
141 }
142
143 ex integral::eval(int level) const
144 {
145         if ((level==1) && (flags & status_flags::evaluated))
146                 return *this;
147         if (level == -max_recursion_level)
148                 throw(std::runtime_error("max recursion level reached"));
149
150         ex eintvar = (level==1) ? x : x.eval(level-1);
151         ex ea      = (level==1) ? a : a.eval(level-1);
152         ex eb      = (level==1) ? b : b.eval(level-1);
153         ex ef      = (level==1) ? f : f.eval(level-1);
154
155         if (!ef.has(eintvar) && !haswild(ef))
156                 return eb*ef-ea*ef;
157
158         if (ea==eb)
159                 return _ex0;
160
161         if (are_ex_trivially_equal(eintvar,x) && are_ex_trivially_equal(ea,a) &&
162             are_ex_trivially_equal(eb,b) && are_ex_trivially_equal(ef,f))
163                 return this->hold();
164         return dynallocate<integral>(eintvar, ea, eb, ef).setflag(status_flags::evaluated);
165 }
166
167 ex integral::evalf(int level) const
168 {
169         ex ea;
170         ex eb;
171         ex ef;
172
173         if (level==1) {
174                 ea = a;
175                 eb = b;
176                 ef = f;
177         } else if (level == -max_recursion_level) {
178                 throw(runtime_error("max recursion level reached"));
179         } else {
180                 ea = a.evalf(level-1);
181                 eb = b.evalf(level-1);
182                 ef = f.evalf(level-1);
183         }
184
185         // 12.34 is just an arbitrary number used to check whether a number
186         // results after substituting a number for the integration variable.
187         if (is_exactly_a<numeric>(ea) && is_exactly_a<numeric>(eb) &&
188             is_exactly_a<numeric>(ef.subs(x==12.34).evalf())) {
189                         return adaptivesimpson(x, ea, eb, ef);
190         }
191
192         if (are_ex_trivially_equal(a, ea) && are_ex_trivially_equal(b, eb) &&
193             are_ex_trivially_equal(f, ef))
194                         return *this;
195                 else
196                         return dynallocate<integral>(x, ea, eb, ef);
197 }
198
199 int integral::max_integration_level = 15;
200 ex integral::relative_integration_error = 1e-8;
201
202 ex subsvalue(const ex & var, const ex & value, const ex & fun)
203 {
204         ex result = fun.subs(var==value).evalf();
205         if (is_a<numeric>(result))
206                 return result;
207         throw logic_error("integrand does not evaluate to numeric");
208 }
209
210 struct error_and_integral
211 {
212         error_and_integral(const ex &err, const ex &integ)
213                 :error(err), integral(integ){}
214         ex error;
215         ex integral;
216 };
217
218 struct error_and_integral_is_less
219 {
220         bool operator()(const error_and_integral &e1,const error_and_integral &e2) const
221         {
222                 int c = e1.integral.compare(e2.integral);
223                 if(c < 0)
224                         return true;
225                 if(c > 0)
226                         return false;
227                 return ex_is_less()(e1.error, e2.error);
228         }
229 };
230
231 typedef map<error_and_integral, ex, error_and_integral_is_less> lookup_map;
232
233 /** Numeric integration routine based upon the "Adaptive Quadrature" one
234   * in "Numerical Analysis" by Burden and Faires. Parameters are integration
235   * variable, left boundary, right boundary, function to be integrated and
236   * the relative integration error. The function should evalf into a number
237   * after substituting the integration variable by a number. Another thing
238   * to note is that this implementation is no good at integrating functions
239   * with discontinuities. */
240 ex adaptivesimpson(const ex & x, const ex & a_in, const ex & b_in, const ex & f, const ex & error)
241 {
242         // Check whether boundaries and error are numbers.
243         ex a = is_exactly_a<numeric>(a_in) ? a_in : a_in.evalf();
244         ex b = is_exactly_a<numeric>(b_in) ? b_in : b_in.evalf();
245         if(!is_exactly_a<numeric>(a) || !is_exactly_a<numeric>(b))
246                 throw std::runtime_error("For numerical integration the boundaries of the integral should evalf into numbers.");
247         if(!is_exactly_a<numeric>(error))
248                 throw std::runtime_error("For numerical integration the error should be a number.");
249
250         // Use lookup table to be potentially much faster.
251         static lookup_map lookup;
252         static symbol ivar("ivar");
253         ex lookupex = integral(ivar,a,b,f.subs(x==ivar));
254         lookup_map::iterator emi = lookup.find(error_and_integral(error, lookupex));
255         if (emi!=lookup.end())
256                 return emi->second;
257
258         ex app = 0;
259         int i = 1;
260         exvector avec(integral::max_integration_level+1);
261         exvector hvec(integral::max_integration_level+1);
262         exvector favec(integral::max_integration_level+1);
263         exvector fbvec(integral::max_integration_level+1);
264         exvector fcvec(integral::max_integration_level+1);
265         exvector svec(integral::max_integration_level+1);
266         exvector errorvec(integral::max_integration_level+1);
267         vector<int> lvec(integral::max_integration_level+1);
268
269         avec[i] = a;
270         hvec[i] = (b-a)/2;
271         favec[i] = subsvalue(x, a, f);
272         fcvec[i] = subsvalue(x, a+hvec[i], f);
273         fbvec[i] = subsvalue(x, b, f);
274         svec[i] = hvec[i]*(favec[i]+4*fcvec[i]+fbvec[i])/3;
275         lvec[i] = 1;
276         errorvec[i] = error*abs(svec[i]);
277
278         while (i>0) {
279                 ex fd = subsvalue(x, avec[i]+hvec[i]/2, f);
280                 ex fe = subsvalue(x, avec[i]+3*hvec[i]/2, f);
281                 ex s1 = hvec[i]*(favec[i]+4*fd+fcvec[i])/6;
282                 ex s2 = hvec[i]*(fcvec[i]+4*fe+fbvec[i])/6;
283                 ex nu1 = avec[i];
284                 ex nu2 = favec[i];
285                 ex nu3 = fcvec[i];
286                 ex nu4 = fbvec[i];
287                 ex nu5 = hvec[i];
288                 // hopefully prevents a crash if the function is zero sometimes.
289                 ex nu6 = max(errorvec[i], abs(s1+s2)*error);
290                 ex nu7 = svec[i];
291                 int nu8 = lvec[i];
292                 --i;
293                 if (abs(ex_to<numeric>(s1+s2-nu7)) <= nu6)
294                         app+=(s1+s2);
295                 else {
296                         if (nu8>=integral::max_integration_level)
297                                 throw runtime_error("max integration level reached");
298                         ++i;
299                         avec[i] = nu1+nu5;
300                         favec[i] = nu3;
301                         fcvec[i] = fe;
302                         fbvec[i] = nu4;
303                         hvec[i] = nu5/2;
304                         errorvec[i]=nu6/2;
305                         svec[i] = s2;
306                         lvec[i] = nu8+1;
307                         ++i;
308                         avec[i] = nu1;
309                         favec[i] = nu2;
310                         fcvec[i] = fd;
311                         fbvec[i] = nu3;
312                         hvec[i] = hvec[i-1];
313                         errorvec[i]=errorvec[i-1];
314                         svec[i] = s1;
315                         lvec[i] = lvec[i-1];
316                 }
317         }
318
319         lookup[error_and_integral(error, lookupex)]=app;
320         return app;
321 }
322
323 int integral::degree(const ex & s) const
324 {
325         return ((b-a)*f).degree(s);
326 }
327
328 int integral::ldegree(const ex & s) const
329 {
330         return ((b-a)*f).ldegree(s);
331 }
332
333 ex integral::eval_ncmul(const exvector & v) const
334 {
335         return f.eval_ncmul(v);
336 }
337
338 size_t integral::nops() const
339 {
340         return 4;
341 }
342
343 ex integral::op(size_t i) const
344 {
345         GINAC_ASSERT(i<4);
346
347         switch (i) {
348                 case 0:
349                         return x;
350                 case 1:
351                         return a;
352                 case 2:
353                         return b;
354                 case 3:
355                         return f;
356                 default:
357                         throw (std::out_of_range("integral::op() out of range"));
358         }
359 }
360
361 ex & integral::let_op(size_t i)
362 {
363         ensure_if_modifiable();
364         switch (i) {
365                 case 0:
366                         return x;
367                 case 1:
368                         return a;
369                 case 2:
370                         return b;
371                 case 3:
372                         return f;
373                 default:
374                         throw (std::out_of_range("integral::let_op() out of range"));
375         }
376 }
377
378 ex integral::expand(unsigned options) const
379 {
380         if (options==0 && (flags & status_flags::expanded))
381                 return *this;
382
383         ex newa = a.expand(options);
384         ex newb = b.expand(options);
385         ex newf = f.expand(options);
386
387         if (is_a<add>(newf)) {
388                 exvector v;
389                 v.reserve(newf.nops());
390                 for (size_t i=0; i<newf.nops(); ++i)
391                         v.push_back(integral(x, newa, newb, newf.op(i)).expand(options));
392                 return ex(add(v)).expand(options);
393         }
394
395         if (is_a<mul>(newf)) {
396                 ex prefactor = 1;
397                 ex rest = 1;
398                 for (size_t i=0; i<newf.nops(); ++i)
399                         if (newf.op(i).has(x))
400                                 rest *= newf.op(i);
401                         else
402                                 prefactor *= newf.op(i);
403                 if (prefactor != 1)
404                         return (prefactor*integral(x, newa, newb, rest)).expand(options);
405         }
406
407         if (are_ex_trivially_equal(a, newa) && are_ex_trivially_equal(b, newb) &&
408             are_ex_trivially_equal(f, newf)) {
409                 if (options==0)
410                         this->setflag(status_flags::expanded);
411                 return *this;
412         }
413
414         const integral & newint = dynallocate<integral>(x, newa, newb, newf);
415         if (options == 0)
416                 newint.setflag(status_flags::expanded);
417         return newint;
418 }
419
420 ex integral::derivative(const symbol & s) const
421 {
422         if (s==x)
423                 throw(logic_error("differentiation with respect to dummy variable"));
424         return b.diff(s)*f.subs(x==b)-a.diff(s)*f.subs(x==a)+integral(x, a, b, f.diff(s));
425 }
426
427 unsigned integral::return_type() const
428 {
429         return f.return_type();
430 }
431
432 return_type_t integral::return_type_tinfo() const
433 {
434         return f.return_type_tinfo();
435 }
436
437 ex integral::conjugate() const
438 {
439         ex conja = a.conjugate();
440         ex conjb = b.conjugate();
441         ex conjf = f.conjugate().subs(x.conjugate()==x);
442
443         if (are_ex_trivially_equal(a, conja) && are_ex_trivially_equal(b, conjb) &&
444             are_ex_trivially_equal(f, conjf))
445                 return *this;
446
447         return dynallocate<integral>(x, conja, conjb, conjf);
448 }
449
450 ex integral::eval_integ() const
451 {
452         if (!(flags & status_flags::expanded))
453                 return this->expand().eval_integ();
454         
455         if (f==x)
456                 return b*b/2-a*a/2;
457         if (is_a<power>(f) && f.op(0)==x) {
458                 if (f.op(1)==-1)
459                         return log(b/a);
460                 if (!f.op(1).has(x)) {
461                         ex primit = power(x,f.op(1)+1)/(f.op(1)+1);
462                         return primit.subs(x==b)-primit.subs(x==a);
463                 }
464         }
465
466         return *this;
467 }
468
469 GINAC_BIND_UNARCHIVER(integral);
470 } // namespace GiNaC