swiginac-1.5.1.1/0000755000175100017520000000000011374770636013706 5ustar skavhaugskavhaugswiginac-1.5.1.1/doc/0000755000175100017520000000000011374770636014453 5ustar skavhaugskavhaugswiginac-1.5.1.1/doc/swiginac_basics.py.txt0000644000175100017520000003274011000603564020756 0ustar skavhaugskavhaug****************************************** SwiGiNaC: Symbolic Computation with Python ****************************************** Basic Examples ************** .. sectnum:: Contents_ Import ====== This script will give a basic overview of what is possible combining symbolic computation by `GiNac` with the flexibility and richness of Python To load swiginac, use one of the ``import`` variants:: import swiginac from swiginac import * Objects defined in this tutorial can be imported with >>> from swiginac_basics import * The swiginac module wraps functions, data and classes defined in the ginac C++ library in a python module. There are more than 600 objects >>> len(dir(swiginac)) 661 but only the most basic will be described in this tutorial. Completing the swiginac functions and classes with docstrings is an open task. Some introspection is possible with e.g. :: # from pprint import pprint # pprint(dir(swiginac)) # pprint(vars(swiginac)) Objects ======= Symbols ------- A symbolic indeterminante or symbolic *variable* is a placeholder for a value in an expression. Symbols are basic units in Swiginac: >>> a = symbol('a') >>> a a The datatype is: >>> type(a) It defines two methods but inherits more than 100 others: >>> len(dir(a)) 108 If you want to list them all, try ``pprint(dir(a))`` In most Computer Algebra Systems (CAS), any unbound variable can be used as a symbol. In Python, you must define a variable as symbol before you can use it in expressions. >>> del(x) >>> y = 3*x Traceback (most recent call last): File "", line 1, in ? NameError: name 'x' is not defined >>> x = symbol('x') >>> y = 3*x `y` is now an expression: >>> y 3*x In order to re-use `y` as a symbol, an ordinary CAS would require you to *delete* it. In Python, you overwrite its current binding with a new assignment to a `symbol` instance: >>> y = symbol('y') >>> y y Defining a set of symbols ~~~~~~~~~~~~~~~~~~~~~~~~~ If we initialize a set of symbols, we might want to use a loop rather than a lot of lines with individual assignments. We can use the feature that the dictionary returned by the built-in function `globals` can be manipulated >>> for name in ['gamma', 'delta', 'epsilon']: ... globals()[name] = swiginac.symbol(name) To define the small latin letters a-z as symbols in this module, :: import string as _string for name in _string.lowercase: globals()[name] = swiginac.symbol(name) Which results in >>> print type(delta), type(x) Numbers ------- The ``numeric`` class can manipulate arbitrary precision integers in a very fast way. Rational numbers are automatically converted to fractions of coprime integers. >>> numeric('4/12') 1/3 The expression given to `numeric` is evaluated using Pythons "standard" arithmetic, which is probabely not what we want when specifying rational numbers: >>> numeric(1/3) 0 >>> numeric(1./3) 0.33333333333333331483 To prevent evaluation the "normal" Python way, rational numbers can be input as string value or as (numerator, denominator) tuple: >>> numeric("1/3") 1/3 >>> numeric(1, 3) 1/3 Often, it is sufficient to specify one number in an expression as `numeric`: >>> numeric(1)/3 1/3 Converting numbers ~~~~~~~~~~~~~~~~~~ The `evalf` method converts any number in GiNaC's expressions into floating point numbers: >>> numeric('1/7').evalf() 0.14285714285714285714 The return value of `evalf` is still a `numeric` value: >>> type(numeric('1/7').evalf()) You can convert it to a Python datatype using the `to_double`, `to_int`, or `to_long` methods: >>> type(numeric('1/7').to_double()) There are other converting methods, like `numeric.evalm` or `numeric.to_cl_N` but what do they do? Complex Numbers ~~~~~~~~~~~~~~~ Complex numbers are expressad with the imaginary unit `I` >>> I, I**2, 2+3*I (I, -1, 2+3*I) However, they are numbers (even if they look like a symbol, sum, or product): >>> type(I), type(2 + 3*I) (, ) Python's `complex` numbers can currently not be converted to `numeric` objects: >>> z_gi = numeric(2+3j) Traceback (most recent call last): ... NotImplementedError: Wrong number of arguments for overloaded function 'new_numeric'. Possible C/C++ prototypes are: GiNaC::numeric(int) GiNaC::numeric(unsigned int) GiNaC::numeric(long) GiNaC::numeric(unsigned long) GiNaC::numeric(long,long) GiNaC::numeric(double) GiNaC::numeric(char const *) GiNaC::numeric(cln::cl_N const &) A workaround is to use an expression:: z_py = 2+3j z_gi = z_py.real + z_py.imag*I which will be simplified to a number: >>> print z_gi, type(z_gi) 2.0+3.0*I How do complex expression evaluate? `evalf` converts real and imaginary part to floating point numbers >>> z_gi.evalf() 2.0+3.0*I `to_double()` returns the real part as `double` instance >>> z_gi.to_double() 2.0 While Phyton's `complex` class stores real and imaginary part as attributes, `numeric` provides methods to retrieve them (as `numeric` instances): >>> z_py.real, z_gi.real (2.0, ) >>> z_gi.real(), z_gi.imag() (2.0, 3.0) Constants --------- Some mathematical constants are available as well >>> print Pi, type(Pi), Pi.evalf() Pi 3.1415926535897932385 >>> print Euler, type(Euler), Euler.evalf() Euler 0.5772156649015328606 Swiginac functions_ know some simplifications for special values >>> print sin(Pi), cos(Pi) 0 -1 Expressions ----------- Expressions in GiNaC are built with symbols and numbers. They are converted to a "canonical" representation and have a class that depends on the expression:: ex1 = a/2 + b ex2 = (a+b)/2 ex3 = (a+b)/c >>> print ex1, type(ex1) 1/2*a+b >>> print ex2, type(ex2) 1/2*a+1/2*b >>> print ex3, type(ex3) (a+b)*c**(-1) In the `Symbolic` package, there is the common class `Symbolic.Expr` with some additional methods. Functions --------- About 40 mathematical functions are available in `swiginac`. All trigonometric and hyperbolic functions are implemented. For a full list of available functions see the file `doc/examples/functions.py`. Some functions are simplified if this is mathemetically sound and non-ambiguous. >>> sin(x), sin(0), sin(Pi/2) (sin(x), 0, 1) >>> cos(x), cos(0), cos(Pi/2) (cos(x), 1, 0) >>> tan(x), tan(0), tan(Pi/2) Traceback (most recent call last): ... StandardError: tan_eval(): simple pole But not all simplifications are implemented >>> sin(x)**2 + cos(x)**2 sin(x)**2+cos(x)**2 :: z_s = cos(x) + I*sin(x) z_e = exp(I*x) >>> z_s/z_e (cos(x)+I*sin(x))*exp(I*x)**(-1) Is there a way get more simplifications? Matrices -------- Marices can be defined giving the number of rows and columns:: M1 = matrix(2,2) Elements will be initialized with 0 and can be set individually:: M1[0,0] = x M1[1,1] = y >>> M1 [[x,0],[0,y]] >>> M1.printc() '[[x,0.0],[0.0,y]]' >>> M1.printlatex() '\\left(\\begin{array}{cc}x&0\\\\0&y\\end{array}\\right)' Alternatively, they can be initialized by a list of lists:: M2 = matrix([[x,0],[0, y]]) Diagonal matrices can be created with a special constructor:: M3 = diag_matrix([x, y]) >>> bool(M1 == M2 == M3) True Vectors are (1,n) or (n,1) matrices:: A = matrix([range(4)]) B = matrix([[a], [b], [c]]) C = matrix([[0], [1], [2]]) But why is the matrix product not working? >>> print A*B [[0,1,2,3]]*[[a],[b],[c]] >>> C = matrix([[0], [1], [2]]) >>> print A*C [[0,1,2,3]]*[[0],[1],[2]] Functions are not broadcast to the matrix elements as in NumPy >>> sin(A) sin([[0,1,2,3]]) How about substitution? >>> sin(x).subs(x == A) sin([[0,1,2,3]]) Symbolic calculations ===================== Differentiation --------------- Objects have the method `diff` for differentiation which is also called by the `diff` function: >>> P = x**5 + x**2 + x >>> P.diff(x) == diff(P, x) 1+5*x**4+2*x==1+5*x**4+2*x >>> P.diff(x, 2) == diff(P, x, 2) 2+20*x**3==2+20*x**3 >>> diff(sin(exp(x)), x) == sin(exp(x)).diff(x) cos(exp(x))*exp(x)==cos(exp(x))*exp(x) Simple integral support ----------------------- We can construct integral objects and integrate either symbolically or numerically:: x = symbol('x') integ = integral(x, 0, 1, x*x) >>> integ [integral object] >>> print integ.printlatex() \int_{0}^{1} dx\,x^{2} >>> integ.eval_integ() 1/3 >>> integ.evalf() 0.33333333333333333332 Substitution ------------ Algebraic objects in expressions can be substituted:: s0 = sin(exp(x)) s1 = s0.subs(exp(x)==sqrt(y)) s2 = s1.subs(y==2) >>> s1 sin(y**(1/2)) >>> s2.evalf() 0.98776594599273552706 >>> float(s2.evalf()) 0.98776594599273548 It is possible to replace individual symbols or terms. Several substitutions can be given in a sequence (list or tuple):: s3 = sin(x+y+z) s4 = s3.subs([x==1, y==2]) s5 = s3.subs(x+y+z==6) >>> print s4 sin(3+z) >>> print s5 sin(6) But sub-expressions do not match:: s6 = s3.subs(x+y==4) >>> s6 sin(x+y+z) >>> s3.subs(x+y==4) sin(x+y+z) Strange: Some substitutions work in the module but fail the doctest: >>> print s3.subs([x==1, y==2]) sin(3+z) Failed example: print s3.subs([x==1, y==2]) Expected: sin(3+z) Got: sin(x+y+z) >>> print s3.subs([x==1, y==2, z==3]) sin(6) Failed example: print s3.subs([x==1, y==2, z==3]) Expected: sin(6) Got: sin(3+x+y) >>> s7 = s3.subs([x==1, y==2, z==3]) >>> s7 sin(6) Failed example: s7 Expected: sin(6) Got: sin(3+x+y) Solving linear systems ---------------------- The function `lsolve` solves linear systems:: lgs = [3*x + 5*y == 2, 5*x+y == -3] ev = lsolve(lgs, [x,y]) >>> ev [x==-17/22, y==19/22] >>> lgs[0].subs(ev) 2==2 >>> lgs[1].subs(ev) -3==-3 Taylor series expansion ----------------------- Expressions can expand themselves as a Taylor series:: x =symbol("x") taylor = sin(x).series(x==0, 8) >>> taylor 1*x+(-1/6)*x**3+1/120*x**5+(-1/5040)*x**7+Order(x**8) Output Formatting ================= Print styles ------------ Expressions have methods returning string representations in several styles: >>> [method for method in dir(ex4) if method.find('print') == 0] ['print_dispatch', 'printc', 'printlatex', 'printpython'] Symbols can be defined with additional TeX string representation Greek letter names will be converted to commands in Tex output:: a_pix = symbol('a_pix', 'a_\mathrm{pix}') beta = symbol('beta') ex4 = a_pix + beta/2 >>> ex4.printpython() '1/2*beta+a_pix' >>> ex4.printc() ' beta/2.0+a_pix' >>> ex4.printlatex() '\\frac{1}{2} \\beta+a_\\mathrm{pix}' A default output style (print context) can be set for an object >>> print ex4 1/2*beta+a_pix >>> ex4.set_print_context('tex') >>> print ex4 \frac{1}{2} \beta+a_\mathrm{pix} Especially for interactive use, it would be nice if this could also be done on a per-module or per-application scale (as in GiNaC itself). Format the output of numbers ---------------------------- The output format for numbers is sometimes too verbose for practical use, especially with floats as precision is govened by DIGITS (20): >>> from swiginac import * >>> x = Pi.evalf() >>> print x 3.1415926535897932385 Python's built in function `round()` can be used to round any object that can be converted to a float to a given accuracy. The result is, however, not always as expected: >>> round(x, 4) 3.1415999999999999 This is caused by the internal use of a number base different from 10. String formatting ----------------- In Python, you can use string formatting to get a specific notation or accuracy: The '%f' specifier can be used for `swiginac.numeric` instances that are convertible to floats: >>> print "%f, %f, %f" % (x, sin(x), exp(x)) 3.141593, -0.000000, 23.140693 It fails on objects that cannot be converted to floats: >>> print "%f" % Pi Traceback (most recent call last): ... TypeError: float argument required Save programming would require to e.g. test the datatype with >>> x.is_real() True or use a try/catch clause. The formatting options are described in the Python documentation on `string formatting operations`_. Here some examples: Precision: >>> print "%.10f" % x 3.1415926536 ... is limited to DIGITS internally >>> print "%.60f" % x 3.141592653589793115997963468544185161590576171875000000000000 Leading sign and zeros: >>> print "%+.1f" % x +3.1 >>> print "%05.1f" % x 003.1 Scientific notation >>> print "%.3E %.2e" % (x, x) 3.142E+00 3.14e+00 >>> print "%g %g" % (x, x**40) 3.14159 7.69121e+19 .. _string formatting operations: http://www.python.org/doc/lib/typesseq-strings.html Interaction with Python ----------------------- Series and sums ~~~~~~~~~~~~~~~ A series could be defined as a Python sequence, e.g. >>> x = symbol('x') >>> [x/n for n in range(1, 10)] [x, 1/2*x, 1/3*x, 1/4*x, 1/5*x, 1/6*x, 1/7*x, 1/8*x, 1/9*x] >>> sinc5 = [sin(phi)/phi for phi in range(1,5)]; sinc5 [sin(1), 1/2*sin(2), 1/3*sin(3), 1/4*sin(4)] Attention, the loop indices are now integers >>> n, phi (9, 4) so it might be a good idea to use separate conventions for naming symbols and indices. As the standard function sum is overloaded for swiginac classes, it can be used on sequences of symbols or expressions: >>> sum((x, y, z)) y+x+z >>> sum([x/n for n in range(1, 10)]) 7129/2520*x Compute the sum over the list defined earlier in this section: >>> sum(sinc5) 1/2*sin(2)+1/3*sin(3)+sin(1)+1/4*sin(4) .. contents:: swiginac-1.5.1.1/doc/swiginac_basics.py.html0000644000175100017520000006067511000606147021113 0ustar skavhaugskavhaug SwiGiNaC: Symbolic Computation with Python

SwiGiNaC: Symbolic Computation with Python

Basic Examples

Contents

1   Import

This script will give a basic overview of what is possible combining symbolic computation by GiNac with the flexibility and richness of Python

To load swiginac, use one of the import variants:

import swiginac
from swiginac import *

Objects defined in this tutorial can be imported with

>>> from swiginac_basics import *

The swiginac module wraps functions, data and classes defined in the ginac C++ library in a python module. There are more than 600 objects

>>> len(dir(swiginac))
661

but only the most basic will be described in this tutorial.

Completing the swiginac functions and classes with docstrings is an open task. Some introspection is possible with e.g.

# from pprint import pprint
# pprint(dir(swiginac))
# pprint(vars(swiginac))

2   Objects

2.1   Symbols

A symbolic indeterminante or symbolic variable is a placeholder for a value in an expression.

Symbols are basic units in Swiginac:

>>> a = symbol('a')
>>> a
a

The datatype is:

>>> type(a)
<class 'swiginac.symbol'>

It defines two methods but inherits more than 100 others:

>>> len(dir(a))
108

If you want to list them all, try pprint(dir(a))

In most Computer Algebra Systems (CAS), any unbound variable can be used as a symbol. In Python, you must define a variable as symbol before you can use it in expressions.

>>> del(x)
>>> y = 3*x
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
NameError: name 'x' is not defined
>>> x = symbol('x')
>>> y = 3*x

y is now an expression:

>>> y
3*x

In order to re-use y as a symbol, an ordinary CAS would require you to delete it. In Python, you overwrite its current binding with a new assignment to a symbol instance:

>>> y = symbol('y')
>>> y
y

2.1.1   Defining a set of symbols

If we initialize a set of symbols, we might want to use a loop rather than a lot of lines with individual assignments.

We can use the feature that the dictionary returned by the built-in function globals can be manipulated

>>> for name in ['gamma', 'delta', 'epsilon']:
...     globals()[name] = swiginac.symbol(name)

To define the small latin letters a-z as symbols in this module,

import string as _string

for name in _string.lowercase:
  globals()[name] = swiginac.symbol(name)

Which results in

>>> print type(delta), type(x)
<class 'swiginac.symbol'> <class 'swiginac.symbol'>

2.2   Numbers

The numeric class can manipulate arbitrary precision integers in a very fast way.

Rational numbers are automatically converted to fractions of coprime integers.

>>> numeric('4/12')
1/3

The expression given to numeric is evaluated using Pythons "standard" arithmetic, which is probabely not what we want when specifying rational numbers:

>>> numeric(1/3)
0
>>> numeric(1./3)
0.33333333333333331483

To prevent evaluation the "normal" Python way, rational numbers can be input as string value or as (numerator, denominator) tuple:

>>> numeric("1/3")
1/3
>>> numeric(1, 3)
1/3

Often, it is sufficient to specify one number in an expression as numeric:

>>> numeric(1)/3
1/3

2.2.1   Converting numbers

The evalf method converts any number in GiNaC's expressions into floating point numbers:

>>> numeric('1/7').evalf()
0.14285714285714285714

The return value of evalf is still a numeric value:

>>> type(numeric('1/7').evalf())
<class 'swiginac.numeric'>

You can convert it to a Python datatype using the to_double, to_int, or to_long methods:

>>> type(numeric('1/7').to_double())
<type 'float'>

There are other converting methods, like numeric.evalm or numeric.to_cl_N but what do they do?

2.2.2   Complex Numbers

Complex numbers are expressad with the imaginary unit I

>>> I, I**2, 2+3*I
(I, -1, 2+3*I)

However, they are numbers (even if they look like a symbol, sum, or product):

>>> type(I), type(2 + 3*I)
(<class 'swiginac.numeric'>, <class 'swiginac.numeric'>)

Python's complex numbers can currently not be converted to numeric objects:

>>> z_gi = numeric(2+3j)
Traceback (most recent call last):
    ...
NotImplementedError: Wrong number of arguments for overloaded function 'new_numeric'.
  Possible C/C++ prototypes are:
    GiNaC::numeric(int)
    GiNaC::numeric(unsigned int)
    GiNaC::numeric(long)
    GiNaC::numeric(unsigned long)
    GiNaC::numeric(long,long)
    GiNaC::numeric(double)
    GiNaC::numeric(char const *)
    GiNaC::numeric(cln::cl_N const &)
<BLANKLINE>

A workaround is to use an expression:

z_py = 2+3j
z_gi = z_py.real + z_py.imag*I

which will be simplified to a number:

>>> print z_gi, type(z_gi)
2.0+3.0*I <class 'swiginac.numeric'>

How do complex expression evaluate?

evalf converts real and imaginary part to floating point numbers

>>> z_gi.evalf()
2.0+3.0*I

to_double() returns the real part as double instance

>>> z_gi.to_double()
2.0

While Phyton's complex class stores real and imaginary part as attributes, numeric provides methods to retrieve them (as numeric instances):

>>> z_py.real, z_gi.real
(2.0, <bound method numeric.real of 2.0+3.0*I>)
>>> z_gi.real(), z_gi.imag()
(2.0, 3.0)

2.3   Constants

Some mathematical constants are available as well

>>> print Pi, type(Pi), Pi.evalf()
Pi <class 'swiginac.constant'> 3.1415926535897932385
>>> print Euler, type(Euler), Euler.evalf()
Euler <class 'swiginac.constant'> 0.5772156649015328606

Swiginac functions know some simplifications for special values

>>> print sin(Pi), cos(Pi)
0 -1

2.4   Expressions

Expressions in GiNaC are built with symbols and numbers.

They are converted to a "canonical" representation and have a class that depends on the expression:

ex1 = a/2 + b
ex2 = (a+b)/2
ex3 = (a+b)/c
>>> print ex1, type(ex1)
1/2*a+b <class 'swiginac.add'>
>>> print ex2, type(ex2)
1/2*a+1/2*b <class 'swiginac.add'>
>>> print ex3, type(ex3)
(a+b)*c**(-1) <class 'swiginac.mul'>

In the Symbolic package, there is the common class Symbolic.Expr with some additional methods.

2.5   Functions

About 40 mathematical functions are available in swiginac. All trigonometric and hyperbolic functions are implemented. For a full list of available functions see the file doc/examples/functions.py.

Some functions are simplified if this is mathemetically sound and non-ambiguous.

>>> sin(x), sin(0), sin(Pi/2)
(sin(x), 0, 1)
>>> cos(x), cos(0), cos(Pi/2)
(cos(x), 1, 0)
>>> tan(x), tan(0), tan(Pi/2)
Traceback (most recent call last):
  ...
StandardError: tan_eval(): simple pole

But not all simplifications are implemented

>>> sin(x)**2 + cos(x)**2
sin(x)**2+cos(x)**2
z_s = cos(x) + I*sin(x)
z_e = exp(I*x)
>>> z_s/z_e
(cos(x)+I*sin(x))*exp(I*x)**(-1)

Is there a way get more simplifications?

2.6   Matrices

Marices can be defined giving the number of rows and columns:

M1 = matrix(2,2)

Elements will be initialized with 0 and can be set individually:

M1[0,0] = x
M1[1,1] = y
>>> M1
[[x,0],[0,y]]
>>> M1.printc()
'[[x,0.0],[0.0,y]]'
>>> M1.printlatex()
'\\left(\\begin{array}{cc}x&0\\\\0&y\\end{array}\\right)'

Alternatively, they can be initialized by a list of lists:

M2 = matrix([[x,0],[0, y]])

Diagonal matrices can be created with a special constructor:

M3 = diag_matrix([x, y])
>>> bool(M1 == M2 == M3)
True

Vectors are (1,n) or (n,1) matrices:

A = matrix([range(4)])
B = matrix([[a], [b], [c]])
C = matrix([[0], [1], [2]])

But why is the matrix product not working?

>>> print A*B
[[0,1,2,3]]*[[a],[b],[c]]
>>> C = matrix([[0], [1], [2]])
>>> print A*C
[[0,1,2,3]]*[[0],[1],[2]]

Functions are not broadcast to the matrix elements as in NumPy

>>> sin(A)
sin([[0,1,2,3]])

How about substitution?

>>> sin(x).subs(x == A)
sin([[0,1,2,3]])

3   Symbolic calculations

3.1   Differentiation

Objects have the method diff for differentiation which is also called by the diff function:

>>> P = x**5 + x**2 + x
>>> P.diff(x) == diff(P, x)
1+5*x**4+2*x==1+5*x**4+2*x
>>> P.diff(x, 2) == diff(P, x, 2)
2+20*x**3==2+20*x**3
>>> diff(sin(exp(x)), x) == sin(exp(x)).diff(x)
cos(exp(x))*exp(x)==cos(exp(x))*exp(x)

3.2   Simple integral support

We can construct integral objects and integrate either symbolically or numerically:

x = symbol('x')
integ = integral(x, 0, 1, x*x)
>>> integ
[integral object]
>>> print integ.printlatex()
\int_{0}^{1} dx\,x^{2}
>>> integ.eval_integ()
1/3
>>> integ.evalf()
0.33333333333333333332

3.3   Substitution

Algebraic objects in expressions can be substituted:

s0 = sin(exp(x))
s1 = s0.subs(exp(x)==sqrt(y))
s2 = s1.subs(y==2)
>>> s1
sin(y**(1/2))
>>> s2.evalf()
0.98776594599273552706
>>> float(s2.evalf())
0.98776594599273548

It is possible to replace individual symbols or terms. Several substitutions can be given in a sequence (list or tuple):

s3 = sin(x+y+z)

s4 = s3.subs([x==1, y==2])
s5 = s3.subs(x+y+z==6)
>>> print s4
sin(3+z)
>>> print s5
sin(6)

But sub-expressions do not match:

s6 = s3.subs(x+y==4)
>>> s6
sin(x+y+z)
>>> s3.subs(x+y==4)
sin(x+y+z)

Strange: Some substitutions work in the module but fail the doctest:

>>> print s3.subs([x==1, y==2])
sin(3+z)
Failed example:
print s3.subs([x==1, y==2])
Expected:
sin(3+z)
Got:
sin(x+y+z)
>>> print s3.subs([x==1, y==2, z==3])
sin(6)
Failed example:
print s3.subs([x==1, y==2, z==3])
Expected:
sin(6)
Got:
sin(3+x+y)
>>> s7 = s3.subs([x==1, y==2, z==3])
>>> s7
sin(6)
Failed example:
s7
Expected:
sin(6)
Got:
sin(3+x+y)

