def solve_system(x0, params):

    xtol = gtol = ftol = 1e-12
    max_iter = 200
    n = p = 2
    T = multifit_nlinear.cvar.trust
    w = multifit_nlinear.workspace(T, params, n, p)

    # What a hack
    w.set_pyobject(w)
    w.init(x0, f=func_f, df=func_df, fvv=func_fvv, args=None)
    #w.init(x0, f = func_f,  args=None)
    f = w.residual()
    chisq0 = np.dot(f, f)

    pygsl.set_debug_level(0)

    w.driver(max_iter, xtol, gtol, ftol, callback=None, callback_params=None)

    f = w.residual()
    chisq = np.dot(f, f)

    rcond = w.rcond()

    print("    NITER         = %d" % w.niter())
    print("    NFEV          = %d" % w.params.fdf.nevalf)
    print("    NJEV          = %d" % w.params.fdf.nevaldf)
    print("    NAEV          = %d" % w.params.fdf.nevalfvv)
    print("    initial cost  = %.12e" % chisq0)
    print("    final cost    = %.12e" % chisq)
    print("    final x       = (%.12e, %.12e)" % tuple(w.position()))
    print("    final cond(J) = %.12e" % (1.0 / rcond, ))
Exemplo n.º 2
0
def run_driver():
    mu = 10
    sys = odeiv2.system(func, jac, 2, mu)
    #sys = odeiv2.system(func, None, 2, mu)

    T = odeiv2.step_rk8pd
    pygsl.set_debug_level(0)
    d = driver_y_new(sys, T, 1e-6, 1e-6, 0.0);
    d.reset()
    d.reset_hstart(2)
    d.set_hmin(0.0)
    d.set_hmax(1.0)
    d.set_nmax(2)
    d.set_nmax(0)
    d.set_hmax(1e-6)
    d.set_hmin(2e-6)
    y = numx.array([1.0, 0.0])
    N = 100
    t = 0.0
    t1 = N * 1.
    ti = (numx.arange(N) +1) / float(N)

    pygsl.set_debug_level(0)

    for tnext in ti:
        #pygsl.set_debug_level(3)
        t, y  = d.apply(t, tnext, y)
        print(t, y)
Exemplo n.º 3
0
 def testCos(self):
     x = numx.arange(self.n) * (2 * numx.pi / self.n)
     for i in range(1, self.n / 2):
         if self.__class__.__name__ == "testrealforwardfloat":
             pygsl.set_debug_level(0)
         try:
             self.CosOne(x, i)
         finally:
             pygsl.set_debug_level(0)
Exemplo n.º 4
0
def run2():
    pygsl.set_debug_level(10)

    x = 2.0
    step = odeiv.step_rk8pd(2, func, None, x)
    control = odeiv.control_y_new(step, 1e-6, 1e-6)
    evolve = odeiv.evolve(step, control)

    pass
Exemplo n.º 5
0
def run2():
    pygsl.set_debug_level(10)

    x = 2.0
    step = odeiv.step_rk8pd(2, func, None, x)
    control = odeiv.control_y_new(step, 1e-6, 1e-6)
    evolve  = odeiv.evolve(step, control)

    pass
Exemplo n.º 6
0
 def testCos(self):        
     x = numx.arange(self.n) * (2 * numx.pi / self.n)
     for i in range(1,self.n/2):
         if self.__class__.__name__ == "testrealforwardfloat":
             pygsl.set_debug_level(0)
         try:                
             self.CosOne(x,i)
         finally:
             pygsl.set_debug_level(0)
