[PATCH] Better formatting for examples.

2 views
Skip to first unread message

andy....@gmail.com

unread,
Nov 19, 2008, 5:55:29 PM11/19/08
to sympy-...@googlegroups.com, Andy R. Terrel
From: Andy R. Terrel <ate...@uchicago.edu>

---
examples/advanced/fem.py | 66 ++++++++++++++----
examples/advanced/fem_test.py | 40 -----------
examples/advanced/gibbs_phenomenon.py | 57 ++++++++-------
examples/advanced/pidigits.py | 14 +++-
examples/advanced/plotting.py | 8 +-
examples/advanced/qft.py | 109 +++++++++++++++--------------
examples/advanced/relativity.py | 30 ++++++++-
examples/advanced/tensors.py | 69 ++++++++++---------
examples/all.py | 116 +++++++++++++++++++++++++++++++
examples/beginner/basic.py | 21 ++++--
examples/beginner/differentiation.py | 27 +++++---
examples/beginner/expansion.py | 22 ++++--
examples/beginner/functions.py | 28 +++++---
examples/beginner/limits_examples.py | 46 ++++++++----
examples/beginner/plotting_nice_plot.py | 16 ++++-
examples/beginner/precision.py | 14 +++-
examples/beginner/print_pretty.py | 49 +++++++------
examples/beginner/series.py | 26 +++++---
examples/beginner/substitution.py | 32 ++++++---
examples/iam_sympy_example.py | 12 ---
examples/intermediate/mplot2d.py | 13 +++-
examples/intermediate/mplot3d.py | 13 +++-
examples/intermediate/print_gtk.py | 19 +++--
examples/intermediate/trees.py | 14 ++--
examples/intermediate/vandermonde.py | 42 +++++++-----
25 files changed, 587 insertions(+), 316 deletions(-)
delete mode 100755 examples/advanced/fem_test.py
create mode 100755 examples/all.py
delete mode 100644 examples/iam_sympy_example.py

diff --git a/examples/advanced/fem.py b/examples/advanced/fem.py
index aad5d32..ceab838 100644
--- a/examples/advanced/fem.py
+++ b/examples/advanced/fem.py
@@ -1,5 +1,19 @@
+"""FEM library
+
+Demonstrates some simple finite element definitions, and computes a mass matrix
+
+$ python fem_test.py
+[ 1/60, 0, -1/360, 0, -1/90, -1/360]
+[ 0, 4/45, 0, 2/45, 2/45, -1/90]
+[-1/360, 0, 1/60, -1/90, 0, -1/360]
+[ 0, 2/45, -1/90, 4/45, 2/45, 0]
+[ -1/90, 2/45, 0, 2/45, 4/45, 0]
+[-1/360, -1/90, -1/360, 0, 0, 1/60]
+
+"""
+
from sympy import symbols, Symbol, factorial, Rational, zeros, div, eye, \
- integrate
+ integrate, diff, pprint

x, y, z = symbols('x y z')

@@ -43,10 +57,8 @@ def bernstein_space(order, nsd):
for o2 in range(0,order+1):
if o1 + o2 == order:
aij = Symbol("a_%d_%d" % (o1,o2))
- sum += aij*binomial(order,o1)*pow(b1, o1)*pow(b2,
-o2)
- basis.append(binomial(order,o1)*pow(b1,
-o1)*pow(b2, o2))
+ sum += aij*binomial(order,o1)*pow(b1, o1)*pow(b2, o2)
+ basis.append(binomial(order,o1)*pow(b1, o1)*pow(b2, o2))
coeff.append(aij)


@@ -57,11 +69,9 @@ o1)*pow(b2, o2))
for o3 in range(0,order+1):
if o1 + o2 + o3 == order:
aij = Symbol("a_%d_%d_%d" % (o1,o2,o3))
- fac = factorial(order)/ (factorial(o1)*factorial(o2)*factorial(o3))
- sum += aij*fac*pow(b1, o1)*pow(b2, o2)*pow(b3,
-o3)
- basis.append(fac*pow(b1, o1)*pow(b2,
-o2)*pow(b3, o3))
+ fac = factorial(order) / (factorial(o1)*factorial(o2)*factorial(o3))
+ sum += aij*fac*pow(b1, o1)*pow(b2, o2)*pow(b3, o3)
+ basis.append(fac*pow(b1, o1)*pow(b2, o2)*pow(b3, o3))
coeff.append(aij)

if nsd == 3:
@@ -71,12 +81,10 @@ o2)*pow(b3, o3))
for o3 in range(0,order+1):
for o4 in range(0,order+1):
if o1 + o2 + o3 + o4 == order:
- aij = Symbol("a_%d_%d_%d_%d" %
-(o1,o2,o3,o4))
+ aij = Symbol("a_%d_%d_%d_%d" % (o1,o2,o3,o4))
fac = factorial(order)/ (factorial(o1)*factorial(o2)*factorial(o3)*factorial(o4))
sum += aij*fac*pow(b1, o1)*pow(b2, o2)*pow(b3, o3)*pow(b4, o4)
- basis.append(fac*pow(b1, o1)*pow(b2,
-o2)*pow(b3, o3)*pow(b4, o4))
+ basis.append(fac*pow(b1, o1)*pow(b2, o2)*pow(b3, o3)*pow(b4, o4))
coeff.append(aij)


@@ -166,3 +174,33 @@ class Lagrange:
N.append(Ni)