3.4   Solving linear systems

The function lsolve solves linear systems:

lgs = [3*x + 5*y == 2, 5*x+y == -3]

ev = lsolve(lgs, [x,y])
>>> ev
[x==-17/22, y==19/22]
>>> lgs[0].subs(ev)
2==2
>>> lgs[1].subs(ev)
-3==-3

3.5   Taylor series expansion

Expressions can expand themselves as a Taylor series:

x =symbol("x")
taylor = sin(x).series(x==0, 8)
>>> taylor
1*x+(-1/6)*x**3+1/120*x**5+(-1/5040)*x**7+Order(x**8)

4   Output Formatting

4.2   Format the output of numbers

The output format for numbers is sometimes too verbose for practical use, especially with floats as precision is govened by DIGITS (20):

>>> from swiginac import *
>>> x = Pi.evalf()
>>> print x
3.1415926535897932385

Python's built in function round() can be used to round any object that can be converted to a float to a given accuracy. The result is, however, not always as expected:

>>> round(x, 4)
3.1415999999999999

This is caused by the internal use of a number base different from 10.

4.3   String formatting

In Python, you can use string formatting to get a specific notation or accuracy:

The '%f' specifier can be used for swiginac.numeric instances that are convertible to floats:

>>> print "%f, %f, %f" % (x, sin(x), exp(x))
3.141593, -0.000000, 23.140693

It fails on objects that cannot be converted to floats:

>>> print "%f" % Pi
Traceback (most recent call last):
  ...
TypeError: float argument required

Save programming would require to e.g. test the datatype with

>>> x.is_real()
True

or use a try/catch clause.

The formatting options are described in the Python documentation on string formatting operations.

Here some examples:

Precision:

>>> print "%.10f" % x
3.1415926536

... is limited to DIGITS internally

>>> print "%.60f" % x
3.141592653589793115997963468544185161590576171875000000000000

Leading sign and zeros:

>>> print "%+.1f" % x
+3.1
>>> print "%05.1f" % x
003.1

Scientific notation

>>> print "%.3E  %.2e" % (x, x)
3.142E+00  3.14e+00
>>> print "%g  %g" % (x, x**40)
3.14159  7.69121e+19

4.4   Interaction with Python

4.4.1   Series and sums

A series could be defined as a Python sequence, e.g.

>>> x = symbol('x')
>>> [x/n for n in range(1, 10)]
[x, 1/2*x, 1/3*x, 1/4*x, 1/5*x, 1/6*x, 1/7*x, 1/8*x, 1/9*x]
>>> sinc5 = [sin(phi)/phi for phi in range(1,5)]; sinc5
[sin(1), 1/2*sin(2), 1/3*sin(3), 1/4*sin(4)]

Attention, the loop indices are now integers

>>> n, phi
(9, 4)

so it might be a good idea to use separate conventions for naming symbols and indices.

As the standard function sum is overloaded for swiginac classes, it can be used on sequences of symbols or expressions:

>>> sum((x, y, z))
y+x+z
>>> sum([x/n for n in range(1, 10)])
7129/2520*x

Compute the sum over the list defined earlier in this section:

>>> sum(sinc5)
1/2*sin(2)+1/3*sin(3)+sin(1)+1/4*sin(4)
swiginac-1.5.1.1/doc/swiginac_tutorial.py.txt0000644000175100017520000003313310737377143021373 0ustar skavhaugskavhaug****************************************** Symbolic Computation with GiNaC and Python ****************************************** .. Bibliographic Fields :Version: 1.3.5 :Status: draft :Date: 2007-02-01 :Copyright: 2006 Guenter Milde. Released under the terms of the GNU General Public License (v. 2 or later) :Abstract: Using the GiNaC open framework for symbolic computation within the Python programming language .. :Author: Guenter Milde .. :Organization: organization. .. :Contact: contact. .. :Address: address. .. :Dedication: topic. .. sectnum:: .. contents:: Introduction ============ This tutorial is intended for the user who is new to GiNaC_ but already has some background in Python programming. It is an adaption of the `GiNaC tutorial`_ (for symbolic computation within the C++ programming language) for computer algebra with GiNaC_ and the Python_ programming language using the swiginac_ wrapper package. This tutorial only covers the basics, the original `GiNaC tutorial`_ says ... since a hand-made documentation like this one is difficult to keep in sync with the development, the actual documentation is inside the sources in the form of comments. That documentation may be parsed by one of the many Javadoc-like documentation systems. If you fail at generating it you may access it from the GiNaC_ home page. It is an invaluable resource not only for the advanced user who wishes to extend the system (or chase bugs) but for everybody who wants to comprehend the inner workings of GiNaC. This little tutorial on the other hand only covers the basic things that are unlikely to change in the near future. The examples in this tutorial assume a working installation of GiNaC and the swiginac package (see the Installation_ chapter for how to get there). .. _`GiNaC tutorial`: http://www.ginac.de/tutorial/ .. _GiNaC: http://www.ginac.de .. _Python: http://www.python.org .. _swiginac: http://swiginac.berlios.de A Tour of GiNaC =============== This quick tour of GiNaC wants to arise your interest in the subsequent chapters by showing off a bit. Please excuse us if it leaves many open questions. How to use it from within Python -------------------------------- GiNaC_ does not define a programming language of is own as conventional computer algebra systems (CAS) do. GiNaC_ is a C++ library for applications in need of symbolic manipulation. Python_ is such an application. Swiginac_ is a Python interface for GiNaC adding symbolic mathematics to the many features of Python. After starting a python interpreter, import the `swiginac` module with: >>> from swiginac import * Now you can test and experiment with GiNaC's features much like in other Computer Algebra Systems. Here is how to generate and print a simple (and rather pointless) bivariate polynomial with some large coefficients:: from swiginac import * def bipol(): x = symbol('x') y = symbol('y') poly = 0 for i in xrange(3): poly += factorial(i+16) * x**i * y**(2-i) return poly Now we can import the function and try it out: >>> from swiginac_tutorial import bipol >>> print bipol() 355687428096000*y*x+20922789888000*y**2+6402373705728000*x**2 Next, there is a more meaningful function that generates Hermite polynomials in a specified free variable:: def HermitePoly(x, n): HKer = exp(-x**2) # uses the identity H_n(x) == (-1)^n exp(x^2) (d/dx)^n exp(-x^2) return normal((-1)**n * 1/HKer * diff(HKer, x, n)) When run, this will type out the Hermite polynomials as symbolic terms: >>> from swiginac_tutorial import HermitePoly >>> z = symbol("z"); >>> for i in xrange(6): ... print "H_%d(z) == %s"%(i, HermitePoly(z,i)) ... H_0(z) == 1 H_1(z) == 2*z H_2(z) == -2+4*z**2 H_3(z) == -12*z+8*z**3 H_4(z) == 12+16*z**4-48*z**2 H_5(z) == 120*z+32*z**5-160*z**3 This method of generating the coefficients is of course far from optimal for production purposes. What it can do for you ---------------------- In order to show some more examples of GiNaC at work, the original tutorial uses the `GiNaC interactive shell` ``ginsh``. The simple ``ginsh`` shell does not provide programming constructs like loops or conditionals, whereas `swiginac` combines the symbolic capacities of GiNaC_ with the ease of use and the power of the full grown and established programming language Python_. Symbols ~~~~~~~ One main difference between "normal" CAS systems (or ginsh) and computer algebra with Python is the need to define any symbols before use. Otherwise Python will complain about unidentified variables: >>> sin(x) Traceback (most recent call last): File "", line 1, in ? NameError: name 'x' is not defined >>> x = symbol('x') >>> sin(x) sin(x) You can also define a set of symbols in a loop: >>> import sys >>> for sym in ['x', 'y', 'z']: ... setattr(sys.modules[__name__], sym, symbol(sym)) Numbers ~~~~~~~ The ``numeric`` class can manipulate arbitrary precision integers in a very fast way. Rational numbers are automatically converted to fractions of coprime integers. As by default Python will convert a number to one of its internal numerical data types, it is necessary to specify the wish to treat a number as arbitrary precision integer. In an expression, it is often sufficient to define just one numeric value as instance of the numeric class: >>> x = numeric(3)**150 >>> print x 369988485035126972924700782451696644186473100389722973815184405301748249 >>> y = numeric(3)**149 >>> print y 123329495011708990974900260817232214728824366796574324605061468433916083 >>> print x/y 3 >>> print y/x 1/3 When specifying rational numbers, the expression that is the argument to `numeric` is evaluated using Pythons "standard" arithmetic, which is probabely not what we want: >>> print numeric(1/3) 0 >>> print numeric(1./3) 0.33333333333333331483 To prevent evaluation by the "normal" Python operators, rational numbers can be input as string value or as (numerator, denominator) tuple: >>> print numeric("1/3") 1/3 >>> print numeric(1, 3) 1/3 >>> print numeric(3, 9) 1/3 Exact numbers are always retained as exact numbers and only evaluated as floating point numbers if requested. For instance, products of sums of radicals can be expanded: >>> a = symbol('a') >>> expand((1+a**numeric('1/5')-a**numeric('2/5'))**3) 1-a**(6/5)+3*a+3*a**(1/5)-5*a**(3/5) Numeric radicals are dealt pretty much as symbols: >>> expand((1+3**numeric('1/5')-3**numeric('2/5'))**3) 10-5*3**(3/5) >>> ((1+3**numeric('1/5')-3**numeric('2/5'))**3).evalf() 0.33408977534118624228 The ``evalf()`` method used above converts any number in GiNaC's expressions into floating point numbers: >>> numeric('1/7').evalf() 0.14285714285714285714 .. note:: In GiNaC or ginsh, this can be done to arbitrary predefined accuracy:: > Digits=150; 150 > evalf(1/7); 0.1428571428571428571428571428571428571428571428571428571428571428571428 There is no equivalent setting in swiginac (yet). The return value of ``evalf()`` is still a ``numeric`` value: >>> type(numeric('1/7').evalf()) You can convert it to a Python datatype by the usual Python means or using the ``to_double()``, ``to_int()``, or ``to_long()`` methods: >>> type(numeric('1/7').to_double()) Exact numbers that can be manipulated in GiNaC include predefined constants like Archimedes' Pi. They can both be used in symbolic manipulations (as an exact number) as well as in numeric expressions (as an inexact number): >>> x = symbol('x') >>> a = Pi**2 + x >>> a x+Pi**2 >>> a.evalf() 9.869604401089358619+x >>> a.subs(x == 2).evalf() 11.869604401089358619 .. note:: In the last example, the ``subs()`` method is used, as changing the value of ``x`` will not propagate to the already defined expression ``a``: >>> x = 2 >>> a.evalf() 9.869604401089358619+x Built-in functions evaluate immediately to exact numbers if this is possible. Conversions that can be safely performed are done immediately; conversions that are not generally valid are not done: >>> x = symbol('x') >>> cos(42*Pi) 1 >>> cos(acos(x)) x >>> acos(cos(x)); acos(cos(x)) (Note that converting the last input to x would allow one to conclude that 42*Pi is equal to 0.) Linear Algebra ~~~~~~~~~~~~~~ Linear equation systems can be solved along with basic linear algebra manipulations over symbolic expressions. swiginac offers a matrix class for this purpose: >>> x = symbol('x'); y = symbol('y'); z = symbol('z') >>> a = symbol('a'); b = symbol('b'); l = symbol('l') >>> lsolve(a+x*y==z,x) (z-a)*y**(-1) >>> lsolve([3*x+5*y == 7, -2*x+10*y == -5], [x, y]) [x==19/8, y==-1/40] >>> M = matrix([[1, 3], [-3, 2]]) >>> determinant(M); 11 >>> charpoly(M,l) 11+l**2-3*l >>> A = matrix([[1, 1], [2, -1]]) >>> A + 2*M [[3,7],[-4,3]] >>> B = matrix([[0, 0, a], [b, 1, -b], [-1/a, 0, 0]]) >>> evalm(B**(2**12)) [[1,0,0],[0,1,0],[0,0,1]] Multivariate polynomials and rational functions may be expanded, collected and normalized (i.e. converted to a ratio of two coprime polynomials): >>> a = x**4 + 2*x**2*y**2 + 4*x**3*y + 12*x*y**3 - 3*y**4 >>> b = x**2 + 4*x*y - y**2 >>> expand(a*b) 43*y**4*x**2+3*y**6-24*y**5*x+17*y**2*x**4+8*y*x**5+x**6+16*y**3*x**3 >>> collect(a+b,x) -3*y**4+x*(4*y+12*y**3)+(1+2*y**2)*x**2+4*y*x**3+x**4-y**2 >>> collect(a+b,y) -3*y**4+x**2+(4*x**3+4*x)*y+12*y**3*x+x**4+y**2*(-1+2*x**2) >>> normal(a/b) x**2+3*y**2 Calculus ~~~~~~~~ You can differentiate functions and expand them as Taylor or Laurent series in a very natural syntax (the second argument of series is a relation defining the evaluation point, the third specifies the order): >>> diff(tan(x),x) 1+tan(x)**2 >>> series(sin(x),x==0,4) 1*x+(-1/6)*x**3+Order(x**4) >>> series(1/tan(x),x==0,2) 1*x**(-1)+(-1/3)*x+Order(x**2) >>> series(tgamma(x),x==0,2) 1*x**(-1)+(-Euler)+(1/12*Pi**2+1/2*Euler**2)*x+Order(x**2) >>> series(tgamma(x),x==0,2).evalf() 1.0*x**(-1)+(-0.5772156649015328606)+0.9890559953279725555*x+Order(x**2) >>> series(tgamma(2*sin(x)-2),x==Pi/2,3) (-1)*(x-1/2*Pi)**(-2)+(-1/12-Euler)+(-1/240-1/12*Pi**2-1/2*Euler**2)*(x-1/2*Pi)**2+Order((x-1/2*Pi)**3) Often, functions don't have roots in closed form. Nevertheless, it's quite easy to compute a solution numerically: >>> fsolve(cos(x)==x,x,0,2) 0.73908513321516064166 >>> f=exp(sin(x))-x >>> X=fsolve(f,x,-10,10) >>> X 2.2191071489137460327 >>> subs(f,x==X) -2.168404344971008868E-19 Notice how the final result above differs slightly from zero by about 2*10^(-19). This is because with 20 decimal digits precision the root cannot be represented more accurately than X. Such inaccuracies are to be expected when computing with finite floating point values. Symbolic types can always be used as tags for different types of objects. Converting from "wrong" units to the metric system is an example: >>> m = symbol('m'); kg = symbol('kg') >>> inch = .0254*m >>> lb = .45359237*kg >>> 200*lb/inch**2 (140613.91592783187407)*m**(-2)*kg However, as generic symbols do not know about special properties of physical units, it can not simplify all expressions with unit symbols: >>> print abs(-3), abs(-3*m) 3 abs(-3*m) (We know, that m is positiv definit, but GiNaC does not.) The *Scientific.Physics.PhysicalQuantities* module from the Scientific_ package provides an elaborated environment specifically designed for working with units. Unfortunately, it does not collaborate well with swiginac. .. _Scientific: http://dirac.cnrs-orleans.fr/ScientificPython/ Installation ============ GiNaC ----- GiNaC_ sources can be fetched from its home site under the section `Download GiNaC now`_ which also says: Since GiNaC is packaged by a couple of software distributors, you may want to try a conveniently packaged binary first (but please don't send us bug-reports about these packages since they may be outdated). We are currently aware of packages in Debian__, SuSE, Mandrake, Fedora, and FreeBSD. The installation__ is covered in the `GiNaC tutorial`_ (and in the INSTALL file of the tarball). .. _download GiNaC now: http://www.ginac.de/Download.html __ http://www.ginac.de/tutorial/Installation.html#Installation __ http://packages.qa.debian.org/g/ginac.html swiginac -------- swiginac_ is a Python interface to GiNaC, built with SWIG_. The aim of swiginac is to make the functionality of GiNaC accessible from Python as an extension module. Current status is beta; a lot (but not all yet) of the GiNaC classes are exposed, virtually all of the GiNaC tests pass. For more information, documentation and software downloads, visit the `swiginac group pages on BerliOS`__. The `source tarballs`_ contain installation instructions in an INSTALL.txt file. .. _SWIG: http://www.swig.org/ __ http://developer.berlios.de/projects/swiginac/ .. _source tarballs: http://developer.berlios.de/project/filelist.php?group_id=4761 About this Document =================== The `source of this tutorial`_ is written in `reStructured Text`_. To translate it, you need the Python docutils_. With docutils installed, the command ``rst2html swiginac_tutorial.py.txt`` will produce the html file, while ``rst2pdf.py swiginac_tutorial.py.txt`` will produce a PDF version. The bidirectional text <-> code converter PyLit_ can be used to transform the tutorial source to a Python module providing the example functions and to run the examples in a doctest. (This is why it has the ``.py.txt`` double extension.) .. _source of this tutorial: http://svn.berlios.de/svnroot/repos/swiginac/trunk/doc/swiginac_tutorial.py.txt .. _docutils: http://docutils.sourceforge.net/rst.html .. _reStructured Text: http://docutils.sourceforge.net/rst.html .. _pylit: http://pylit.berlios.de swiginac-1.5.1.1/doc/html4css1.css0000644000175100017520000001266011000556362016774 0ustar skavhaugskavhaug/* :Author: David Goodger :Contact: goodger@users.sourceforge.net :Date: $Date: 2008-04-14 06:26:26 +0200 (Mon, 14 Apr 2008) $ :Revision: $Revision: 270 $ :Copyright: This stylesheet has been placed in the public domain. Default cascading style sheet for the HTML output of Docutils. See http://docutils.sf.net/docs/howto/html-stylesheets.html for how to customize this style sheet. */ /* used to remove borders from tables and images */ .borderless, table.borderless td, table.borderless th { border: 0 } table.borderless td, table.borderless th { /* Override padding for "table.docutils td" with "! important". The right padding separates the table cells. */ padding: 0 0.5em 0 0 ! important } .first { /* Override more specific margin styles with "! important". */ margin-top: 0 ! important } .last, .with-subtitle { margin-bottom: 0 ! important } .hidden { display: none } a.toc-backref { text-decoration: none ; color: black } blockquote.epigraph { margin: 2em 5em ; } dl.docutils dd { margin-bottom: 0.5em } /* Uncomment (and remove this text!) to get bold-faced definition list terms dl.docutils dt { font-weight: bold } */ div.abstract { margin: 2em 5em } div.abstract p.topic-title { font-weight: bold ; text-align: center } div.admonition, div.attention, div.caution, div.danger, div.error, div.hint, div.important, div.note, div.tip, div.warning { margin: 2em ; border: medium outset ; padding: 1em } div.admonition p.admonition-title, div.hint p.admonition-title, div.important p.admonition-title, div.note p.admonition-title, div.tip p.admonition-title { font-weight: bold ; font-family: sans-serif } div.attention p.admonition-title, div.caution p.admonition-title, div.danger p.admonition-title, div.error p.admonition-title, div.warning p.admonition-title { color: red ; font-weight: bold ; font-family: sans-serif } /* Uncomment (and remove this text!) to get reduced vertical space in compound paragraphs. div.compound .compound-first, div.compound .compound-middle { margin-bottom: 0.5em } div.compound .compound-last, div.compound .compound-middle { margin-top: 0.5em } */ div.dedication { margin: 2em 5em ; text-align: center ; font-style: italic } div.dedication p.topic-title { font-weight: bold ; font-style: normal } div.figure { margin-left: 2em ; margin-right: 2em } div.footer, div.header { clear: both; font-size: smaller } div.line-block { display: block ; margin-top: 1em ; margin-bottom: 1em } div.line-block div.line-block { margin-top: 0 ; margin-bottom: 0 ; margin-left: 1.5em } div.sidebar { margin-left: 1em ; border: medium outset ; padding: 1em ; background-color: #ffffee ; width: 40% ; float: right ; clear: right } div.sidebar p.rubric { font-family: sans-serif ; font-size: medium } div.system-messages { margin: 5em } div.system-messages h1 { color: red } div.system-message { border: medium outset ; padding: 1em } div.system-message p.system-message-title { color: red ; font-weight: bold } div.topic { margin: 2em } h1.section-subtitle, h2.section-subtitle, h3.section-subtitle, h4.section-subtitle, h5.section-subtitle, h6.section-subtitle { margin-top: 0.4em } h1.title { text-align: center } h2.subtitle { text-align: center } hr.docutils { width: 75% } img.align-left { clear: left } img.align-right { clear: right } ol.simple, ul.simple { margin-bottom: 1em } ol.arabic { list-style: decimal } ol.loweralpha { list-style: lower-alpha } ol.upperalpha { list-style: upper-alpha } ol.lowerroman { list-style: lower-roman } ol.upperroman { list-style: upper-roman } p.attribution { text-align: right ; margin-left: 50% } p.caption { font-style: italic } p.credits { font-style: italic ; font-size: smaller } p.label { white-space: nowrap } p.rubric { font-weight: bold ; font-size: larger ; color: maroon ; text-align: center } p.sidebar-title { font-family: sans-serif ; font-weight: bold ; font-size: larger } p.sidebar-subtitle { font-family: sans-serif ; font-weight: bold } p.topic-title { font-weight: bold } pre.address { margin-bottom: 0 ; margin-top: 0 ; font-family: serif ; font-size: 100% } pre.literal-block, pre.doctest-block { margin-left: 2em ; margin-right: 2em ; background-color: #eeeeee } span.classifier { font-family: sans-serif ; font-style: oblique } span.classifier-delimiter { font-family: sans-serif ; font-weight: bold } span.interpreted { font-family: sans-serif } span.option { white-space: nowrap } span.pre { white-space: pre } span.problematic { color: red } span.section-subtitle { /* font-size relative to parent (h1..h6 element) */ font-size: 80% } table.citation { border-left: solid 1px gray; margin-left: 1px } table.docinfo { margin: 2em 4em } table.docutils { margin-top: 0.5em ; margin-bottom: 0.5em } table.footnote { border-left: solid 1px black; margin-left: 1px } table.docutils td, table.docutils th, table.docinfo td, table.docinfo th { padding-left: 0.5em ; padding-right: 0.5em ; vertical-align: top } table.docutils th.field-name, table.docinfo th.docinfo-name { font-weight: bold ; text-align: left ; white-space: nowrap ; padding-left: 0 } h1 tt.docutils, h2 tt.docutils, h3 tt.docutils, h4 tt.docutils, h5 tt.docutils, h6 tt.docutils { font-size: 100% } tt.docutils { background-color: #eeeeee } ul.auto-toc { list-style-type: none } swiginac-1.5.1.1/doc/swiginac_overview.py.txt0000644000175100017520000001147011000603564021355 0ustar skavhaugskavhaugSwiginac - Extending Python with Symbolic Mathematics ===================================================== Ola Skavhaug [1]_\ [2]_ Ondrej Certic [3]_\ [4]_ Excerpt from the slides_ of a presentation of swiginac given at the Fenics'05 meeting in Chicago GiNaC ----- GiNaC__ is not a CAS. GiNaC is a C++ library for applications in need of symbolic manipulation. Python__ is such an application. Features: * Symbols and expressions with arithmetic operations * Multivariate polynomials and rational functions * Matrices and vectors * Linear systems solver * Tayler series expansions * Differentiation and integration * Output C, Python and LaTeX code * ... __ http://www.ginac.de __ http://www.python.org Swiginac -------- Swiginac__ is a Python interface for GiNaC and can be imported as module: >>> from swiginac import * * Strategy: Manually convert the GiNaC header files to SWIG__ interface files, and implement a set of typemaps to make a high-level interface. * A lot, but not all, of the GiNaC classes are now exposed to Python. * Certain GiNaC structures are converted to Python types in the interface and vice versa. __ http://swiginac.berlios.de/ __ http://www.swig.org/ Symbols ------- Symbols are basic units in Swiginac: >>> a = symbol('a', r'\alpha') >>> b = symbol('beta') >>> print a, b a beta >>> u = b + a >>> print u beta+a >>> u.set_print_context('tex') >>> print u \beta+\alpha All expressions in GiNaC are built with symbols. The drawback of this approach is that the level of abstraction is limited Numbers ------- The ``numeric`` class can manipulate arbitrary precision integers in a very fast way. Rational numbers are automatically converted to fractions of coprime integers. When specifying rational numbers, the expression that is the argument to `numeric` is evaluated using Pythons "standard" arithmetic, which is probabely not what we want: >>> numeric(1/3) 0 >>> numeric(1./3) 0.33333333333333331483 To prevent evaluation by the "normal" Python operators, rational numbers can be input as string value or as (numerator, denominator): >>> numeric("1/3") 1/3 >>> numeric(1, 3) 1/3 >>> numeric(3, 9) 1/3 Often, it is sufficient to specify one number in an expression as `numeric`: >>> numeric(1)/3 1/3 Functions --------- Lots of functions are available >>> sin(exp(b)) sin(exp(beta)) >>> v = tgamma(a+sqrt(b)) >>> print v.printlatex() \Gamma(\alpha+\sqrt{\beta}) All trigonometric and hyperbolic functions are implemented in GiNaC, most of them interfaced in swiginac Symbolic differentiation ------------------------ Objects have the method `diff` for differentiation >>> x = symbol('x'); y = symbol('y') >>> P = x**5 + x**2 + y >>> P.diff(x, 1) 2*x+5*x**4 >>> P.diff(x, 2) 2+20*x**3 `diff` exists as a function call too >>> u = sin(exp(x)) >>> diff(u, x) exp(x)*cos(exp(x)) >>> diff(u, x, 2) exp(x)*cos(exp(x))-sin(exp(x))*exp(x)**2 Matrices -------- >>> mat1 = matrix(2,2) # Two by two matrix >>> mat1[0,0] = x >>> mat1[1,1] = y >>> mat1 [[x,0],[0,y]] >>> mat1a = diag_matrix([x,y]) # Alternative definition >>> print mat1.printlatex() \left(\begin{array}{cc}x&0\\0&y\end{array}\right) >>> mat2 = matrix([[sqrt(a),0],[1.0, cosh(b)]]) >>> print mat2.printc() [[pow(a,(1.0/2.0)),0.0],[1.0000000000000000e+00,cosh(beta)]] Simple integral support ----------------------- We can construct integral objects and integrate either symbolically or numerically: >>> integ = integral(x, 0, 1, x*x) >>> integ [integral object] >>> print integ.printlatex() \int_{0}^{1} dx\,x^{2} >>> integ.eval_integ() 1/3 >>> integ.evalf() 0.33333333333333333332 Substitution ------------ Algebraic objects in expressions can be substituted: >>> u = sin(exp(b)) >>> v = u.subs(exp(b)==sqrt(a)) # v = sin(a**(1/2)) >>> w = v.subs(a==2).evalf() # Convert sin(2**(1/2)) to `numeric` >>> print v, w sin(a**(1/2)) 0.98776594599273552706 >>> float(w) # Convert to Python double 0.98776594599273548 Sub-expressions do not match: >>> x = symbol('x'); y = symbol('y'); z = symbol('z') >>> u = sin(x+y+z) >>> u.subs(x+y==4) sin(z+y+x) >>> u.subs([x==1, y==3]) sin(4+z) >>> u.subs([x==1, y==2, z==3]) # Same as u.subs(x+y+z==6) sin(6) Solving linear systems ---------------------- ``lsolve`` solves linear systems: >>> x = symbol('x'); y = symbol('y') >>> solution = lsolve([3*x + 5*y == 2, 5*x+y == -3], [x,y]) >>> solution [x==-17/22, y==19/22] Taylor series expansion ----------------------- Expressions can expand themselves as a Taylor series: >>> sin(x).series(x==0, 8) 1*x+(-1/6)*x**3+1/120*x**5+(-1/5040)*x**7+Order(x**8) .. [1] Simula Research Laboratory .. [2] Dept. of Informatics, University of Oslo .. [3] Faculty of Mathematics and Physics .. [4] Charles University in Prague .. _slides: http://swiginac.berlios.de/chicago05.pdf swiginac-1.5.1.1/doc/swiginac_tutorial.py.html0000644000175100017520000005355511000606147021511 0ustar skavhaugskavhaug Symbolic Computation with GiNaC and Python

