Exemplo n.º 1
0
except:
    from nlpy.linalg.pyma27 import PyMa27Context as LBLContext

from pysparse.sparse import spmatrix
from pysparse.sparse.pysparseMatrix import PysparseMatrix as sp
import numpy as np
from nlpy.tools.timing import cputime
import sys

if len(sys.argv) < 3:
    sys.stderr.write("Please supply two positive definite matrices as input")
    sys.stderr.write(" in MatrixMarket format.\n")
    sys.exit(1)

# Create symmetric quasi-definite matrix K
A = sp(matrix=spmatrix.ll_mat_from_mtx(sys.argv[1]))
C = sp(matrix=spmatrix.ll_mat_from_mtx(sys.argv[2]))

nA = A.shape[0]
nC = C.shape[0]
# K = spmatrix.ll_mat_sym(nA + nC, A.nnz + C.nnz + min(nA,nC))
K = sp(size=nA + nC, sizeHint=A.nnz + C.nnz + min(nA, nC), symmetric=True)
K[:nA, :nA] = A
K[nA:, nA:] = -C
# K[nA:,nA:].scale(-1.0)
idx = np.arange(min(nA, nC), dtype=np.int)
K.put(1, nA + idx, idx)

# Create right-hand side rhs=K*e
e = np.ones(nA + nC)
# rhs = np.empty(nA+nC)
Exemplo n.º 2
0
printMatrix(spmatrix.matrixmultiply(O, O))
printMatrix(spmatrix.matrixmultiply(Os, O))

print 'Dot product'
printMatrix(spmatrix.dot(I, A))

print 'Matrix export'
A[:4,:4].export_mtx('A.mtx', 3)
As[:4,:4].export_mtx('As.mtx', 3)

print open('A.mtx').read()
print open('As.mtx').read()

print 'Matrix import'
printMatrix(spmatrix.ll_mat_from_mtx('A.mtx'))
printMatrix(spmatrix.ll_mat_from_mtx('As.mtx'))

print 'Conversion to CSR'
print A[:4,:4]
print A[:4,:4].to_csr()
print As[:4,:4].to_csr()

print 'update_add_mask operations'
ind = np.array([3, 4, 5, 6], 'i')
mask = np.array([1, 1, 1, 1], 'i')
B = np.ones((4,4), 'd')
Ac = A.copy()
Ac.update_add_mask(B, ind, ind, mask, mask)
A.update_add_mask_sym(B, ind, mask)
As.update_add_mask_sym(B, ind, mask)
Exemplo n.º 3
0
print L
print L.nnz

#------------------------------------------------------------

if 0:
    f = open(os.environ['HOME'] + '/matrices/poi2d_300.mtx')
    t1 = time.clock()
    L = ll_mat_from_mtx(f)
    t_read = time.clock() - t1
    f.close()
    print 'time for reading matrix data from file: %.2f sec' % t_read

if 1:
    t1 = time.clock()
    L = spmatrix.ll_mat_from_mtx(os.environ['HOME'] +
                                 '/matrices/poi2d_300.mtx')
    t_read = time.clock() - t1
    print 'time for reading matrix data from file: %.2f sec' % t_read

#------------------------------------------------------------

L = spmatrix.ll_mat_from_mtx(os.environ['HOME'] + '/matrices/node4x3x1_A.mtx')
print L.shape, L.nnz

A = L.to_sss()


class diag_prec:
    def __init__(self, A):
        self.shape = A.shape
        n = self.shape[0]