self.N = N
+
+
+def main():
+ t = ReferenceSimplex(2)
+ fe = Lagrange(2,2)
+
+ u = 0
+ #compute u = sum_i u_i N_i
+ us = []
+ for i in range(0, fe.nbf()):
+ ui = Symbol("u_%d" % i)
+ us.append(ui)
+ u += ui*fe.N[i]
+
+
+ J = zeros(fe.nbf())
+ for i in range(0, fe.nbf()):
+ Fi = u*fe.N[i]
+ print Fi
+ for j in range(0, fe.nbf()):
+ uj = us[j]
+ integrands = diff(Fi, uj)
+ print integrands
+ J[j,i] = t.integrate(integrands)
+
+ pprint(J)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/examples/advanced/fem_test.py b/examples/advanced/fem_test.py
deleted file mode 100755
index ba68f66..0000000
--- a/examples/advanced/fem_test.py
+++ /dev/null
@@ -1,40 +0,0 @@
-#!/usr/bin/env python
-import iam_sympy_example
-
-"""
-Go to the sympy root directory and execute:
-
-$ python examples/fem_test.py
-[ 1/60, 0, -1/360, 0, -1/90, -1/360]
-[ 0, 4/45, 0, 2/45, 2/45, -1/90]
-[-1/360, 0, 1/60, -1/90, 0, -1/360]
-[ 0, 2/45, -1/90, 4/45, 2/45, 0]
-[ -1/90, 2/45, 0, 2/45, 4/45, 0]
-[-1/360, -1/90, -1/360, 0, 0, 1/60]
-"""
-
-from sympy import Symbol, zeros, diff, pprint
-from fem import ReferenceSimplex, Lagrange
-
-t = ReferenceSimplex(2)
-fe = Lagrange(2,2)
-
-u = 0
-#compute u = sum_i u_i N_i
-us = []
-for i in range(0, fe.nbf()):
- ui = Symbol("u_%d" % i)
- us.append(ui)
- u += ui*fe.N[i]
-
-
-J = zeros(fe.nbf())
-for i in range(0, fe.nbf()):
- Fi = u*fe.N[i]
- for j in range(0, fe.nbf()):
- uj = us[j]
- integrands = diff(Fi, uj)
- J[j,i] = t.integrate(integrands)
-
-
-pprint(J)
diff --git a/examples/advanced/gibbs_phenomenon.py b/examples/advanced/gibbs_phenomenon.py
index 64f8c02..e12a074 100755
--- a/examples/advanced/gibbs_phenomenon.py
+++ b/examples/advanced/gibbs_phenomenon.py
@@ -8,9 +8,10 @@ It also calculates the Wilbraham-Gibbs constant by two approaches:
1) calculating the fourier series of the step function and determining the
first maximum.
2) evaluating the integral for si(pi).
-"""

-import iam_sympy_example
+See:
+ * http://en.wikipedia.org/wiki/Gibbs_phenomena
+"""

from sympy import var, sqrt, integrate, conjugate, seterr, abs, pprint, I, pi,\
sin, cos, sign, Plot, msolve, lambdify, Integral, S
@@ -70,24 +71,15 @@ def l2_gram_schmidt(list, lim):
r.append(v/v_norm)
return r

-#l = l2_gram_schmidt([1, cos(x), sin(x), cos(2*x), sin(2*x)], (x, -pi, pi))
-#l = l2_gram_schmidt([1, cos(x), sin(x)], (x, -pi, pi))
-# the code below is equivalen to l2_gram_schmidt(), but faster:
-l = [1/sqrt(2)]
-for i in range(1, 100):
- l.append(cos(i*x))
- l.append(sin(i*x))
-l = [f/sqrt(pi) for f in l]
-
def integ(f):
return integrate(f, (x, -pi, 0)) + integrate(-f, (x, 0, pi))

-def series(l):
+def series(L):
"""
Normalizes the series.
"""
r = 0
- for b in l:
+ for b in L:
r += integ(b)*b
return r

@@ -116,16 +108,29 @@ def msolve(f, x):
x_min = x0
return x0

-f = series(l)
-print "Fourier series of the step function"
-pprint(f)
-#Plot(f.diff(x), [x, -5, 5, 3000])
-x0 = msolve(f.diff(x), x)
-
-print "x-value of the maximum:", x0
-max = f.subs(x, x0).evalf()
-print "y-value of the maximum:", max
-g = max*pi/2
-print "Wilbraham-Gibbs constant :", g.evalf()
-print "Wilbraham-Gibbs constant (exact):", \
- Integral(sin(x)/x, (x, 0, pi)).evalf()
+def main():
+ #L = l2_gram_schmidt([1, cos(x), sin(x), cos(2*x), sin(2*x)], (x, -pi, pi))
+ #L = l2_gram_schmidt([1, cos(x), sin(x)], (x, -pi, pi))
+ # the code below is equivalen to l2_gram_schmidt(), but faster:
+ L = [1/sqrt(2)]
+ for i in range(1, 100):
+ L.append(cos(i*x))
+ L.append(sin(i*x))
+ L = [f/sqrt(pi) for f in L]
+
+ f = series(L)
+ print "Fourier series of the step function"
+ pprint(f)
+ #Plot(f.diff(x), [x, -5, 5, 3000])
+ x0 = msolve(f.diff(x), x)
+
+ print "x-value of the maximum:", x0
+ max = f.subs(x, x0).evalf()
+ print "y-value of the maximum:", max
+ g = max*pi/2
+ print "Wilbraham-Gibbs constant :", g.evalf()
+ print "Wilbraham-Gibbs constant (exact):", \
+ Integral(sin(x)/x, (x, 0, pi)).evalf()
+
+if __name__ == "__main__":
+ main()
diff --git a/examples/advanced/pidigits.py b/examples/advanced/pidigits.py
index 5c6b793..60b59ca 100755
--- a/examples/advanced/pidigits.py
+++ b/examples/advanced/pidigits.py
@@ -1,5 +1,8 @@
#!/usr/bin/env python
-import iam_sympy_example
+"""Pi digits example
+
+Example shows the computation of the digits of pi.
+"""