Symbolic Computation with GiNaC and Python

Version: 1.3.5
Status: draft
Date: 2007-02-01
Copyright: 2006 Guenter Milde. Released under the terms of the GNU General Public License (v. 2 or later)

Abstract

Using the GiNaC open framework for symbolic computation with the Python programming language

1   Introduction

This tutorial is intended for the user who is new to GiNaC but already has some background in Python programming. It is an adaption of the GiNaC tutorial (for symbolic computation within the C++ programming language) for computer algebra with GiNaC and the Python programming language using the swiginac wrapper package.

This tutorial only covers the basics, the original GiNaC tutorial says

... since a hand-made documentation like this one is difficult to keep in sync with the development, the actual documentation is inside the sources in the form of comments. That documentation may be parsed by one of the many Javadoc-like documentation systems. If you fail at generating it you may access it from the GiNaC home page. It is an invaluable resource not only for the advanced user who wishes to extend the system (or chase bugs) but for everybody who wants to comprehend the inner workings of GiNaC. This little tutorial on the other hand only covers the basic things that are unlikely to change in the near future.

The examples in this tutorial assume a working installation of GiNaC and the swiginac package (see the Installation chapter for how to get there).

2   A Tour of GiNaC

This quick tour of GiNaC wants to arise your interest in the subsequent chapters by showing off a bit.

Please excuse us if it leaves many open questions.

2.1   How to use it from within Python

GiNaC does not define a programming language of is own as conventional computer algebra systems (CAS) do. GiNaC is a C++ library for applications in need of symbolic manipulation.

Python is such an application.

Swiginac is a Python interface for GiNaC adding symbolic mathematics to the many features of Python. After starting a python interpreter, import the swiginac module with:

>>> from swiginac import *

Now you can test and experiment with GiNaC's features much like in other Computer Algebra Systems.

Here is how to generate and print a simple (and rather pointless) bivariate polynomial with some large coefficients:

from swiginac import *

def bipol():
    x = symbol('x')
    y = symbol('y')

    poly = 0
    for i in xrange(3):
         poly += factorial(i+16) * x**i * y**(2-i)

    return poly

Now we can import the function and try it out:

>>> from swiginac_tutorial import bipol
>>> print bipol()
355687428096000*y*x+20922789888000*y**2+6402373705728000*x**2

Next, there is a more meaningful function that generates Hermite polynomials in a specified free variable:

def HermitePoly(x, n):
     HKer = exp(-x**2)
     # uses the identity H_n(x) == (-1)^n exp(x^2) (d/dx)^n exp(-x^2)
     return normal((-1)**n * 1/HKer * diff(HKer, x, n))

When run, this will type out the Hermite polynomials as symbolic terms:

>>> from swiginac_tutorial import HermitePoly
>>> z = symbol("z");
>>> for i in xrange(6):
...     print "H_%d(z) == %s"%(i, HermitePoly(z,i))
...
H_0(z) == 1
H_1(z) == 2*z
H_2(z) == -2+4*z**2
H_3(z) == -12*z+8*z**3
H_4(z) == 12+16*z**4-48*z**2
H_5(z) == 120*z+32*z**5-160*z**3

This method of generating the coefficients is of course far from optimal for production purposes.

2.2   What it can do for you

In order to show some more examples of GiNaC at work, the original tutorial uses the GiNaC interactive shell ginsh. The simple ginsh shell does not provide programming constructs like loops or conditionals, whereas swiginac combines the symbolic capacities of GiNaC with the ease of use and the power of the full grown and established programming language Python.

2.2.1   Symbols

One main difference between "normal" CAS systems (or ginsh) and computer algebra with Python is the need to define any symbols before use. Otherwise Python will complain about unidentified variables:

>>> sin(x)
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
NameError: name 'x' is not defined
>>> x = symbol('x')
>>> sin(x)
sin(x)

You can also define a set of symbols in a loop:

>>> import sys
>>> for sym in ['x', 'y', 'z']:
...    setattr(sys.modules[__name__], sym, symbol(sym))

2.2.2   Numbers

The numeric class can manipulate arbitrary precision integers in a very fast way. Rational numbers are automatically converted to fractions of coprime integers. As by default Python will convert a number to one of its internal numerical data types, it is necessary to specify the wish to treat a number as arbitrary precision integer. In an expression, it is often sufficient to define just one numeric value as instance of the numeric class:

>>> x = numeric(3)**150
>>> print x
369988485035126972924700782451696644186473100389722973815184405301748249
>>> y = numeric(3)**149
>>> print y
123329495011708990974900260817232214728824366796574324605061468433916083
>>> print x/y
3
>>> print y/x
1/3

When specifying rational numbers, the expression that is the argument to numeric is evaluated using Pythons "standard" arithmetic, which is probabely not what we want:

>>> print numeric(1/3)
0
>>> print numeric(1./3)
0.33333333333333331483

To prevent evaluation by the "normal" Python operators, rational numbers can be input as string value or as (numerator, denominator) tuple:

>>> print numeric("1/3")
1/3
>>> print numeric(1, 3)
1/3
>>> print numeric(3, 9)
1/3

Exact numbers are always retained as exact numbers and only evaluated as floating point numbers if requested. For instance, products of sums of radicals can be expanded:

>>> a = symbol('a')
>>> expand((1+a**numeric('1/5')-a**numeric('2/5'))**3)
1-a**(6/5)+3*a+3*a**(1/5)-5*a**(3/5)

Numeric radicals are dealt pretty much as symbols:

>>> expand((1+3**numeric('1/5')-3**numeric('2/5'))**3)
10-5*3**(3/5)
>>> ((1+3**numeric('1/5')-3**numeric('2/5'))**3).evalf()
0.33408977534118624228

The evalf() method used above converts any number in GiNaC's expressions into floating point numbers:

>>> numeric('1/7').evalf()
0.14285714285714285714

Note

In GiNaC or ginsh, this can be done to arbitrary predefined accuracy:

> Digits=150;
150
> evalf(1/7);
0.1428571428571428571428571428571428571428571428571428571428571428571428

There is no equivalent setting in swiginac (yet).

The return value of evalf() is still a numeric value:

>>> type(numeric('1/7').evalf())
<class 'swiginac.numeric'>

You can convert it to a Python datatype by the usual Python means or using the to_double(), to_int(), or to_long() methods:

>>> type(numeric('1/7').to_double())
<type 'float'>

Exact numbers that can be manipulated in GiNaC include predefined constants like Archimedes' Pi. They can both be used in symbolic manipulations (as an exact number) as well as in numeric expressions (as an inexact number):

>>> x = symbol('x')
>>> a = Pi**2 + x
>>> a
x+Pi**2
>>> a.evalf()
9.869604401089358619+x
>>> a.subs(x == 2).evalf()
11.869604401089358619

Note

In the last example, the subs() method is used, as changing the value of x will not propagate to the already defined expression a:

>>> x = 2
>>> a.evalf()
9.869604401089358619+x

Built-in functions evaluate immediately to exact numbers if this is possible. Conversions that can be safely performed are done immediately; conversions that are not generally valid are not done:

>>> x = symbol('x')
>>> cos(42*Pi)
1
>>> cos(acos(x))
x
>>> acos(cos(x));
acos(cos(x))

(Note that converting the last input to x would allow one to conclude that 42*Pi is equal to 0.)

2.2.3   Linear Algebra

Linear equation systems can be solved along with basic linear algebra manipulations over symbolic expressions. swiginac offers a matrix class for this purpose:

>>> x = symbol('x'); y = symbol('y'); z = symbol('z')
>>> a = symbol('a'); b = symbol('b'); l = symbol('l')
>>> lsolve(a+x*y==z,x)
(z-a)*y**(-1)
>>> lsolve([3*x+5*y == 7, -2*x+10*y == -5], [x, y])
[x==19/8, y==-1/40]
>>> M = matrix([[1, 3], [-3, 2]])
>>> determinant(M);
11
>>> charpoly(M,l)
11+l**2-3*l
>>> A = matrix([[1, 1], [2, -1]])
>>> A + 2*M
[[3,7],[-4,3]]
>>> B = matrix([[0, 0, a], [b, 1, -b], [-1/a, 0, 0]])
>>> evalm(B**(2**12))
[[1,0,0],[0,1,0],[0,0,1]]

Multivariate polynomials and rational functions may be expanded, collected and normalized (i.e. converted to a ratio of two coprime polynomials):

>>> a = x**4 + 2*x**2*y**2 + 4*x**3*y + 12*x*y**3 - 3*y**4
>>> b = x**2 + 4*x*y - y**2
>>> expand(a*b)
43*y**4*x**2+3*y**6-24*y**5*x+17*y**2*x**4+8*y*x**5+x**6+16*y**3*x**3
>>> collect(a+b,x)
-3*y**4+x*(4*y+12*y**3)+(1+2*y**2)*x**2+4*y*x**3+x**4-y**2
>>> collect(a+b,y)
-3*y**4+x**2+(4*x**3+4*x)*y+12*y**3*x+x**4+y**2*(-1+2*x**2)
>>> normal(a/b)
x**2+3*y**2

2.2.4   Calculus

You can differentiate functions and expand them as Taylor or Laurent series in a very natural syntax (the second argument of series is a relation defining the evaluation point, the third specifies the order):

>>> diff(tan(x),x)
1+tan(x)**2
>>> series(sin(x),x==0,4)
1*x+(-1/6)*x**3+Order(x**4)
>>> series(1/tan(x),x==0,2)
1*x**(-1)+(-1/3)*x+Order(x**2)
>>> series(tgamma(x),x==0,2)
1*x**(-1)+(-Euler)+(1/12*Pi**2+1/2*Euler**2)*x+Order(x**2)
>>> series(tgamma(x),x==0,2).evalf()
1.0*x**(-1)+(-0.5772156649015328606)+0.9890559953279725555*x+Order(x**2)
>>> series(tgamma(2*sin(x)-2),x==Pi/2,3)
(-1)*(x-1/2*Pi)**(-2)+(-1/12-Euler)+(-1/240-1/12*Pi**2-1/2*Euler**2)*(x-1/2*Pi)**2+Order((x-1/2*Pi)**3)

Often, functions don't have roots in closed form. Nevertheless, it's quite easy to compute a solution numerically:

>>> fsolve(cos(x)==x,x,0,2)
0.73908513321516064166
>>> f=exp(sin(x))-x
>>> X=fsolve(f,x,-10,10)
>>> X
2.2191071489137460327
>>> subs(f,x==X)
-2.168404344971008868E-19

Notice how the final result above differs slightly from zero by about 2*10^(-19). This is because with 20 decimal digits precision the root cannot be represented more accurately than X. Such inaccuracies are to be expected when computing with finite floating point values.

Symbolic types can always be used as tags for different types of objects. Converting from "wrong" units to the metric system is an example:

>>> m = symbol('m'); kg = symbol('kg')
>>> inch = .0254*m
>>> lb = .45359237*kg
>>> 200*lb/inch**2
(140613.91592783187407)*m**(-2)*kg

However, as generic symbols do not know about special properties of physical units, it can not simplify all expressions with unit symbols:

>>> print abs(-3), abs(-3*m)
3 abs(-3*m)

(We know, that m is positiv definit, but GiNaC does not.)

The Scientific.Physics.PhysicalQuantities module from the Scientific package provides an elaborated environment specifically designed for working with units. Unfortunately, it does not collaborate well with swiginac.

3   Installation

3.1   GiNaC

GiNaC sources can be fetched from its home site under the section Download GiNaC now which also says:

