def test_verify(): """ Verify that scalar, vectorized, F77, weave implementations give the same answer in a test problem. """ Lx = 10; Ly = 10; c = 1.0 def I(x, y): return exp(-pow(x-Lx/2.0,2)/2.0 -pow(y-Ly/2.0,2)/2.0) def f(x, y, t): return sin(2*x) + y def bc(x, y, t): return sin(t) # use string formulas instead so also weave can be tested: # (need to transfer globals() so that vectorized versions work) I = StringFunction('exp(-pow(x-Lx/2.0,2)/2.0 - pow(y-Ly/2.0,2)/2.0)', independent_variables=('x', 'y'), Lx=Lx, Ly=Ly, globals=globals()) f = StringFunction('sin(2*x) + y', independent_variables=('x', 'y', 't'), globals=globals()) bc = StringFunction('sin(t)', independent_variables=('x', 'y', 't'), globals=globals()) #nx = 15; ny = 10; tstop = 2 nx = 4; ny = 3; tstop = 16 verify_implementations(I, f, c, bc, Lx, Ly, nx, ny, tstop)
def benchmark(nx, tstop): """Initial Gaussian bell in the middle of the domain.""" Lx = 10 Ly = 10 c = 1.0 ny = nx # our use of weave requires string formulas: Is = StringFunction('exp(-pow(x-Lx/2.0,2)/2.0 -pow(y-Ly/2.0,2)/2.0)', independent_variables=('x','y'), Lx=Lx, Ly=Ly, globals=globals()) fs = StringFunction('0.0', independent_variables=('x', 'y', 't'), globals=globals()) BCs = StringFunction('0.0', independent_variables=('x', 'y', 't'), globals=globals()) def action(u, xv, yv, t): #print t pass implementation = {} cpu = [] for ic in 'f77', 'vec', 'scalar', 'weave': for bc in 'f77', 'vec', 'scalar', 'weave': for inner in 'f77', 'vec', 'scalar', 'weave': implementation['ic'] = ic implementation['inner'] = inner implementation['bc'] = bc # optimize StringFunction functions for the non-weave case: # implementation: if 'weave' in (ic, bc, inner) or 'f77' in (ic, bc, inner): I = Is; f = fs; BC = BCs else: I = Is.__call__; f = fs.__call__; BC = BCs.__call__ t0 = time.clock() dt, cpu_ic, cpu_inner, cpu_bc = \ solver(I, f, c, BC, Lx, Ly, nx, ny, 0, tstop, user_action=None, implementation=implementation, verbose=False) t1 = time.clock() cpu_total = cpu_ic + cpu_inner + cpu_bc overhead = (t1-t0)-cpu_total cpu.append([implementation.copy(), cpu_total, cpu_ic, cpu_inner, cpu_bc, overhead]) print t1-t0, implementation, 'overhead:', overhead # normalize CPU-times: cpu_min = min([abs(c) for i, c, c1, c2, c3, c4 in cpu]) print '\n\nMinimum CPU time:', cpu_min print 'no of time steps:', int(tstop/dt) print 'interior/boundary ratio:', int(nx*ny*1.0/max(nx,ny)) for impl, cpu, cpu_ic, cpu_inner, cpu_bc, overhead in cpu: # normalized-CPU ic inner bc overhead print "%8.2f" % (cpu/cpu_min), print "%-10s %8.2f; " % (impl['ic'], cpu_ic), print "%-10s %8.2f; " % (impl['inner'], cpu_inner), print "%-10s %8.2f; " % (impl['bc'], cpu_bc), print "%d%%" % (overhead/cpu*100)
def parsedesc(string): expr, rest = string.split(' is a function of ') var_and_params = rest.split(' with parameter ') func = StringFunction(expr, independent_variable=var_and_params[0]) if len(var_and_params) > 1: parameters = eval("dict(%s)" % var_and_params[1]) func.set_parameters(**parameters) return func
def test_plot1(plot=1, version='scalar'): """ Initial Gaussian bell in the middle of the domain. plot: 0 = no plot; 1 = on the screen, 2 = hardcopy too """ Lx = 10 Ly = 10 c = 1.0 def I2(x, y): return exp(-(x-Lx/2.0)**2/2.0 -(y-Ly/2.0)**2/2.0) def f(x, y, t): return 0.0 def bc(x, y, t): return 0.0 I2 = StringFunction('exp(-(x-Lx/2.0)**2/2.0 -(y-Ly/2.0)**2/2.0)', independent_variables=('x', 'y'), Lx=Lx, Ly=Ly, globals=globals()) f = StringFunction('0.0', independent_variables=('x', 'y', 't'), globals=globals()) bc = StringFunction('0.0', independent_variables=('x', 'y', 't'), globals=globals()) if plot: g = Gnuplot.Gnuplot(persist=1) g('set parametric') g('set data style lines') g('set hidden') g('set contour base') g('set zrange [-0.7:0.7]') # nice plot... def action(u, xv, yv, t): #print 'action, t=',t,'\nu=',u, '\nx=',x, '\ny=', y if plot: data = Gnuplot.GridData(u, xv[:,0], yv[0,:], binary=0) g.splot(data) g('set title "t=%g"' % t) if plot == 2: g.hardcopy(filename='tmp_%020f.ps' % t, enhanced=1, mode='eps', color=0, fontname='Times-Roman', fontsize=14) time.sleep(1) time.sleep(0.2) # pause between frames t0 = time.clock() implementation = {'ic': version, 'inner': version, 'bc': version} nx = 40; ny = 40; tstop = 700 solver(I2, f, c, bc, Lx, Ly, nx, ny, 0, tstop, user_action=action, implementation=implementation) t1 = time.clock() cpu = t1 - t0 print 'CPU time: %s version =' % version, cpu time.sleep(3)
def init_prms(m, b, L, k, beta, S0, dt, g, w_formula, N): import argparse parser = argparse.ArgumentParser() parser.add_argument('--m', '--mass', type=float, default=m) parser.add_argument('--b', '--boxheight', type=float, default=b) parser.add_argument('--L', '--spring-length', type=float, default=L) parser.add_argument('--k', '--spring-stiffness', type=float, default=k) parser.add_argument('--beta', '--spring-damping', type=float, default=beta) parser.add_argument('--dt','--timestep', type=float, default=dt) parser.add_argument('--g', '--gravity', type=float, default=g) parser.add_argument('--S0', '--initial-position', type=str, default=str(S0)) #So that S0 can be an expression of other parameters (ex: m*g/k) parser.add_argument('--w', type=str, default=w_formula) parser.add_argument('--N', type=int, default=N) args = parser.parse_args() from scitools.StringFunction import StringFunction w = StringFunction(args.w, independent_variables='t') return args.m, args.b, args.L, args.k, args.beta, \ args.S0, args.dt, args.g, w, args.N
def test(argv=sys.argv): f_formula = argv[1] a = eval(argv[2]) b = eval(argv[3]) n = int(argv[4]) f = StringFunction(f_formula) I = trapezoidal(f, a, b, n) print 'Approximation of the integral: ', I
def equal(expr1, expr2, A, B, n=500): failures = [] for t in range(1, n + 1) : a = random.uniform(A, B) b = random.uniform(A, B) f = StringFunction(expr1, independent_variables=('a','b')) s = StringFunction(expr2, independent_variables=('a','b')) first = f(a, b) second = s(a,b) if first != second: result = abs(first - second) failures.append(result) nFailures = float(len(failures)) percentage = (nFailures/n)*100 return n, nFailures, percentage
def test(argv=sys.argv): try: f_formula = argv[1] a = eval(argv[2]) b = eval(argv[3]) n = int(argv[4]) except: print "usage: %s 'f(x)' a b n" % sys.argv[0] sys.exit(1) f = StringFunction(f_formula) I = trapezoidal(f, a, b, n) print 'Approximation of the integral: ', I
def verify1(): g = Grid2D() from scitools.StringFunction import StringFunction expression = StringFunction('x + a*y', independent_variables=('x', 'y'), globals=globals(), a=2) f = g(expression) print g, f f = g.gridloop(expression) print g, f g = Grid2D(dx=0.05, dy=0.025) f = g.vectorized_eval(expression) plot_easyviz(g, f)
def deriv(): """ On the fly, allows user input of symblic expression prints derivative, returns derivative as string expression """ expression = raw_input('Enter an expression involving x: ') from scitools.StringFunction import StringFunction from sympy import diff, Symbol x = Symbol('x') f = StringFunction(expression) df = diff(f, x) print('The derivative of %s with respect to x is %s' % (expression, df)) return df
def verify1(): """Basic test of the extension module.""" g = Grid2Deff(dx=0.5, dy=1) f_exact = g(f1) # NumPy computation expression1 = StringFunction('x + 2*y', independent_variables=('x', 'y'), globals=globals()) f = g.ext_gridloop1(f1) print 'f computed by external gridloop1 function and f1:\n', f if allclose(f, f_exact, atol=1.0E-10, rtol=1.0E-12): print 'f is correct' f = g.ext_gridloop2(f1) print 'f computed by external gridloop2 function and f1:\n', f if allclose(f, f_exact, atol=1.0E-10, rtol=1.0E-12): print 'f is correct' f = g.ext_gridloop1(expression1) print 'f computed by external gridloop1 function and StringFunction:\n', f if allclose(f, f_exact, atol=1.0E-10, rtol=1.0E-12): print 'f is correct' f = g.ext_gridloop2(expression1) print 'f computed by external gridloop2 function and StringFunction:\n', f if allclose(f, f_exact, atol=1.0E-10, rtol=1.0E-12): print 'f is correct' fast_func = expression1.__call__ f = g.ext_gridloop2(fast_func) print 'f computed by external gridloop2 function and StringFunction.__call__:\n', f if allclose(f, f_exact, atol=1.0E-10, rtol=1.0E-12): print 'f is correct' f = g(expression1) print 'f computed by __call__ and StringFunction:\n', f if allclose(f, f_exact, atol=1.0E-10, rtol=1.0E-12): print 'f is correct' # check printing: print 'array seen from Python:' g.dump(f) if 'dump' in dir(ext_gridloop): print 'array seen from Fortran (transposed, but right values):' ext_gridloop.dump(f, g.xcoor, g.ycoor)
def main(): from scitools.StringFunction import StringFunction import sys try: formula = sys.argv[1] difftype = sys.argv[2] difforder = sys.argv[3] x = float(sys.argv[4]) except IndexError: print 'Usage: Diff.py formula difftype difforder x' print 'Example: Diff.py "sin(x)*exp(-x)" Central 4 3.14' sys.exit(1) classname = difftype + difforder f = StringFunction(formula) df = eval(classname)(f) print df(x)
def integrate_function(): """Integration function Using scitools.StringFunction to do integration. >>> integration.py 'sin(x)' 0 pi/2 integral of sin(x) on [0, 1.5708] with n=200: 1 """ def midpoint_integration(f, a, b, n=100): h = (b - a) / float(n) I = 0 for i in range(n): I += f(a + i * h + 0.5 * h) return h * I f_formula = sys.argv[1] a = eval(sys.argv[2]) b = eval(sys.argv[3]) if len(sys.argv) >= 5: n = int(sys.arvg[4]) else: n = 200 from scitools.StringFunction import StringFunction f = StringFunction(f_formula) # turn formula into f(x) func. """ >>> g = StringFunction('A*exp(-a*t)*sin(omega*x)', independent_variable='t', A=1, a=0.1, omega=pi, x=0.5) >>> g.set_parameters(omega=0.1) >>> g.set_parameters(omega=0.1, A=5, x=0) >>> g(0) 0.0 >>> g(pi) 2.8382392288852166e-15 """ I = midpoint_integration(f, a, b, n) print("Integral of {:s} on [{:g}, {:g}] with n ={:d}: {:g}" \ .format(f_formula, a, b, n, I))
k = float(value) elif option in ('--beta', '--spring-damping'): beta = float(value) elif option in ('--S0', '--initial-position'): S0 = float(value) elif option in ('--dt', '--timestep'): dt = float(value) elif option in ('--g', '--gravity'): g = float(value) elif option in ('--w',): w_formula = value # string elif option == '--N': N = int(value) from scitools.StringFunction import StringFunction w = StringFunction(w_formula, independent_variables='t') return m, b, L, k, beta, S0, dt, g, w, N def solve(m, k, beta, S0, dt, g, w, N, user_action=lambda S, time, time_step_no: None): """Calculate N steps forward. Return list S.""" S = [0.0]*(N+1) # output list gamma = beta*dt/2.0 # short form t = 0 S[0] = S0 user_action(S, t, 0) # special formula for first time step: i = 0 S[i+1] = (1/(2.0*m))*(2*m*S[i] - dt**2*k*S[i] + m*(w(t+dt) - 2*w(t) + w(t-dt)) + dt**2*m*g)
def __init__(self): # Set default parameter values self.alpha = 1. self.R = StringFunction('1.0', independent_variable='t') self.U0 = 0.01 self.T = 4.
# Exercise 5.33 from numpy import * import matplotlib.pyplot as plt import sys from scitools.StringFunction import StringFunction f = StringFunction(sys.argv[1]) f.vectorize(globals()) x = linspace(eval(sys.argv[2]), eval(sys.argv[3]), 501) plt.plot(x, f(x)) plt.xlabel('x') plt.ylabel('f(x)') plt.legend(['f(x) = %s' % sys.argv[1]]) plt.show() raw_input()
try: k = float(sys.argv[1]) m = float(sys.argv[2]) x0 = float(sys.argv[3]) force_formula = sys.argv[4] tstart = float(sys.argv[5]) tstop = float(sys.argv[6]) dt = float(sys.argv[7]) except IndexError, e: print e, '\n', usage sys.exit(1) if force_formula != '0': from scitools.StringFunction import StringFunction F = StringFunction(formula) else: F = None print F t = tstart x = [x0, x0] while t <= tstop: t += dt if F is not None: try: F_value = F(t) except: raise ValueError('Could not evaluate %s for t=%g' \ % (force_formula, t))
import sys usage = '%s f-formula a b [epsilon]' % sys.argv[0] try: f_formula = sys.argv[1] a = float(sys.argv[2]) b = float(sys.argv[3]) except IndexError: print usage sys.exit(1) try: # is epsilon given on the command-line? epsilon = float(sys.argv[4]) except IndexError: epsilon = 1E-6 # default value from scitools.StringFunction import StringFunction from math import * # might be needed for f_formula f = StringFunction(f_formula) from bisection import bisection root, iter = bisection(f, a, b, epsilon) if root == None: print 'The interval [%g, %g] does not contain a root' % (a, b) sys.exit(1) print 'Found root %g\nof %s = 0 in [%g, %g] in %d iterations' % \ (root, f_formula, a, b, iter)
('a/b', '1/(b/a)'),\ ('(a*b)**4', 'a**4*b**4'),\ ('(a+b)**2', 'a**2 + 2*a*b + b**2'),\ ('(a+b)*(a-b)', 'a**2 - b**2'),\ ('log(a*b)', 'log(a) + log(b)'),\ ('a*b', 'exp(log(a) + log(b))'),\ ('1/(1/a + 1/b)', 'a*b/(a+b)'),\ ('a*(sin(b)**2+cos(b)**2)', 'a'),\ ('tan(a+b)', 'sin(a+b)/cos(a+b)'),\ ('sin(a+b)', 'sin(a)*cos(b)+sin(b)*cos(a)') ) print '%30s %30s %5s %5s %15s' % ('expression 1', 'expression 2', 'A', 'B', 'Success Rate') A = 0 B = 1 for i in functions: fn1 = StringFunction(i[0], independent_variables=('a', 'b')) fn2 = StringFunction(i[1], independent_variables=('a', 'b')) x = equal(fn1, fn2, A, B) print '%30s %30s %5d %5d %15f' % (i[0], i[1], A, B, x) print '%30s %30s %5s %5s %15s' % ('expression 1', 'expression 2', 'A', 'B', 'Success Rate') A = 1E-7 B = 1E+7 for i in functions: fn1 = StringFunction(i[0], independent_variables=('a', 'b')) fn2 = StringFunction(i[1], independent_variables=('a', 'b')) x = equal(fn1, fn2, A, B) print '%30s %30s %5g %5g %15f' % (i[0], i[1], A, B, x)
""" TODO Exercise 3.13. Extend a program from Ch. 3.2.1. How can you modify the add_cml.py program from the end of Chap- ter 3.1.2 such that it accepts input like sqrt(2) and sin(1.2)? """ import math import sys from scitools.StringFunction import StringFunction i1 = StringFunction(sys.argv[1]) i2 = StringFunction(sys.argv[2]) print i1, i2 #print '%s + %s becomes %s\nwith value %s' % \ # (type(i1), type(i2), type(r), r)
import sys from scitools.StringFunction import StringFunction parameters = {} for prm in sys.argv[4:]: key, value = prm.split('=') parameters[key] = eval(value) f = StringFunction(sys.argv[1], independent_valiable=sys.argv[2], **parameters) var = float(sys.argv[3]) print f print f(var) """ The program accepts system arguments. It interperets the first one as a function definition, the second one as the variable of the function and the third one as where the function should be evaluated. The rest of the arguments are also passed on to the function. """ f = eval('StringFunction(sys.argv[1], ' + \ 'independent_valiables=sys.argv[2], %s)' % \ (', '.join(sys.argv[4:]) )) var = float(sys.argv[3]) print f(var) """ The second program does the same as the first one, only more directly and compactly. """
# Exercise 5.32 # Author: Noah Waterfield Price from numpy import * import matplotlib.pyplot as plt import sys from scitools.StringFunction import StringFunction f = StringFunction(sys.argv[1]) f.vectorize(globals()) if len(sys.argv) == 5: n = sys.argv[4] else: n = 501 x = linspace(eval(sys.argv[2]), eval(sys.argv[3]), n) plt.plot(x, f(x)) plt.xlabel('x') plt.ylabel('f(x)') plt.legend(['f(x) = %s' % sys.argv[1]]) plt.show() raw_input()
#------------------------------------------------------------------------------# # UI Management # #------------------------------------------------------------------------------# # Clear the terminal for readability print("\033c" + "*************************************************") print("CS 101 James Scholar Project By Kenneth Tochihara") print("*************************************************") print("\nCtrl + C to exit at anytime. ") # Infinite loop until KeyboardInterrupt while True: try: # Taking in the values f = StringFunction(input("f(u, t) = "), independent_variables=('u', 't')) u0 = float(input("u0 = ")) #initial condition dt = float(input("dt = ")) #time step T = float(input("T = ")) #Final time of simulation type = str(input("Solve Method: ")) #Initializing the u array, arrU and time array, arrT arrU = [] currentT = 0 arrT = [currentT] while (currentT < T) or (np.isclose(currentT, T)): currentT += dt arrT.append(currentT) #------------------------------------------------------------------------------# # Deciding which method to use #
def test_set_parameters(self): f = StringFunction('a+b*x', a=1) f.set_parameters(b=4) v = f(2) self.failUnlessEqual(v, 9, 'wrong value')
print usage sys.exit(1) try: # is epsilon given on the command-line? epsilon = float(sys.argv[4]) except IndexError: epsilon = 1E-6 # default value # clean up all plot files: import glob, os for filename in glob.glob('tmp_*.eps'): os.remove(filename) from scitools.StringFunction import StringFunction from scitools.std import * # might be needed for f_formula f = StringFunction(f_formula) f.vectorize(globals()) results = bisection_evolution(f, a, b, epsilon) if results is None: print 'f does not change sign in [%g, %g]' % (a, b) sys.exit(1) # plot: x = linspace(a, b, 501) y = f(x) ymin = min(y) ymax = max(y) itcount = 1 for interval, m in results: a, b = interval
if dfdx is not None: print '%15f' % (dfdx(x)) else: print '' from scitools.std import * f = ['x**2', 'sin(pi*x)**6', 'tanh(10*x)'] df = ['2*x', '6*pi*sin(pi*x)**5*cos(pi*x)', '10*(1-tanh(10*x)**2)'] hlist = [1E-1, 1E-3, 1E-5, 1E-7] from scitools.StringFunction import StringFunction x = [0, 0.25] for a in range(2): for b in range(3): print 'x = %.2f, f = %s' % (x[a], f[b]) table(StringFunction(f[b]), x[a], hlist, \ StringFunction(df[b])) print '' x = linspace(-1, 1, 500) for a in f: figure() plot(x, vectorize(StringFunction(a))(x), title='%s' % a) raw_input('Press Enter to quit:') ''' python Derivative_comparisons.py x = 0.00, f = x**2 h Derivative Central True 0.1 0.1 0 0.000000 0.001 0.001 0 0.000000 1e-05 1e-05 0 0.000000
K1 = dt * f(u[k], t[k]) K2 = dt * f(u[k] + 0.5 * K1, t[k] + dt2) K3 = dt * f(u[k] + 0.5 * K2, t[k] + dt2) K4 = dt * f(u[k] + K3, t[k] + dt) u_new = u[k] + (1 / 6.0) * (K1 + 2 * K2 + 2 * K3 + K4) return u_new import sys from scitools.StringFunction import StringFunction try: f_formula = sys.argv[1] U0 = float(sys.argv[2]) dt = float(sys.argv[3]) T = float(sys.argv[4]) f = StringFunction(f_formula, independent_variables=('u', 't')) except: print("Usage: %s f U0 dt T" % sys.argv[0]) print("Optional 5° argument: numerical method") sys.exit(1) try: method = eval(sys.argv[5]) except: method = ForwardEuler #Default method n = int(T / dt) + 1 times = np.linspace( 0, n * dt, n + 1) #This way we respect the dt. The last point will be T' in [T;T+dt]
def verify2(n=3): """ Test of some methods in class Grid2Deff that call up some F77 routines for improving the efficiency of callbacks to Python. """ if not 'gridloop_vec2' in dir(ext_gridloop): raise ImportError, 'verify2 works only for F77 module' dx = 1.0 / n g = Grid2Deff(dx=dx, dy=dx) from StringIO import StringIO from scitools.numpyutils import arr a_exact = arr(file_=StringIO(""" 0. 0. 0. 0. 2.66666667 2.7775493 2.88706441 2.99386136 5.33333333 5.55373108 5.7632897 5.95170314 8. 8.3271947 8.6183698 8.84147098""")) def _check(): if not allclose(a, a_exact): print 'ERROR, a is wrong, correct a reads\n', a_exact else: print 'correct array' a = g.ext_gridloop_vec1(myfuncf1) print "g.ext_gridloop_vec1(myfuncf1): a=\n", a _check() a = g.ext_gridloop_vec2(myfuncf2) print "g.ext_gridloop_vec2(myfuncf2): a=\n", a _check() # need f2py version > 2.42 (callback to class method): a = g.ext_gridloop_vec3(g.myfuncf3) print "g.ext_gridloop_vec3(g.myfuncf3): a=\n", a _check() a = g.ext_gridloop2_str('myfunc') print "g.ext_gridloop_str('myfunc'): a=\n", a _check() a = g.ext_gridloop_noalloc('myfunc', a) print "g.ext_gridloop_str_noalloc('myfunc'): a=\n", a _check() fstr = 'sin(x*y) + 8*x' g.ext_gridloop2_fcb_compile(fstr) a = g.ext_gridloop2_fcb() print "g.gridloop2_fcb: a=\n", a _check() import callback print 'contents of callback module:', dir(callback) fstr = StringFunction('sin(x*y) + 8*x') g.ext_gridloop2_fcb_ptr_compile(fstr) a = g.ext_gridloop2_fcb_ptr() print "g.gridloop2_fcb_ptr: a=\n", a _check() import callback print 'fcb callback module:', dir(callback), dir(callback.fcb) g.ext_gridloop2_compile(fstr) a = g.ext_gridloop2_v2() print "g.gridloop2_v2: a=\n", a _check() a = g.ext_gridloop2_weave(fstr) print "g.gridloop2_weave: a=\n", a _check() g.gridloop_psyco_init(g.gridloop) a = g.gridloop_psyco(fstr) print "g.gridloop_psyco(str): a=\n", a _check() a = g.gridloop_psyco(myfunc) print "g.gridloop_psyco(func): a=\n", a _check() g.ext_gridloop1_instant(fstr) g.gridloop1_instant(a, g.nx, g.ny, g.xcoor, g.ycoor) print "g.gridloop1_instant: a=\n", a
def __init__(self, input): self.function = StringFunction(input) self.input = input
def timing2(n=2000, best_time=1.0): """Time different implementations of the extension module.""" print 'Grid2Deff.timing2: reference CPU time = %g' % best_time dx = 1.0 / n g = Grid2Deff(dx=dx, dy=dx) # here we use straight NumPy sin in a scalar context: def myfunc1(x, y): return sin(x * y) + 8 * x def myfunc2(x, y): return math.sin(x * y) + 8 * x expression1 = StringFunction('sin(x*y) + 8*x', independent_variables=('x', 'y'), globals=globals()) expression1_f = expression1.__call__ # for efficiency and F77 callback expression2 = StringFunction('math.sin(x*y) + 8*x', independent_variables=('x', 'y'), globals=globals()) expression2_f = expression2.__call__ # for efficiency and F77 callback from scitools.misc import timer from scitools.EfficiencyTable import EfficiencyTable e = EfficiencyTable('Grid2Deff tests, %dx%d grid' % (n, n), best_time) t0a = timer(g.gridloop, (myfunc1, ), repetitions=1) e.add('g.gridloop, myfunc1', t0a) t0b = timer(g.gridloop, (myfunc2, ), repetitions=1) e.add('g.gridloop, myfunc2', t0b) t0c = timer(g.__call__, (myfunc1, ), repetitions=1) e.add('g.__call__, myfunc1', t0c) t0d = timer(g.__call__, (expression1_f, ), repetitions=1) e.add('g.__call__, expression1_f', t0d) t0e = timer(g.gridloop_itemset, (myfunc2, ), repetitions=1) e.add('g.gridloop_itemset, myfunc2', t0e) t1a = timer(g.ext_gridloop1, (myfunc1, ), repetitions=1) e.add('g.ext_gridloop1, myfunc1', t1a) t1b = timer(g.ext_gridloop1, (myfunc2, ), repetitions=1) e.add('g.ext_gridloop1, myfunc2', t1b) t2a = timer(g.ext_gridloop2, (myfunc1, ), repetitions=1) e.add('g.ext_gridloop2, myfunc1', t2a) t2b = timer(g.ext_gridloop2, (myfunc2, ), repetitions=1) e.add('g.ext_gridloop2, myfunc2', t2b) t3a = timer(g.ext_gridloop2, (expression1_f, ), repetitions=1) e.add('g.ext_gridloop2, expression1_f', t3a) t3b = timer(g.ext_gridloop2, (expression2_f, ), repetitions=1) e.add('g.ext_gridloop2, expression2_f', t3b) nrep = 20 # try the improved functions (works only for the F77 module): if 'gridloop_vec2' in dir(ext_gridloop): t4 = timer(g.ext_gridloop_vec2, (myfuncf2, ), repetitions=nrep) e.add('g.ext_gridloop_vec2, myfuncf2', t4) if 'gridloop2_str' in dir(ext_gridloop): t5 = timer(g.ext_gridloop2_str, ('myfunc', ), repetitions=nrep) e.add('g.ext_gridloop2_str, myfunc', t5) # try the version without allocation (first, make an a array): a = g.ext_gridloop2(myfunc1) # a has now Fortran storage t5b = timer(g.ext_gridloop_noalloc, ('myfunc', a), repetitions=nrep) e.add('g.ext_gridloop_noalloc, myfunc', t5b) # try 'inline' F77 compiled callback too: # (give F77 source for core of callback function as argument) g.ext_gridloop2_fcb_compile(str(expression1)) t6 = timer(g.ext_gridloop2_fcb, (), repetitions=nrep) e.add('g.ext_gridloop2_fcb(%s)' % repr(str(expression1)), t6) g.ext_gridloop2_fcb_ptr_compile(expression1) t6b = timer(g.ext_gridloop2_fcb_ptr, (), repetitions=nrep) e.add('g.ext_gridloop2_fcb_ptr(%s)' % repr(expression1), t6b) g.ext_gridloop2_compile(str(expression1)) t7 = timer(g.ext_gridloop2_v2, (), repetitions=nrep) e.add('g.ext_gridloop2_v2(%s)' % repr(str(expression1)), t7) # weave version: t8 = timer(g.ext_gridloop2_weave, (str(expression1), ), repetitions=nrep) e.add('g.ext_gridloop2_weave(%s)' % repr(str(expression1)), t8) # psyco: g.gridloop_psyco_init(g.gridloop) if g.gridloop_psyco != g.gridloop: # has psyco t9a = timer(g.gridloop_psyco, (myfunc2, ), repetitions=1) e.add('g.gridloop_psyco, myfunc2', t9a) t9b = timer(g.gridloop_psyco, (expression2_f, ), repetitions=1) e.add('g.gridloop_psyco, expression2_f', t9b) g.gridloop_psyco_init(g.gridloop_itemset) if g.gridloop_psyco != g.gridloop_itemset: # has psyco t9a = timer(g.gridloop_psyco, (myfunc2, ), repetitions=1) e.add('g.gridloop_psyco (itemset), myfunc2', t9a) t9b = timer(g.gridloop_psyco, (expression2_f, ), repetitions=1) e.add('g.gridloop_psyco (itemset), expression2_f', t9b) # instant: g.ext_gridloop1_instant(str(expression1)) if g.gridloop1_instant is not None: a = zeros((self.nx, self.ny)) t10 = timer(g.gridloop1_instant, (a, self.nx, g.ny, g.xcoor, g.ycoor), repetitions=nrep) e.add('g.gridloop1_instant', t10) print '\n\n\n\nrun from directory', os.getcwd() print e
import sys from scitools.StringFunction import StringFunction from Newton import Newton from Secant import Secant from bisection import bisection_evolution from scitools.std import * usage = 'f(x) f\'(x) a b x0 x1' try: f = StringFunction(sys.argv[1]) df = StringFunction(sys.argv[2]) a = float(eval(sys.argv[3])) b = float(eval(sys.argv[4])) x0 = float(eval(sys.argv[5])) x1 = float(eval(sys.argv[6])) except: print usage sys.exit(1) def printRootConvergence(x_values, f_values, method_name=None): if method_name is not None: print method_name print '%5s %15s %15s' % ('n', 'root', 'f(x)') for i in range(len(f_values)): print '%5d %15.10f %15.10f' % (i + 1, x_values[i], f_values[i]) N = 100 epsilon = 1e-10
def toStringFunction(text): return StringFunction(text, independent_variable='t')