Exemplo n.º 7
0
def run():
    N = 100
    n = N - 2
    A = matrix.sparse_matrix(n, n)

    h = 1.0 / ( N - 1.0)

    # first row
    A.set(0, 0, -2.0)
    A.set(0, 1, 1.0)

    # rows [1:n-2]
    for i in range(1, n - 1):
        A.set(i, i + 1,  1.0)
        A.set(i, i,     -2.0)
        A.set(i, i - 1,  1.0)

    # last row
    A.set(n - 1, n -1, -2.0)
    A.set(n - 1, n -2,  1.0)

    A.scale(1.0 / h**2)

    cnt = (np.arange(n))
    x = (cnt + 1) * h
    f = - np.pi**2  * np.sin(np.pi * x)

    C = A.ccs()

    tol = 1.0e-6
    max_iter = 10

    work = linalg.GMRES(n, 0)
    u = np.zeros(len(x), np.float_)

    for t_iter in range(max_iter):
        pygsl.set_debug_level(0)
        #status, u = work.iterate(C, f, tol)
        status, u = work.iterate(C, f, tol, u)
        pygsl.set_debug_level(0)
        residual = work.normr()
        print("iter %d residual = %.12e" %(t_iter, residual))

        if status == errno.GSL_SUCCESS:
            break
    else:
        raise ValueError("Exceed maximum number of iterations")

    return x, u
Exemplo n.º 8
0
def run_driver_fixed_step():
    mu = 10
    sys = odeiv2.system(func, jac, 2, mu)

    T = odeiv2.step_rk8pd
    d = driver_y_new(sys, T, 1e-6, 1e-6, 0.0);
    d.reset()
    y = numx.array([1.0, 0.0])
    N = 100
    pygsl.set_debug_level(0)

    t = 0
    for cnt in range(N):
        t, y  = d.apply_fixed_step(t, 1e-3, 1000, y)
        print(t, y)
Exemplo n.º 9
0
def run():
    r = rng.rng()

    # slope
    a = 1.45
    # intercept
    b = 3.88

    # Generate the data
    n = 20
    i = numx.arange(n - 3)
    dx = 10.0 / (n - 1.0)
    e = r.uniform(n)
    x = -5.0 + i * dx
    y = a * x + b

    #outliers
    xo = numx.array([4.1, 3.5, 4.7])
    yo = numx.array([-6.0, -6.7, -8.3])

    x = numx.concatenate((x, xo))
    y = numx.concatenate((y, yo))

    X = numx.array([x * 0 + 1, x]).transpose()
    ws = fr.workspace(*((fr.ols, ) + X.shape))
    c_ols, cov_ols = ws.fit(X, y)
    ws = fr.workspace(*((fr.bisquare, ) + X.shape))
    c, cov = ws.fit(X, y)

    y_rob = numx.zeros(n, numx.float_)
    y_ols = numx.zeros(n, numx.float_)

    yerr_rob = numx.zeros(n, numx.float_)
    yerr_ols = numx.zeros(n, numx.float_)

    pygsl.set_debug_level(0)
    fr.est(X[0, :], c, cov)
    y_rob, yerr_rob = fr.est_vector(X, c, cov)
    pygsl.set_debug_level(0)
    y_ols, yerr_ols = fr.est_vector(X, c_ols, cov_ols)

    return x, y, (y_rob, yerr_rob), (y_ols, yerr_ols)
Exemplo n.º 10
0
def run_fail():
    """Demonstrates pygsl capabilites in finding problems with callbacks
    """
    def f1(x, *args):
        return None

    import pygsl

    sys = integrate.gsl_function(f1, None)

    # Enables printing debug messages. The higher the level the more information
    # will be displayed
    #pygsl.set_debug_level(3)

    # Quite a few functions add traceback frames when they propage the error
    # through the different levels. If you can not understand the error messages
    # directly, looking at the source where the error occured can help.
    #pygsl.add_c_traceback_frames(True)
    flag, result, error, method = integrate.qng(sys, 0, numx.pi, 1e-8, 1e-8)
    pygsl.set_debug_level(0)
Exemplo n.º 11
0
def run():
    N = 1024
    x = numx.arange(N) * (numx.pi * 2 / N)
    y = numx.sin(x)

    b = bspline(4, nbreak)
    k = b.get_internal_knots()
    pygsl.set_debug_level(10)
    b.knots(k)
    X = b.eval_vector(x)
    c, cov, chisq = multifit.linear(X, y)

    b.set_coefficients_and_covariance_matrix(c, cov)

    res_x = x[:: N / 64]
    res_y, res_y_err = b.eval_dep_yerr_vector(res_x)
    # res_y = b.eval_dep_vector(res_x)

    print res_y
    pylab.plot(x, y, "-")
    pylab.errorbar(res_x, res_y, fmt="g-", xerr=res_y_err)