#from sympy.numerics import *
#from sympy.numerics.utils_ import *
@@ -68,4 +71,11 @@ def interactive():
calculateit(pi_float, base, digits, tofile)
raw_input("\nPress enter to close this script.")

-interactive()
+def main():
+ base = 10
+ digits = 10000
+ tofile = None
+ calculateit(pi_float, base, digits, tofile)
+
+if __name__ == "__main__":
+ interactive()
diff --git a/examples/advanced/plotting.py b/examples/advanced/plotting.py
index ca2b8d4..7d98794 100755
--- a/examples/advanced/plotting.py
+++ b/examples/advanced/plotting.py
@@ -1,6 +1,4 @@
#!/usr/bin/env python
-import iam_sympy_example
-
"""
Plotting Examples

@@ -17,8 +15,7 @@ from sympy import sin, cos, pi, sqrt, exp

from time import sleep, clock

-if __name__ == "__main__":
-
+def main():
x,y,z = symbols('xyz')

# toggle axes visibility with F5, colors with F6
@@ -219,3 +216,6 @@ if __name__ == "__main__":
#cProfile.run("p.append(x**2+y**2)", 'plot.profile2')
#s = Stats('plot.profile2')
#s.sort_stats('cumulative').print_stats(20)
+
+if __name__ == "__main__":
+ main()
diff --git a/examples/advanced/qft.py b/examples/advanced/qft.py
index 36f6269..9586ecd 100755
--- a/examples/advanced/qft.py
+++ b/examples/advanced/qft.py
@@ -1,5 +1,8 @@
#!/usr/bin/env python
-import iam_sympy_example
+"""Quantum field theory example
+
+* http://en.wikipedia.org/wiki/Quantum_field_theory
+"""

from sympy import Basic,exp,Symbol,sin,Rational,I,Mul, Matrix, \
ones, sqrt, pprint, simplify, trim, Eq, sympify
@@ -59,63 +62,67 @@ def Tr(M):
t+=M[i,i]
return t

-a=Symbol("a", real=True)
-b=Symbol("b", real=True)
-c=Symbol("c", real=True)
+def xprint(lhs, rhs):
+ pprint( Eq(sympify(lhs), rhs ) )

-p = (a,b,c)
+def main():
+ a=Symbol("a", real=True)
+ b=Symbol("b", real=True)
+ c=Symbol("c", real=True)

-assert u(p, 1).D * u(p, 2) == Matrix(1, 1, [0])
-assert u(p, 2).D * u(p, 1) == Matrix(1, 1, [0])
+ p = (a,b,c)

-p1,p2,p3 =[Symbol(x, real=True) for x in ["p1","p2","p3"]]
-pp1,pp2,pp3 =[Symbol(x, real=True) for x in ["pp1","pp2","pp3"]]
-k1,k2,k3 =[Symbol(x, real=True) for x in ["k1","k2","k3"]]
-kp1,kp2,kp3 =[Symbol(x, real=True) for x in ["kp1","kp2","kp3"]]
+ assert u(p, 1).D * u(p, 2) == Matrix(1, 1, [0])
+ assert u(p, 2).D * u(p, 1) == Matrix(1, 1, [0])

-p = (p1,p2,p3)
-pp = (pp1,pp2,pp3)
+ p1,p2,p3 =[Symbol(x, real=True) for x in ["p1","p2","p3"]]
+ pp1,pp2,pp3 =[Symbol(x, real=True) for x in ["pp1","pp2","pp3"]]
+ k1,k2,k3 =[Symbol(x, real=True) for x in ["k1","k2","k3"]]
+ kp1,kp2,kp3 =[Symbol(x, real=True) for x in ["kp1","kp2","kp3"]]

-k = (k1,k2,k3)
-kp = (kp1,kp2,kp3)
+ p = (p1,p2,p3)
+ pp = (pp1,pp2,pp3)

-mu = Symbol("mu")
+ k = (k1,k2,k3)
+ kp = (kp1,kp2,kp3)

-e = (pslash(p)+m*ones(4))*(pslash(k)-m*ones(4))
-f = pslash(p)+m*ones(4)
-g = pslash(p)-m*ones(4)
+ mu = Symbol("mu")

+ e = (pslash(p)+m*ones(4))*(pslash(k)-m*ones(4))
+ f = pslash(p)+m*ones(4)
+ g = pslash(p)-m*ones(4)

-def xprint(lhs, rhs):
- pprint( Eq(sympify(lhs), rhs ) )

-#pprint(e)
-xprint( 'Tr(f*g)', Tr(f*g) )
-#print Tr(pslash(p) * pslash(k)).expand()
-
-M0 = [ ( v(pp, 1).D * mgamma(mu) * u(p, 1) ) * ( u(k, 1).D * mgamma(mu,True) * \
- v(kp, 1) ) for mu in range(4)]
-M = M0[0]+M0[1]+M0[2]+M0[3]
-M = M[0]
-assert isinstance(M, Basic)
-#print M
-#print trim(M)
-
-d=Symbol("d", real=True) #d=E+m
-
-xprint('M', M)
-print "-"*40
-M = ((M.subs(E,d-m)).expand() * d**2 ).expand()
-xprint('M2', 1/(E+m)**2 * M)
-print "-"*40
-x,y= M.as_real_imag()
-xprint('Re(M)', x)
-xprint('Im(M)', y)
-e = x**2+y**2
-xprint('abs(M)**2', e)
-print "-"*40
-xprint('Expand(abs(M)**2)', e.expand())
-
-#print Pauli(1)*Pauli(1)
-#print Pauli(1)**2
-#print Pauli(1)*2*Pauli(1)
+ #pprint(e)
+ xprint( 'Tr(f*g)', Tr(f*g) )
+ #print Tr(pslash(p) * pslash(k)).expand()
+
+ M0 = [ ( v(pp, 1).D * mgamma(mu) * u(p, 1) ) * ( u(k, 1).D * mgamma(mu,True) * \
+ v(kp, 1) ) for mu in range(4)]
+ M = M0[0]+M0[1]+M0[2]+M0[3]
+ M = M[0]
+ assert isinstance(M, Basic)
+ #print M
+ #print trim(M)
+
+ d=Symbol("d", real=True) #d=E+m
+
+ xprint('M', M)
+ print "-"*40
+ M = ((M.subs(E,d-m)).expand() * d**2 ).expand()
+ xprint('M2', 1/(E+m)**2 * M)
+ print "-"*40
+ x,y= M.as_real_imag()
+ xprint('Re(M)', x)
+ xprint('Im(M)', y)
+ e = x**2+y**2
+ xprint('abs(M)**2', e)
+ print "-"*40
+ xprint('Expand(abs(M)**2)', e.expand())
+
+ #print Pauli(1)*Pauli(1)
+ #print Pauli(1)**2
+ #print Pauli(1)*2*Pauli(1)
+
+if __name__ == "__main__":
+ main()
diff --git a/examples/advanced/relativity.py b/examples/advanced/relativity.py
index f884ed2..12d43da 100755
--- a/examples/advanced/relativity.py
+++ b/examples/advanced/relativity.py
@@ -1,5 +1,4 @@
#!/usr/bin/env python
-import iam_sympy_example

"""
This example calculates the Ricci tensor from the metric and does this
@@ -139,6 +138,35 @@ def pprint_Gamma_udd(i,k,l):
def pprint_Rmn_dd(i,j):
pprint( Eq(Symbol('R_%i%i' % (i,j)), Rmn.dd(i,j)) )