Exemplo n.º 4
0
        triangular and B is block diagonal with 1x1 and 2x2
        blocks. Access to the factors is available as soon
        as a PyMa27Context has been instantiated.
        """
        self.context.fetchlb( self.L, self.B )
        return None
        

if __name__ == '__main__':

    import sys
    from pysparse.sparse import spmatrix
    import numpy
    from nlpy.tools import norms

    M = spmatrix.ll_mat_from_mtx( sys.argv[1] )
    (m,n) = M.shape
    if m != n:
        sys.stderr( 'Matrix must be square' )
        sys.exit(1)
    if not M.issym:
        sys.stderr( 'Matrix must be symmetric' )
        sys.exit(2)
    e = numpy.ones( n, 'd' )
    rhs = numpy.zeros( n, 'd' )
    M.matvec( e, rhs )
    sys.stderr.write( ' Factorizing matrix... ' )
    G = PyMa27Context( M )
    sys.stderr.write( ' done\n' )
    sys.stderr.write( ' Solving system... ' )
    G.solve( rhs )
Exemplo n.º 5
0
except:
    from nlpy.linalg.pyma27 import PyMa27Context as LBLContext

from pysparse.sparse import spmatrix
from pysparse.sparse.pysparseMatrix import PysparseMatrix as sp
import numpy as np
from nlpy.tools.timing import cputime
import sys

if len(sys.argv) < 3:
    sys.stderr.write('Please supply two positive definite matrices as input')
    sys.stderr.write(' in MatrixMarket format.\n')
    sys.exit(1)

# Create symmetric quasi-definite matrix K
A = sp(matrix=spmatrix.ll_mat_from_mtx(sys.argv[1]))
C = sp(matrix=spmatrix.ll_mat_from_mtx(sys.argv[2]))

nA = A.shape[0]
nC = C.shape[0]
#K = spmatrix.ll_mat_sym(nA + nC, A.nnz + C.nnz + min(nA,nC))
K = sp(size=nA + nC, sizeHint=A.nnz + C.nnz + min(nA, nC), symmetric=True)
K[:nA, :nA] = A
K[nA:, nA:] = -C
#K[nA:,nA:].scale(-1.0)
idx = np.arange(min(nA, nC), dtype=np.int)
K.put(1, nA + idx, idx)

# Create right-hand side rhs=K*e
e = np.ones(nA + nC)
#rhs = np.empty(nA+nC)
Exemplo n.º 6
0
#         where P is as in fetch_perm(), L is unit upper
#         triangular and B is block diagonal with 1x1 and 2x2
#         blocks. Access to the factors is available as soon
#         as a PyMa27Context has been instantiated.
#         """
#         self.context.fetchlb( self.L, self.B )
#         return None


if __name__ == '__main__':

    import sys
    from pysparse.sparse import spmatrix
    import numpy as np

    M = spmatrix.ll_mat_from_mtx( sys.argv[1] )
    (m,n) = M.shape
    if m != n:
        sys.stderr( 'Matrix must be square' )
        sys.exit(1)
    if not M.issym:
        sys.stderr( 'Matrix must be symmetric' )
        sys.exit(2)
    e = numpy.ones( n, 'd' )
    rhs = numpy.zeros( n, 'd' )
    M.matvec( e, rhs )
    sys.stderr.write( ' Factorizing matrix... ' )
    G = PyMa57Context( M )
    w = sys.stderr.write
    w( ' done\n' )
    w( ' Matrix order = %d\n' % G.n )
Exemplo n.º 7
0
import nltk, sys


#Variables indicadores comparativos tag documents
archivo1 = sys.argv[1] #matriz dispersa matlab labels
archivo2 = sys.argv[2] #documentos labels
archivo3 = sys.argv[3] #tokens labels

archivo4 = sys.argv[4] #matriz dispersa matlab text
archivo5 = sys.argv[5] #documentos text
clase = sys.argv[6] #clase o etiqueta a buscar

matrizDispersa = np.loadtxt(archivo1, delimiter=",", dtype='str')
documents = np.loadtxt(archivo2, delimiter=",", dtype='str')
tokens = np.loadtxt(archivo3, delimiter=" ", dtype='str')
spmatrix.ll_mat_from_mtx(fileName)


#inicializacion de variables
arrayDocs = []
DocumentsGenerated = []

countD = 0
count = 0

#Encontrar los documentos que contienen la clase
for i in range(len(tokens)):
	if re.match(clase, tokens[i,0]):
		lineaClase = i

for i in range(len(matrizDispersa[0,:])): #terminos
Exemplo n.º 8
0
print L
print L.nnz

#------------------------------------------------------------

