Ejemplo n.º 1
0
 def time_solve(self, n, solver):
     if solver == 'dense':
         linalg.solve(self.P_dense, self.b)
     elif solver == 'cg':
         cg(self.P_sparse, self.b)
     elif solver == 'minres':
         minres(self.P_sparse, self.b)
     elif solver == 'gmres':
         gmres(self.P_sparse, self.b)
     elif solver == 'lgmres':
         lgmres(self.P_sparse, self.b)
     elif solver == 'gcrotmk':
         gcrotmk(self.P_sparse, self.b)
     elif solver == 'spsolve':
         spsolve(self.P_sparse, self.b)
     else:
         raise ValueError('Unknown solver: %r' % solver)
Ejemplo n.º 2
0
    def iterate(self,Keff_solve,f_new,u,du,ddu):
        """Newmark's iteration"""
        R_new = f_new + self.M.dot(self.a0*u + self.a2*du + self.a3*ddu) + self.C.dot(self.a1*u + self.a4*du + self.a5*ddu)

        u_new = sla.gcrotmk(self.Keff,R_new,M=self.Keff_prec,x0=u,atol=1e-5)[0]

        ddu_new = self.a0*(u_new - u) - self.a2*du - self.a3*ddu
        du_new = du + self.a6*ddu + self.a7*ddu_new
        return u_new,du_new,ddu_new
Ejemplo n.º 3
0
 def __solve_linear_problem__(self, matr_multiply, b_vector, x0, precond=None):
     self.l("  Solving linear problem ...")
     size = len(b_vector)
     Ax = spla.LinearOperator((size, size), matr_multiply)
     if precond is not None:
         mx = spla.LinearOperator((size, size), precond)
     else:
         mx = None
     result, info = spla.gcrotmk(Ax, b_vector, x0=x0, callback=self.__spla_callback__, M=mx, atol=0, tol=1e-1)
     if info != 0:
         raise RuntimeError("Error solving linear problem: info={:d}".format(info))
     return result
Ejemplo n.º 4
0
def time_solve(drop_tol, fill_factor):
    try:
        iLU = spilu(A.tocsc(), fill_factor=fill_factor, drop_tol=10**drop_tol)
    except:
        print("Runtime error")
        return np.nan
    iLUx = lambda x: iLU.solve(x)
    P = LinearOperator(A.shape, iLUx)
    ## Solve the equation
    start_time = time.time()
    x, info = gcrotmk(A, b, tol=tol, atol=tol, maxiter=1000, M=P)
    elapsed = time.time() - start_time
    print("Completed Fill factor", fill_factor, "at drop tol", 10**drop_tol,
          "in", elapsed)
    return elapsed
Ejemplo n.º 5
0
def gf_iter(interface, ps, qs, energies, return_ncalls=False, debug=False, **kwargs):
    """Conventional GF iterations."""
    e_vector = list()
    interface.logger.note("Starting a GF calculation n_p x n_q = {:d} x {:d}".format(
        len(ps),
        len(qs),
    ))
    interface.logger.log("Calculating kets ({:d}) ...".format(len(qs)))
    for q in qs:
        e_vector.append(interface.make_e(q))
    matvec_callable = CallCounter(interface.matvec_logging if debug else interface.matvec)
    __ncalls_prev__ = 0
    gfvals = np.zeros((len(ps), len(qs), len(energies)), dtype=complex)
    interface.logger.log("Calculating bras ({:d}) ...".format(len(ps)))
    for ip, p in enumerate(ps):
        b_vector = np.array(interface.make_b(p), dtype=complex)
        for i_energy, energy in enumerate(energies):
            interface.logger.debug1("Calculating bra @ p={:d} e={:d} ... ({:.0f} complete)".format(
                ip, i_energy, 100.0 * (ip*len(energies) + i_energy) / len(ps) / len(energies)))
            size = len(b_vector)
            Ax = spla.LinearOperator((size, size), lambda vector: matvec_callable(vector, energy))
            mx = spla.LinearOperator((size, size), interface.precond(energy))
            x0 = interface.iguess(p, energy)
            if debug:
                interface.reset_log(rhs=b_vector)
            sol, info = spla.gcrotmk(Ax, b_vector, x0=x0, M=mx, **kwargs)
            if debug:
                interface.plot_log()
            interface.logger.debug1("Complete with {:d} matvec calls".format(matvec_callable.n_calls - __ncalls_prev__))
            interface.logger.debug2("Initial guess: {}".format(repr(x0)))
            interface.logger.debug2("Solution: {}".format(repr(sol)))
            interface.logger.debug1("Norm: {:.3e}, initial guess ovlp: {:.3e}, diagonal: {:.3e}".format(
                np.linalg.norm(sol), sol.dot(x0), np.dot(e_vector[ip], sol)))
            __ncalls_prev__ = matvec_callable.n_calls
            if info != 0:
                raise RuntimeError("Error solving linear problem: info={:d}".format(info))
            for iq, q in enumerate(qs):
                gfvals[ip, iq, i_energy] = np.dot(e_vector[iq], sol)
    if return_ncalls:
        return gfvals, matvec_callable.n_calls
    else:
        return gfvals