+
+# from Differential Equations example
+def eq1():
+ r = Symbol("r")
+ e = Rmn.dd(0,0)
+ e = e.subs(nu(r), -lam(r))
+ print dsolve(e, [lam(r)])
+
+def eq2():
+ r = Symbol("r")
+ e = Rmn.dd(1,1)
+ C = Symbol("CC")
+ e = e.subs(nu(r), -lam(r))
+ print dsolve(e, [lam(r)])
+
+def eq3():
+ r = Symbol("r")
+ e = Rmn.dd(2,2)
+ e = e.subs(nu(r), -lam(r))
+ print dsolve(e, [lam(r)])
+
+def eq4():
+ r = Symbol("r")
+ e = Rmn.dd(3,3)
+ e = e.subs(nu(r), -lam(r))
+ print dsolve(e, [lam(r)])
+
+
+
def main():

print "Initial metric:"
diff --git a/examples/advanced/tensors.py b/examples/advanced/tensors.py
index 4eda747..71d8d8d 100755
--- a/examples/advanced/tensors.py
+++ b/examples/advanced/tensors.py
@@ -1,7 +1,6 @@
#!/usr/bin/env python
-import iam_sympy_example
+""" Tensor example

-"""
http://www.lncc.br/~portugal/Canon.html
http://www.lncc.br/~portugal/Invar.html
http://www.ginac.de/tutorial/Indexed-objects.html
@@ -50,34 +49,38 @@ class Idx(Symbol):
def values(self):
return range(self._dim)