Exemplo n.º 12
0
def run():
    N = 1024
    x = numx.arange(N) * (numx.pi * 2 / N)
    y = numx.sin(x)

    b = bspline(4, nbreak)
    k = b.get_internal_knots()
    pygsl.set_debug_level(10)
    b.knots(k)
    X = b.eval_vector(x)
    c, cov, chisq = multifit.linear(X, y)

    b.set_coefficients_and_covariance_matrix(c, cov)

    res_x = x[::N / 64]
    res_y, res_y_err = b.eval_dep_yerr_vector(res_x)
    #res_y = b.eval_dep_vector(res_x)

    print(res_y)
    pylab.plot(x, y, '-')
    pylab.errorbar(res_x, res_y, fmt='g-', xerr=res_y_err)
Exemplo n.º 13
0
def run_fdfsolver():
    A       = 1.
    lambda_ = .1
    b       = .5

    n = 40
    p = 3

    t = numx.arange(n);
    y = testfunc(t, A, lambda_, b)
    sigma = numx.ones(n) * 0.1
    data = numx.array((t,y,sigma), numx.Float)
    #mysys = multifit_nlin.gsl_multifit_function_fdf(exp_f, exp_df, exp_fdf,
    # data, n,p)
    pygsl.set_debug_level(0)
    solver = multifit_nlin.lmsder(n, p)
    pygsl.set_debug_level(0)
    #solver = multifit_nlin.lmder(mysys, n, p)


    x = numx.array((1.0, 0.0, 0.0))
    pygsl.set_debug_level(0)
    solver.set(exp_f, exp_df, exp_fdf, x, data)
    pygsl.set_debug_level(0)
    print "# Testing solver ", solver.name() 
    print "# %5s %9s %9s  %9s  %10s" % ("iter", "A", "lambda", "b", "|f(x)|")
    for iter in range(20):	    
        status = solver.iterate()
	x  = solver.x()
	dx = solver.dx()
	f  = solver.f()
	J  = solver.J()
	#tdx = multifit_nlin.gradient(J, f)
	#status = multifit_nlin.test_delta(dx, x, 1e-8, 1e-8)
	status = solver.test_delta(1e-8, 1e-8)
	fn = numx.sqrt(numx.sum(f*f))
	if status == 0:
		print "# Convereged :"
	if status == 0:
                break
        print "  %5d % .7f % .7f  % .7f  % .7f" %(iter, x[0], x[1], x[2], fn)
    else:
	raise ValueError, "Number of Iterations exceeded!"

    J = solver.J()
    covar =  multifit_nlin.covar(solver.J(), 0.0)
    print "# A      = % .5f +/- % .5f" % (x[0], covar[0,0])
    print "# lambda = % .5f +/- % .5f" % (x[1], covar[1,1])
    print "# b      = % .5f +/- % .5f" % (x[2], covar[2,2])
Exemplo n.º 14
0
def real_example_simple():
    n = 1024*1024
    data = numx.zeros((n,), numx.Int)
    data[n/3:2*n/3] = 1
    result =  fft.real_transform(data)
    #print "Nyqusit ->", result[0]
    result[11:] = 0
    final = fft.halfcomplex_inverse(result, n)    
    #print final
    return
    import Gnuplot
    g = Gnuplot.Gnuplot()
    g.plot(Gnuplot.Data(data, with='line'),
           Gnuplot.Data(final, with='linespoints'),)
    raw_input()

def halfcomplex_radix2_unpack():
    n = 32   
    a = numx.arange(n)
    c = numx.zeros((n,))
    c[1:n/2+1]=a[1::2]
    c[n/2+1:]=a[-2:1:-2]    
    print c
    print fft.halfcomplex_radix2_unpack(c)
    
def doc():
    help(fft)
    
if __name__ == '__main__':
    import pygsl
    pygsl.set_debug_level(0)
    complex_example_simple()
    complex_example()
    real_example_simple()
    real_example_simple1()
    halfcomplex_radix2_unpack()
