Ejemplo n.º 1
0
def main():
    import sys
    if (len(sys.argv) != 3):
        print "Matrix dimension = argv[1], l = argv[2]. "
        return -1
    pr = cProfile.Profile()
    pr.enable()
    dimension = int(sys.argv[1])
    l = float(sys.argv[2])
    dimension, row, col, data = spmv.sparseMatrix(dimension, l)
    b = np.zeros(dimension)
    for i in range(dimension):
        b[i] = i + 1

    tol = 0.0001
    iterMax = 100
    x = conjugateGradient(dimension, row, col, data, b, tol, iterMax)
    if (False):
        print "Vector b: "
        print b
        print "Solution of Ax = b: "
        print x
        print "Ax = "
        print spmv.product(dimension, row, col, data, x)
    pr.disable()
    pr.dump_stats("profile")
    pr.print_stats()
    return 0
Ejemplo n.º 2
0
def conjugateGradient(dimension, row, col, data, b, tol, jmax, printResidual = False):
    import sys
    if (len(b) != dimension):
        print "Dimension incompatible. "
        sys.exit(-1)
    x0 = np.zeros(dimension)
    r0 = b - spmv.product(dimension, row, col, data, x0)
    p0 = r0
    j = 0
    while(True):
        rj = r0
        pj = p0
        xj = x0
        AP = spmv.product(dimension, row, col, data, pj)

        alpha = np.dot(rj, rj)/np.dot(pj, AP)
        x0 = xj + alpha*pj
        r0 = rj - alpha*AP
        beta = np.dot(r0, r0)/np.dot(rj, rj)
        p0 = r0 + beta*pj
        j = j + 1
        if (printResidual):
            print j
            print np.dot(r0, r0)
        if (j == jmax):
            break
        if (np.dot(r0, r0) < tol**2):
            break
    return x0
Ejemplo n.º 3
0
def thetaEuler(nx, ntmax, theta):
    '''theta == 0 means forward Euler method, theta == 1 means backward Euler method. 0 <= theta <= 1. '''
    dx = 1.0/nx
    dt = 0.5*dx**2
    x = []
    for i in range(nx + 1):
        x.append(i*dx)
    u = np.zeros(nx + 1)
    dimension = nx - 1
    dimension, rowA, colA, dataA = spmv.sparseMatrix(dimension, theta*dt/dx**2)
    dimension, rowB, colB, dataB = spmv.sparseMatrix(dimension, -(1-theta)*dt/dx**2)

    f = np.zeros(len(x))
    for i in range(len(x)):
        f[i] = F(x[i])

    tol = 0.0001
    iterMax = 100
    step = 0
    while(True):
        V = []
        for element in u[1:-1]:
            V.append(element)
        u[1:-1] = spmvcg.conjugateGradient(dimension, rowA, colA, dataA, spmv.product(dimension, rowB, colB, dataB, u[1:-1]) + dt*f[1:-1], tol, iterMax)
        step = step + 1
        residual = 0
        for i in range(len(V)):
            residual = residual + (V[i] - u[1:-1][i])**2
        #print step
        #print residual
        if (step > ntmax):
            break
        if (np.sqrt(residual) < 0.0000001):
            break
    return x, u