-t=Symbol("t")
-r=Symbol("r")
-theta=Symbol(r"\theta")
-phi=Symbol(r"\phi")
-
-class nu(Function):
- pass
-class lam(Function):
- pass
-
-gdd=Matrix((
- (-exp(nu(r)),0,0,0),
- (0, exp(lam(r)), 0, 0),
- (0, 0, r**2, 0),
- (0, 0, 0, r**2*sin(theta)**2)
- ))
-
-mu = Idx("mu")
-nu = Idx("mu")
-i = Idx("i")
-m = Idx("m")
-k = Idx("k")
-l = Idx("l")
-g = Indexed(Symbol("A"), [mu,nu])
-Chr = g[i.up, m.up]/2 * (g[m.dn, k.dn].diff(l.up) + g[m.dn,l.dn].diff(k.up) \
- - g[k.dn, l.dn].diff(m.up))
-#G = g.uu(i,m)/2 * (g.dd(m,k).diff(x[l])+g.dd(m,l).diff(x[k]) \
-# - g.dd(k,l).diff(x[m]))
-
-print g
-print Chr
+def main():
+ t=Symbol("t")
+ r=Symbol("r")
+ theta=Symbol(r"\theta")
+ phi=Symbol(r"\phi")
+
+ class nu(Function):
+ pass
+ class lam(Function):
+ pass
+
+ gdd=Matrix((
+ (-exp(nu(r)),0,0,0),
+ (0, exp(lam(r)), 0, 0),
+ (0, 0, r**2, 0),
+ (0, 0, 0, r**2*sin(theta)**2)
+ ))
+
+ mu = Idx("mu")
+ nu = Idx("mu")
+ i = Idx("i")
+ m = Idx("m")
+ k = Idx("k")
+ l = Idx("l")
+ g = Indexed(Symbol("A"), [mu,nu])
+ Chr = g[i.up, m.up]/2 * (g[m.dn, k.dn].diff(l.up) + g[m.dn,l.dn].diff(k.up) \
+ - g[k.dn, l.dn].diff(m.up))
+ #G = g.uu(i,m)/2 * (g.dd(m,k).diff(x[l])+g.dd(m,l).diff(x[k]) \
+ # - g.dd(k,l).diff(x[m]))
+
+ print g
+ print Chr
+
+if __name__ == "__main__":
+ main()
diff --git a/examples/all.py b/examples/all.py
new file mode 100755
index 0000000..4e1c80f
--- /dev/null
+++ b/examples/all.py
@@ -0,0 +1,116 @@
+#!/usr/bin/env python
+"""Runner script
+
+Runs all the known working examples.
+
+ Usage:
+
+ When all examples run:
+ $ ./all > out
+ $
+
+ When some examples fail:
+ $ ./all > out
+ Traceback (most recent call last):
+ File "./limits_examples.py", line 17, in ?
+ [...]
+ $
+
+ Obviously, we want to achieve the first result.
+"""
+
+import imp
+import os
+import sys
+import traceback
+
+WORKING_EXAMPLES = [
+ "beginner.basic",
+ "beginner.differentiation",
+ "beginner.expansion",
+ "beginner.functions",
+ "beginner.limits_examples",
+ #"beginner.plotting_nice_plot",
+ "beginner.precision",
+ "beginner.print_pretty",
+ "beginner.series",
+ "beginner.substitution",
+ "beginner.expansion",
+ #"intermediate.differential_equations",
+ #"intermediate.mplot2d",
+ #"intermediate.mplot3d",
+ #"intermediate.print_gtk",
+ "intermediate.trees",
+ "intermediate.vandermonde",
+ "advanced.fem",
+ "advanced.gibbs_phenomenon",
+ #"advanced.pidigits",
+ #"advanced.plotting",
+ #"advanced.qft",
+ "advanced.relativity",
+ #"advanced.tensors",
+ ]
+
+example_dir = os.path.dirname(__file__)
+example_modules = []
+
+def __import__(name, globals=None, locals=None, fromlist=None):
+ """An alternative to the import function so that we can import
+ modules defined as strings.
+
+ This code was taken from: http://docs.python.org/lib/examples-imp.html
+ """
+ # Fast path: see if the module has already been imported.
+ try:
+ return sys.modules[name]
+ except KeyError:
+ pass
+
+ # If any of the following calls raises an exception,
+ # there's a problem we can't handle -- let the caller handle it.
+ module_name = name.split('.')[-1]
+ module_path = os.path.join(example_dir, *name.split('.')[:-1])
+
+ fp, pathname, description = imp.find_module(module_name, [module_path])
+
+ try:
+ return imp.load_module(module_name, fp, pathname, description)
+ finally:
+ # Since we may exit via an exception, close fp explicitly.
+ if fp:
+ fp.close()
+
+def load_example_modules ():
+ """Loads modules based upon the given package name"""
+ global example_modules
+
+ for entry in WORKING_EXAMPLES:
+ mod = __import__(entry)
+ example_modules.append(mod)
+
+def setup_path ():
+ """Put example directories in the path to load easily"""
+ sys.path.insert(0,example_dir)
+
+def run_examples():
+ success = []
+ fail = []
+ for mod in example_modules:
+ print "="*79
+ print "Running: ", mod.__name__
+ try:
+ mod.main()
+ success.append(mod.__name__)
+ except:
+ traceback.print_exc()
+ fail.append(mod.__name__)
+ print "SUCCESS: ", success
+ print "FAIL: ", fail
+
+def main (*args, **kws):
+ setup_path()
+ load_example_modules()
+ run_examples()
+
+if __name__ == "__main__":
+ main(*sys.argv[1:])
diff --git a/examples/beginner/basic.py b/examples/beginner/basic.py
index 11dae75..5a51544 100755
--- a/examples/beginner/basic.py
+++ b/examples/beginner/basic.py
@@ -1,9 +1,18 @@
#!/usr/bin/env python
-import iam_sympy_example
+"""Basic example
+
+Demonstrates how to create symbols and print some algebra operations.
+"""

import sympy
-a=sympy.Symbol('a')
-b=sympy.Symbol('b')
-c=sympy.Symbol('c')
-e=( a*b*b+2*b*a*b )**c
-print e
+
+def main():
+ a = sympy.Symbol('a')
+ b = sympy.Symbol('b')
+ c = sympy.Symbol('c')
+ e = ( a*b*b + 2*b*a*b )**c
+
+ print e
+
+if __name__ == "__main__":
+ main()
diff --git a/examples/beginner/differentiation.py b/examples/beginner/differentiation.py
index 4ddb533..bcc1b80 100755
--- a/examples/beginner/differentiation.py
+++ b/examples/beginner/differentiation.py
@@ -1,12 +1,21 @@
#!/usr/bin/env python
-import iam_sympy_example
+"""Differentiation example
+
+Demonstrates some differentiation operations.
+"""

import sympy
-a=sympy.Symbol('a')
-b=sympy.Symbol('b')
-e=(a+2*b)**5
-print e
-print e.diff(a)
-print e.diff(b)
-print e.diff(b).diff(a,3)
-print e.expand().diff(b).diff(a,3)
+
+def main():
+ a = sympy.Symbol('a')
+ b = sympy.Symbol('b')
+ e = (a + 2*b)**5
+
+ print e
+ print e.diff(a)
+ print e.diff(b)
+ print e.diff(b).diff(a, 3)
+ print e.expand().diff(b).diff(a, 3)
+
+if __name__ == "__main__":
+ main()
diff --git a/examples/beginner/expansion.py b/examples/beginner/expansion.py
index 1e56a29..297a838 100755
--- a/examples/beginner/expansion.py
+++ b/examples/beginner/expansion.py
@@ -1,9 +1,17 @@
-#!/usr/bin/env python
-import iam_sympy_example
+"""Expansion Example
+
+Demonstrates how to expand expressions.
+"""