Since GiNaC is packaged by a couple of software distributors, you may want to try a conveniently packaged binary first (but please don't send us bug-reports about these packages since they may be outdated). We are currently aware of packages in Debian, SuSE, Mandrake, Fedora, and FreeBSD.

The installation is covered in the GiNaC tutorial (and in the INSTALL file of the tarball).

3.2   swiginac

swiginac is a Python interface to GiNaC, built with SWIG. The aim of swiginac is to make the functionality of GiNaC accessible from Python as an extension module.

Current status is beta; a lot (but not all yet) of the GiNaC classes are exposed, virtually all of the GiNaC tests pass.

For more information, documentation and software downloads, visit the swiginac group pages on BerliOS.

The source tarballs contain installation instructions in an INSTALL.txt file.

4   About this Document

The source of this tutorial is written in reStructured Text. To translate it, you need the Python docutils. With docutils installed, the command rst2html swiginac_tutorial.py.txt will produce the html file, while rst2pdf.py swiginac_tutorial.py.txt will produce a PDF version.

The bidirectional text <-> code converter PyLit can be used to transform the tutorial source to a Python module providing the example functions and to run the examples in a doctest. (This is why it has the .py.txt double extension.)

swiginac-1.5.1.1/doc/swiginac_attributes.html0000644000175100017520000013540411000556362021402 0ustar skavhaugskavhaug Objects and attributes defined in the swiginac module

Objects and attributes defined in the swiginac module

Module objects

Object:Value
Catalan                                Catalan
CatalanEvalf                           <function>
EXPAIRSEQ_USE_HASHTAB                  0
Euler                                  Euler
EulerEvalf                             <function>
G                                      <function>
G2                                     <function>
G2_SERIAL                              <class>
G2_SERIAL_swigregister                 <built-in function>
G3                                     <function>
G3_SERIAL                              <class>
G3_SERIAL_swigregister                 <built-in function>
G_basic_basic                          <function>
G_basic_basic_basic                    <function>
G_basic_basic_double                   <function>
G_basic_basic_int                      <function>
G_basic_double                         <function>
G_basic_double_basic                   <function>
G_basic_double_double                  <function>
G_basic_double_int                     <function>
G_basic_int                            <function>
G_basic_int_basic                      <function>
G_basic_int_double                     <function>
G_basic_int_int                        <function>
G_double_basic                         <function>
G_double_basic_basic                   <function>
G_double_basic_double                  <function>
G_double_basic_int                     <function>
G_double_double                        <function>
G_double_double_basic                  <function>
G_double_double_double                 <function>
G_double_double_int                    <function>
G_double_int                           <function>
G_double_int_basic                     <function>
G_double_int_double                    <function>
G_double_int_int                       <function>
G_int_basic                            <function>
G_int_basic_basic                      <function>
G_int_basic_double                     <function>
G_int_basic_int                        <function>
G_int_double                           <function>
G_int_double_basic                     <function>
G_int_double_double                    <function>
G_int_double_int                       <function>
G_int_int                              <function>
G_int_int_basic                        <function>
G_int_int_double                       <function>
G_int_int_int                          <function>
H                                      <function>
H_NPARAMS                              2
H_SERIAL                               <class>
H_SERIAL_swigregister                  <built-in function>
H_basic_basic                          <function>
H_basic_double                         <function>
H_basic_int                            <function>
H_double_basic                         <function>
H_double_double                        <function>
H_double_int                           <function>
H_int_basic                            <function>
H_int_double                           <function>
H_int_int                              <function>
I                                      I
Li                                     <function>
Li2                                    <function>
Li2_NPARAMS                            1
Li2_SERIAL                             <class>
Li2_SERIAL_swigregister                <built-in function>
Li2_basic                              <function>
Li2_double                             <function>
Li2_int                                <function>
Li3                                    <function>
Li3_NPARAMS                            1
Li3_SERIAL                             <class>
Li3_SERIAL_swigregister                <built-in function>
Li3_basic                              <function>
Li3_double                             <function>
Li3_int                                <function>
Li_NPARAMS                             2
Li_SERIAL                              <class>
Li_SERIAL_swigregister                 <built-in function>
Li_basic_basic                         <function>
Li_basic_double                        <function>
Li_basic_int                           <function>
Li_double_basic                        <function>
Li_double_double                       <function>
Li_double_int                          <function>
Li_int_basic                           <function>
Li_int_double                          <function>
Li_int_int                             <function>
Order                                  <function>
Order_NPARAMS                          1
Order_SERIAL                           <class>
Order_SERIAL_swigregister              <built-in function>
Order_basic                            <function>
Order_double                           <function>
Order_int                              <function>
Pi                                     Pi
PiEvalf                                <function>
PySwigIterator                         <class>
PySwigIterator_swigregister            <built-in function>
S                                      <function>
S_NPARAMS                              3
S_SERIAL                               <class>
S_SERIAL_swigregister                  <built-in function>
S_basic_basic_basic                    <function>
S_basic_basic_double                   <function>
S_basic_basic_int                      <function>
S_basic_double_basic                   <function>
S_basic_double_double                  <function>
S_basic_double_int                     <function>
S_basic_int_basic                      <function>
S_basic_int_double                     <function>
S_basic_int_int                        <function>
S_double_basic_basic                   <function>
S_double_basic_double                  <function>
S_double_basic_int                     <function>
S_double_double_basic                  <function>
S_double_double_double                 <function>
S_double_double_int                    <function>
S_double_int_basic                     <function>
S_double_int_double                    <function>
S_double_int_int                       <function>
S_int_basic_basic                      <function>
S_int_basic_double                     <function>
S_int_basic_int                        <function>
S_int_double_basic                     <function>
S_int_double_double                    <function>
S_int_double_int                       <function>
S_int_int_basic                        <function>
S_int_int_double                       <function>
S_int_int_int                          <function>
__doc__                                None
__file__                               '.../swiginac.pyc'
__name__                               'swiginac'
_dict                                  {}
_newclass                              1
_object                                <type 'object'>
_swig_getattr                          <function>
_swig_property                         <type 'property'>
_swig_repr                             <function>
_swig_setattr                          <function>
_swig_setattr_nondynamic               <function>
_swiginac                              <module '_swiginac' from '_swiginac.so'>
abs                                    <function>
abs_NPARAMS                            1
abs_SERIAL                             <class>
abs_SERIAL_swigregister                <built-in function>
abs_basic                              <function>
abs_double                             <function>
abs_int                                <function>
acos                                   <function>
acos_NPARAMS                           1
acos_SERIAL                            <class>
acos_SERIAL_swigregister               <built-in function>
acos_basic                             <function>
acos_double                            <function>
acos_int                               <function>
acosh                                  <function>
acosh_NPARAMS                          1
acosh_SERIAL                           <class>
acosh_SERIAL_swigregister              <built-in function>
acosh_basic                            <function>
acosh_double                           <function>
acosh_int                              <function>
adaptivesimpson                        <function>
add                                    <class>
add_swigregister                       <built-in function>
antisymmetric2                         <function>
antisymmetric3                         <function>
antisymmetric4                         <function>
antisymmetrize                         <function>
asin                                   <function>
asin_NPARAMS                           1
asin_SERIAL                            <class>
asin_SERIAL_swigregister               <built-in function>
asin_basic                             <function>
asin_double                            <function>
asin_int                               <function>
asinh                                  <function>
asinh_NPARAMS                          1
asinh_SERIAL                           <class>
asinh_SERIAL_swigregister              <built-in function>
asinh_basic                            <function>
asinh_double                           <function>
asinh_int                              <function>
atan                                   <function>
atan2                                  <function>
atan2_NPARAMS                          2
atan2_SERIAL                           <class>
atan2_SERIAL_swigregister              <built-in function>
atan2_basic_basic                      <function>
atan2_basic_double                     <function>
atan2_basic_int                        <function>
atan2_double_basic                     <function>
atan2_double_double                    <function>
atan2_double_int                       <function>
atan2_int_basic                        <function>
atan2_int_double                       <function>
atan2_int_int                          <function>
atan_NPARAMS                           1
atan_SERIAL                            <class>
atan_SERIAL_swigregister               <built-in function>
atan_basic                             <function>
atan_double                            <function>
atan_int                               <function>
atanh                                  <function>
atanh_NPARAMS                          1
atanh_SERIAL                           <class>
atanh_SERIAL_swigregister              <built-in function>
atanh_basic                            <function>
atanh_double                           <function>
atanh_int                              <function>
basic                                  <class>
basic_swigregister                     <built-in function>
beta                                   <function>
beta_NPARAMS                           2
beta_SERIAL                            <class>
beta_SERIAL_swigregister               <built-in function>
beta_basic_basic                       <function>
beta_basic_double                      <function>
beta_basic_int                         <function>
beta_double_basic                      <function>
beta_double_double                     <function>
beta_double_int                        <function>
beta_int_basic                         <function>
beta_int_double                        <function>
beta_int_int                           <function>
binomial                               <function>
binomial_NPARAMS                       2
binomial_SERIAL                        <class>
binomial_SERIAL_swigregister           <built-in function>
binomial_basic_basic                   <function>
binomial_basic_double                  <function>
binomial_basic_int                     <function>
binomial_double_basic                  <function>
binomial_double_double                 <function>
binomial_double_int                    <function>
binomial_int_basic                     <function>
binomial_int_double                    <function>
binomial_int_int                       <function>
canonicalize                           <function>
canonicalize_clifford                  <function>
charpoly                               <function>
clifford                               <class>
clifford_bar                           <function>
clifford_inverse                       <function>
clifford_moebius_map                   <function>
clifford_norm                          <function>
clifford_prime                         <function>
clifford_star                          <function>
clifford_swigregister                  <built-in function>
clifford_to_lst                        <function>
clifford_unit                          <function>
cliffordunit                           <class>
cliffordunit_swigregister              <built-in function>
coeff                                  <function>
collect                                <function>
collect_common_factors                 <function>
color                                  <class>
color_ONE                              <function>
color_T                                <function>
color_d                                <function>
color_f                                <function>
color_h                                <function>
color_swigregister                     <built-in function>
color_trace                            <function>
cols                                   <function>
conjugate                              <function>
conjugate_function                     <function>
conjugate_function_NPARAMS             1
conjugate_function_SERIAL              <class>
conjugate_function_SERIAL_swigregister <built-in function>
conjugate_function_basic               <function>
conjugate_function_double              <function>
conjugate_function_int                 <function>
conjugateepvector                      <function>
constant                               <class>
constant_swigregister                  <built-in function>
cos                                    <function>
cos_NPARAMS                            1
cos_SERIAL                             <class>
cos_SERIAL_swigregister                <built-in function>
cos_basic                              <function>
cos_double                             <function>
cos_int                                <function>
cosh                                   <function>
cosh_NPARAMS                           1
cosh_SERIAL                            <class>
cosh_SERIAL_swigregister               <built-in function>
cosh_basic                             <function>
cosh_double                            <function>
cosh_int                               <function>
count_dummy_indices                    <function>
count_free_indices                     <function>
csgn                                   <function>
csgn_NPARAMS                           1
csgn_SERIAL                            <class>
csgn_SERIAL_swigregister               <built-in function>
csgn_basic                             <function>
csgn_double                            <function>
csgn_int                               <function>
cvar                                   <Swig global variables>
decomp_rational                        <function>
degree                                 <function>
delta_tensor                           <function>
denom                                  <function>
determinant                            <function>
determinant_algo                       <class>
determinant_algo_swigregister          <built-in function>
diag_matrix                            <function>
diff                                   <function>
dirac_ONE                              <function>
dirac_gamma                            <function>
dirac_gamma5                           <function>
dirac_gammaL                           <function>
dirac_gammaR                           <function>
dirac_slash                            <function>
dirac_trace                            <function>
diracgamma                             <class>
diracgamma5                            <class>
diracgamma5_swigregister               <built-in function>
diracgammaL                            <class>
diracgammaL_swigregister               <built-in function>
diracgammaR                            <class>
diracgammaR_swigregister               <built-in function>
diracgamma_swigregister                <built-in function>
diracone                               <class>
diracone_swigregister                  <built-in function>
divide                                 <function>
do_taylor                              <class>
do_taylor_swigregister                 <built-in function>
epsilon_tensor                         <function>
eta                                    <function>
eta_NPARAMS                            2
eta_SERIAL                             <class>
eta_SERIAL_swigregister                <built-in function>
eta_basic_basic                        <function>
eta_basic_double                       <function>
eta_basic_int                          <function>
eta_double_basic                       <function>
eta_double_double                      <function>
eta_double_int                         <function>
eta_int_basic                          <function>
eta_int_double                         <function>
eta_int_int                            <function>
eval                                   <function>
eval_integ                             <function>
evalf                                  <function>
evalm                                  <function>
ex                                     <class>
ex_swigregister                        <built-in function>
exmap                                  <class>
exmap_swigregister                     <built-in function>
exp                                    <function>
exp_NPARAMS                            1
exp_SERIAL                             <class>
exp_SERIAL_swigregister                <built-in function>
exp_basic                              <function>
exp_double                             <function>
exp_int                                <function>
expairseq                              <class>
expairseq_swigregister                 <built-in function>
expand                                 <function>
expand_dummy_sum                       <function>
expand_options                         <class>
expand_options_swigregister            <built-in function>
exvector                               <class>
exvector_swigregister                  <built-in function>
factorial                              <function>
factorial_NPARAMS                      1
factorial_SERIAL                       <class>
factorial_SERIAL_swigregister          <built-in function>
factorial_basic                        <function>
factorial_double                       <function>
factorial_int                          <function>
find                                   <function>
find_dummy_indices                     <function>
find_free_and_dummy                    <function>
find_tinfo_key                         <function>
find_unarch_func                       <function>
fsolve                                 <function>
function                               <class>
function_find_function                 <function>
function_options                       <class>
function_options_swigregister          <built-in function>
function_register_new                  <function>
function_swigregister                  <built-in function>
gcd                                    <function>
get_all_dummy_indices                  <function>
get_symbols                            <function>
has                                    <function>
haswild                                <function>
idx                                    <class>
idx_swigregister                       <built-in function>
indexed                                <class>
indexed_swigregister                   <built-in function>
info_flags                             <class>
info_flags_swigregister                <built-in function>
integral                               <class>
integral_swigregister                  <built-in function>
inverse                                <function>
is_dummy_pair                          <function>
is_terminating                         <function>
lcm                                    <function>
ldegree                                <function>
lgamma                                 <function>
lgamma_NPARAMS                         1
lgamma_SERIAL                          <class>
lgamma_SERIAL_swigregister             <built-in function>
lgamma_basic                           <function>
lgamma_double                          <function>
lgamma_int                             <function>
lhs                                    <function>
log                                    <function>
log_NPARAMS                            1
log_SERIAL                             <class>
log_SERIAL_swigregister                <built-in function>
log_basic                              <function>
log_double                             <function>
log_int                                <function>
lorentz_eps                            <function>
lorentz_g                              <function>
lsolve                                 <function>
lst                                    <class>
lst_swigregister                       <built-in function>
lst_to_clifford                        <function>
lst_to_matrix                          <function>
match                                  <function>
matrix                                 <class>
matrix2                                <function>
matrix_swigregister                    <built-in function>
metric_tensor                          <function>
minimal_dim                            <function>
minkmetric                             <class>
minkmetric_swigregister                <built-in function>
mul                                    <class>
mul_swigregister                       <built-in function>
ncmul                                  <class>
ncmul_swigregister                     <built-in function>
new                                    <module 'new' from '.../new.pyc'>
new_instancemethod                     <type 'instancemethod'>
nops                                   <function>
normal                                 <function>
not_symmetric                          <function>
numer                                  <function>
numer_denom                            <function>
numeric                                <class>, see `numeric attributes`_
numeric_swigregister                   <built-in function>
op                                     <function>
parse_string                           <function>
power                                  <class>
power_swigregister                     <built-in function>
prem                                   <function>
pseries                                <class>
pseries_swigregister                   <built-in function>
psi                                    <function>
psi1                                   <function>
psi1_SERIAL                            <class>
psi1_SERIAL_swigregister               <built-in function>
psi2                                   <function>
psi2_SERIAL                            <class>
psi2_SERIAL_swigregister               <built-in function>
psi_basic                              <function>
psi_basic_basic                        <function>
psi_basic_double                       <function>
psi_basic_int                          <function>
psi_double                             <function>
psi_double_basic                       <function>
psi_double_double                      <function>
psi_double_int                         <function>
psi_int                                <function>
psi_int_basic                          <function>
psi_int_double                         <function>
psi_int_int                            <function>
quo                                    <function>
rank                                   <function>
refcounted                             <class>
refcounted_swigregister                <built-in function>
registered_class_options               <class>
registered_class_options_swigregister  <built-in function>
relational                             <class>
relational_swigregister                <built-in function>
rem                                    <function>
remove_dirac_ONE                       <function>
rename_dummy_indices_uniquely          <function>
resultant                              <function>
rhs                                    <function>
rows                                   <function>
scalar_products                        <class>
scalar_products_swigregister           <built-in function>
series                                 <function>
series_to_poly                         <function>
simplify_indexed                       <function>
sin                                    <function>
sin_NPARAMS                            1
sin_SERIAL                             <class>
sin_SERIAL_swigregister                <built-in function>
sin_basic                              <function>
sin_double                             <function>
sin_int                                <function>
sinh                                   <function>
sinh_NPARAMS                           1
sinh_SERIAL                            <class>
sinh_SERIAL_swigregister               <built-in function>
sinh_basic                             <function>
sinh_double                            <function>
sinh_int                               <function>
spinidx                                <class>
spinidx_swigregister                   <built-in function>
spinmetric                             <class>
spinmetric_swigregister                <built-in function>
spinor_metric                          <function>
spmapkey                               <class>
spmapkey_swigregister                  <built-in function>
sprem                                  <function>
sqrfree                                <function>
sqrfree_parfrac                        <function>
sqrt                                   <function>
su3d                                   <class>
su3d_swigregister                      <built-in function>
su3f                                   <class>
su3f_swigregister                      <built-in function>
su3one                                 <class>
su3one_swigregister                    <built-in function>
su3t                                   <class>
su3t_swigregister                      <built-in function>
subs                                   <function>
subs_options                           <class>
subs_options_swigregister              <built-in function>
swap                                   <function>
sy_anti                                <function>
sy_cycl                                <function>
sy_none                                <function>
sy_symm                                <function>
symbol                                 <class>
symbol_swigregister                    <built-in function>
symbolic_matrix                        <function>
symmetric2                             <function>
symmetric3                             <function>
symmetric4                             <function>
symmetrize                             <function>
symmetrize_cyclic                      <function>
symmetry                               <class>
symmetry_swigregister                  <built-in function>
tan                                    <function>
tan_NPARAMS                            1
tan_SERIAL                             <class>
tan_SERIAL_swigregister                <built-in function>
tan_basic                              <function>
tan_double                             <function>
tan_int                                <function>
tanh                                   <function>
tanh_NPARAMS                           1
tanh_SERIAL                            <class>
tanh_SERIAL_swigregister               <built-in function>
tanh_basic                             <function>
tanh_double                            <function>
tanh_int                               <function>
tensdelta                              <class>
tensdelta_swigregister                 <built-in function>
tensepsilon                            <class>
tensepsilon_swigregister               <built-in function>
tensmetric                             <class>
tensmetric_swigregister                <built-in function>
tensor                                 <class>
tensor_swigregister                    <built-in function>
tgamma                                 <function>
tgamma_NPARAMS                         1
tgamma_SERIAL                          <class>
tgamma_SERIAL_swigregister             <built-in function>
tgamma_basic                           <function>
tgamma_double                          <function>
tgamma_int                             <function>
to_polynomial                          <function>
to_rational                            <function>
toex                                   <function>
trace                                  <function>
transpose                              <function>
unit_matrix                            <function>
varidx                                 <class>
varidx_swigregister                    <built-in function>
wild                                   <function>
wildcard                               <class>
wildcard_swigregister                  <built-in function>
zeta                                   <function>
zeta1                                  <function>
zeta1_SERIAL                           <class>
zeta1_SERIAL_swigregister              <built-in function>
zeta2                                  <function>
zeta2_SERIAL                           <class>
zeta2_SERIAL_swigregister              <built-in function>
zeta_basic                             <function>
zeta_basic_basic                       <function>
zeta_basic_double                      <function>
zeta_basic_int                         <function>
zeta_double                            <function>
zeta_double_basic                      <function>
zeta_double_double                     <function>
zeta_double_int                        <function>
zeta_int                               <function>
zeta_int_basic                         <function>
zeta_int_double                        <function>
zeta_int_int                           <function>
zetaderiv                              <function>
zetaderiv_NPARAMS                      2
zetaderiv_SERIAL                       <class>
zetaderiv_SERIAL_swigregister          <built-in function>
zetaderiv_basic_basic                  <function>
zetaderiv_basic_double                 <function>
zetaderiv_basic_int                    <function>
zetaderiv_double_basic                 <function>
zetaderiv_double_double                <function>
zetaderiv_double_int                   <function>
zetaderiv_int_basic                    <function>
zetaderiv_int_double                   <function>
zetaderiv_int_int                      <function>

Class attributes

numeric

__add__
__class__
__copy__
__del__
__delattr__
__dict__
__div__
__doc__
__eq__
__float__
__ge__
__getattr__
__getattribute__
__gt__
__hash__
__init__
__int__
__le__
__lt__
__module__
__mul__
__ne__
__neg__
__new__
__nonzero__
__pos__
__pow__
__radd__
__rdiv__
__reduce__
__reduce_ex__
__repr__
__rmul__
__rpow__
__rsub__
__setattr__
__str__
__sub__
__swig_destroy__
__swig_getmethods__
__swig_setmethods__
__weakref__
_s
accept
add
add_dyn
add_indexed
add_reference
clearflag
coeff
collect
compare
conjugate
content
contract_with
copy
csgn
dbgprint
dbgprinttree
degree
denom
diff
div
div_dyn
duplicate
eval
eval_indexed
evalf
evalm
expand
get_free_indices
get_refcount
gethash
has
hold
imag
info
int_length
integer_content
inverse
is_cinteger
is_crational
is_equal
is_even
is_integer
is_negative
is_nonneg_integer
is_odd
is_pos_integer
is_positive
is_prime
is_rational
is_real
is_zero
ldegree
let_op
map
match
max_coefficient
mul
mul_dyn
nops
normal
numer
op
power
power_dyn
precedence
primpart
print_dispatch
printc
printlatex
printpython
real
remove_reference
return_type
return_type_tinfo
scalar_mul_indexed
series
set_print_context
set_refcount
setflag
simplify_indexed
smod
sub
sub_dyn
subs
subs_one_level
this
tinfo
to_cl_N
to_double
to_int
to_long
to_polynomial
to_rational
toex
unit

symbol

__add__
__class__
__copy__
__del__
__delattr__
__dict__
__div__
__doc__
__eq__
__ge__
__getattr__
__getattribute__
__gt__
__hash__
__init__
__le__
__lt__
__module__
__mul__
__ne__
__neg__
__new__
__nonzero__
__pos__
__pow__
__radd__
__rdiv__
__reduce__
__reduce_ex__
__repr__
__rmul__
__rpow__
__rsub__
__setattr__
__str__
__sub__
__swig_destroy__
__swig_getmethods__
__swig_setmethods__
__weakref__
_s
accept
add_indexed
add_reference
clearflag
coeff
collect
compare
conjugate
content
contract_with
copy
dbgprint
dbgprinttree
degree
denom
diff
duplicate
eval
eval_indexed
evalf
evalm
expand
get_free_indices
get_refcount
gethash
has
hold
info
integer_content
is_equal
is_zero
ldegree
let_op
map
match
max_coefficient
nops
normal
op
precedence
primpart
print_dispatch
printc
printlatex
printpython
remove_reference
return_type
return_type_tinfo
scalar_mul_indexed
series
set_print_context
set_refcount
setflag
simplify_indexed
smod
subs
subs_one_level
this
tinfo
to_polynomial
to_rational
toex
unit

ex

__class__
__del__
__delattr__
__dict__
__doc__
__getattr__
__getattribute__
__hash__
__init__
__module__
__new__
__reduce__
__reduce_ex__
__repr__
__setattr__
__str__
__swig_destroy__
__swig_getmethods__
__swig_setmethods__
__weakref__
eval
this'

add

__add__
__class__
__copy__
__del__
__delattr__
__dict__
__div__
__doc__
__eq__
__ge__
__getattr__
__getattribute__
__gt__
__hash__
__init__
__le__
__lt__
__module__
__mul__
__ne__
__neg__
__new__
__nonzero__
__pos__
__pow__
__radd__
__rdiv__
__reduce__
__reduce_ex__
__repr__
__rmul__
__rpow__
__rsub__
__setattr__
__str__
__sub__
__swig_destroy__
__swig_getmethods__
__swig_setmethods__
__weakref__
_s
accept
add_indexed
add_reference
clearflag
coeff
collect
compare
conjugate
content
contract_with
copy
dbgprint
dbgprinttree
degree
denom
diff
duplicate
eval
eval_indexed
evalf
evalm
expand
get_free_indices
get_refcount
gethash
has
hold
info
integer_content
is_equal
is_zero
ldegree
let_op
map
match
max_coefficient
nops
normal
op
precedence
primpart
print_dispatch
printc
printlatex
printpython
remove_reference
return_type
return_type_tinfo
scalar_mul_indexed
series
set_print_context
set_refcount
setflag
simplify_indexed
smod
subs
subs_one_level
this
tinfo
to_polynomial
to_rational
toex
unit

mul

__add__
__class__
__copy__
__del__
__delattr__
__dict__
__div__
__doc__
__eq__
__ge__
__getattr__
__getattribute__
__gt__
__hash__
__init__
__le__
__lt__
__module__
__mul__
__ne__
__neg__
__new__
__nonzero__
__pos__
__pow__
__radd__
__rdiv__
__reduce__
__reduce_ex__
__repr__
__rmul__
__rpow__
__rsub__
__setattr__
__str__
__sub__
__swig_destroy__
__swig_getmethods__
__swig_setmethods__
__weakref__
_s
accept
add_indexed
add_reference
algebraic_subs_mul
clearflag
coeff
collect
compare
conjugate
content
contract_with
copy
dbgprint
dbgprinttree
degree
denom
diff
duplicate
eval
eval_indexed
evalf
evalm
expand
get_free_indices
get_refcount
gethash
has
hold
info
integer_content
is_equal
is_zero
ldegree
let_op
map
match
max_coefficient
nops
normal
op
precedence
primpart
print_dispatch
printc
printlatex
printpython
remove_reference
return_type
return_type_tinfo
scalar_mul_indexed
series
set_print_context
set_refcount
setflag
simplify_indexed
smod
subs
subs_one_level
this
tinfo
to_polynomial
to_rational
toex
unit

About this document

Created with:

>>> import swiginac
>>> from pprint import pprint
>>> pprint(vars(swiginac))
>>> pprint(dir(swiginac.numeric(1)))
>>> pprint(dir(swiginac.symbol('x')))
>>> pprint(dir(swiginac.ex()))
>>> pprint(dir(swiginac.symbol('x')*2))

and some post processing.

swiginac-1.5.1.1/doc/swiginac_attributes.txt0000644000175100017520000011322610741722607021263 0ustar skavhaugskavhaug.. -*- rst-mode -*- Objects and attributes defined in the swiginac module ===================================================== .. contents:: Module objects -------------- :Object: Value :: Catalan Catalan CatalanEvalf EXPAIRSEQ_USE_HASHTAB 0 Euler Euler EulerEvalf G G2 G2_SERIAL G2_SERIAL_swigregister G3 G3_SERIAL G3_SERIAL_swigregister G_basic_basic G_basic_basic_basic G_basic_basic_double G_basic_basic_int G_basic_double G_basic_double_basic G_basic_double_double G_basic_double_int G_basic_int G_basic_int_basic G_basic_int_double G_basic_int_int G_double_basic G_double_basic_basic G_double_basic_double G_double_basic_int G_double_double G_double_double_basic G_double_double_double G_double_double_int G_double_int G_double_int_basic G_double_int_double G_double_int_int G_int_basic G_int_basic_basic G_int_basic_double G_int_basic_int G_int_double G_int_double_basic G_int_double_double G_int_double_int G_int_int G_int_int_basic G_int_int_double G_int_int_int H H_NPARAMS 2 H_SERIAL H_SERIAL_swigregister H_basic_basic H_basic_double H_basic_int H_double_basic H_double_double H_double_int H_int_basic H_int_double H_int_int I I Li Li2 Li2_NPARAMS 1 Li2_SERIAL Li2_SERIAL_swigregister Li2_basic Li2_double Li2_int Li3 Li3_NPARAMS 1 Li3_SERIAL Li3_SERIAL_swigregister Li3_basic Li3_double Li3_int Li_NPARAMS 2 Li_SERIAL Li_SERIAL_swigregister Li_basic_basic Li_basic_double Li_basic_int Li_double_basic Li_double_double Li_double_int Li_int_basic Li_int_double Li_int_int Order Order_NPARAMS 1 Order_SERIAL Order_SERIAL_swigregister Order_basic Order_double Order_int Pi Pi PiEvalf PySwigIterator PySwigIterator_swigregister S S_NPARAMS 3 S_SERIAL S_SERIAL_swigregister S_basic_basic_basic S_basic_basic_double S_basic_basic_int S_basic_double_basic S_basic_double_double S_basic_double_int S_basic_int_basic S_basic_int_double S_basic_int_int S_double_basic_basic S_double_basic_double S_double_basic_int S_double_double_basic S_double_double_double S_double_double_int S_double_int_basic S_double_int_double S_double_int_int S_int_basic_basic S_int_basic_double S_int_basic_int S_int_double_basic S_int_double_double S_int_double_int S_int_int_basic S_int_int_double S_int_int_int __doc__ None __file__ '.../swiginac.pyc' __name__ 'swiginac' _dict {} _newclass 1 _object _swig_getattr _swig_property _swig_repr _swig_setattr _swig_setattr_nondynamic _swiginac abs abs_NPARAMS 1 abs_SERIAL abs_SERIAL_swigregister abs_basic abs_double abs_int acos acos_NPARAMS 1 acos_SERIAL acos_SERIAL_swigregister acos_basic acos_double acos_int acosh acosh_NPARAMS 1 acosh_SERIAL acosh_SERIAL_swigregister acosh_basic acosh_double acosh_int adaptivesimpson add add_swigregister antisymmetric2 antisymmetric3 antisymmetric4 antisymmetrize asin asin_NPARAMS 1 asin_SERIAL asin_SERIAL_swigregister asin_basic asin_double asin_int asinh asinh_NPARAMS 1 asinh_SERIAL asinh_SERIAL_swigregister asinh_basic asinh_double asinh_int atan atan2 atan2_NPARAMS 2 atan2_SERIAL atan2_SERIAL_swigregister atan2_basic_basic atan2_basic_double atan2_basic_int atan2_double_basic atan2_double_double atan2_double_int atan2_int_basic atan2_int_double atan2_int_int atan_NPARAMS 1 atan_SERIAL atan_SERIAL_swigregister atan_basic atan_double atan_int atanh atanh_NPARAMS 1 atanh_SERIAL atanh_SERIAL_swigregister atanh_basic atanh_double atanh_int basic basic_swigregister beta beta_NPARAMS 2 beta_SERIAL beta_SERIAL_swigregister beta_basic_basic beta_basic_double beta_basic_int beta_double_basic beta_double_double beta_double_int beta_int_basic beta_int_double beta_int_int binomial binomial_NPARAMS 2 binomial_SERIAL binomial_SERIAL_swigregister binomial_basic_basic binomial_basic_double binomial_basic_int binomial_double_basic binomial_double_double binomial_double_int binomial_int_basic binomial_int_double binomial_int_int canonicalize canonicalize_clifford charpoly clifford clifford_bar clifford_inverse clifford_moebius_map clifford_norm clifford_prime clifford_star clifford_swigregister clifford_to_lst clifford_unit cliffordunit cliffordunit_swigregister coeff collect collect_common_factors color color_ONE color_T color_d color_f color_h color_swigregister color_trace cols conjugate conjugate_function conjugate_function_NPARAMS 1 conjugate_function_SERIAL conjugate_function_SERIAL_swigregister conjugate_function_basic conjugate_function_double conjugate_function_int conjugateepvector constant constant_swigregister cos cos_NPARAMS 1 cos_SERIAL cos_SERIAL_swigregister cos_basic cos_double cos_int cosh cosh_NPARAMS 1 cosh_SERIAL cosh_SERIAL_swigregister cosh_basic cosh_double cosh_int count_dummy_indices count_free_indices csgn csgn_NPARAMS 1 csgn_SERIAL csgn_SERIAL_swigregister csgn_basic csgn_double csgn_int cvar decomp_rational degree delta_tensor denom determinant determinant_algo determinant_algo_swigregister diag_matrix diff dirac_ONE dirac_gamma dirac_gamma5 dirac_gammaL dirac_gammaR dirac_slash dirac_trace diracgamma diracgamma5 diracgamma5_swigregister diracgammaL diracgammaL_swigregister diracgammaR diracgammaR_swigregister diracgamma_swigregister diracone diracone_swigregister divide do_taylor do_taylor_swigregister epsilon_tensor eta eta_NPARAMS 2 eta_SERIAL eta_SERIAL_swigregister eta_basic_basic eta_basic_double eta_basic_int eta_double_basic eta_double_double eta_double_int eta_int_basic eta_int_double eta_int_int eval eval_integ evalf evalm ex ex_swigregister exmap exmap_swigregister exp exp_NPARAMS 1 exp_SERIAL exp_SERIAL_swigregister exp_basic exp_double exp_int expairseq expairseq_swigregister expand expand_dummy_sum expand_options expand_options_swigregister exvector exvector_swigregister factorial factorial_NPARAMS 1 factorial_SERIAL factorial_SERIAL_swigregister factorial_basic factorial_double factorial_int find find_dummy_indices find_free_and_dummy find_tinfo_key find_unarch_func fsolve function function_find_function function_options function_options_swigregister function_register_new function_swigregister gcd get_all_dummy_indices get_symbols has haswild idx idx_swigregister indexed indexed_swigregister info_flags info_flags_swigregister integral integral_swigregister inverse is_dummy_pair is_terminating lcm ldegree lgamma lgamma_NPARAMS 1 lgamma_SERIAL lgamma_SERIAL_swigregister lgamma_basic lgamma_double lgamma_int lhs log log_NPARAMS 1 log_SERIAL log_SERIAL_swigregister log_basic log_double log_int lorentz_eps lorentz_g lsolve lst lst_swigregister lst_to_clifford lst_to_matrix match matrix matrix2 matrix_swigregister metric_tensor minimal_dim minkmetric minkmetric_swigregister mul mul_swigregister ncmul ncmul_swigregister new new_instancemethod nops normal not_symmetric numer numer_denom numeric , see `numeric attributes`_ numeric_swigregister op parse_string power power_swigregister prem pseries pseries_swigregister psi psi1 psi1_SERIAL psi1_SERIAL_swigregister psi2 psi2_SERIAL psi2_SERIAL_swigregister psi_basic psi_basic_basic psi_basic_double psi_basic_int psi_double psi_double_basic psi_double_double psi_double_int psi_int psi_int_basic psi_int_double psi_int_int quo rank refcounted refcounted_swigregister registered_class_options registered_class_options_swigregister relational relational_swigregister rem remove_dirac_ONE rename_dummy_indices_uniquely resultant rhs rows scalar_products scalar_products_swigregister series series_to_poly simplify_indexed sin sin_NPARAMS 1 sin_SERIAL sin_SERIAL_swigregister sin_basic sin_double sin_int sinh sinh_NPARAMS 1 sinh_SERIAL sinh_SERIAL_swigregister sinh_basic sinh_double sinh_int spinidx spinidx_swigregister spinmetric spinmetric_swigregister spinor_metric spmapkey spmapkey_swigregister sprem sqrfree sqrfree_parfrac sqrt su3d su3d_swigregister su3f su3f_swigregister su3one su3one_swigregister su3t su3t_swigregister subs subs_options subs_options_swigregister swap sy_anti sy_cycl sy_none sy_symm symbol symbol_swigregister symbolic_matrix symmetric2 symmetric3 symmetric4 symmetrize symmetrize_cyclic symmetry symmetry_swigregister tan tan_NPARAMS 1 tan_SERIAL tan_SERIAL_swigregister tan_basic tan_double tan_int tanh tanh_NPARAMS 1 tanh_SERIAL tanh_SERIAL_swigregister tanh_basic tanh_double tanh_int tensdelta tensdelta_swigregister tensepsilon tensepsilon_swigregister tensmetric tensmetric_swigregister tensor tensor_swigregister tgamma tgamma_NPARAMS 1 tgamma_SERIAL tgamma_SERIAL_swigregister tgamma_basic tgamma_double tgamma_int to_polynomial to_rational toex trace transpose unit_matrix varidx varidx_swigregister wild wildcard wildcard_swigregister zeta zeta1 zeta1_SERIAL zeta1_SERIAL_swigregister zeta2 zeta2_SERIAL zeta2_SERIAL_swigregister zeta_basic zeta_basic_basic zeta_basic_double zeta_basic_int zeta_double zeta_double_basic zeta_double_double zeta_double_int zeta_int zeta_int_basic zeta_int_double zeta_int_int zetaderiv zetaderiv_NPARAMS 2 zetaderiv_SERIAL zetaderiv_SERIAL_swigregister zetaderiv_basic_basic zetaderiv_basic_double zetaderiv_basic_int zetaderiv_double_basic zetaderiv_double_double zetaderiv_double_int zetaderiv_int_basic zetaderiv_int_double zetaderiv_int_int Class attributes ---------------- numeric ~~~~~~~ :: __add__ __class__ __copy__ __del__ __delattr__ __dict__ __div__ __doc__ __eq__ __float__ __ge__ __getattr__ __getattribute__ __gt__ __hash__ __init__ __int__ __le__ __lt__ __module__ __mul__ __ne__ __neg__ __new__ __nonzero__ __pos__ __pow__ __radd__ __rdiv__ __reduce__ __reduce_ex__ __repr__ __rmul__ __rpow__ __rsub__ __setattr__ __str__ __sub__ __swig_destroy__ __swig_getmethods__ __swig_setmethods__ __weakref__ _s accept add add_dyn add_indexed add_reference clearflag coeff collect compare conjugate content contract_with copy csgn dbgprint dbgprinttree degree denom diff div div_dyn duplicate eval eval_indexed evalf evalm expand get_free_indices get_refcount gethash has hold imag info int_length integer_content inverse is_cinteger is_crational is_equal is_even is_integer is_negative is_nonneg_integer is_odd is_pos_integer is_positive is_prime is_rational is_real is_zero ldegree let_op map match max_coefficient mul mul_dyn nops normal numer op power power_dyn precedence primpart print_dispatch printc printlatex printpython real remove_reference return_type return_type_tinfo scalar_mul_indexed series set_print_context set_refcount setflag simplify_indexed smod sub sub_dyn subs subs_one_level this tinfo to_cl_N to_double to_int to_long to_polynomial to_rational toex unit symbol ~~~~~~ :: __add__ __class__ __copy__ __del__ __delattr__ __dict__ __div__ __doc__ __eq__ __ge__ __getattr__ __getattribute__ __gt__ __hash__ __init__ __le__ __lt__ __module__ __mul__ __ne__ __neg__ __new__ __nonzero__ __pos__ __pow__ __radd__ __rdiv__ __reduce__ __reduce_ex__ __repr__ __rmul__ __rpow__ __rsub__ __setattr__ __str__ __sub__ __swig_destroy__ __swig_getmethods__ __swig_setmethods__ __weakref__ _s accept add_indexed add_reference clearflag coeff collect compare conjugate content contract_with copy dbgprint dbgprinttree degree denom diff duplicate eval eval_indexed evalf evalm expand get_free_indices get_refcount gethash has hold info integer_content is_equal is_zero ldegree let_op map match max_coefficient nops normal op precedence primpart print_dispatch printc printlatex printpython remove_reference return_type return_type_tinfo scalar_mul_indexed series set_print_context set_refcount setflag simplify_indexed smod subs subs_one_level this tinfo to_polynomial to_rational toex unit ex ~~~~~~~~~~~~~ :: __class__ __del__ __delattr__ __dict__ __doc__ __getattr__ __getattribute__ __hash__ __init__ __module__ __new__ __reduce__ __reduce_ex__ __repr__ __setattr__ __str__ __swig_destroy__ __swig_getmethods__ __swig_setmethods__ __weakref__ eval this' add ~~~~~~~~~~~~~~ :: __add__ __class__ __copy__ __del__ __delattr__ __dict__ __div__ __doc__ __eq__ __ge__ __getattr__ __getattribute__ __gt__ __hash__ __init__ __le__ __lt__ __module__ __mul__ __ne__ __neg__ __new__ __nonzero__ __pos__ __pow__ __radd__ __rdiv__ __reduce__ __reduce_ex__ __repr__ __rmul__ __rpow__ __rsub__ __setattr__ __str__ __sub__ __swig_destroy__ __swig_getmethods__ __swig_setmethods__ __weakref__ _s accept add_indexed add_reference clearflag coeff collect compare conjugate content contract_with copy dbgprint dbgprinttree degree denom diff duplicate eval eval_indexed evalf evalm expand get_free_indices get_refcount gethash has hold info integer_content is_equal is_zero ldegree let_op map match max_coefficient nops normal op precedence primpart print_dispatch printc printlatex printpython remove_reference return_type return_type_tinfo scalar_mul_indexed series set_print_context set_refcount setflag simplify_indexed smod subs subs_one_level this tinfo to_polynomial to_rational toex unit mul ~~~ :: __add__ __class__ __copy__ __del__ __delattr__ __dict__ __div__ __doc__ __eq__ __ge__ __getattr__ __getattribute__ __gt__ __hash__ __init__ __le__ __lt__ __module__ __mul__ __ne__ __neg__ __new__ __nonzero__ __pos__ __pow__ __radd__ __rdiv__ __reduce__ __reduce_ex__ __repr__ __rmul__ __rpow__ __rsub__ __setattr__ __str__ __sub__ __swig_destroy__ __swig_getmethods__ __swig_setmethods__ __weakref__ _s accept add_indexed add_reference algebraic_subs_mul clearflag coeff collect compare conjugate content contract_with copy dbgprint dbgprinttree degree denom diff duplicate eval eval_indexed evalf evalm expand get_free_indices get_refcount gethash has hold info integer_content is_equal is_zero ldegree let_op map match max_coefficient nops normal op precedence primpart print_dispatch printc printlatex printpython remove_reference return_type return_type_tinfo scalar_mul_indexed series set_print_context set_refcount setflag simplify_indexed smod subs subs_one_level this tinfo to_polynomial to_rational toex unit About this document ------------------- Created with: >>> import swiginac >>> from pprint import pprint >>> pprint(vars(swiginac)) >>> pprint(dir(swiginac.numeric(1))) >>> pprint(dir(swiginac.symbol('x'))) >>> pprint(dir(swiginac.ex())) >>> pprint(dir(swiginac.symbol('x')*2)) and some post processing. swiginac-1.5.1.1/doc/swiginac_basics.py0000644000175100017520000003503611000603564020141 0ustar skavhaugskavhaug# ****************************************** # SwiGiNaC: Symbolic Computation with Python # ****************************************** # # Basic Examples # ************** # # .. sectnum:: # # Contents_ # # Import # ====== # # This script will give a basic overview of what is possible combining # symbolic computation by `GiNac` with the flexibility and richness of Python # # To load swiginac, use one of the ``import`` variants:: import swiginac from swiginac import * # Objects defined in this tutorial can be imported with # # >>> from swiginac_basics import * # # The swiginac module wraps functions, data and classes defined in the ginac # C++ library in a python module. There are more than 600 objects # # >>> len(dir(swiginac)) # 661 # # but only the most basic will be described in this tutorial. # # Completing the swiginac functions and classes with docstrings is an # open task. Some introspection is possible with e.g. :: # # from pprint import pprint # # pprint(dir(swiginac)) # # pprint(vars(swiginac)) # # # Objects # ======= # # Symbols # ------- # # A symbolic indeterminante or symbolic *variable* is a placeholder for a value # in an expression. # # Symbols are basic units in Swiginac: # # >>> a = symbol('a') # >>> a # a # # The datatype is: # # >>> type(a) # # # It defines two methods but inherits more than 100 others: # # >>> len(dir(a)) # 108 # # If you want to list them all, try ``pprint(dir(a))`` # # In most Computer Algebra Systems (CAS), any unbound variable can be used as # a symbol. In Python, you must define a variable as symbol before you can use # it in expressions. # # >>> del(x) # >>> y = 3*x # Traceback (most recent call last): # File "", line 1, in ? # NameError: name 'x' is not defined # # >>> x = symbol('x') # >>> y = 3*x # # `y` is now an expression: # # >>> y # 3*x # # In order to re-use `y` as a symbol, an ordinary CAS would require you # to *delete* it. In Python, you overwrite its current binding with a new # assignment to a `symbol` instance: # # >>> y = symbol('y') # >>> y # y # # Defining a set of symbols # ~~~~~~~~~~~~~~~~~~~~~~~~~ # # If we initialize a set of symbols, we might want to use a loop rather than a # lot of lines with individual assignments. # # We can use the feature that the dictionary returned by the built-in function # `globals` can be manipulated # # >>> for name in ['gamma', 'delta', 'epsilon']: # ... globals()[name] = swiginac.symbol(name) # # To define the small latin letters a-z as symbols in this module, :: import string as _string for name in _string.lowercase: globals()[name] = swiginac.symbol(name) # Which results in # # >>> print type(delta), type(x) # # # # Numbers # ------- # # The ``numeric`` class can manipulate arbitrary precision integers in a very # fast way. # # Rational numbers are automatically converted to fractions of coprime # integers. # # >>> numeric('4/12') # 1/3 # # The expression given to `numeric` is evaluated using Pythons "standard" # arithmetic, which is probabely not what we want when specifying rational # numbers: # # >>> numeric(1/3) # 0 # >>> numeric(1./3) # 0.33333333333333331483 # # To prevent evaluation the "normal" Python way, rational numbers can # be input as string value or as (numerator, denominator) tuple: # # >>> numeric("1/3") # 1/3 # >>> numeric(1, 3) # 1/3 # # Often, it is sufficient to specify one number in an expression as `numeric`: # # >>> numeric(1)/3 # 1/3 # # Converting numbers # ~~~~~~~~~~~~~~~~~~ # # The `evalf` method converts any number in GiNaC's expressions # into floating point numbers: # # >>> numeric('1/7').evalf() # 0.14285714285714285714 # # The return value of `evalf` is still a `numeric` value: # # >>> type(numeric('1/7').evalf()) # # # You can convert it to a Python datatype using the `to_double`, `to_int`, or # `to_long` methods: # # >>> type(numeric('1/7').to_double()) # # # There are other converting methods, like `numeric.evalm` or `numeric.to_cl_N` # but what do they do? # # # Complex Numbers # ~~~~~~~~~~~~~~~ # # Complex numbers are expressad with the imaginary unit `I` # # >>> I, I**2, 2+3*I # (I, -1, 2+3*I) # # However, they are numbers (even if they look like a symbol, sum, or product): # # >>> type(I), type(2 + 3*I) # (, ) # # Python's `complex` numbers can currently not be converted to `numeric` # objects: # # >>> z_gi = numeric(2+3j) # Traceback (most recent call last): # ... # NotImplementedError: Wrong number of arguments for overloaded function 'new_numeric'. # Possible C/C++ prototypes are: # GiNaC::numeric(int) # GiNaC::numeric(unsigned int) # GiNaC::numeric(long) # GiNaC::numeric(unsigned long) # GiNaC::numeric(long,long) # GiNaC::numeric(double) # GiNaC::numeric(char const *) # GiNaC::numeric(cln::cl_N const &) # # # # A workaround is to use an expression:: z_py = 2+3j z_gi = z_py.real + z_py.imag*I # which will be simplified to a number: # # >>> print z_gi, type(z_gi) # 2.0+3.0*I # # How do complex expression evaluate? # # `evalf` converts real and imaginary part to floating point numbers # # >>> z_gi.evalf() # 2.0+3.0*I # # `to_double()` returns the real part as `double` instance # # >>> z_gi.to_double() # 2.0 # # While Phyton's `complex` class stores real and imaginary part as attributes, # `numeric` provides methods to retrieve them (as `numeric` instances): # # >>> z_py.real, z_gi.real # (2.0, ) # # >>> z_gi.real(), z_gi.imag() # (2.0, 3.0) # # Constants # --------- # # Some mathematical constants are available as well # # >>> print Pi, type(Pi), Pi.evalf() # Pi 3.1415926535897932385 # >>> print Euler, type(Euler), Euler.evalf() # Euler 0.5772156649015328606 # # Swiginac functions_ know some simplifications for special values # # >>> print sin(Pi), cos(Pi) # 0 -1 # # Expressions # ----------- # # Expressions in GiNaC are built with symbols and numbers. # # They are converted to a "canonical" representation and have a class that # depends on the expression:: ex1 = a/2 + b ex2 = (a+b)/2 ex3 = (a+b)/c # >>> print ex1, type(ex1) # 1/2*a+b # >>> print ex2, type(ex2) # 1/2*a+1/2*b # >>> print ex3, type(ex3) # (a+b)*c**(-1) # # In the `Symbolic` package, there is the common class `Symbolic.Expr` with # some additional methods. # # # Functions # --------- # # About 40 mathematical functions are available in `swiginac`. All # trigonometric and hyperbolic functions are implemented. For a full list of # available functions see the file `doc/examples/functions.py`. # # Some functions are simplified if this is mathemetically sound and # non-ambiguous. # # >>> sin(x), sin(0), sin(Pi/2) # (sin(x), 0, 1) # >>> cos(x), cos(0), cos(Pi/2) # (cos(x), 1, 0) # >>> tan(x), tan(0), tan(Pi/2) # Traceback (most recent call last): # ... # StandardError: tan_eval(): simple pole # # But not all simplifications are implemented # # >>> sin(x)**2 + cos(x)**2 # sin(x)**2+cos(x)**2 # # :: z_s = cos(x) + I*sin(x) z_e = exp(I*x) # >>> z_s/z_e # (cos(x)+I*sin(x))*exp(I*x)**(-1) # # Is there a way get more simplifications? # # # Matrices # -------- # # Marices can be defined giving the number of rows and columns:: M1 = matrix(2,2) # Elements will be initialized with 0 and can be set individually:: M1[0,0] = x M1[1,1] = y # >>> M1 # [[x,0],[0,y]] # >>> M1.printc() # '[[x,0.0],[0.0,y]]' # >>> M1.printlatex() # '\\left(\\begin{array}{cc}x&0\\\\0&y\\end{array}\\right)' # # Alternatively, they can be initialized by a list of lists:: M2 = matrix([[x,0],[0, y]]) # Diagonal matrices can be created with a special constructor:: M3 = diag_matrix([x, y]) # >>> bool(M1 == M2 == M3) # True # # Vectors are (1,n) or (n,1) matrices:: A = matrix([range(4)]) B = matrix([[a], [b], [c]]) C = matrix([[0], [1], [2]]) # But why is the matrix product not working? # # >>> print A*B # [[0,1,2,3]]*[[a],[b],[c]] # >>> C = matrix([[0], [1], [2]]) # >>> print A*C # [[0,1,2,3]]*[[0],[1],[2]] # # Functions are not broadcast to the matrix elements as in NumPy # # >>> sin(A) # sin([[0,1,2,3]]) # # How about substitution? # # >>> sin(x).subs(x == A) # sin([[0,1,2,3]]) # # Symbolic calculations # ===================== # # Differentiation # --------------- # # Objects have the method `diff` for differentiation which is also called by # the `diff` function: # # >>> P = x**5 + x**2 + x # # # >>> P.diff(x) == diff(P, x) # 1+5*x**4+2*x==1+5*x**4+2*x # # >>> P.diff(x, 2) == diff(P, x, 2) # 2+20*x**3==2+20*x**3 # # >>> diff(sin(exp(x)), x) == sin(exp(x)).diff(x) # cos(exp(x))*exp(x)==cos(exp(x))*exp(x) # # # Simple integral support # ----------------------- # # We can construct integral objects and integrate either symbolically # or numerically:: x = symbol('x') integ = integral(x, 0, 1, x*x) # >>> integ # [integral object] # >>> print integ.printlatex() # \int_{0}^{1} dx\,x^{2} # >>> integ.eval_integ() # 1/3 # >>> integ.evalf() # 0.33333333333333333332 # # # Substitution # ------------ # # Algebraic objects in expressions can be substituted:: s0 = sin(exp(x)) s1 = s0.subs(exp(x)==sqrt(y)) s2 = s1.subs(y==2) # >>> s1 # sin(y**(1/2)) # >>> s2.evalf() # 0.98776594599273552706 # >>> float(s2.evalf()) # 0.98776594599273548 # # It is possible to replace individual symbols or terms. # Several substitutions can be given in a sequence (list or tuple):: s3 = sin(x+y+z) s4 = s3.subs([x==1, y==2]) s5 = s3.subs(x+y+z==6) # >>> print s4 # sin(3+z) # >>> print s5 # sin(6) # # But sub-expressions do not match:: s6 = s3.subs(x+y==4) # >>> s6 # sin(x+y+z) # # >>> s3.subs(x+y==4) # sin(x+y+z) # # Strange: Some substitutions work in the module but fail the doctest: # # >>> print s3.subs([x==1, y==2]) # sin(3+z) # # Failed example: # print s3.subs([x==1, y==2]) # Expected: # sin(3+z) # Got: # sin(x+y+z) # # >>> print s3.subs([x==1, y==2, z==3]) # sin(6) # # Failed example: # print s3.subs([x==1, y==2, z==3]) # Expected: # sin(6) # Got: # sin(3+x+y) # # >>> s7 = s3.subs([x==1, y==2, z==3]) # >>> s7 # sin(6) # # Failed example: # s7 # Expected: # sin(6) # Got: # sin(3+x+y) # # # Solving linear systems # ---------------------- # # The function `lsolve` solves linear systems:: lgs = [3*x + 5*y == 2, 5*x+y == -3] ev = lsolve(lgs, [x,y]) # >>> ev # [x==-17/22, y==19/22] # >>> lgs[0].subs(ev) # 2==2 # >>> lgs[1].subs(ev) # -3==-3 # # # # Taylor series expansion # ----------------------- # # Expressions can expand themselves as a Taylor series:: x =symbol("x") taylor = sin(x).series(x==0, 8) # >>> taylor # 1*x+(-1/6)*x**3+1/120*x**5+(-1/5040)*x**7+Order(x**8) # # # # # Output Formatting # ================= # # Print styles # ------------ # # Expressions have methods returning string representations in several styles: # # >>> [method for method in dir(ex4) if method.find('print') == 0] # ['print_dispatch', 'printc', 'printlatex', 'printpython'] # # Symbols can be defined with additional TeX string representation # Greek letter names will be converted to commands in Tex output:: a_pix = symbol('a_pix', 'a_\mathrm{pix}') beta = symbol('beta') ex4 = a_pix + beta/2 # >>> ex4.printpython() # '1/2*beta+a_pix' # >>> ex4.printc() # ' beta/2.0+a_pix' # >>> ex4.printlatex() # '\\frac{1}{2} \\beta+a_\\mathrm{pix}' # # A default output style (print context) can be set for an object # # >>> print ex4 # 1/2*beta+a_pix # >>> ex4.set_print_context('tex') # >>> print ex4 # \frac{1}{2} \beta+a_\mathrm{pix} # # Especially for interactive use, it would be nice if this could also be done # on a per-module or per-application scale (as in GiNaC itself). # # # Format the output of numbers # ---------------------------- # # The output format for numbers is sometimes too verbose for practical use, # especially with floats as precision is govened by DIGITS (20): # # # >>> from swiginac import * # >>> x = Pi.evalf() # >>> print x # 3.1415926535897932385 # # Python's built in function `round()` can be used to round any object that # can be converted to a float to a given accuracy. The result is, however, not # always as expected: # # >>> round(x, 4) # 3.1415999999999999 # # This is caused by the internal use of a number base different from 10. # # String formatting # ----------------- # # In Python, you can use string formatting to get a specific notation or # accuracy: # # The '%f' specifier can be used for `swiginac.numeric` instances that are # convertible to floats: # # >>> print "%f, %f, %f" % (x, sin(x), exp(x)) # 3.141593, -0.000000, 23.140693 # # It fails on objects that cannot be converted to floats: # # >>> print "%f" % Pi # Traceback (most recent call last): # ... # TypeError: float argument required # # Save programming would require to e.g. test the datatype with # # >>> x.is_real() # True # # or use a try/catch clause. # # The formatting options are described in the Python documentation on # `string formatting operations`_. # # Here some examples: # # Precision: # # >>> print "%.10f" % x # 3.1415926536 # # ... is limited to DIGITS internally # # >>> print "%.60f" % x # 3.141592653589793115997963468544185161590576171875000000000000 # # Leading sign and zeros: # # >>> print "%+.1f" % x # +3.1 # >>> print "%05.1f" % x # 003.1 # # Scientific notation # # >>> print "%.3E %.2e" % (x, x) # 3.142E+00 3.14e+00 # # >>> print "%g %g" % (x, x**40) # 3.14159 7.69121e+19 # # # .. _string formatting operations: # http://www.python.org/doc/lib/typesseq-strings.html # # # Interaction with Python # ----------------------- # # Series and sums # ~~~~~~~~~~~~~~~ # # A series could be defined as a Python sequence, e.g. # # >>> x = symbol('x') # >>> [x/n for n in range(1, 10)] # [x, 1/2*x, 1/3*x, 1/4*x, 1/5*x, 1/6*x, 1/7*x, 1/8*x, 1/9*x] # # >>> sinc5 = [sin(phi)/phi for phi in range(1,5)]; sinc5 # [sin(1), 1/2*sin(2), 1/3*sin(3), 1/4*sin(4)] # # Attention, the loop indices are now integers # # >>> n, phi # (9, 4) # # so it might be a good idea to use separate conventions for naming symbols and # indices. # # As the standard function sum is overloaded for swiginac classes, it can be # used on sequences of symbols or expressions: # # >>> sum((x, y, z)) # y+x+z # # >>> sum([x/n for n in range(1, 10)]) # 7129/2520*x # # Compute the sum over the list defined earlier in this section: # # >>> sum(sinc5) # 1/2*sin(2)+1/3*sin(3)+sin(1)+1/4*sin(4) # # # .. contents:: # swiginac-1.5.1.1/doc/examples/0000755000175100017520000000000011374770636016271 5ustar skavhaugskavhaugswiginac-1.5.1.1/doc/examples/functions.py0000644000175100017520000000672110740400644020642 0ustar skavhaugskavhaug#!/usr/bin/env python # -*- coding: iso-8859-1 -*- # =============================================================== # functions.py: mathematical functions in swiGiNaC # =============================================================== # # :Date: $Date: 2008-01-07 11:40:36 +0100 (Mon, 07 Jan 2008) $ # :Version: SVN-Revision $Revision: 253 $ # :URL: $URL: svn+ssh://svn.berlios.de/svnroot/repos/pylit/trunk/src/pylit.py $ # :Copyright: 2005, 2007 Guenter Milde. # Released under the terms of the GNU General Public License # (v. 2 or later) from swiginac import * a = symbol("a") k = symbol("k") m = symbol("m") n = symbol("n") p = symbol("p") s = symbol("s") x = symbol("x") y = symbol("y") # GiNaC contains the following predefined mathematical functions: # # Functions that are not mapped to swiginac, are commented out. # Name Function abs(x) # absolute value # step(x) # step function csgn(x) # complex sign conjugate(x) # complex conjugation # real_part(x) # real part # imag_part(x) # imaginary part sqrt(x) # square root (alias for pow(x, numeric(1, 2))) sin(x) # sine cos(x) # cosine tan(x) # tangent asin(x) # inverse sine acos(x) # inverse cosine atan(x) # inverse tangent atan2(y, x) # inverse tangent with two arguments sinh(x) # hyperbolic sine cosh(x) # hyperbolic cosine tanh(x) # hyperbolic tangent asinh(x) # inverse hyperbolic sine acosh(x) # inverse hyperbolic cosine atanh(x) # inverse hyperbolic tangent exp(x) # exponential function log(x) # natural logarithm Li2(x) # dilogarithm Li(m, x) # classical polylogarithm as well as multiple polylogarithm G(a, y) # multiple polylogarithm G(a, s, y) # multiple polylogarithm with explicit signs for the imaginary parts S(n, p, x) # Nielsen's generalized polylogarithm H(m, x) # harmonic polylogarithm zeta(m) # Riemann's zeta function as well as multiple zeta value zeta(m, s) # alternating Euler sum zetaderiv(n, x) # derivatives of Riemann's zeta function tgamma(x) # gamma function lgamma(x) # logarithm of gamma function beta(x, y) # beta function (tgamma(x)*tgamma(y)/tgamma(x+y)) psi(x) # psi (digamma) function psi(n, x) # derivatives of psi function (polygamma functions) factorial(n) # factorial function n! binomial(n, k) # binomial coefficients Order(x) # order term function in truncated power series # For functions that have a branch cut in the complex plane GiNaC follows the conventions for # C++ as defined in the ANSI standard as far as possible. In particular: the natural logarithm # (log) and the square root (sqrt) both have their branch cuts running along the negative real swiginac-1.5.1.1/doc/examples/T0d.py0000644000175100017520000002237311000556614017261 0ustar skavhaugskavhaug#!/usr/bin/env python # -*- coding: latin-1 -*- # :Copyright: 2007 Guenter Milde. # Released under the terms of the GNU General Public License # (v. 2 or later) # thermisch0d_symbolic.py: Kompaktes Modell eines Pyroelements # ============================================================ # mit sybolic computing (swiginac) # -------------------------------- # # Imports # ======= # # Import this module with # # >>> from T0d import * # # Python standard modules and established extensions:: import sys, os from pprint import pprint import Gnuplot # The swiginac module for symbolic algebra with GiNaC:: from swiginac import * # symbolic algebra (CAS) # from Symbolic import * # # and private extensions:: # from gm_tools import sgn # from Sensor_analytisch import * import LyX # Ausgabe # ======= # :: if __name__ == '__main__': output_format = "text" # output_format = "lyx" # output_format = "tex" else: output_format = "" # keine Ausgabe # Load the LyX client and open a new LyX buffer for the output:: if output_format == "lyx": from LyX import lfuns lfuns.buffer_new() def heading(text, level=1, output_format=output_format): """print a heading (TODO: of level `level`) suited for `output_format` """ if output_format == "lyx": lfuns.break_paragraph() lfuns.layout("Section") lfuns.self_insert(text) lfuns.break_paragraph() lfuns.layout("Standard") elif output_format == "tex": print "\n\\section{%s}"%text elif output_format == "text": print "\n" + text print "-" * len(text) def printlatex(obj): try: return obj.printlatex() except AttributeError: return str(obj) def printout(*args): if output_format == "lyx": lfuns.break_paragraph() args = [printlatex(arg) for arg in args] lfuns.math_insert(*args) lfuns.char_forward() elif output_format == "tex": print " ".join([printlatex(arg) for arg in args]) elif output_format == "text": print " ".join([str(arg) for arg in args]) # Real- und Imaginärteil # ====================== # # Die Funktionen zur Bestimmung von Real- und Imaginärteil sind (noch) nicht # von Python aus zugänglich. Für viele Objecte existieren entsprechende # Methoden. :: def real(z): """z = real(z) + I * imag(z)""" try: return z.real() except AttributeError: return (z + conjugate(z))/2 def imag(z): """z = real(z) + I * imag(z)""" try: return z.imag() except AttributeError: return (z - conjugate(z))/(2*I) # >>> conjugate(3+ 2*I) # complex conjugation # 3-2*I # >>> real(3 + 2*I) # 3 # >>> print imag(3 + 2*I), imag(3), imag(2*I) # 2 0 2 # >>> abs(3 + 2*I) # 3.6055512754639892931 # # Noch nicht implementiert ist arg() für das Argument in Euler-Notation # # #>>> arg(3 + 2*I) # #>>> arg(3), arg(3 + 3*I), arg(3*I), arg(-3 + 3*I), arg(-3), arg(-3 + -3*I), arg(-3*I), arg(3 + -3*I) # # # Einheiten # ========= # :: W = symbol("W", "\\textrm{W}") mm = symbol("mm", "\\textrm{mm}") m = 1000*mm mum = mm/1000 s = symbol("s", "\\textrm{s}") K = symbol("K", "\\textrm{K}") kg = symbol("kg", "\\textrm{kg}") J = W*s C = symbol("C", "\\textrm{C}") # Größensymbole # ============= # # Geometrie:: t = symbol('t'); t.unit = s # Zeit l = symbol("l"); l.unit = m # Länge A = symbol("A"); A.unit = m**2 # Fläche, Querschnitt V = symbol("V"); V.unit = m**3 # Volumen # Eingangsstrahlung:: E = symbol("E"); E.unit = W/m**2 # IR-Strahlungsdichte Phi = E*A; Phi.unit = W # Wärmestrom, Strahlungsleistung omega = symbol("omega"); omega.unit = 1/s # Kreisfrequenz # Materialgrößen:: lambda_T = symbol("lambda_T", r"\lambda_T") # Wärmeleitfähighkeit lambda_T.unit = W/(m*K) c_T = symbol("c_T"); c_T.unit = J/(kg*K) # spezifische Wärmekapazität rho = symbol("rho"); rho.unit = kg/m**3 # Dichte cv_T = c_T * rho # volumenspez. Wärmekapazität cv_T.unit = J/(m**3*K) a_T = lambda_T/cv_T # Thermische Diffusionskonstante a_T.unit = lambda_T.unit/cv_T.unit # m²/s p = symbol("p"); p.unit = C/(m**2*K) # pyroelektrischer Koeffizient # >>> print a_T # c_T**(-1)*lambda_T*rho**(-1) # Modell: Chip mit umgebender Luftschicht # ======================================= # :: heading("Modellwerte") # Geometrie # --------- # # Pixel (Sensorelemente):: a_pix = 90 * mum # Pixelbreite [µm]) b_pix = 100 * mum # Pixelhöhe (x-Richtung) [µm] c_pix = 100 * mum # Pitch (y-Richtung) [µm] d_pix = 20 * mum # Dicke (z-Richtung) [µm] # L_y = 1200 * mum # Länge des Modells in y-Richtung A_pix = a_pix * b_pix # Pixelfläche V_pix = A_pix * d_pix # Pixelvolumen # Luftschicht:: d_Luft = symbol("d_Luft") d_Luft.oben = 350 * mum # Luftschicht oben d_Luft.unten = 250 * mum # Luftschicht unten heading("Geometrie") printout("A_\mathrm{pix} = ", A_pix.evalf()) printout("V_\mathrm{pix} =", V_pix.evalf()) # IR-Strahlung # ------------ # :: E_in = 200 * W/m**2 # Strahlungsdichte f_ch = 128 * 1/s # Chopperfrequenz T_ch = 1/f_ch # Chopperperiode (0.0078125 s) omega.ch = 2*Pi*f_ch # Chopperkreisfrequenz Phi_in = E_in * A_pix # unmoduliert Phi_quer = Phi_in/2 # mittlere Strahlungsdichte Phi_0 = Phi_in/2 # Amplitude der Wechselgröße heading("Eingangstrahlung") printout(r"\Phi_\mathrm{in} =", Phi_in.evalf()) printout(r"<\Phi> = \Phi_0 = \Phi_\mathrm{in}/2 =", Phi_0.evalf()) # Materialkonstanten # ------------------ # :: # Wärmeleitfähigkeit lambda_T.Lita = 4.2 * W/(m*K) lambda_T.Luft = 0.026 * W/(m*K) c_T.Lita = 429.53 * J/(kg*K) # spezifische Wärmekapazität rho.Lita = 7450 * kg/m**3 # Dichte p.Lita = -1.7e-4 * C/(m**2*K) # pyroelektrischer Koeffizient # cv_T.Lita = c_T.Lita * rho.Lita # volumenspez. Wärmekapazität 'Ws/m³K' a_T.Lita = lambda_T.Lita/cv_T.Lita # Thermische Diffusionskonstante ,'m²/s') heading("Materialkonstanten") printout("cv_T(\LiTa) =", cv_T.Lita) printout("a_T(\LiTa) =", a_T, "=", a_T.Lita) # Zwischengrößen # ============== # Wärmeleitwert # ------------- # :: G_T = lambda_T * A / l G_T.Luft_oben = G_T.subs([lambda_T == lambda_T.Luft, A == A_pix, l == d_Luft.oben ]) G_T.Luft_unten = G_T.subs([lambda_T == lambda_T.Luft, A == A_pix, l == d_Luft.unten ]) G_T.Luft = G_T.Luft_oben + G_T.Luft_unten heading("Wärmeleitwert") printout("G_T =", G_T) printout("G_T(Luft oben) =", G_T.Luft_oben) printout("G_T(Luft unten) =", G_T.Luft_unten) printout("G_T(Luft) =", G_T.Luft) # Wärmekapazität # -------------- # :: C_T = cv_T * V C_T.pix = V_pix * cv_T.Lita heading("Wärmekapazität") printout("C_T =", C_T) printout("C_T(pix) =", C_T.pix) # Wärmeleitwert der Kapazität G_T.C = I * omega * C_T G_T.C.pix = I * omega * C_T.pix G_T.C.pix.omega_ch = G_T.C.pix.subs(omega == omega.ch.evalf()) heading("kapazitiver Wärmeleitwert") printout("G_T(C) =", G_T.C) printout("G_T(C_{pix}) =", G_T.C.pix) printout("G_T(C_{pix}, \wch) =", G_T.C.pix.omega_ch) # Lösung # ====== # :: heading("Lösungen") # mittlere Temperaturdifferenz # ---------------------------- # :: T_quer = Phi / G_T T_quer.pix = Phi_quer / G_T.Luft heading("mittlere Temperatur") printout("=", T_quer) printout("(pix)=", T_quer.pix) # Temperaturdifferenz bei sinusförmiger Zeitabhängigkeit # ------------------------------------------------------ # :: heading("sinusförmige Zeitabhängigkeit mit omega_ch") heading("Wärmeleitwerte") printout("G_T(Luft) =", G_T.Luft) printout("G_T(C_{pix}) =", G_T.C.pix) G_T.omega = G_T.Luft + G_T.C.pix # Zusammenfassen der Einheiten #G_T.omega = G_T.omega.collect(W).collect(K) G_T.omega.ch = G_T.omega.subs(omega==omega.ch) printout("G^~(\omega) =", G_T.omega) printout("G^~(\omega=\omega_{ch}) =", G_T.omega.ch) T_0 = Phi_0.evalf() / G_T.omega T_0.ch = T_0.subs(omega == omega.ch.evalf()) T_sin = T_0 * exp(I*omega*t) T_sin.ch = T_sin.subs(omega == omega.ch.evalf()) heading("Temperatur") heading("Temperaturamplitude") printout("komplexe Temperatuamplitude") printout("T_0 =", T_0) printout("reelle Temperatuamplitude") printout("|T_0(\omega)| =", abs(T_0.subs([W==1, s==1, K==1]))*K) # abs(K) == K printout("für f_ch = 128 Hz") printout("T_0(\omega_{ch}) =", T_0.ch) printout("|T_0(\omega_{ch})| =", abs(T_0.ch/K)*K) # abs(K) == K heading("Zeitverlauf Sinus") printout("T^~(\omega_{ch}) =", T_sin.ch) printout("|T^~(\omega_{ch})| =", abs(T_sin.ch)) printout("T^~ =", real(T_sin)) printout("T_0 =") printout(T_0.expand()) printout(T_0.collect(K)) printout(T_0.collect(I)) printout(T_0.simplify_indexed()) # printout(type(T_0) # pprint( dir(T_0)) # Plotting # -------- # :: # open a gnuplot session gp = Gnuplot.Gnuplot(persist=True) # gp("set size 0.8,0.5") # gp.xlabel('x [cm]') # gp("set xtics 0.25"); # gp("set ytics 1"); # gp.ylabel('s(x) [beliebige Einheiten]') gp("I = {0,1}") funs = [Gnuplot.Func('x**2', title='calculated by gnuplot'), Gnuplot.Func('real(exp(I*x))', title='Re(e^Ix)') ] # gp.plot(*funs) # gp.hardcopy(filename="T_0d.eps", mode="eps", fontsize=14) # os.system("gv T_0d.eps") swiginac-1.5.1.1/doc/swiginac_overview.py.html0000644000175100017520000002131011000606147021474 0ustar skavhaugskavhaug Swiginac - Extending Python with Symbolic Mathematics

Swiginac - Extending Python with Symbolic Mathematics

Ola Skavhaug [1][2] Ondrej Certic [3][4]

Excerpt from the slides of a presentation of swiginac given at the Fenics'05 meeting in Chicago

GiNaC

GiNaC is not a CAS. GiNaC is a C++ library for applications in need of symbolic manipulation. Python is such an application.

Features:

  • Symbols and expressions with arithmetic operations
  • Multivariate polynomials and rational functions
  • Matrices and vectors
  • Linear systems solver
  • Tayler series expansions
  • Differentiation and integration
  • Output C, Python and LaTeX code
  • ...

Swiginac

Swiginac is a Python interface for GiNaC and can be imported as module:

>>> from swiginac import *
  • Strategy: Manually convert the GiNaC header files to SWIG interface files, and implement a set of typemaps to make a high-level interface.
  • A lot, but not all, of the GiNaC classes are now exposed to Python.
  • Certain GiNaC structures are converted to Python types in the interface and vice versa.

Symbols

Symbols are basic units in Swiginac:

>>> a = symbol('a', r'\alpha')
>>> b = symbol('beta')
>>> print a, b
a beta
>>> u = b + a
>>> print u
beta+a
>>> u.set_print_context('tex')
>>> print u
\beta+\alpha

All expressions in GiNaC are built with symbols. The drawback of this approach is that the level of abstraction is limited

Numbers

The numeric class can manipulate arbitrary precision integers in a very fast way. Rational numbers are automatically converted to fractions of coprime integers.

When specifying rational numbers, the expression that is the argument to numeric is evaluated using Pythons "standard" arithmetic, which is probabely not what we want:

>>> numeric(1/3)
0
>>> numeric(1./3)
0.33333333333333331483

To prevent evaluation by the "normal" Python operators, rational numbers can be input as string value or as (numerator, denominator):

>>> numeric("1/3")
1/3
>>> numeric(1, 3)
1/3
>>> numeric(3, 9)
1/3

Often, it is sufficient to specify one number in an expression as numeric:

>>> numeric(1)/3
1/3

Functions

Lots of functions are available

>>> sin(exp(b))
sin(exp(beta))
>>> v = tgamma(a+sqrt(b))
>>> print v.printlatex()
\Gamma(\alpha+\sqrt{\beta})

All trigonometric and hyperbolic functions are implemented in GiNaC, most of them interfaced in swiginac

Symbolic differentiation

Objects have the method diff for differentiation

>>> x = symbol('x'); y = symbol('y')
>>> P = x**5 + x**2 + y
>>> P.diff(x, 1)
2*x+5*x**4
>>> P.diff(x, 2)
2+20*x**3

diff exists as a function call too

>>> u = sin(exp(x))
>>> diff(u, x)
exp(x)*cos(exp(x))
>>> diff(u, x, 2)
exp(x)*cos(exp(x))-sin(exp(x))*exp(x)**2

Matrices

>>> mat1 = matrix(2,2)   # Two by two matrix
>>> mat1[0,0] = x
>>> mat1[1,1] = y
>>> mat1
[[x,0],[0,y]]
>>> mat1a = diag_matrix([x,y]) # Alternative definition
>>> print mat1.printlatex()
\left(\begin{array}{cc}x&0\\0&y\end{array}\right)
>>> mat2 = matrix([[sqrt(a),0],[1.0, cosh(b)]])
>>> print mat2.printc()
[[pow(a,(1.0/2.0)),0.0],[1.0000000000000000e+00,cosh(beta)]]

Simple integral support

We can construct integral objects and integrate either symbolically or numerically:

>>> integ = integral(x, 0, 1, x*x)
>>> integ
[integral object]
>>> print integ.printlatex()
\int_{0}^{1} dx\,x^{2}
>>> integ.eval_integ()
1/3
>>> integ.evalf()
0.33333333333333333332

Substitution

Algebraic objects in expressions can be substituted:

>>> u = sin(exp(b))
>>> v = u.subs(exp(b)==sqrt(a)) # v = sin(a**(1/2))
>>> w = v.subs(a==2).evalf()    # Convert sin(2**(1/2)) to `numeric`
>>> print v, w
sin(a**(1/2)) 0.98776594599273552706
>>> float(w)                    # Convert to Python double
0.98776594599273548

Sub-expressions do not match:

>>> x = symbol('x'); y = symbol('y'); z = symbol('z')
>>> u = sin(x+y+z)
>>> u.subs(x+y==4)
sin(z+y+x)
>>> u.subs([x==1, y==3])
sin(4+z)
>>> u.subs([x==1, y==2, z==3]) # Same as u.subs(x+y+z==6)
sin(6)

Solving linear systems

lsolve solves linear systems:

>>> x = symbol('x'); y = symbol('y')
>>> solution = lsolve([3*x + 5*y == 2, 5*x+y == -3], [x,y])
>>> solution
[x==-17/22, y==19/22]

Taylor series expansion

Expressions can expand themselves as a Taylor series:

>>> sin(x).series(x==0, 8)
1*x+(-1/6)*x**3+1/120*x**5+(-1/5040)*x**7+Order(x**8)
[1]Simula Research Laboratory
[2]Dept. of Informatics, University of Oslo
[3]Faculty of Mathematics and Physics
[4]Charles University in Prague
swiginac-1.5.1.1/doc/swiginac-doc.css0000644000175100017520000000435011000556362017516 0ustar skavhaugskavhaug/* Stylesheet swiginac doc pages (for use with docutils) :Author: Guenter Milde :Copyright: 2007 G. Milde This stylesheet is released under the GPL v. 2 or later */ @import url("html4css1.css"); /* docutils style sheet */ /* @import url("pygments-default.css"); */ /* code syntax highlight */ /* Swiginac doc customizations */ /* -------------------- */ div#Inhalt { margin-left: 0em; /* padding-left: 0.5em; */ /* border: 1px dashed silver; */ /* border-left-width: 1px */ /* border-color: silver */ min-width: 16em; /* Mindestbreite verhindert Anzeigefehler in modernen Browsern */ } hr { height: 1px; color: #aaa; background-color: #aaa; border: 0; margin: .2em 0 .2em 0; } h1, h2, h3, h4, h5, h6 { color: black; font-weight: normal; background: none; margin: 0; padding-top: .5em; padding-bottom: .17em; border-bottom: 1px solid #aaa; } h1.title { font-size: 188%; } h1 { font-size: 132%; border-bottom-width: 3px; } h2.subtitle { font-size: 150%; } h2 { font-size: 116%; border-bottom-width: 2px; } /* h3, h4, h5, h6 { */ /* border-bottom: none; */ /* font-weight: bold; */ /* } */ h3, h4, h5, h6 { font-size: 100%; } /* Table of Contents */ p.topic-title { font-weight: bold } /* bold definition terms */ dt { font-weight: bold; } /* background colour for literal blocks*/ pre.literal-block { padding: 1em; border: 1px dashed #2f6fab; color: black; background-color: #f9f9f9; line-height: 1.1em; /* background-color: #faf0e6; */ /* linen */ } /* and doctest blocks (interactive python session) */ pre.doctest-block, tt.docutils { background-color: #f9f9f9; /* background-color: #eee9e9; */ } /* Underline links if the mouse is over them */ a:hover { text-decoration: underline; } /* last line with Berlios logo */ p.thanks { text-align: right; background-color: silver; } /* div.contents { margin: 5px } */ div.contents { margin: 0em } div.contents p.topic-title { font-weight: normal; margin: 0; padding-top: .5em; padding-bottom: .17em; font-size: 132%; border-bottom: 2px solid #aaa; } div.contents a { /* text-decoration: none ; */ color: black } swiginac-1.5.1.1/src/0000755000175100017520000000000011374770636014475 5ustar skavhaugskavhaugswiginac-1.5.1.1/src/swiginac/0000755000175100017520000000000011374770636016301 5ustar skavhaugskavhaugswiginac-1.5.1.1/src/swiginac/numeric.i0000644000175100017520000000564410334172146020111 0ustar skavhaugskavhaug/* (c) Copyright 2003, 2004, 2005 Author: Ola Skavhaug and Ondrej Certik This file is part of swiginac. swiginac is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. swiginac is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with swiginac; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ class numeric : public basic { public: numeric(int i); numeric(unsigned int i); numeric(long i); numeric(unsigned long i); numeric(long numer, long denom); numeric(double d); numeric(const char *); const numeric add(const numeric &other) const; const numeric sub(const numeric &other) const; const numeric mul(const numeric &other) const; const numeric div(const numeric &other) const; const numeric power(const numeric &other) const; const numeric & add_dyn(const numeric &other) const; const numeric & sub_dyn(const numeric &other) const; const numeric & mul_dyn(const numeric &other) const; const numeric & div_dyn(const numeric &other) const; const numeric & power_dyn(const numeric &other) const; const numeric inverse() const; int csgn() const; int compare(const numeric &other) const; bool is_equal(const numeric &other) const; bool is_zero() const; bool is_positive() const; bool is_negative() const; bool is_integer() const; bool is_pos_integer() const; bool is_nonneg_integer() const; bool is_even() const; bool is_odd() const; bool is_prime() const; bool is_rational() const; bool is_real() const; bool is_cinteger() const; bool is_crational() const; // bool operator==(const numeric &other) const; // bool operator!=(const numeric &other) const; // bool operator<(const numeric &other) const; // bool operator<=(const numeric &other) const; // bool operator>(const numeric &other) const; // bool operator>=(const numeric &other) const; int to_int() const; long to_long() const; double to_double() const; cln::cl_N to_cl_N() const; const numeric real() const; const numeric imag() const; const numeric numer() const; const numeric denom() const; int int_length() const; numeric(const cln::cl_N &z); }; %extend numeric { double __float__() { return (*self).to_double(); } int __int__() { return (*self).to_int(); } }; ex PiEvalf(void); ex EulerEvalf(void); ex CatalanEvalf(void); // vim:ft=cpp: swiginac-1.5.1.1/src/swiginac/ex.i0000644000175100017520000001315211171051565017055 0ustar skavhaugskavhaug/* (c) Copyright 2003, 2004, 2005 Author: Ola Skavhaug and Ondrej Certik This file is part of swiginac. swiginac is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. swiginac is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with swiginac; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ %{ lst* list2lst(PyObject *input); PyObject* lst2list(const lst *input); //GETDESC1 and GETDESC2 are equivalent - GETDESC1 is the official way how to do //it, but it is slower than the undocumented way GETDESC2. #define GETDESC1(NAME) \ static swig_type_info *NAME##descr=0;\ if (!NAME##descr){\ NAME##descr=SWIG_TypeQuery("GiNaC::"#NAME" *");\ if (!NAME##descr) {\ PyErr_SetString(PyExc_ValueError,"Cannot get a "#NAME" descriptor. Fix in ex.i");\ return NULL;\ }\ } #define GETDESC2(NAME) \ static swig_type_info *NAME##descr=SWIGTYPE_p_GiNaC__##NAME #define GETDESC(NAME) GETDESC2(NAME) //converts any type from python to ex ex * type2ex(PyObject * input) { basic *btmp; GETDESC(basic); if (not((SWIG_ConvertPtr(input, (void **) &btmp, basicdescr,0)) == -1)) return new ex((*btmp)); if (PyInt_Check(input)) return new ex(numeric(PyInt_AsLong(input))); if (PyFloat_Check(input)) return new ex(numeric(PyFloat_AsDouble(input))); if (PyList_Check(input)) { lst *l=list2lst(input); if (l==NULL) return NULL; return new ex(l->eval()); } return NULL; } numeric * type2numeric(PyObject * input) { numeric *btmp; GETDESC(numeric); if (not((SWIG_ConvertPtr(input, (void **) &btmp, numericdescr,0)) == -1)) return new numeric((*btmp)); if (PyInt_Check(input)) return new numeric(PyInt_AsLong(input)); if (PyFloat_Check(input)) return new numeric(PyFloat_AsDouble(input)); return NULL; } bool checktype2ex(PyObject * input) { //we assume, that everything can be converted to ex. //if you find some counterexample, write test for it first (which fail) //and then implement it here. return true; } #define EX2(NAME) \ if (is_a(*convert)) {\ NAME *p = new NAME(ex_to(*convert));\ GETDESC(NAME);\ return SWIG_NewPointerObj((void *)p, NAME##descr, 1);\ } //unwraps ex and return python object PyObject * ex2type(const ex* input) { ex tmp; try { tmp = input->evalm(); } catch(std::exception & e) { tmp = *input; } const ex* convert = &tmp; EX2(symbol) EX2(constant) EX2(numeric) if (is_a(*convert)) { const lst *l = &ex_to(*convert); return lst2list(l); } EX2(pseries) EX2(su3one) EX2(su3t) EX2(su3f) EX2(su3d) EX2(diracone) EX2(diracgamma) EX2(diracgamma5) EX2(diracgammaL) EX2(diracgammaR) EX2(cliffordunit) EX2(tensor) EX2(tensdelta) EX2(tensmetric) EX2(minkmetric) EX2(spinmetric) EX2(tensepsilon) EX2(wildcard) EX2(color) EX2(clifford) EX2(indexed) EX2(varidx) EX2(spinidx) EX2(idx) EX2(symmetry) EX2(integral) EX2(relational) EX2(function) EX2(add) EX2(mul) EX2(ncmul) EX2(matrix) EX2(power) // Nothing converted, throw exception throw (std::logic_error("Cannot unwrap ex. Fix in ex.i")); } //converts ginac lst to python list (unwrapping all exs) PyObject *lst2list(const lst *input) { lst::const_iterator i = input->begin(); lst::const_iterator i_end = input->end(); PyObject *pylist = PyList_New(0); while (i!=i_end) { PyObject *item = ex2type(&(*i)); PyList_Append(pylist, item); //is this necessary? Py_INCREF(item); i++; } return (pylist); } /* PyObject *lst2list(lst *input) { lst *l = input; int n = l->nops(); PyObject *pylist = PyList_New(n); PyObject *item; for (int i=0;ilet_op(i))); PyList_SetItem(pylist, i, item); Py_INCREF(item); } return (pylist); }*/ //convert any python list to ginac lst lst* list2lst(PyObject * input) { lst *out=new lst(); if PyList_Check(input) { int n = PyList_Size(input); PyObject *item; ex *tmp; for (int i = 0; iappend(*tmp); } else { PyErr_SetString(PyExc_ValueError,"Cannot convert type to ex."); return NULL; } } return out; } else { PyErr_SetString(PyExc_ValueError,"List expected."); delete out; return NULL; } } //converts ginac exvector to python list (unwrapping all exs) PyObject *exvector2list(exvector *input) { exvector::const_iterator i = input->begin(); exvector::const_iterator i_end = input->end(); PyObject *pylist = PyList_New(0); while (i!=i_end) { PyObject *item = ex2type(&(*i)); PyList_Append(pylist, item); //is this necessary? Py_INCREF(item); i++; } return (pylist); } %} // vim:ft=cpp: swiginac-1.5.1.1/src/swiginac/color.i0000644000175100017520000000337110361775450017567 0ustar skavhaugskavhaug/* (c) Copyright 2006 Author: Matti Peltomaki This file is part of swiginac. swiginac is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. swiginac is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with swiginac; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ class color : public indexed { public: color(const ex & b, unsigned char rl = 0); color(const ex & b, const ex & i1, unsigned char rl = 0); // internal constructors color(unsigned char rl, const exvector & v, bool discardable = false); color(unsigned char rl, std::auto_ptr vp); unsigned char get_representation_label() const {return representation_label;} }; class su3one : public tensor { }; class su3t : public tensor { }; class su3f : public tensor { }; class su3d : public tensor { }; ex color_ONE(unsigned char rl = 0); ex color_T(const ex & a, unsigned char rl = 0); ex color_f(const ex & a, const ex & b, const ex & c); ex color_d(const ex & a, const ex & b, const ex & c); ex color_h(const ex & a, const ex & b, const ex & c); ex color_trace(const ex & e, const std::set & rls); ex color_trace(const ex & e, const lst & rll); ex color_trace(const ex & e, unsigned char rl = 0); swiginac-1.5.1.1/src/swiginac/pseries.i0000644000175100017520000000314210334172146020110 0ustar skavhaugskavhaug/* (c) Copyright 2003, 2004, 2005 Author: Ola Skavhaug and Ondrej Certik This file is part of swiginac. swiginac is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. swiginac is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with swiginac; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ class pseries : public basic { public: pseries(const ex &rel_, const epvector &ops_); ex get_var() const {return var;} ex get_point() const {return point;} ex convert_to_poly(bool no_order = false) const; bool is_compatible_to(const pseries &other) const {return var.is_equal(other.var) && point.is_equal(other.point);} bool is_zero() const {return seq.size() == 0;} bool is_terminating() const; ex coeffop(size_t i) const; ex exponop(size_t i) const; ex add_series(const pseries &other) const; ex mul_const(const numeric &other) const; ex mul_series(const pseries &other) const; ex power_const(const numeric &p, int deg) const; pseries shift_exponents(int deg) const; }; inline ex series_to_poly(const ex &e); inline bool is_terminating(const pseries & s); // vim:ft=cpp: swiginac-1.5.1.1/src/swiginac/Makefile0000644000175100017520000000170010334225256017723 0ustar skavhaugskavhaug#PYTHONVERSION = 2.4 PYTHONVERSION = 2.3 GCC=g++ #GCC=g++-3.3 #SWIG = swig -v -Wall SWIG = swig INTERFACE = swiginac CXX = $(GCC) CXXSHARED = $(GCC) -shared INCLUDES = -I/usr/include/python$(PYTHONVERSION) -I/usr/include/ginac CFLAGS = -g -c -fpic LDFLAGS = -lginac #PREFIX = $(HOME)/home/devel/pygin PREFIX = /usr/lib/python$(PYTHONVERSION)/site-packages all:: python lib python:: $(SWIG) -c++ -python $(INTERFACE).i lib:: $(CXX) $(CFLAGS) $(INTERFACE)_wrap.cxx -o $(INTERFACE)_wrap.o $(INCLUDES) $(CXXSHARED) $(INTERFACE)_wrap.o $(LDFLAGS) -o _$(INTERFACE).so clean:: rm -f *_wrap* *.so *.o $(OBJ_FILES) *~ swiginac.py swiginac.pyc ../../tests/swiginac/*.pyc rm -rf build install:: mkdir -p $(PREFIX)/swiginac cp _$(INTERFACE).so $(PREFIX)/swiginac/ cp $(INTERFACE).py $(PREFIX)/swiginac/__init__.py check:: python ../../tests/swiginac/checkall.py checkquick:: python ../../tests/swiginac/checkall.py quick swiginac-1.5.1.1/src/swiginac/normal.i0000644000175100017520000000365310607666706017752 0ustar skavhaugskavhaug/* (c) Copyright 2003, 2004, 2005 Author: Ola Skavhaug and Ondrej Certik This file is part of swiginac. swiginac is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. swiginac is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with swiginac; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ ex quo(const ex &a, const ex &b, const ex &x, bool check_args = true); ex quo(const ex &a, const ex &b, const ex &x) throw(std::invalid_argument); ex rem(const ex &a, const ex &b, const ex &x, bool check_args = true); ex decomp_rational(const ex &a, const ex &x); ex prem(const ex &a, const ex &b, const ex &x, bool check_args = true); ex sprem(const ex &a, const ex &b, const ex &x, bool check_args = true); bool divide(const ex &a, const ex &b, ex &q, bool check_args = true); ex gcd(const ex &a, const ex &b, ex *ca = NULL, ex *cb = NULL, bool check_args = true); ex gcd(const ex &a, const ex &b) throw(std::invalid_argument); ex lcm(const ex &a, const ex &b, bool check_args = true); ex sqrfree(const ex &a, const lst &l = lst()); ex sqrfree_parfrac(const ex & a, const symbol & x); ex collect_common_factors(const ex & e); ex resultant(const ex & e1, const ex & e2, const ex & s); /* From normal.cpp */ //static void add_symbol(const ex &s, sym_desc_vec &v); //extern void collect_symbols(const ex &e, sym_desc_vec &v); //extern void get_symbol_stats(const ex &a, const ex &b, sym_desc_vec &v); // vim:ft=cpp: swiginac-1.5.1.1/src/swiginac/add.i0000644000175100017520000000207510334172146017172 0ustar skavhaugskavhaug/* (c) Copyright 2003, 2004, 2005 Author: Ola Skavhaug and Ondrej Certik This file is part of swiginac. swiginac is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. swiginac is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with swiginac; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ class add : public expairseq { public: add(const ex & lh, const ex & rh); add(const exvector & v); add(const epvector & v); // add(const epvector & v, const ex & oc); // add(std::auto_ptr vp, const ex & oc); }; // vim:ft=cpp: swiginac-1.5.1.1/src/swiginac/idx.i0000644000175100017520000000513311171051565017225 0ustar skavhaugskavhaug/* (c) Copyright 2003, 2004, 2005 Author: Ola Skavhaug and Ondrej Certik This file is part of swiginac. swiginac is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. swiginac is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with swiginac; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ class idx : public basic { public: explicit idx(const ex & v, const ex & dim); virtual bool is_dummy_pair_same_type(const basic & other) const; ex get_value() const {return value;} bool is_numeric() const {return is_exactly_a(value);} bool is_symbolic() const {return !is_exactly_a(value);} ex get_dim() const {return dim;} bool is_dim_numeric() const {return is_exactly_a(dim);} bool is_dim_symbolic() const {return !is_exactly_a(dim);} ex replace_dim(const ex & new_dim) const; ex minimal_dim(const idx & other) const; }; class varidx : public idx { public: varidx(const ex & v, const ex & dim, bool covariant = false); bool is_dummy_pair_same_type(const basic & other) const; bool is_covariant() const {return covariant;} bool is_contravariant() const {return !covariant;} ex toggle_variance() const; }; class spinidx : public varidx { public: spinidx(const ex & v, const ex & dim = 2, bool covariant = false, bool dotted = false); bool is_dummy_pair_same_type(const basic & other) const; bool is_dotted() const {return dotted;} bool is_undotted() const {return !dotted;} ex toggle_dot() const; ex toggle_variance_dot() const; }; bool is_dummy_pair(const idx & i1, const idx & i2); bool is_dummy_pair(const ex & e1, const ex & e2); void find_free_and_dummy(exvector::const_iterator it, exvector::const_iterator itend, exvector & out_free, exvector & out_dummy); void find_free_and_dummy(const exvector & v, exvector & out_free, exvector & out_dummy); void find_dummy_indices(const exvector & v, exvector & out_dummy); size_t count_dummy_indices(const exvector & v); size_t count_free_indices(const exvector & v); ex minimal_dim(const ex & dim1, const ex & dim2); // vim:ft=cpp: swiginac-1.5.1.1/src/swiginac/mul.i0000644000175100017520000000241710334172146017237 0ustar skavhaugskavhaug/* (c) Copyright 2003, 2004, 2005 Author: Ola Skavhaug and Ondrej Certik This file is part of swiginac. swiginac is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. swiginac is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with swiginac; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ /** Product of expressions. */ class mul : public expairseq { friend class add; friend class ncmul; friend class power; public: mul(const ex & lh, const ex & rh); mul(const exvector & v); mul(const epvector & v); // mul(const epvector & v, const ex & oc); // mul(std::auto_ptr vp, const ex & oc); mul(const ex & lh, const ex & mh, const ex & rh); ex algebraic_subs_mul(const exmap & m, unsigned options) const; }; // vim:ft=cpp: swiginac-1.5.1.1/src/swiginac/ptr.i0000644000175100017520000000745110334172146017252 0ustar skavhaugskavhaug/* (c) Copyright 2003, 2004, 2005 Author: Ola Skavhaug and Ondrej Certik This file is part of swiginac. swiginac is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. swiginac is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with swiginac; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ /** Base class for reference-counted objects. */ class refcounted { public: refcounted() throw() : refcount(0) {} size_t add_reference() throw() { return ++refcount; } size_t remove_reference() throw() { return --refcount; } size_t get_refcount() const throw() { return refcount; } void set_refcount(size_t r) throw() { refcount = r; } private: size_t refcount; ///< reference counter }; /** Class of (intrusively) reference-counted pointers that support * copy-on-write semantics. * * Requirements for T: * must support the refcounted interface (usually by being derived * from refcounted) * T* T::duplicate() member function (only if makewriteable() is used) */ template class ptr { friend class std::less< ptr >; // NB: This implementation of reference counting is not thread-safe. // The reference counter needs to be incremented/decremented atomically, // and makewritable() requires locking. public: // no default ctor: a ptr is never unbound /** Bind ptr to newly created object, start reference counting. */ ptr(T *t) throw() : p(t) { GINAC_ASSERT(p); p->set_refcount(1); } /** Bind ptr to existing reference-counted object. */ explicit ptr(T &t) throw() : p(&t) { p->add_reference(); } ptr(const ptr & other) throw() : p(other.p) { p->add_reference(); } ~ptr() { if (p->remove_reference() == 0) delete p; } // ptr &operator=(const ptr & other) // { // // NB: must first add reference to "other", since other might be *this. // other.p->add_reference(); // if (p->remove_reference() == 0) // delete p; // p = other.p; // return *this; // } T &operator*() const throw() { return *p; } T *operator->() const throw() { return p; } friend inline T *get_pointer(const ptr & x) throw() { return x.p; } /** Announce your intention to modify the object bound to this ptr. * This ensures that the object is not shared by any other ptrs. */ void makewritable() { if (p->get_refcount() > 1) { T *p2 = p->duplicate(); p2->set_refcount(1); p->remove_reference(); p = p2; } } /** Swap the bound object of this ptr with another ptr. */ void swap(ptr & other) throw() { T *t = p; p = other.p; other.p = t; } template bool operator==(const ptr & rhs) const throw() { return p == get_pointer(rhs); } template bool operator!=(const ptr & rhs) const throw() { return p != get_pointer(rhs); } template inline friend bool operator==(const ptr & lhs, const U * rhs) throw() { return lhs.p == rhs; } template inline friend bool operator!=(const ptr & lhs, const U * rhs) throw() { return lhs.p != rhs; } template inline friend bool operator==(const U * lhs, const ptr & rhs) throw() { return lhs == rhs.p; } template inline friend bool operator!=(const U * lhs, const ptr & rhs) throw() { return lhs != rhs.p; } inline friend std::ostream & operator<<(std::ostream & os, const ptr & rhs) { os << rhs.p; } private: T *p; }; // vim:ft=cpp: swiginac-1.5.1.1/src/swiginac/tensor.i0000644000175100017520000000457210361766243017767 0ustar skavhaugskavhaug/* (c) Copyright 2003, 2004, 2005 Author: Ola Skavhaug and Ondrej Certik This file is part of swiginac. swiginac is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. swiginac is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with swiginac; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ class tensor : public basic { public: tensor(); bool replace_contr_index(exvector::iterator self, exvector::iterator other) const; }; class tensdelta : public tensor { public: tensdelta(); ex eval_indexed(const basic & i) const; bool contract_with(exvector::iterator self, exvector::iterator other, exvector & v) const; }; class tensmetric : public tensor { public: tensmetric(); ex eval_indexed(const basic & i) const; bool contract_with(exvector::iterator self, exvector::iterator other, exvector & v) const; }; class minkmetric : public tensmetric { public: minkmetric(); minkmetric(bool pos_sig); ex eval_indexed(const basic & i) const; }; class spinmetric : public tensmetric { public: spinmetric(); ex eval_indexed(const basic & i) const; bool contract_with(exvector::iterator self, exvector::iterator other, exvector & v) const; }; class tensepsilon : public tensor { public: tensepsilon(); tensepsilon(bool minkowski, bool pos_sig); ex eval_indexed(const basic & i) const; bool contract_with(exvector::iterator self, exvector::iterator other, exvector & v) const; }; ex delta_tensor(const ex & i1, const ex & i2); ex metric_tensor(const ex & i1, const ex & i2); ex lorentz_g(const ex & i1, const ex & i2, bool pos_sig = false); ex spinor_metric(const ex & i1, const ex & i2); ex epsilon_tensor(const ex & i1, const ex & i2); ex epsilon_tensor(const ex & i1, const ex & i2, const ex & i3); ex lorentz_eps(const ex & i1, const ex & i2, const ex & i3, const ex & i4, bool pos_sig = false); // vim:ft=cpp: swiginac-1.5.1.1/src/swiginac/swiginac.h0000644000175100017520000000040511374766322020252 0ustar skavhaugskavhaug ex * type2ex(PyObject * input); numeric * type2numeric(PyObject * input); PyObject * ex2type(const ex* input); bool checktype2ex(PyObject * input); lst* list2lst(PyObject *input); PyObject *lst2list(const lst *input); PyObject *exvector2list(exvector *input); swiginac-1.5.1.1/src/swiginac/swiginac.i0000644000175100017520000000726411256636160020260 0ustar skavhaugskavhaug/* (c) Copyright 2003, 2004, 2005 Author: Ola Skavhaug and Ondrej Certik This file is part of swiginac. swiginac is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. swiginac is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with swiginac; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ %module swiginac %{ #include "ginac/ginac.h" using namespace GiNaC; #include %} %{ #include #include std::map symbol_collection; const symbol & get_symbol(const std::string & name) { std::map::iterator i = symbol_collection.find(name); if( i != symbol_collection.end() ) { return i->second; } return symbol_collection.insert(make_pair(name, symbol(name))).first->second; } %} %include "pyexceptions.i" %include std_sstream.i %include std_string.i %include std_map.i %include std_vector.i %include stl.i %feature("autodoc", "1"); namespace GiNaC { //%feature("ref") refcounted "$this->add_reference();" //%feature("unref") refcounted "$this->remove_reference();" %include "ex.i" %include "typemaps.i" %include "ptr.i" %include "registrar.i" %include "basic.i" %include "symbol.i" %include "numeric.i" %include "relational.i" %include "normal.i" %include "constant.i" %include "container.i" %include "integral.i" %include "matrix.i" %include "expairseq.i" %include "mul.i" %include "ncmul.i" %include "power.i" %include "add.i" %include "function.i" %include "tensor.i" %include "indexed.i" %include "idx.i" %include "symmetry.i" %include "clifford.i" %include "color.i" %include "wildcard.i" %include "flags.i" %include "pseries.i" %include "inifcns.i" %include "archive.i" %define ADD_REPR(name) %extend name { %pythoncode %{ def __repr__(self): return self.__str__() %} }; %enddef ADD_REPR(add); ADD_REPR(mul); ADD_REPR(power); ADD_REPR(matrix); ADD_REPR(clifford); ADD_REPR(relational); ADD_REPR(numeric); ADD_REPR(function); ADD_REPR(constant); ADD_REPR(symbol); ADD_REPR(integral); ADD_REPR(idx); ADD_REPR(varidx); ADD_REPR(pseries); }; // typedefs and template instantiations for stl containers with ginac objects %typedef std::vector GiNaC::exvector; %template(exvector) std::vector; %typedef std::map GiNaC::exmap; %template(exmap) std::map; %pythoncode %{ _dict = {} def get_symbols(name, number): global _dict if not _dict.has_key(name): _dict[name] = [symbol("%s%d" % (name,i)) for i in xrange(number)] else: x = _dict[name] n = len(x) if n >= number: return x[:] else: _dict[name] += [symbol("%s%d" % (name,i)) for i in xrange(n, number)] return _dict[name][:] %} const GiNaC::symbol & get_symbol(const std::string & name); %inline %{ namespace GiNaC { ex parse_string(const std::string &str, lst &ls) { return ex(str,ls); } ex * toex(lst& l) { return new ex(l); } ex * toex(lst* l) { return new ex(*l); } ex * toex(basic & b) { return new ex(b); } } %}; // vim:ft=cpp: swiginac-1.5.1.1/src/swiginac/inifcns.i0000644000175100017520000000166710564447542020113 0ustar skavhaugskavhaug/* (c) Copyright 2003, 2004, 2005 Author: Ola Skavhaug and Ondrej Certik This file is part of swiginac. swiginac is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. swiginac is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with swiginac; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ const numeric fsolve(const ex& f, const symbol& x, const numeric& x1, const numeric& x2); // vim:ft=cpp: swiginac-1.5.1.1/src/swiginac/function.i0000644000175100017520000004570211171051565020274 0ustar skavhaugskavhaug/* (c) Copyright 2003, 2004, 2005 Author: Ola Skavhaug and Ondrej Certik This file is part of swiginac. swiginac is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. swiginac is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with swiginac; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ class function; class symmetry; class function_options { public: function_options(); function_options(std::string const & n, std::string const & tn=std::string()); function_options(std::string const & n, unsigned np); ~function_options(); void initialize(); function_options & dummy() { return *this; } function_options & set_name(std::string const & n, std::string const & tn=std::string()); function_options & latex_name(std::string const & tn); // the following lines have been generated for max. 14 parameters function_options & eval_func(eval_funcp_1 e); function_options & eval_func(eval_funcp_2 e); function_options & eval_func(eval_funcp_3 e); function_options & eval_func(eval_funcp_4 e); function_options & eval_func(eval_funcp_5 e); function_options & evalf_func(evalf_funcp_1 ef); function_options & evalf_func(evalf_funcp_2 ef); function_options & evalf_func(evalf_funcp_3 ef); function_options & evalf_func(evalf_funcp_4 ef); function_options & evalf_func(evalf_funcp_5 ef); function_options & conjugate_func(conjugate_funcp_1 d); function_options & conjugate_func(conjugate_funcp_2 d); function_options & conjugate_func(conjugate_funcp_3 d); function_options & conjugate_func(conjugate_funcp_4 d); function_options & conjugate_func(conjugate_funcp_5 d); function_options & derivative_func(derivative_funcp_1 d); function_options & derivative_func(derivative_funcp_2 d); function_options & derivative_func(derivative_funcp_3 d); function_options & derivative_func(derivative_funcp_4 d); function_options & derivative_func(derivative_funcp_5 d); function_options & series_func(series_funcp_1 s); function_options & series_func(series_funcp_2 s); function_options & series_func(series_funcp_3 s); function_options & series_func(series_funcp_4 s); function_options & series_func(series_funcp_5 s); template function_options & print_func(print_funcp_1 p) { test_and_set_nparams(1); set_print_func(Ctx::get_class_info_static().options.get_id(), print_funcp(p)); return *this; } template function_options & print_func(print_funcp_2 p) { test_and_set_nparams(2); set_print_func(Ctx::get_class_info_static().options.get_id(), print_funcp(p)); return *this; } template function_options & print_func(print_funcp_3 p) { test_and_set_nparams(3); set_print_func(Ctx::get_class_info_static().options.get_id(), print_funcp(p)); return *this; } template function_options & print_func(print_funcp_4 p) { test_and_set_nparams(4); set_print_func(Ctx::get_class_info_static().options.get_id(), print_funcp(p)); return *this; } template function_options & print_func(print_funcp_5 p) { test_and_set_nparams(5); set_print_func(Ctx::get_class_info_static().options.get_id(), print_funcp(p)); return *this; } // end of generated lines function_options & eval_func(eval_funcp_exvector e); function_options & evalf_func(evalf_funcp_exvector ef); function_options & conjugate_func(conjugate_funcp_exvector d); function_options & derivative_func(derivative_funcp_exvector d); function_options & series_func(series_funcp_exvector s); template function_options & print_func(print_funcp_exvector p) { print_use_exvector_args = true; set_print_func(Ctx::get_class_info_static().options.get_id(), print_funcp(p)); return *this; } function_options & set_return_type(unsigned rt, const return_type_t* rtt = 0); function_options & do_not_evalf_params(); function_options & remember(unsigned size, unsigned assoc_size=0, unsigned strategy=remember_strategies::delete_never); function_options & overloaded(unsigned o); function_options & set_symmetry(const symmetry & s); std::string get_name() const { return name; } unsigned get_nparams() const { return nparams; } }; /** Exception class thrown by classes which provide their own series expansion * to signal that ordinary Taylor expansion is safe. */ class do_taylor {}; /** The class function is used to implement builtin functions like sin, cos... and user defined functions */ //class function : public exprseq //class function class function : public basic { public: function(unsigned ser); // the following lines have been generated for max. 14 parameters function(unsigned ser, const ex & param1); function(unsigned ser, const ex & param1, const ex & param2); function(unsigned ser, const ex & param1, const ex & param2, const ex & param3); function(unsigned ser, const ex & param1, const ex & param2, const ex & param3, const ex & param4); function(unsigned ser, const ex & param1, const ex & param2, const ex & param3, const ex & param4, const ex & param5); // end of generated lines //function(unsigned ser, const exprseq & es); //function(unsigned ser, const exvector & v, bool discardable = false); // function(unsigned ser, std::auto_ptr vp); // functions overriding virtual functions from base classes unsigned precedence() const {return 70;} unsigned calchash() const; ex thiscontainer(const exvector & v) const; // ex thiscontainer(std::auto_ptr vp) const; //ex conjugate() const; static unsigned register_new(function_options const & opt); static unsigned current_serial; static unsigned find_function(const std::string &name, unsigned nparams); unsigned get_serial() const {return serial;} std::string get_name() const; }; //size_t nops(const ex & thisex); //ex expand(const ex & thisex, unsigned options = 0); ex conjugate(const ex & thisex); bool has(const ex & thisex, const ex & pattern); bool find(const ex & thisex, const ex & pattern, exset & found); int degree(const ex & thisex, const ex & s); int ldegree(const ex & thisex, const ex & s); ex coeff(const ex & thisex, const ex & s, int n=1); ex numer(const ex & thisex); ex denom(const ex & thisex); ex numer_denom(const ex & thisex); ex normal(const ex & thisex, int level=0); ex to_rational(const ex & thisex, lst & repl_lst); //ex to_rational(const ex & thisex, exmap & repl); //ex to_polynomial(const ex & thisex, exmap & repl); ex to_polynomial(const ex & thisex, lst & repl_lst); ex collect(const ex & thisex, const ex & s, bool distributed = false); //ex eval(const ex & thisex, int level = 0); //ex evalf(const ex & thisex, int level = 0); ex evalm(const ex & thisex); ex eval_integ(const ex & thisex); ex diff(const ex & thisex, const symbol & s, unsigned nth = 1); ex series(const ex & thisex, const ex & r, int order, unsigned options = 0); bool match(const ex & thisex, const ex & pattern, exmap & repl_lst); ex simplify_indexed(const ex & thisex, unsigned options = 0); ex simplify_indexed(const ex & thisex, const scalar_products & sp, unsigned options = 0); ex symmetrize(const ex & thisex); ex symmetrize(const ex & thisex, const lst & l); ex antisymmetrize(const ex & thisex); ex antisymmetrize(const ex & thisex, const lst & l); ex symmetrize_cyclic(const ex & thisex); ex symmetrize_cyclic(const ex & thisex, const lst & l); ex op(const ex & thisex, size_t i); ex lhs(const ex & thisex); ex rhs(const ex & thisex); //bool is_zero(const ex & thisex); void swap(ex & e1, ex & e2); //ex ex::subs(const exmap & m, unsigned options) const; //ex subs(const ex & thisex, const exmap & m, unsigned options = 0); ex subs(const ex & thisex, const lst & ls, const lst & lr, unsigned options = 0); ex subs(const ex & thisex, const ex & e); //this doesn't work. why? //ex subs(const ex & thisex, const ex & e, unsigned options = 0); ex sqrt(const ex & a); //ex expand(const ex & thisex, unsigned options = 0); ex expand(const ex & thisex); %define DECLARE_FUNCTION_1P_TEMPLATES(NAME) %template(NAME##_basic) NAME; %template(NAME##_int) NAME; %template(NAME##_double) NAME; %enddef %define DECLARE_FUNCTION_1P_PYTHONCODE(FUNCNAME, TEMPLATENAME) %pythoncode %{ def FUNCNAME(x): if isinstance(x,basic): return TEMPLATENAME##_basic(x).eval() elif isinstance(x,int): return TEMPLATENAME##_int(x).eval() elif isinstance(x,float): return TEMPLATENAME##_double(x).eval() else: raise "Unimplented type. Fix in function.i." %} %enddef %define DECLARE_FUNCTION_2P_TEMPLATES(NAME) %template(NAME##_basic_basic) NAME; %template(NAME##_basic_int) NAME; %template(NAME##_basic_double) NAME; %template(NAME##_int_basic) NAME; %template(NAME##_int_int) NAME; %template(NAME##_int_double) NAME; %template(NAME##_double_basic) NAME; %template(NAME##_double_int) NAME; %template(NAME##_double_double) NAME; %enddef %define DECLARE_FUNCTION_2P_PYTHONCODE(FUNCNAME,TEMPLATENAME) %pythoncode %{ def FUNCNAME(x,y): def which(p): types = [basic,int,float] for t in types: if isinstance(p,t): return t raise "Unimplemented type. Fix in function.i." xt = which(x) yt = which(y) func_hash = {(basic,basic) : TEMPLATENAME##_basic_basic, (basic,int) : TEMPLATENAME##_basic_int, (basic,float) : TEMPLATENAME##_basic_double, (int,basic) : TEMPLATENAME##_int_basic, (int,int) : TEMPLATENAME##_int_int, (int,float) : TEMPLATENAME##_int_double, (float,basic) : TEMPLATENAME##_double_basic, (float,int) : TEMPLATENAME##_double_int, (float,float) : TEMPLATENAME##_double_double} return func_hash[(xt,yt)](x,y) %} %enddef %define DECLARE_FUNCTION_3P_TEMPLATES(NAME) %template(NAME##_basic_basic_basic) NAME; %template(NAME##_basic_basic_int) NAME; %template(NAME##_basic_basic_double) NAME; %template(NAME##_basic_int_basic) NAME; %template(NAME##_basic_int_int) NAME; %template(NAME##_basic_int_double) NAME; %template(NAME##_basic_double_basic) NAME; %template(NAME##_basic_double_int) NAME; %template(NAME##_basic_double_double) NAME; %template(NAME##_int_basic_basic) NAME; %template(NAME##_int_basic_int) NAME; %template(NAME##_int_basic_double) NAME; %template(NAME##_int_int_basic) NAME; %template(NAME##_int_int_int) NAME; %template(NAME##_int_int_double) NAME; %template(NAME##_int_double_basic) NAME; %template(NAME##_int_double_int) NAME; %template(NAME##_int_double_double) NAME; %template(NAME##_double_basic_basic) NAME; %template(NAME##_double_basic_int) NAME; %template(NAME##_double_basic_double) NAME; %template(NAME##_double_int_basic) NAME; %template(NAME##_double_int_int) NAME; %template(NAME##_double_int_double) NAME; %template(NAME##_double_double_basic) NAME; %template(NAME##_double_double_int) NAME; %template(NAME##_double_double_double) NAME; %enddef %define DECLARE_FUNCTION_3P_PYTHONCODE(FUNCNAME,TEMPLATENAME) %pythoncode %{ def FUNCNAME(x,y,z): def which(p): types = [basic,int,float] for t in types: if isinstance(p,t): return t raise "Unimplemented type. Fix in function.i." xt = which(x) yt = which(y) zt = which(z) func_hash = {(basic,basic,basic) : TEMPLATENAME##_basic_basic_basic, (basic,basic,int) : TEMPLATENAME##_basic_basic_int, (basic,basic,float) : TEMPLATENAME##_basic_basic_double, (basic,int,basic) : TEMPLATENAME##_basic_int_basic, (basic,int,int) : TEMPLATENAME##_basic_int_int, (basic,int,float) : TEMPLATENAME##_basic_int_double, (basic,float,basic) : TEMPLATENAME##_basic_double_basic, (basic,float,int) : TEMPLATENAME##_basic_double_int, (basic,float,float) : TEMPLATENAME##_basic_double_double, (int,basic,basic) : TEMPLATENAME##_int_basic_basic, (int,basic,int) : TEMPLATENAME##_int_basic_int, (int,basic,float) : TEMPLATENAME##_int_basic_double, (int,int,basic) : TEMPLATENAME##_int_int_basic, (int,int,int) : TEMPLATENAME##_int_int_int, (int,int,float) : TEMPLATENAME##_int_int_double, (int,float,basic) : TEMPLATENAME##_int_double_basic, (int,float,int) : TEMPLATENAME##_int_double_int, (int,float,float) : TEMPLATENAME##_int_double_double, (float,basic,basic) : TEMPLATENAME##_double_basic_basic, (float,basic,int) : TEMPLATENAME##_double_basic_int, (float,basic,float) : TEMPLATENAME##_double_basic_double, (float,int,basic) : TEMPLATENAME##_double_int_basic, (float,int,int) : TEMPLATENAME##_double_int_int, (float,int,float) : TEMPLATENAME##_double_int_double, (float,float,basic) : TEMPLATENAME##_double_double_basic, (float,float,int) : TEMPLATENAME##_double_double_int, (float,float,float) : TEMPLATENAME##_double_double_double} return func_hash[(xt,yt,zt)](x,y,z) %} %enddef %define DECLARE_FUNCTION_1P(NAME) class NAME##_SERIAL { public: static unsigned serial; }; const unsigned NAME##_NPARAMS = 1; template const GiNaC::function NAME(const T1 & p1) { return GiNaC::function(NAME##_SERIAL::serial, GiNaC::ex(p1)); } DECLARE_FUNCTION_1P_TEMPLATES(NAME) DECLARE_FUNCTION_1P_PYTHONCODE(NAME, NAME) %enddef %define DECLARE_FUNCTION_2P(NAME) class NAME##_SERIAL { public: static unsigned serial; }; const unsigned NAME##_NPARAMS = 2; template const GiNaC::function NAME(const T1 & p1, const T2 & p2) { return GiNaC::function(NAME##_SERIAL::serial, GiNaC::ex(p1), GiNaC::ex(p2)); } DECLARE_FUNCTION_2P_TEMPLATES(NAME) DECLARE_FUNCTION_2P_PYTHONCODE(NAME, NAME) %enddef %define DECLARE_FUNCTION_3P(NAME) class NAME##_SERIAL { public: static unsigned serial; }; const unsigned NAME##_NPARAMS = 3; template const GiNaC::function NAME(const T1 & p1, const T2 & p2, const T3 & p3) { return GiNaC::function(NAME##_SERIAL::serial, GiNaC::ex(p1), GiNaC::ex(p2), GiNaC::ex(p3)); } DECLARE_FUNCTION_3P_TEMPLATES(NAME) DECLARE_FUNCTION_3P_PYTHONCODE(NAME, NAME) %enddef DECLARE_FUNCTION_1P(conjugate_function) DECLARE_FUNCTION_1P(abs) DECLARE_FUNCTION_1P(csgn) DECLARE_FUNCTION_2P(eta) DECLARE_FUNCTION_1P(sin) DECLARE_FUNCTION_1P(cos) DECLARE_FUNCTION_1P(tan) DECLARE_FUNCTION_1P(exp) DECLARE_FUNCTION_1P(log) DECLARE_FUNCTION_1P(asin) DECLARE_FUNCTION_1P(acos) DECLARE_FUNCTION_1P(atan) DECLARE_FUNCTION_2P(atan2) DECLARE_FUNCTION_1P(sinh) DECLARE_FUNCTION_1P(cosh) DECLARE_FUNCTION_1P(tanh) DECLARE_FUNCTION_1P(asinh) DECLARE_FUNCTION_1P(acosh) DECLARE_FUNCTION_1P(atanh) DECLARE_FUNCTION_1P(Li2) DECLARE_FUNCTION_1P(Li3) DECLARE_FUNCTION_2P(zetaderiv) DECLARE_FUNCTION_2P(Li) DECLARE_FUNCTION_3P(S) DECLARE_FUNCTION_2P(H) DECLARE_FUNCTION_1P(lgamma) DECLARE_FUNCTION_1P(tgamma) DECLARE_FUNCTION_2P(beta) DECLARE_FUNCTION_1P(factorial) DECLARE_FUNCTION_2P(binomial) DECLARE_FUNCTION_1P(Order) /** Multiple zeta value including Riemann's zeta-function. */ class zeta1_SERIAL { public: static unsigned serial; }; template inline function zeta(const T1& p1) { return function(zeta1_SERIAL::serial, ex(p1)); } /** Alternating Euler sum or colored MZV. */ class zeta2_SERIAL { public: static unsigned serial; }; template inline function zeta(const T1& p1, const T2& p2) { return function(zeta2_SERIAL::serial, ex(p1), ex(p2)); } /* Since zeta() is overloaded, we first create separate Python functions for both versions, and then one that takes an arbitrary argument list and checks for the actual number of them. The same takes place for G and psi below.*/ DECLARE_FUNCTION_1P_TEMPLATES(zeta) DECLARE_FUNCTION_1P_PYTHONCODE(zeta1, zeta) DECLARE_FUNCTION_2P_TEMPLATES(zeta) DECLARE_FUNCTION_2P_PYTHONCODE(zeta2, zeta) %pythoncode %{ def zeta(*args): if len(args)==1: return zeta1(*args) elif len(args)==2: return zeta2(*args) else: raise "zeta() takes 1 or 2 arguments" %} /** Generalized multiple polylogarithm. */ class G2_SERIAL { public: static unsigned serial; }; template inline function G(const T1& x, const T2& y) { return function(G2_SERIAL::serial, ex(x), ex(y)); } /** Generalized multiple polylogarithm with explicit imaginary parts. */ class G3_SERIAL { public: static unsigned serial; }; template inline function G(const T1& x, const T2& s, const T3& y) { return function(G3_SERIAL::serial, ex(x), ex(s), ex(y)); } DECLARE_FUNCTION_2P_TEMPLATES(G) DECLARE_FUNCTION_2P_PYTHONCODE(G2, G) DECLARE_FUNCTION_3P_TEMPLATES(G) DECLARE_FUNCTION_3P_PYTHONCODE(G3, G) %pythoncode %{ def G(*args): if len(args)==2: return G2(*args) elif len(args)==3: return G3(*args) else: raise "G() takes 2 or 3 arguments" %} /** Psi-function (aka digamma-function). */ class psi1_SERIAL { public: static unsigned serial; }; template inline function psi(const T1 & p1) { return function(psi1_SERIAL::serial, ex(p1)); } /** Derivatives of Psi-function (aka polygamma-functions). */ class psi2_SERIAL { public: static unsigned serial; }; template inline function psi(const T1 & p1, const T2 & p2) { return function(psi2_SERIAL::serial, ex(p1), ex(p2)); } DECLARE_FUNCTION_1P_TEMPLATES(psi) DECLARE_FUNCTION_1P_PYTHONCODE(psi1, psi) DECLARE_FUNCTION_2P_TEMPLATES(psi) DECLARE_FUNCTION_2P_PYTHONCODE(psi2, psi) %pythoncode %{ def psi(*args): if len(args)==1: return psi1(*args) elif len(args)==2: return psi2(*args) else: raise "psi() takes 1 or 2 arguments" %} ex lsolve(const ex &eqns, const ex &symbols, unsigned options = solve_algo::automatic); // vim:ft=cpp: swiginac-1.5.1.1/src/swiginac/archive.i0000644000175100017520000000715610756525553020104 0ustar skavhaugskavhaug/* (c) Copyright 2008 Author: Ola Skavhaug This file is part of swiginac. swiginac is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. swiginac is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with swiginac; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ class archive; typedef unsigned archive_node_id; typedef unsigned archive_atom; class archive_node { //friend std::ostream &operator<<(std::ostream &os, const archive_node &ar); //friend std::istream &operator>>(std::istream &is, archive_node &ar); public: archive_node() : a(*dummy_ar_creator()), has_expression(false) {} // hack for cint which always requires a default constructor archive_node(archive &ar) : a(ar), has_expression(false) {} archive_node(archive &ar, const ex &expr); //const archive_node &operator=(const archive_node &other); void add_bool(const std::string &name, bool value); void add_unsigned(const std::string &name, unsigned value); void add_string(const std::string &name, const std::string &value); void add_ex(const std::string &name, const ex &value); bool find_bool(const std::string &name, bool &ret, unsigned index = 0) const; bool find_unsigned(const std::string &name, unsigned &ret, unsigned index = 0) const; bool find_string(const std::string &name, std::string &ret, unsigned index = 0) const; bool find_ex(const std::string &name, ex &ret, lst &sym_lst, unsigned index = 0) const; const archive_node &find_ex_node(const std::string &name, unsigned index = 0) const; ex unarchive(lst &sym_lst) const; bool has_same_ex_as(const archive_node &other) const; bool has_ex() const; ex get_ex() const; void forget(); void printraw(std::ostream &os) const; }; class archive { friend std::ostream &operator<<(std::ostream &os, const archive &ar); friend std::istream &operator>>(std::istream &is, archive &ar); public: archive() {} ~archive() {} archive(const ex &e) {archive_ex(e, "ex");} archive(const ex &e, const char *n) {archive_ex(e, n);} void archive_ex(const ex &e, const char *name); ex unarchive_ex(const lst &sym_lst, const char *name) const; ex unarchive_ex(const lst &sym_lst, unsigned index = 0) const; ex unarchive_ex(const lst &sym_lst, std::string &name, unsigned index = 0) const; unsigned num_expressions() const; const archive_node &get_top_node(unsigned index = 0) const; void clear(); archive_node_id add_node(const archive_node &n); archive_node &get_node(archive_node_id id); void forget(); void printraw(std::ostream &os) const; public: archive_atom atomize(const std::string &s) const; const std::string &unatomize(archive_atom id) const; }; std::ostream &operator<<(std::ostream &os, const archive &ar); std::istream &operator>>(std::istream &is, archive &ar); %extend archive { %{ #include %} void load(std::string filename) { std::ifstream infile(filename.c_str()); infile >> *self; } void dump(std::string filename) { std::ofstream outfile(filename.c_str()); outfile << *self; //*self >> outfile; } } swiginac-1.5.1.1/src/swiginac/flags.i0000644000175100017520000000357510334172146017544 0ustar skavhaugskavhaug/* (c) Copyright 2003, 2004, 2005 Author: Ola Skavhaug and Ondrej Certik This file is part of swiginac. swiginac is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. swiginac is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with swiginac; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ class expand_options { public: enum { expand_indexed = 0x0001, expand_function_args = 0x0002 }; }; class subs_options { public: enum { no_pattern = 0x0001, subs_no_pattern = 0x0001, algebraic = 0x0002, subs_algebraic = 0x0002, pattern_is_product = 0x0004, pattern_is_not_product = 0x0008 }; }; class determinant_algo { public: enum { automatic, gauss, divfree, laplace, bareiss }; }; class info_flags { public: enum { numeric, real, rational, integer, crational, cinteger, positive, negative, nonnegative, posint, negint, nonnegint, even, odd, prime, relation, relation_equal, relation_not_equal, relation_less, relation_less_or_equal, relation_greater, relation_greater_or_equal, symbol, list, exprseq, polynomial, integer_polynomial, cinteger_polynomial, rational_polynomial, crational_polynomial, rational_function, algebraic, indexed, has_indices, idx }; }; // vim:ft=cpp: swiginac-1.5.1.1/src/swiginac/constant.i0000644000175100017520000000245110361766243020300 0ustar skavhaugskavhaug/* (c) Copyright 2003, 2004, 2005 Author: Ola Skavhaug and Ondrej Certik This file is part of swiginac. swiginac is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. swiginac is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with swiginac; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ class constant : public basic { public: constant(); constant(const std::string & initname, evalffunctype efun = 0, const std::string & texname = std::string()); constant(const std::string & initname, const numeric & initnumber, const std::string & texname = std::string()); }; extern const constant Pi; extern const constant Catalan; extern const constant Euler; extern const numeric I; %pythoncode %{ Pi=cvar.Pi I=cvar.I %} // vim:ft=cpp: swiginac-1.5.1.1/src/swiginac/ncmul.i0000644000175100017520000000255110334172146017557 0ustar skavhaugskavhaug/* (c) Copyright 2003, 2004, 2005 Author: Ola Skavhaug and Ondrej Certik This file is part of swiginac. swiginac is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. swiginac is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with swiginac; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ //class ncmul : public exprseq class ncmul : public basic { public: ncmul(const ex & lh, const ex & rh); ncmul(const ex & f1, const ex & f2, const ex & f3); ncmul(const ex & f1, const ex & f2, const ex & f3, const ex & f4); ncmul(const ex & f1, const ex & f2, const ex & f3, const ex & f4, const ex & f5); ncmul(const ex & f1, const ex & f2, const ex & f3, const ex & f4, const ex & f5, const ex & f6); // ncmul(const exvector & v, bool discardable=false); // ncmul(std::auto_ptr vp); }; // vim:ft=cpp: swiginac-1.5.1.1/src/swiginac/wildcard.i0000644000175100017520000000203510361766243020236 0ustar skavhaugskavhaug/* (c) Copyright 2003, 2004, 2005 Author: Ola Skavhaug and Ondrej Certik This file is part of swiginac. swiginac is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. swiginac is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with swiginac; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ class wildcard : public basic { public: wildcard(); wildcard(unsigned label); unsigned get_label() const {return label;} }; ex wild(unsigned label = 0); bool haswild(const ex & x); // vim:ft=cpp: swiginac-1.5.1.1/src/swiginac/matrix.i0000644000175100017520000000715110667472766017772 0ustar skavhaugskavhaug/* (c) Copyright 2003, 2004, 2005 Author: Ola Skavhaug and Ondrej Certik This file is part of swiginac. swiginac is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. swiginac is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with swiginac; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ /** Symbolic matrices. */ class matrix : public basic { public: matrix(unsigned r, unsigned c); //matrix(unsigned r, unsigned c, const exvector & m2); matrix(unsigned r, unsigned c, const lst & l); //matrix(const lst & l); ex eval_indexed(const basic & i) const; ex add_indexed(const ex & self, const ex & other) const; ex scalar_mul_indexed(const ex & self, const numeric & other) const; bool contract_with(exvector::iterator self, exvector::iterator other, exvector & v) const; unsigned rows() const; unsigned cols() const; matrix add(const matrix & other) const; matrix sub(const matrix & other) const; matrix mul(const matrix & other) const; matrix mul(const numeric & other) const; matrix mul_scalar(const ex & other) const; matrix pow(const ex & expn) const; const ex & operator() (unsigned ro, unsigned co) const; ex & operator() (unsigned ro, unsigned co); matrix & set(unsigned ro, unsigned co, const ex & value) { (*this)(ro, co) = value; return *this; } matrix transpose() const; ex determinant(unsigned algo = determinant_algo::automatic) const; ex trace() const; ex charpoly(const ex & lambda) const; matrix inverse() const throw(std::runtime_error); matrix solve(const matrix & vars, const matrix & rhs, unsigned algo = solve_algo::automatic) const; unsigned rank() const; %extend { matrix(const lst & l) { matrix *m = new matrix(ex_to(lst_to_matrix(l))); return m; } int __len__() { return self->nops(); } void __setitem__(int idx0, int idx1, ex &e) { (*self)(idx0, idx1) = e; } ex __getitem__(int idx0, int idx1) { return (*self)(idx0, idx1); } } }; %pythoncode %{ def matrix2(x): return lst_to_matrix(x) %} inline size_t nops(const matrix & m); //inline ex expand(const matrix & m, unsigned options = 0); inline ex eval(const matrix & m, int level = 0); inline ex evalf(const matrix & m, int level = 0); inline unsigned rows(const matrix & m); inline unsigned cols(const matrix & m); inline matrix transpose(const matrix & m); inline ex determinant(const matrix & m, unsigned options = determinant_algo::automatic); inline ex trace(const matrix & m); inline ex charpoly(const matrix & m, const ex & lambda); inline matrix inverse(const matrix & m); inline unsigned rank(const matrix & m); /** Specialization of is_exactly_a(obj) for matrix objects. */ template<> inline bool is_exactly_a(const basic & obj); extern ex lst_to_matrix(const lst & l); extern ex diag_matrix(const lst & l); extern ex unit_matrix(unsigned r, unsigned c); inline ex unit_matrix(unsigned x); extern ex symbolic_matrix(unsigned r, unsigned c, const std::string & base_name, const std::string & tex_base_name); inline ex symbolic_matrix(unsigned r, unsigned c, const std::string & base_name); // vim:ft=cpp: swiginac-1.5.1.1/src/swiginac/registrar.i0000644000175100017520000000235211171051565020443 0ustar skavhaugskavhaug class ex; class archive_node; template