Exemplo n.º 15
0
Arquivo: fft.py Projeto: pygsl/pygsl
#import Gnuplot
#    g = Gnuplot.Gnuplot()
#    g.plot(Gnuplot.Data(data, with='line'),
#           Gnuplot.Data(final, with='linespoints'),)
#    raw_input()


def halfcomplex_radix2_unpack():
    n = 32
    a = numx.arange(n)
    c = numx.zeros((n, ))
    c[1:n / 2 + 1] = a[1::2]
    c[n / 2 + 1:] = a[-2:1:-2]
    print(c)
    print(fft.halfcomplex_radix2_unpack(c))


def doc():
    help(fft)


if __name__ == '__main__':
    import pygsl
    pygsl.set_debug_level(0)
    complex_example_simple()
    complex_example()
    real_example_simple()
    real_example_simple1()
    halfcomplex_radix2_unpack()
    doc()
Exemplo n.º 16
0
def run():

    x_init = np.array([1.0, 1.0, 0.0])
    xtol = 1e-8
    gtol = 1e-8
    ftol = 0

    fdf = (expb_f, expb_df)
    p = 3
    n = 40

    r = rng.rng()
    t = np.arange(n)
    y = 1.0 + 5 * np.exp(-0.1 * t)
    dy = r.gaussian(n)
    y += dy
    weights = 1. / ((0.1 * y)**2)

    T = multifit_nlinear.cvar.trust
    pygsl.add_c_traceback_frames(True)
    pygsl.set_debug_level(0)
    params = multifit_nlinear.default_parameters()
    w = multifit_nlinear.workspace(T, params, n, p)
    w.set_pyobject(w)
    # w.params.fdf.p = p
    # w.params.fdf.n = n
    args = y
    #print(w.init.__doc__)

    print("params factor: up %s down %s" % (
        params.factor_up,
        params.factor_down,
    ))
    errors.error_safe_state.reset()
    pygsl.set_debug_level(0)
    # w.init(x_init, df= expb_df, f=expb_f, fvv=None, args=args)
    w.init(x_init, df=None, f=expb_f, fvv=None, args=args)
    pygsl.set_debug_level(0)

    f = w.residual()
    chisq0 = np.dot(f, f)
    pygsl.set_debug_level(0)
    status, info = w.driver(200, xtol, gtol, ftol, callback)
    pygsl.set_debug_level(0)

    J = w.jac()
    covar = multifit_nlinear.covar(J, 0.0, p)
    J = w.jac()
    covar = w.covar(0.0)

    f = w.residual()
    chisq = np.dot(f, f)

    dof = n - p
    c = max(1, np.sqrt(chisq / dof))

    reasons = ("small step size", "small gradient")

    print("Summary from method %s/%s" % (w.name(), w.trs_name()))
    print("  number of iterations %d" % (w.niter(), ))
    print("  function evaluations %d" % (w.params.fdf.nevalf, ))
    print("  jacobian evaluations %d" % (w.params.fdf.nevaldf, ))
    print("  reason for stopping  %s" % (reasons[info]))

    print("  chisq / dof          %g" % (chisq / dof))

    x = w.position()
    x = w.x()
    print("  A     = %.5f +/- %.5f" % (x[0], c * covar[0, 0]))
    print("  lamba = %.5f +/- %.5f" % (x[1], c * covar[1, 1]))
    print("  b     = %.5f +/- %.5f" % (x[2], c * covar[2, 2]))
Exemplo n.º 17
0
A.set(4, 0, 4.1)

print("printing all matrix elements:\n")
for i in range(5):
    for j in range(4):
        val = A.get(i, j)
        val2 = A.get_val_or_none(i, j)
        print("A[%d, %d] = %g %s" % (i, j, val, val2))

print(dir(matrix))
print(dir(matrix.sparse_matrix))
print(dir(A))
print(A.get_shape())
print(A.shape)

pygsl.set_debug_level(5)
A.sp2d()
#print(A == A)
B = A.memcpy()
print("A == B", A == B)
B.scale(2)
print("A == 2*B", A == B)

#: Minimum maximum of the matrix
A.minmax()

#: compact row type
A.crs()