import sympy
-a=sympy.Symbol('a')
-b=sympy.Symbol('b')
-e=(a+b)**5
-print e
-print e.expand()
+
+def main():
+ a = sympy.Symbol('a')
+ b = sympy.Symbol('b')
+ e = (a + b)**5
+
+ print e
+ print e.expand()
+
+if __name__ == "__main__":
+ main(*sys.argv[1:])
diff --git a/examples/beginner/functions.py b/examples/beginner/functions.py
index da12cad..35e7c45 100755
--- a/examples/beginner/functions.py
+++ b/examples/beginner/functions.py
@@ -1,12 +1,22 @@
#!/usr/bin/env python
-import iam_sympy_example
+"""Functions example
+
+Demonstrates sympy defined functions.
+"""

import sympy
-a=sympy.Symbol('a')
-b=sympy.Symbol('b')
-e=sympy.log((a+b)**5)
-print e
-e=sympy.exp(e)
-print e
-e=sympy.log(sympy.exp((a+b)**5))
-print e
+
+def main():
+ a = sympy.Symbol('a')
+ b = sympy.Symbol('b')
+ e = sympy.log((a + b)**5)
+ print e
+
+ e = sympy.exp(e)
+ print e
+
+ e = sympy.log(sympy.exp((a + b)**5))
+ print e
+
+if __name__ == "__main__":
+ main()
diff --git a/examples/beginner/limits_examples.py b/examples/beginner/limits_examples.py
index 7839451..26c0927 100755
--- a/examples/beginner/limits_examples.py
+++ b/examples/beginner/limits_examples.py
@@ -1,23 +1,37 @@
#!/usr/bin/env python
-import iam_sympy_example
+"""Limits Example

-from sympy import exp,log,Symbol,Rational,sin,limit, sqrt,oo
+Demonstrates limits.
+"""

-x=Symbol("x")
-a=Symbol("a")
-h=Symbol("h")
+from sympy import exp,log,Symbol,Rational,sin,limit, sqrt,oo

def sqrt3(x):
- return x**Rational(1,3)
+ return x**Rational(1, 3)

def show(computed, correct):
- print "computed:",computed,"correct:",correct
-
-show( limit(sqrt(x**2-5*x+6)-x,x,oo) , -Rational(5)/2 )
-#show( limit(x*(sqrt(x**2+1)-x),x,oo) , Rational(1)/2 )
-show( limit(x-sqrt3(x**3-1),x,oo) , Rational(0) )
-show( limit(log(1+exp(x))/x,x,-oo) , Rational(0) )
-show( limit(log(1+exp(x))/x,x,oo) , Rational(1) )
-show( limit(sin(3*x)/x,x,0) , Rational(3) )
-show( limit(sin(5*x)/sin(2*x),x,0) , Rational(5)/2 )
-#show( limit(((x-1)/(x+1))**x,x,oo) , exp(-2))
+ print "computed:", computed, "correct:", correct
+
+def main():
+ x = Symbol("x")
+ a = Symbol("a")
+ h = Symbol("h")
+
+ show( limit(sqrt(x**2 - 5*x + 6) - x, x, oo) , -Rational(5)/2 )
+
+ show( limit(x*(sqrt(x**2 + 1) - x), x, oo) , Rational(1)/2 )
+
+ show( limit(x - sqrt3(x**3 - 1), x, oo) , Rational(0) )
+
+ show( limit(log(1 + exp(x))/x, x, -oo) , Rational(0) )
+
+ show( limit(log(1 + exp(x))/x, x, oo) , Rational(1) )
+
+ show( limit(sin(3*x)/x, x, 0) , Rational(3) )
+
+ show( limit(sin(5*x)/sin(2*x), x, 0) , Rational(5)/2 )
+
+ show( limit(((x - 1)/(x + 1))**x, x, oo) , exp(-2))
+
+if __name__ == "__main__":
+ main()
diff --git a/examples/beginner/plotting_nice_plot.py b/examples/beginner/plotting_nice_plot.py
index 753ca6f..f2ff50a 100755
--- a/examples/beginner/plotting_nice_plot.py
+++ b/examples/beginner/plotting_nice_plot.py
@@ -1,8 +1,18 @@
#!/usr/bin/env python
-import iam_sympy_example
+"""Plotting example
+
+Demonstrates simple plotting.
+"""

from sympy import Symbol, cos, sin, Plot, log, tan
from sympy.abc import x, y

-Plot(cos(x)*sin(y), sin(x)*sin(y), cos(y)+log(tan(y/2))+0.2*x, [x, -0.00,
- 12.4, 40], [y, 0.1, 2, 40])
+def main():
+ fun1 = cos(x)*sin(y)
+ fun2 = sin(x)*sin(y)
+ fun3 = cos(y) + log(tan(y/2)) + 0.2*x
+
+ Plot(fun1, fun2, fun3, [x, -0.00, 12.4, 40], [y, 0.1, 2, 40])
+
+if __name__ == "__main__":
+ main()
diff --git a/examples/beginner/precision.py b/examples/beginner/precision.py
index 49baea1..f7b1f88 100755
--- a/examples/beginner/precision.py
+++ b/examples/beginner/precision.py
@@ -1,6 +1,14 @@
#!/usr/bin/env python
-import iam_sympy_example
+"""Precision Example
+
+Demonstrates SymPy's arbitrary precision abilities
+"""