if 0:
    f = open(os.environ['HOME']+'/matrices/poi2d_300.mtx')
    t1 = time.clock()
    L = ll_mat_from_mtx(f)
    t_read = time.clock() - t1
    f.close()
    print 'time for reading matrix data from file: %.2f sec' % t_read

if 1:
    t1 = time.clock()
    L = spmatrix.ll_mat_from_mtx(os.environ['HOME']+'/matrices/poi2d_300.mtx')
    t_read = time.clock() - t1
    print 'time for reading matrix data from file: %.2f sec' % t_read

#------------------------------------------------------------

L = spmatrix.ll_mat_from_mtx(os.environ['HOME']+'/matrices/node4x3x1_A.mtx')
print L.shape, L.nnz

A = L.to_sss()

class diag_prec:
    def __init__(self, A):
        self.shape = A.shape
        n = self.shape[0]
        self.dinv = np.zeros(n, 'd')
Exemplo n.º 9
0
def test_pcg(ProblemList, tol=1.0e-6):

    if len(ProblemList) == 0:
        usage()
        sys.exit(1)
    
    header1 = '%10s  %6s  %6s  ' % ('Name', 'n', 'nnz')
    header2 = '%6s  %8s  %8s  %4s  %6s  %6s\n' % ('iter','relres','error','info','form M','solve')
    dheader1 = '%10s  %6d  %6d  '
    dheader2 = '%6d  %8.1e  %8.1e  %4d  %6.2f  %6.2f\n' 
    lhead1 = len(header1)
    lhead2 = len(header2)
    lhead = lhead1 + lhead2
    sys.stderr.write('-' * lhead + '\n')
    sys.stderr.write(header1)
    sys.stderr.write(header2)
    sys.stderr.write('-' * lhead + '\n')

    # Record timings for each preconditioner
    timings = { 'None' : [],
                'Diagonal' : [],
                'SSOR' : []
              }

    for problem in ProblemList:
    
        A = spmatrix.ll_mat_from_mtx(problem)
        (m, n) = A.shape
        if m != n: break
    
        prob = os.path.basename(problem)
        if prob[-4:] == '.mtx': prob = prob[:-4]

        # Right-hand side is Ae
        e = np.ones(n, 'd')
        b = np.empty(n, 'd')
        A.matvec(e, b)

        sys.stdout.write(dheader1 % (prob, n, A.nnz))

        # No preconditioner
        x = np.zeros(n, 'd')
        t = cputime()
        info, iter, relres = pcg(A, b, x, tol, 2*n)
        t_noprec = cputime() - t
        err = np.linalg.norm(x-e, ord=np.Inf)
        sys.stdout.write(dheader2 % (iter, relres, err, info, 0.0, t_noprec))
        timings['None'].append(t_noprec)

        # Diagonal preconditioner
        x = np.zeros(n, 'd')
        t = cputime()
        M = precon.jacobi(A, 1.0, 1)
        t_getM_diag = cputime() - t
        t = cputime()
        info, iter, relres = pcg(A, b, x, tol, 2*n, M)
        t_diag = cputime() - t
        err = np.linalg.norm(x-e, ord=np.Inf)
        sys.stdout.write(lhead1 * ' ')
        sys.stdout.write(dheader2 % (iter,relres,err,info,t_getM_diag,t_diag))
        timings['Diagonal'].append(t_diag)

        # SSOR preconditioner
        # It appears that steps=1 and omega=1.0 are nearly optimal in all cases
        x = np.zeros(n, 'd')
        t = cputime()
        M = precon.ssor(A.to_sss(), 1.0, 1)
        t_getM_ssor = cputime() - t
        t = cputime()
        info, iter, relres = pcg(A, b, x, tol, 2*n, M)
        t_ssor = cputime() - t
        err = np.linalg.norm(x-e, ord=np.Inf)
        sys.stdout.write(lhead1 * ' ')
        sys.stdout.write(dheader2 % (iter,relres,err,info,t_getM_ssor,t_ssor))
        timings['SSOR'].append(t_ssor)
        sys.stderr.write('-' * lhead + '\n')

    return timings