1This is ginac.info, produced by makeinfo version 6.8 from ginac.texi.
2
3INFO-DIR-SECTION Mathematics
4START-INFO-DIR-ENTRY
5* ginac: (ginac).                   C++ library for symbolic computation.
6END-INFO-DIR-ENTRY
7
8This is a tutorial that documents GiNaC 1.8.2, an open framework for
9symbolic computation within the C++ programming language.
10
11Copyright (C) 1999-2022 Johannes Gutenberg University Mainz, Germany
12
13Permission is granted to make and distribute verbatim copies of this
14manual provided the copyright notice and this permission notice are
15preserved on all copies.
16
17Permission is granted to copy and distribute modified versions of this
18manual under the conditions for verbatim copying, provided that the
19entire resulting derived work is distributed under the terms of a
20permission notice identical to this one.
21
22
23File: ginac.info,  Node: Top,  Next: Introduction,  Prev: (dir),  Up: (dir)
24
25GiNaC
26*****
27
28This is a tutorial that documents GiNaC 1.8.2, an open framework for
29symbolic computation within the C++ programming language.
30
31* Menu:
32
33* Introduction::                 GiNaC's purpose.
34* A tour of GiNaC::              A quick tour of the library.
35* Installation::                 How to install the package.
36* Basic concepts::               Description of fundamental classes.
37* Methods and functions::        Algorithms for symbolic manipulations.
38* Extending GiNaC::              How to extend the library.
39* A comparison with other CAS::  Compares GiNaC to traditional CAS.
40* Internal structures::          Description of some internal structures.
41* Package tools::                Configuring packages to work with GiNaC.
42* Bibliography::
43* Concept index::
44
45
46File: ginac.info,  Node: Introduction,  Next: A tour of GiNaC,  Prev: Top,  Up: Top
47
481 Introduction
49**************
50
51The motivation behind GiNaC derives from the observation that most
52present day computer algebra systems (CAS) are linguistically and
53semantically impoverished.  Although they are quite powerful tools for
54learning math and solving particular problems they lack modern
55linguistic structures that allow for the creation of large-scale
56projects.  GiNaC is an attempt to overcome this situation by extending a
57well established and standardized computer language (C++) by some
58fundamental symbolic capabilities, thus allowing for integrated systems
59that embed symbolic manipulations together with more established areas
60of computer science (like computation-intense numeric applications,
61graphical interfaces, etc.)  under one roof.
62
63The particular problem that led to the writing of the GiNaC framework is
64still a very active field of research, namely the calculation of higher
65order corrections to elementary particle interactions.  There,
66theoretical physicists are interested in matching present day theories
67against experiments taking place at particle accelerators.  The
68computations involved are so complex they call for a combined symbolical
69and numerical approach.  This turned out to be quite difficult to
70accomplish with the present day CAS we have worked with so far and so we
71tried to fill the gap by writing GiNaC. But of course its applications
72are in no way restricted to theoretical physics.
73
74This tutorial is intended for the novice user who is new to GiNaC but
75already has some background in C++ programming.  However, since a
76hand-made documentation like this one is difficult to keep in sync with
77the development, the actual documentation is inside the sources in the
78form of comments.  That documentation may be parsed by one of the many
79Javadoc-like documentation systems.  If you fail at generating it you
80may access it from the GiNaC home page
81(https://www.ginac.de/reference/).  It is an invaluable resource not
82only for the advanced user who wishes to extend the system (or chase
83bugs) but for everybody who wants to comprehend the inner workings of
84GiNaC. This little tutorial on the other hand only covers the basic
85things that are unlikely to change in the near future.
86
871.1 License
88===========
89
90The GiNaC framework for symbolic computation within the C++ programming
91language is Copyright (C) 1999-2021 Johannes Gutenberg University Mainz,
92Germany.
93
94This program is free software; you can redistribute it and/or modify it
95under the terms of the GNU General Public License as published by the
96Free Software Foundation; either version 2 of the License, or (at your
97option) any later version.
98
99This program is distributed in the hope that it will be useful, but
100WITHOUT ANY WARRANTY; without even the implied warranty of
101MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
102Public License for more details.
103
104You should have received a copy of the GNU General Public License along
105with this program; see the file COPYING. If not, write to the Free
106Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
10702110-1301, USA.
108
109
110File: ginac.info,  Node: A tour of GiNaC,  Next: How to use it from within C++,  Prev: Introduction,  Up: Top
111
1122 A Tour of GiNaC
113*****************
114
115This quick tour of GiNaC wants to arise your interest in the subsequent
116chapters by showing off a bit.  Please excuse us if it leaves many open
117questions.
118
119* Menu:
120
121* How to use it from within C++::  Two simple examples.
122* What it can do for you::         A Tour of GiNaC's features.
123
124
125File: ginac.info,  Node: How to use it from within C++,  Next: What it can do for you,  Prev: A tour of GiNaC,  Up: A tour of GiNaC
126
1272.1 How to use it from within C++
128=================================
129
130The GiNaC open framework for symbolic computation within the C++
131programming language does not try to define a language of its own as
132conventional CAS do.  Instead, it extends the capabilities of C++ by
133symbolic manipulations.  Here is how to generate and print a simple (and
134rather pointless) bivariate polynomial with some large coefficients:
135
136     #include <iostream>
137     #include <ginac/ginac.h>
138     using namespace std;
139     using namespace GiNaC;
140
141     int main()
142     {
143         symbol x("x"), y("y");
144         ex poly;
145
146         for (int i=0; i<3; ++i)
147             poly += factorial(i+16)*pow(x,i)*pow(y,2-i);
148
149         cout << poly << endl;
150         return 0;
151     }
152
153Assuming the file is called 'hello.cc', on our system we can compile and
154run it like this:
155
156     $ c++ hello.cc -o hello -lginac -lcln
157     $ ./hello
158     355687428096000*x*y+20922789888000*y^2+6402373705728000*x^2
159
160(*Note Package tools::, for tools that help you when creating a software
161package that uses GiNaC.)
162
163Next, there is a more meaningful C++ program that calls a function which
164generates Hermite polynomials in a specified free variable.
165
166     #include <iostream>
167     #include <ginac/ginac.h>
168     using namespace std;
169     using namespace GiNaC;
170
171     ex HermitePoly(const symbol & x, int n)
172     {
173         ex HKer=exp(-pow(x, 2));
174         // uses the identity H_n(x) == (-1)^n exp(x^2) (d/dx)^n exp(-x^2)
175         return normal(pow(-1, n) * diff(HKer, x, n) / HKer);
176     }
177
178     int main()
179     {
180         symbol z("z");
181
182         for (int i=0; i<6; ++i)
183             cout << "H_" << i << "(z) == " << HermitePoly(z,i) << endl;
184
185         return 0;
186     }
187
188When run, this will type out
189
190     H_0(z) == 1
191     H_1(z) == 2*z
192     H_2(z) == 4*z^2-2
193     H_3(z) == -12*z+8*z^3
194     H_4(z) == -48*z^2+16*z^4+12
195     H_5(z) == 120*z-160*z^3+32*z^5
196
197This method of generating the coefficients is of course far from optimal
198for production purposes.
199
200In order to show some more examples of what GiNaC can do we will now use
201the 'ginsh', a simple GiNaC interactive shell that provides a convenient
202window into GiNaC's capabilities.
203
204
205File: ginac.info,  Node: What it can do for you,  Next: Installation,  Prev: How to use it from within C++,  Up: A tour of GiNaC
206
2072.2 What it can do for you
208==========================
209
210After invoking 'ginsh' one can test and experiment with GiNaC's features
211much like in other Computer Algebra Systems except that it does not
212provide programming constructs like loops or conditionals.  For a
213concise description of the 'ginsh' syntax we refer to its accompanied
214man page.  Suffice to say that assignments and comparisons in 'ginsh'
215are written as they are in C, i.e.  '=' assigns and '==' compares.
216
217It can manipulate arbitrary precision integers in a very fast way.
218Rational numbers are automatically converted to fractions of coprime
219integers:
220
221     > x=3^150;
222     369988485035126972924700782451696644186473100389722973815184405301748249
223     > y=3^149;
224     123329495011708990974900260817232214728824366796574324605061468433916083
225     > x/y;
226     3
227     > y/x;
228     1/3
229
230Exact numbers are always retained as exact numbers and only evaluated as
231floating point numbers if requested.  For instance, with numeric
232radicals is dealt pretty much as with symbols.  Products of sums of them
233can be expanded:
234
235     > expand((1+a^(1/5)-a^(2/5))^3);
236     1+3*a+3*a^(1/5)-5*a^(3/5)-a^(6/5)
237     > expand((1+3^(1/5)-3^(2/5))^3);
238     10-5*3^(3/5)
239     > evalf((1+3^(1/5)-3^(2/5))^3);
240     0.33408977534118624228
241
242The function 'evalf' that was used above converts any number in GiNaC's
243expressions into floating point numbers.  This can be done to arbitrary
244predefined accuracy:
245
246     > evalf(1/7);
247     0.14285714285714285714
248     > Digits=150;
249     150
250     > evalf(1/7);
251     0.1428571428571428571428571428571428571428571428571428571428571428571428
252     5714285714285714285714285714285714285
253
254Exact numbers other than rationals that can be manipulated in GiNaC
255include predefined constants like Archimedes' 'Pi'.  They can both be
256used in symbolic manipulations (as an exact number) as well as in
257numeric expressions (as an inexact number):
258
259     > a=Pi^2+x;
260     x+Pi^2
261     > evalf(a);
262     9.869604401089358619+x
263     > x=2;
264     2
265     > evalf(a);
266     11.869604401089358619
267
268Built-in functions evaluate immediately to exact numbers if this is
269possible.  Conversions that can be safely performed are done
270immediately; conversions that are not generally valid are not done:
271
272     > cos(42*Pi);
273     1
274     > cos(acos(x));
275     x
276     > acos(cos(x));
277     acos(cos(x))
278
279(Note that converting the last input to 'x' would allow one to conclude
280that '42*Pi' is equal to '0'.)
281
282Linear equation systems can be solved along with basic linear algebra
283manipulations over symbolic expressions.  In C++ GiNaC offers a matrix
284class for this purpose but we can see what it can do using 'ginsh''s
285bracket notation to type them in:
286
287     > lsolve(a+x*y==z,x);
288     y^(-1)*(z-a);
289     > lsolve({3*x+5*y == 7, -2*x+10*y == -5}, {x, y});
290     {x==19/8,y==-1/40}
291     > M = [ [1, 3], [-3, 2] ];
292     [[1,3],[-3,2]]
293     > determinant(M);
294     11
295     > charpoly(M,lambda);
296     lambda^2-3*lambda+11
297     > A = [ [1, 1], [2, -1] ];
298     [[1,1],[2,-1]]
299     > A+2*M;
300     [[1,1],[2,-1]]+2*[[1,3],[-3,2]]
301     > evalm(%);
302     [[3,7],[-4,3]]
303     > B = [ [0, 0, a], [b, 1, -b], [-1/a, 0, 0] ];
304     > evalm(B^(2^12345));
305     [[1,0,0],[0,1,0],[0,0,1]]
306
307Multivariate polynomials and rational functions may be expanded,
308collected, factorized, and normalized (i.e.  converted to a ratio of two
309coprime polynomials):
310
311     > a = x^4 + 2*x^2*y^2 + 4*x^3*y + 12*x*y^3 - 3*y^4;
312     12*x*y^3+2*x^2*y^2+4*x^3*y-3*y^4+x^4
313     > b = x^2 + 4*x*y - y^2;
314     4*x*y-y^2+x^2
315     > expand(a*b);
316     8*x^5*y+17*x^4*y^2+43*x^2*y^4-24*x*y^5+16*x^3*y^3+3*y^6+x^6
317     > factor(%);
318     (4*x*y+x^2-y^2)^2*(x^2+3*y^2)
319     > collect(a+b,x);
320     4*x^3*y-y^2-3*y^4+(12*y^3+4*y)*x+x^4+x^2*(1+2*y^2)
321     > collect(a+b,y);
322     12*x*y^3-3*y^4+(-1+2*x^2)*y^2+(4*x+4*x^3)*y+x^2+x^4
323     > normal(a/b);
324     3*y^2+x^2
325
326Here we have made use of the 'ginsh'-command '%' to pop the previously
327evaluated element from 'ginsh''s internal stack.
328
329You can differentiate functions and expand them as Taylor or Laurent
330series in a very natural syntax (the second argument of 'series' is a
331relation defining the evaluation point, the third specifies the order):
332
333     > diff(tan(x),x);
334     tan(x)^2+1
335     > series(sin(x),x==0,4);
336     x-1/6*x^3+Order(x^4)
337     > series(1/tan(x),x==0,4);
338     x^(-1)-1/3*x+Order(x^2)
339     > series(tgamma(x),x==0,3);
340     x^(-1)-Euler+(1/12*Pi^2+1/2*Euler^2)*x+
341     (-1/3*zeta(3)-1/12*Pi^2*Euler-1/6*Euler^3)*x^2+Order(x^3)
342     > evalf(%);
343     x^(-1)-0.5772156649015328606+(0.9890559953279725555)*x
344     -(0.90747907608088628905)*x^2+Order(x^3)
345     > series(tgamma(2*sin(x)-2),x==Pi/2,6);
346     -(x-1/2*Pi)^(-2)+(-1/12*Pi^2-1/2*Euler^2-1/240)*(x-1/2*Pi)^2
347     -Euler-1/12+Order((x-1/2*Pi)^3)
348
349Often, functions don't have roots in closed form.  Nevertheless, it's
350quite easy to compute a solution numerically, to arbitrary precision:
351
352     > Digits=50:
353     > fsolve(cos(x)==x,x,0,2);
354     0.7390851332151606416553120876738734040134117589007574649658
355     > f=exp(sin(x))-x:
356     > X=fsolve(f,x,-10,10);
357     2.2191071489137460325957851882042901681753665565320678854155
358     > subs(f,x==X);
359     -6.372367644529809108115521591070847222364418220770475144296E-58
360
361Notice how the final result above differs slightly from zero by about
3626*10^(-58).  This is because with 50 decimal digits precision the root
363cannot be represented more accurately than 'X'.  Such inaccuracies are
364to be expected when computing with finite floating point values.
365
366If you ever wanted to convert units in C or C++ and found this is
367cumbersome, here is the solution.  Symbolic types can always be used as
368tags for different types of objects.  Converting from wrong units to the
369metric system is now easy:
370
371     > in=.0254*m;
372     0.0254*m
373     > lb=.45359237*kg;
374     0.45359237*kg
375     > 200*lb/in^2;
376     140613.91592783185568*kg*m^(-2)
377
378
379File: ginac.info,  Node: Installation,  Next: Prerequisites,  Prev: What it can do for you,  Up: Top
380
3813 Installation
382**************
383
384GiNaC's installation follows the spirit of most GNU software.  It is
385easily installed on your system by three steps: configuration, build,
386installation.
387
388* Menu:
389
390* Prerequisites::                Packages upon which GiNaC depends.
391* Configuration::                How to configure GiNaC.
392* Building GiNaC::               How to compile GiNaC.
393* Installing GiNaC::             How to install GiNaC on your system.
394
395
396File: ginac.info,  Node: Prerequisites,  Next: Configuration,  Prev: Installation,  Up: Installation
397
3983.1 Prerequisites
399=================
400
401In order to install GiNaC on your system, some prerequisites need to be
402met.  First of all, you need to have a C++-compiler adhering to the ISO
403standard 'ISO/IEC 14882:2011(E)'. We used GCC for development so if you
404have a different compiler you are on your own.  For the configuration to
405succeed you need a Posix compliant shell installed in '/bin/sh', GNU
406'bash' is fine.  The pkg-config utility is required for the
407configuration, it can be downloaded from
408<http://pkg-config.freedesktop.org>.  Last but not least, the CLN
409library is used extensively and needs to be installed on your system.
410Please get it from <https://www.ginac.de/CLN/> (it is licensed under the
411GPL) and install it prior to trying to install GiNaC. The configure
412script checks if it can find it and if it cannot, it will refuse to
413continue.
414
415
416File: ginac.info,  Node: Configuration,  Next: Building GiNaC,  Prev: Prerequisites,  Up: Installation
417
4183.2 Configuration
419=================
420
421To configure GiNaC means to prepare the source distribution for
422building.  It is done via a shell script called 'configure' that is
423shipped with the sources and was originally generated by GNU Autoconf.
424Since a configure script generated by GNU Autoconf never prompts, all
425customization must be done either via command line parameters or
426environment variables.  It accepts a list of parameters, the complete
427set of which can be listed by calling it with the '--help' option.  The
428most important ones will be shortly described in what follows:
429
430   * '--disable-shared': When given, this option switches off the build
431     of a shared library, i.e.  a '.so' file.  This may be convenient
432     when developing because it considerably speeds up compilation.
433
434   * '--prefix=PREFIX': The directory where the compiled library and
435     headers are installed.  It defaults to '/usr/local' which means
436     that the library is installed in the directory '/usr/local/lib',
437     the header files in '/usr/local/include/ginac' and the
438     documentation (like this one) into '/usr/local/share/doc/GiNaC'.
439
440   * '--libdir=LIBDIR': Use this option in case you want to have the
441     library installed in some other directory than 'PREFIX/lib/'.
442
443   * '--includedir=INCLUDEDIR': Use this option in case you want to have
444     the header files installed in some other directory than
445     'PREFIX/include/ginac/'.  For instance, if you specify
446     '--includedir=/usr/include' you will end up with the header files
447     sitting in the directory '/usr/include/ginac/'.  Note that the
448     subdirectory 'ginac' is enforced by this process in order to keep
449     the header files separated from others.  This avoids some clashes
450     and allows for an easier deinstallation of GiNaC. This ought to be
451     considered A Good Thing (tm).
452
453   * '--datadir=DATADIR': This option may be given in case you want to
454     have the documentation installed in some other directory than
455     'PREFIX/share/doc/GiNaC/'.
456
457In addition, you may specify some environment variables.  'CXX' holds
458the path and the name of the C++ compiler in case you want to override
459the default in your path.  (The 'configure' script searches your path
460for 'c++', 'g++', 'gcc', 'CC', 'cxx' and 'cc++' in that order.)  It may
461be very useful to define some compiler flags with the 'CXXFLAGS'
462environment variable, like optimization, debugging information and
463warning levels.  If omitted, it defaults to '-g -O2'.(1)
464
465The whole process is illustrated in the following two examples.
466(Substitute 'setenv VARIABLE VALUE' for 'export VARIABLE=VALUE' if the
467Berkeley C shell is your login shell.)
468
469Here is a simple configuration for a site-wide GiNaC library assuming
470everything is in default paths:
471
472     $ export CXXFLAGS="-Wall -O2"
473     $ ./configure
474
475And here is a configuration for a private static GiNaC library with
476several components sitting in custom places (site-wide GCC and private
477CLN). The compiler is persuaded to be picky and full assertions and
478debugging information are switched on:
479
480     $ export CXX=/usr/local/gnu/bin/c++
481     $ export CPPFLAGS="$(CPPFLAGS) -I$(HOME)/include"
482     $ export CXXFLAGS="$(CXXFLAGS) -DDO_GINAC_ASSERT -ggdb -Wall -pedantic"
483     $ export LDFLAGS="$(LDFLAGS) -L$(HOME)/lib"
484     $ ./configure --disable-shared --prefix=$(HOME)
485
486   ---------- Footnotes ----------
487
488   (1) The 'configure' script is itself generated from the file
489'configure.ac'.  It is only distributed in packaged releases of GiNaC.
490If you got the naked sources, e.g.  from git, you must generate
491'configure' along with the various 'Makefile.in' by using the
492'autoreconf' utility.  This will require a fair amount of support from
493your local toolchain, though.
494
495
496File: ginac.info,  Node: Building GiNaC,  Next: Installing GiNaC,  Prev: Configuration,  Up: Installation
497
4983.3 Building GiNaC
499==================
500
501After proper configuration you should just build the whole library by
502typing
503     $ make
504at the command prompt and go for a cup of coffee.  The exact time it
505takes to compile GiNaC depends not only on the speed of your machines
506but also on other parameters, for instance what value for 'CXXFLAGS' you
507entered.  Optimization may be very time-consuming.
508
509Just to make sure GiNaC works properly you may run a collection of
510regression tests by typing
511
512     $ make check
513
514This will compile some sample programs, run them and check the output
515for correctness.  The regression tests fall in three categories.  First,
516the so called _exams_ are performed, simple tests where some predefined
517input is evaluated (like a pupils' exam).  Second, the _checks_ test the
518coherence of results among each other with possible random input.
519Third, some _timings_ are performed, which benchmark some predefined
520problems with different sizes and display the CPU time used in seconds.
521Each individual test should return a message 'passed'.  This is mostly
522intended to be a QA-check if something was broken during development,
523not a sanity check of your system.  Some of the tests in sections
524_checks_ and _timings_ may require insane amounts of memory and CPU
525time.  Feel free to kill them if your machine catches fire.  Another
526quite important intent is to allow people to fiddle around with
527optimization.
528
529By default, the only documentation that will be built is this tutorial
530in '.info' format.  To build the GiNaC tutorial and reference manual in
531HTML, DVI, PostScript, or PDF formats, use one of
532
533     $ make html
534     $ make dvi
535     $ make ps
536     $ make pdf
537
538Generally, the top-level Makefile runs recursively to the
539subdirectories.  It is therefore safe to go into any subdirectory
540('doc/', 'ginsh/', ...) and simply type 'make' TARGET there in case
541something went wrong.
542
543
544File: ginac.info,  Node: Installing GiNaC,  Next: Basic concepts,  Prev: Building GiNaC,  Up: Installation
545
5463.4 Installing GiNaC
547====================
548
549To install GiNaC on your system, simply type
550
551     $ make install
552
553As described in the section about configuration the files will be
554installed in the following directories (the directories will be created
555if they don't already exist):
556
557   * 'libginac.a' will go into 'PREFIX/lib/' (or 'LIBDIR') which
558     defaults to '/usr/local/lib/'.  So will 'libginac.so' unless the
559     configure script was given the option '--disable-shared'.  The
560     proper symlinks will be established as well.
561
562   * All the header files will be installed into 'PREFIX/include/ginac/'
563     (or 'INCLUDEDIR/ginac/', if specified).
564
565   * All documentation (info) will be stuffed into
566     'PREFIX/share/doc/GiNaC/' (or 'DATADIR/doc/GiNaC/', if DATADIR was
567     specified).
568
569For the sake of completeness we will list some other useful make
570targets: 'make clean' deletes all files generated by 'make', i.e.  all
571the object files.  In addition 'make distclean' removes all files
572generated by the configuration and 'make maintainer-clean' goes one step
573further and deletes files that may require special tools to rebuild
574(like the 'libtool' for instance).  Finally 'make uninstall' removes the
575installed library, header files and documentation(1).
576
577   ---------- Footnotes ----------
578
579   (1) Uninstallation does not work after you have called 'make
580distclean' since the 'Makefile' is itself generated by the configuration
581from 'Makefile.in' and hence deleted by 'make distclean'.  There are two
582obvious ways out of this dilemma.  First, you can run the configuration
583again with the same PREFIX thus creating a 'Makefile' with a working
584'uninstall' target.  Second, you can do it by hand since you now know
585where all the files went during installation.
586
587
588File: ginac.info,  Node: Basic concepts,  Next: Expressions,  Prev: Installing GiNaC,  Up: Top
589
5904 Basic concepts
591****************
592
593This chapter will describe the different fundamental objects that can be
594handled by GiNaC. But before doing so, it is worthwhile introducing you
595to the more commonly used class of expressions, representing a flexible
596meta-class for storing all mathematical objects.
597
598* Menu:
599
600* Expressions::                  The fundamental GiNaC class.
601* Automatic evaluation::         Evaluation and canonicalization.
602* Error handling::               How the library reports errors.
603* The class hierarchy::          Overview of GiNaC's classes.
604* Symbols::                      Symbolic objects.
605* Numbers::                      Numerical objects.
606* Constants::                    Pre-defined constants.
607* Fundamental containers::       Sums, products and powers.
608* Lists::                        Lists of expressions.
609* Mathematical functions::       Mathematical functions.
610* Relations::                    Equality, Inequality and all that.
611* Integrals::                    Symbolic integrals.
612* Matrices::                     Matrices.
613* Indexed objects::              Handling indexed quantities.
614* Non-commutative objects::      Algebras with non-commutative products.
615
616
617File: ginac.info,  Node: Expressions,  Next: Automatic evaluation,  Prev: Basic concepts,  Up: Basic concepts
618
6194.1 Expressions
620===============
621
622The most common class of objects a user deals with is the expression
623'ex', representing a mathematical object like a variable, number,
624function, sum, product, etc... Expressions may be put together to form
625new expressions, passed as arguments to functions, and so on.  Here is a
626little collection of valid expressions:
627
628     ex MyEx1 = 5;                       // simple number
629     ex MyEx2 = x + 2*y;                 // polynomial in x and y
630     ex MyEx3 = (x + 1)/(x - 1);         // rational expression
631     ex MyEx4 = sin(x + 2*y) + 3*z + 41; // containing a function
632     ex MyEx5 = MyEx4 + 1;               // similar to above
633
634Expressions are handles to other more fundamental objects, that often
635contain other expressions thus creating a tree of expressions (*Note
636Internal structures::, for particular examples).  Most methods on 'ex'
637therefore run top-down through such an expression tree.  For example,
638the method 'has()' scans recursively for occurrences of something inside
639an expression.  Thus, if you have declared 'MyEx4' as in the example
640above 'MyEx4.has(y)' will find 'y' inside the argument of 'sin' and
641hence return 'true'.
642
643The next sections will outline the general picture of GiNaC's class
644hierarchy and describe the classes of objects that are handled by 'ex'.
645
6464.1.1 Note: Expressions and STL containers
647------------------------------------------
648
649GiNaC expressions ('ex' objects) have value semantics (they can be
650assigned, reassigned and copied like integral types) but the operator
651'<' doesn't provide a well-defined ordering on them.  In STL-speak,
652expressions are 'Assignable' but not 'LessThanComparable'.
653
654This implies that in order to use expressions in sorted containers such
655as 'std::map<>' and 'std::set<>' you have to supply a suitable
656comparison predicate.  GiNaC provides such a predicate, called
657'ex_is_less'.  For example, a set of expressions should be defined as
658'std::set<ex, ex_is_less>'.
659
660Unsorted containers such as 'std::vector<>' and 'std::list<>' don't pose
661a problem.  A 'std::vector<ex>' works as expected.
662
663*Note Information about expressions::, for more about comparing and
664ordering expressions.
665
666
667File: ginac.info,  Node: Automatic evaluation,  Next: Error handling,  Prev: Expressions,  Up: Basic concepts
668
6694.2 Automatic evaluation and canonicalization of expressions
670============================================================
671
672GiNaC performs some automatic transformations on expressions, to
673simplify them and put them into a canonical form.  Some examples:
674
675     ex MyEx1 = 2*x - 1 + x;  // 3*x-1
676     ex MyEx2 = x - x;        // 0
677     ex MyEx3 = cos(2*Pi);    // 1
678     ex MyEx4 = x*y/x;        // y
679
680This behavior is usually referred to as "automatic" or "anonymous
681evaluation".  GiNaC only performs transformations that are
682
683   * at most of complexity O(n log n)
684   * algebraically correct, possibly except for a set of measure zero
685     (e.g.  x/x is transformed to 1 although this is incorrect for x=0)
686
687There are two types of automatic transformations in GiNaC that may not
688behave in an entirely obvious way at first glance:
689
690   * The terms of sums and products (and some other things like the
691     arguments of symmetric functions, the indices of symmetric tensors
692     etc.)  are re-ordered into a canonical form that is deterministic,
693     but not lexicographical or in any other way easy to guess (it
694     almost always depends on the number and order of the symbols you
695     define).  However, constructing the same expression twice, either
696     implicitly or explicitly, will always result in the same canonical
697     form.
698   * Expressions of the form 'number times sum' are automatically
699     expanded (this has to do with GiNaC's internal representation of
700     sums and products).  For example
701          ex MyEx5 = 2*(x + y);   // 2*x+2*y
702          ex MyEx6 = z*(x + y);   // z*(x+y)
703
704The general rule is that when you construct expressions, GiNaC
705automatically creates them in canonical form, which might differ from
706the form you typed in your program.  This may create some awkward
707looking output ('-y+x' instead of 'x-y') but allows for more efficient
708operation and usually yields some immediate simplifications.
709
710Internally, the anonymous evaluator in GiNaC is implemented by the
711methods
712
713     ex ex::eval() const;
714     ex basic::eval() const;
715
716but unless you are extending GiNaC with your own classes or functions,
717there should never be any reason to call them explicitly.  All GiNaC
718methods that transform expressions, like 'subs()' or 'normal()',
719automatically re-evaluate their results.
720
721
722File: ginac.info,  Node: Error handling,  Next: The class hierarchy,  Prev: Automatic evaluation,  Up: Basic concepts
723
7244.3 Error handling
725==================
726
727GiNaC reports run-time errors by throwing C++ exceptions.  All
728exceptions generated by GiNaC are subclassed from the standard
729'exception' class defined in the '<stdexcept>' header.  In addition to
730the predefined 'logic_error', 'domain_error', 'out_of_range',
731'invalid_argument', 'runtime_error', 'range_error' and 'overflow_error'
732types, GiNaC also defines a 'pole_error' exception that gets thrown when
733trying to evaluate a mathematical function at a singularity.
734
735The 'pole_error' class has a member function
736
737     int pole_error::degree() const;
738
739that returns the order of the singularity (or 0 when the pole is
740logarithmic or the order is undefined).
741
742When using GiNaC it is useful to arrange for exceptions to be caught in
743the main program even if you don't want to do any special error
744handling.  Otherwise whenever an error occurs in GiNaC, it will be
745delegated to the default exception handler of your C++ compiler's
746run-time system which usually only aborts the program without giving any
747information what went wrong.
748
749Here is an example for a 'main()' function that catches and prints
750exceptions generated by GiNaC:
751
752     #include <iostream>
753     #include <stdexcept>
754     #include <ginac/ginac.h>
755     using namespace std;
756     using namespace GiNaC;
757
758     int main()
759     {
760         try {
761             ...
762             // code using GiNaC
763             ...
764         } catch (exception &p) {
765             cerr << p.what() << endl;
766             return 1;
767         }
768         return 0;
769     }
770
771
772File: ginac.info,  Node: The class hierarchy,  Next: Symbols,  Prev: Error handling,  Up: Basic concepts
773
7744.4 The class hierarchy
775=======================
776
777GiNaC's class hierarchy consists of several classes representing
778mathematical objects, all of which (except for 'ex' and some helpers)
779are internally derived from one abstract base class called 'basic'.  You
780do not have to deal with objects of class 'basic', instead you'll be
781dealing with symbols, numbers, containers of expressions and so on.
782
783To get an idea about what kinds of symbolic composites may be built we
784have a look at the most important classes in the class hierarchy and
785some of the relations among the classes:
786
787<PICTURE MISSING>
788
789The abstract classes shown here (the ones without drop-shadow) are of no
790interest for the user.  They are used internally in order to avoid code
791duplication if two or more classes derived from them share certain
792features.  An example is 'expairseq', a container for a sequence of
793pairs each consisting of one expression and a number ('numeric').  What
794_is_ visible to the user are the derived classes 'add' and 'mul',
795representing sums and products.  *Note Internal structures::, where
796these two classes are described in more detail.  The following table
797shortly summarizes what kinds of mathematical objects are stored in the
798different classes:
799
800'symbol'         Algebraic symbols a, x, y...
801'constant'       Constants like Pi
802'numeric'        All kinds of numbers, 42, 7/3*I, 3.14159...
803'add'            Sums like x+y or a-(2*b)+3
804'mul'            Products like x*y or 2*a^2*(x+y+z)/b
805'ncmul'          Products of non-commutative objects
806'power'          Exponentials such as x^2, a^b, 'sqrt('2')' ...
807'pseries'        Power Series, e.g.  x-1/6*x^3+1/120*x^5+O(x^7)
808'function'       A symbolic function like sin(2*x)
809'lst'            Lists of expressions {x, 2*y, 3+z}
810'matrix'         mxn matrices of expressions
811'relational'     A relation like the identity x'=='y
812'indexed'        Indexed object like A_ij
813'tensor'         Special tensor like the delta and metric tensors
814'idx'            Index of an indexed object
815'varidx'         Index with variance
816'spinidx'        Index with variance and dot (used in
817                 Weyl-van-der-Waerden spinor formalism)
818'wildcard'       Wildcard for pattern matching
819'structure'      Template for user-defined classes
820
821
822File: ginac.info,  Node: Symbols,  Next: Numbers,  Prev: The class hierarchy,  Up: Basic concepts
823
8244.5 Symbols
825===========
826
827Symbolic indeterminates, or "symbols" for short, are for symbolic
828manipulation what atoms are for chemistry.
829
830A typical symbol definition looks like this:
831     symbol x("x");
832
833This definition actually contains three very different things:
834   * a C++ variable named 'x'
835   * a 'symbol' object stored in this C++ variable; this object
836     represents the symbol in a GiNaC expression
837   * the string '"x"' which is the name of the symbol, used (almost)
838     exclusively for printing expressions holding the symbol
839
840Symbols have an explicit name, supplied as a string during construction,
841because in C++, variable names can't be used as values, and the C++
842compiler throws them away during compilation.
843
844It is possible to omit the symbol name in the definition:
845     symbol x;
846
847In this case, GiNaC will assign the symbol an internal, unique name of
848the form 'symbolNNN'.  This won't affect the usability of the symbol but
849the output of your calculations will become more readable if you give
850your symbols sensible names (for intermediate expressions that are only
851used internally such anonymous symbols can be quite useful, however).
852
853Now, here is one important property of GiNaC that differentiates it from
854other computer algebra programs you may have used: GiNaC does _not_ use
855the names of symbols to tell them apart, but a (hidden) serial number
856that is unique for each newly created 'symbol' object.  If you want to
857use one and the same symbol in different places in your program, you
858must only create one 'symbol' object and pass that around.  If you
859create another symbol, even if it has the same name, GiNaC will treat it
860as a different indeterminate.
861
862Observe:
863     ex f(int n)
864     {
865         symbol x("x");
866         return pow(x, n);
867     }
868
869     int main()
870     {
871         symbol x("x");
872         ex e = f(6);
873
874         cout << e << endl;
875          // prints "x^6" which looks right, but...
876
877         cout << e.degree(x) << endl;
878          // ...this doesn't work. The symbol "x" here is different from the one
879          // in f() and in the expression returned by f(). Consequently, it
880          // prints "0".
881     }
882
883One possibility to ensure that 'f()' and 'main()' use the same symbol is
884to pass the symbol as an argument to 'f()':
885     ex f(int n, const ex & x)
886     {
887         return pow(x, n);
888     }
889
890     int main()
891     {
892         symbol x("x");
893
894         // Now, f() uses the same symbol.
895         ex e = f(6, x);
896
897         cout << e.degree(x) << endl;
898          // prints "6", as expected
899     }
900
901Another possibility would be to define a global symbol 'x' that is used
902by both 'f()' and 'main()'.  If you are using global symbols and
903multiple compilation units you must take special care, however.  Suppose
904that you have a header file 'globals.h' in your program that defines a
905'symbol x("x");'.  In this case, every unit that includes 'globals.h'
906would also get its own definition of 'x' (because header files are just
907inlined into the source code by the C++ preprocessor), and hence you
908would again end up with multiple equally-named, but different, symbols.
909Instead, the 'globals.h' header should only contain a _declaration_ like
910'extern symbol x;', with the definition of 'x' moved into a C++ source
911file such as 'globals.cpp'.
912
913A different approach to ensuring that symbols used in different parts of
914your program are identical is to create them with a _factory_ function
915like this one:
916     const symbol & get_symbol(const string & s)
917     {
918         static map<string, symbol> directory;
919         map<string, symbol>::iterator i = directory.find(s);
920         if (i != directory.end())
921             return i->second;
922         else
923             return directory.insert(make_pair(s, symbol(s))).first->second;
924     }
925
926This function returns one newly constructed symbol for each name that is
927passed in, and it returns the same symbol when called multiple times
928with the same name.  Using this symbol factory, we can rewrite our
929example like this:
930     ex f(int n)
931     {
932         return pow(get_symbol("x"), n);
933     }
934
935     int main()
936     {
937         ex e = f(6);
938
939         // Both calls of get_symbol("x") yield the same symbol.
940         cout << e.degree(get_symbol("x")) << endl;
941          // prints "6"
942     }
943
944Instead of creating symbols from strings we could also have
945'get_symbol()' take, for example, an integer number as its argument.  In
946this case, we would probably want to give the generated symbols names
947that include this number, which can be accomplished with the help of an
948'ostringstream'.
949
950In general, if you're getting weird results from GiNaC such as an
951expression 'x-x' that is not simplified to zero, you should check your
952symbol definitions.
953
954As we said, the names of symbols primarily serve for purposes of
955expression output.  But there are actually two instances where GiNaC
956uses the names for identifying symbols: When constructing an expression
957from a string, and when recreating an expression from an archive (*note
958Input/output::).
959
960In addition to its name, a symbol may contain a special string that is
961used in LaTeX output:
962     symbol x("x", "\\Box");
963
964This creates a symbol that is printed as "'x'" in normal output, but as
965"'\Box'" in LaTeX code (*Note Input/output::, for more information about
966the different output formats of expressions in GiNaC). GiNaC
967automatically creates proper LaTeX code for symbols having names of
968greek letters ('alpha', 'mu', etc.).  You can retrieve the name and the
969LaTeX name of a symbol using the respective methods:
970     symbol::get_name() const;
971     symbol::get_TeX_name() const;
972
973Symbols in GiNaC can't be assigned values.  If you need to store results
974of calculations and give them a name, use C++ variables of type 'ex'.
975If you want to replace a symbol in an expression with something else,
976you can invoke the expression's '.subs()' method (*note Substituting
977expressions::).
978
979By default, symbols are expected to stand in for complex values, i.e.
980they live in the complex domain.  As a consequence, operations like
981complex conjugation, for example (*note Complex expressions::), do _not_
982evaluate if applied to such symbols.  Likewise 'log(exp(x))' does not
983evaluate to 'x', because of the unknown imaginary part of 'x'.  On the
984other hand, if you are sure that your symbols will hold only real
985values, you would like to have such functions evaluated.  Therefore
986GiNaC allows you to specify the domain of the symbol.  Instead of
987'symbol x("x");' you can write 'realsymbol x("x");' to tell GiNaC that
988'x' stands in for real values.
989
990Furthermore, it is also possible to declare a symbol as positive.  This
991will, for instance, enable the automatic simplification of 'abs(x)' into
992'x'.  This is done by declaring the symbol as 'possymbol x("x");'.
993
994
995File: ginac.info,  Node: Numbers,  Next: Constants,  Prev: Symbols,  Up: Basic concepts
996
9974.6 Numbers
998===========
999
1000For storing numerical things, GiNaC uses Bruno Haible's library CLN. The
1001classes therein serve as foundation classes for GiNaC. CLN stands for
1002Class Library for Numbers or alternatively for Common Lisp Numbers.  In
1003order to find out more about CLN's internals, the reader is referred to
1004the documentation of that library.  *note (cln)Introduction::, for more
1005information.  Suffice to say that it is by itself build on top of
1006another library, the GNU Multiple Precision library GMP, which is an
1007extremely fast library for arbitrary long integers and rationals as well
1008as arbitrary precision floating point numbers.  It is very commonly used
1009by several popular cryptographic applications.  CLN extends GMP by
1010several useful things: First, it introduces the complex number field
1011over either reals (i.e.  floating point numbers with arbitrary
1012precision) or rationals.  Second, it automatically converts rationals to
1013integers if the denominator is unity and complex numbers to real numbers
1014if the imaginary part vanishes and also correctly treats algebraic
1015functions.  Third it provides good implementations of state-of-the-art
1016algorithms for all trigonometric and hyperbolic functions as well as for
1017calculation of some useful constants.
1018
1019The user can construct an object of class 'numeric' in several ways.
1020The following example shows the four most important constructors.  It
1021uses construction from C-integer, construction of fractions from two
1022integers, construction from C-float and construction from a string:
1023
1024     #include <iostream>
1025     #include <ginac/ginac.h>
1026     using namespace GiNaC;
1027
1028     int main()
1029     {
1030         numeric two = 2;                      // exact integer 2
1031         numeric r(2,3);                       // exact fraction 2/3
1032         numeric e(2.71828);                   // floating point number
1033         numeric p = "3.14159265358979323846"; // constructor from string
1034         // Trott's constant in scientific notation:
1035         numeric trott("1.0841015122311136151E-2");
1036
1037         std::cout << two*p << std::endl;  // floating point 6.283...
1038         ...
1039
1040The imaginary unit in GiNaC is a predefined 'numeric' object with the
1041name 'I':
1042
1043         ...
1044         numeric z1 = 2-3*I;                    // exact complex number 2-3i
1045         numeric z2 = 5.9+1.6*I;                // complex floating point number
1046     }
1047
1048It may be tempting to construct fractions by writing 'numeric r(3/2)'.
1049This would, however, call C's built-in operator '/' for integers first
1050and result in a numeric holding a plain integer 1.  *Never use the
1051operator '/' on integers* unless you know exactly what you are doing!
1052Use the constructor from two integers instead, as shown in the example
1053above.  Writing 'numeric(1)/2' may look funny but works also.
1054
1055We have seen now the distinction between exact numbers and floating
1056point numbers.  Clearly, the user should never have to worry about
1057dynamically created exact numbers, since their 'exactness' always
1058determines how they ought to be handled, i.e.  how 'long' they are.  The
1059situation is different for floating point numbers.  Their accuracy is
1060controlled by one _global_ variable, called 'Digits'.  (For those
1061readers who know about Maple: it behaves very much like Maple's
1062'Digits').  All objects of class numeric that are constructed from then
1063on will be stored with a precision matching that number of decimal
1064digits:
1065
1066     #include <iostream>
1067     #include <ginac/ginac.h>
1068     using namespace std;
1069     using namespace GiNaC;
1070
1071     void foo()
1072     {
1073         numeric three(3.0), one(1.0);
1074         numeric x = one/three;
1075
1076         cout << "in " << Digits << " digits:" << endl;
1077         cout << x << endl;
1078         cout << Pi.evalf() << endl;
1079     }
1080
1081     int main()
1082     {
1083         foo();
1084         Digits = 60;
1085         foo();
1086         return 0;
1087     }
1088
1089The above example prints the following output to screen:
1090
1091     in 17 digits:
1092     0.33333333333333333334
1093     3.1415926535897932385
1094     in 60 digits:
1095     0.33333333333333333333333333333333333333333333333333333333333333333334
1096     3.1415926535897932384626433832795028841971693993751058209749445923078
1097
1098Note that the last number is not necessarily rounded as you would
1099naively expect it to be rounded in the decimal system.  But note also,
1100that in both cases you got a couple of extra digits.  This is because
1101numbers are internally stored by CLN as chunks of binary digits in order
1102to match your machine's word size and to not waste precision.  Thus, on
1103architectures with different word size, the above output might even
1104differ with regard to actually computed digits.
1105
1106It should be clear that objects of class 'numeric' should be used for
1107constructing numbers or for doing arithmetic with them.  The objects one
1108deals with most of the time are the polymorphic expressions 'ex'.
1109
11104.6.1 Tests on numbers
1111----------------------
1112
1113Once you have declared some numbers, assigned them to expressions and
1114done some arithmetic with them it is frequently desired to retrieve some
1115kind of information from them like asking whether that number is
1116integer, rational, real or complex.  For those cases GiNaC provides
1117several useful methods.  (Internally, they fall back to invocations of
1118certain CLN functions.)
1119
1120As an example, let's construct some rational number, multiply it with
1121some multiple of its denominator and test what comes out:
1122
1123     #include <iostream>
1124     #include <ginac/ginac.h>
1125     using namespace std;
1126     using namespace GiNaC;
1127
1128     // some very important constants:
1129     const numeric twentyone(21);
1130     const numeric ten(10);
1131     const numeric five(5);
1132
1133     int main()
1134     {
1135         numeric answer = twentyone;
1136
1137         answer /= five;
1138         cout << answer.is_integer() << endl;  // false, it's 21/5
1139         answer *= ten;
1140         cout << answer.is_integer() << endl;  // true, it's 42 now!
1141     }
1142
1143Note that the variable 'answer' is constructed here as an integer by
1144'numeric''s copy constructor, but in an intermediate step it holds a
1145rational number represented as integer numerator and integer
1146denominator.  When multiplied by 10, the denominator becomes unity and
1147the result is automatically converted to a pure integer again.
1148Internally, the underlying CLN is responsible for this behavior and we
1149refer the reader to CLN's documentation.  Suffice to say that the same
1150behavior applies to complex numbers as well as return values of certain
1151functions.  Complex numbers are automatically converted to real numbers
1152if the imaginary part becomes zero.  The full set of tests that can be
1153applied is listed in the following table.
1154
1155*Method*               *Returns true if the object is...*
1156'.is_zero()'           ...equal to zero
1157'.is_positive()'       ...not complex and greater than 0
1158'.is_negative()'       ...not complex and smaller than 0
1159'.is_integer()'        ...a (non-complex) integer
1160'.is_pos_integer()'    ...an integer and greater than 0
1161'.is_nonneg_integer()' ...an integer and greater equal 0
1162'.is_even()'           ...an even integer
1163'.is_odd()'            ...an odd integer
1164'.is_prime()'          ...a prime integer (probabilistic primality
1165                       test)
1166'.is_rational()'       ...an exact rational number (integers are
1167                       rational, too)
1168'.is_real()'           ...a real integer, rational or float (i.e.  is
1169                       not complex)
1170'.is_cinteger()'       ...a (complex) integer (such as 2-3*I)
1171'.is_crational()'      ...an exact (complex) rational number (such as
1172                       2/3+7/2*I)
1173
11744.6.2 Numeric functions
1175-----------------------
1176
1177The following functions can be applied to 'numeric' objects and will be
1178evaluated immediately:
1179
1180*Name*                 *Function*
1181'inverse(z)'           returns 1/z
1182'pow(a, b)'            exponentiation a^b
1183'abs(z)'               absolute value
1184'real(z)'              real part
1185'imag(z)'              imaginary part
1186'csgn(z)'              complex sign (returns an 'int')
1187'step(x)'              step function (returns an 'numeric')
1188'numer(z)'             numerator of rational or complex rational number
1189'denom(z)'             denominator of rational or complex rational
1190                       number
1191'sqrt(z)'              square root
1192'isqrt(n)'             integer square root
1193'sin(z)'               sine
1194'cos(z)'               cosine
1195'tan(z)'               tangent
1196'asin(z)'              inverse sine
1197'acos(z)'              inverse cosine
1198'atan(z)'              inverse tangent
1199'atan(y, x)'           inverse tangent with two arguments
1200'sinh(z)'              hyperbolic sine
1201'cosh(z)'              hyperbolic cosine
1202'tanh(z)'              hyperbolic tangent
1203'asinh(z)'             inverse hyperbolic sine
1204'acosh(z)'             inverse hyperbolic cosine
1205'atanh(z)'             inverse hyperbolic tangent
1206'exp(z)'               exponential function
1207'log(z)'               natural logarithm
1208'Li2(z)'               dilogarithm
1209'zeta(z)'              Riemann's zeta function
1210'tgamma(z)'            gamma function
1211'lgamma(z)'            logarithm of gamma function
1212'psi(z)'               psi (digamma) function
1213'psi(n, z)'            derivatives of psi function (polygamma
1214                       functions)
1215'factorial(n)'         factorial function n!
1216'doublefactorial(n)'   double factorial function n!!
1217'binomial(n, k)'       binomial coefficients
1218'bernoulli(n)'         Bernoulli numbers
1219'fibonacci(n)'         Fibonacci numbers
1220'mod(a, b)'            modulus in positive representation (in the range
1221                       '[0, abs(b)-1]' with the sign of b, or zero)
1222'smod(a, b)'           modulus in symmetric representation (in the
1223                       range '[-iquo(abs(b), 2), iquo(abs(b), 2)]')
1224'irem(a, b)'           integer remainder (has the sign of a, or is
1225                       zero)
1226'irem(a, b, q)'        integer remainder and quotient, 'irem(a, b, q)
1227                       == a-q*b'
1228'iquo(a, b)'           integer quotient
1229'iquo(a, b, r)'        integer quotient and remainder, 'r == a-iquo(a,
1230                       b)*b'
1231'gcd(a, b)'            greatest common divisor
1232'lcm(a, b)'            least common multiple
1233
1234Most of these functions are also available as symbolic functions that
1235can be used in expressions (*note Mathematical functions::) or, like
1236'gcd()', as polynomial algorithms.
1237
12384.6.3 Converting numbers
1239------------------------
1240
1241Sometimes it is desirable to convert a 'numeric' object back to a
1242built-in arithmetic type ('int', 'double', etc.).  The 'numeric' class
1243provides a couple of methods for this purpose:
1244
1245     int numeric::to_int() const;
1246     long numeric::to_long() const;
1247     double numeric::to_double() const;
1248     cln::cl_N numeric::to_cl_N() const;
1249
1250'to_int()' and 'to_long()' only work when the number they are applied on
1251is an exact integer.  Otherwise the program will halt with a message
1252like 'Not a 32-bit integer'.  'to_double()' applied on a rational number
1253will return a floating-point approximation.  Both 'to_int()/to_long()'
1254and 'to_double()' discard the imaginary part of complex numbers.
1255
1256Note the signature of the above methods, you may need to apply a type
1257conversion and call 'evalf()' as shown in the following example:
1258         ...
1259         ex e1 = 1, e2 = sin(Pi/5);
1260         cout << ex_to<numeric>(e1).to_int() << endl
1261              << ex_to<numeric>(e2.evalf()).to_double() << endl;
1262         ...
1263
1264
1265File: ginac.info,  Node: Constants,  Next: Fundamental containers,  Prev: Numbers,  Up: Basic concepts
1266
12674.7 Constants
1268=============
1269
1270Constants behave pretty much like symbols except that they return some
1271specific number when the method '.evalf()' is called.
1272
1273The predefined known constants are:
1274
1275*Name*     *Common Name*           *Numerical Value (to 35 digits)*
1276'Pi'       Archimedes' constant    3.14159265358979323846264338327950288
1277'Catalan'  Catalan's constant      0.91596559417721901505460351493238411
1278'Euler'    Euler's (or             0.57721566490153286060651209008240243
1279           Euler-Mascheroni)
1280           constant
1281
1282
1283File: ginac.info,  Node: Fundamental containers,  Next: Lists,  Prev: Constants,  Up: Basic concepts
1284
12854.8 Sums, products and powers
1286=============================
1287
1288Simple rational expressions are written down in GiNaC pretty much like
1289in other CAS or like expressions involving numerical variables in C. The
1290necessary operators '+', '-', '*' and '/' have been overloaded to
1291achieve this goal.  When you run the following code snippet, the
1292constructor for an object of type 'mul' is automatically called to hold
1293the product of 'a' and 'b' and then the constructor for an object of
1294type 'add' is called to hold the sum of that 'mul' object and the number
1295one:
1296
1297         ...
1298         symbol a("a"), b("b");
1299         ex MyTerm = 1+a*b;
1300         ...
1301
1302For exponentiation, you have already seen the somewhat clumsy (though
1303C-ish) statement 'pow(x,2);' to represent 'x' squared.  This direct
1304construction is necessary since we cannot safely overload the
1305constructor '^' in C++ to construct a 'power' object.  If we did, it
1306would have several counterintuitive and undesired effects:
1307
1308   * Due to C's operator precedence, '2*x^2' would be parsed as
1309     '(2*x)^2'.
1310   * Due to the binding of the operator '^', 'x^a^b' would result in
1311     '(x^a)^b'.  This would be confusing since most (though not all)
1312     other CAS interpret this as 'x^(a^b)'.
1313   * Also, expressions involving integer exponents are very frequently
1314     used, which makes it even more dangerous to overload '^' since it
1315     is then hard to distinguish between the semantics as exponentiation
1316     and the one for exclusive or.  (It would be embarrassing to return
1317     '1' where one has requested '2^3'.)
1318
1319All effects are contrary to mathematical notation and differ from the
1320way most other CAS handle exponentiation, therefore overloading '^' is
1321ruled out for GiNaC's C++ part.  The situation is different in 'ginsh',
1322there the exponentiation-'^' exists.  (Also note that the other
1323frequently used exponentiation operator '**' does not exist at all in
1324C++).
1325
1326To be somewhat more precise, objects of the three classes described
1327here, are all containers for other expressions.  An object of class
1328'power' is best viewed as a container with two slots, one for the basis,
1329one for the exponent.  All valid GiNaC expressions can be inserted.
1330However, basic transformations like simplifying 'pow(pow(x,2),3)' to
1331'x^6' automatically are only performed when this is mathematically
1332possible.  If we replace the outer exponent three in the example by some
1333symbols 'a', the simplification is not safe and will not be performed,
1334since 'a' might be '1/2' and 'x' negative.
1335
1336Objects of type 'add' and 'mul' are containers with an arbitrary number
1337of slots for expressions to be inserted.  Again, simple and safe
1338simplifications are carried out like transforming '3*x+4-x' to '2*x+4'.
1339
1340
1341File: ginac.info,  Node: Lists,  Next: Mathematical functions,  Prev: Fundamental containers,  Up: Basic concepts
1342
13434.9 Lists of expressions
1344========================
1345
1346The GiNaC class 'lst' serves for holding a "list" of arbitrary
1347expressions.  They are not as ubiquitous as in many other computer
1348algebra packages, but are sometimes used to supply a variable number of
1349arguments of the same type to GiNaC methods such as 'subs()' and some
1350'matrix' constructors, so you should have a basic understanding of them.
1351
1352Lists can be constructed from an initializer list of expressions:
1353
1354     {
1355         symbol x("x"), y("y");
1356         lst l = {x, 2, y, x+y};
1357         // now, l is a list holding the expressions 'x', '2', 'y', and 'x+y',
1358         // in that order
1359         ...
1360
1361Use the 'nops()' method to determine the size (number of expressions) of
1362a list and the 'op()' method or the '[]' operator to access individual
1363elements:
1364
1365         ...
1366         cout << l.nops() << endl;                // prints '4'
1367         cout << l.op(2) << " " << l[0] << endl;  // prints 'y x'
1368         ...
1369
1370As with the standard 'list<T>' container, accessing random elements of a
1371'lst' is generally an operation of order O(N). Faster read-only
1372sequential access to the elements of a list is possible with the
1373iterator types provided by the 'lst' class:
1374
1375     typedef ... lst::const_iterator;
1376     typedef ... lst::const_reverse_iterator;
1377     lst::const_iterator lst::begin() const;
1378     lst::const_iterator lst::end() const;
1379     lst::const_reverse_iterator lst::rbegin() const;
1380     lst::const_reverse_iterator lst::rend() const;
1381
1382For example, to print the elements of a list individually you can use:
1383
1384         ...
1385         // O(N)
1386         for (lst::const_iterator i = l.begin(); i != l.end(); ++i)
1387             cout << *i << endl;
1388         ...
1389
1390which is one order faster than
1391
1392         ...
1393         // O(N^2)
1394         for (size_t i = 0; i < l.nops(); ++i)
1395             cout << l.op(i) << endl;
1396         ...
1397
1398These iterators also allow you to use some of the algorithms provided by
1399the C++ standard library:
1400
1401         ...
1402         // print the elements of the list (requires #include <iterator>)
1403         std::copy(l.begin(), l.end(), ostream_iterator<ex>(cout, "\n"));
1404
1405         // sum up the elements of the list (requires #include <numeric>)
1406         ex sum = std::accumulate(l.begin(), l.end(), ex(0));
1407         cout << sum << endl;  // prints '2+2*x+2*y'
1408         ...
1409
1410'lst' is one of the few GiNaC classes that allow in-place modifications
1411(the only other one is 'matrix').  You can modify single elements:
1412
1413         ...
1414         l[1] = 42;       // l is now {x, 42, y, x+y}
1415         l.let_op(1) = 7; // l is now {x, 7, y, x+y}
1416         ...
1417
1418You can append or prepend an expression to a list with the 'append()'
1419and 'prepend()' methods:
1420
1421         ...
1422         l.append(4*x);   // l is now {x, 7, y, x+y, 4*x}
1423         l.prepend(0);    // l is now {0, x, 7, y, x+y, 4*x}
1424         ...
1425
1426You can remove the first or last element of a list with 'remove_first()'
1427and 'remove_last()':
1428
1429         ...
1430         l.remove_first();   // l is now {x, 7, y, x+y, 4*x}
1431         l.remove_last();    // l is now {x, 7, y, x+y}
1432         ...
1433
1434You can remove all the elements of a list with 'remove_all()':
1435
1436         ...
1437         l.remove_all();     // l is now empty
1438         ...
1439
1440You can bring the elements of a list into a canonical order with
1441'sort()':
1442
1443         ...
1444         lst l1 = {x, 2, y, x+y};
1445         lst l2 = {2, x+y, x, y};
1446         l1.sort();
1447         l2.sort();
1448         // l1 and l2 are now equal
1449         ...
1450
1451Finally, you can remove all but the first element of consecutive groups
1452of elements with 'unique()':
1453
1454         ...
1455         lst l3 = {x, 2, 2, 2, y, x+y, y+x};
1456         l3.unique();        // l3 is now {x, 2, y, x+y}
1457     }
1458
1459
1460File: ginac.info,  Node: Mathematical functions,  Next: Relations,  Prev: Lists,  Up: Basic concepts
1461
14624.10 Mathematical functions
1463===========================
1464
1465There are quite a number of useful functions hard-wired into GiNaC. For
1466instance, all trigonometric and hyperbolic functions are implemented
1467(*Note Built-in functions::, for a complete list).
1468
1469These functions (better called _pseudofunctions_) are all objects of
1470class 'function'.  They accept one or more expressions as arguments and
1471return one expression.  If the arguments are not numerical, the
1472evaluation of the function may be halted, as it does in the next
1473example, showing how a function returns itself twice and finally an
1474expression that may be really useful:
1475
1476         ...
1477         symbol x("x"), y("y");
1478         ex foo = x+y/2;
1479         cout << tgamma(foo) << endl;
1480          // -> tgamma(x+(1/2)*y)
1481         ex bar = foo.subs(y==1);
1482         cout << tgamma(bar) << endl;
1483          // -> tgamma(x+1/2)
1484         ex foobar = bar.subs(x==7);
1485         cout << tgamma(foobar) << endl;
1486          // -> (135135/128)*Pi^(1/2)
1487         ...
1488
1489Besides evaluation most of these functions allow differentiation, series
1490expansion and so on.  Read the next chapter in order to learn more about
1491this.
1492
1493It must be noted that these pseudofunctions are created by inline
1494functions, where the argument list is templated.  This means that
1495whenever you call 'GiNaC::sin(1)' it is equivalent to 'sin(ex(1))' and
1496will therefore not result in a floating point number.  Unless of course
1497the function prototype is explicitly overridden - which is the case for
1498arguments of type 'numeric' (not wrapped inside an 'ex').  Hence, in
1499order to obtain a floating point number of class 'numeric' you should
1500call 'sin(numeric(1))'.  This is almost the same as calling
1501'sin(1).evalf()' except that the latter will return a numeric wrapped
1502inside an 'ex'.
1503
1504
1505File: ginac.info,  Node: Relations,  Next: Integrals,  Prev: Mathematical functions,  Up: Basic concepts
1506
15074.11 Relations
1508==============
1509
1510Sometimes, a relation holding between two expressions must be stored
1511somehow.  The class 'relational' is a convenient container for such
1512purposes.  A relation is by definition a container for two 'ex' and a
1513relation between them that signals equality, inequality and so on.  They
1514are created by simply using the C++ operators '==', '!=', '<', '<=', '>'
1515and '>=' between two expressions.
1516
1517*Note Mathematical functions::, for examples where various applications
1518of the '.subs()' method show how objects of class relational are used as
1519arguments.  There they provide an intuitive syntax for substitutions.
1520They are also used as arguments to the 'ex::series' method, where the
1521left hand side of the relation specifies the variable to expand in and
1522the right hand side the expansion point.  They can also be used for
1523creating systems of equations that are to be solved for unknown
1524variables.
1525
1526But the most common usage of objects of this class is rather
1527inconspicuous in statements of the form 'if
1528(expand(pow(a+b,2))==a*a+2*a*b+b*b) {...}'.  Here, an implicit
1529conversion from 'relational' to 'bool' takes place.  Note, however, that
1530'==' here does not perform any simplifications, hence 'expand()' must be
1531called explicitly.
1532
1533Simplifications of relationals may be more efficient if preceded by a
1534call to
1535     ex relational::canonical() const
1536which returns an equivalent relation with the zero right-hand side.  For
1537example:
1538     possymbol p("p");
1539     relational rel = (p >= (p*p-1)/p);
1540     if (ex_to<relational>(rel.canonical().normal()))
1541     	cout << "correct inequality" << endl;
1542However, a user shall not expect that any inequality can be fully
1543resolved by GiNaC.
1544
1545
1546File: ginac.info,  Node: Integrals,  Next: Matrices,  Prev: Relations,  Up: Basic concepts
1547
15484.12 Integrals
1549==============
1550
1551An object of class "integral" can be used to hold a symbolic integral.
1552If you want to symbolically represent the integral of 'x*x' from 0 to 1,
1553you would write this as
1554     integral(x, 0, 1, x*x)
1555The first argument is the integration variable.  It should be noted that
1556GiNaC is not very good (yet?)  at symbolically evaluating integrals.  In
1557fact, it can only integrate polynomials.  An expression containing
1558integrals can be evaluated symbolically by calling the
1559     .eval_integ()
1560method on it.  Numerical evaluation is available by calling the
1561     .evalf()
1562method on an expression containing the integral.  This will only
1563evaluate integrals into a number if 'subs'ing the integration variable
1564by a number in the fourth argument of an integral and then 'evalf'ing
1565the result always results in a number.  Of course, also the boundaries
1566of the integration domain must 'evalf' into numbers.  It should be noted
1567that trying to 'evalf' a function with discontinuities in the
1568integration domain is not recommended.  The accuracy of the numeric
1569evaluation of integrals is determined by the static member variable
1570     ex integral::relative_integration_error
1571of the class 'integral'.  The default value of this is 10^-8.  The
1572integration works by halving the interval of integration, until numeric
1573stability of the answer indicates that the requested accuracy has been
1574reached.  The maximum depth of the halving can be set via the static
1575member variable
1576     int integral::max_integration_level
1577The default value is 15.  If this depth is exceeded, 'evalf' will simply
1578return the integral unevaluated.  The function that performs the
1579numerical evaluation, is also available as
1580     ex adaptivesimpson(const ex & x, const ex & a, const ex & b, const ex & f,
1581                        const ex & error)
1582This function will throw an exception if the maximum depth is exceeded.
1583The last parameter of the function is optional and defaults to the
1584'relative_integration_error'.  To make sure that we do not do too much
1585work if an expression contains the same integral multiple times, a
1586lookup table is used.
1587
1588If you know that an expression holds an integral, you can get the
1589integration variable, the left boundary, right boundary and integrand by
1590respectively calling '.op(0)', '.op(1)', '.op(2)', and '.op(3)'.
1591Differentiating integrals with respect to variables works as expected.
1592Note that it makes no sense to differentiate an integral with respect to
1593the integration variable.
1594
1595
1596File: ginac.info,  Node: Matrices,  Next: Indexed objects,  Prev: Integrals,  Up: Basic concepts
1597
15984.13 Matrices
1599=============
1600
1601A "matrix" is a two-dimensional array of expressions.  The elements of a
1602matrix with m rows and n columns are accessed with two 'unsigned'
1603indices, the first one in the range 0...m-1, the second one in the range
16040...n-1.
1605
1606There are a couple of ways to construct matrices, with or without preset
1607elements.  The constructor
1608
1609     matrix::matrix(unsigned r, unsigned c);
1610
1611creates a matrix with 'r' rows and 'c' columns with all elements set to
1612zero.
1613
1614The easiest way to create a matrix is using an initializer list of
1615initializer lists, all of the same size:
1616
1617     {
1618         matrix m = {{1, -a},
1619                     {a,  1}};
1620     }
1621
1622You can also specify the elements as a (flat) list with
1623
1624     matrix::matrix(unsigned r, unsigned c, const lst & l);
1625
1626The function
1627
1628     ex lst_to_matrix(const lst & l);
1629
1630constructs a matrix from a list of lists, each list representing a
1631matrix row.
1632
1633There is also a set of functions for creating some special types of
1634matrices:
1635
1636     ex diag_matrix(const lst & l);
1637     ex diag_matrix(initializer_list<ex> l);
1638     ex unit_matrix(unsigned x);
1639     ex unit_matrix(unsigned r, unsigned c);
1640     ex symbolic_matrix(unsigned r, unsigned c, const string & base_name);
1641     ex symbolic_matrix(unsigned r, unsigned c, const string & base_name,
1642                        const string & tex_base_name);
1643
1644'diag_matrix()' constructs a square diagonal matrix given the diagonal
1645elements.  'unit_matrix()' creates an 'x' by 'x' (or 'r' by 'c') unit
1646matrix.  And finally, 'symbolic_matrix' constructs a matrix filled with
1647newly generated symbols made of the specified base name and the position
1648of each element in the matrix.
1649
1650Matrices often arise by omitting elements of another matrix.  For
1651instance, the submatrix 'S' of a matrix 'M' takes a rectangular block
1652from 'M'.  The reduced matrix 'R' is defined by removing one row and one
1653column from a matrix 'M'.  (The determinant of a reduced matrix is
1654called a _Minor_ of 'M' and can be used for computing the inverse using
1655Cramer's rule.)
1656
1657     ex sub_matrix(const matrix&m, unsigned r, unsigned nr, unsigned c, unsigned nc);
1658     ex reduced_matrix(const matrix& m, unsigned r, unsigned c);
1659
1660The function 'sub_matrix()' takes a row offset 'r' and a column offset
1661'c' and takes a block of 'nr' rows and 'nc' columns.  The function
1662'reduced_matrix()' has two integer arguments that specify which row and
1663column to remove:
1664
1665     {
1666         matrix m = {{11, 12, 13},
1667                     {21, 22, 23},
1668                     {31, 32, 33}};
1669         cout << reduced_matrix(m, 1, 1) << endl;
1670         // -> [[11,13],[31,33]]
1671         cout << sub_matrix(m, 1, 2, 1, 2) << endl;
1672         // -> [[22,23],[32,33]]
1673     }
1674
1675Matrix elements can be accessed and set using the parenthesis (function
1676call) operator:
1677
1678     const ex & matrix::operator()(unsigned r, unsigned c) const;
1679     ex & matrix::operator()(unsigned r, unsigned c);
1680
1681It is also possible to access the matrix elements in a linear fashion
1682with the 'op()' method.  But C++-style subscripting with square brackets
1683'[]' is not available.
1684
1685Here are a couple of examples for constructing matrices:
1686
1687     {
1688         symbol a("a"), b("b");
1689
1690         matrix M = {{a, 0},
1691                     {0, b}};
1692         cout << M << endl;
1693          // -> [[a,0],[0,b]]
1694
1695         matrix M2(2, 2);
1696         M2(0, 0) = a;
1697         M2(1, 1) = b;
1698         cout << M2 << endl;
1699          // -> [[a,0],[0,b]]
1700
1701         cout << matrix(2, 2, lst{a, 0, 0, b}) << endl;
1702          // -> [[a,0],[0,b]]
1703
1704         cout << lst_to_matrix(lst{lst{a, 0}, lst{0, b}}) << endl;
1705          // -> [[a,0],[0,b]]
1706
1707         cout << diag_matrix(lst{a, b}) << endl;
1708          // -> [[a,0],[0,b]]
1709
1710         cout << unit_matrix(3) << endl;
1711          // -> [[1,0,0],[0,1,0],[0,0,1]]
1712
1713         cout << symbolic_matrix(2, 3, "x") << endl;
1714          // -> [[x00,x01,x02],[x10,x11,x12]]
1715     }
1716
1717The method 'matrix::is_zero_matrix()' returns 'true' only if all entries
1718of the matrix are zeros.  There is also method 'ex::is_zero_matrix()'
1719which returns 'true' only if the expression is zero or a zero matrix.
1720
1721There are three ways to do arithmetic with matrices.  The first (and
1722most direct one) is to use the methods provided by the 'matrix' class:
1723
1724     matrix matrix::add(const matrix & other) const;
1725     matrix matrix::sub(const matrix & other) const;
1726     matrix matrix::mul(const matrix & other) const;
1727     matrix matrix::mul_scalar(const ex & other) const;
1728     matrix matrix::pow(const ex & expn) const;
1729     matrix matrix::transpose() const;
1730
1731All of these methods return the result as a new matrix object.  Here is
1732an example that calculates A*B-2*C for three matrices A, B and C:
1733
1734     {
1735         matrix A = {{ 1, 2},
1736                     { 3, 4}};
1737         matrix B = {{-1, 0},
1738                     { 2, 1}};
1739         matrix C = {{ 8, 4},
1740                     { 2, 1}};
1741
1742         matrix result = A.mul(B).sub(C.mul_scalar(2));
1743         cout << result << endl;
1744          // -> [[-13,-6],[1,2]]
1745         ...
1746     }
1747
1748The second (and probably the most natural) way is to construct an
1749expression containing matrices with the usual arithmetic operators and
1750'pow()'.  For efficiency reasons, expressions with sums, products and
1751powers of matrices are not automatically evaluated in GiNaC. You have to
1752call the method
1753
1754     ex ex::evalm() const;
1755
1756to obtain the result:
1757
1758     {
1759         ...
1760         ex e = A*B - 2*C;
1761         cout << e << endl;
1762          // -> [[1,2],[3,4]]*[[-1,0],[2,1]]-2*[[8,4],[2,1]]
1763         cout << e.evalm() << endl;
1764          // -> [[-13,-6],[1,2]]
1765         ...
1766     }
1767
1768The non-commutativity of the product 'A*B' in this example is
1769automatically recognized by GiNaC. There is no need to use a special
1770operator here.  *Note Non-commutative objects::, for more information
1771about dealing with non-commutative expressions.
1772
1773Finally, you can work with indexed matrices and call
1774'simplify_indexed()' to perform the arithmetic:
1775
1776     {
1777         ...
1778         idx i(symbol("i"), 2), j(symbol("j"), 2), k(symbol("k"), 2);
1779         e = indexed(A, i, k) * indexed(B, k, j) - 2 * indexed(C, i, j);
1780         cout << e << endl;
1781          // -> -2*[[8,4],[2,1]].i.j+[[-1,0],[2,1]].k.j*[[1,2],[3,4]].i.k
1782         cout << e.simplify_indexed() << endl;
1783          // -> [[-13,-6],[1,2]].i.j
1784     }
1785
1786Using indices is most useful when working with rectangular matrices and
1787one-dimensional vectors because you don't have to worry about having to
1788transpose matrices before multiplying them.  *Note Indexed objects::,
1789for more information about using matrices with indices, and about
1790indices in general.
1791
1792The 'matrix' class provides a couple of additional methods for computing
1793determinants, traces, characteristic polynomials and ranks:
1794
1795     ex matrix::determinant(unsigned algo=determinant_algo::automatic) const;
1796     ex matrix::trace() const;
1797     ex matrix::charpoly(const ex & lambda) const;
1798     unsigned matrix::rank(unsigned algo=solve_algo::automatic) const;
1799
1800The optional 'algo' argument of 'determinant()' and 'rank()' functions
1801allows to select between different algorithms for calculating the
1802determinant and rank respectively.  The asymptotic speed (as
1803parametrized by the matrix size) can greatly differ between those
1804algorithms, depending on the nature of the matrix' entries.  The
1805possible values are defined in the 'flags.h' header file.  By default,
1806GiNaC uses a heuristic to automatically select an algorithm that is
1807likely (but not guaranteed) to give the result most quickly.
1808
1809Linear systems can be solved with:
1810
1811     matrix matrix::solve(const matrix & vars, const matrix & rhs,
1812                          unsigned algo=solve_algo::automatic) const;
1813
1814Assuming the matrix object this method is applied on is an 'm' times 'n'
1815matrix, then 'vars' must be a 'n' times 'p' matrix of symbolic
1816indeterminates and 'rhs' a 'm' times 'p' matrix.  The returned matrix
1817then has dimension 'n' times 'p' and in the case of an underdetermined
1818system will still contain some of the indeterminates from 'vars'.  If
1819the system is overdetermined, an exception is thrown.
1820
1821To invert a matrix, use the method:
1822
1823     matrix matrix::inverse(unsigned algo=solve_algo::automatic) const;
1824
1825The 'algo' argument is optional.  If given, it must be one of
1826'solve_algo' defined in 'flags.h'.
1827
1828
1829File: ginac.info,  Node: Indexed objects,  Next: Non-commutative objects,  Prev: Matrices,  Up: Basic concepts
1830
18314.14 Indexed objects
1832====================
1833
1834GiNaC allows you to handle expressions containing general indexed
1835objects in arbitrary spaces.  It is also able to canonicalize and
1836simplify such expressions and perform symbolic dummy index summations.
1837There are a number of predefined indexed objects provided, like delta
1838and metric tensors.
1839
1840There are few restrictions placed on indexed objects and their indices
1841and it is easy to construct nonsense expressions, but our intention is
1842to provide a general framework that allows you to implement algorithms
1843with indexed quantities, getting in the way as little as possible.
1844
18454.14.1 Indexed quantities and their indices
1846-------------------------------------------
1847
1848Indexed expressions in GiNaC are constructed of two special types of
1849objects, "index objects" and "indexed objects".
1850
1851   * Index objects are of class 'idx' or a subclass.  Every index has a
1852     "value" and a "dimension" (which is the dimension of the space the
1853     index lives in) which can both be arbitrary expressions but are
1854     usually a number or a simple symbol.  In addition, indices of class
1855     'varidx' have a "variance" (they can be co- or contravariant), and
1856     indices of class 'spinidx' have a variance and can be "dotted" or
1857     "undotted".
1858
1859   * Indexed objects are of class 'indexed' or a subclass.  They contain
1860     a "base expression" (which is the expression being indexed), and
1861     one or more indices.
1862
1863*Please notice:* when printing expressions, covariant indices and
1864indices without variance are denoted '.i' while contravariant indices
1865are denoted '~i'.  Dotted indices have a '*' in front of the index
1866value.  In the following, we are going to use that notation in the text
1867so instead of A^i_jk we will write 'A~i.j.k'.  Index dimensions are not
1868visible in the output.
1869
1870A simple example shall illustrate the concepts:
1871
1872     #include <iostream>
1873     #include <ginac/ginac.h>
1874     using namespace std;
1875     using namespace GiNaC;
1876
1877     int main()
1878     {
1879         symbol i_sym("i"), j_sym("j");
1880         idx i(i_sym, 3), j(j_sym, 3);
1881
1882         symbol A("A");
1883         cout << indexed(A, i, j) << endl;
1884          // -> A.i.j
1885         cout << index_dimensions << indexed(A, i, j) << endl;
1886          // -> A.i[3].j[3]
1887         cout << dflt; // reset cout to default output format (dimensions hidden)
1888         ...
1889
1890The 'idx' constructor takes two arguments, the index value and the index
1891dimension.  First we define two index objects, 'i' and 'j', both with
1892the numeric dimension 3.  The value of the index 'i' is the symbol
1893'i_sym' (which prints as 'i') and the value of the index 'j' is the
1894symbol 'j_sym' (which prints as 'j').  Next we construct an expression
1895containing one indexed object, 'A.i.j'.  It has the symbol 'A' as its
1896base expression and the two indices 'i' and 'j'.
1897
1898The dimensions of indices are normally not visible in the output, but
1899one can request them to be printed with the 'index_dimensions'
1900manipulator, as shown above.
1901
1902Note the difference between the indices 'i' and 'j' which are of class
1903'idx', and the index values which are the symbols 'i_sym' and 'j_sym'.
1904The indices of indexed objects cannot directly be symbols or numbers but
1905must be index objects.  For example, the following is not correct and
1906will raise an exception:
1907
1908     symbol i("i"), j("j");
1909     e = indexed(A, i, j); // ERROR: indices must be of type idx
1910
1911You can have multiple indexed objects in an expression, index values can
1912be numeric, and index dimensions symbolic:
1913
1914         ...
1915         symbol B("B"), dim("dim");
1916         cout << 4 * indexed(A, i)
1917               + indexed(B, idx(j_sym, 4), idx(2, 3), idx(i_sym, dim)) << endl;
1918          // -> B.j.2.i+4*A.i
1919         ...
1920
1921'B' has a 4-dimensional symbolic index 'k', a 3-dimensional numeric
1922index of value 2, and a symbolic index 'i' with the symbolic dimension
1923'dim'.  Note that GiNaC doesn't automatically notify you that the free
1924indices of 'A' and 'B' in the sum don't match (you have to call
1925'simplify_indexed()' for that, see below).
1926
1927In fact, base expressions, index values and index dimensions can be
1928arbitrary expressions:
1929
1930         ...
1931         cout << indexed(A+B, idx(2*i_sym+1, dim/2)) << endl;
1932          // -> (B+A).(1+2*i)
1933         ...
1934
1935It's also possible to construct nonsense like 'Pi.sin(x)'.  You will not
1936get an error message from this but you will probably not be able to do
1937anything useful with it.
1938
1939The methods
1940
1941     ex idx::get_value();
1942     ex idx::get_dim();
1943
1944return the value and dimension of an 'idx' object.  If you have an index
1945in an expression, such as returned by calling '.op()' on an indexed
1946object, you can get a reference to the 'idx' object with the function
1947'ex_to<idx>()' on the expression.
1948
1949There are also the methods
1950
1951     bool idx::is_numeric();
1952     bool idx::is_symbolic();
1953     bool idx::is_dim_numeric();
1954     bool idx::is_dim_symbolic();
1955
1956for checking whether the value and dimension are numeric or symbolic
1957(non-numeric).  Using the 'info()' method of an index (see *note
1958Information about expressions::) returns information about the index
1959value.
1960
1961If you need co- and contravariant indices, use the 'varidx' class:
1962
1963         ...
1964         symbol mu_sym("mu"), nu_sym("nu");
1965         varidx mu(mu_sym, 4), nu(nu_sym, 4); // default is contravariant ~mu, ~nu
1966         varidx mu_co(mu_sym, 4, true);       // covariant index .mu
1967
1968         cout << indexed(A, mu, nu) << endl;
1969          // -> A~mu~nu
1970         cout << indexed(A, mu_co, nu) << endl;
1971          // -> A.mu~nu
1972         cout << indexed(A, mu.toggle_variance(), nu) << endl;
1973          // -> A.mu~nu
1974         ...
1975
1976A 'varidx' is an 'idx' with an additional flag that marks it as co- or
1977contravariant.  The default is a contravariant (upper) index, but this
1978can be overridden by supplying a third argument to the 'varidx'
1979constructor.  The two methods
1980
1981     bool varidx::is_covariant();
1982     bool varidx::is_contravariant();
1983
1984allow you to check the variance of a 'varidx' object (use
1985'ex_to<varidx>()' to get the object reference from an expression).
1986There's also the very useful method
1987
1988     ex varidx::toggle_variance();
1989
1990which makes a new index with the same value and dimension but the
1991opposite variance.  By using it you only have to define the index once.
1992
1993The 'spinidx' class provides dotted and undotted variant indices, as
1994used in the Weyl-van-der-Waerden spinor formalism:
1995
1996         ...
1997         symbol K("K"), C_sym("C"), D_sym("D");
1998         spinidx C(C_sym, 2), D(D_sym);          // default is 2-dimensional,
1999                                                 // contravariant, undotted
2000         spinidx C_co(C_sym, 2, true);           // covariant index
2001         spinidx D_dot(D_sym, 2, false, true);   // contravariant, dotted
2002         spinidx D_co_dot(D_sym, 2, true, true); // covariant, dotted
2003
2004         cout << indexed(K, C, D) << endl;
2005          // -> K~C~D
2006         cout << indexed(K, C_co, D_dot) << endl;
2007          // -> K.C~*D
2008         cout << indexed(K, D_co_dot, D) << endl;
2009          // -> K.*D~D
2010         ...
2011
2012A 'spinidx' is a 'varidx' with an additional flag that marks it as
2013dotted or undotted.  The default is undotted but this can be overridden
2014by supplying a fourth argument to the 'spinidx' constructor.  The two
2015methods
2016
2017     bool spinidx::is_dotted();
2018     bool spinidx::is_undotted();
2019
2020allow you to check whether or not a 'spinidx' object is dotted (use
2021'ex_to<spinidx>()' to get the object reference from an expression).
2022Finally, the two methods
2023
2024     ex spinidx::toggle_dot();
2025     ex spinidx::toggle_variance_dot();
2026
2027create a new index with the same value and dimension but opposite
2028dottedness and the same or opposite variance.
2029
20304.14.2 Substituting indices
2031---------------------------
2032
2033Sometimes you will want to substitute one symbolic index with another
2034symbolic or numeric index, for example when calculating one specific
2035element of a tensor expression.  This is done with the '.subs()' method,
2036as it is done for symbols (see *note Substituting expressions::).
2037
2038You have two possibilities here.  You can either substitute the whole
2039index by another index or expression:
2040
2041         ...
2042         ex e = indexed(A, mu_co);
2043         cout << e << " becomes " << e.subs(mu_co == nu) << endl;
2044          // -> A.mu becomes A~nu
2045         cout << e << " becomes " << e.subs(mu_co == varidx(0, 4)) << endl;
2046          // -> A.mu becomes A~0
2047         cout << e << " becomes " << e.subs(mu_co == 0) << endl;
2048          // -> A.mu becomes A.0
2049         ...
2050
2051The third example shows that trying to replace an index with something
2052that is not an index will substitute the index value instead.
2053
2054Alternatively, you can substitute the _symbol_ of a symbolic index by
2055another expression:
2056
2057         ...
2058         ex e = indexed(A, mu_co);
2059         cout << e << " becomes " << e.subs(mu_sym == nu_sym) << endl;
2060          // -> A.mu becomes A.nu
2061         cout << e << " becomes " << e.subs(mu_sym == 0) << endl;
2062          // -> A.mu becomes A.0
2063         ...
2064
2065As you see, with the second method only the value of the index will get
2066substituted.  Its other properties, including its dimension, remain
2067unchanged.  If you want to change the dimension of an index you have to
2068substitute the whole index by another one with the new dimension.
2069
2070Finally, substituting the base expression of an indexed object works as
2071expected:
2072
2073         ...
2074         ex e = indexed(A, mu_co);
2075         cout << e << " becomes " << e.subs(A == A+B) << endl;
2076          // -> A.mu becomes (B+A).mu
2077         ...
2078
20794.14.3 Symmetries
2080-----------------
2081
2082Indexed objects can have certain symmetry properties with respect to
2083their indices.  Symmetries are specified as a tree of objects of class
2084'symmetry' that is constructed with the helper functions
2085
2086     symmetry sy_none(...);
2087     symmetry sy_symm(...);
2088     symmetry sy_anti(...);
2089     symmetry sy_cycl(...);
2090
2091'sy_none()' stands for no symmetry, 'sy_symm()' and 'sy_anti()' specify
2092fully symmetric or antisymmetric, respectively, and 'sy_cycl()'
2093represents a cyclic symmetry.  Each of these functions accepts up to
2094four arguments which can be either symmetry objects themselves or
2095unsigned integer numbers that represent an index position (counting from
20960).  A symmetry specification that consists of only a single
2097'sy_symm()', 'sy_anti()' or 'sy_cycl()' with no arguments specifies the
2098respective symmetry for all indices.
2099
2100Here are some examples of symmetry definitions:
2101
2102         ...
2103         // No symmetry:
2104         e = indexed(A, i, j);
2105         e = indexed(A, sy_none(), i, j);     // equivalent
2106         e = indexed(A, sy_none(0, 1), i, j); // equivalent
2107
2108         // Symmetric in all three indices:
2109         e = indexed(A, sy_symm(), i, j, k);
2110         e = indexed(A, sy_symm(0, 1, 2), i, j, k); // equivalent
2111         e = indexed(A, sy_symm(2, 0, 1), i, j, k); // same symmetry, but yields a
2112                                                    // different canonical order
2113
2114         // Symmetric in the first two indices only:
2115         e = indexed(A, sy_symm(0, 1), i, j, k);
2116         e = indexed(A, sy_none(sy_symm(0, 1), 2), i, j, k); // equivalent
2117
2118         // Antisymmetric in the first and last index only (index ranges need not
2119         // be contiguous):
2120         e = indexed(A, sy_anti(0, 2), i, j, k);
2121         e = indexed(A, sy_none(sy_anti(0, 2), 1), i, j, k); // equivalent
2122
2123         // An example of a mixed symmetry: antisymmetric in the first two and
2124         // last two indices, symmetric when swapping the first and last index
2125         // pairs (like the Riemann curvature tensor):
2126         e = indexed(A, sy_symm(sy_anti(0, 1), sy_anti(2, 3)), i, j, k, l);
2127
2128         // Cyclic symmetry in all three indices:
2129         e = indexed(A, sy_cycl(), i, j, k);
2130         e = indexed(A, sy_cycl(0, 1, 2), i, j, k); // equivalent
2131
2132         // The following examples are invalid constructions that will throw
2133         // an exception at run time.
2134
2135         // An index may not appear multiple times:
2136         e = indexed(A, sy_symm(0, 0, 1), i, j, k); // ERROR
2137         e = indexed(A, sy_none(sy_symm(0, 1), sy_anti(0, 2)), i, j, k); // ERROR
2138
2139         // Every child of sy_symm(), sy_anti() and sy_cycl() must refer to the
2140         // same number of indices:
2141         e = indexed(A, sy_symm(sy_anti(0, 1), 2), i, j, k); // ERROR
2142
2143         // And of course, you cannot specify indices which are not there:
2144         e = indexed(A, sy_symm(0, 1, 2, 3), i, j, k); // ERROR
2145         ...
2146
2147If you need to specify more than four indices, you have to use the
2148'.add()' method of the 'symmetry' class.  For example, to specify full
2149symmetry in the first six indices you would write 'sy_symm(0, 1, 2,
21503).add(4).add(5)'.
2151
2152If an indexed object has a symmetry, GiNaC will automatically bring the
2153indices into a canonical order which allows for some immediate
2154simplifications:
2155
2156         ...
2157         cout << indexed(A, sy_symm(), i, j)
2158               + indexed(A, sy_symm(), j, i) << endl;
2159          // -> 2*A.j.i
2160         cout << indexed(B, sy_anti(), i, j)
2161               + indexed(B, sy_anti(), j, i) << endl;
2162          // -> 0
2163         cout << indexed(B, sy_anti(), i, j, k)
2164               - indexed(B, sy_anti(), j, k, i) << endl;
2165          // -> 0
2166         ...
2167
21684.14.4 Dummy indices
2169--------------------
2170
2171GiNaC treats certain symbolic index pairs as "dummy indices" meaning
2172that a summation over the index range is implied.  Symbolic indices
2173which are not dummy indices are called "free indices".  Numeric indices
2174are neither dummy nor free indices.
2175
2176To be recognized as a dummy index pair, the two indices must be of the
2177same class and their value must be the same single symbol (an index like
2178'2*n+1' is never a dummy index).  If the indices are of class 'varidx'
2179they must also be of opposite variance; if they are of class 'spinidx'
2180they must be both dotted or both undotted.
2181
2182The method '.get_free_indices()' returns a vector containing the free
2183indices of an expression.  It also checks that the free indices of the
2184terms of a sum are consistent:
2185
2186     {
2187         symbol A("A"), B("B"), C("C");
2188
2189         symbol i_sym("i"), j_sym("j"), k_sym("k"), l_sym("l");
2190         idx i(i_sym, 3), j(j_sym, 3), k(k_sym, 3), l(l_sym, 3);
2191
2192         ex e = indexed(A, i, j) * indexed(B, j, k) + indexed(C, k, l, i, l);
2193         cout << exprseq(e.get_free_indices()) << endl;
2194          // -> (.i,.k)
2195          // 'j' and 'l' are dummy indices
2196
2197         symbol mu_sym("mu"), nu_sym("nu"), rho_sym("rho"), sigma_sym("sigma");
2198         varidx mu(mu_sym, 4), nu(nu_sym, 4), rho(rho_sym, 4), sigma(sigma_sym, 4);
2199
2200         e = indexed(A, mu, nu) * indexed(B, nu.toggle_variance(), rho)
2201           + indexed(C, mu, sigma, rho, sigma.toggle_variance());
2202         cout << exprseq(e.get_free_indices()) << endl;
2203          // -> (~mu,~rho)
2204          // 'nu' is a dummy index, but 'sigma' is not
2205
2206         e = indexed(A, mu, mu);
2207         cout << exprseq(e.get_free_indices()) << endl;
2208          // -> (~mu)
2209          // 'mu' is not a dummy index because it appears twice with the same
2210          // variance
2211
2212         e = indexed(A, mu, nu) + 42;
2213         cout << exprseq(e.get_free_indices()) << endl; // ERROR
2214          // this will throw an exception:
2215          // "add::get_free_indices: inconsistent indices in sum"
2216     }
2217
2218A dummy index summation like a.i b~i can be expanded for indices with
2219numeric dimensions (e.g.  3) into the explicit sum like a.1 b~1 + a.2
2220b~2 + a.3 b~3.  This is performed by the function
2221
2222         ex expand_dummy_sum(const ex & e, bool subs_idx = false);
2223
2224which takes an expression 'e' and returns the expanded sum for all dummy
2225indices with numeric dimensions.  If the parameter 'subs_idx' is set to
2226'true' then all substitutions are made by 'idx' class indices, i.e.
2227without variance.  In this case the above sum a.i b~i will be expanded
2228to a.1 b.1 + a.2 b.2 + a.3 b.3.
2229
22304.14.5 Simplifying indexed expressions
2231--------------------------------------
2232
2233In addition to the few automatic simplifications that GiNaC performs on
2234indexed expressions (such as re-ordering the indices of symmetric
2235tensors and calculating traces and convolutions of matrices and
2236predefined tensors) there is the method
2237
2238     ex ex::simplify_indexed();
2239     ex ex::simplify_indexed(const scalar_products & sp);
2240
2241that performs some more expensive operations:
2242
2243   * it checks the consistency of free indices in sums in the same way
2244     'get_free_indices()' does
2245   * it tries to give dummy indices that appear in different terms of a
2246     sum the same name to allow simplifications like a_i*b_i-a_j*b_j=0
2247   * it (symbolically) calculates all possible dummy index
2248     summations/contractions with the predefined tensors (this will be
2249     explained in more detail in the next section)
2250   * it detects contractions that vanish for symmetry reasons, for
2251     example the contraction of a symmetric and a totally antisymmetric
2252     tensor
2253   * as a special case of dummy index summation, it can replace scalar
2254     products of two tensors with a user-defined value
2255
2256The last point is done with the help of the 'scalar_products' class
2257which is used to store scalar products with known values (this is not an
2258arithmetic class, you just pass it to 'simplify_indexed()'):
2259
2260     {
2261         symbol A("A"), B("B"), C("C"), i_sym("i");
2262         idx i(i_sym, 3);
2263
2264         scalar_products sp;
2265         sp.add(A, B, 0); // A and B are orthogonal
2266         sp.add(A, C, 0); // A and C are orthogonal
2267         sp.add(A, A, 4); // A^2 = 4 (A has length 2)
2268
2269         e = indexed(A + B, i) * indexed(A + C, i);
2270         cout << e << endl;
2271          // -> (B+A).i*(A+C).i
2272
2273         cout << e.expand(expand_options::expand_indexed).simplify_indexed(sp)
2274              << endl;
2275          // -> 4+C.i*B.i
2276     }
2277
2278The 'scalar_products' object 'sp' acts as a storage for the scalar
2279products added to it with the '.add()' method.  This method takes three
2280arguments: the two expressions of which the scalar product is taken, and
2281the expression to replace it with.
2282
2283The example above also illustrates a feature of the 'expand()' method:
2284if passed the 'expand_indexed' option it will distribute indices over
2285sums, so '(A+B).i' becomes 'A.i+B.i'.
2286
22874.14.6 Predefined tensors
2288-------------------------
2289
2290Some frequently used special tensors such as the delta, epsilon and
2291metric tensors are predefined in GiNaC. They have special properties
2292when contracted with other tensor expressions and some of them have
2293constant matrix representations (they will evaluate to a number when
2294numeric indices are specified).
2295
22964.14.6.1 Delta tensor
2297.....................
2298
2299The delta tensor takes two indices, is symmetric and has the matrix
2300representation 'diag(1, 1, 1, ...)'.  It is constructed by the function
2301'delta_tensor()':
2302
2303     {
2304         symbol A("A"), B("B");
2305
2306         idx i(symbol("i"), 3), j(symbol("j"), 3),
2307             k(symbol("k"), 3), l(symbol("l"), 3);
2308
2309         ex e = indexed(A, i, j) * indexed(B, k, l)
2310              * delta_tensor(i, k) * delta_tensor(j, l);
2311         cout << e.simplify_indexed() << endl;
2312          // -> B.i.j*A.i.j
2313
2314         cout << delta_tensor(i, i) << endl;
2315          // -> 3
2316     }
2317
23184.14.6.2 General metric tensor
2319..............................
2320
2321The function 'metric_tensor()' creates a general symmetric metric tensor
2322with two indices that can be used to raise/lower tensor indices.  The
2323metric tensor is denoted as 'g' in the output and if its indices are of
2324mixed variance it is automatically replaced by a delta tensor:
2325
2326     {
2327         symbol A("A");
2328
2329         varidx mu(symbol("mu"), 4), nu(symbol("nu"), 4), rho(symbol("rho"), 4);
2330
2331         ex e = metric_tensor(mu, nu) * indexed(A, nu.toggle_variance(), rho);
2332         cout << e.simplify_indexed() << endl;
2333          // -> A~mu~rho
2334
2335         e = delta_tensor(mu, nu.toggle_variance()) * metric_tensor(nu, rho);
2336         cout << e.simplify_indexed() << endl;
2337          // -> g~mu~rho
2338
2339         e = metric_tensor(mu.toggle_variance(), nu.toggle_variance())
2340           * metric_tensor(nu, rho);
2341         cout << e.simplify_indexed() << endl;
2342          // -> delta.mu~rho
2343
2344         e = metric_tensor(nu.toggle_variance(), rho.toggle_variance())
2345           * metric_tensor(mu, nu) * (delta_tensor(mu.toggle_variance(), rho)
2346             + indexed(A, mu.toggle_variance(), rho));
2347         cout << e.simplify_indexed() << endl;
2348          // -> 4+A.rho~rho
2349     }
2350
23514.14.6.3 Minkowski metric tensor
2352................................
2353
2354The Minkowski metric tensor is a special metric tensor with a constant
2355matrix representation which is either 'diag(1, -1, -1, ...)' (negative
2356signature, the default) or 'diag(-1, 1, 1, ...)' (positive signature).
2357It is created with the function 'lorentz_g()' (although it is output as
2358'eta'):
2359
2360     {
2361         varidx mu(symbol("mu"), 4);
2362
2363         e = delta_tensor(varidx(0, 4), mu.toggle_variance())
2364           * lorentz_g(mu, varidx(0, 4));       // negative signature
2365         cout << e.simplify_indexed() << endl;
2366          // -> 1
2367
2368         e = delta_tensor(varidx(0, 4), mu.toggle_variance())
2369           * lorentz_g(mu, varidx(0, 4), true); // positive signature
2370         cout << e.simplify_indexed() << endl;
2371          // -> -1
2372     }
2373
23744.14.6.4 Spinor metric tensor
2375.............................
2376
2377The function 'spinor_metric()' creates an antisymmetric tensor with two
2378indices that is used to raise/lower indices of 2-component spinors.  It
2379is output as 'eps':
2380
2381     {
2382         symbol psi("psi");
2383
2384         spinidx A(symbol("A")), B(symbol("B")), C(symbol("C"));
2385         ex A_co = A.toggle_variance(), B_co = B.toggle_variance();
2386
2387         e = spinor_metric(A, B) * indexed(psi, B_co);
2388         cout << e.simplify_indexed() << endl;
2389          // -> psi~A
2390
2391         e = spinor_metric(A, B) * indexed(psi, A_co);
2392         cout << e.simplify_indexed() << endl;
2393          // -> -psi~B
2394
2395         e = spinor_metric(A_co, B_co) * indexed(psi, B);
2396         cout << e.simplify_indexed() << endl;
2397          // -> -psi.A
2398
2399         e = spinor_metric(A_co, B_co) * indexed(psi, A);
2400         cout << e.simplify_indexed() << endl;
2401          // -> psi.B
2402
2403         e = spinor_metric(A_co, B_co) * spinor_metric(A, B);
2404         cout << e.simplify_indexed() << endl;
2405          // -> 2
2406
2407         e = spinor_metric(A_co, B_co) * spinor_metric(B, C);
2408         cout << e.simplify_indexed() << endl;
2409          // -> -delta.A~C
2410     }
2411
2412The matrix representation of the spinor metric is '[[0, 1], [-1, 0]]'.
2413
24144.14.6.5 Epsilon tensor
2415.......................
2416
2417The epsilon tensor is totally antisymmetric, its number of indices is
2418equal to the dimension of the index space (the indices must all be of
2419the same numeric dimension), and 'eps.1.2.3...' (resp.  'eps~0~1~2...')
2420is defined to be 1.  Its behavior with indices that have a variance also
2421depends on the signature of the metric.  Epsilon tensors are output as
2422'eps'.
2423
2424There are three functions defined to create epsilon tensors in 2, 3 and
24254 dimensions:
2426
2427     ex epsilon_tensor(const ex & i1, const ex & i2);
2428     ex epsilon_tensor(const ex & i1, const ex & i2, const ex & i3);
2429     ex lorentz_eps(const ex & i1, const ex & i2, const ex & i3, const ex & i4,
2430                    bool pos_sig = false);
2431
2432The first two functions create an epsilon tensor in 2 or 3 Euclidean
2433dimensions, the last function creates an epsilon tensor in a
24344-dimensional Minkowski space (the last 'bool' argument specifies
2435whether the metric has negative or positive signature, as in the case of
2436the Minkowski metric tensor):
2437
2438     {
2439         varidx mu(symbol("mu"), 4), nu(symbol("nu"), 4), rho(symbol("rho"), 4),
2440                sig(symbol("sig"), 4), lam(symbol("lam"), 4), bet(symbol("bet"), 4);
2441         e = lorentz_eps(mu, nu, rho, sig) *
2442             lorentz_eps(mu.toggle_variance(), nu.toggle_variance(), lam, bet);
2443         cout << simplify_indexed(e) << endl;
2444          // -> 2*eta~bet~rho*eta~sig~lam-2*eta~sig~bet*eta~rho~lam
2445
2446         idx i(symbol("i"), 3), j(symbol("j"), 3), k(symbol("k"), 3);
2447         symbol A("A"), B("B");
2448         e = epsilon_tensor(i, j, k) * indexed(A, j) * indexed(B, k);
2449         cout << simplify_indexed(e) << endl;
2450          // -> -B.k*A.j*eps.i.k.j
2451         e = epsilon_tensor(i, j, k) * indexed(A, j) * indexed(A, k);
2452         cout << simplify_indexed(e) << endl;
2453          // -> 0
2454     }
2455
24564.14.7 Linear algebra
2457---------------------
2458
2459The 'matrix' class can be used with indices to do some simple linear
2460algebra (linear combinations and products of vectors and matrices,
2461traces and scalar products):
2462
2463     {
2464         idx i(symbol("i"), 2), j(symbol("j"), 2);
2465         symbol x("x"), y("y");
2466
2467         // A is a 2x2 matrix, X is a 2x1 vector
2468         matrix A = {{1, 2},
2469                     {3, 4}};
2470         matrix X = {{x, y}};
2471
2472         cout << indexed(A, i, i) << endl;
2473          // -> 5
2474
2475         ex e = indexed(A, i, j) * indexed(X, j);
2476         cout << e.simplify_indexed() << endl;
2477          // -> [[2*y+x],[4*y+3*x]].i
2478
2479         e = indexed(A, i, j) * indexed(X, i) + indexed(X, j) * 2;
2480         cout << e.simplify_indexed() << endl;
2481          // -> [[3*y+3*x,6*y+2*x]].j
2482     }
2483
2484You can of course obtain the same results with the 'matrix::add()',
2485'matrix::mul()' and 'matrix::trace()' methods (*note Matrices::) but
2486with indices you don't have to worry about transposing matrices.
2487
2488Matrix indices always start at 0 and their dimension must match the
2489number of rows/columns of the matrix.  Matrices with one row or one
2490column are vectors and can have one or two indices (it doesn't matter
2491whether it's a row or a column vector).  Other matrices must have two
2492indices.
2493
2494You should be careful when using indices with variance on matrices.
2495GiNaC doesn't look at the variance and doesn't know that 'F~mu~nu' and
2496'F.mu.nu' are different matrices.  In this case you should use only one
2497form for 'F' and explicitly multiply it with a matrix representation of
2498the metric tensor.
2499
2500
2501File: ginac.info,  Node: Non-commutative objects,  Next: Methods and functions,  Prev: Indexed objects,  Up: Basic concepts
2502
25034.15 Non-commutative objects
2504============================
2505
2506GiNaC is equipped to handle certain non-commutative algebras.  Three
2507classes of non-commutative objects are built-in which are mostly of use
2508in high energy physics:
2509
2510   * Clifford (Dirac) algebra (class 'clifford')
2511   * su(3) Lie algebra (class 'color')
2512   * Matrices (unindexed) (class 'matrix')
2513
2514The 'clifford' and 'color' classes are subclasses of 'indexed' because
2515the elements of these algebras usually carry indices.  The 'matrix'
2516class is described in more detail in *note Matrices::.
2517
2518Unlike most computer algebra systems, GiNaC does not primarily provide
2519an operator (often denoted '&*') for representing inert products of
2520arbitrary objects.  Rather, non-commutativity in GiNaC is a property of
2521the classes of objects involved, and non-commutative products are formed
2522with the usual '*' operator, as are ordinary products.  GiNaC is capable
2523of figuring out by itself which objects commutate and will group the
2524factors by their class.  Consider this example:
2525
2526         ...
2527         varidx mu(symbol("mu"), 4), nu(symbol("nu"), 4);
2528         idx a(symbol("a"), 8), b(symbol("b"), 8);
2529         ex e = -dirac_gamma(mu) * (2*color_T(a)) * 8 * color_T(b) * dirac_gamma(nu);
2530         cout << e << endl;
2531          // -> -16*(gamma~mu*gamma~nu)*(T.a*T.b)
2532         ...
2533
2534As can be seen, GiNaC pulls out the overall commutative factor '-16' and
2535groups the non-commutative factors (the gammas and the su(3) generators)
2536together while preserving the order of factors within each class
2537(because Clifford objects commutate with color objects).  The resulting
2538expression is a _commutative_ product with two factors that are
2539themselves non-commutative products ('gamma~mu*gamma~nu' and 'T.a*T.b').
2540For clarification, parentheses are placed around the non-commutative
2541products in the output.
2542
2543Non-commutative products are internally represented by objects of the
2544class 'ncmul', as opposed to commutative products which are handled by
2545the 'mul' class.  You will normally not have to worry about this
2546distinction, though.
2547
2548The advantage of this approach is that you never have to worry about
2549using (or forgetting to use) a special operator when constructing
2550non-commutative expressions.  Also, non-commutative products in GiNaC
2551are more intelligent than in other computer algebra systems; they can,
2552for example, automatically canonicalize themselves according to rules
2553specified in the implementation of the non-commutative classes.  The
2554drawback is that to work with other than the built-in algebras you have
2555to implement new classes yourself.  Both symbols and user-defined
2556functions can be specified as being non-commutative.  For symbols, this
2557is done by subclassing class symbol; for functions, by explicitly
2558setting the return type (*note Symbolic functions::).
2559
2560Information about the commutativity of an object or expression can be
2561obtained with the two member functions
2562
2563     unsigned      ex::return_type() const;
2564     return_type_t ex::return_type_tinfo() const;
2565
2566The 'return_type()' function returns one of three values (defined in the
2567header file 'flags.h'), corresponding to three categories of expressions
2568in GiNaC:
2569
2570   * 'return_types::commutative': Commutates with everything.  Most
2571     GiNaC classes are of this kind.
2572   * 'return_types::noncommutative': Non-commutative, belonging to a
2573     certain class of non-commutative objects which can be determined
2574     with the 'return_type_tinfo()' method.  Expressions of this
2575     category commutate with everything except 'noncommutative'
2576     expressions of the same class.
2577   * 'return_types::noncommutative_composite': Non-commutative, composed
2578     of non-commutative objects of different classes.  Expressions of
2579     this category don't commutate with any other 'noncommutative' or
2580     'noncommutative_composite' expressions.
2581
2582The 'return_type_tinfo()' method returns an object of type
2583'return_type_t' that contains information about the type of the
2584expression and, if given, its representation label (see section on dirac
2585gamma matrices for more details).  The objects of type 'return_type_t'
2586can be tested for equality to test whether two expressions belong to the
2587same category and therefore may not commute.
2588
2589Here are a couple of examples:
2590
2591*Expression*                                *'return_type()'*
2592'42'                                        'commutative'
2593'2*x-y'                                     'commutative'
2594'dirac_ONE()'                               'noncommutative'
2595'dirac_gamma(mu)*dirac_gamma(nu)'           'noncommutative'
2596'2*color_T(a)'                              'noncommutative'
2597'dirac_ONE()*color_T(a)'                    'noncommutative_composite'
2598
2599A last note: With the exception of matrices, positive integer powers of
2600non-commutative objects are automatically expanded in GiNaC. For
2601example, 'pow(a*b, 2)' becomes 'a*b*a*b' if 'a' and 'b' are
2602non-commutative expressions).
2603
26044.15.1 Clifford algebra
2605-----------------------
2606
2607Clifford algebras are supported in two flavours: Dirac gamma matrices
2608(more physical) and generic Clifford algebras (more mathematical).
2609
26104.15.1.1 Dirac gamma matrices
2611.............................
2612
2613Dirac gamma matrices (note that GiNaC doesn't treat them as matrices)
2614are designated as 'gamma~mu' and satisfy 'gamma~mu*gamma~nu +
2615gamma~nu*gamma~mu = 2*eta~mu~nu' where 'eta~mu~nu' is the Minkowski
2616metric tensor.  Dirac gammas are constructed by the function
2617
2618     ex dirac_gamma(const ex & mu, unsigned char rl = 0);
2619
2620which takes two arguments: the index and a "representation label" in the
2621range 0 to 255 which is used to distinguish elements of different
2622Clifford algebras (this is also called a "spin line index").  Gammas
2623with different labels commutate with each other.  The dimension of the
2624index can be 4 or (in the framework of dimensional regularization) any
2625symbolic value.  Spinor indices on Dirac gammas are not supported in
2626GiNaC.
2627
2628The unity element of a Clifford algebra is constructed by
2629
2630     ex dirac_ONE(unsigned char rl = 0);
2631
2632*Please notice:* You must always use 'dirac_ONE()' when referring to
2633multiples of the unity element, even though it's customary to omit it.
2634E.g.  instead of 'dirac_gamma(mu)*(dirac_slash(q,4)+m)' you have to
2635write 'dirac_gamma(mu)*(dirac_slash(q,4)+m*dirac_ONE())'.  Otherwise,
2636GiNaC will complain and/or produce incorrect results.
2637
2638There is a special element 'gamma5' that commutates with all other
2639gammas, has a unit square, and in 4 dimensions equals 'gamma~0 gamma~1
2640gamma~2 gamma~3', provided by
2641
2642     ex dirac_gamma5(unsigned char rl = 0);
2643
2644The chiral projectors '(1+/-gamma5)/2' are also available as proper
2645objects, constructed by
2646
2647     ex dirac_gammaL(unsigned char rl = 0);
2648     ex dirac_gammaR(unsigned char rl = 0);
2649
2650They observe the relations 'gammaL^2 = gammaL', 'gammaR^2 = gammaR', and
2651'gammaL gammaR = gammaR gammaL = 0'.
2652
2653Finally, the function
2654
2655     ex dirac_slash(const ex & e, const ex & dim, unsigned char rl = 0);
2656
2657creates a term that represents a contraction of 'e' with the Dirac
2658Lorentz vector (it behaves like a term of the form 'e.mu gamma~mu' with
2659a unique index whose dimension is given by the 'dim' argument).  Such
2660slashed expressions are printed with a trailing backslash, e.g.  'e\'.
2661
2662In products of dirac gammas, superfluous unity elements are
2663automatically removed, squares are replaced by their values, and
2664'gamma5', 'gammaL' and 'gammaR' are moved to the front.
2665
2666The 'simplify_indexed()' function performs contractions in gamma
2667strings, for example
2668
2669     {
2670         ...
2671         symbol a("a"), b("b"), D("D");
2672         varidx mu(symbol("mu"), D);
2673         ex e = dirac_gamma(mu) * dirac_slash(a, D)
2674              * dirac_gamma(mu.toggle_variance());
2675         cout << e << endl;
2676          // -> gamma~mu*a\*gamma.mu
2677         e = e.simplify_indexed();
2678         cout << e << endl;
2679          // -> -D*a\+2*a\
2680         cout << e.subs(D == 4) << endl;
2681          // -> -2*a\
2682         ...
2683     }
2684
2685To calculate the trace of an expression containing strings of Dirac
2686gammas you use one of the functions
2687
2688     ex dirac_trace(const ex & e, const std::set<unsigned char> & rls,
2689                    const ex & trONE = 4);
2690     ex dirac_trace(const ex & e, const lst & rll, const ex & trONE = 4);
2691     ex dirac_trace(const ex & e, unsigned char rl = 0, const ex & trONE = 4);
2692
2693These functions take the trace over all gammas in the specified set
2694'rls' or list 'rll' of representation labels, or the single label 'rl';
2695gammas with other labels are left standing.  The last argument to
2696'dirac_trace()' is the value to be returned for the trace of the unity
2697element, which defaults to 4.
2698
2699The 'dirac_trace()' function is a linear functional that is equal to the
2700ordinary matrix trace only in D = 4 dimensions.  In particular, the
2701functional is not cyclic in D != 4 dimensions when acting on expressions
2702containing 'gamma5', so it's not a proper trace.  This 'gamma5' scheme
2703is described in greater detail in the article 'The Role of gamma5 in
2704Dimensional Regularization' (*note Bibliography::).
2705
2706The value of the trace itself is also usually different in 4 and in D !=
27074 dimensions:
2708
2709     {
2710         // 4 dimensions
2711         varidx mu(symbol("mu"), 4), nu(symbol("nu"), 4), rho(symbol("rho"), 4);
2712         ex e = dirac_gamma(mu) * dirac_gamma(nu) *
2713                dirac_gamma(mu.toggle_variance()) * dirac_gamma(rho);
2714         cout << dirac_trace(e).simplify_indexed() << endl;
2715          // -> -8*eta~rho~nu
2716     }
2717     ...
2718     {
2719         // D dimensions
2720         symbol D("D");
2721         varidx mu(symbol("mu"), D), nu(symbol("nu"), D), rho(symbol("rho"), D);
2722         ex e = dirac_gamma(mu) * dirac_gamma(nu) *
2723                dirac_gamma(mu.toggle_variance()) * dirac_gamma(rho);
2724         cout << dirac_trace(e).simplify_indexed() << endl;
2725          // -> 8*eta~rho~nu-4*eta~rho~nu*D
2726     }
2727
2728Here is an example for using 'dirac_trace()' to compute a value that
2729appears in the calculation of the one-loop vacuum polarization amplitude
2730in QED:
2731
2732     {
2733         symbol q("q"), l("l"), m("m"), ldotq("ldotq"), D("D");
2734         varidx mu(symbol("mu"), D), nu(symbol("nu"), D);
2735
2736         scalar_products sp;
2737         sp.add(l, l, pow(l, 2));
2738         sp.add(l, q, ldotq);
2739
2740         ex e = dirac_gamma(mu) *
2741                (dirac_slash(l, D) + dirac_slash(q, D) + m * dirac_ONE()) *
2742                dirac_gamma(mu.toggle_variance()) *
2743                (dirac_slash(l, D) + m * dirac_ONE());
2744         e = dirac_trace(e).simplify_indexed(sp);
2745         e = e.collect(lst{l, ldotq, m});
2746         cout << e << endl;
2747          // -> (8-4*D)*l^2+(8-4*D)*ldotq+4*D*m^2
2748     }
2749
2750The 'canonicalize_clifford()' function reorders all gamma products that
2751appear in an expression to a canonical (but not necessarily simple)
2752form.  You can use this to compare two expressions or for further
2753simplifications:
2754
2755     {
2756         varidx mu(symbol("mu"), 4), nu(symbol("nu"), 4);
2757         ex e = dirac_gamma(mu) * dirac_gamma(nu) + dirac_gamma(nu) * dirac_gamma(mu);
2758         cout << e << endl;
2759          // -> gamma~mu*gamma~nu+gamma~nu*gamma~mu
2760
2761         e = canonicalize_clifford(e);
2762         cout << e << endl;
2763          // -> 2*ONE*eta~mu~nu
2764     }
2765
27664.15.1.2 A generic Clifford algebra
2767...................................
2768
2769A generic Clifford algebra, i.e.  a 2^n dimensional algebra with
2770generators e_k satisfying the identities e~i e~j + e~j e~i = M(i, j) +
2771M(j, i) for some bilinear form ('metric') M(i, j), which may be
2772non-symmetric (see arXiv:math.QA/9911180) and contain symbolic entries.
2773Such generators are created by the function
2774
2775         ex clifford_unit(const ex & mu, const ex & metr, unsigned char rl = 0);
2776
2777where 'mu' should be a 'idx' (or descendant) class object indexing the
2778generators.  Parameter 'metr' defines the metric M(i, j) and can be
2779represented by a square 'matrix', 'tensormetric' or 'indexed' class
2780object.  In fact, any expression either with two free indices or without
2781indices at all is admitted as 'metr'.  In the later case an 'indexed'
2782object with two newly created indices with 'metr' as its 'op(0)' will be
2783used.  Optional parameter 'rl' allows to distinguish different Clifford
2784algebras, which will commute with each other.
2785
2786Note that the call 'clifford_unit(mu, minkmetric())' creates something
2787very close to 'dirac_gamma(mu)', although 'dirac_gamma' have more
2788efficient simplification mechanism.  Also, the object created by
2789'clifford_unit(mu, minkmetric())' is not aware about the symmetry of its
2790metric, see the start of the previous paragraph.  A more accurate analog
2791of 'dirac_gamma(mu)' should be specifies as follows:
2792
2793         clifford_unit(mu, indexed(minkmetric(),sy_symm(),varidx(symbol("i"),4),varidx(symbol("j"),4)));
2794
2795The method 'clifford::get_metric()' returns a metric defining this
2796Clifford number.
2797
2798If the matrix M(i, j) is in fact symmetric you may prefer to create the
2799Clifford algebra units with a call like that
2800
2801         ex e = clifford_unit(mu, indexed(M, sy_symm(), i, j));
2802
2803since this may yield some further automatic simplifications.  Again, for
2804a metric defined through a 'matrix' such a symmetry is detected
2805automatically.
2806
2807Individual generators of a Clifford algebra can be accessed in several
2808ways.  For example
2809
2810     {
2811         ...
2812         idx i(symbol("i"), 4);
2813         realsymbol s("s");
2814         ex M = diag_matrix(lst{1, -1, 0, s});
2815         ex e = clifford_unit(i, M);
2816         ex e0 = e.subs(i == 0);
2817         ex e1 = e.subs(i == 1);
2818         ex e2 = e.subs(i == 2);
2819         ex e3 = e.subs(i == 3);
2820         ...
2821     }
2822
2823will produce four anti-commuting generators of a Clifford algebra with
2824properties 'pow(e0, 2) = 1', 'pow(e1, 2) = -1', 'pow(e2, 2) = 0' and
2825'pow(e3, 2) = s'.
2826
2827A similar effect can be achieved from the function
2828
2829         ex lst_to_clifford(const ex & v, const ex & mu,  const ex & metr,
2830                            unsigned char rl = 0);
2831         ex lst_to_clifford(const ex & v, const ex & e);
2832
2833which converts a list or vector 'v = (v~0, v~1, ..., v~n)' into the
2834Clifford number 'v~0 e.0 + v~1 e.1 + ... + v~n e.n' with 'e.k' directly
2835supplied in the second form of the procedure.  In the first form the
2836Clifford unit 'e.k' is generated by the call of 'clifford_unit(mu, metr,
2837rl)'.  If the number of components supplied by 'v' exceeds the
2838dimensionality of the Clifford unit 'e' by 1 then function
2839'lst_to_clifford()' uses the following pseudo-vector representation:
2840'v~0 ONE + v~1 e.0 + v~2 e.1 + ... + v~[n+1] e.n'
2841
2842The previous code may be rewritten with the help of 'lst_to_clifford()'
2843as follows
2844
2845     {
2846         ...
2847         idx i(symbol("i"), 4);
2848         realsymbol s("s");
2849         ex M = diag_matrix({1, -1, 0, s});
2850         ex e0 = lst_to_clifford(lst{1, 0, 0, 0}, i, M);
2851         ex e1 = lst_to_clifford(lst{0, 1, 0, 0}, i, M);
2852         ex e2 = lst_to_clifford(lst{0, 0, 1, 0}, i, M);
2853         ex e3 = lst_to_clifford(lst{0, 0, 0, 1}, i, M);
2854       ...
2855     }
2856
2857There is the inverse function
2858
2859         lst clifford_to_lst(const ex & e, const ex & c, bool algebraic = true);
2860
2861which takes an expression 'e' and tries to find a list 'v = (v~0, v~1,
2862..., v~n)' such that the expression is either vector 'e = v~0 c.0 + v~1
2863c.1 + ... + v~n c.n' or pseudo-vector 'v~0 ONE + v~1 e.0 + v~2 e.1 + ...
2864+ v~[n+1] e.n' with respect to the given Clifford units 'c'.  Here none
2865of the 'v~k' should contain Clifford units 'c' (of course, this may be
2866impossible).  This function can use an 'algebraic' method (default) or a
2867symbolic one.  With the 'algebraic' method the 'v~k' are calculated as
2868'(e c.k + c.k e)/pow(c.k, 2)'.  If 'pow(c.k, 2)' is zero or is not
2869'numeric' for some 'k' then the method will be automatically changed to
2870symbolic.  The same effect is obtained by the assignment ('algebraic =
2871false') in the procedure call.
2872
2873There are several functions for (anti-)automorphisms of Clifford
2874algebras:
2875
2876         ex clifford_prime(const ex & e)
2877         inline ex clifford_star(const ex & e)
2878         inline ex clifford_bar(const ex & e)
2879
2880The automorphism of a Clifford algebra 'clifford_prime()' simply changes
2881signs of all Clifford units in the expression.  The reversion of a
2882Clifford algebra 'clifford_star()' reverses the order of Clifford units
2883in any product.  Finally the main anti-automorphism of a Clifford
2884algebra 'clifford_bar()' is the composition of the previous two, i.e.
2885it makes the reversion and changes signs of all Clifford units in a
2886product.  These functions correspond to the notations e', e* and
2887'\bar{e}' used in Clifford algebra textbooks.
2888
2889The function
2890
2891         ex clifford_norm(const ex & e);
2892
2893calculates the norm of a Clifford number from the expression '||e||^2 =
2894e \bar{e}' The inverse of a Clifford expression is returned by the
2895function
2896
2897         ex clifford_inverse(const ex & e);
2898
2899which calculates it as e^{-1} = \bar{e}/||e||^2 If ||e||=0 then an
2900exception is raised.
2901
2902If a Clifford number happens to be a factor of 'dirac_ONE()' then we can
2903convert it to a "real" (non-Clifford) expression by the function
2904
2905         ex remove_dirac_ONE(const ex & e);
2906
2907The function 'canonicalize_clifford()' works for a generic Clifford
2908algebra in a similar way as for Dirac gammas.
2909
2910The next provided function is
2911
2912         ex clifford_moebius_map(const ex & a, const ex & b, const ex & c,
2913                                 const ex & d, const ex & v, const ex & G,
2914                                 unsigned char rl = 0);
2915         ex clifford_moebius_map(const ex & M, const ex & v, const ex & G,
2916                                 unsigned char rl = 0);
2917
2918It takes a list or vector 'v' and makes the Moebius (conformal or
2919linear-fractional) transformation 'v -> (av+b)/(cv+d)' defined by the
2920matrix 'M = [[a, b], [c, d]]'.  The parameter 'G' defines the metric of
2921the surrounding (pseudo-)Euclidean space.  This can be an indexed
2922object, tensormetric, matrix or a Clifford unit, in the later case the
2923optional parameter 'rl' is ignored even if supplied.  Depending from the
2924type of 'v' the returned value of this function is either a vector or a
2925list holding vector's components.
2926
2927Finally the function
2928
2929     char clifford_max_label(const ex & e, bool ignore_ONE = false);
2930
2931can detect a presence of Clifford objects in the expression 'e': if such
2932objects are found it returns the maximal 'representation_label' of them,
2933otherwise '-1'.  The optional parameter 'ignore_ONE' indicates if
2934'dirac_ONE' objects should be ignored during the search.
2935
2936LaTeX output for Clifford units looks like '\clifford[1]{e}^{{\nu}}',
2937where '1' is the 'representation_label' and '\nu' is the index of the
2938corresponding unit.  This provides a flexible typesetting with a
2939suitable definition of the '\clifford' command.  For example, the
2940definition
2941         \newcommand{\clifford}[1][]{}
2942typesets all Clifford units identically, while the alternative
2943definition
2944         \newcommand{\clifford}[2][]{\ifcase #1 #2\or \tilde{#2} \or \breve{#2} \fi}
2945prints units with 'representation_label=0' as 'e', with
2946'representation_label=1' as '\tilde{e}' and with
2947'representation_label=2' as '\breve{e}'.
2948
29494.15.2 Color algebra
2950--------------------
2951
2952For computations in quantum chromodynamics, GiNaC implements the base
2953elements and structure constants of the su(3) Lie algebra (color
2954algebra).  The base elements T_a are constructed by the function
2955
2956     ex color_T(const ex & a, unsigned char rl = 0);
2957
2958which takes two arguments: the index and a "representation label" in the
2959range 0 to 255 which is used to distinguish elements of different color
2960algebras.  Objects with different labels commutate with each other.  The
2961dimension of the index must be exactly 8 and it should be of class
2962'idx', not 'varidx'.
2963
2964The unity element of a color algebra is constructed by
2965
2966     ex color_ONE(unsigned char rl = 0);
2967
2968*Please notice:* You must always use 'color_ONE()' when referring to
2969multiples of the unity element, even though it's customary to omit it.
2970E.g.  instead of 'color_T(a)*(color_T(b)*indexed(X,b)+1)' you have to
2971write 'color_T(a)*(color_T(b)*indexed(X,b)+color_ONE())'.  Otherwise,
2972GiNaC may produce incorrect results.
2973
2974The functions
2975
2976     ex color_d(const ex & a, const ex & b, const ex & c);
2977     ex color_f(const ex & a, const ex & b, const ex & c);
2978
2979create the symmetric and antisymmetric structure constants d_abc and
2980f_abc which satisfy {T_a, T_b} = 1/3 delta_ab + d_abc T_c and [T_a, T_b]
2981= i f_abc T_c.
2982
2983These functions evaluate to their numerical values, if you supply
2984numeric indices to them.  The index values should be in the range from 1
2985to 8, not from 0 to 7.  This departure from usual conventions goes along
2986better with the notations used in physical literature.
2987
2988There's an additional function
2989
2990     ex color_h(const ex & a, const ex & b, const ex & c);
2991
2992which returns the linear combination 'color_d(a, b, c)+I*color_f(a, b,
2993c)'.
2994
2995The function 'simplify_indexed()' performs some simplifications on
2996expressions containing color objects:
2997
2998     {
2999         ...
3000         idx a(symbol("a"), 8), b(symbol("b"), 8), c(symbol("c"), 8),
3001             k(symbol("k"), 8), l(symbol("l"), 8);
3002
3003         e = color_d(a, b, l) * color_f(a, b, k);
3004         cout << e.simplify_indexed() << endl;
3005          // -> 0
3006
3007         e = color_d(a, b, l) * color_d(a, b, k);
3008         cout << e.simplify_indexed() << endl;
3009          // -> 5/3*delta.k.l
3010
3011         e = color_f(l, a, b) * color_f(a, b, k);
3012         cout << e.simplify_indexed() << endl;
3013          // -> 3*delta.k.l
3014
3015         e = color_h(a, b, c) * color_h(a, b, c);
3016         cout << e.simplify_indexed() << endl;
3017          // -> -32/3
3018
3019         e = color_h(a, b, c) * color_T(b) * color_T(c);
3020         cout << e.simplify_indexed() << endl;
3021          // -> -2/3*T.a
3022
3023         e = color_h(a, b, c) * color_T(a) * color_T(b) * color_T(c);
3024         cout << e.simplify_indexed() << endl;
3025          // -> -8/9*ONE
3026
3027         e = color_T(k) * color_T(a) * color_T(b) * color_T(k);
3028         cout << e.simplify_indexed() << endl;
3029          // -> 1/4*delta.b.a*ONE-1/6*T.a*T.b
3030         ...
3031
3032To calculate the trace of an expression containing color objects you use
3033one of the functions
3034
3035     ex color_trace(const ex & e, const std::set<unsigned char> & rls);
3036     ex color_trace(const ex & e, const lst & rll);
3037     ex color_trace(const ex & e, unsigned char rl = 0);
3038
3039These functions take the trace over all color 'T' objects in the
3040specified set 'rls' or list 'rll' of representation labels, or the
3041single label 'rl'; 'T's with other labels are left standing.  For
3042example:
3043
3044         ...
3045         e = color_trace(4 * color_T(a) * color_T(b) * color_T(c));
3046         cout << e << endl;
3047          // -> -I*f.a.c.b+d.a.c.b
3048     }
3049
3050
3051File: ginac.info,  Node: Methods and functions,  Next: Information about expressions,  Prev: Non-commutative objects,  Up: Top
3052
30535 Methods and functions
3054***********************
3055
3056In this chapter the most important algorithms provided by GiNaC will be
3057described.  Some of them are implemented as functions on expressions,
3058others are implemented as methods provided by expression objects.  If
3059they are methods, there exists a wrapper function around it, so you can
3060alternatively call it in a functional way as shown in the simple
3061example:
3062
3063         ...
3064         cout << "As method:   " << sin(1).evalf() << endl;
3065         cout << "As function: " << evalf(sin(1)) << endl;
3066         ...
3067
3068The general rule is that wherever methods accept one or more parameters
3069(ARG1, ARG2, ...) the order of arguments the function wrapper accepts is
3070the same but preceded by the object to act on (OBJECT, ARG1, ARG2, ...).
3071This approach is the most natural one in an OO model but it may lead to
3072confusion for MapleV users because where they would type 'A:=x+1;
3073subs(x=2,A);' GiNaC would require 'A=x+1; subs(A,x==2);' (after proper
3074declaration of 'A' and 'x').  On the other hand, since MapleV returns 3
3075on 'A:=x^2+3; coeff(A,x,0);' (GiNaC: 'A=pow(x,2)+3; coeff(A,x,0);') it
3076is clear that MapleV is not trying to be consistent here.  Also, users
3077of MuPAD will in most cases feel more comfortable with GiNaC's
3078convention.  All function wrappers are implemented as simple inline
3079functions which just call the corresponding method and are only provided
3080for users uncomfortable with OO who are dead set to avoid method
3081invocations.  Generally, nested function wrappers are much harder to
3082read than a sequence of methods and should therefore be avoided if
3083possible.  On the other hand, not everything in GiNaC is a method on
3084class 'ex' and sometimes calling a function cannot be avoided.
3085
3086* Menu:
3087
3088* Information about expressions::
3089* Numerical evaluation::
3090* Substituting expressions::
3091* Pattern matching and advanced substitutions::
3092* Applying a function on subexpressions::
3093* Visitors and tree traversal::
3094* Polynomial arithmetic::           Working with polynomials.
3095* Rational expressions::            Working with rational functions.
3096* Symbolic differentiation::
3097* Series expansion::                Taylor and Laurent expansion.
3098* Symmetrization::
3099* Built-in functions::              List of predefined mathematical functions.
3100* Multiple polylogarithms::
3101* Iterated integrals::
3102* Complex expressions::
3103* Solving linear systems of equations::
3104* Input/output::                    Input and output of expressions.
3105
3106
3107File: ginac.info,  Node: Information about expressions,  Next: Numerical evaluation,  Prev: Methods and functions,  Up: Methods and functions
3108
31095.1 Getting information about expressions
3110=========================================
3111
31125.1.1 Checking expression types
3113-------------------------------
3114
3115Sometimes it's useful to check whether a given expression is a plain
3116number, a sum, a polynomial with integer coefficients, or of some other
3117specific type.  GiNaC provides a couple of functions for this:
3118
3119     bool is_a<T>(const ex & e);
3120     bool is_exactly_a<T>(const ex & e);
3121     bool ex::info(unsigned flag);
3122     unsigned ex::return_type() const;
3123     return_type_t ex::return_type_tinfo() const;
3124
3125When the test made by 'is_a<T>()' returns true, it is safe to call one
3126of the functions 'ex_to<T>()', where 'T' is one of the class names
3127(*Note The class hierarchy::, for a list of all classes).  For example,
3128assuming 'e' is an 'ex':
3129
3130     {
3131         ...
3132         if (is_a<numeric>(e))
3133             numeric n = ex_to<numeric>(e);
3134         ...
3135     }
3136
3137'is_a<T>(e)' allows you to check whether the top-level object of an
3138expression 'e' is an instance of the GiNaC class 'T' (*Note The class
3139hierarchy::, for a list of all classes).  This is most useful, e.g., for
3140checking whether an expression is a number, a sum, or a product:
3141
3142     {
3143         symbol x("x");
3144         ex e1 = 42;
3145         ex e2 = 4*x - 3;
3146         is_a<numeric>(e1);  // true
3147         is_a<numeric>(e2);  // false
3148         is_a<add>(e1);      // false
3149         is_a<add>(e2);      // true
3150         is_a<mul>(e1);      // false
3151         is_a<mul>(e2);      // false
3152     }
3153
3154In contrast, 'is_exactly_a<T>(e)' allows you to check whether the
3155top-level object of an expression 'e' is an instance of the GiNaC class
3156'T', not including parent classes.
3157
3158The 'info()' method is used for checking certain attributes of
3159expressions.  The possible values for the 'flag' argument are defined in
3160'ginac/flags.h', the most important being explained in the following
3161table:
3162
3163*Flag*                 *Returns true if the object is...*
3164'numeric'              ...a number (same as 'is_a<numeric>(...)')
3165'real'                 ...a real number, symbol or constant (i.e.  is
3166                       not complex)
3167'rational'             ...an exact rational number (integers are
3168                       rational, too)
3169'integer'              ...a (non-complex) integer
3170'crational'            ...an exact (complex) rational number (such as
3171                       2/3+7/2*I)
3172'cinteger'             ...a (complex) integer (such as 2-3*I)
3173'positive'             ...not complex and greater than 0
3174'negative'             ...not complex and less than 0
3175'nonnegative'          ...not complex and greater than or equal to 0
3176'posint'               ...an integer greater than 0
3177'negint'               ...an integer less than 0
3178'nonnegint'            ...an integer greater than or equal to 0
3179'even'                 ...an even integer
3180'odd'                  ...an odd integer
3181'prime'                ...a prime integer (probabilistic primality
3182                       test)
3183'relation'             ...a relation (same as 'is_a<relational>(...)')
3184'relation_equal'       ...a '==' relation
3185'relation_not_equal'   ...a '!=' relation
3186'relation_less'        ...a '<' relation
3187'relation_less_or_equal'...a '<=' relation
3188'relation_greater'     ...a '>' relation
3189'relation_greater_or_equal'...a '>=' relation
3190'symbol'               ...a symbol (same as 'is_a<symbol>(...)')
3191'list'                 ...a list (same as 'is_a<lst>(...)')
3192'polynomial'           ...a polynomial (i.e.  only consists of sums and
3193                       products of numbers and symbols with positive
3194                       integer powers)
3195'integer_polynomial'   ...a polynomial with (non-complex) integer
3196                       coefficients
3197'cinteger_polynomial'  ...a polynomial with (possibly complex) integer
3198                       coefficients (such as 2-3*I)
3199'rational_polynomial'  ...a polynomial with (non-complex) rational
3200                       coefficients
3201'crational_polynomial' ...a polynomial with (possibly complex) rational
3202                       coefficients (such as 2/3+7/2*I)
3203'rational_function'    ...a rational function (x+y, z/(x+y))
3204
3205To determine whether an expression is commutative or non-commutative and
3206if so, with which other expressions it would commutate, you use the
3207methods 'return_type()' and 'return_type_tinfo()'.  *Note
3208Non-commutative objects::, for an explanation of these.
3209
32105.1.2 Accessing subexpressions
3211------------------------------
3212
3213Many GiNaC classes, like 'add', 'mul', 'lst', and 'function', act as
3214containers for subexpressions.  For example, the subexpressions of a sum
3215(an 'add' object) are the individual terms, and the subexpressions of a
3216'function' are the function's arguments.
3217
3218GiNaC provides several ways of accessing subexpressions.  The first way
3219is to use the two methods
3220
3221     size_t ex::nops();
3222     ex ex::op(size_t i);
3223
3224'nops()' determines the number of subexpressions (operands) contained in
3225the expression, while 'op(i)' returns the 'i'-th (0..'nops()-1')
3226subexpression.  In the case of a 'power' object, 'op(0)' will return the
3227basis and 'op(1)' the exponent.  For 'indexed' objects, 'op(0)' is the
3228base expression and 'op(i)', i>0 are the indices.
3229
3230The second way to access subexpressions is via the STL-style
3231random-access iterator class 'const_iterator' and the methods
3232
3233     const_iterator ex::begin();
3234     const_iterator ex::end();
3235
3236'begin()' returns an iterator referring to the first subexpression;
3237'end()' returns an iterator which is one-past the last subexpression.
3238If the expression has no subexpressions, then 'begin() == end()'.  These
3239iterators can also be used in conjunction with non-modifying STL
3240algorithms.
3241
3242Here is an example that (non-recursively) prints the subexpressions of a
3243given expression in three different ways:
3244
3245     {
3246         ex e = ...
3247
3248         // with nops()/op()
3249         for (size_t i = 0; i != e.nops(); ++i)
3250             cout << e.op(i) << endl;
3251
3252         // with iterators
3253         for (const_iterator i = e.begin(); i != e.end(); ++i)
3254             cout << *i << endl;
3255
3256         // with iterators and STL copy()
3257         std::copy(e.begin(), e.end(), std::ostream_iterator<ex>(cout, "\n"));
3258     }
3259
3260'op()'/'nops()' and 'const_iterator' only access an expression's
3261immediate children.  GiNaC provides two additional iterator classes,
3262'const_preorder_iterator' and 'const_postorder_iterator', that iterate
3263over all objects in an expression tree, in preorder or postorder,
3264respectively.  They are STL-style forward iterators, and are created
3265with the methods
3266
3267     const_preorder_iterator ex::preorder_begin();
3268     const_preorder_iterator ex::preorder_end();
3269     const_postorder_iterator ex::postorder_begin();
3270     const_postorder_iterator ex::postorder_end();
3271
3272The following example illustrates the differences between
3273'const_iterator', 'const_preorder_iterator', and
3274'const_postorder_iterator':
3275
3276     {
3277         symbol A("A"), B("B"), C("C");
3278         ex e = lst{lst{A, B}, C};
3279
3280         std::copy(e.begin(), e.end(),
3281                   std::ostream_iterator<ex>(cout, "\n"));
3282         // {A,B}
3283         // C
3284
3285         std::copy(e.preorder_begin(), e.preorder_end(),
3286                   std::ostream_iterator<ex>(cout, "\n"));
3287         // {{A,B},C}
3288         // {A,B}
3289         // A
3290         // B
3291         // C
3292
3293         std::copy(e.postorder_begin(), e.postorder_end(),
3294                   std::ostream_iterator<ex>(cout, "\n"));
3295         // A
3296         // B
3297         // {A,B}
3298         // C
3299         // {{A,B},C}
3300     }
3301
3302Finally, the left-hand side and right-hand side expressions of objects
3303of class 'relational' (and only of these) can also be accessed with the
3304methods
3305
3306     ex ex::lhs();
3307     ex ex::rhs();
3308
33095.1.3 Comparing expressions
3310---------------------------
3311
3312Expressions can be compared with the usual C++ relational operators like
3313'==', '>', and '<' but if the expressions contain symbols, the result is
3314usually not determinable and the result will be 'false', except in the
3315case of the '!=' operator.  You should also be aware that GiNaC will
3316only do the most trivial test for equality (subtracting both
3317expressions), so something like '(pow(x,2)+x)/x==x+1' will return
3318'false'.
3319
3320Actually, if you construct an expression like 'a == b', this will be
3321represented by an object of the 'relational' class (*note Relations::)
3322which is not evaluated until (explicitly or implicitly) cast to a
3323'bool'.
3324
3325There are also two methods
3326
3327     bool ex::is_equal(const ex & other);
3328     bool ex::is_zero();
3329
3330for checking whether one expression is equal to another, or equal to
3331zero, respectively.  See also the method 'ex::is_zero_matrix()', *note
3332Matrices::.
3333
33345.1.4 Ordering expressions
3335--------------------------
3336
3337Sometimes it is necessary to establish a mathematically well-defined
3338ordering on a set of arbitrary expressions, for example to use
3339expressions as keys in a 'std::map<>' container, or to bring a vector of
3340expressions into a canonical order (which is done internally by GiNaC
3341for sums and products).
3342
3343The operators '<', '>' etc.  described in the last section cannot be
3344used for this, as they don't implement an ordering relation in the
3345mathematical sense.  In particular, they are not guaranteed to be
3346antisymmetric: if 'a' and 'b' are different expressions, and 'a < b'
3347yields 'false', then 'b < a' doesn't necessarily yield 'true'.
3348
3349By default, STL classes and algorithms use the '<' and '==' operators to
3350compare objects, which are unsuitable for expressions, but GiNaC
3351provides two functors that can be supplied as proper binary comparison
3352predicates to the STL:
3353
3354     class ex_is_less {
3355     public:
3356         bool operator()(const ex &lh, const ex &rh) const;
3357     };
3358
3359     class ex_is_equal {
3360     public:
3361         bool operator()(const ex &lh, const ex &rh) const;
3362     };
3363
3364For example, to define a 'map' that maps expressions to strings you have
3365to use
3366
3367     std::map<ex, std::string, ex_is_less> myMap;
3368
3369Omitting the 'ex_is_less' template parameter will introduce spurious
3370bugs because the map operates improperly.
3371
3372Other examples for the use of the functors:
3373
3374     std::vector<ex> v;
3375     // fill vector
3376     ...
3377
3378     // sort vector
3379     std::sort(v.begin(), v.end(), ex_is_less());
3380
3381     // count the number of expressions equal to '1'
3382     unsigned num_ones = std::count_if(v.begin(), v.end(),
3383                                       [](const ex& e) { return ex_is_equal()(e, 1); });
3384
3385The implementation of 'ex_is_less' uses the member function
3386
3387     int ex::compare(const ex & other) const;
3388
3389which returns 0 if '*this' and 'other' are equal, -1 if '*this' sorts
3390before 'other', and 1 if '*this' sorts after 'other'.
3391
3392
3393File: ginac.info,  Node: Numerical evaluation,  Next: Substituting expressions,  Prev: Information about expressions,  Up: Methods and functions
3394
33955.2 Numerical evaluation
3396========================
3397
3398GiNaC keeps algebraic expressions, numbers and constants in their exact
3399form.  To evaluate them using floating-point arithmetic you need to call
3400
3401     ex ex::evalf() const;
3402
3403The accuracy of the evaluation is controlled by the global object
3404'Digits' which can be assigned an integer value.  The default value of
3405'Digits' is 17.  *Note Numbers::, for more information and examples.
3406
3407To evaluate an expression to a 'double' floating-point number you can
3408call 'evalf()' followed by 'numeric::to_double()', like this:
3409
3410     {
3411         // Approximate sin(x/Pi)
3412         symbol x("x");
3413         ex e = series(sin(x/Pi), x == 0, 6);
3414
3415         // Evaluate numerically at x=0.1
3416         ex f = evalf(e.subs(x == 0.1));
3417
3418         // ex_to<numeric> is an unsafe cast, so check the type first
3419         if (is_a<numeric>(f)) {
3420             double d = ex_to<numeric>(f).to_double();
3421             cout << d << endl;
3422              // -> 0.0318256
3423         } else
3424             // error
3425     }
3426
3427
3428File: ginac.info,  Node: Substituting expressions,  Next: Pattern matching and advanced substitutions,  Prev: Numerical evaluation,  Up: Methods and functions
3429
34305.3 Substituting expressions
3431============================
3432
3433Algebraic objects inside expressions can be replaced with arbitrary
3434expressions via the '.subs()' method:
3435
3436     ex ex::subs(const ex & e, unsigned options = 0);
3437     ex ex::subs(const exmap & m, unsigned options = 0);
3438     ex ex::subs(const lst & syms, const lst & repls, unsigned options = 0);
3439
3440In the first form, 'subs()' accepts a relational of the form 'object ==
3441expression' or a 'lst' of such relationals:
3442
3443     {
3444         symbol x("x"), y("y");
3445
3446         ex e1 = 2*x*x-4*x+3;
3447         cout << "e1(7) = " << e1.subs(x == 7) << endl;
3448          // -> 73
3449
3450         ex e2 = x*y + x;
3451         cout << "e2(-2, 4) = " << e2.subs(lst{x == -2, y == 4}) << endl;
3452          // -> -10
3453     }
3454
3455If you specify multiple substitutions, they are performed in parallel,
3456so e.g.  'subs(lst{x == y, y == x})' exchanges 'x' and 'y'.
3457
3458The second form of 'subs()' takes an 'exmap' object which is a pair
3459associative container that maps expressions to expressions (currently
3460implemented as a 'std::map').  This is the most efficient one of the
3461three 'subs()' forms and should be used when the number of objects to be
3462substituted is large or unknown.
3463
3464Using this form, the second example from above would look like this:
3465
3466     {
3467         symbol x("x"), y("y");
3468         ex e2 = x*y + x;
3469
3470         exmap m;
3471         m[x] = -2;
3472         m[y] = 4;
3473         cout << "e2(-2, 4) = " << e2.subs(m) << endl;
3474     }
3475
3476The third form of 'subs()' takes two lists, one for the objects to be
3477replaced and one for the expressions to be substituted (both lists must
3478contain the same number of elements).  Using this form, you would write
3479
3480     {
3481         symbol x("x"), y("y");
3482         ex e2 = x*y + x;
3483
3484         cout << "e2(-2, 4) = " << e2.subs(lst{x, y}, lst{-2, 4}) << endl;
3485     }
3486
3487The optional last argument to 'subs()' is a combination of
3488'subs_options' flags.  There are three options available:
3489'subs_options::no_pattern' disables pattern matching, which makes large
3490'subs()' operations significantly faster if you are not using patterns.
3491The second option, 'subs_options::algebraic' enables algebraic
3492substitutions in products and powers.  *Note Pattern matching and
3493advanced substitutions::, for more information about patterns and
3494algebraic substitutions.  The third option,
3495'subs_options::no_index_renaming' disables the feature that dummy
3496indices are renamed if the substitution could give a result in which a
3497dummy index occurs more than two times.  This is sometimes necessary if
3498you want to use 'subs()' to rename your dummy indices.
3499
3500'subs()' performs syntactic substitution of any complete algebraic
3501object; it does not try to match sub-expressions as is demonstrated by
3502the following example:
3503
3504     {
3505         symbol x("x"), y("y"), z("z");
3506
3507         ex e1 = pow(x+y, 2);
3508         cout << e1.subs(x+y == 4) << endl;
3509          // -> 16
3510
3511         ex e2 = sin(x)*sin(y)*cos(x);
3512         cout << e2.subs(sin(x) == cos(x)) << endl;
3513          // -> cos(x)^2*sin(y)
3514
3515         ex e3 = x+y+z;
3516         cout << e3.subs(x+y == 4) << endl;
3517          // -> x+y+z
3518          // (and not 4+z as one might expect)
3519     }
3520
3521A more powerful form of substitution using wildcards is described in the
3522next section.
3523
3524
3525File: ginac.info,  Node: Pattern matching and advanced substitutions,  Next: Applying a function on subexpressions,  Prev: Substituting expressions,  Up: Methods and functions
3526
35275.4 Pattern matching and advanced substitutions
3528===============================================
3529
3530GiNaC allows the use of patterns for checking whether an expression is
3531of a certain form or contains subexpressions of a certain form, and for
3532substituting expressions in a more general way.
3533
3534A "pattern" is an algebraic expression that optionally contains
3535wildcards.  A "wildcard" is a special kind of object (of class
3536'wildcard') that represents an arbitrary expression.  Every wildcard has
3537a "label" which is an unsigned integer number to allow having multiple
3538different wildcards in a pattern.  Wildcards are printed as '$label'
3539(this is also the way they are specified in 'ginsh').  In C++ code,
3540wildcard objects are created with the call
3541
3542     ex wild(unsigned label = 0);
3543
3544which is simply a wrapper for the 'wildcard()' constructor with a
3545shorter name.
3546
3547Some examples for patterns:
3548
3549*Constructed as*                     *Output as*
3550'wild()'                             '$0'
3551'pow(x,wild())'                      'x^$0'
3552'atan2(wild(1),wild(2))'             'atan2($1,$2)'
3553'indexed(A,idx(wild(),3))'           'A.$0'
3554
3555Notes:
3556
3557   * Wildcards behave like symbols and are subject to the same algebraic
3558     rules.  E.g., '$0+2*$0' is automatically transformed to '3*$0'.
3559   * As shown in the last example, to use wildcards for indices you have
3560     to use them as the value of an 'idx' object.  This is because
3561     indices must always be of class 'idx' (or a subclass).
3562   * Wildcards only represent expressions or subexpressions.  It is not
3563     possible to use them as placeholders for other properties like
3564     index dimension or variance, representation labels, symmetry of
3565     indexed objects etc.
3566   * Because wildcards are commutative, it is not possible to use
3567     wildcards as part of noncommutative products.
3568   * A pattern does not have to contain wildcards.  'x' and 'x+y' are
3569     also valid patterns.
3570
35715.4.1 Matching expressions
3572--------------------------
3573
3574The most basic application of patterns is to check whether an expression
3575matches a given pattern.  This is done by the function
3576
3577     bool ex::match(const ex & pattern);
3578     bool ex::match(const ex & pattern, exmap& repls);
3579
3580This function returns 'true' when the expression matches the pattern and
3581'false' if it doesn't.  If used in the second form, the actual
3582subexpressions matched by the wildcards get returned in the associative
3583array 'repls' with 'wildcard' as a key.  If 'match()' returns false,
3584'repls' remains unmodified.
3585
3586The matching algorithm works as follows:
3587
3588   * A single wildcard matches any expression.  If one wildcard appears
3589     multiple times in a pattern, it must match the same expression in
3590     all places (e.g.  '$0' matches anything, and '$0*($0+1)' matches
3591     'x*(x+1)' but not 'x*(y+1)').
3592   * If the expression is not of the same class as the pattern, the
3593     match fails (i.e.  a sum only matches a sum, a function only
3594     matches a function, etc.).
3595   * If the pattern is a function, it only matches the same function
3596     (i.e.  'sin($0)' matches 'sin(x)' but doesn't match 'exp(x)').
3597   * Except for sums and products, the match fails if the number of
3598     subexpressions ('nops()') is not equal to the number of
3599     subexpressions of the pattern.
3600   * If there are no subexpressions, the expressions and the pattern
3601     must be equal (in the sense of 'is_equal()').
3602   * Except for sums and products, each subexpression ('op()') must
3603     match the corresponding subexpression of the pattern.
3604
3605Sums ('add') and products ('mul') are treated in a special way to
3606account for their commutativity and associativity:
3607
3608   * If the pattern contains a term or factor that is a single wildcard,
3609     this one is used as the "global wildcard".  If there is more than
3610     one such wildcard, one of them is chosen as the global wildcard in
3611     a random way.
3612   * Every term/factor of the pattern, except the global wildcard, is
3613     matched against every term of the expression in sequence.  If no
3614     match is found, the whole match fails.  Terms that did match are
3615     not considered in further matches.
3616   * If there are no unmatched terms left, the match succeeds.
3617     Otherwise the match fails unless there is a global wildcard in the
3618     pattern, in which case this wildcard matches the remaining terms.
3619
3620In general, having more than one single wildcard as a term of a sum or a
3621factor of a product (such as 'a+$0+$1') will lead to unpredictable or
3622ambiguous results.
3623
3624Here are some examples in 'ginsh' to demonstrate how it works (the
3625'match()' function in 'ginsh' returns 'FAIL' if the match fails, and the
3626list of wildcard replacements otherwise):
3627
3628     > match((x+y)^a,(x+y)^a);
3629     {}
3630     > match((x+y)^a,(x+y)^b);
3631     FAIL
3632     > match((x+y)^a,$1^$2);
3633     {$1==x+y,$2==a}
3634     > match((x+y)^a,$1^$1);
3635     FAIL
3636     > match((x+y)^(x+y),$1^$1);
3637     {$1==x+y}
3638     > match((x+y)^(x+y),$1^$2);
3639     {$1==x+y,$2==x+y}
3640     > match((a+b)*(a+c),($1+b)*($1+c));
3641     {$1==a}
3642     > match((a+b)*(a+c),(a+$1)*(a+$2));
3643     {$1==b,$2==c}
3644       (Unpredictable. The result might also be [$1==c,$2==b].)
3645     > match((a+b)*(a+c),($1+$2)*($1+$3));
3646       (The result is undefined. Due to the sequential nature of the algorithm
3647        and the re-ordering of terms in GiNaC, the match for the first factor
3648        may be {$1==a,$2==b} in which case the match for the second factor
3649        succeeds, or it may be {$1==b,$2==a} which causes the second match to
3650        fail.)
3651     > match(a*(x+y)+a*z+b,a*$1+$2);
3652       (This is also ambiguous and may return either {$1==z,$2==a*(x+y)+b} or
3653        {$1=x+y,$2=a*z+b}.)
3654     > match(a+b+c+d+e+f,c);
3655     FAIL
3656     > match(a+b+c+d+e+f,c+$0);
3657     {$0==a+e+b+f+d}
3658     > match(a+b+c+d+e+f,c+e+$0);
3659     {$0==a+b+f+d}
3660     > match(a+b,a+b+$0);
3661     {$0==0}
3662     > match(a*b^2,a^$1*b^$2);
3663     FAIL
3664       (The matching is syntactic, not algebraic, and "a" doesn't match "a^$1"
3665        even though a==a^1.)
3666     > match(x*atan2(x,x^2),$0*atan2($0,$0^2));
3667     {$0==x}
3668     > match(atan2(y,x^2),atan2(y,$0));
3669     {$0==x^2}
3670
36715.4.2 Matching parts of expressions
3672-----------------------------------
3673
3674A more general way to look for patterns in expressions is provided by
3675the member function
3676
3677     bool ex::has(const ex & pattern);
3678
3679This function checks whether a pattern is matched by an expression
3680itself or by any of its subexpressions.
3681
3682Again some examples in 'ginsh' for illustration (in 'ginsh', 'has()'
3683returns '1' for 'true' and '0' for 'false'):
3684
3685     > has(x*sin(x+y+2*a),y);
3686     1
3687     > has(x*sin(x+y+2*a),x+y);
3688     0
3689       (This is because in GiNaC, "x+y" is not a subexpression of "x+y+2*a" (which
3690        has the subexpressions "x", "y" and "2*a".)
3691     > has(x*sin(x+y+2*a),x+y+$1);
3692     1
3693       (But this is possible.)
3694     > has(x*sin(2*(x+y)+2*a),x+y);
3695     0
3696       (This fails because "2*(x+y)" automatically gets converted to "2*x+2*y" of
3697        which "x+y" is not a subexpression.)
3698     > has(x+1,x^$1);
3699     0
3700       (Although x^1==x and x^0==1, neither "x" nor "1" are actually of the form
3701        "x^something".)
3702     > has(4*x^2-x+3,$1*x);
3703     1
3704     > has(4*x^2+x+3,$1*x);
3705     0
3706       (Another possible pitfall. The first expression matches because the term
3707        "-x" has the form "(-1)*x" in GiNaC. To check whether a polynomial
3708        contains a linear term you should use the coeff() function instead.)
3709
3710The method
3711
3712     bool ex::find(const ex & pattern, exset& found);
3713
3714works a bit like 'has()' but it doesn't stop upon finding the first
3715match.  Instead, it appends all found matches to the specified list.  If
3716there are multiple occurrences of the same expression, it is entered
3717only once to the list.  'find()' returns false if no matches were found
3718(in 'ginsh', it returns an empty list):
3719
3720     > find(1+x+x^2+x^3,x);
3721     {x}
3722     > find(1+x+x^2+x^3,y);
3723     {}
3724     > find(1+x+x^2+x^3,x^$1);
3725     {x^3,x^2}
3726       (Note the absence of "x".)
3727     > expand((sin(x)+sin(y))*(a+b));
3728     sin(y)*a+sin(x)*b+sin(x)*a+sin(y)*b
3729     > find(%,sin($1));
3730     {sin(y),sin(x)}
3731
37325.4.3 Substituting expressions
3733------------------------------
3734
3735Probably the most useful application of patterns is to use them for
3736substituting expressions with the 'subs()' method.  Wildcards can be
3737used in the search patterns as well as in the replacement expressions,
3738where they get replaced by the expressions matched by them.  'subs()'
3739doesn't know anything about algebra; it performs purely syntactic
3740substitutions.
3741
3742Some examples:
3743
3744     > subs(a^2+b^2+(x+y)^2,$1^2==$1^3);
3745     b^3+a^3+(x+y)^3
3746     > subs(a^4+b^4+(x+y)^4,$1^2==$1^3);
3747     b^4+a^4+(x+y)^4
3748     > subs((a+b+c)^2,a+b==x);
3749     (a+b+c)^2
3750     > subs((a+b+c)^2,a+b+$1==x+$1);
3751     (x+c)^2
3752     > subs(a+2*b,a+b==x);
3753     a+2*b
3754     > subs(4*x^3-2*x^2+5*x-1,x==a);
3755     -1+5*a-2*a^2+4*a^3
3756     > subs(4*x^3-2*x^2+5*x-1,x^$0==a^$0);
3757     -1+5*x-2*a^2+4*a^3
3758     > subs(sin(1+sin(x)),sin($1)==cos($1));
3759     cos(1+cos(x))
3760     > expand(subs(a*sin(x+y)^2+a*cos(x+y)^2+b,cos($1)^2==1-sin($1)^2));
3761     a+b
3762
3763The last example would be written in C++ in this way:
3764
3765     {
3766         symbol a("a"), b("b"), x("x"), y("y");
3767         e = a*pow(sin(x+y), 2) + a*pow(cos(x+y), 2) + b;
3768         e = e.subs(pow(cos(wild()), 2) == 1-pow(sin(wild()), 2));
3769         cout << e.expand() << endl;
3770          // -> a+b
3771     }
3772
37735.4.4 The option algebraic
3774--------------------------
3775
3776Both 'has()' and 'subs()' take an optional argument to pass them extra
3777options.  This section describes what happens if you give the former the
3778option 'has_options::algebraic' or the latter 'subs_options::algebraic'.
3779In that case the matching condition for powers and multiplications is
3780changed in such a way that they become more intuitive.  Intuition says
3781that 'x*y' is a part of 'x*y*z'.  If you use these options you will find
3782that '(x*y*z).has(x*y, has_options::algebraic)' indeed returns true.
3783Besides matching some of the factors of a product also powers match as
3784often as is possible without getting negative exponents.  For example
3785'(x^5*y^2*z).subs(x^2*y^2==c, subs_options::algebraic)' will return
3786'x*c^2*z'.  This also works with negative powers:
3787'(x^(-3)*y^(-2)*z).subs(1/(x*y)==c, subs_options::algebraic)' will
3788return 'x^(-1)*c^2*z'.
3789
3790*Please notice:* this only works for multiplications and not for
3791locating 'x+y' within 'x+y+z'.
3792
3793
3794File: ginac.info,  Node: Applying a function on subexpressions,  Next: Visitors and tree traversal,  Prev: Pattern matching and advanced substitutions,  Up: Methods and functions
3795
37965.5 Applying a function on subexpressions
3797=========================================
3798
3799Sometimes you may want to perform an operation on specific parts of an
3800expression while leaving the general structure of it intact.  An example
3801of this would be a matrix trace operation: the trace of a sum is the sum
3802of the traces of the individual terms.  That is, the trace should "map"
3803on the sum, by applying itself to each of the sum's operands.  It is
3804possible to do this manually which usually results in code like this:
3805
3806     ex calc_trace(ex e)
3807     {
3808         if (is_a<matrix>(e))
3809             return ex_to<matrix>(e).trace();
3810         else if (is_a<add>(e)) {
3811             ex sum = 0;
3812             for (size_t i=0; i<e.nops(); i++)
3813                 sum += calc_trace(e.op(i));
3814             return sum;
3815         } else if (is_a<mul>)(e)) {
3816             ...
3817         } else {
3818             ...
3819         }
3820     }
3821
3822This is, however, slightly inefficient (if the sum is very large it can
3823take a long time to add the terms one-by-one), and its applicability is
3824limited to a rather small class of expressions.  If 'calc_trace()' is
3825called with a relation or a list as its argument, you will probably want
3826the trace to be taken on both sides of the relation or of all elements
3827of the list.
3828
3829GiNaC offers the 'map()' method to aid in the implementation of such
3830operations:
3831
3832     ex ex::map(map_function & f) const;
3833     ex ex::map(ex (*f)(const ex & e)) const;
3834
3835In the first (preferred) form, 'map()' takes a function object that is
3836subclassed from the 'map_function' class.  In the second form, it takes
3837a pointer to a function that accepts and returns an expression.  'map()'
3838constructs a new expression of the same type, applying the specified
3839function on all subexpressions (in the sense of 'op()'),
3840non-recursively.
3841
3842The use of a function object makes it possible to supply more arguments
3843to the function that is being mapped, or to keep local state
3844information.  The 'map_function' class declares a virtual function call
3845operator that you can overload.  Here is a sample implementation of
3846'calc_trace()' that uses 'map()' in a recursive fashion:
3847
3848     struct calc_trace : public map_function {
3849         ex operator()(const ex &e)
3850         {
3851             if (is_a<matrix>(e))
3852                 return ex_to<matrix>(e).trace();
3853             else if (is_a<mul>(e)) {
3854                 ...
3855             } else
3856                 return e.map(*this);
3857         }
3858     };
3859
3860This function object could then be used like this:
3861
3862     {
3863         ex M = ... // expression with matrices
3864         calc_trace do_trace;
3865         ex tr = do_trace(M);
3866     }
3867
3868Here is another example for you to meditate over.  It removes quadratic
3869terms in a variable from an expanded polynomial:
3870
3871     struct map_rem_quad : public map_function {
3872         ex var;
3873         map_rem_quad(const ex & var_) : var(var_) {}
3874
3875         ex operator()(const ex & e)
3876         {
3877             if (is_a<add>(e) || is_a<mul>(e))
3878          	    return e.map(*this);
3879             else if (is_a<power>(e) &&
3880                      e.op(0).is_equal(var) && e.op(1).info(info_flags::even))
3881                 return 0;
3882             else
3883                 return e;
3884         }
3885     };
3886
3887     ...
3888
3889     {
3890         symbol x("x"), y("y");
3891
3892         ex e;
3893         for (int i=0; i<8; i++)
3894             e += pow(x, i) * pow(y, 8-i) * (i+1);
3895         cout << e << endl;
3896          // -> 4*y^5*x^3+5*y^4*x^4+8*y*x^7+7*y^2*x^6+2*y^7*x+6*y^3*x^5+3*y^6*x^2+y^8
3897
3898         map_rem_quad rem_quad(x);
3899         cout << rem_quad(e) << endl;
3900          // -> 4*y^5*x^3+8*y*x^7+2*y^7*x+6*y^3*x^5+y^8
3901     }
3902
3903'ginsh' offers a slightly different implementation of 'map()' that
3904allows applying algebraic functions to operands.  The second argument to
3905'map()' is an expression containing the wildcard '$0' which acts as the
3906placeholder for the operands:
3907
3908     > map(a*b,sin($0));
3909     sin(a)*sin(b)
3910     > map(a+2*b,sin($0));
3911     sin(a)+sin(2*b)
3912     > map({a,b,c},$0^2+$0);
3913     {a^2+a,b^2+b,c^2+c}
3914
3915Note that it is only possible to use algebraic functions in the second
3916argument.  You can not use functions like 'diff()', 'op()', 'subs()'
3917etc.  because these are evaluated immediately:
3918
3919     > map({a,b,c},diff($0,a));
3920     {0,0,0}
3921       This is because "diff($0,a)" evaluates to "0", so the command is equivalent
3922       to "map({a,b,c},0)".
3923
3924
3925File: ginac.info,  Node: Visitors and tree traversal,  Next: Polynomial arithmetic,  Prev: Applying a function on subexpressions,  Up: Methods and functions
3926
39275.6 Visitors and tree traversal
3928===============================
3929
3930Suppose that you need a function that returns a list of all indices
3931appearing in an arbitrary expression.  The indices can have any
3932dimension, and for indices with variance you always want the covariant
3933version returned.
3934
3935You can't use 'get_free_indices()' because you also want to include
3936dummy indices in the list, and you can't use 'find()' as it needs
3937specific index dimensions (and it would require two passes: one for
3938indices with variance, one for plain ones).
3939
3940The obvious solution to this problem is a tree traversal with a type
3941switch, such as the following:
3942
3943     void gather_indices_helper(const ex & e, lst & l)
3944     {
3945         if (is_a<varidx>(e)) {
3946             const varidx & vi = ex_to<varidx>(e);
3947             l.append(vi.is_covariant() ? vi : vi.toggle_variance());
3948         } else if (is_a<idx>(e)) {
3949             l.append(e);
3950         } else {
3951             size_t n = e.nops();
3952             for (size_t i = 0; i < n; ++i)
3953                 gather_indices_helper(e.op(i), l);
3954         }
3955     }
3956
3957     lst gather_indices(const ex & e)
3958     {
3959         lst l;
3960         gather_indices_helper(e, l);
3961         l.sort();
3962         l.unique();
3963         return l;
3964     }
3965
3966This works fine but fans of object-oriented programming will feel
3967uncomfortable with the type switch.  One reason is that there is a
3968possibility for subtle bugs regarding derived classes.  If we had, for
3969example, written
3970
3971         if (is_a<idx>(e)) {
3972           ...
3973         } else if (is_a<varidx>(e)) {
3974           ...
3975
3976in 'gather_indices_helper', the code wouldn't have worked because the
3977first line "absorbs" all classes derived from 'idx', including 'varidx',
3978so the special case for 'varidx' would never have been executed.
3979
3980Also, for a large number of classes, a type switch like the above can
3981get unwieldy and inefficient (it's a linear search, after all).
3982'gather_indices_helper' only checks for two classes, but if you had to
3983write a function that required a different implementation for nearly
3984every GiNaC class, the result would be very hard to maintain and extend.
3985
3986The cleanest approach to the problem would be to add a new virtual
3987function to GiNaC's class hierarchy.  In our example, there would be
3988specializations for 'idx' and 'varidx' while the default implementation
3989in 'basic' performed the tree traversal.  Unfortunately, in C++ it's
3990impossible to add virtual member functions to existing classes without
3991changing their source and recompiling everything.  GiNaC comes with
3992source, so you could actually do this, but for a small algorithm like
3993the one presented this would be impractical.
3994
3995One solution to this dilemma is the "Visitor" design pattern, which is
3996implemented in GiNaC (actually, Robert Martin's Acyclic Visitor
3997variation, described in detail in
3998<https://condor.depaul.edu/dmumaugh/OOT/Design-Principles/acv.pdf>).
3999Instead of adding virtual functions to the class hierarchy to implement
4000operations, GiNaC provides a single "bouncing" method 'accept()' that
4001takes an instance of a special 'visitor' class and redirects execution
4002to the one 'visit()' virtual function of the visitor that matches the
4003type of object that 'accept()' was being invoked on.
4004
4005Visitors in GiNaC must derive from the global 'visitor' class as well as
4006from the class 'T::visitor' of each class 'T' they want to visit, and
4007implement the member functions 'void visit(const T &)' for each class.
4008
4009A call of
4010
4011     void ex::accept(visitor & v) const;
4012
4013will then dispatch to the correct 'visit()' member function of the
4014specified visitor 'v' for the type of GiNaC object at the root of the
4015expression tree (e.g.  a 'symbol', an 'idx' or a 'mul').
4016
4017Here is an example of a visitor:
4018
4019     class my_visitor
4020      : public visitor,          // this is required
4021        public add::visitor,     // visit add objects
4022        public numeric::visitor, // visit numeric objects
4023        public basic::visitor    // visit basic objects
4024     {
4025         void visit(const add & x)
4026         { cout << "called with an add object" << endl; }
4027
4028         void visit(const numeric & x)
4029         { cout << "called with a numeric object" << endl; }
4030
4031         void visit(const basic & x)
4032         { cout << "called with a basic object" << endl; }
4033     };
4034
4035which can be used as follows:
4036
4037     ...
4038         symbol x("x");
4039         ex e1 = 42;
4040         ex e2 = 4*x-3;
4041         ex e3 = 8*x;
4042
4043         my_visitor v;
4044         e1.accept(v);
4045          // prints "called with a numeric object"
4046         e2.accept(v);
4047          // prints "called with an add object"
4048         e3.accept(v);
4049          // prints "called with a basic object"
4050     ...
4051
4052The 'visit(const basic &)' method gets called for all objects that are
4053not 'numeric' or 'add' and acts as an (optional) default.
4054
4055From a conceptual point of view, the 'visit()' methods of the visitor
4056behave like a newly added virtual function of the visited hierarchy.  In
4057addition, visitors can store state in member variables, and they can be
4058extended by deriving a new visitor from an existing one, thus building
4059hierarchies of visitors.
4060
4061We can now rewrite our index example from above with a visitor:
4062
4063     class gather_indices_visitor
4064      : public visitor, public idx::visitor, public varidx::visitor
4065     {
4066         lst l;
4067
4068         void visit(const idx & i)
4069         {
4070             l.append(i);
4071         }
4072
4073         void visit(const varidx & vi)
4074         {
4075             l.append(vi.is_covariant() ? vi : vi.toggle_variance());
4076         }
4077
4078     public:
4079         const lst & get_result() // utility function
4080         {
4081             l.sort();
4082             l.unique();
4083             return l;
4084         }
4085     };
4086
4087What's missing is the tree traversal.  We could implement it in
4088'visit(const basic &)', but GiNaC has predefined methods for this:
4089
4090     void ex::traverse_preorder(visitor & v) const;
4091     void ex::traverse_postorder(visitor & v) const;
4092     void ex::traverse(visitor & v) const;
4093
4094'traverse_preorder()' visits a node _before_ visiting its
4095subexpressions, while 'traverse_postorder()' visits a node _after_
4096visiting its subexpressions.  'traverse()' is a synonym for
4097'traverse_preorder()'.
4098
4099Here is a new implementation of 'gather_indices()' that uses the visitor
4100and 'traverse()':
4101
4102     lst gather_indices(const ex & e)
4103     {
4104         gather_indices_visitor v;
4105         e.traverse(v);
4106         return v.get_result();
4107     }
4108
4109Alternatively, you could use pre- or postorder iterators for the tree
4110traversal:
4111
4112     lst gather_indices(const ex & e)
4113     {
4114         gather_indices_visitor v;
4115         for (const_preorder_iterator i = e.preorder_begin();
4116              i != e.preorder_end(); ++i) {
4117             i->accept(v);
4118         }
4119         return v.get_result();
4120     }
4121
4122
4123File: ginac.info,  Node: Polynomial arithmetic,  Next: Rational expressions,  Prev: Visitors and tree traversal,  Up: Methods and functions
4124
41255.7 Polynomial arithmetic
4126=========================
4127
41285.7.1 Testing whether an expression is a polynomial
4129---------------------------------------------------
4130
4131Testing whether an expression is a polynomial in one or more variables
4132can be done with the method
4133     bool ex::is_polynomial(const ex & vars) const;
4134In the case of more than one variable, the variables are given as a
4135list.
4136
4137     (x*y*sin(y)).is_polynomial(x)         // Returns true.
4138     (x*y*sin(y)).is_polynomial(lst{x,y})  // Returns false.
4139
41405.7.2 Expanding and collecting
4141------------------------------
4142
4143A polynomial in one or more variables has many equivalent
4144representations.  Some useful ones serve a specific purpose.  Consider
4145for example the trivariate polynomial 4*x*y + x*z + 20*y^2 + 21*y*z +
41464*z^2 (written down here in output-style).  It is equivalent to the
4147factorized polynomial (x + 5*y + 4*z)*(4*y + z).  Other representations
4148are the recursive ones where one collects for exponents in one of the
4149three variable.  Since the factors are themselves polynomials in the
4150remaining two variables the procedure can be repeated.  In our example,
4151two possibilities would be (4*y + z)*x + 20*y^2 + 21*y*z + 4*z^2 and
415220*y^2 + (21*z + 4*x)*y + 4*z^2 + x*z.
4153
4154To bring an expression into expanded form, its method
4155
4156     ex ex::expand(unsigned options = 0);
4157
4158may be called.  In our example above, this corresponds to 4*x*y + x*z +
415920*y^2 + 21*y*z + 4*z^2.  Again, since the canonical form in GiNaC is
4160not easy to guess you should be prepared to see different orderings of
4161terms in such sums!
4162
4163Another useful representation of multivariate polynomials is as a
4164univariate polynomial in one of the variables with the coefficients
4165being polynomials in the remaining variables.  The method 'collect()'
4166accomplishes this task:
4167
4168     ex ex::collect(const ex & s, bool distributed = false);
4169
4170The first argument to 'collect()' can also be a list of objects in which
4171case the result is either a recursively collected polynomial, or a
4172polynomial in a distributed form with terms like c*x1^e1*...*xn^en, as
4173specified by the 'distributed' flag.
4174
4175Note that the original polynomial needs to be in expanded form (for the
4176variables concerned) in order for 'collect()' to be able to find the
4177coefficients properly.
4178
4179The following 'ginsh' transcript shows an application of 'collect()'
4180together with 'find()':
4181
4182     > a=expand((sin(x)+sin(y))*(1+p+q)*(1+d));
4183     d*p*sin(x)+p*sin(x)+q*d*sin(x)+q*sin(y)+d*sin(x)+q*d*sin(y)+sin(y)+d*sin(y)
4184     +q*sin(x)+d*sin(y)*p+sin(x)+sin(y)*p
4185     > collect(a,{p,q});
4186     d*sin(x)+(d*sin(x)+sin(y)+d*sin(y)+sin(x))*p
4187     +(d*sin(x)+sin(y)+d*sin(y)+sin(x))*q+sin(y)+d*sin(y)+sin(x)
4188     > collect(a,find(a,sin($1)));
4189     (1+q+d+q*d+d*p+p)*sin(y)+(1+q+d+q*d+d*p+p)*sin(x)
4190     > collect(a,{find(a,sin($1)),p,q});
4191     (1+(1+d)*p+d+q*(1+d))*sin(x)+(1+(1+d)*p+d+q*(1+d))*sin(y)
4192     > collect(a,{find(a,sin($1)),d});
4193     (1+q+d*(1+q+p)+p)*sin(y)+(1+q+d*(1+q+p)+p)*sin(x)
4194
4195Polynomials can often be brought into a more compact form by collecting
4196common factors from the terms of sums.  This is accomplished by the
4197function
4198
4199     ex collect_common_factors(const ex & e);
4200
4201This function doesn't perform a full factorization but only looks for
4202factors which are already explicitly present:
4203
4204     > collect_common_factors(a*x+a*y);
4205     (x+y)*a
4206     > collect_common_factors(a*x^2+2*a*x*y+a*y^2);
4207     a*(2*x*y+y^2+x^2)
4208     > collect_common_factors(a*(b*(a+c)*x+b*((a+c)*x+(a+c)*y)*y));
4209     (c+a)*a*(x*y+y^2+x)*b
4210
42115.7.3 Degree and coefficients
4212-----------------------------
4213
4214The degree and low degree of a polynomial in expanded form can be
4215obtained using the two methods
4216
4217     int ex::degree(const ex & s);
4218     int ex::ldegree(const ex & s);
4219
4220These functions even work on rational functions, returning the
4221asymptotic degree.  By definition, the degree of zero is zero.  To
4222extract a coefficient with a certain power from an expanded polynomial
4223you use
4224
4225     ex ex::coeff(const ex & s, int n);
4226
4227You can also obtain the leading and trailing coefficients with the
4228methods
4229
4230     ex ex::lcoeff(const ex & s);
4231     ex ex::tcoeff(const ex & s);
4232
4233which are equivalent to 'coeff(s, degree(s))' and 'coeff(s,
4234ldegree(s))', respectively.
4235
4236An application is illustrated in the next example, where a multivariate
4237polynomial is analyzed:
4238
4239     {
4240         symbol x("x"), y("y");
4241         ex PolyInp = 4*pow(x,3)*y + 5*x*pow(y,2) + 3*y
4242                      - pow(x+y,2) + 2*pow(y+2,2) - 8;
4243         ex Poly = PolyInp.expand();
4244
4245         for (int i=Poly.ldegree(x); i<=Poly.degree(x); ++i) {
4246             cout << "The x^" << i << "-coefficient is "
4247                  << Poly.coeff(x,i) << endl;
4248         }
4249         cout << "As polynomial in y: "
4250              << Poly.collect(y) << endl;
4251     }
4252
4253When run, it returns an output in the following fashion:
4254
4255     The x^0-coefficient is y^2+11*y
4256     The x^1-coefficient is 5*y^2-2*y
4257     The x^2-coefficient is -1
4258     The x^3-coefficient is 4*y
4259     As polynomial in y: -x^2+(5*x+1)*y^2+(-2*x+4*x^3+11)*y
4260
4261As always, the exact output may vary between different versions of GiNaC
4262or even from run to run since the internal canonical ordering is not
4263within the user's sphere of influence.
4264
4265'degree()', 'ldegree()', 'coeff()', 'lcoeff()', 'tcoeff()' and
4266'collect()' can also be used to a certain degree with non-polynomial
4267expressions as they not only work with symbols but with constants,
4268functions and indexed objects as well:
4269
4270     {
4271         symbol a("a"), b("b"), c("c"), x("x");
4272         idx i(symbol("i"), 3);
4273
4274         ex e = pow(sin(x) - cos(x), 4);
4275         cout << e.degree(cos(x)) << endl;
4276          // -> 4
4277         cout << e.expand().coeff(sin(x), 3) << endl;
4278          // -> -4*cos(x)
4279
4280         e = indexed(a+b, i) * indexed(b+c, i);
4281         e = e.expand(expand_options::expand_indexed);
4282         cout << e.collect(indexed(b, i)) << endl;
4283          // -> a.i*c.i+(a.i+c.i)*b.i+b.i^2
4284     }
4285
42865.7.4 Polynomial division
4287-------------------------
4288
4289The two functions
4290
4291     ex quo(const ex & a, const ex & b, const ex & x);
4292     ex rem(const ex & a, const ex & b, const ex & x);
4293
4294compute the quotient and remainder of univariate polynomials in the
4295variable 'x'.  The results satisfy a = b*quo(a, b, x) + rem(a, b, x).
4296
4297The additional function
4298
4299     ex prem(const ex & a, const ex & b, const ex & x);
4300
4301computes the pseudo-remainder of 'a' and 'b' which satisfies c*a = b*q +
4302prem(a, b, x), where c = b.lcoeff(x) ^ (a.degree(x) - b.degree(x) + 1).
4303
4304Exact division of multivariate polynomials is performed by the function
4305
4306     bool divide(const ex & a, const ex & b, ex & q);
4307
4308If 'b' divides 'a' over the rationals, this function returns 'true' and
4309returns the quotient in the variable 'q'.  Otherwise it returns 'false'
4310in which case the value of 'q' is undefined.
4311
43125.7.5 Unit, content and primitive part
4313--------------------------------------
4314
4315The methods
4316
4317     ex ex::unit(const ex & x);
4318     ex ex::content(const ex & x);
4319     ex ex::primpart(const ex & x);
4320     ex ex::primpart(const ex & x, const ex & c);
4321
4322return the unit part, content part, and primitive polynomial of a
4323multivariate polynomial with respect to the variable 'x' (the unit part
4324being the sign of the leading coefficient, the content part being the
4325GCD of the coefficients, and the primitive polynomial being the input
4326polynomial divided by the unit and content parts).  The second variant
4327of 'primpart()' expects the previously calculated content part of the
4328polynomial in 'c', which enables it to work faster in the case where the
4329content part has already been computed.  The product of unit, content,
4330and primitive part is the original polynomial.
4331
4332Additionally, the method
4333
4334     void ex::unitcontprim(const ex & x, ex & u, ex & c, ex & p);
4335
4336computes the unit, content, and primitive parts in one go, returning
4337them in 'u', 'c', and 'p', respectively.
4338
43395.7.6 GCD, LCM and resultant
4340----------------------------
4341
4342The functions for polynomial greatest common divisor and least common
4343multiple have the synopsis
4344
4345     ex gcd(const ex & a, const ex & b);
4346     ex lcm(const ex & a, const ex & b);
4347
4348The functions 'gcd()' and 'lcm()' accept two expressions 'a' and 'b' as
4349arguments and return a new expression, their greatest common divisor or
4350least common multiple, respectively.  If the polynomials 'a' and 'b' are
4351coprime 'gcd(a,b)' returns 1 and 'lcm(a,b)' returns the product of 'a'
4352and 'b'.  Note that all the coefficients must be rationals.
4353
4354     #include <ginac/ginac.h>
4355     using namespace GiNaC;
4356
4357     int main()
4358     {
4359         symbol x("x"), y("y"), z("z");
4360         ex P_a = 4*x*y + x*z + 20*pow(y, 2) + 21*y*z + 4*pow(z, 2);
4361         ex P_b = x*y + 3*x*z + 5*pow(y, 2) + 19*y*z + 12*pow(z, 2);
4362
4363         ex P_gcd = gcd(P_a, P_b);
4364         // x + 5*y + 4*z
4365         ex P_lcm = lcm(P_a, P_b);
4366         // 4*x*y^2 + 13*y*x*z + 20*y^3 + 81*y^2*z + 67*y*z^2 + 3*x*z^2 + 12*z^3
4367     }
4368
4369The resultant of two expressions only makes sense with polynomials.  It
4370is always computed with respect to a specific symbol within the
4371expressions.  The function has the interface
4372
4373     ex resultant(const ex & a, const ex & b, const ex & s);
4374
4375Resultants are symmetric in 'a' and 'b'.  The following example computes
4376the resultant of two expressions with respect to 'x' and 'y',
4377respectively:
4378
4379     #include <ginac/ginac.h>
4380     using namespace GiNaC;
4381
4382     int main()
4383     {
4384         symbol x("x"), y("y");
4385
4386         ex e1 = x+pow(y,2), e2 = 2*pow(x,3)-1; // x+y^2, 2*x^3-1
4387         ex r;
4388
4389         r = resultant(e1, e2, x);
4390         // -> 1+2*y^6
4391         r = resultant(e1, e2, y);
4392         // -> 1-4*x^3+4*x^6
4393     }
4394
43955.7.7 Square-free decomposition
4396-------------------------------
4397
4398Square-free decomposition is available in GiNaC:
4399     ex sqrfree(const ex & a, const lst & l = lst{});
4400Here is an example that by the way illustrates how the exact form of the
4401result may slightly depend on the order of differentiation, calling for
4402some care with subsequent processing of the result:
4403         ...
4404         symbol x("x"), y("y");
4405         ex BiVarPol = expand(pow(2-2*y,3) * pow(1+x*y,2) * pow(x-2*y,2) * (x+y));
4406
4407         cout << sqrfree(BiVarPol, lst{x,y}) << endl;
4408          // -> 8*(1-y)^3*(y*x^2-2*y+x*(1-2*y^2))^2*(y+x)
4409
4410         cout << sqrfree(BiVarPol, lst{y,x}) << endl;
4411          // -> 8*(1-y)^3*(-y*x^2+2*y+x*(-1+2*y^2))^2*(y+x)
4412
4413         cout << sqrfree(BiVarPol) << endl;
4414          // -> depending on luck, any of the above
4415         ...
4416Note also, how factors with the same exponents are not fully factorized
4417with this method.
4418
44195.7.8 Polynomial factorization
4420------------------------------
4421
4422Polynomials can also be fully factored with a call to the function
4423     ex factor(const ex & a, unsigned int options = 0);
4424The factorization works for univariate and multivariate polynomials with
4425rational coefficients.  The following code snippet shows its
4426capabilities:
4427         ...
4428         cout << factor(pow(x,2)-1) << endl;
4429          // -> (1+x)*(-1+x)
4430         cout << factor(expand((x-y*z)*(x-pow(y,2)-pow(z,3))*(x+y+z))) << endl;
4431          // -> (y+z+x)*(y*z-x)*(y^2-x+z^3)
4432         cout << factor(pow(x,2)-1+sin(pow(x,2)-1)) << endl;
4433          // -> -1+sin(-1+x^2)+x^2
4434         ...
4435The results are as expected except for the last one where no
4436factorization seems to have been done.  This is due to the default
4437option 'factor_options::polynomial' (equals zero) to 'factor()', which
4438tells GiNaC to try a factorization only if the expression is a valid
4439polynomial.  In the shown example this is not the case, because one term
4440is a function.
4441
4442There exists a second option 'factor_options::all', which tells GiNaC to
4443ignore non-polynomial parts of an expression and also to look inside
4444function arguments.  With this option the example gives:
4445         ...
4446         cout << factor(pow(x,2)-1+sin(pow(x,2)-1), factor_options::all)
4447              << endl;
4448          // -> (-1+x)*(1+x)+sin((-1+x)*(1+x))
4449         ...
4450GiNaC's factorization functions cannot handle algebraic extensions.
4451Therefore the following example does not factor:
4452         ...
4453         cout << factor(pow(x,2)-2) << endl;
4454          // -> -2+x^2  and not  (x-sqrt(2))*(x+sqrt(2))
4455         ...
4456Factorization is useful in many applications.  A lot of algorithms in
4457computer algebra depend on the ability to factor a polynomial.  Of
4458course, factorization can also be used to simplify expressions, but it
4459is costly and applying it to complicated expressions (high degrees or
4460many terms) may consume far too much time.  So usually, looking for a
4461GCD at strategic points in a calculation is the cheaper and more
4462appropriate alternative.
4463
4464
4465File: ginac.info,  Node: Rational expressions,  Next: Symbolic differentiation,  Prev: Polynomial arithmetic,  Up: Methods and functions
4466
44675.8 Rational expressions
4468========================
4469
44705.8.1 The 'normal' method
4471-------------------------
4472
4473Some basic form of simplification of expressions is called for
4474frequently.  GiNaC provides the method '.normal()', which converts a
4475rational function into an equivalent rational function of the form
4476'numerator/denominator' where numerator and denominator are coprime.  If
4477the input expression is already a fraction, it just finds the GCD of
4478numerator and denominator and cancels it, otherwise it performs fraction
4479addition and multiplication.
4480
4481'.normal()' can also be used on expressions which are not rational
4482functions as it will replace all non-rational objects (like functions or
4483non-integer powers) by temporary symbols to bring the expression to the
4484domain of rational functions before performing the normalization, and
4485re-substituting these symbols afterwards.  This algorithm is also
4486available as a separate method '.to_rational()', described below.
4487
4488This means that both expressions 't1' and 't2' are indeed simplified in
4489this little code snippet:
4490
4491     {
4492         symbol x("x");
4493         ex t1 = (pow(x,2) + 2*x + 1)/(x + 1);
4494         ex t2 = (pow(sin(x),2) + 2*sin(x) + 1)/(sin(x) + 1);
4495         std::cout << "t1 is " << t1.normal() << std::endl;
4496         std::cout << "t2 is " << t2.normal() << std::endl;
4497     }
4498
4499Of course this works for multivariate polynomials too, so the ratio of
4500the sample-polynomials from the section about GCD and LCM above would be
4501normalized to 'P_a/P_b' = '(4*y+z)/(y+3*z)'.
4502
45035.8.2 Numerator and denominator
4504-------------------------------
4505
4506The numerator and denominator of an expression can be obtained with
4507
4508     ex ex::numer();
4509     ex ex::denom();
4510     ex ex::numer_denom();
4511
4512These functions will first normalize the expression as described above
4513and then return the numerator, denominator, or both as a list,
4514respectively.  If you need both numerator and denominator, call
4515'numer_denom()': it is faster than using 'numer()' and 'denom()'
4516separately.  And even more important: a separate evaluation of 'numer()'
4517and 'denom()' may result in a spurious sign, e.g.  for $x/(x^2-1)$
4518'numer()' may return $x$ and 'denom()' $1-x^2$.
4519
45205.8.3 Converting to a polynomial or rational expression
4521-------------------------------------------------------
4522
4523Some of the methods described so far only work on polynomials or
4524rational functions.  GiNaC provides a way to extend the domain of these
4525functions to general expressions by using the temporary replacement
4526algorithm described above.  You do this by calling
4527
4528     ex ex::to_polynomial(exmap & m);
4529or
4530     ex ex::to_rational(exmap & m);
4531
4532on the expression to be converted.  The supplied 'exmap' will be filled
4533with the generated temporary symbols and their replacement expressions
4534in a format that can be used directly for the 'subs()' method.  It can
4535also already contain a list of replacements from an earlier application
4536of '.to_polynomial()' or '.to_rational()', so it's possible to use it on
4537multiple expressions and get consistent results.
4538
4539The difference between '.to_polynomial()' and '.to_rational()' is
4540probably best illustrated with an example:
4541
4542     {
4543         symbol x("x"), y("y");
4544         ex a = 2*x/sin(x) - y/(3*sin(x));
4545         cout << a << endl;
4546
4547         exmap mp;
4548         ex p = a.to_polynomial(mp);
4549         cout << " = " << p << "\n   with " << mp << endl;
4550          // = symbol3*symbol2*y+2*symbol2*x
4551          //   with {symbol2==sin(x)^(-1),symbol3==-1/3}
4552
4553         exmap mr;
4554         ex r = a.to_rational(mr);
4555         cout << " = " << r << "\n   with " << mr << endl;
4556          // = -1/3*symbol4^(-1)*y+2*symbol4^(-1)*x
4557          //   with {symbol4==sin(x)}
4558     }
4559
4560The following more useful example will print 'sin(x)-cos(x)':
4561
4562     {
4563         symbol x("x");
4564         ex a = pow(sin(x), 2) - pow(cos(x), 2);
4565         ex b = sin(x) + cos(x);
4566         ex q;
4567         exmap m;
4568         divide(a.to_polynomial(m), b.to_polynomial(m), q);
4569         cout << q.subs(m) << endl;
4570     }
4571
4572
4573File: ginac.info,  Node: Symbolic differentiation,  Next: Series expansion,  Prev: Rational expressions,  Up: Methods and functions
4574
45755.9 Symbolic differentiation
4576============================
4577
4578GiNaC's objects know how to differentiate themselves.  Thus, a
4579polynomial (class 'add') knows that its derivative is the sum of the
4580derivatives of all the monomials:
4581
4582     {
4583         symbol x("x"), y("y"), z("z");
4584         ex P = pow(x, 5) + pow(x, 2) + y;
4585
4586         cout << P.diff(x,2) << endl;
4587          // -> 20*x^3 + 2
4588         cout << P.diff(y) << endl;    // 1
4589          // -> 1
4590         cout << P.diff(z) << endl;    // 0
4591          // -> 0
4592     }
4593
4594If a second integer parameter N is given, the 'diff' method returns the
4595Nth derivative.
4596
4597If _every_ object and every function is told what its derivative is, all
4598derivatives of composed objects can be calculated using the chain rule
4599and the product rule.  Consider, for instance the expression
4600'1/cosh(x)'.  Since the derivative of 'cosh(x)' is 'sinh(x)' and the
4601derivative of 'pow(x,-1)' is '-pow(x,-2)', GiNaC can readily compute the
4602composition.  It turns out that the composition is the generating
4603function for Euler Numbers, i.e.  the so called Nth Euler number is the
4604coefficient of 'x^n/n!' in the expansion of '1/cosh(x)'.  We may use
4605this identity to code a function that generates Euler numbers in just
4606three lines:
4607
4608     #include <ginac/ginac.h>
4609     using namespace GiNaC;
4610
4611     ex EulerNumber(unsigned n)
4612     {
4613         symbol x;
4614         const ex generator = pow(cosh(x),-1);
4615         return generator.diff(x,n).subs(x==0);
4616     }
4617
4618     int main()
4619     {
4620         for (unsigned i=0; i<11; i+=2)
4621             std::cout << EulerNumber(i) << std::endl;
4622         return 0;
4623     }
4624
4625When you run it, it produces the sequence '1', '-1', '5', '-61', '1385',
4626'-50521'.  We increment the loop variable 'i' by two since all odd Euler
4627numbers vanish anyways.
4628
4629
4630File: ginac.info,  Node: Series expansion,  Next: Symmetrization,  Prev: Symbolic differentiation,  Up: Methods and functions
4631
46325.10 Series expansion
4633=====================
4634
4635Expressions know how to expand themselves as a Taylor series or (more
4636generally) a Laurent series.  As in most conventional Computer Algebra
4637Systems, no distinction is made between those two.  There is a class of
4638its own for storing such series ('class pseries') and a built-in
4639function (called 'Order') for storing the order term of the series.  As
4640a consequence, if you want to work with series, i.e.  multiply two
4641series, you need to call the method 'ex::series' again to convert it to
4642a series object with the usual structure (expansion plus order term).  A
4643sample application from special relativity could read:
4644
4645     #include <ginac/ginac.h>
4646     using namespace std;
4647     using namespace GiNaC;
4648
4649     int main()
4650     {
4651         symbol v("v"), c("c");
4652
4653         ex gamma = 1/sqrt(1 - pow(v/c,2));
4654         ex mass_nonrel = gamma.series(v==0, 10);
4655
4656         cout << "the relativistic mass increase with v is " << endl
4657              << mass_nonrel << endl;
4658
4659         cout << "the inverse square of this series is " << endl
4660              << pow(mass_nonrel,-2).series(v==0, 10) << endl;
4661     }
4662
4663Only calling the series method makes the last output simplify to
46641-v^2/c^2+O(v^10), without that call we would just have a long series
4665raised to the power -2.
4666
4667As another instructive application, let us calculate the numerical value
4668of Archimedes' constant Pi (for which there already exists the built-in
4669constant 'Pi') using John Machin's amazing formula
4670Pi==16*atan(1/5)-4*atan(1/239).  This equation (and similar ones) were
4671used for over 200 years for computing digits of pi (see 'Pi Unleashed').
4672We may expand the arcus tangent around '0' and insert the fractions
4673'1/5' and '1/239'.  However, as we have seen, a series in GiNaC carries
4674an order term with it and the question arises what the system is
4675supposed to do when the fractions are plugged into that order term.  The
4676solution is to use the function 'series_to_poly()' to simply strip the
4677order term off:
4678
4679     #include <ginac/ginac.h>
4680     using namespace GiNaC;
4681
4682     ex machin_pi(int degr)
4683     {
4684         symbol x;
4685         ex pi_expansion = series_to_poly(atan(x).series(x,degr));
4686         ex pi_approx = 16*pi_expansion.subs(x==numeric(1,5))
4687                        -4*pi_expansion.subs(x==numeric(1,239));
4688         return pi_approx;
4689     }
4690
4691     int main()
4692     {
4693         using std::cout;  // just for fun, another way of...
4694         using std::endl;  // ...dealing with this namespace std.
4695         ex pi_frac;
4696         for (int i=2; i<12; i+=2) {
4697             pi_frac = machin_pi(i);
4698             cout << i << ":\t" << pi_frac << endl
4699                  << "\t" << pi_frac.evalf() << endl;
4700         }
4701         return 0;
4702     }
4703
4704Note how we just called '.series(x,degr)' instead of
4705'.series(x==0,degr)'.  This is a simple shortcut for 'ex''s method
4706'series()': if the first argument is a symbol the expression is expanded
4707in that symbol around point '0'.  When you run this program, it will
4708type out:
4709
4710     2:      3804/1195
4711             3.1832635983263598326
4712     4:      5359397032/1706489875
4713             3.1405970293260603143
4714     6:      38279241713339684/12184551018734375
4715             3.141621029325034425
4716     8:      76528487109180192540976/24359780855939418203125
4717             3.141591772182177295
4718     10:     327853873402258685803048818236/104359128170408663038552734375
4719             3.1415926824043995174
4720
4721
4722File: ginac.info,  Node: Symmetrization,  Next: Built-in functions,  Prev: Series expansion,  Up: Methods and functions
4723
47245.11 Symmetrization
4725===================
4726
4727The three methods
4728
4729     ex ex::symmetrize(const lst & l);
4730     ex ex::antisymmetrize(const lst & l);
4731     ex ex::symmetrize_cyclic(const lst & l);
4732
4733symmetrize an expression by returning the sum over all symmetric,
4734antisymmetric or cyclic permutations of the specified list of objects,
4735weighted by the number of permutations.
4736
4737The three additional methods
4738
4739     ex ex::symmetrize();
4740     ex ex::antisymmetrize();
4741     ex ex::symmetrize_cyclic();
4742
4743symmetrize or antisymmetrize an expression over its free indices.
4744
4745Symmetrization is most useful with indexed expressions but can be used
4746with almost any kind of object (anything that is 'subs()'able):
4747
4748     {
4749         idx i(symbol("i"), 3), j(symbol("j"), 3), k(symbol("k"), 3);
4750         symbol A("A"), B("B"), a("a"), b("b"), c("c");
4751
4752         cout << ex(indexed(A, i, j)).symmetrize() << endl;
4753          // -> 1/2*A.j.i+1/2*A.i.j
4754         cout << ex(indexed(A, i, j, k)).antisymmetrize(lst{i, j}) << endl;
4755          // -> -1/2*A.j.i.k+1/2*A.i.j.k
4756         cout << ex(lst{a, b, c}).symmetrize_cyclic(lst{a, b, c}) << endl;
4757          // -> 1/3*{a,b,c}+1/3*{b,c,a}+1/3*{c,a,b}
4758     }
4759
4760
4761File: ginac.info,  Node: Built-in functions,  Next: Multiple polylogarithms,  Prev: Symmetrization,  Up: Methods and functions
4762
47635.12 Predefined mathematical functions
4764======================================
4765
47665.12.1 Overview
4767---------------
4768
4769GiNaC contains the following predefined mathematical functions:
4770
4771*Name*                 *Function*
4772'abs(x)'               absolute value
4773'step(x)'              step function
4774'csgn(x)'              complex sign
4775'conjugate(x)'         complex conjugation
4776'real_part(x)'         real part
4777'imag_part(x)'         imaginary part
4778'sqrt(x)'              square root (not a GiNaC function, rather an
4779                       alias for 'pow(x, numeric(1, 2))')
4780'sin(x)'               sine
4781'cos(x)'               cosine
4782'tan(x)'               tangent
4783'asin(x)'              inverse sine
4784'acos(x)'              inverse cosine
4785'atan(x)'              inverse tangent
4786'atan2(y, x)'          inverse tangent with two arguments
4787'sinh(x)'              hyperbolic sine
4788'cosh(x)'              hyperbolic cosine
4789'tanh(x)'              hyperbolic tangent
4790'asinh(x)'             inverse hyperbolic sine
4791'acosh(x)'             inverse hyperbolic cosine
4792'atanh(x)'             inverse hyperbolic tangent
4793'exp(x)'               exponential function
4794'log(x)'               natural logarithm
4795'eta(x,y)'             Eta function: 'eta(x,y) = log(x*y) - log(x) -
4796                       log(y)'
4797'Li2(x)'               dilogarithm
4798'Li(m, x)'             classical polylogarithm as well as multiple
4799                       polylogarithm
4800'G(a, y)'              multiple polylogarithm
4801'G(a, s, y)'           multiple polylogarithm with explicit signs for
4802                       the imaginary parts
4803'S(n, p, x)'           Nielsen's generalized polylogarithm
4804'H(m, x)'              harmonic polylogarithm
4805'zeta(m)'              Riemann's zeta function as well as multiple zeta
4806                       value
4807'zeta(m, s)'           alternating Euler sum
4808'zetaderiv(n, x)'      derivatives of Riemann's zeta function
4809'iterated_integral(a,  iterated integral
4810y)'
4811'iterated_integral(a,  iterated integral with explicit truncation
4812y, N)'                 parameter
4813'tgamma(x)'            gamma function
4814'lgamma(x)'            logarithm of gamma function
4815'beta(x, y)'           beta function
4816                       ('tgamma(x)*tgamma(y)/tgamma(x+y)')
4817'psi(x)'               psi (digamma) function
4818'psi(n, x)'            derivatives of psi function (polygamma
4819                       functions)
4820'EllipticK(x)'         complete elliptic integral of the first kind
4821'EllipticE(x)'         complete elliptic integral of the second kind
4822'factorial(n)'         factorial function n!
4823'binomial(n, k)'       binomial coefficients
4824'Order(x)'             order term function in truncated power series
4825
4826For functions that have a branch cut in the complex plane, GiNaC follows
4827the conventions of C/C++ for systems that do not support a signed zero.
4828In particular: the natural logarithm ('log') and the square root
4829('sqrt') both have their branch cuts running along the negative real
4830axis.  The 'asin', 'acos', and 'atanh' functions all have two branch
4831cuts starting at +/-1 and running away towards infinity along the real
4832axis.  The 'atan' and 'asinh' functions have two branch cuts starting at
4833+/-i and running away towards infinity along the imaginary axis.  The
4834'acosh' function has one branch cut starting at +1 and running towards
4835-infinity.  These functions are continuous as the branch cut is
4836approached coming around the finite endpoint of the cut in a counter
4837clockwise direction.
4838
48395.12.2 Expanding functions
4840--------------------------
4841
4842GiNaC knows several expansion laws for trancedent functions, e.g.
4843'exp(a+b)=exp(a) exp(b), |zw|=|z| |w|' or 'log(cd)=log(c)+log(d)' (for
4844positive 'c, d' ).  In order to use these rules you need to call
4845'expand()' method with the option
4846'expand_options::expand_transcendental'.  Another relevant option is
4847'expand_options::expand_function_args'.  Their usage and interaction can
4848be seen from the following example:
4849     {
4850     	symbol x("x"),  y("y");
4851     	ex e=exp(pow(x+y,2));
4852     	cout << e.expand() << endl;
4853     	// -> exp((x+y)^2)
4854     	cout << e.expand(expand_options::expand_transcendental) << endl;
4855     	// -> exp((x+y)^2)
4856     	cout << e.expand(expand_options::expand_function_args) << endl;
4857     	// -> exp(2*x*y+x^2+y^2)
4858     	cout << e.expand(expand_options::expand_function_args
4859     			| expand_options::expand_transcendental) << endl;
4860     	// -> exp(y^2)*exp(2*x*y)*exp(x^2)
4861     }
4862If both flags are set (as in the last call), then GiNaC tries to get the
4863maximal expansion.  For example, for the exponent GiNaC firstly expands
4864the argument and then the function.  For the logarithm and absolute
4865value, GiNaC uses the opposite order: firstly expands the function and
4866then its argument.  Of course, a user can fine-tune this behavior by
4867sequential calls of several 'expand()' methods with desired flags.
4868
4869
4870File: ginac.info,  Node: Multiple polylogarithms,  Next: Iterated integrals,  Prev: Built-in functions,  Up: Methods and functions
4871
48725.12.3 Multiple polylogarithms
4873------------------------------
4874
4875The multiple polylogarithm is the most generic member of a family of
4876functions, to which others like the harmonic polylogarithm, Nielsen's
4877generalized polylogarithm and the multiple zeta value belong.  Each of
4878these functions can also be written as a multiple polylogarithm with
4879specific parameters.  This whole family of functions is therefore often
4880referred to simply as multiple polylogarithms, containing 'Li', 'G',
4881'H', 'S' and 'zeta'.  The multiple polylogarithm itself comes in two
4882variants: 'Li' and 'G'.  While 'Li' and 'G' in principle represent the
4883same function, the different notations are more natural to the series
4884representation or the integral representation, respectively.
4885
4886To facilitate the discussion of these functions we distinguish between
4887indices and arguments as parameters.  In the table above indices are
4888printed as 'm', 's', 'n' or 'p', whereas arguments are printed as 'x',
4889'a' and 'y'.
4890
4891To define a 'Li', 'H' or 'zeta' with a depth greater than one, you have
4892to pass a GiNaC 'lst' for the indices 'm' and 's', and in the case of
4893'Li' for the argument 'x' as well.  The parameter 'a' of 'G' must always
4894be a 'lst' containing the arguments in expanded form.  If 'G' is used
4895with a third parameter 's', 's' must have the same length as 'a'.  It
4896contains then the signs of the imaginary parts of the arguments.  If 's'
4897is not given, the signs default to +1.  Note that 'Li' and 'zeta' are
4898polymorphic in this respect.  They can stand in for the classical
4899polylogarithm and Riemann's zeta function (if depth is one), as well as
4900for the multiple polylogarithm and the multiple zeta value,
4901respectively.  Note also, that GiNaC doesn't check whether the 'lst's
4902for two parameters do have the same length.  It is up to the user to
4903ensure this, otherwise evaluating will result in undefined behavior.
4904
4905The functions print in LaTeX format as
4906'\mbox{Li}_{m_1,m_2,...,m_k}(x_1,x_2,...,x_k)', '\mbox{S}_{n,p}(x)',
4907'\mbox{H}_{m_1,m_2,...,m_k}(x)' and '\zeta(m_1,m_2,...,m_k)' (with the
4908dots replaced by actual parameters).  If 'zeta' is an alternating zeta
4909sum, i.e.  'zeta(m,s)', the indices with negative sign are printed with
4910a line above, e.g.  '\zeta(5,\overline{2})'.  The order of indices and
4911arguments in the GiNaC 'lst's and in the output is the same.
4912
4913Definitions and analytical as well as numerical properties of multiple
4914polylogarithms are too numerous to be covered here.  Instead, the user
4915is referred to the publications listed at the end of this section.  The
4916implementation in GiNaC adheres to the definitions and conventions
4917therein, except for a few differences which will be explicitly stated in
4918the following.
4919
4920One difference is about the order of the indices and arguments.  For
4921GiNaC we adopt the convention that the indices and arguments are
4922understood to be in the same order as in which they appear in the series
4923representation.  This means 'Li_{m_1,m_2,m_3}(x,1,1) =
4924H_{m_1,m_2,m_3}(x)' and 'Li_{2,1}(1,1) = zeta(2,1) = zeta(3)', but
4925'zeta(1,2)' evaluates to infinity.  So in comparison to the older ones
4926of the referenced publications the order of indices and arguments for
4927'Li' is reversed.
4928
4929The functions only evaluate if the indices are integers greater than
4930zero, except for the indices 's' in 'zeta' and 'G' as well as 'm' in
4931'H'.  Since 's' will be interpreted as the sequence of signs for the
4932corresponding indices 'm' or the sign of the imaginary part for the
4933corresponding arguments 'a', it must contain 1 or -1, e.g.
4934'zeta(lst{3,4}, lst{-1,1})' means 'zeta(\overline{3},4)' and
4935'G(lst{a,b}, lst{-1,1}, c)' means 'G(a-0\epsilon,b+0\epsilon;c)'.  The
4936definition of 'H' allows indices to be 0, 1 or -1 (in expanded notation)
4937or equally to be any integer (in compact notation).  With GiNaC expanded
4938and compact notation can be mixed, e.g.  'lst{0,0,-1,0,1,0,0}',
4939'lst{0,0,-1,2,0,0}' and 'lst{-3,2,0,0}' are equivalent as indices.  The
4940anonymous evaluator 'eval()' tries to reduce the functions, if possible,
4941to the least-generic multiple polylogarithm.  If all arguments are unit,
4942it returns 'zeta'.  Arguments equal to zero get considered, too.
4943Riemann's zeta function 'zeta' (with depth one) evaluates also for
4944negative integers and positive even integers.  For example:
4945
4946     > Li({3,1},{x,1});
4947     S(2,2,x)
4948     > H({-3,2},1);
4949     -zeta({3,2},{-1,-1})
4950     > S(3,1,1);
4951     1/90*Pi^4
4952
4953It is easy to tell for a given function into which other function it can
4954be rewritten, may it be a less-generic or a more-generic one, except for
4955harmonic polylogarithms 'H' with negative indices or trailing zeros (the
4956example above gives a hint).  Signs can quickly be messed up, for
4957example.  Therefore GiNaC offers a C++ function 'convert_H_to_Li()' to
4958deal with the upgrade of a 'H' to a multiple polylogarithm 'Li'
4959('eval()' already cares for the possible downgrade):
4960
4961     > convert_H_to_Li({0,-2,-1,3},x);
4962     Li({3,1,3},{-x,1,-1})
4963     > convert_H_to_Li({2,-1,0},x);
4964     -Li({2,1},{x,-1})*log(x)+2*Li({3,1},{x,-1})+Li({2,2},{x,-1})
4965
4966Every function can be numerically evaluated for arbitrary real or
4967complex arguments.  The precision is arbitrary and can be set through
4968the global variable 'Digits':
4969
4970     > Digits=100;
4971     100
4972     > evalf(zeta({3,1,3,1}));
4973     0.005229569563530960100930652283899231589890420784634635522547448972148869544...
4974
4975Note that the convention for arguments on the branch cut in GiNaC as
4976stated above is different from the one Remiddi and Vermaseren have
4977chosen for the harmonic polylogarithm.
4978
4979If a function evaluates to infinity, no exceptions are raised, but the
4980function is returned unevaluated, e.g.  'zeta(1)'.  In long expressions
4981this helps a lot with debugging, because you can easily spot the
4982divergencies.  But on the other hand, you have to make sure for
4983yourself, that no illegal cancellations of divergencies happen.
4984
4985Useful publications:
4986
4987'Nested Sums, Expansion of Transcendental Functions and Multi-Scale
4988Multi-Loop Integrals', S.Moch, P.Uwer, S.Weinzierl, hep-ph/0110083
4989
4990'Harmonic Polylogarithms', E.Remiddi, J.A.M.Vermaseren, Int.J.Mod.Phys.
4991A15 (2000), pp.  725-754
4992
4993'Special Values of Multiple Polylogarithms', J.Borwein, D.Bradley,
4994D.Broadhurst, P.Lisonek, Trans.Amer.Math.Soc.  353/3 (2001), pp.
4995907-941
4996
4997'Numerical Evaluation of Multiple Polylogarithms', J.Vollinga,
4998S.Weinzierl, hep-ph/0410259
4999
5000
5001File: ginac.info,  Node: Iterated integrals,  Next: Complex expressions,  Prev: Multiple polylogarithms,  Up: Methods and functions
5002
50035.12.4 Iterated integrals
5004-------------------------
5005
5006Multiple polylogarithms are a particular example of iterated integrals.
5007An iterated integral is defined by the function
5008'iterated_integral(a,y)'.  The variable 'y' gives the upper integration
5009limit for the outermost integration, by convention the lower integration
5010limit is always set to zero.  The variable 'a' must be a GiNaC 'lst'
5011containing sub-classes of 'integration_kernel' as elements.  The depth
5012of the iterated integral corresponds to the number of elements of 'a'.
5013The available integrands for iterated integrals are (for a more detailed
5014description the user is referred to the publications listed at the end
5015of this section)
5016*Class*                       *Description*
5017'integration_kernel()'        Base class, represents the one-form dy
5018'basic_log_kernel()'          Logarithmic one-form dy/y
5019'multiple_polylog_kernel(z_j)'The one-form dy/(y-z_j)
5020'ELi_kernel(n, m, x, y)'      The one form ELi_{n;m}(x;y;q) dq/q
5021'Ebar_kernel(n, m, x, y)'     The one form \overline{E}_{n;m}(x;y;q)
5022                              dq/q
5023'Kronecker_dtau_kernel(k,     The one form C_k K (k-1)/(2 \pi i)^k
5024z_j, K, C_k)'                 g^{(k)}(z_j,K \tau) dq/q
5025'Kronecker_dz_kernel(k,       The one form C_k (2 \pi i)^{2-k}
5026z_j, tau, K, C_k)'            g^{(k-1)}(z-z_j,K \tau) dz
5027'Eisenstein_kernel(k, N, a,   The one form C_k E_{k,N,a,b,K}(\tau) dq/q
5028b, K, C_k)'
5029'Eisenstein_h_kernel(k, N,    The one form C_k h_{k,N,r,s}(\tau) dq/q
5030r, s, C_k)'
5031'modular_form_kernel(k, P,    The one form C_k P dq/q
5032C_k)'
5033'user_defined_kernel(f, y)'   The one form f(y) dy
5034All parameters are assumed to be such that all integration kernels have
5035a convergent Laurent expansion around zero with at most a simple pole at
5036zero.  The iterated integral may also be called with an optional third
5037parameter 'iterated_integral(a,y,N_trunc)', in which case the numerical
5038evaluation will truncate the series expansion at order 'N_trunc'.
5039
5040The classes 'Eisenstein_kernel()', 'Eisenstein_h_kernel()' and
5041'modular_form_kernel()' provide a method 'q_expansion_modular_form(q,
5042order)', which can used to obtain the q-expansion of
5043E_{k,N,a,b,K}(\tau), h_{k,N,r,s}(\tau) or P to the specified order.
5044
5045Useful publications:
5046
5047'Numerical evaluation of iterated integrals related to elliptic Feynman
5048integrals', M.Walden, S.Weinzierl, arXiv:2010.05271
5049
5050
5051File: ginac.info,  Node: Complex expressions,  Next: Solving linear systems of equations,  Prev: Iterated integrals,  Up: Methods and functions
5052
50535.13 Complex expressions
5054========================
5055
5056For dealing with complex expressions there are the methods
5057
5058     ex ex::conjugate();
5059     ex ex::real_part();
5060     ex ex::imag_part();
5061
5062that return respectively the complex conjugate, the real part and the
5063imaginary part of an expression.  Complex conjugation works as expected
5064for all built-in functions and objects.  Taking real and imaginary parts
5065has not yet been implemented for all built-in functions.  In cases where
5066it is not known how to conjugate or take a real/imaginary part one of
5067the functions 'conjugate', 'real_part' or 'imag_part' is returned.  For
5068instance, in case of a complex symbol 'x' (symbols are complex by
5069default), one could not simplify 'conjugate(x)'.  In the case of strings
5070of gamma matrices, the 'conjugate' method takes the Dirac conjugate.
5071
5072For example,
5073     {
5074         varidx a(symbol("a"), 4), b(symbol("b"), 4);
5075         symbol x("x");
5076         realsymbol y("y");
5077
5078         cout << (3*I*x*y + sin(2*Pi*I*y)).conjugate() << endl;
5079          // -> -3*I*conjugate(x)*y+sin(-2*I*Pi*y)
5080         cout << (dirac_gamma(a)*dirac_gamma(b)*dirac_gamma5()).conjugate() << endl;
5081          // -> -gamma5*gamma~b*gamma~a
5082     }
5083
5084If you declare your own GiNaC functions and you want to conjugate them,
5085you will have to supply a specialized conjugation method for them (see
5086*note Symbolic functions:: and the GiNaC source-code for 'abs' as an
5087example).  GiNaC does not automatically conjugate user-supplied
5088functions by conjugating their arguments because this would be incorrect
5089on branch cuts.  Also, specialized methods can be provided to take real
5090and imaginary parts of user-defined functions.
5091
5092
5093File: ginac.info,  Node: Solving linear systems of equations,  Next: Input/output,  Prev: Complex expressions,  Up: Methods and functions
5094
50955.14 Solving linear systems of equations
5096========================================
5097
5098The function 'lsolve()' provides a convenient wrapper around some matrix
5099operations that comes in handy when a system of linear equations needs
5100to be solved:
5101
5102     ex lsolve(const ex & eqns, const ex & symbols,
5103               unsigned options = solve_algo::automatic);
5104
5105Here, 'eqns' is a 'lst' of equalities (i.e.  class 'relational') while
5106'symbols' is a 'lst' of indeterminates.  (*Note The class hierarchy::,
5107for an exposition of class 'lst').
5108
5109It returns the 'lst' of solutions as an expression.  As an example, let
5110us solve the two equations 'a*x+b*y==3' and 'x-y==b':
5111
5112     {
5113         symbol a("a"), b("b"), x("x"), y("y");
5114         lst eqns = {a*x+b*y==3, x-y==b};
5115         lst vars = {x, y};
5116         cout << lsolve(eqns, vars) << endl;
5117          // -> {x==(3+b^2)/(b+a),y==(3-b*a)/(b+a)}
5118
5119When the linear equations 'eqns' are underdetermined, the solution will
5120contain one or more tautological entries like 'x==x', depending on the
5121rank of the system.  When they are overdetermined, the solution will be
5122an empty 'lst'.  Note the third optional parameter to 'lsolve()': it
5123accepts the same parameters as 'matrix::solve()'.  This is because
5124'lsolve' is just a wrapper around that method.
5125
5126
5127File: ginac.info,  Node: Input/output,  Next: Extending GiNaC,  Prev: Solving linear systems of equations,  Up: Methods and functions
5128
51295.15 Input and output of expressions
5130====================================
5131
51325.15.1 Expression output
5133------------------------
5134
5135Expressions can simply be written to any stream:
5136
5137     {
5138         symbol x("x");
5139         ex e = 4.5*I+pow(x,2)*3/2;
5140         cout << e << endl;    // prints '4.5*I+3/2*x^2'
5141         // ...
5142
5143The default output format is identical to the 'ginsh' input syntax and
5144to that used by most computer algebra systems, but not directly pastable
5145into a GiNaC C++ program (note that in the above example, 'pow(x,2)' is
5146printed as 'x^2').
5147
5148It is possible to print expressions in a number of different formats
5149with a set of stream manipulators;
5150
5151     std::ostream & dflt(std::ostream & os);
5152     std::ostream & latex(std::ostream & os);
5153     std::ostream & tree(std::ostream & os);
5154     std::ostream & csrc(std::ostream & os);
5155     std::ostream & csrc_float(std::ostream & os);
5156     std::ostream & csrc_double(std::ostream & os);
5157     std::ostream & csrc_cl_N(std::ostream & os);
5158     std::ostream & index_dimensions(std::ostream & os);
5159     std::ostream & no_index_dimensions(std::ostream & os);
5160
5161The 'tree', 'latex' and 'csrc' formats are also available in 'ginsh' via
5162the 'print()', 'print_latex()' and 'print_csrc()' functions,
5163respectively.
5164
5165All manipulators affect the stream state permanently.  To reset the
5166output format to the default, use the 'dflt' manipulator:
5167
5168         // ...
5169         cout << latex;            // all output to cout will be in LaTeX format from
5170                                   // now on
5171         cout << e << endl;        // prints '4.5 i+\frac{3}{2} x^{2}'
5172         cout << sin(x/2) << endl; // prints '\sin(\frac{1}{2} x)'
5173         cout << dflt;             // revert to default output format
5174         cout << e << endl;        // prints '4.5*I+3/2*x^2'
5175         // ...
5176
5177If you don't want to affect the format of the stream you're working
5178with, you can output to a temporary 'ostringstream' like this:
5179
5180         // ...
5181         ostringstream s;
5182         s << latex << e;         // format of cout remains unchanged
5183         cout << s.str() << endl; // prints '4.5 i+\frac{3}{2} x^{2}'
5184         // ...
5185
5186The 'csrc' (an alias for 'csrc_double'), 'csrc_float', 'csrc_double' and
5187'csrc_cl_N' manipulators set the output to a format that can be directly
5188used in a C or C++ program.  The three possible formats select the data
5189types used for numbers ('csrc_cl_N' uses the classes provided by the CLN
5190library):
5191
5192         // ...
5193         cout << "f = " << csrc_float << e << ";\n";
5194         cout << "d = " << csrc_double << e << ";\n";
5195         cout << "n = " << csrc_cl_N << e << ";\n";
5196         // ...
5197
5198The above example will produce (note the 'x^2' being converted to
5199'x*x'):
5200
5201     f = (3.0/2.0)*(x*x)+std::complex<float>(0.0,4.5000000e+00);
5202     d = (3.0/2.0)*(x*x)+std::complex<double>(0.0,4.5000000000000000e+00);
5203     n = cln::cl_RA("3/2")*(x*x)+cln::complex(cln::cl_I("0"),cln::cl_F("4.5_17"));
5204
5205The 'tree' manipulator allows dumping the internal structure of an
5206expression for debugging purposes:
5207
5208         // ...
5209         cout << tree << e;
5210     }
5211
5212produces
5213
5214     add, hash=0x0, flags=0x3, nops=2
5215         power, hash=0x0, flags=0x3, nops=2
5216             x (symbol), serial=0, hash=0xc8d5bcdd, flags=0xf
5217             2 (numeric), hash=0x6526b0fa, flags=0xf
5218         3/2 (numeric), hash=0xf9828fbd, flags=0xf
5219         -----
5220         overall_coeff
5221         4.5L0i (numeric), hash=0xa40a97e0, flags=0xf
5222         =====
5223
5224The 'latex' output format is for LaTeX parsing in mathematical mode.  It
5225is rather similar to the default format but provides some braces needed
5226by LaTeX for delimiting boxes and also converts some common objects to
5227conventional LaTeX names.  It is possible to give symbols a special name
5228for LaTeX output by supplying it as a second argument to the 'symbol'
5229constructor.
5230
5231For example, the code snippet
5232
5233     {
5234         symbol x("x", "\\circ");
5235         ex e = lgamma(x).series(x==0,3);
5236         cout << latex << e << endl;
5237     }
5238
5239will print
5240
5241         {(-\ln(\circ))}+{(-\gamma_E)} \circ+{(\frac{1}{12} \pi^{2})} \circ^{2}
5242         +\mathcal{O}(\circ^{3})
5243
5244Index dimensions are normally hidden in the output.  To make them
5245visible, use the 'index_dimensions' manipulator.  The dimensions will be
5246written in square brackets behind each index value in the default and
5247LaTeX output formats:
5248
5249     {
5250         symbol x("x"), y("y");
5251         varidx mu(symbol("mu"), 4), nu(symbol("nu"), 4);
5252         ex e = indexed(x, mu) * indexed(y, nu);
5253
5254         cout << e << endl;
5255          // prints 'x~mu*y~nu'
5256         cout << index_dimensions << e << endl;
5257          // prints 'x~mu[4]*y~nu[4]'
5258         cout << no_index_dimensions << e << endl;
5259          // prints 'x~mu*y~nu'
5260     }
5261
5262If you need any fancy special output format, e.g.  for interfacing GiNaC
5263with other algebra systems or for producing code for different
5264programming languages, you can always traverse the expression tree
5265yourself:
5266
5267     static void my_print(const ex & e)
5268     {
5269         if (is_a<function>(e))
5270             cout << ex_to<function>(e).get_name();
5271         else
5272             cout << ex_to<basic>(e).class_name();
5273         cout << "(";
5274         size_t n = e.nops();
5275         if (n)
5276             for (size_t i=0; i<n; i++) {
5277                 my_print(e.op(i));
5278                 if (i != n-1)
5279                     cout << ",";
5280             }
5281         else
5282             cout << e;
5283         cout << ")";
5284     }
5285
5286     int main()
5287     {
5288         my_print(pow(3, x) - 2 * sin(y / Pi)); cout << endl;
5289         return 0;
5290     }
5291
5292This will produce
5293
5294     add(power(numeric(3),symbol(x)),mul(sin(mul(power(constant(Pi),numeric(-1)),
5295     symbol(y))),numeric(-2)))
5296
5297If you need an output format that makes it possible to accurately
5298reconstruct an expression by feeding the output to a suitable parser or
5299object factory, you should consider storing the expression in an
5300'archive' object and reading the object properties from there.  See the
5301section on archiving for more information.
5302
53035.15.2 Expression input
5304-----------------------
5305
5306GiNaC provides no way to directly read an expression from a stream
5307because you will usually want the user to be able to enter something
5308like '2*x+sin(y)' and have the 'x' and 'y' correspond to the symbols 'x'
5309and 'y' you defined in your program and there is no way to specify the
5310desired symbols to the '>>' stream input operator.
5311
5312Instead, GiNaC lets you read an expression from a stream or a string,
5313specifying the mapping between the input strings and symbols to be used:
5314
5315     {
5316         symbol x, y;
5317         symtab table;
5318         table["x"] = x;
5319         table["y"] = y;
5320         parser reader(table);
5321         ex e = reader("2*x+sin(y)");
5322     }
5323
5324The input syntax is the same as that used by 'ginsh' and the stream
5325output operator '<<'.  Matching between the input strings and
5326expressions is given by 'table'.  The 'table' in this example instructs
5327GiNaC to substitute any input substring "x" with symbol 'x'.  Likewise,
5328the substring "y" will be replaced with symbol 'y'.  It's also possible
5329to map input (sub)strings to arbitrary expressions:
5330
5331     {
5332         symbol x, y;
5333         symtab table;
5334         table["x"] = x+log(y)+1;
5335         parser reader(table);
5336         ex e = reader("5*x^3 - x^2");
5337         // e = 5*(x+log(y)+1)^3 - (x+log(y)+1)^2
5338     }
5339
5340If no mapping is specified for a particular string GiNaC will create a
5341symbol with corresponding name.  Later on you can obtain all parser
5342generated symbols with 'get_syms()' method:
5343
5344     {
5345         parser reader;
5346         ex e = reader("2*x+sin(y)");
5347         symtab table = reader.get_syms();
5348         symbol x = ex_to<symbol>(table["x"]);
5349         symbol y = ex_to<symbol>(table["y"]);
5350     }
5351
5352Sometimes you might want to prevent GiNaC from inserting these extra
5353symbols (for example, you want treat an unexpected string in the input
5354as an error).
5355
5356     {
5357     	symtab table;
5358     	table["x"] = symbol();
5359     	parser reader(table);
5360     	parser.strict = true;
5361     	ex e;
5362     	try {
5363     		e = reader("2*x+sin(y)");
5364     	} catch (parse_error& err) {
5365     		cerr << err.what() << endl;
5366     		// prints "unknown symbol "y" in the input"
5367     	}
5368     }
5369
5370With this parser, it's also easy to implement interactive GiNaC
5371programs.  When running the following program interactively, remember to
5372send an EOF marker after the input, e.g.  by pressing Ctrl-D on an empty
5373line:
5374
5375     #include <iostream>
5376     #include <string>
5377     #include <stdexcept>
5378     #include <ginac/ginac.h>
5379     using namespace std;
5380     using namespace GiNaC;
5381
5382     int main()
5383     {
5384     	cout << "Enter an expression containing 'x': " << flush;
5385     	parser reader;
5386
5387     	try {
5388     		ex e = reader(cin);
5389     		symtab table = reader.get_syms();
5390     		symbol x = table.find("x") != table.end() ?
5391     			   ex_to<symbol>(table["x"]) : symbol("x");
5392     		cout << "The derivative of " << e << " with respect to x is ";
5393     		cout << e.diff(x) << "." << endl;
5394     	} catch (exception &p) {
5395     		cerr << p.what() << endl;
5396     	}
5397     }
5398
53995.15.3 Compiling expressions to C function pointers
5400---------------------------------------------------
5401
5402Numerical evaluation of algebraic expressions is seamlessly integrated
5403into GiNaC by help of the CLN library.  While CLN allows for very fast
5404arbitrary precision numerics, which is more than sufficient for most
5405users, sometimes only the speed of built-in floating point numbers is
5406fast enough, e.g.  for Monte Carlo integration.  The only viable option
5407then is the following: print the expression in C syntax format, manually
5408add necessary C code, compile that program and run is as a separate
5409application.  This is not only cumbersome and involves a lot of manual
5410intervention, but it also separates the algebraic and the numerical
5411evaluation into different execution stages.
5412
5413GiNaC offers a couple of functions that help to avoid these
5414inconveniences and problems.  The functions automatically perform the
5415printing of a GiNaC expression and the subsequent compiling of its
5416associated C code.  The created object code is then dynamically linked
5417to the currently running program.  A function pointer to the C function
5418that performs the numerical evaluation is returned and can be used
5419instantly.  This all happens automatically, no user intervention is
5420needed.
5421
5422The following example demonstrates the use of 'compile_ex':
5423
5424         // ...
5425         symbol x("x");
5426         ex myexpr = sin(x) / x;
5427
5428         FUNCP_1P fp;
5429         compile_ex(myexpr, x, fp);
5430
5431         cout << fp(3.2) << endl;
5432         // ...
5433
5434The function 'compile_ex' is called with the expression to be compiled
5435and its only free variable 'x'.  Upon successful completion the third
5436parameter contains a valid function pointer to the corresponding C code
5437module.  If called like in the last line only built-in double precision
5438numerics is involved.
5439
5440The function pointer has to be defined in advance.  GiNaC offers three
5441function pointer types at the moment:
5442
5443         typedef double (*FUNCP_1P) (double);
5444         typedef double (*FUNCP_2P) (double, double);
5445         typedef void (*FUNCP_CUBA) (const int*, const double[], const int*, double[]);
5446
5447'FUNCP_2P' allows for two variables in the expression.  'FUNCP_CUBA' is
5448the correct type to be used with the CUBA library
5449(<http://www.feynarts.de/cuba>) for numerical integrations.  The details
5450for the parameters of 'FUNCP_CUBA' are explained in the CUBA manual.
5451
5452For every function pointer type there is a matching 'compile_ex'
5453available:
5454
5455         void compile_ex(const ex& expr, const symbol& sym, FUNCP_1P& fp,
5456                         const std::string filename = "");
5457         void compile_ex(const ex& expr, const symbol& sym1, const symbol& sym2,
5458                         FUNCP_2P& fp, const std::string filename = "");
5459         void compile_ex(const lst& exprs, const lst& syms, FUNCP_CUBA& fp,
5460                         const std::string filename = "");
5461
5462When the last parameter 'filename' is not supplied, 'compile_ex' will
5463choose a unique random name for the intermediate source and object files
5464it produces.  On program termination these files will be deleted.  If
5465one wishes to keep the C code and the object files, one can supply the
5466'filename' parameter.  The intermediate files will use that filename and
5467will not be deleted.
5468
5469'link_ex' is a function that allows to dynamically link an existing
5470object file and to make it available via a function pointer.  This is
5471useful if you have already used 'compile_ex' on an expression and want
5472to avoid the compilation step to be performed over and over again when
5473you restart your program.  The precondition for this is of course, that
5474you have chosen a filename when you did call 'compile_ex'.  For every
5475above mentioned function pointer type there exists a corresponding
5476'link_ex' function:
5477
5478         void link_ex(const std::string filename, FUNCP_1P& fp);
5479         void link_ex(const std::string filename, FUNCP_2P& fp);
5480         void link_ex(const std::string filename, FUNCP_CUBA& fp);
5481
5482The complete filename (including the suffix '.so') of the object file
5483has to be supplied.
5484
5485The function
5486
5487         void unlink_ex(const std::string filename);
5488
5489is supplied for the rare cases when one wishes to close the dynamically
5490linked object files directly and have the intermediate files (only if
5491filename has not been given) deleted.  Normally one doesn't need this
5492function, because all the clean-up will be done automatically upon
5493(regular) program termination.
5494
5495All the described functions will throw an exception in case they cannot
5496perform correctly, like for example when writing the file or starting
5497the compiler fails.  Since internally the same printing methods as
5498described in section *note csrc printing:: are used, only functions and
5499objects that are available in standard C will compile successfully (that
5500excludes polylogarithms for example at the moment).  Another
5501precondition for success is, of course, that it must be possible to
5502evaluate the expression numerically.  No free variables despite the ones
5503supplied to 'compile_ex' should appear in the expression.
5504
5505'compile_ex' uses the shell script 'ginac-excompiler' to start the C
5506compiler and produce the object files.  This shell script comes with
5507GiNaC and will be installed together with GiNaC in the configured
5508'$LIBEXECDIR' (typically '$PREFIX/libexec' or '$PREFIX/lib/ginac').  You
5509can also export additional compiler flags via the '$CXXFLAGS' variable:
5510
5511     setenv("CXXFLAGS", "-O3 -fomit-frame-pointer -ffast-math", 1);
5512     compile_ex(...);
5513
55145.15.4 Archiving
5515----------------
5516
5517GiNaC allows creating "archives" of expressions which can be stored to
5518or retrieved from files.  To create an archive, you declare an object of
5519class 'archive' and archive expressions in it, giving each expression a
5520unique name:
5521
5522     #include <fstream>
5523     #include <ginac/ginac.h>
5524     using namespace std;
5525     using namespace GiNaC;
5526
5527     int main()
5528     {
5529         symbol x("x"), y("y"), z("z");
5530
5531         ex foo = sin(x + 2*y) + 3*z + 41;
5532         ex bar = foo + 1;
5533
5534         archive a;
5535         a.archive_ex(foo, "foo");
5536         a.archive_ex(bar, "the second one");
5537         // ...
5538
5539The archive can then be written to a file:
5540
5541         // ...
5542         ofstream out("foobar.gar", ios::binary);
5543         out << a;
5544         out.close();
5545         // ...
5546
5547The file 'foobar.gar' contains all information that is needed to
5548reconstruct the expressions 'foo' and 'bar'.  The flag 'ios::binary'
5549prevents locales setting of your OS tampers the archive file structure.
5550
5551The tool 'viewgar' that comes with GiNaC can be used to view the
5552contents of GiNaC archive files:
5553
5554     $ viewgar foobar.gar
5555     foo = 41+sin(x+2*y)+3*z
5556     the second one = 42+sin(x+2*y)+3*z
5557
5558The point of writing archive files is of course that they can later be
5559read in again:
5560
5561         // ...
5562         archive a2;
5563         ifstream in("foobar.gar", ios::binary);
5564         in >> a2;
5565         // ...
5566
5567And the stored expressions can be retrieved by their name:
5568
5569         // ...
5570         lst syms = {x, y};
5571
5572         ex ex1 = a2.unarchive_ex(syms, "foo");
5573         ex ex2 = a2.unarchive_ex(syms, "the second one");
5574
5575         cout << ex1 << endl;              // prints "41+sin(x+2*y)+3*z"
5576         cout << ex2 << endl;              // prints "42+sin(x+2*y)+3*z"
5577         cout << ex1.subs(x == 2) << endl; // prints "41+sin(2+2*y)+3*z"
5578     }
5579
5580Note that you have to supply a list of the symbols which are to be
5581inserted in the expressions.  Symbols in archives are stored by their
5582name only and if you don't specify which symbols you have, unarchiving
5583the expression will create new symbols with that name.  E.g.  if you
5584hadn't included 'x' in the 'syms' list above, the 'ex1.subs(x == 2)'
5585statement would have had no effect because the 'x' in 'ex1' would have
5586been a different symbol than the 'x' which was defined at the beginning
5587of the program, although both would appear as 'x' when printed.
5588
5589You can also use the information stored in an 'archive' object to output
5590expressions in a format suitable for exact reconstruction.  The
5591'archive' and 'archive_node' classes have a couple of member functions
5592that let you access the stored properties:
5593
5594     static void my_print2(const archive_node & n)
5595     {
5596         string class_name;
5597         n.find_string("class", class_name);
5598         cout << class_name << "(";
5599
5600         archive_node::propinfovector p;
5601         n.get_properties(p);
5602
5603         size_t num = p.size();
5604         for (size_t i=0; i<num; i++) {
5605             const string &name = p[i].name;
5606             if (name == "class")
5607                 continue;
5608             cout << name << "=";
5609
5610             unsigned count = p[i].count;
5611             if (count > 1)
5612                 cout << "{";
5613
5614             for (unsigned j=0; j<count; j++) {
5615                 switch (p[i].type) {
5616                     case archive_node::PTYPE_BOOL: {
5617                         bool x;
5618                         n.find_bool(name, x, j);
5619                         cout << (x ? "true" : "false");
5620                         break;
5621                     }
5622                     case archive_node::PTYPE_UNSIGNED: {
5623                         unsigned x;
5624                         n.find_unsigned(name, x, j);
5625                         cout << x;
5626                         break;
5627                     }
5628                     case archive_node::PTYPE_STRING: {
5629                         string x;
5630                         n.find_string(name, x, j);
5631                         cout << '\"' << x << '\"';
5632                         break;
5633                     }
5634                     case archive_node::PTYPE_NODE: {
5635                         const archive_node &x = n.find_ex_node(name, j);
5636                         my_print2(x);
5637                         break;
5638                     }
5639                 }
5640
5641                 if (j != count-1)
5642                     cout << ",";
5643             }
5644
5645             if (count > 1)
5646                 cout << "}";
5647
5648             if (i != num-1)
5649                 cout << ",";
5650         }
5651
5652         cout << ")";
5653     }
5654
5655     int main()
5656     {
5657         ex e = pow(2, x) - y;
5658         archive ar(e, "e");
5659         my_print2(ar.get_top_node(0)); cout << endl;
5660         return 0;
5661     }
5662
5663This will produce:
5664
5665     add(rest={power(basis=numeric(number="2"),exponent=symbol(name="x")),
5666     symbol(name="y")},coeff={numeric(number="1"),numeric(number="-1")},
5667     overall_coeff=numeric(number="0"))
5668
5669Be warned, however, that the set of properties and their meaning for
5670each class may change between GiNaC versions.
5671
5672
5673File: ginac.info,  Node: Extending GiNaC,  Next: What does not belong into GiNaC,  Prev: Input/output,  Up: Top
5674
56756 Extending GiNaC
5676*****************
5677
5678By reading so far you should have gotten a fairly good understanding of
5679GiNaC's design patterns.  From here on you should start reading the
5680sources.  All we can do now is issue some recommendations how to tackle
5681GiNaC's many loose ends in order to fulfill everybody's dreams.  If you
5682develop some useful extension please don't hesitate to contact the GiNaC
5683authors--they will happily incorporate them into future versions.
5684
5685* Menu:
5686
5687* What does not belong into GiNaC::  What to avoid.
5688* Symbolic functions::               Implementing symbolic functions.
5689* Printing::                         Adding new output formats.
5690* Structures::                       Defining new algebraic classes (the easy way).
5691* Adding classes::                   Defining new algebraic classes (the hard way).
5692
5693
5694File: ginac.info,  Node: What does not belong into GiNaC,  Next: Symbolic functions,  Prev: Extending GiNaC,  Up: Extending GiNaC
5695
56966.1 What doesn't belong into GiNaC
5697==================================
5698
5699First of all, GiNaC's name must be read literally.  It is designed to be
5700a library for use within C++.  The tiny 'ginsh' accompanying GiNaC makes
5701this even more clear: it doesn't even attempt to provide a language.
5702There are no loops or conditional expressions in 'ginsh', it is merely a
5703window into the library for the programmer to test stuff (or to show
5704off).  Still, the design of a complete CAS with a language of its own,
5705graphical capabilities and all this on top of GiNaC is possible and is
5706without doubt a nice project for the future.
5707
5708There are many built-in functions in GiNaC that do not know how to
5709evaluate themselves numerically to a precision declared at runtime
5710(using 'Digits').  Some may be evaluated at certain points, but not
5711generally.  This ought to be fixed.  However, doing numerical
5712computations with GiNaC's quite abstract classes is doomed to be
5713inefficient.  For this purpose, the underlying foundation classes
5714provided by CLN are much better suited.
5715
5716
5717File: ginac.info,  Node: Symbolic functions,  Next: Printing,  Prev: What does not belong into GiNaC,  Up: Extending GiNaC
5718
57196.2 Symbolic functions
5720======================
5721
5722The easiest and most instructive way to start extending GiNaC is
5723probably to create your own symbolic functions.  These are implemented
5724with the help of two preprocessor macros:
5725
5726     DECLARE_FUNCTION_<n>P(<name>)
5727     REGISTER_FUNCTION(<name>, <options>)
5728
5729The 'DECLARE_FUNCTION' macro will usually appear in a header file.  It
5730declares a C++ function with the given 'name' that takes exactly 'n'
5731parameters of type 'ex' and returns a newly constructed GiNaC 'function'
5732object that represents your function.
5733
5734The 'REGISTER_FUNCTION' macro implements the function.  It must be
5735passed the same 'name' as the respective 'DECLARE_FUNCTION' macro, and a
5736set of options that associate the symbolic function with C++ functions
5737you provide to implement the various methods such as evaluation,
5738derivative, series expansion etc.  They also describe additional
5739attributes the function might have, such as symmetry and commutation
5740properties, and a name for LaTeX output.  Multiple options are separated
5741by the member access operator '.' and can be given in an arbitrary
5742order.
5743
5744(By the way: in case you are worrying about all the macros above we can
5745assure you that functions are GiNaC's most macro-intense classes.  We
5746have done our best to avoid macros where we can.)
5747
57486.2.1 A minimal example
5749-----------------------
5750
5751Here is an example for the implementation of a function with two
5752arguments that is not further evaluated:
5753
5754     DECLARE_FUNCTION_2P(myfcn)
5755
5756     REGISTER_FUNCTION(myfcn, dummy())
5757
5758Any code that has seen the 'DECLARE_FUNCTION' line can use 'myfcn()' in
5759algebraic expressions:
5760
5761     {
5762         ...
5763         symbol x("x");
5764         ex e = 2*myfcn(42, 1+3*x) - x;
5765         cout << e << endl;
5766          // prints '2*myfcn(42,1+3*x)-x'
5767         ...
5768     }
5769
5770The 'dummy()' option in the 'REGISTER_FUNCTION' line signifies "no
5771options".  A function with no options specified merely acts as a kind of
5772container for its arguments.  It is a pure "dummy" function with no
5773associated logic (which is, however, sometimes perfectly sufficient).
5774
5775Let's now have a look at the implementation of GiNaC's cosine function
5776for an example of how to make an "intelligent" function.
5777
57786.2.2 The cosine function
5779-------------------------
5780
5781The GiNaC header file 'inifcns.h' contains the line
5782
5783     DECLARE_FUNCTION_1P(cos)
5784
5785which declares to all programs using GiNaC that there is a function
5786'cos' that takes one 'ex' as an argument.  This is all they need to know
5787to use this function in expressions.
5788
5789The implementation of the cosine function is in 'inifcns_trans.cpp'.
5790Here is its 'REGISTER_FUNCTION' line:
5791
5792     REGISTER_FUNCTION(cos, eval_func(cos_eval).
5793                            evalf_func(cos_evalf).
5794                            derivative_func(cos_deriv).
5795                            latex_name("\\cos"));
5796
5797There are four options defined for the cosine function.  One of them
5798('latex_name') gives the function a proper name for LaTeX output; the
5799other three indicate the C++ functions in which the "brains" of the
5800cosine function are defined.
5801
5802The 'eval_func()' option specifies the C++ function that implements the
5803'eval()' method, GiNaC's anonymous evaluator.  This function takes the
5804same number of arguments as the associated symbolic function (one in
5805this case) and returns the (possibly transformed or in some way
5806simplified) symbolically evaluated function (*Note Automatic
5807evaluation::, for a description of the automatic evaluation process).
5808If no (further) evaluation is to take place, the 'eval_func()' function
5809must return the original function with '.hold()', to avoid a potential
5810infinite recursion.  If your symbolic functions produce a segmentation
5811fault or stack overflow when using them in expressions, you are probably
5812missing a '.hold()' somewhere.
5813
5814The 'eval_func()' function for the cosine looks something like this
5815(actually, it doesn't look like this at all, but it should give you an
5816idea what is going on):
5817
5818     static ex cos_eval(const ex & x)
5819     {
5820         if ("x is a multiple of 2*Pi")
5821             return 1;
5822         else if ("x is a multiple of Pi")
5823             return -1;
5824         else if ("x is a multiple of Pi/2")
5825             return 0;
5826         // more rules...
5827
5828         else if ("x has the form 'acos(y)'")
5829             return y;
5830         else if ("x has the form 'asin(y)'")
5831             return sqrt(1-y^2);
5832         // more rules...
5833
5834         else
5835             return cos(x).hold();
5836     }
5837
5838This function is called every time the cosine is used in a symbolic
5839expression:
5840
5841     {
5842         ...
5843         e = cos(Pi);
5844          // this calls cos_eval(Pi), and inserts its return value into
5845          // the actual expression
5846         cout << e << endl;
5847          // prints '-1'
5848         ...
5849     }
5850
5851In this way, 'cos(4*Pi)' automatically becomes 1, 'cos(asin(a+b))'
5852becomes 'sqrt(1-(a+b)^2)', etc.  If no reasonable symbolic
5853transformation can be done, the unmodified function is returned with
5854'.hold()'.
5855
5856GiNaC doesn't automatically transform 'cos(2)' to '-0.416146...'.  The
5857user has to call 'evalf()' for that.  This is implemented in a different
5858function:
5859
5860     static ex cos_evalf(const ex & x)
5861     {
5862         if (is_a<numeric>(x))
5863             return cos(ex_to<numeric>(x));
5864         else
5865             return cos(x).hold();
5866     }
5867
5868Since we are lazy we defer the problem of numeric evaluation to somebody
5869else, in this case the 'cos()' function for 'numeric' objects, which in
5870turn hands it over to the 'cos()' function in CLN. The '.hold()' isn't
5871really needed here, but reminds us that the corresponding 'eval()'
5872function would require it in this place.
5873
5874Differentiation will surely turn up and so we need to tell 'cos' what
5875its first derivative is (higher derivatives, '.diff(x,3)' for instance,
5876are then handled automatically by 'basic::diff' and 'ex::diff'):
5877
5878     static ex cos_deriv(const ex & x, unsigned diff_param)
5879     {
5880         return -sin(x);
5881     }
5882
5883The second parameter is obligatory but uninteresting at this point.  It
5884specifies which parameter to differentiate in a partial derivative in
5885case the function has more than one parameter, and its main application
5886is for correct handling of the chain rule.
5887
5888Derivatives of some functions, for example 'abs()' and 'Order()', could
5889not be evaluated through the chain rule.  In such cases the full
5890derivative may be specified as shown for 'Order()':
5891
5892     static ex Order_expl_derivative(const ex & arg, const symbol & s)
5893     {
5894     	return Order(arg.diff(s));
5895     }
5896
5897That is, we need to supply a procedure, which returns the expression of
5898derivative with respect to the variable 's' for the argument 'arg'.
5899This procedure need to be registered with the function through the
5900option 'expl_derivative_func' (see the next Subsection).  In contrast, a
5901partial derivative, e.g.  as was defined for 'cos()' above, needs to be
5902registered through the option 'derivative_func'.
5903
5904An implementation of the series expansion is not needed for 'cos()' as
5905it doesn't have any poles and GiNaC can do Taylor expansion by itself
5906(as long as it knows what the derivative of 'cos()' is).  'tan()', on
5907the other hand, does have poles and may need to do Laurent expansion:
5908
5909     static ex tan_series(const ex & x, const relational & rel,
5910                          int order, unsigned options)
5911     {
5912         // Find the actual expansion point
5913         const ex x_pt = x.subs(rel);
5914
5915         if ("x_pt is not an odd multiple of Pi/2")
5916             throw do_taylor();  // tell function::series() to do Taylor expansion
5917
5918         // On a pole, expand sin()/cos()
5919         return (sin(x)/cos(x)).series(rel, order+2, options);
5920     }
5921
5922The 'series()' implementation of a function _must_ return a 'pseries'
5923object, otherwise your code will crash.
5924
59256.2.3 Function options
5926----------------------
5927
5928GiNaC functions understand several more options which are always
5929specified as '.option(params)'.  None of them are required, but you need
5930to specify at least one option to 'REGISTER_FUNCTION()'.  There is a
5931do-nothing option called 'dummy()' which you can use to define functions
5932without any special options.
5933
5934     eval_func(<C++ function>)
5935     evalf_func(<C++ function>)
5936     derivative_func(<C++ function>)
5937     expl_derivative_func(<C++ function>)
5938     series_func(<C++ function>)
5939     conjugate_func(<C++ function>)
5940
5941These specify the C++ functions that implement symbolic evaluation,
5942numeric evaluation, partial derivatives, explicit derivative, and series
5943expansion, respectively.  They correspond to the GiNaC methods 'eval()',
5944'evalf()', 'diff()' and 'series()'.
5945
5946The 'eval_func()' function needs to use '.hold()' if no further
5947automatic evaluation is desired or possible.
5948
5949If no 'series_func()' is given, GiNaC defaults to simple Taylor
5950expansion, which is correct if there are no poles involved.  If the
5951function has poles in the complex plane, the 'series_func()' needs to
5952check whether the expansion point is on a pole and fall back to Taylor
5953expansion if it isn't.  Otherwise, the pole usually needs to be
5954regularized by some suitable transformation.
5955
5956     latex_name(const string & n)
5957
5958specifies the LaTeX code that represents the name of the function in
5959LaTeX output.  The default is to put the function name in an '\mbox{}'.
5960
5961     do_not_evalf_params()
5962
5963This tells 'evalf()' to not recursively evaluate the parameters of the
5964function before calling the 'evalf_func()'.
5965
5966     set_return_type(unsigned return_type, const return_type_t * return_type_tinfo)
5967
5968This allows you to explicitly specify the commutation properties of the
5969function (*Note Non-commutative objects::, for an explanation of
5970(non)commutativity in GiNaC). For example, with an object of type
5971'return_type_t' created like
5972
5973     return_type_t my_type = make_return_type_t<matrix>();
5974
5975you can use 'set_return_type(return_types::noncommutative, &my_type)' to
5976make GiNaC treat your function like a matrix.  By default, functions
5977inherit the commutation properties of their first argument.  The
5978utilized template function 'make_return_type_t<>()'
5979
5980     template<typename T> inline return_type_t make_return_type_t(const unsigned rl = 0)
5981
5982can also be called with an argument specifying the representation label
5983of the non-commutative function (see section on dirac gamma matrices for
5984more details).
5985
5986     set_symmetry(const symmetry & s)
5987
5988specifies the symmetry properties of the function with respect to its
5989arguments.  *Note Indexed objects::, for an explanation of symmetry
5990specifications.  GiNaC will automatically rearrange the arguments of
5991symmetric functions into a canonical order.
5992
5993Sometimes you may want to have finer control over how functions are
5994displayed in the output.  For example, the 'abs()' function prints
5995itself as 'abs(x)' in the default output format, but as '|x|' in LaTeX
5996mode, and 'fabs(x)' in C source output.  This is achieved with the
5997
5998     print_func<C>(<C++ function>)
5999
6000option which is explained in the next section.
6001
60026.2.4 Functions with a variable number of arguments
6003---------------------------------------------------
6004
6005The 'DECLARE_FUNCTION' and 'REGISTER_FUNCTION' macros define functions
6006with a fixed number of arguments.  Sometimes, though, you may need to
6007have a function that accepts a variable number of expressions.  One way
6008to accomplish this is to pass variable-length lists as arguments.  The
6009'Li()' function uses this method for multiple polylogarithms.
6010
6011It is also possible to define functions that accept a different number
6012of parameters under the same function name, such as the 'psi()' function
6013which can be called either as 'psi(z)' (the digamma function) or as
6014'psi(n, z)' (polygamma functions).  These are actually two different
6015functions in GiNaC that, however, have the same name.  Defining such
6016functions is not possible with the macros but requires manually fiddling
6017with GiNaC internals.  If you are interested, please consult the GiNaC
6018source code for the 'psi()' function ('inifcns.h' and
6019'inifcns_gamma.cpp').
6020
6021
6022File: ginac.info,  Node: Printing,  Next: Structures,  Prev: Symbolic functions,  Up: Extending GiNaC
6023
60246.3 GiNaC's expression output system
6025====================================
6026
6027GiNaC allows the output of expressions in a variety of different formats
6028(*note Input/output::).  This section will explain how expression output
6029is implemented internally, and how to define your own output formats or
6030change the output format of built-in algebraic objects.  You will also
6031want to read this section if you plan to write your own algebraic
6032classes or functions.
6033
6034All the different output formats are represented by a hierarchy of
6035classes rooted in the 'print_context' class, defined in the 'print.h'
6036header file:
6037
6038'print_dflt'
6039     the default output format
6040'print_latex'
6041     output in LaTeX mathematical mode
6042'print_tree'
6043     a dump of the internal expression structure (for debugging)
6044'print_csrc'
6045     the base class for C source output
6046'print_csrc_float'
6047     C source output using the 'float' type
6048'print_csrc_double'
6049     C source output using the 'double' type
6050'print_csrc_cl_N'
6051     C source output using CLN types
6052
6053The 'print_context' base class provides two public data members:
6054
6055     class print_context
6056     {
6057         ...
6058     public:
6059         std::ostream & s;
6060         unsigned options;
6061     };
6062
6063's' is a reference to the stream to output to, while 'options' holds
6064flags and modifiers.  Currently, there is only one flag defined:
6065'print_options::print_index_dimensions' instructs the 'idx' class to
6066print the index dimension which is normally hidden.
6067
6068When you write something like 'std::cout << e', where 'e' is an object
6069of class 'ex', GiNaC will construct an appropriate 'print_context'
6070object (of a class depending on the selected output format), fill in the
6071's' and 'options' members, and call
6072
6073     void ex::print(const print_context & c, unsigned level = 0) const;
6074
6075which in turn forwards the call to the 'print()' method of the top-level
6076algebraic object contained in the expression.
6077
6078Unlike other methods, GiNaC classes don't usually override their
6079'print()' method to implement expression output.  Instead, the default
6080implementation 'basic::print(c, level)' performs a run-time double
6081dispatch to a function selected by the dynamic type of the object and
6082the passed 'print_context'.  To this end, GiNaC maintains a separate
6083method table for each class, similar to the virtual function table used
6084for ordinary (single) virtual function dispatch.
6085
6086The method table contains one slot for each possible 'print_context'
6087type, indexed by the (internally assigned) serial number of the type.
6088Slots may be empty, in which case GiNaC will retry the method lookup
6089with the 'print_context' object's parent class, possibly repeating the
6090process until it reaches the 'print_context' base class.  If there's
6091still no method defined, the method table of the algebraic object's
6092parent class is consulted, and so on, until a matching method is found
6093(eventually it will reach the combination 'basic/print_context', which
6094prints the object's class name enclosed in square brackets).
6095
6096You can think of the print methods of all the different classes and
6097output formats as being arranged in a two-dimensional matrix with one
6098axis listing the algebraic classes and the other axis listing the
6099'print_context' classes.
6100
6101Subclasses of 'basic' can, of course, also overload 'basic::print()' to
6102implement printing, but then they won't get any of the benefits of the
6103double dispatch mechanism (such as the ability for derived classes to
6104inherit only certain print methods from its parent, or the replacement
6105of methods at run-time).
6106
61076.3.1 Print methods for classes
6108-------------------------------
6109
6110The method table for a class is set up either in the definition of the
6111class, by passing the appropriate 'print_func<C>()' option to
6112'GINAC_IMPLEMENT_REGISTERED_CLASS_OPT()' (*Note Adding classes::, for an
6113example), or at run-time using 'set_print_func<T, C>()'.  The latter can
6114also be used to override existing methods dynamically.
6115
6116The argument to 'print_func<C>()' and 'set_print_func<T, C>()' can be a
6117member function of the class (or one of its parent classes), a static
6118member function, or an ordinary (global) C++ function.  The 'C' template
6119parameter specifies the appropriate 'print_context' type for which the
6120method should be invoked, while, in the case of 'set_print_func<>()',
6121the 'T' parameter specifies the algebraic class (for 'print_func<>()',
6122the class is the one being implemented by
6123'GINAC_IMPLEMENT_REGISTERED_CLASS_OPT').
6124
6125For print methods that are member functions, their first argument must
6126be of a type convertible to a 'const C &', and the second argument must
6127be an 'unsigned'.
6128
6129For static members and global functions, the first argument must be of a
6130type convertible to a 'const T &', the second argument must be of a type
6131convertible to a 'const C &', and the third argument must be an
6132'unsigned'.  A global function will, of course, not have access to
6133private and protected members of 'T'.
6134
6135The 'unsigned' argument of the print methods (and of 'ex::print()' and
6136'basic::print()') is used for proper parenthesizing of the output (and
6137by 'print_tree' for proper indentation).  It can be used for similar
6138purposes if you write your own output formats.
6139
6140The explanations given above may seem complicated, but in practice it's
6141really simple, as shown in the following example.  Suppose that we want
6142to display exponents in LaTeX output not as superscripts but with little
6143upwards-pointing arrows.  This can be achieved in the following way:
6144
6145     void my_print_power_as_latex(const power & p,
6146                                  const print_latex & c,
6147                                  unsigned level)
6148     {
6149         // get the precedence of the 'power' class
6150         unsigned power_prec = p.precedence();
6151
6152         // if the parent operator has the same or a higher precedence
6153         // we need parentheses around the power
6154         if (level >= power_prec)
6155             c.s << '(';
6156
6157         // print the basis and exponent, each enclosed in braces, and
6158         // separated by an uparrow
6159         c.s << '{';
6160         p.op(0).print(c, power_prec);
6161         c.s << "}\\uparrow{";
6162         p.op(1).print(c, power_prec);
6163         c.s << '}';
6164
6165         // don't forget the closing parenthesis
6166         if (level >= power_prec)
6167             c.s << ')';
6168     }
6169
6170     int main()
6171     {
6172         // a sample expression
6173         symbol x("x"), y("y");
6174         ex e = -3*pow(x, 3)*pow(y, -2) + pow(x+y, 2) - 1;
6175
6176         // switch to LaTeX mode
6177         cout << latex;
6178
6179         // this prints "-1+{(y+x)}^{2}-3 \frac{x^{3}}{y^{2}}"
6180         cout << e << endl;
6181
6182         // now we replace the method for the LaTeX output of powers with
6183         // our own one
6184         set_print_func<power, print_latex>(my_print_power_as_latex);
6185
6186         // this prints "-1+{{(y+x)}}\uparrow{2}-3 \frac{{x}\uparrow{3}}{{y}
6187         //              \uparrow{2}}"
6188         cout << e << endl;
6189     }
6190
6191Some notes:
6192
6193   * The first argument of 'my_print_power_as_latex' could also have
6194     been a 'const basic &', the second one a 'const print_context &'.
6195
6196   * The above code depends on 'mul' objects converting their operands
6197     to 'power' objects for the purpose of printing.
6198
6199   * The output of products including negative powers as fractions is
6200     also controlled by the 'mul' class.
6201
6202   * The 'power/print_latex' method provided by GiNaC prints square
6203     roots using '\sqrt', but the above code doesn't.
6204
6205It's not possible to restore a method table entry to its previous or
6206default value.  Once you have called 'set_print_func()', you can only
6207override it with another call to 'set_print_func()', but you can't
6208easily go back to the default behavior again (you can, of course, dig
6209around in the GiNaC sources, find the method that is installed at
6210startup ('power::do_print_latex' in this case), and 'set_print_func'
6211that one; that is, after you circumvent the C++ member access
6212control...).
6213
62146.3.2 Print methods for functions
6215---------------------------------
6216
6217Symbolic functions employ a print method dispatch mechanism similar to
6218the one used for classes.  The methods are specified with
6219'print_func<C>()' function options.  If you don't specify any special
6220print methods, the function will be printed with its name (or LaTeX
6221name, if supplied), followed by a comma-separated list of arguments
6222enclosed in parentheses.
6223
6224For example, this is what GiNaC's 'abs()' function is defined like:
6225
6226     static ex abs_eval(const ex & arg) { ... }
6227     static ex abs_evalf(const ex & arg) { ... }
6228
6229     static void abs_print_latex(const ex & arg, const print_context & c)
6230     {
6231         c.s << "{|"; arg.print(c); c.s << "|}";
6232     }
6233
6234     static void abs_print_csrc_float(const ex & arg, const print_context & c)
6235     {
6236         c.s << "fabs("; arg.print(c); c.s << ")";
6237     }
6238
6239     REGISTER_FUNCTION(abs, eval_func(abs_eval).
6240                            evalf_func(abs_evalf).
6241                            print_func<print_latex>(abs_print_latex).
6242                            print_func<print_csrc_float>(abs_print_csrc_float).
6243                            print_func<print_csrc_double>(abs_print_csrc_float));
6244
6245This will display 'abs(x)' as '|x|' in LaTeX mode and 'fabs(x)' in
6246non-CLN C source output, but as 'abs(x)' in all other formats.
6247
6248There is currently no equivalent of 'set_print_func()' for functions.
6249
62506.3.3 Adding new output formats
6251-------------------------------
6252
6253Creating a new output format involves subclassing 'print_context', which
6254is somewhat similar to adding a new algebraic class (*note Adding
6255classes::).  There is a macro 'GINAC_DECLARE_PRINT_CONTEXT' that needs
6256to go into the class definition, and a corresponding macro
6257'GINAC_IMPLEMENT_PRINT_CONTEXT' that has to appear at global scope.
6258Every 'print_context' class needs to provide a default constructor and a
6259constructor from an 'std::ostream' and an 'unsigned' options value.
6260
6261Here is an example for a user-defined 'print_context' class:
6262
6263     class print_myformat : public print_dflt
6264     {
6265         GINAC_DECLARE_PRINT_CONTEXT(print_myformat, print_dflt)
6266     public:
6267         print_myformat(std::ostream & os, unsigned opt = 0)
6268          : print_dflt(os, opt) {}
6269     };
6270
6271     print_myformat::print_myformat() : print_dflt(std::cout) {}
6272
6273     GINAC_IMPLEMENT_PRINT_CONTEXT(print_myformat, print_dflt)
6274
6275That's all there is to it.  None of the actual expression output logic
6276is implemented in this class.  It merely serves as a selector for
6277choosing a particular format.  The algorithms for printing expressions
6278in the new format are implemented as print methods, as described above.
6279
6280'print_myformat' is a subclass of 'print_dflt', so it behaves exactly
6281like GiNaC's default output format:
6282
6283     {
6284         symbol x("x");
6285         ex e = pow(x, 2) + 1;
6286
6287         // this prints "1+x^2"
6288         cout << e << endl;
6289
6290         // this also prints "1+x^2"
6291         e.print(print_myformat()); cout << endl;
6292
6293         ...
6294     }
6295
6296To fill 'print_myformat' with life, we need to supply appropriate print
6297methods with 'set_print_func()', like this:
6298
6299     // This prints powers with '**' instead of '^'. See the LaTeX output
6300     // example above for explanations.
6301     void print_power_as_myformat(const power & p,
6302                                  const print_myformat & c,
6303                                  unsigned level)
6304     {
6305         unsigned power_prec = p.precedence();
6306         if (level >= power_prec)
6307             c.s << '(';
6308         p.op(0).print(c, power_prec);
6309         c.s << "**";
6310         p.op(1).print(c, power_prec);
6311         if (level >= power_prec)
6312             c.s << ')';
6313     }
6314
6315     {
6316         ...
6317         // install a new print method for power objects
6318         set_print_func<power, print_myformat>(print_power_as_myformat);
6319
6320         // now this prints "1+x**2"
6321         e.print(print_myformat()); cout << endl;
6322
6323         // but the default format is still "1+x^2"
6324         cout << e << endl;
6325     }
6326
6327
6328File: ginac.info,  Node: Structures,  Next: Adding classes,  Prev: Printing,  Up: Extending GiNaC
6329
63306.4 Structures
6331==============
6332
6333If you are doing some very specialized things with GiNaC, or if you just
6334need some more organized way to store data in your expressions instead
6335of anonymous lists, you may want to implement your own algebraic
6336classes.  ('algebraic class' means any class directly or indirectly
6337derived from 'basic' that can be used in GiNaC expressions).
6338
6339GiNaC offers two ways of accomplishing this: either by using the
6340'structure<T>' template class, or by rolling your own class from
6341scratch.  This section will discuss the 'structure<T>' template which is
6342easier to use but more limited, while the implementation of custom GiNaC
6343classes is the topic of the next section.  However, you may want to read
6344both sections because many common concepts and member functions are
6345shared by both concepts, and it will also allow you to decide which
6346approach is most suited to your needs.
6347
6348The 'structure<T>' template, defined in the GiNaC header file
6349'structure.h', wraps a type that you supply (usually a C++ 'struct' or
6350'class') into a GiNaC object that can be used in expressions.
6351
63526.4.1 Example: scalar products
6353------------------------------
6354
6355Let's suppose that we need a way to handle some kind of abstract scalar
6356product of the form '<x|y>' in expressions.  Objects of the scalar
6357product class have to store their left and right operands, which can in
6358turn be arbitrary expressions.  Here is a possible way to represent such
6359a product in a C++ 'struct':
6360
6361     #include <iostream>
6362     #include <ginac/ginac.h>
6363     using namespace std;
6364     using namespace GiNaC;
6365
6366     struct sprod_s {
6367         ex left, right;
6368
6369         sprod_s() {}
6370         sprod_s(ex l, ex r) : left(l), right(r) {}
6371     };
6372
6373The default constructor is required.  Now, to make a GiNaC class out of
6374this data structure, we need only one line:
6375
6376     typedef structure<sprod_s> sprod;
6377
6378That's it.  This line constructs an algebraic class 'sprod' which
6379contains objects of type 'sprod_s'.  We can now use 'sprod' in
6380expressions like any other GiNaC class:
6381
6382     ...
6383         symbol a("a"), b("b");
6384         ex e = sprod(sprod_s(a, b));
6385     ...
6386
6387Note the difference between 'sprod' which is the algebraic class, and
6388'sprod_s' which is the unadorned C++ structure containing the 'left' and
6389'right' data members.  As shown above, an 'sprod' can be constructed
6390from an 'sprod_s' object.
6391
6392If you find the nested 'sprod(sprod_s())' constructor too unwieldy, you
6393could define a little wrapper function like this:
6394
6395     inline ex make_sprod(ex left, ex right)
6396     {
6397         return sprod(sprod_s(left, right));
6398     }
6399
6400The 'sprod_s' object contained in 'sprod' can be accessed with the GiNaC
6401'ex_to<>()' function followed by the '->' operator or 'get_struct()':
6402
6403     ...
6404         cout << ex_to<sprod>(e)->left << endl;
6405          // -> a
6406         cout << ex_to<sprod>(e).get_struct().right << endl;
6407          // -> b
6408     ...
6409
6410You only have read access to the members of 'sprod_s'.
6411
6412The type definition of 'sprod' is enough to write your own algorithms
6413that deal with scalar products, for example:
6414
6415     ex swap_sprod(ex p)
6416     {
6417         if (is_a<sprod>(p)) {
6418             const sprod_s & sp = ex_to<sprod>(p).get_struct();
6419             return make_sprod(sp.right, sp.left);
6420         } else
6421             return p;
6422     }
6423
6424     ...
6425         f = swap_sprod(e);
6426          // f is now <b|a>
6427     ...
6428
64296.4.2 Structure output
6430----------------------
6431
6432While the 'sprod' type is useable it still leaves something to be
6433desired, most notably proper output:
6434
6435     ...
6436         cout << e << endl;
6437          // -> [structure object]
6438     ...
6439
6440By default, any structure types you define will be printed as
6441'[structure object]'.  To override this you can either specialize the
6442template's 'print()' member function, or specify print methods with
6443'set_print_func<>()', as described in *note Printing::.  Unfortunately,
6444it's not possible to supply class options like 'print_func<>()' to
6445structures, so for a self-contained structure type you need to resort to
6446overriding the 'print()' function, which is also what we will do here.
6447
6448The member functions of GiNaC classes are described in more detail in
6449the next section, but it shouldn't be hard to figure out what's going on
6450here:
6451
6452     void sprod::print(const print_context & c, unsigned level) const
6453     {
6454         // tree debug output handled by superclass
6455         if (is_a<print_tree>(c))
6456             inherited::print(c, level);
6457
6458         // get the contained sprod_s object
6459         const sprod_s & sp = get_struct();
6460
6461         // print_context::s is a reference to an ostream
6462         c.s << "<" << sp.left << "|" << sp.right << ">";
6463     }
6464
6465Now we can print expressions containing scalar products:
6466
6467     ...
6468         cout << e << endl;
6469          // -> <a|b>
6470         cout << swap_sprod(e) << endl;
6471          // -> <b|a>
6472     ...
6473
64746.4.3 Comparing structures
6475--------------------------
6476
6477The 'sprod' class defined so far still has one important drawback: all
6478scalar products are treated as being equal because GiNaC doesn't know
6479how to compare objects of type 'sprod_s'.  This can lead to some
6480confusing and undesired behavior:
6481
6482     ...
6483         cout << make_sprod(a, b) - make_sprod(a*a, b*b) << endl;
6484          // -> 0
6485         cout << make_sprod(a, b) + make_sprod(a*a, b*b) << endl;
6486          // -> 2*<a|b> or 2*<a^2|b^2> (which one is undefined)
6487     ...
6488
6489To remedy this, we first need to define the operators '==' and '<' for
6490objects of type 'sprod_s':
6491
6492     inline bool operator==(const sprod_s & lhs, const sprod_s & rhs)
6493     {
6494         return lhs.left.is_equal(rhs.left) && lhs.right.is_equal(rhs.right);
6495     }
6496
6497     inline bool operator<(const sprod_s & lhs, const sprod_s & rhs)
6498     {
6499         return lhs.left.compare(rhs.left) < 0
6500                ? true : lhs.right.compare(rhs.right) < 0;
6501     }
6502
6503The ordering established by the '<' operator doesn't have to make any
6504algebraic sense, but it needs to be well defined.  Note that we can't
6505use expressions like 'lhs.left == rhs.left' or 'lhs.left < rhs.left' in
6506the implementation of these operators because they would construct GiNaC
6507'relational' objects which in the case of '<' do not establish a well
6508defined ordering (for arbitrary expressions, GiNaC can't decide which
6509one is algebraically 'less').
6510
6511Next, we need to change our definition of the 'sprod' type to let GiNaC
6512know that an ordering relation exists for the embedded objects:
6513
6514     typedef structure<sprod_s, compare_std_less> sprod;
6515
6516'sprod' objects then behave as expected:
6517
6518     ...
6519         cout << make_sprod(a, b) - make_sprod(a*a, b*b) << endl;
6520          // -> <a|b>-<a^2|b^2>
6521         cout << make_sprod(a, b) + make_sprod(a*a, b*b) << endl;
6522          // -> <a|b>+<a^2|b^2>
6523         cout << make_sprod(a, b) - make_sprod(a, b) << endl;
6524          // -> 0
6525         cout << make_sprod(a, b) + make_sprod(a, b) << endl;
6526          // -> 2*<a|b>
6527     ...
6528
6529The 'compare_std_less' policy parameter tells GiNaC to use the
6530'std::less' and 'std::equal_to' functors to compare objects of type
6531'sprod_s'.  By default, these functors forward their work to the
6532standard '<' and '==' operators, which we have overloaded.
6533Alternatively, we could have specialized 'std::less' and 'std::equal_to'
6534for class 'sprod_s'.
6535
6536GiNaC provides two other comparison policies for 'structure<T>' objects:
6537the default 'compare_all_equal', and 'compare_bitwise' which does a
6538bit-wise comparison of the contained 'T' objects.  This should be used
6539with extreme care because it only works reliably with built-in integral
6540types, and it also compares any padding (filler bytes of undefined
6541value) that the 'T' class might have.
6542
65436.4.4 Subexpressions
6544--------------------
6545
6546Our scalar product class has two subexpressions: the left and right
6547operands.  It might be a good idea to make them accessible via the
6548standard 'nops()' and 'op()' methods:
6549
6550     size_t sprod::nops() const
6551     {
6552         return 2;
6553     }
6554
6555     ex sprod::op(size_t i) const
6556     {
6557         switch (i) {
6558         case 0:
6559             return get_struct().left;
6560         case 1:
6561             return get_struct().right;
6562         default:
6563             throw std::range_error("sprod::op(): no such operand");
6564         }
6565     }
6566
6567Implementing 'nops()' and 'op()' for container types such as 'sprod' has
6568two other nice side effects:
6569
6570   * 'has()' works as expected
6571   * GiNaC generates better hash keys for the objects (the default
6572     implementation of 'calchash()' takes subexpressions into account)
6573
6574There is a non-const variant of 'op()' called 'let_op()' that allows
6575replacing subexpressions:
6576
6577     ex & sprod::let_op(size_t i)
6578     {
6579         // every non-const member function must call this
6580         ensure_if_modifiable();
6581
6582         switch (i) {
6583         case 0:
6584             return get_struct().left;
6585         case 1:
6586             return get_struct().right;
6587         default:
6588             throw std::range_error("sprod::let_op(): no such operand");
6589         }
6590     }
6591
6592Once we have provided 'let_op()' we also get 'subs()' and 'map()' for
6593free.  In fact, every container class that returns a non-null 'nops()'
6594value must either implement 'let_op()' or provide custom implementations
6595of 'subs()' and 'map()'.
6596
6597In turn, the availability of 'map()' enables the recursive behavior of a
6598couple of other default method implementations, in particular 'evalf()',
6599'evalm()', 'normal()', 'diff()' and 'expand()'.  Although we probably
6600want to provide our own version of 'expand()' for scalar products that
6601turns expressions like '<a+b|c>' into '<a|c>+<b|c>'.  This is left as an
6602exercise for the reader.
6603
6604The 'structure<T>' template defines many more member functions that you
6605can override by specialization to customize the behavior of your
6606structures.  You are referred to the next section for a description of
6607some of these (especially 'eval()').  There is, however, one topic that
6608shall be addressed here, as it demonstrates one peculiarity of the
6609'structure<T>' template: archiving.
6610
66116.4.5 Archiving structures
6612--------------------------
6613
6614If you don't know how the archiving of GiNaC objects is implemented, you
6615should first read the next section and then come back here.  You're
6616back?  Good.
6617
6618To implement archiving for structures it is not enough to provide
6619specializations for the 'archive()' member function and the unarchiving
6620constructor (the 'unarchive()' function has a default implementation).
6621You also need to provide a unique name (as a string literal) for each
6622structure type you define.  This is because in GiNaC archives, the class
6623of an object is stored as a string, the class name.
6624
6625By default, this class name (as returned by the 'class_name()' member
6626function) is 'structure' for all structure classes.  This works as long
6627as you have only defined one structure type, but if you use two or more
6628you need to provide a different name for each by specializing the
6629'get_class_name()' member function.  Here is a sample implementation for
6630enabling archiving of the scalar product type defined above:
6631
6632     const char *sprod::get_class_name() { return "sprod"; }
6633
6634     void sprod::archive(archive_node & n) const
6635     {
6636         inherited::archive(n);
6637         n.add_ex("left", get_struct().left);
6638         n.add_ex("right", get_struct().right);
6639     }
6640
6641     sprod::structure(const archive_node & n, lst & sym_lst) : inherited(n, sym_lst)
6642     {
6643         n.find_ex("left", get_struct().left, sym_lst);
6644         n.find_ex("right", get_struct().right, sym_lst);
6645     }
6646
6647Note that the unarchiving constructor is 'sprod::structure' and not
6648'sprod::sprod', and that we don't need to supply an 'sprod::unarchive()'
6649function.
6650
6651
6652File: ginac.info,  Node: Adding classes,  Next: A comparison with other CAS,  Prev: Structures,  Up: Extending GiNaC
6653
66546.5 Adding classes
6655==================
6656
6657The 'structure<T>' template provides an way to extend GiNaC with custom
6658algebraic classes that is easy to use but has its limitations, the most
6659severe of which being that you can't add any new member functions to
6660structures.  To be able to do this, you need to write a new class
6661definition from scratch.
6662
6663This section will explain how to implement new algebraic classes in
6664GiNaC by giving the example of a simple 'string' class.  After reading
6665this section you will know how to properly declare a GiNaC class and
6666what the minimum required member functions are that you have to
6667implement.  We only cover the implementation of a 'leaf' class here
6668(i.e.  one that doesn't contain subexpressions).  Creating a container
6669class like, for example, a class representing tensor products is more
6670involved but this section should give you enough information so you can
6671consult the source to GiNaC's predefined classes if you want to
6672implement something more complicated.
6673
66746.5.1 Hierarchy of algebraic classes.
6675-------------------------------------
6676
6677All algebraic classes (that is, all classes that can appear in
6678expressions) in GiNaC are direct or indirect subclasses of the class
6679'basic'.  So a 'basic *' represents a generic pointer to an algebraic
6680class.  Working with such pointers directly is cumbersome (think of
6681memory management), hence GiNaC wraps them into 'ex' (*note Expressions
6682are reference counted::).  To make such wrapping possible every
6683algebraic class has to implement several methods.  Visitors (*note
6684Visitors and tree traversal::), printing, and (un)archiving (*note
6685Input/output::) require helper methods too.  But don't worry, most of
6686the work is simplified by the following macros (defined in
6687'registrar.h'):
6688   * 'GINAC_DECLARE_REGISTERED_CLASS'
6689   * 'GINAC_IMPLEMENT_REGISTERED_CLASS'
6690   * 'GINAC_IMPLEMENT_REGISTERED_CLASS_OPT'
6691
6692The 'GINAC_DECLARE_REGISTERED_CLASS' macro inserts declarations required
6693for memory management, visitors, printing, and (un)archiving.  It takes
6694the name of the class and its direct superclass as arguments.  The
6695'GINAC_DECLARE_REGISTERED_CLASS' should be the first line after the
6696opening brace of the class definition.
6697
6698'GINAC_IMPLEMENT_REGISTERED_CLASS' takes the same arguments as
6699'GINAC_DECLARE_REGISTERED_CLASS'.  It initializes certain static members
6700of a class so that printing and (un)archiving works.  The
6701'GINAC_IMPLEMENT_REGISTERED_CLASS' may appear anywhere else in the
6702source (at global scope, of course, not inside a function).
6703
6704'GINAC_IMPLEMENT_REGISTERED_CLASS_OPT' is a variant of
6705'GINAC_IMPLEMENT_REGISTERED_CLASS'.  It allows specifying additional
6706options, such as custom printing functions.
6707
67086.5.2 A minimalistic example
6709----------------------------
6710
6711Now we will start implementing a new class 'mystring' that allows
6712placing character strings in algebraic expressions (this is not very
6713useful, but it's just an example).  This class will be a direct subclass
6714of 'basic'.  You can use this sample implementation as a starting point
6715for your own classes (1).
6716
6717The code snippets given here assume that you have included some header
6718files as follows:
6719
6720     #include <iostream>
6721     #include <string>
6722     #include <stdexcept>
6723     #include <ginac/ginac.h>
6724     using namespace std;
6725     using namespace GiNaC;
6726
6727Now we can write down the class declaration.  The class stores a C++
6728'string' and the user shall be able to construct a 'mystring' object
6729from a string:
6730
6731     class mystring : public basic
6732     {
6733         GINAC_DECLARE_REGISTERED_CLASS(mystring, basic)
6734
6735     public:
6736         mystring(const string & s);
6737
6738     private:
6739         string str;
6740     };
6741
6742     GINAC_IMPLEMENT_REGISTERED_CLASS(mystring, basic)
6743
6744The 'GINAC_DECLARE_REGISTERED_CLASS' macro insert declarations required
6745for memory management, visitors, printing, and (un)archiving.
6746'GINAC_IMPLEMENT_REGISTERED_CLASS' initializes certain static members of
6747a class so that printing and (un)archiving works.
6748
6749Now there are three member functions we have to implement to get a
6750working class:
6751
6752   * 'mystring()', the default constructor.
6753
6754   * 'int compare_same_type(const basic & other)', which is used
6755     internally by GiNaC to establish a canonical sort order for terms.
6756     It returns 0, +1 or -1, depending on the relative order of this
6757     object and the 'other' object.  If it returns 0, the objects are
6758     considered equal.  *Please notice:* This has nothing to do with the
6759     (numeric) ordering relationship expressed by '<', '>=' etc (which
6760     cannot be defined for non-numeric classes).  For example,
6761     'numeric(1).compare_same_type(numeric(2))' may return +1 even
6762     though 1 is clearly smaller than 2.  Every GiNaC class must provide
6763     a 'compare_same_type()' function, even those representing objects
6764     for which no reasonable algebraic ordering relationship can be
6765     defined.
6766
6767   * And, of course, 'mystring(const string& s)' which is the
6768     constructor we declared.
6769
6770Let's proceed step-by-step.  The default constructor looks like this:
6771
6772     mystring::mystring() { }
6773
6774In the default constructor you should set all other member variables to
6775reasonable default values (we don't need that here since our 'str'
6776member gets set to an empty string automatically).
6777
6778Our 'compare_same_type()' function uses a provided function to compare
6779the string members:
6780
6781     int mystring::compare_same_type(const basic & other) const
6782     {
6783         const mystring &o = static_cast<const mystring &>(other);
6784         int cmpval = str.compare(o.str);
6785         if (cmpval == 0)
6786             return 0;
6787         else if (cmpval < 0)
6788             return -1;
6789         else
6790             return 1;
6791     }
6792
6793Although this function takes a 'basic &', it will always be a reference
6794to an object of exactly the same class (objects of different classes are
6795not comparable), so the cast is safe.  If this function returns 0, the
6796two objects are considered equal (in the sense that A-B=0), so you
6797should compare all relevant member variables.
6798
6799Now the only thing missing is our constructor:
6800
6801     mystring::mystring(const string& s) : str(s) { }
6802
6803No surprises here.  We set the 'str' member from the argument.
6804
6805That's it!  We now have a minimal working GiNaC class that can store
6806strings in algebraic expressions.  Let's confirm that the RTTI works:
6807
6808     ex e = mystring("Hello, world!");
6809     cout << is_a<mystring>(e) << endl;
6810      // -> 1 (true)
6811
6812     cout << ex_to<basic>(e).class_name() << endl;
6813      // -> mystring
6814
6815Obviously it does.  Let's see what the expression 'e' looks like:
6816
6817     cout << e << endl;
6818      // -> [mystring object]
6819
6820Hm, not exactly what we expect, but of course the 'mystring' class
6821doesn't yet know how to print itself.  This can be done either by
6822implementing the 'print()' member function, or, preferably, by
6823specifying a 'print_func<>()' class option.  Let's say that we want to
6824print the string surrounded by double quotes:
6825
6826     class mystring : public basic
6827     {
6828         ...
6829     protected:
6830         void do_print(const print_context & c, unsigned level = 0) const;
6831         ...
6832     };
6833
6834     void mystring::do_print(const print_context & c, unsigned level) const
6835     {
6836         // print_context::s is a reference to an ostream
6837         c.s << '\"' << str << '\"';
6838     }
6839
6840The 'level' argument is only required for container classes to correctly
6841parenthesize the output.
6842
6843Now we need to tell GiNaC that 'mystring' objects should use the
6844'do_print()' member function for printing themselves.  For this, we
6845replace the line
6846
6847     GINAC_IMPLEMENT_REGISTERED_CLASS(mystring, basic)
6848
6849with
6850
6851     GINAC_IMPLEMENT_REGISTERED_CLASS_OPT(mystring, basic,
6852       print_func<print_context>(&mystring::do_print))
6853
6854Let's try again to print the expression:
6855
6856     cout << e << endl;
6857      // -> "Hello, world!"
6858
6859Much better.  If we wanted to have 'mystring' objects displayed in a
6860different way depending on the output format (default, LaTeX, etc.), we
6861would have supplied multiple 'print_func<>()' options with different
6862template parameters ('print_dflt', 'print_latex', etc.), separated by
6863dots.  This is similar to the way options are specified for symbolic
6864functions.  *Note Printing::, for a more in-depth description of the way
6865expression output is implemented in GiNaC.
6866
6867The 'mystring' class can be used in arbitrary expressions:
6868
6869     e += mystring("GiNaC rulez");
6870     cout << e << endl;
6871      // -> "GiNaC rulez"+"Hello, world!"
6872
6873(GiNaC's automatic term reordering is in effect here), or even
6874
6875     e = pow(mystring("One string"), 2*sin(Pi-mystring("Another string")));
6876     cout << e << endl;
6877      // -> "One string"^(2*sin(-"Another string"+Pi))
6878
6879Whether this makes sense is debatable but remember that this is only an
6880example.  At least it allows you to implement your own symbolic
6881algorithms for your objects.
6882
6883Note that GiNaC's algebraic rules remain unchanged:
6884
6885     e = mystring("Wow") * mystring("Wow");
6886     cout << e << endl;
6887      // -> "Wow"^2
6888
6889     e = pow(mystring("First")-mystring("Second"), 2);
6890     cout << e.expand() << endl;
6891      // -> -2*"First"*"Second"+"First"^2+"Second"^2
6892
6893There's no way to, for example, make GiNaC's 'add' class perform string
6894concatenation.  You would have to implement this yourself.
6895
68966.5.3 Automatic evaluation
6897--------------------------
6898
6899When dealing with objects that are just a little more complicated than
6900the simple string objects we have implemented, chances are that you will
6901want to have some automatic simplifications or canonicalizations
6902performed on them.  This is done in the evaluation member function
6903'eval()'.  Let's say that we wanted all strings automatically converted
6904to lowercase with non-alphabetic characters stripped, and empty strings
6905removed:
6906
6907     class mystring : public basic
6908     {
6909         ...
6910     public:
6911         ex eval() const override;
6912         ...
6913     };
6914
6915     ex mystring::eval() const
6916     {
6917         string new_str;
6918         for (size_t i=0; i<str.length(); i++) {
6919             char c = str[i];
6920             if (c >= 'A' && c <= 'Z')
6921                 new_str += tolower(c);
6922             else if (c >= 'a' && c <= 'z')
6923                 new_str += c;
6924         }
6925
6926         if (new_str.length() == 0)
6927             return 0;
6928
6929         return mystring(new_str).hold();
6930     }
6931
6932The 'hold()' member function sets a flag in the object that prevents
6933further evaluation.  Otherwise we might end up in an endless loop.  When
6934you want to return the object unmodified, use 'return this->hold();'.
6935
6936If our class had subobjects, we would have to evaluate them first
6937(unless they are all of type 'ex', which are automatically evaluated).
6938We don't have any subexpressions in the 'mystring' class, so we are not
6939concerned with this.
6940
6941Let's confirm that it works:
6942
6943     ex e = mystring("Hello, world!") + mystring("!?#");
6944     cout << e << endl;
6945      // -> "helloworld"
6946
6947     e = mystring("Wow!") + mystring("WOW") + mystring(" W ** o ** W");
6948     cout << e << endl;
6949      // -> 3*"wow"
6950
69516.5.4 Optional member functions
6952-------------------------------
6953
6954We have implemented only a small set of member functions to make the
6955class work in the GiNaC framework.  There are two functions that are not
6956strictly required but will make operations with objects of the class
6957more efficient:
6958
6959     unsigned calchash() const override;
6960     bool is_equal_same_type(const basic & other) const override;
6961
6962The 'calchash()' method returns an 'unsigned' hash value for the object
6963which will allow GiNaC to compare and canonicalize expressions much more
6964efficiently.  You should consult the implementation of some of the
6965built-in GiNaC classes for examples of hash functions.  The default
6966implementation of 'calchash()' calculates a hash value out of the
6967'tinfo_key' of the class and all subexpressions that are accessible via
6968'op()'.
6969
6970'is_equal_same_type()' works like 'compare_same_type()' but only tests
6971for equality without establishing an ordering relation, which is often
6972faster.  The default implementation of 'is_equal_same_type()' just calls
6973'compare_same_type()' and tests its result for zero.
6974
69756.5.5 Other member functions
6976----------------------------
6977
6978For a real algebraic class, there are probably some more functions that
6979you might want to provide:
6980
6981     bool info(unsigned inf) const override;
6982     ex evalf() const override;
6983     ex series(const relational & r, int order, unsigned options = 0) const override;
6984     ex derivative(const symbol & s) const override;
6985
6986If your class stores sub-expressions (see the scalar product example in
6987the previous section) you will probably want to override
6988
6989     size_t nops() const override;
6990     ex op(size_t i) const override;
6991     ex & let_op(size_t i) override;
6992     ex subs(const lst & ls, const lst & lr, unsigned options = 0) const override;
6993     ex map(map_function & f) const override;
6994
6995'let_op()' is a variant of 'op()' that allows write access.  The default
6996implementations of 'subs()' and 'map()' use it, so you have to implement
6997either 'let_op()', or 'subs()' and 'map()'.
6998
6999You can, of course, also add your own new member functions.  Remember
7000that the RTTI may be used to get information about what kinds of objects
7001you are dealing with (the position in the class hierarchy) and that you
7002can always extract the bare object from an 'ex' by stripping the 'ex'
7003off using the 'ex_to<mystring>(e)' function when that should become a
7004need.
7005
7006That's it.  May the source be with you!
7007
70086.5.6 Upgrading extension classes from older version of GiNaC
7009-------------------------------------------------------------
7010
7011GiNaC used to use a custom run time type information system (RTTI). It
7012was removed from GiNaC. Thus, one needs to rewrite constructors which
7013set 'tinfo_key' (which does not exist any more).  For example,
7014
7015     myclass::myclass() : inherited(&myclass::tinfo_static) {}
7016
7017needs to be rewritten as
7018
7019     myclass::myclass() {}
7020
7021   ---------- Footnotes ----------
7022
7023   (1) The self-contained source for this example is included in GiNaC,
7024see the 'doc/examples/mystring.cpp' file.
7025
7026
7027File: ginac.info,  Node: A comparison with other CAS,  Next: Advantages,  Prev: Adding classes,  Up: Top
7028
70297 A Comparison With Other CAS
7030*****************************
7031
7032This chapter will give you some information on how GiNaC compares to
7033other, traditional Computer Algebra Systems, like _Maple_, _Mathematica_
7034or _Reduce_, where it has advantages and disadvantages over these
7035systems.
7036
7037* Menu:
7038
7039* Advantages::                       Strengths of the GiNaC approach.
7040* Disadvantages::                    Weaknesses of the GiNaC approach.
7041* Why C++?::                         Attractiveness of C++.
7042
7043
7044File: ginac.info,  Node: Advantages,  Next: Disadvantages,  Prev: A comparison with other CAS,  Up: A comparison with other CAS
7045
70467.1 Advantages
7047==============
7048
7049GiNaC has several advantages over traditional Computer Algebra Systems,
7050like
7051
7052   * familiar language: all common CAS implement their own proprietary
7053     grammar which you have to learn first (and maybe learn again when
7054     your vendor decides to 'enhance' it).  With GiNaC you can write
7055     your program in common C++, which is standardized.
7056
7057   * structured data types: you can build up structured data types using
7058     'struct's or 'class'es together with STL features instead of using
7059     unnamed lists of lists of lists.
7060
7061   * strongly typed: in CAS, you usually have only one kind of variables
7062     which can hold contents of an arbitrary type.  This 4GL like
7063     feature is nice for novice programmers, but dangerous.
7064
7065   * development tools: powerful development tools exist for C++, like
7066     fancy editors (e.g.  with automatic indentation and syntax
7067     highlighting), debuggers, visualization tools, documentation
7068     generators...
7069
7070   * modularization: C++ programs can easily be split into modules by
7071     separating interface and implementation.
7072
7073   * price: GiNaC is distributed under the GNU Public License which
7074     means that it is free and available with source code.  And there
7075     are excellent C++-compilers for free, too.
7076
7077   * extendable: you can add your own classes to GiNaC, thus extending
7078     it on a very low level.  Compare this to a traditional CAS that you
7079     can usually only extend on a high level by writing in the language
7080     defined by the parser.  In particular, it turns out to be almost
7081     impossible to fix bugs in a traditional system.
7082
7083   * multiple interfaces: Though real GiNaC programs have to be written
7084     in some editor, then be compiled, linked and executed, there are
7085     more ways to work with the GiNaC engine.  Many people want to play
7086     with expressions interactively, as in traditional CASs: The tiny
7087     'ginsh' that comes with the distribution exposes many, but not all,
7088     of GiNaC's types to a command line.
7089
7090   * seamless integration: it is somewhere between difficult and
7091     impossible to call CAS functions from within a program written in
7092     C++ or any other programming language and vice versa.  With GiNaC,
7093     your symbolic routines are part of your program.  You can easily
7094     call third party libraries, e.g.  for numerical evaluation or
7095     graphical interaction.  All other approaches are much more
7096     cumbersome: they range from simply ignoring the problem (i.e.
7097     _Maple_) to providing a method for 'embedding' the system (i.e.
7098     _Yacas_).
7099
7100   * efficiency: often large parts of a program do not need symbolic
7101     calculations at all.  Why use large integers for loop variables or
7102     arbitrary precision arithmetics where 'int' and 'double' are
7103     sufficient?  For pure symbolic applications, GiNaC is comparable in
7104     speed with other CAS.
7105
7106
7107File: ginac.info,  Node: Disadvantages,  Next: Why C++?,  Prev: Advantages,  Up: A comparison with other CAS
7108
71097.2 Disadvantages
7110=================
7111
7112Of course it also has some disadvantages:
7113
7114   * advanced features: GiNaC cannot compete with a program like
7115     _Reduce_ which exists for more than 30 years now or _Maple_ which
7116     grows since 1981 by the work of dozens of programmers, with respect
7117     to mathematical features.  Integration, non-trivial
7118     simplifications, limits etc.  are missing in GiNaC (and are not
7119     planned for the near future).
7120
7121   * portability: While the GiNaC library itself is designed to avoid
7122     any platform dependent features (it should compile on any ANSI
7123     compliant C++ compiler), the currently used version of the CLN
7124     library (fast large integer and arbitrary precision arithmetics)
7125     can only by compiled without hassle on systems with the C++
7126     compiler from the GNU Compiler Collection (GCC).(1) GiNaC uses
7127     recent language features like explicit constructors, mutable
7128     members, RTTI, 'dynamic_cast's and STL, so ANSI compliance is meant
7129     literally.
7130
7131   ---------- Footnotes ----------
7132
7133   (1) This is because CLN uses PROVIDE/REQUIRE like macros to let the
7134compiler gather all static initializations, which works for GNU C++
7135only.  Feel free to contact the authors in case you really believe that
7136you need to use a different compiler.  We have occasionally used other
7137compilers and may be able to give you advice.
7138
7139
7140File: ginac.info,  Node: Why C++?,  Next: Internal structures,  Prev: Disadvantages,  Up: A comparison with other CAS
7141
71427.3 Why C++?
7143============
7144
7145Why did we choose to implement GiNaC in C++ instead of Java or any other
7146language?  C++ is not perfect: type checking is not strict (casting is
7147possible), separation between interface and implementation is not
7148complete, object oriented design is not enforced.  The main reason is
7149the often scolded feature of operator overloading in C++.  While it may
7150be true that operating on classes with a '+' operator is rarely
7151meaningful, it is perfectly suited for algebraic expressions.  Writing
71523x+5y as '3*x+5*y' instead of 'x.times(3).plus(y.times(5))' looks much
7153more natural.  Furthermore, the main developers are more familiar with
7154C++ than with any other programming language.
7155
7156
7157File: ginac.info,  Node: Internal structures,  Next: Expressions are reference counted,  Prev: Why C++?,  Up: Top
7158
7159Appendix A Internal structures
7160******************************
7161
7162* Menu:
7163
7164* Expressions are reference counted::
7165* Internal representation of products and sums::
7166
7167
7168File: ginac.info,  Node: Expressions are reference counted,  Next: Internal representation of products and sums,  Prev: Internal structures,  Up: Internal structures
7169
7170A.1 Expressions are reference counted
7171=====================================
7172
7173In GiNaC, there is an _intrusive reference-counting_ mechanism at work
7174where the counter belongs to the algebraic objects derived from class
7175'basic' but is maintained by the smart pointer class 'ptr', of which
7176'ex' contains an instance.  If you understood that, you can safely skip
7177the rest of this passage.
7178
7179Expressions are extremely light-weight since internally they work like
7180handles to the actual representation.  They really hold nothing more
7181than a pointer to some other object.  What this means in practice is
7182that whenever you create two 'ex' and set the second equal to the first
7183no copying process is involved.  Instead, the copying takes place as
7184soon as you try to change the second.  Consider the simple sequence of
7185code:
7186
7187     #include <iostream>
7188     #include <ginac/ginac.h>
7189     using namespace std;
7190     using namespace GiNaC;
7191
7192     int main()
7193     {
7194         symbol x("x"), y("y"), z("z");
7195         ex e1, e2;
7196
7197         e1 = sin(x + 2*y) + 3*z + 41;
7198         e2 = e1;                // e2 points to same object as e1
7199         cout << e2 << endl;     // prints sin(x+2*y)+3*z+41
7200         e2 += 1;                // e2 is copied into a new object
7201         cout << e2 << endl;     // prints sin(x+2*y)+3*z+42
7202     }
7203
7204The line 'e2 = e1;' creates a second expression pointing to the object
7205held already by 'e1'.  The time involved for this operation is therefore
7206constant, no matter how large 'e1' was.  Actual copying, however, must
7207take place in the line 'e2 += 1;' because 'e1' and 'e2' are not handles
7208for the same object any more.  This concept is called "copy-on-write
7209semantics".  It increases performance considerably whenever one object
7210occurs multiple times and represents a simple garbage collection scheme
7211because when an 'ex' runs out of scope its destructor checks whether
7212other expressions handle the object it points to too and deletes the
7213object from memory if that turns out not to be the case.  A slightly
7214less trivial example of differentiation using the chain-rule should make
7215clear how powerful this can be:
7216
7217     {
7218         symbol x("x"), y("y");
7219
7220         ex e1 = x + 3*y;
7221         ex e2 = pow(e1, 3);
7222         ex e3 = diff(sin(e2), x);   // first derivative of sin(e2) by x
7223         cout << e1 << endl          // prints x+3*y
7224              << e2 << endl          // prints (x+3*y)^3
7225              << e3 << endl;         // prints 3*(x+3*y)^2*cos((x+3*y)^3)
7226     }
7227
7228Here, 'e1' will actually be referenced three times while 'e2' will be
7229referenced two times.  When the power of an expression is built, that
7230expression needs not be copied.  Likewise, since the derivative of a
7231power of an expression can be easily expressed in terms of that
7232expression, no copying of 'e1' is involved when 'e3' is constructed.
7233So, when 'e3' is constructed it will print as
7234'3*(x+3*y)^2*cos((x+3*y)^3)' but the argument of 'cos()' only holds a
7235reference to 'e2' and the factor in front is just '3*e1^2'.
7236
7237As a user of GiNaC, you cannot see this mechanism of copy-on-write
7238semantics.  When you insert an expression into a second expression, the
7239result behaves exactly as if the contents of the first expression were
7240inserted.  But it may be useful to remember that this is not what
7241happens.  Knowing this will enable you to write much more efficient
7242code.  If you still have an uncertain feeling with copy-on-write
7243semantics, we recommend you have a look at the C++-FAQ's
7244(https://isocpp.org/faq) chapter on memory management.  It covers this
7245issue and presents an implementation which is pretty close to the one in
7246GiNaC.
7247
7248
7249File: ginac.info,  Node: Internal representation of products and sums,  Next: Package tools,  Prev: Expressions are reference counted,  Up: Internal structures
7250
7251A.2 Internal representation of products and sums
7252================================================
7253
7254Although it should be completely transparent for the user of GiNaC a
7255short discussion of this topic helps to understand the sources and also
7256explain performance to a large degree.  Consider the unexpanded symbolic
7257expression 2*d^3*(4*a+5*b-3) which could naively be represented by a
7258tree of linear containers for addition and multiplication, one container
7259for exponentiation with base and exponent and some atomic leaves of
7260symbols and numbers in this fashion:
7261
7262<PICTURE MISSING>
7263
7264However, doing so results in a rather deeply nested tree which will
7265quickly become inefficient to manipulate.  We can improve on this by
7266representing the sum as a sequence of terms, each one being a pair of a
7267purely numeric multiplicative coefficient and its rest.  In the same
7268spirit we can store the multiplication as a sequence of terms, each
7269having a numeric exponent and a possibly complicated base, the tree
7270becomes much more flat:
7271
7272<PICTURE MISSING>
7273
7274The number '3' above the symbol 'd' shows that 'mul' objects are treated
7275similarly where the coefficients are interpreted as _exponents_ now.
7276Addition of sums of terms or multiplication of products with numerical
7277exponents can be coded to be very efficient with such a pair-wise
7278representation.  Internally, this handling is performed by most CAS in
7279this way.  It typically speeds up manipulations by an order of
7280magnitude.  The overall multiplicative factor '2' and the additive term
7281'-3' look somewhat out of place in this representation, however, since
7282they are still carrying a trivial exponent and multiplicative factor '1'
7283respectively.  Within GiNaC, this is avoided by adding a field that
7284carries an overall numeric coefficient.  This results in the realistic
7285picture of internal representation for 2*d^3*(4*a+5*b-3):
7286
7287<PICTURE MISSING>
7288
7289This also allows for a better handling of numeric radicals, since
7290'sqrt(2)' can now be carried along calculations.  Now it should be
7291clear, why both classes 'add' and 'mul' are derived from the same
7292abstract class: the data representation is the same, only the semantics
7293differs.  In the class hierarchy, methods for polynomial expansion and
7294the like are reimplemented for 'add' and 'mul', but the data structure
7295is inherited from 'expairseq'.
7296
7297
7298File: ginac.info,  Node: Package tools,  Next: Configure script options,  Prev: Internal representation of products and sums,  Up: Top
7299
7300Appendix B Package tools
7301************************
7302
7303If you are creating a software package that uses the GiNaC library,
7304setting the correct command line options for the compiler and linker can
7305be difficult.  The 'pkg-config' utility makes this process easier.
7306GiNaC supplies all necessary data in 'ginac.pc' (installed into
7307'/usr/local/lib/pkgconfig' by default).  To compile a simple program use
7308(1)
7309     g++ -o simple `pkg-config --cflags --libs ginac` simple.cpp
7310
7311This command line might expand to (for example):
7312     g++ -o simple -lginac -lcln simple.cpp
7313
7314Not only is the form using 'pkg-config' easier to type, it will work on
7315any system, no matter how GiNaC was configured.
7316
7317For packages configured using GNU automake, 'pkg-config' also provides
7318the 'PKG_CHECK_MODULES' macro to automate the process of checking for
7319libraries
7320
7321     PKG_CHECK_MODULES(MYAPP, ginac >= MINIMUM_VERSION,
7322                       [ACTION-IF-FOUND],
7323                       [ACTION-IF-NOT-FOUND])
7324
7325This macro:
7326
7327   * Determines the location of GiNaC using data from 'ginac.pc', which
7328     is either found in the default 'pkg-config' search path, or from
7329     the environment variable 'PKG_CONFIG_PATH'.
7330
7331   * Tests the installed libraries to make sure that their version is
7332     later than MINIMUM-VERSION.
7333
7334   * If the required version was found, sets the 'MYAPP_CFLAGS' variable
7335     to the output of 'pkg-config --cflags ginac' and the 'MYAPP_LIBS'
7336     variable to the output of 'pkg-config --libs ginac', and calls
7337     'AC_SUBST()' for these variables so they can be used in generated
7338     makefiles, and then executes ACTION-IF-FOUND.
7339
7340   * If the required version was not found, executes
7341     ACTION-IF-NOT-FOUND.
7342
7343* Menu:
7344
7345* Configure script options::  Configuring a package that uses GiNaC
7346* Example package::           Example of a package using GiNaC
7347
7348   ---------- Footnotes ----------
7349
7350   (1) If GiNaC is installed into some non-standard directory PREFIX one
7351should set the PKG_CONFIG_PATH environment variable to
7352PREFIX/lib/pkgconfig for this to work.
7353
7354
7355File: ginac.info,  Node: Configure script options,  Next: Example package,  Prev: Package tools,  Up: Package tools
7356
7357B.1 Configuring a package that uses GiNaC
7358=========================================
7359
7360The directory where the GiNaC libraries are installed needs to be found
7361by your system's dynamic linkers (both compile- and run-time ones).  See
7362the documentation of your system linker for details.  Also make sure
7363that 'ginac.pc' is in 'pkg-config''s search path, *Note pkg-config:
7364(*manpages*)pkg-config.
7365
7366The short summary below describes how to do this on a GNU/Linux system.
7367
7368Suppose GiNaC is installed into the directory 'PREFIX'.  To tell the
7369linkers where to find the library one should
7370
7371   * edit '/etc/ld.so.conf' and run 'ldconfig'.  For example,
7372          # echo PREFIX/lib >> /etc/ld.so.conf
7373          # ldconfig
7374
7375   * or set the environment variables 'LD_LIBRARY_PATH' and
7376     'LD_RUN_PATH'
7377          $ export LD_LIBRARY_PATH=PREFIX/lib
7378          $ export LD_RUN_PATH=PREFIX/lib
7379
7380   * or give a '-L' and '--rpath' flags when running configure, for
7381     instance:
7382
7383          $ LDFLAGS='-Wl,-LPREFIX/lib -Wl,--rpath=PREFIX/lib' ./configure
7384
7385To tell 'pkg-config' where the 'ginac.pc' file is, set the
7386'PKG_CONFIG_PATH' environment variable:
7387     $ export PKG_CONFIG_PATH=PREFIX/lib/pkgconfig
7388
7389Finally, run the 'configure' script
7390     $ ./configure
7391
7392
7393File: ginac.info,  Node: Example package,  Next: Bibliography,  Prev: Configure script options,  Up: Package tools
7394
7395B.2 Example of a package using GiNaC
7396====================================
7397
7398The following shows how to build a simple package using automake and the
7399'PKG_CHECK_MODULES' macro.  The program used here is 'simple.cpp':
7400
7401     #include <iostream>
7402     #include <ginac/ginac.h>
7403
7404     int main()
7405     {
7406         GiNaC::symbol x("x");
7407         GiNaC::ex a = GiNaC::sin(x);
7408         std::cout << "Derivative of " << a
7409                   << " is " << a.diff(x) << std::endl;
7410         return 0;
7411     }
7412
7413You should first read the introductory portions of the automake Manual,
7414if you are not already familiar with it.
7415
7416Two files are needed, 'configure.ac', which is used to build the
7417configure script:
7418
7419     dnl Process this file with autoreconf to produce a configure script.
7420     AC_INIT([simple], 1.0.0, bogus@example.net)
7421     AC_CONFIG_SRCDIR(simple.cpp)
7422     AM_INIT_AUTOMAKE([foreign 1.8])
7423
7424     AC_PROG_CXX
7425     AC_PROG_INSTALL
7426     AC_LANG([C++])
7427
7428     PKG_CHECK_MODULES(SIMPLE, ginac >= 1.3.7)
7429
7430     AC_OUTPUT(Makefile)
7431
7432The 'PKG_CHECK_MODULES' macro does the following: If a GiNaC version
7433greater or equal than 1.3.7 is found, then it defines SIMPLE_CFLAGS and
7434SIMPLE_LIBS.  Otherwise, it dies with the error message like
7435     configure: error: Package requirements (ginac >= 1.3.7) were not met:
7436
7437     Requested 'ginac >= 1.3.7' but version of GiNaC is 1.3.5
7438
7439     Consider adjusting the PKG_CONFIG_PATH environment variable if you
7440     installed software in a non-standard prefix.
7441
7442     Alternatively, you may set the environment variables SIMPLE_CFLAGS
7443     and SIMPLE_LIBS to avoid the need to call pkg-config.
7444     See the pkg-config man page for more details.
7445
7446And the 'Makefile.am', which will be used to build the Makefile.
7447
7448     ## Process this file with automake to produce Makefile.in
7449     bin_PROGRAMS = simple
7450     simple_SOURCES = simple.cpp
7451     simple_CPPFLAGS = $(SIMPLE_CFLAGS)
7452     simple_LDADD = $(SIMPLE_LIBS)
7453
7454This 'Makefile.am', says that we are building a single executable, from
7455a single source file 'simple.cpp'.  Since every program we are building
7456uses GiNaC we could have simply added SIMPLE_CFLAGS to CPPFLAGS and
7457SIMPLE_LIBS to LIBS.  However, it is more flexible to specify libraries
7458and complier options on a per-program basis.
7459
7460To try this example out, create a new directory and add the three files
7461above to it.
7462
7463Now execute the following command:
7464
7465     $ autoreconf -i
7466
7467You now have a package that can be built in the normal fashion
7468
7469     $ ./configure
7470     $ make
7471     $ make install
7472
7473
7474File: ginac.info,  Node: Bibliography,  Next: Concept index,  Prev: Example package,  Up: Top
7475
7476Appendix C Bibliography
7477***********************
7478
7479   - 'ISO/IEC 14882:2011: Programming Languages: C++'
7480
7481   - 'CLN: A Class Library for Numbers', Bruno Haible <haible@ilog.fr>
7482
7483   - 'The C++ Programming Language', Bjarne Stroustrup, 3rd Edition,
7484     ISBN 0-201-88954-4, Addison Wesley
7485
7486   - 'C++ FAQs', Marshall Cline, ISBN 0-201-58958-3, 1995, Addison
7487     Wesley
7488
7489   - 'Algorithms for Computer Algebra', Keith O. Geddes, Stephen R.
7490     Czapor, and George Labahn, ISBN 0-7923-9259-0, 1992, Kluwer
7491     Academic Publishers, Norwell, Massachusetts
7492
7493   - 'Computer Algebra: Systems and Algorithms for Algebraic
7494     Computation', James H. Davenport, Yvon Siret and Evelyne Tournier,
7495     ISBN 0-12-204230-1, 1988, Academic Press, London
7496
7497   - 'Computer Algebra Systems - A Practical Guide', Michael J. Wester
7498     (editor), ISBN 0-471-98353-5, 1999, Wiley, Chichester
7499
7500   - 'The Art of Computer Programming, Vol 2: Seminumerical Algorithms',
7501     Donald E. Knuth, ISBN 0-201-89684-2, 1998, Addison Wesley
7502
7503   - 'Pi Unleashed', Jörg Arndt and Christoph Haenel, ISBN
7504     3-540-66572-2, 2001, Springer, Heidelberg
7505
7506   - 'The Role of gamma5 in Dimensional Regularization', Dirk Kreimer,
7507     hep-ph/9401354
7508
7509
7510File: ginac.info,  Node: Concept index,  Prev: Bibliography,  Up: Top
7511
7512Concept index
7513*************
7514
7515�[index�]
7516* Menu:
7517
7518* abs():                                 Built-in functions.  (line  12)
7519* accept():                              Visitors and tree traversal.
7520                                                              (line   6)
7521* accuracy:                              Numbers.             (line  61)
7522* acos():                                Built-in functions.  (line  24)
7523* acosh():                               Built-in functions.  (line  31)
7524* add:                                   Fundamental containers.
7525                                                              (line   6)
7526* add <1>:                               Internal representation of products and sums.
7527                                                              (line   6)
7528* advocacy:                              A comparison with other CAS.
7529                                                              (line   6)
7530* alternating Euler sum:                 Multiple polylogarithms.
7531                                                              (line   6)
7532* antisymmetrize():                      Symmetrization.      (line   6)
7533* append():                              Lists.               (line   6)
7534* archive (class):                       Input/output.        (line 391)
7535* archiving:                             Input/output.        (line 391)
7536* asin():                                Built-in functions.  (line  23)
7537* asinh():                               Built-in functions.  (line  30)
7538* atan():                                Built-in functions.  (line  25)
7539* atanh():                               Built-in functions.  (line  32)
7540* atom:                                  The class hierarchy. (line  12)
7541* atom <1>:                              Symbols.             (line   6)
7542* Autoconf:                              Configuration.       (line   6)
7543* basic_log_kernel():                    Iterated integrals.  (line  18)
7544* bernoulli():                           Numbers.             (line 224)
7545* beta():                                Built-in functions.  (line  56)
7546* binomial():                            Built-in functions.  (line  63)
7547* branch cut:                            Built-in functions.  (line  66)
7548* building GiNaC:                        Building GiNaC.      (line   6)
7549* calchash():                            Adding classes.      (line 308)
7550* canonicalize_clifford():               Non-commutative objects.
7551                                                              (line 407)
7552* Catalan:                               Constants.           (line   6)
7553* chain rule:                            Symbolic differentiation.
7554                                                              (line   6)
7555* charpoly():                            Matrices.            (line 200)
7556* clifford (class):                      Non-commutative objects.
7557                                                              (line 103)
7558* clifford_bar():                        Non-commutative objects.
7559                                                              (line 373)
7560* clifford_inverse():                    Non-commutative objects.
7561                                                              (line 393)
7562* clifford_max_label():                  Non-commutative objects.
7563                                                              (line 427)
7564* clifford_moebius_map():                Non-commutative objects.
7565                                                              (line 412)
7566* clifford_norm():                       Non-commutative objects.
7567                                                              (line 389)
7568* clifford_prime():                      Non-commutative objects.
7569                                                              (line 373)
7570* clifford_star():                       Non-commutative objects.
7571                                                              (line 373)
7572* clifford_to_lst():                     Non-commutative objects.
7573                                                              (line 357)
7574* clifford_unit():                       Non-commutative objects.
7575                                                              (line 265)
7576* CLN:                                   Installation.        (line   6)
7577* CLN <1>:                               Numbers.             (line   6)
7578* coeff():                               Polynomial arithmetic.
7579                                                              (line  92)
7580* collect():                             Polynomial arithmetic.
7581                                                              (line  21)
7582* collect_common_factors():              Polynomial arithmetic.
7583                                                              (line  21)
7584* color (class):                         Non-commutative objects.
7585                                                              (line 448)
7586* color_d():                             Non-commutative objects.
7587                                                              (line 474)
7588* color_f():                             Non-commutative objects.
7589                                                              (line 474)
7590* color_h():                             Non-commutative objects.
7591                                                              (line 488)
7592* color_ONE():                           Non-commutative objects.
7593                                                              (line 464)
7594* color_T():                             Non-commutative objects.
7595                                                              (line 452)
7596* color_trace():                         Non-commutative objects.
7597                                                              (line 532)
7598* compare():                             Information about expressions.
7599                                                              (line 231)
7600* compare_same_type():                   Adding classes.      (line 103)
7601* compile_ex:                            Input/output.        (line 326)
7602* compiling expressions:                 Input/output.        (line 276)
7603* complex numbers:                       Numbers.             (line  46)
7604* configuration:                         Configuration.       (line   6)
7605* conjugate():                           Built-in functions.  (line  14)
7606* conjugate() <1>:                       Complex expressions. (line   6)
7607* constant (class):                      Constants.           (line   6)
7608* const_iterator:                        Information about expressions.
7609                                                              (line 124)
7610* const_postorder_iterator:              Information about expressions.
7611                                                              (line 154)
7612* const_preorder_iterator:               Information about expressions.
7613                                                              (line 154)
7614* container:                             The class hierarchy. (line  12)
7615* container <1>:                         Information about expressions.
7616                                                              (line 107)
7617* content():                             Polynomial arithmetic.
7618                                                              (line 193)
7619* contravariant:                         Indexed objects.     (line  23)
7620* Converting ex to other classes:        Information about expressions.
7621                                                              (line   9)
7622* copy-on-write:                         Expressions are reference counted.
7623                                                              (line   6)
7624* cos():                                 Built-in functions.  (line  21)
7625* cosh():                                Built-in functions.  (line  28)
7626* covariant:                             Indexed objects.     (line  23)
7627* csrc:                                  Input/output.        (line  60)
7628* csrc_cl_N:                             Input/output.        (line  60)
7629* csrc_double:                           Input/output.        (line  60)
7630* csrc_float:                            Input/output.        (line  60)
7631* CUBA library:                          Input/output.        (line 321)
7632* DECLARE_FUNCTION:                      Symbolic functions.  (line  10)
7633* degree():                              Polynomial arithmetic.
7634                                                              (line  92)
7635* delta_tensor():                        Indexed objects.     (line 467)
7636* denom():                               Rational expressions.
7637                                                              (line  42)
7638* denominator:                           Rational expressions.
7639                                                              (line  42)
7640* determinant():                         Matrices.            (line 200)
7641* dflt:                                  Input/output.        (line  39)
7642* diag_matrix():                         Matrices.            (line  41)
7643* diff():                                Symbolic differentiation.
7644                                                              (line   6)
7645* differentiation:                       Symbolic differentiation.
7646                                                              (line   6)
7647* Digits:                                Numbers.             (line  61)
7648* Digits <1>:                            Numerical evaluation.
7649                                                              (line  11)
7650* dirac_gamma():                         Non-commutative objects.
7651                                                              (line 109)
7652* dirac_gamma5():                        Non-commutative objects.
7653                                                              (line 138)
7654* dirac_gammaL():                        Non-commutative objects.
7655                                                              (line 144)
7656* dirac_gammaR():                        Non-commutative objects.
7657                                                              (line 144)
7658* dirac_ONE():                           Non-commutative objects.
7659                                                              (line 128)
7660* dirac_slash():                         Non-commutative objects.
7661                                                              (line 153)
7662* dirac_trace():                         Non-commutative objects.
7663                                                              (line 185)
7664* divide():                              Polynomial arithmetic.
7665                                                              (line 167)
7666* doublefactorial():                     Numbers.             (line 222)
7667* dummy index:                           Indexed objects.     (line 339)
7668* Ebar_kernel():                         Iterated integrals.  (line  22)
7669* Eisenstein_h_kernel():                 Iterated integrals.  (line  29)
7670* Eisenstein_kernel():                   Iterated integrals.  (line  28)
7671* ELi_kernel():                          Iterated integrals.  (line  20)
7672* EllipticE():                           Built-in functions.  (line  61)
7673* EllipticK():                           Built-in functions.  (line  60)
7674* epsilon_tensor():                      Indexed objects.     (line 586)
7675* eta():                                 Built-in functions.  (line  36)
7676* Euler:                                 Constants.           (line   6)
7677* Euler numbers:                         Symbolic differentiation.
7678                                                              (line  36)
7679* eval():                                Automatic evaluation.
7680                                                              (line  44)
7681* eval() <1>:                            Adding classes.      (line 248)
7682* evalf():                               Constants.           (line   6)
7683* evalf() <1>:                           Numerical evaluation.
7684                                                              (line   6)
7685* evalm():                               Matrices.            (line 153)
7686* evaluation:                            Automatic evaluation.
7687                                                              (line   6)
7688* evaluation <1>:                        Symbolic functions.  (line  86)
7689* evaluation <2>:                        Adding classes.      (line 248)
7690* exceptions:                            Error handling.      (line   6)
7691* exp():                                 Built-in functions.  (line  33)
7692* expand trancedent functions:           Built-in functions.  (line  82)
7693* expand():                              Indexed objects.     (line 455)
7694* expand() <1>:                          Polynomial arithmetic.
7695                                                              (line  21)
7696* expand_dummy_sum():                    Indexed objects.     (line 390)
7697* expand_options::expand_function_args:  Built-in functions.  (line  82)
7698* expand_options::expand_transcendental: Built-in functions.  (line  82)
7699* expression (class ex):                 Expressions.         (line   6)
7700* ex_is_equal (class):                   Information about expressions.
7701                                                              (line 231)
7702* ex_is_less (class):                    Information about expressions.
7703                                                              (line 231)
7704* ex_to<...>():                          Information about expressions.
7705                                                              (line   9)
7706* factor():                              Polynomial arithmetic.
7707                                                              (line 300)
7708* factorial():                           Built-in functions.  (line  62)
7709* factorization:                         Polynomial arithmetic.
7710                                                              (line 276)
7711* factorization <1>:                     Polynomial arithmetic.
7712                                                              (line 300)
7713* fibonacci():                           Numbers.             (line 225)
7714* find():                                Pattern matching and advanced substitutions.
7715                                                              (line 186)
7716* fraction:                              Numbers.             (line   6)
7717* fsolve:                                What it can do for you.
7718                                                              (line 148)
7719* FUNCP_1P:                              Input/output.        (line 314)
7720* FUNCP_2P:                              Input/output.        (line 314)
7721* FUNCP_CUBA:                            Input/output.        (line 314)
7722* function (class):                      Mathematical functions.
7723                                                              (line   6)
7724* G():                                   Built-in functions.  (line  40)
7725* G() <1>:                               Built-in functions.  (line  42)
7726* Gamma function:                        Mathematical functions.
7727                                                              (line  17)
7728* gamma function:                        Built-in functions.  (line  53)
7729* garbage collection:                    Expressions are reference counted.
7730                                                              (line   6)
7731* GCD:                                   Polynomial arithmetic.
7732                                                              (line 220)
7733* gcd():                                 Polynomial arithmetic.
7734                                                              (line 220)
7735* get_dim():                             Indexed objects.     (line 111)
7736* get_free_indices():                    Indexed objects.     (line 340)
7737* get_metric():                          Non-commutative objects.
7738                                                              (line 288)
7739* get_name():                            Symbols.             (line 148)
7740* get_TeX_name():                        Symbols.             (line 148)
7741* get_value():                           Indexed objects.     (line 111)
7742* ginac-excompiler:                      Input/output.        (line 379)
7743* ginsh:                                 What it can do for you.
7744                                                              (line   6)
7745* ginsh <1>:                             Fundamental containers.
7746                                                              (line  37)
7747* ginsh <2>:                             What does not belong into GiNaC.
7748                                                              (line   6)
7749* GMP:                                   Numbers.             (line   6)
7750* H():                                   Built-in functions.  (line  44)
7751* harmonic polylogarithm:                Multiple polylogarithms.
7752                                                              (line   6)
7753* has():                                 Expressions.         (line   6)
7754* has() <1>:                             Pattern matching and advanced substitutions.
7755                                                              (line 150)
7756* Hermite polynomial:                    How to use it from within C++.
7757                                                              (line  39)
7758* hierarchy of classes:                  Symbols.             (line   6)
7759* hierarchy of classes <1>:              Adding classes.      (line  26)
7760* history of GiNaC:                      Introduction.        (line   6)
7761* hold():                                Symbolic functions.  (line  86)
7762* hold() <1>:                            Adding classes.      (line 248)
7763* hyperbolic function:                   Mathematical functions.
7764                                                              (line   6)
7765* I:                                     Numbers.             (line  46)
7766* I/O:                                   Input/output.        (line   5)
7767* idx (class):                           Indexed objects.     (line  17)
7768* imag():                                Numbers.             (line 191)
7769* imag_part():                           Built-in functions.  (line  16)
7770* indexed (class):                       Indexed objects.     (line  16)
7771* index_dimensions:                      Input/output.        (line 118)
7772* info():                                Information about expressions.
7773                                                              (line   9)
7774* input of expressions:                  Input/output.        (line 180)
7775* installation:                          Installing GiNaC.    (line   6)
7776* integral (class):                      Integrals.           (line   6)
7777* integration_kernel():                  Iterated integrals.  (line  17)
7778* inverse() (matrix):                    Matrices.            (line 226)
7779* inverse() (numeric):                   Numbers.             (line 187)
7780* iquo():                                Numbers.             (line 234)
7781* irem():                                Numbers.             (line 231)
7782* isqrt():                               Numbers.             (line 198)
7783* is_a<...>():                           Information about expressions.
7784                                                              (line   9)
7785* is_equal():                            Information about expressions.
7786                                                              (line 206)
7787* is_equal_same_type():                  Adding classes.      (line 308)
7788* is_exactly_a<...>():                   Information about expressions.
7789                                                              (line   9)
7790* is_polynomial():                       Polynomial arithmetic.
7791                                                              (line   9)
7792* is_zero():                             Information about expressions.
7793                                                              (line 206)
7794* is_zero_matrix():                      Matrices.            (line 122)
7795* iterated_integral():                   Built-in functions.  (line  49)
7796* iterated_integral() <1>:               Built-in functions.  (line  52)
7797* iterators:                             Information about expressions.
7798                                                              (line 124)
7799* Kronecker_dtau_kernel():               Iterated integrals.  (line  24)
7800* Kronecker_dz_kernel():                 Iterated integrals.  (line  26)
7801* latex:                                 Input/output.        (line  98)
7802* Laurent expansion:                     Series expansion.    (line   6)
7803* LCM:                                   Polynomial arithmetic.
7804                                                              (line 220)
7805* lcm():                                 Polynomial arithmetic.
7806                                                              (line 220)
7807* ldegree():                             Polynomial arithmetic.
7808                                                              (line  92)
7809* let_op():                              Structures.          (line 247)
7810* let_op() <1>:                          Adding classes.      (line 338)
7811* lgamma():                              Built-in functions.  (line  54)
7812* Li():                                  Built-in functions.  (line  39)
7813* Li2():                                 Built-in functions.  (line  37)
7814* link_ex:                               Input/output.        (line 343)
7815* lists:                                 Lists.               (line   6)
7816* log():                                 Built-in functions.  (line  34)
7817* lorentz_eps():                         Indexed objects.     (line 585)
7818* lorentz_g():                           Indexed objects.     (line 522)
7819* lsolve():                              Solving linear systems of equations.
7820                                                              (line   6)
7821* lst (class):                           Lists.               (line   6)
7822* lst_to_clifford():                     Non-commutative objects.
7823                                                              (line 327)
7824* lst_to_matrix():                       Matrices.            (line  33)
7825* Machin's formula:                      Series expansion.    (line  38)
7826* map():                                 Applying a function on subexpressions.
7827                                                              (line   6)
7828* match():                               Pattern matching and advanced substitutions.
7829                                                              (line  50)
7830* matrix (class):                        Matrices.            (line   6)
7831* metric_tensor():                       Indexed objects.     (line 489)
7832* mod():                                 Numbers.             (line 227)
7833* modular_form_kernel():                 Iterated integrals.  (line  31)
7834* Monte Carlo integration:               Input/output.        (line 321)
7835* mul:                                   Fundamental containers.
7836                                                              (line   6)
7837* mul <1>:                               Internal representation of products and sums.
7838                                                              (line   6)
7839* multiple polylogarithm:                Multiple polylogarithms.
7840                                                              (line   6)
7841* multiple zeta value:                   Multiple polylogarithms.
7842                                                              (line   6)
7843* multiple_polylog_kernel():             Iterated integrals.  (line  19)
7844* ncmul (class):                         Non-commutative objects.
7845                                                              (line  43)
7846* Nielsen's generalized polylogarithm:   Multiple polylogarithms.
7847                                                              (line   6)
7848* nops():                                Lists.               (line   6)
7849* nops() <1>:                            Information about expressions.
7850                                                              (line 112)
7851* normal():                              Rational expressions.
7852                                                              (line   9)
7853* no_index_dimensions:                   Input/output.        (line 118)
7854* numer():                               Rational expressions.
7855                                                              (line  42)
7856* numerator:                             Rational expressions.
7857                                                              (line  42)
7858* numeric (class):                       Numbers.             (line   6)
7859* numer_denom():                         Rational expressions.
7860                                                              (line  42)
7861* op():                                  Lists.               (line   6)
7862* op() <1>:                              Information about expressions.
7863                                                              (line 112)
7864* Order():                               Series expansion.    (line   6)
7865* Order() <1>:                           Built-in functions.  (line  64)
7866* output of expressions:                 Input/output.        (line   9)
7867* pair-wise representation:              Internal representation of products and sums.
7868                                                              (line  16)
7869* Pattern matching:                      Pattern matching and advanced substitutions.
7870                                                              (line   6)
7871* Pi:                                    Constants.           (line   6)
7872* pole_error (class):                    Error handling.      (line   6)
7873* polylogarithm:                         Multiple polylogarithms.
7874                                                              (line   6)
7875* polynomial:                            Fundamental containers.
7876                                                              (line   6)
7877* polynomial <1>:                        Methods and functions.
7878                                                              (line   6)
7879* polynomial division:                   Polynomial arithmetic.
7880                                                              (line 167)
7881* polynomial factorization:              Polynomial arithmetic.
7882                                                              (line 300)
7883* possymbol():                           Symbols.             (line 169)
7884* pow():                                 Fundamental containers.
7885                                                              (line  20)
7886* power:                                 Fundamental containers.
7887                                                              (line   6)
7888* power <1>:                             Internal representation of products and sums.
7889                                                              (line   6)
7890* prem():                                Polynomial arithmetic.
7891                                                              (line 167)
7892* prepend():                             Lists.               (line   6)
7893* primpart():                            Polynomial arithmetic.
7894                                                              (line 193)
7895* print():                               Printing.            (line  52)
7896* printing:                              Input/output.        (line   9)
7897* print_context (class):                 Printing.            (line  13)
7898* print_csrc (class):                    Printing.            (line  13)
7899* print_dflt (class):                    Printing.            (line  13)
7900* print_latex (class):                   Printing.            (line  13)
7901* print_tree (class):                    Printing.            (line  13)
7902* product rule:                          Symbolic differentiation.
7903                                                              (line   6)
7904* product rule <1>:                      Symbolic functions.  (line 167)
7905* pseries (class):                       Series expansion.    (line   6)
7906* pseudo-remainder:                      Polynomial arithmetic.
7907                                                              (line 167)
7908* pseudo-vector:                         Non-commutative objects.
7909                                                              (line 337)
7910* psi():                                 Built-in functions.  (line  57)
7911* quo():                                 Polynomial arithmetic.
7912                                                              (line 167)
7913* quotient:                              Polynomial arithmetic.
7914                                                              (line 167)
7915* radical:                               Internal representation of products and sums.
7916                                                              (line  41)
7917* rank():                                Matrices.            (line 200)
7918* rational:                              Numbers.             (line   6)
7919* real():                                Numbers.             (line 190)
7920* realsymbol():                          Symbols.             (line 158)
7921* real_part():                           Built-in functions.  (line  15)
7922* reduced_matrix():                      Matrices.            (line  62)
7923* reference counting:                    Expressions are reference counted.
7924                                                              (line   6)
7925* REGISTER_FUNCTION:                     Symbolic functions.  (line  10)
7926* relational (class):                    Relations.           (line   6)
7927* relational (class) <1>:                Information about expressions.
7928                                                              (line 196)
7929* rem():                                 Polynomial arithmetic.
7930                                                              (line 167)
7931* remainder:                             Polynomial arithmetic.
7932                                                              (line 167)
7933* remove_all():                          Lists.               (line   6)
7934* remove_dirac_ONE():                    Non-commutative objects.
7935                                                              (line 402)
7936* remove_first():                        Lists.               (line   6)
7937* remove_last():                         Lists.               (line   6)
7938* representation:                        Internal representation of products and sums.
7939                                                              (line   6)
7940* resultant:                             Polynomial arithmetic.
7941                                                              (line 247)
7942* resultant():                           Polynomial arithmetic.
7943                                                              (line 247)
7944* return_type():                         Non-commutative objects.
7945                                                              (line  60)
7946* return_type() <1>:                     Information about expressions.
7947                                                              (line   9)
7948* return_type_tinfo():                   Non-commutative objects.
7949                                                              (line  60)
7950* return_type_tinfo() <1>:               Information about expressions.
7951                                                              (line   9)
7952* rounding:                              Numbers.             (line 104)
7953* S():                                   Built-in functions.  (line  43)
7954* series():                              Series expansion.    (line   6)
7955* simplification:                        Rational expressions.
7956                                                              (line   9)
7957* simplify_indexed():                    Indexed objects.     (line 401)
7958* sin():                                 Built-in functions.  (line  20)
7959* sinh():                                Built-in functions.  (line  27)
7960* smod():                                Numbers.             (line 229)
7961* solve():                               Matrices.            (line 214)
7962* spinidx (class):                       Indexed objects.     (line 165)
7963* spinor_metric():                       Indexed objects.     (line 545)
7964* sqrfree():                             Polynomial arithmetic.
7965                                                              (line 276)
7966* sqrt():                                Built-in functions.  (line  19)
7967* square-free decomposition:             Polynomial arithmetic.
7968                                                              (line 276)
7969* step():                                Built-in functions.  (line  13)
7970* STL:                                   Advantages.          (line  14)
7971* subs():                                Symbols.             (line 152)
7972* subs() <1>:                            Mathematical functions.
7973                                                              (line  17)
7974* subs() <2>:                            Indexed objects.     (line 205)
7975* subs() <3>:                            Methods and functions.
7976                                                              (line  18)
7977* subs() <4>:                            Substituting expressions.
7978                                                              (line   6)
7979* subs() <5>:                            Pattern matching and advanced substitutions.
7980                                                              (line 211)
7981* sub_matrix():                          Matrices.            (line  62)
7982* symbol (class):                        Symbols.             (line   6)
7983* symbolic_matrix():                     Matrices.            (line  41)
7984* symmetrize():                          Symmetrization.      (line   6)
7985* symmetrize_cyclic():                   Symmetrization.      (line   6)
7986* symmetry (class):                      Indexed objects.     (line 254)
7987* sy_anti():                             Indexed objects.     (line 254)
7988* sy_cycl():                             Indexed objects.     (line 254)
7989* sy_none():                             Indexed objects.     (line 254)
7990* sy_symm():                             Indexed objects.     (line 254)
7991* tan():                                 Built-in functions.  (line  22)
7992* tanh():                                Built-in functions.  (line  29)
7993* Taylor expansion:                      Series expansion.    (line   6)
7994* temporary replacement:                 Rational expressions.
7995                                                              (line   9)
7996* tensor (class):                        Indexed objects.     (line 458)
7997* tgamma():                              Built-in functions.  (line  53)
7998* to_cl_N():                             Numbers.             (line 251)
7999* to_double():                           Numbers.             (line 251)
8000* to_int():                              Numbers.             (line 251)
8001* to_long():                             Numbers.             (line 251)
8002* to_polynomial():                       Rational expressions.
8003                                                              (line  59)
8004* to_rational():                         Rational expressions.
8005                                                              (line  59)
8006* trace():                               Matrices.            (line 200)
8007* transpose():                           Matrices.            (line 126)
8008* traverse():                            Visitors and tree traversal.
8009                                                              (line   6)
8010* traverse_postorder():                  Visitors and tree traversal.
8011                                                              (line   6)
8012* traverse_preorder():                   Visitors and tree traversal.
8013                                                              (line   6)
8014* tree:                                  Input/output.        (line  79)
8015* tree traversal:                        Applying a function on subexpressions.
8016                                                              (line   6)
8017* tree traversal <1>:                    Visitors and tree traversal.
8018                                                              (line   6)
8019* Tree traversal:                        Input/output.        (line 136)
8020* trigonometric function:                Mathematical functions.
8021                                                              (line   6)
8022* unit():                                Polynomial arithmetic.
8023                                                              (line 193)
8024* unitcontprim():                        Polynomial arithmetic.
8025                                                              (line 193)
8026* unit_matrix():                         Matrices.            (line  41)
8027* unlink_ex:                             Input/output.        (line 361)
8028* user_defined_kernel():                 Iterated integrals.  (line  33)
8029* variance:                              Indexed objects.     (line  23)
8030* varidx (class):                        Indexed objects.     (line 133)
8031* viewgar:                               Input/output.        (line 425)
8032* visit():                               Visitors and tree traversal.
8033                                                              (line   6)
8034* visitor (class):                       Visitors and tree traversal.
8035                                                              (line   6)
8036* wildcard (class):                      Pattern matching and advanced substitutions.
8037                                                              (line   6)
8038* Zeta function:                         What it can do for you.
8039                                                              (line 129)
8040* zeta():                                Built-in functions.  (line  46)
8041* zeta() <1>:                            Built-in functions.  (line  47)
8042
8043
8044
8045Tag Table:
8046Node: Top823
8047Node: Introduction1678
8048Node: A tour of GiNaC4874
8049Node: How to use it from within C++5309
8050Node: What it can do for you7632
8051Node: Installation13624
8052Node: Prerequisites14173
8053Node: Configuration15129
8054Ref: Configuration-Footnote-118622
8055Node: Building GiNaC18985
8056Node: Installing GiNaC20992
8057Ref: Installing GiNaC-Footnote-122402
8058Node: Basic concepts22870
8059Node: Expressions24165
8060Node: Automatic evaluation26465
8061Node: Error handling28887
8062Node: The class hierarchy30549
8063Node: Symbols32920
8064Node: Numbers39790
8065Node: Constants51232
8066Node: Fundamental containers51867
8067Node: Lists54699
8068Node: Mathematical functions58519
8069Node: Relations60410
8070Node: Integrals62216
8071Node: Matrices64809
8072Node: Indexed objects73194
8073Node: Non-commutative objects99146
8074Node: Methods and functions121854
8075Node: Information about expressions124445
8076Node: Numerical evaluation135183
8077Node: Substituting expressions136358
8078Node: Pattern matching and advanced substitutions139758
8079Node: Applying a function on subexpressions150275
8080Node: Visitors and tree traversal154807
8081Node: Polynomial arithmetic161716
8082Node: Rational expressions174449
8083Node: Symbolic differentiation178585
8084Node: Series expansion180497
8085Node: Symmetrization184056
8086Node: Built-in functions185351
8087Node: Multiple polylogarithms190300
8088Node: Iterated integrals196795
8089Node: Complex expressions199288
8090Node: Solving linear systems of equations201105
8091Node: Input/output202526
8092Ref: csrc printing204813
8093Node: Extending GiNaC222207
8094Node: What does not belong into GiNaC223147
8095Node: Symbolic functions224332
8096Node: Printing236425
8097Node: Structures248435
8098Node: Adding classes260149
8099Ref: Adding classes-Footnote-1274153
8100Node: A comparison with other CAS274268
8101Node: Advantages274866
8102Node: Disadvantages277891
8103Ref: Disadvantages-Footnote-1279055
8104Node: Why C++?279384
8105Node: Internal structures280208
8106Node: Expressions are reference counted280485
8107Node: Internal representation of products and sums284274
8108Node: Package tools286766
8109Ref: Package tools-Footnote-1288783
8110Node: Configure script options288951
8111Node: Example package290315
8112Node: Bibliography292952
8113Node: Concept index294254
8114
8115End Tag Table
8116
8117
8118Local Variables:
8119coding: utf-8
8120End:
8121