import sympy
-e=sympy.Rational(2)**50/sympy.Rational(10)**50
-print e
+
+def main():
+ e = sympy.Rational(2)**50/sympy.Rational(10)**50
+ print e
+
+if __name__ == "__main__":
+ main()
diff --git a/examples/beginner/print_pretty.py b/examples/beginner/print_pretty.py
index bbf6646..3410a8e 100755
--- a/examples/beginner/print_pretty.py
+++ b/examples/beginner/print_pretty.py
@@ -1,36 +1,41 @@
#!/usr/bin/env python
-import iam_sympy_example
+"""Pretty print example

-from sympy import Symbol, pprint, sin, cos, exp, sqrt
+Demonstrates pretty printing.
+"""

-x=Symbol("x")
-y=Symbol("y")
+from sympy import Symbol, pprint, sin, cos, exp, sqrt

+def main():
+ x = Symbol("x")
+ y = Symbol("y")

-pprint( x**x )
-print '\n'# separate with two blank likes
+ pprint( x**x )
+ print '\n'# separate with two blank likes

-pprint(x**2+y+x)
-print '\n'
+ pprint(x**2 + y + x)
+ print '\n'

-pprint(sin(x)**x)
-print '\n'
+ pprint(sin(x)**x)
+ print '\n'

-pprint( sin(x)**cos(x) )
-print '\n'
+ pprint( sin(x)**cos(x) )
+ print '\n'

-pprint( sin(x)/(cos(x)**2 * x**x +(2*y)) )
-print '\n'
+ pprint( sin(x)/(cos(x)**2 * x**x + (2*y)) )
+ print '\n'

-pprint( sin(x**2+exp(x)) )
-print '\n'
+ pprint( sin(x**2 + exp(x)) )
+ print '\n'

-pprint( sqrt(exp(x)) )
-print '\n'
+ pprint( sqrt(exp(x)) )
+ print '\n'

-pprint( sqrt(sqrt(exp(x))) )
-print '\n'
+ pprint( sqrt(sqrt(exp(x))) )
+ print '\n'

-pprint( (1/cos(x)).series(x,0,10) )
-print '\n'
+ pprint( (1/cos(x)).series(x, 0, 10) )
+ print '\n'

+if __name__ == "__main__":
+ main()
diff --git a/examples/beginner/series.py b/examples/beginner/series.py
index 67dd17f..61778f2 100755
--- a/examples/beginner/series.py
+++ b/examples/beginner/series.py
@@ -1,14 +1,22 @@
#!/usr/bin/env python
-import iam_sympy_example
+"""Series example
+
+Demonstrates series.
+"""

from sympy import Symbol, cos, sin
-x=Symbol('x')

-e=1/cos(x)
-print "Series for sec(x):"
-print e.series(x,0,10)
-print ""
+def main():
+ x = Symbol('x')
+
+ e = 1/cos(x)
+ print "Series for sec(x):"
+ print e.series(x, 0, 10)
+ print ""
+
+ e = 1/sin(x)
+ print "Series for csc(x):"
+ print e.series(x, 0, 4)

-e=1/sin(x)
-print "Series for csc(x):"
-print e.series(x,0,4)
+if __name__ == "__main__":
+ main()
diff --git a/examples/beginner/substitution.py b/examples/beginner/substitution.py
index ba9dd39..b6516aa 100755
--- a/examples/beginner/substitution.py
+++ b/examples/beginner/substitution.py
@@ -1,14 +1,24 @@
#!/usr/bin/env python
-import iam_sympy_example
+"""Substitution example
+
+Demonstrates substitution.
+"""

import sympy
-x=sympy.Symbol('x')
-y=sympy.Symbol('y')
-e=1/sympy.cos(x)
-print e
-print e.subs(sympy.cos(x),y)
-print e.subs(sympy.cos(x),y).subs(y,x**2)
-e=1/sympy.log(x)
-e=e.subs(x,sympy.Real("2.71828"))
-print e
-print e.evalf()
+
+def main():
+ x = sympy.Symbol('x')
+ y = sympy.Symbol('y')
+
+ e = 1/sympy.cos(x)
+ print e
+ print e.subs(sympy.cos(x), y)
+ print e.subs(sympy.cos(x), y).subs(y, x**2)
+
+ e = 1/sympy.log(x)
+ e = e.subs(x, sympy.Real("2.71828"))
+ print e
+ print e.evalf()
+
+if __name__ == "__main__":
+ main()
diff --git a/examples/iam_sympy_example.py b/examples/iam_sympy_example.py
deleted file mode 100644
index 226e811..0000000
--- a/examples/iam_sympy_example.py
+++ /dev/null
@@ -1,12 +0,0 @@
-"""Module to make life easier for SymPy examples"""
-
-# hook in-tree sympy into python path if running example
-import sys
-import os.path
-my_dir = os.path.dirname(__file__) # examples/
-sympy_top = os.path.split(my_dir)[0] # ../
-sympy_dir = os.path.join(sympy_top, 'sympy') # ../sympy/
-if os.path.isdir(sympy_dir):
- #print 'working in-tree...'
- sys.path.insert(0, sympy_top)
-
diff --git a/examples/intermediate/mplot2d.py b/examples/intermediate/mplot2d.py
index d44c363..38d836e 100755
--- a/examples/intermediate/mplot2d.py
+++ b/examples/intermediate/mplot2d.py
@@ -1,8 +1,11 @@
#!/usr/bin/env python
-import iam_sympy_example
+"""Matplotlib 2D plotting example
+
+Demonstrates plotting with matplotlib.
+"""

-from sympy import Symbol, Basic
from sample import sample
+from sympy import Basic, log, pi, sqrt, sin, Symbol