#: compact column type
A.ccs()
Exemplo n.º 18
0
def run():

    x_init = np.array([1.0, 1.0, 0.0])
    xtol = 1e-8
    gtol = 1e-8
    ftol = 0

    p = 3
    n = 40

    rng.env_setup()
    r = rng.rng()
    t = np.arange(n)
    x_final =  5., .1 , 1
    y = func(x_final, t)
    s = 0.1 * y
    dy = np.array(list(map(r.gaussian, s)))
    y = y + dy
    weights = 1./((0.1 * y)**2)

    T = multifit_nlinear.cvar.trust
    pygsl.add_c_traceback_frames(True)
    pygsl.set_debug_level(0)
    params = multifit_nlinear.default_parameters()
    w = multifit_nlinear.workspace(T, params, n, p)

    # What a hack 
    w.set_pyobject(w)
    
    w.winit(x_init, weights, df= expb_df, f=expb_f, fvv = None, args=y)

    f  = w.residual()
    chisq0 = np.dot(f, f)

    #plt.ion()
    fig = plt.figure()
    ax = fig.add_subplot(111)
    ax.clear()
    ax.errorbar(t, y, yerr=dy)
    Y = func(x_init, t)
    line, = ax.plot(t, Y, '-')
    plt.show(False)
    plt.draw()
    
    max_iter = 200
    #status, info  = w.driver(200, xtol, gtol, ftol, callback)

    for step in range(max_iter):
        x = w.position()
        print("x = %s" %(x,))
        #x = w.x()
        Y = func(x, t)
        line.set_data(t, Y)

        w.iterate()
        status, info = w.test(xtol, gtol, ftol)
        fig.canvas.draw()
        plt.pause(0.5)
        #ax.figure.clf()
        if status == errno.GSL_SUCCESS:
            break
        elif status == errno.GSL_CONTINUE:
            continue
        else:
            raise ValueError("Unexpected status %d" %(status,))
    else:
        raise ValueError("Did not finish within %d steps" %(max_iter,))


    covar = w.covar(0.0)
    f  = w.residual()
    chisq = np.dot(f, f)

    dof = n - p
    c = max(1,  np.sqrt(chisq / dof))

    reasons = ("small gradient", "small step size")
    status, info = w.test(xtol, gtol, ftol)

    print("Summary from method %s/%s" %(w.name(), w.trs_name()) )
    print("  number of iterations %d" %(w.niter(),) )
    print("  function evaluations %d" %(w.params.fdf.nevalf,))
    print("  jacobian evaluations %d" %(w.params.fdf.nevaldf,))
    print("  reason for stopping  %s" %(reasons[info],))
    print("  initial |f(x)|     = %f" %(np.sqrt(chisq0),) )
    print("  final   |f(x)|     = %f" %(np.sqrt(chisq),) )
    print("  chisq / dof          %g" %(chisq / dof) )

    x = w.position()
    x = w.x()
    print("  A     = %.5f +/- %.5f" %  ( x[0], c * covar[0,0]) )
    print("  lamba = %.5f +/- %.5f" %  ( x[1], c * covar[1,1]) )
    print("  b     = %.5f +/- %.5f" %  ( x[2], c * covar[2,2]) )

    plt.show()
Exemplo n.º 19
0
# Author : Pierre Schnizer
"""
The python equivalent of the C example found in the GSL Reference document.

It prints the calculational ouput to stdout. The first column is t, the
second y[0] and the thrid y[1]. Plot it with your favourite programm to see
the output.

"""
import sys
sys.stdout = sys.stderr
import pygsl._numobj as Numeric
import pygsl
pygsl.set_debug_level(0)
import time
from pygsl.testing import odeiv


def func(t, y, mu):
    f = Numeric.zeros((2,), Numeric.Float) * 1.0
    f[0] = y[1]
    f[1] = -y[0] - mu * y[1] * (y[0] ** 2 -1);
    #f[0] = y[1]
    #f[1] = y[0] * mu
    #print "y", y, "f", f
    return f

def jac(t, y, mu):
    dfdy = Numeric.ones((2,2), Numeric.Float) 
    dfdy[0, 0] = 0.0
    dfdy[0, 1] = 1.0