def runFastSinkSource(P,
                      positives,
                      negatives=None,
                      max_iters=1000,
                      eps=0.0001,
                      a=0.8,
                      tol=1e-5,
                      solver=None,
                      Milu=None,
                      verbose=False):
    """
    *P*: Network ags a scipy sparse matrix. Should already be normalized
    *positives*: numpy array of node ids to be used as positives
    *negatives*: numpy array of node ids to be used as negatives. 
        If not given, will be run as FastSinkSourcePlus. 
        For FastSinkSourcePlus, if the lambda parameter is desired, it should already have been included in the graph normalization process. 
        See the function normalizeGraphEdgeWeights in alg_utils.py 
    *max_iters*: max # of iterations to run SinkSource. 
        If 0, use spsolve to solve the equation directly 
    """
    num_nodes = P.shape[0]
    if len(positives) == 0:
        print("WARNING: No positive examples given. Skipping.")
        return np.zeros(num_nodes), 0, 0, 0
    # remove the positive and negative nodes from the graph
    # and setup the f vector which contains the influence from positive and negative nodes
    newP, f, = alg_utils.setup_fixed_scores(P,
                                            positives,
                                            negatives,
                                            a=a,
                                            remove_nonreachable=False)

    if solver is None:
        s, process_time, wall_time, num_iters = FastSinkSource(
            newP, f, max_iters=max_iters, eps=eps, a=a, verbose=verbose)
    else:
        # Solve for s directly. Scipy uses the form Ax=b to solve for x
        # SinkSource equation: (I - aP)s = f
        #solvers = ['bicg', 'bicgstab', 'cg', 'cgs', 'gmres', 'lgmres', 'minres', 'qmr', 'gcrotmk']#, 'lsmr']
        # eye is the identity matrix
        #M = eye(P.shape[0]) - a*P
        M = eye(newP.shape[0]) - a * newP

        # keep track of the number of iterations
        def callback(xk):
            # keep the reference to the variable within the callback function (Python 3)
            nonlocal num_iters
            num_iters += 1

        # this measures the amount of time taken by all processors
        start_process_time = time.process_time()
        # this measures the amount of time that has passed
        start_wall_time = time.time()
        num_iters = 0
        # spsolve basically stalls for large or dense networks (e.g., e-value cutoff 0.1)
        if solver == 'spsolve':
            s = linalg.spsolve(M, f)
        elif solver == 'bicg':
            s, info = linalg.bicg(M,
                                  f,
                                  tol=tol,
                                  maxiter=max_iters,
                                  M=Milu,
                                  callback=callback)
        elif solver == 'bicgstab':
            s, info = linalg.bicgstab(M,
                                      f,
                                      tol=tol,
                                      maxiter=max_iters,
                                      M=Milu,
                                      callback=callback)
        elif solver == 'cg':
            s, info = linalg.cg(M,
                                f,
                                tol=tol,
                                maxiter=max_iters,
                                M=Milu,
                                callback=callback)
        elif solver == 'cgs':
            s, info = linalg.cgs(M,
                                 f,
                                 tol=tol,
                                 maxiter=max_iters,
                                 M=Milu,
                                 callback=callback)
        elif solver == 'gmres':
            s, info = linalg.gmres(M,
                                   f,
                                   tol=tol,
                                   maxiter=max_iters,
                                   M=Milu,
                                   callback=callback)
        elif solver == 'lgmres':
            s, info = linalg.lgmres(M,
                                    f,
                                    tol=tol,
                                    maxiter=max_iters,
                                    M=Milu,
                                    callback=callback)
        elif solver == 'minres':
            s, info = linalg.minres(M,
                                    f,
                                    tol=tol,
                                    maxiter=max_iters,
                                    M=Milu,
                                    callback=callback)
        elif solver == 'qmr':
            s, info = linalg.qmr(M,
                                 f,
                                 tol=tol,
                                 maxiter=max_iters,
                                 M=Milu,
                                 callback=callback)
        elif solver == 'gcrotmk':
            s, info = linalg.gcrotmk(M,
                                     f,
                                     tol=tol,
                                     maxiter=max_iters,
                                     M=Milu,
                                     callback=callback)
        #elif solver == 'lsmr':
        #    s, info = linalg.lsmr(M, f, maxiter=max_iters, callback=callback)

        process_time = time.process_time() - start_process_time
        wall_time = time.time() - start_wall_time
        if verbose:
            print("Solved SS using %s (%0.3f sec, %0.3f process time). %s" %
                  (solver, wall_time, process_time,
                   "iters: %d, max_iters: %d, info: %s" %
                   (num_iters, 1000, info) if solver != 'spsolve' else ''))

    # keep the positive examples at 1
    s[positives] = 1

    return s, process_time, wall_time, num_iters