def mplot2d(f, var, show=True):
"""
@@ -28,10 +31,12 @@ def mplot2d(f, var, show=True):
if show:
p.show()

-if __name__ == "__main__":
- from sympy import sqrt, sin, log, pi
+def main():
x = Symbol('x')

#mplot2d(log(x), (x, 0, 2, 100))
#mplot2d([sin(x), -sin(x)], (x, float(-2*pi), float(2*pi), 50))
mplot2d([sqrt(x), -sqrt(x), sqrt(-x), -sqrt(-x)], (x, -40.0, 40.0, 80))
+
+if __name__ == "__main__":
+ main()
diff --git a/examples/intermediate/mplot3d.py b/examples/intermediate/mplot3d.py
index a682b24..5bfc73c 100755
--- a/examples/intermediate/mplot3d.py
+++ b/examples/intermediate/mplot3d.py
@@ -1,7 +1,10 @@
#!/usr/bin/env python
-import iam_sympy_example
+"""Matplotlib 3D plotting example

-from sympy import Symbol, Basic
+Demonstrates plotting with matplotlib.
+"""
+
+from sympy import Basic, sin, Symbol
from sample import sample

def mplot3d(f, var1, var2, show=True):
@@ -33,11 +36,13 @@ def mplot3d(f, var1, var2, show=True):
if show:
p.show()

-if __name__ == "__main__":
- from sympy import sin
+def main():
x = Symbol('x')
y = Symbol('y')

mplot3d(x**2-y**2, (x, -10.0, 10.0, 20), (y, -10.0, 10.0, 20))
#mplot3d(x**2+y**2, (x, -10.0, 10.0, 20), (y, -10.0, 10.0, 20))
#mplot3d(sin(x)+sin(y), (x, -3.14, 3.14, 10), (y, -3.14, 3.14, 10))
+
+if __name__ == "__main__":
+ main()
diff --git a/examples/intermediate/print_gtk.py b/examples/intermediate/print_gtk.py
index b75b1f6..aca5ff9 100755
--- a/examples/intermediate/print_gtk.py
+++ b/examples/intermediate/print_gtk.py
@@ -1,15 +1,20 @@
#!/usr/bin/env python
-import iam_sympy_example
+"""print_gtk example

-"""examples for print_gtk. It prints in gtkmathview using mathml"""
+Demonstrates printing with gtkmathview using mathml
+"""

from sympy import Symbol, integrate, exp
from sympy.printing import print_gtk

-x = Symbol('x')
+def main():
+ x = Symbol('x')

-#l1 = limit(sin(x)/x, x, 0, evaluate=False)
-#print_gtk(l1)
+ #l1 = limit(sin(x)/x, x, 0, evaluate=False)
+ #print_gtk(l1)

-l2 = integrate(exp(x), (x,0,1), evaluate=False)
-print_gtk(l2)
+ l2 = integrate(exp(x), (x,0,1), evaluate=False)
+ print_gtk(l2)
+
+if __name__ == "__main__":
+ main()
diff --git a/examples/intermediate/trees.py b/examples/intermediate/trees.py
index a965731..929c44a 100755
--- a/examples/intermediate/trees.py
+++ b/examples/intermediate/trees.py
@@ -1,5 +1,4 @@
#!/usr/bin/env python
-import iam_sympy_example

from sympy import Symbol, Poly

@@ -10,10 +9,13 @@ def T(x):
def A(x):
return 1 + T(x) - T(x)**2/2 + T(x**2)/2

+def main():
+ x=Symbol("x")
+ s = Poly(A(x), x)
+ num = [s.coeff(n) for n in range(11)]

-x=Symbol("x")
-s = Poly(A(x), x)
-num = [s.coeff(n) for n in range(11)]
+ print s.as_basic()
+ print num

-print s.as_basic()
-print num
+if __name__ == "__main__":
+ main()
diff --git a/examples/intermediate/vandermonde.py b/examples/intermediate/vandermonde.py
index 201ed7d..b6e3116 100755
--- a/examples/intermediate/vandermonde.py
+++ b/examples/intermediate/vandermonde.py
@@ -1,22 +1,30 @@
#!/usr/bin/env python
-import iam_sympy_example
+"""Vandermonde matrix example
+
+Demonstrates matrix computations using the Vandermonde matrix.
+ * http://en.wikipedia.org/wiki/Vandermonde_matrix
+"""

from sympy import sqrt, symbols, eye

-w, x, y, z = symbols("wxyz")
-L = [x,y,z]
-V = eye(len(L))
-for i in range(len(L)):
- for j in range(len(L)):
- V[i,j] = L[i]**j
-det = 1
-for i in range(len(L)):
- det *= L[i]-L[i-1]
+def main():
+ w, x, y, z = symbols("wxyz")
+ L = [x,y,z]
+ V = eye(len(L))
+ for i in range(len(L)):
+ for j in range(len(L)):
+ V[i,j] = L[i]**j
+ det = 1
+ for i in range(len(L)):
+ det *= L[i]-L[i-1]
+
+ print "matrix"
+ print V
+ print "det:"
+ print V.det().expand()
+ print "correct result"
+ print det
+ print det.expand()

-print "matrix"
-print V
-print "det:"
-print V.det().expand()
-print "correct result"
-print det
-print det.expand()
+if __name__ == "__main__":
+ main()
--
1.6.0.3

Ondrej Certik

unread,
Nov 19, 2008, 7:44:12 PM11/19/08
to sympy-...@googlegroups.com
On Wed, Nov 19, 2008 at 11:55 PM, <andy....@gmail.com> wrote:
>
> From: Andy R. Terrel <ate...@uchicago.edu>


I checked it from your repo and it seems ok to me. +1

Ondrej

Reply all
Reply to author
Forward
0 new messages