Beispiel #1
0
    def test_real_lu(self):
        """Getting factors of real matrix"""
        umfpack = um.UmfpackContext("di")

        for A in self.real_matrices:
            umfpack.numeric(A)

            (L,U,P,Q,R,do_recip) = umfpack.lu(A)

            L = L.todense()
            U = U.todense()
            A = A.todense()
            if not do_recip: R = 1.0/R
            R = matrix(diag(R))
            P = eye(A.shape[0])[P,:]
            Q = eye(A.shape[1])[:,Q]

            assert_array_almost_equal(P*R*A*Q,L*U)
Beispiel #2
0
# needed to speed up a few cases.
# See discussions at:
# https://groups.google.com/d/msg/scikit-image/FrM5IGP6wh4/1hp-FtVZmfcJ
# http://stackoverflow.com/questions/13977970/ignore-exceptions-printed-to-stderr-in-del/13977992?noredirect=1#comment28386412_13977992
try:
    from scipy.sparse.linalg.dsolve import umfpack
    old_del = umfpack.UmfpackContext.__del__

    def new_del(self):
        try:
            old_del(self)
        except AttributeError:
            pass

    umfpack.UmfpackContext.__del__ = new_del
    UmfpackContext = umfpack.UmfpackContext()
except:
    UmfpackContext = None

try:
    from pyamg import ruge_stuben_solver
    amg_loaded = True
except ImportError:
    amg_loaded = False
from scipy.sparse.linalg import cg
from ..util import img_as_float
from ..filter import rank_order

#-----------Laplacian--------------------

def main():
    parser = OptionParser(usage=usage)
    parser.add_option(
        "-c",
        "--compare",
        action="store_true",
        dest="compare",
        default=False,
        help="compare with default scipy.sparse solver [default: %default]")
    parser.add_option("-p",
                      "--plot",
                      action="store_true",
                      dest="plot",
                      default=False,
                      help="plot time statistics [default: %default]")
    parser.add_option("-d",
                      "--default-url",
                      action="store_true",
                      dest="default_url",
                      default=False,
                      help="use default url [default: %default]")
    parser.add_option("-f",
                      "--format",
                      type=type(''),
                      dest="format",
                      default='triplet',
                      help="matrix format [default: %default]")
    (options, args) = parser.parse_args()

    if (len(args) >= 1):
        matrixNames = args
    else:
        parser.print_help(),
        return

    sizes, nnzs, times, errors = [], [], [], []
    legends = ['umfpack', 'sparse.solve']
    for ii, matrixName in enumerate(matrixNames):

        print('*' * 50)
        mtx = readMatrix(matrixName, options)

        sizes.append(mtx.shape)
        nnzs.append(mtx.nnz)
        tts = np.zeros((2, ), dtype=np.double)
        times.append(tts)
        err = np.zeros((2, 2), dtype=np.double)
        errors.append(err)

        print('size              : %s (%d nnz)' % (mtx.shape, mtx.nnz))

        sol0 = np.ones((mtx.shape[0], ), dtype=np.double)
        rhs = mtx * sol0

        umfpack = um.UmfpackContext()

        tt = time.clock()
        sol = umfpack(um.UMFPACK_A, mtx, rhs, autoTranspose=True)
        tts[0] = time.clock() - tt
        print("umfpack           : %.2f s" % tts[0])

        error = mtx * sol - rhs
        err[0, 0] = nla.norm(error)
        print('||Ax-b||          :', err[0, 0])

        error = sol0 - sol
        err[0, 1] = nla.norm(error)
        print('||x - x_{exact}|| :', err[0, 1])

        if options.compare:
            tt = time.clock()
            sol = sp.solve(mtx, rhs)
            tts[1] = time.clock() - tt
            print("sparse.solve      : %.2f s" % tts[1])

            error = mtx * sol - rhs
            err[1, 0] = nla.norm(error)
            print('||Ax-b||          :', err[1, 0])

            error = sol0 - sol
            err[1, 1] = nla.norm(error)
            print('||x - x_{exact}|| :', err[1, 1])

    if options.plot:
        try:
            import pylab
        except ImportError:
            raise ImportError("could not import pylab")
        times = np.array(times)
        print(times)
        pylab.plot(times[:, 0], 'b-o')
        if options.compare:
            pylab.plot(times[:, 1], 'r-s')
        else:
            del legends[1]

        print(legends)

        ax = pylab.axis()
        y2 = 0.5 * (ax[3] - ax[2])
        xrng = list(range(len(nnzs)))
        for ii in xrng:
            yy = y2 + 0.4 * (ax[3] - ax[2])\
                 * np.sin( ii * 2 * np.pi / (len( xrng ) - 1) )

            if options.compare:
                pylab.text(
                    ii + 0.02, yy, '%s\n%.2e err_umf\n%.2e err_sp' %
                    (sizes[ii], np.sum(
                        errors[ii][0, :]), np.sum(errors[ii][1, :])))
            else:
                pylab.text(
                    ii + 0.02, yy,
                    '%s\n%.2e err_umf' % (sizes[ii], np.sum(errors[ii][0, :])))
            pylab.plot([ii, ii], [ax[2], ax[3]], 'k:')

        pylab.xticks(xrng, ['%d' % (nnzs[ii]) for ii in xrng])
        pylab.xlabel('nnz')
        pylab.ylabel('time [s]')
        pylab.legend(legends)
        pylab.axis([ax[0] - 0.05, ax[1] + 1, ax[2], ax[3]])
        pylab.show()