Exemplo n.º 1
0
    def build(self, A=None, preconditioner = 'spilu',**kwargs):
        super().build(A,**kwargs)
        A = self._A
        if preconditioner == 'spilu':
            M = spla.spilu(A)
            M = spla.LinearOperator(A.shape,M.solve)

            self.__solve = lambda b: spla.bicg(A,b,**kwargs)
        else:
            self.__solve = lambda b: spla.bicg(A,b,**kwargs)
        self.built = True
        return self
def mm_quadratic(x0,
                 y,
                 H,
                 G,
                 lamb,
                 delta,
                 theta=1.0,
                 maxit=2000,
                 eps=1e-3 * np.sqrt(N)):
    it = 0
    grad_norm = np.inf
    x = x0.copy()
    grad_norms = []
    timing_list = []
    while it <= maxit and grad_norm > eps:
        start = time.clock()
        linop = create_linear_operator(x, H, G, lamb, delta)
        grad = gradient(H, G, x, y, delta, lamb)
        grad_norm = np.linalg.norm(grad)
        grad_norms.append(grad_norm)
        # We set a very low number of iteration which results in a low precision in the solution,
        # But an approximate direction is enough in that case and it speeds up the process dramatically
        xsol, success = sparselinalg.bicg(linop, b=grad, maxiter=50)
        x -= theta * xsol
        it += 1
        end = time.clock()
        timing_list.append(end - start)
        print(grad_norm)
    return x, grad_norms, np.cumsum(timing_list)
def solve(A, b, method, tol=1e-3):
    """ General sparse solver interface.

    method can be one of
    - spsolve_umfpack_mmd_ata
    - spsolve_umfpack_colamd
    - spsolve_superlu_mmd_ata
    - spsolve_superlu_colamd
    - bicg
    - bicgstab
    - cg
    - cgs
    - gmres
    - lgmres
    - minres
    - qmr
    - lsqr
    - lsmr
    """

    if method == 'spsolve_umfpack_mmd_ata':
        return spla.spsolve(A, b, use_umfpack=True, permc_spec='MMD_ATA')
    elif method == 'spsolve_umfpack_colamd':
        return spla.spsolve(A, b, use_umfpack=True, permc_spec='COLAMD')
    elif method == 'spsolve_superlu_mmd_ata':
        return spla.spsolve(A, b, use_umfpack=False, permc_spec='MMD_ATA')
    elif method == 'spsolve_superlu_colamd':
        return spla.spsolve(A, b, use_umfpack=False, permc_spec='COLAMD')
    elif method == 'bicg':
        res = spla.bicg(A, b, tol=tol)
        return res[0]
    elif method == 'bicgstab':
        res = spla.bicgstab(A, b, tol=tol)
        return res[0]
    elif method == 'cg':
        res = spla.cg(A, b, tol=tol)
        return res[0]
    elif method == 'cgs':
        res = spla.cgs(A, b, tol=tol)
        return res[0]
    elif method == 'gmres':
        res = spla.gmres(A, b, tol=tol)
        return res[0]
    elif method == 'lgmres':
        res = spla.lgmres(A, b, tol=tol)
        return res[0]
    elif method == 'minres':
        res = spla.minres(A, b, tol=tol)
        return res[0]
    elif method == 'qmr':
        res = spla.qmr(A, b, tol=tol)
        return res[0]
    elif method == 'lsqr':
        res = spla.lsqr(A, b, atol=tol, btol=tol)
        return res[0]
    elif method == 'lsmr':
        res = spla.lsmr(A, b, atol=tol, btol=tol)
        return res[0]
    else:
        raise Exception('UnknownSolverType')
Exemplo n.º 4
0
def false_transient(A, B, C, D, v0, ϵ, dx, bc, impose_bc):
    r"""
    Implement false transient scheme of one iteration,
    and update from :math:`\phi_i(y)` to :math:`\phi_{i+1}(y)`
    according to :math:numref:`FT`.
    
    See appendix B(TODO: cross-ref link) for further detail.
    
    Parameters
    ----------
    A, B, C, D: 
        Same as those in :func:`~source.solver.compute_coefficient`
    v0 : (I, ) ndarrays
        Value function from last iteration, :math:`\phi_i(y)`
    ϵ : float
        Step size of false transient
    dx : float
        Step size of Grid
    bc : 
        See :func:`~source.solver.linearize`.
    impose_bc:
        See :func:`~source.solver.linearize`.
        
    Returns
    -------
    v :  (I, ) ndarrays
        Updated value function, :math:`\phi_{i+1}(y)` according to :math:numref:`FT`.
    """
    LHS, RHS = linearize(A, B, C, D, v0, ϵ, dx, bc, impose_bc)
    v, exit_code = bicg(csc_matrix(LHS), RHS)
    return v
Exemplo n.º 5
0
    def solve(self):
        '''
        Method that solves the linear equations system.
        
        Param:
            -
        Return:
            -
        '''
        G = self.__matrix.getMatrix()
        f = self.__matrix.getfv()

        if self.__algorithm == 'linalg':
            self.__lam = np.linalg.solve(G, f)
        elif self.__algorithm == 'bicgstab':
            A = sps.csr_matrix(G)
            self.__lam = spla.bicgstab(A, f)[0]
        elif self.__algorithm == 'bicg':
            A = sps.csr_matrix(G)
            self.__lam = spla.bicg(A, f)[0]
        elif self.__algorithm == 'cg':
            A = sps.csr_matrix(G)
            self.__lam = spla.cg(A, f)[0]
        elif self.__algorithm == 'gmres':
            A = sps.csr_matrix(G)
            self.__lam = spla.gmres(A, f)[0]
    def solve(self, tol=1e-08, maxiter=100000):
        """
            Solve discretized system with BiCG.
            Input parameters:
                - "tol" - tolerence for the error
                - "maxiter" - needed to tune iterations properly
        """

        nn = self.n**2
        x_zero = np.zeros(nn)
        mtx = csr_matrix((self.a, self.ja, self.ia), shape=(nn, nn))
        rmtx = csr_matrix((self.ra, self.jra, self.ira), shape=(nn, nn))
        self.stack = x_zero

        for i in range(self.T):
            right = (rmtx @ x_zero) + self.f
            x_appr, info = bicg(mtx,
                                right,
                                x0=np.zeros(nn),
                                tol=tol,
                                maxiter=maxiter)
            self.stack = np.vstack((self.stack, x_appr))
            x_zero = x_appr.copy()

            if info > 0:
                print("Iterations number: ", info)
                self.iter = info
                return info
Exemplo n.º 7
0
    def optimize(self, x0):
        x_n = x0.copy()
        self.init_time()

        for k in tqdm(range(self.max_iter), disable=self.disable_progressbar):
            j = (k - 1) % self.j_total
            j += 1
            block_indices = self.get_block_indices(j)
            all_grad = self.grad_f(x_n)
            grad_j = all_grad[block_indices]

            # a_j = self.get_a_j(my_x=x_n, block_indices=block_indices)
            # x_n_j = x_n[block_indices].copy()
            # a_j_inv = np.linalg.inv(a_j)
            # x_n_j = x_n_j - self.theta * a_j_inv.dot(grad_j)

            a_j = self.get_operator(
                self.get_a_j(my_x=x_n, block_indices=block_indices))
            # print(a_j.shape, grad_j.shape)
            right_term = bicg(A=a_j, b=grad_j)
            right_term = right_term[0]
            x_n_j = x_n[block_indices].copy()
            x_n_j = x_n_j - self.theta * right_term

            x_n[block_indices] = x_n_j
            self.f_eval(x_n)

            if self.has_converged(x_n):
                print('Method has converged')
                break

        return x_n, (self.times, self.f_vals)
Exemplo n.º 8
0
    def solve(self, x_0=None, tol=1e-05, max_iter=100, exchange_zero=1e-16):
        """
        Solve the equation *A * x = b* using an linear equation solver. After
        solving old unknown vectors and volume field values are overwritten.
        """
        if self.solver   == "cg":
            solver_return = lin.cg(self.A, self.b, x_0, tol, max_iter)
        elif self.solver == "bicg":
            solver_return = lin.bicg(self.A, self.b, x_0, tol, max_iter)
        elif self.solver == "lu_solver":
             solver_return = mylin.lu_solver_plu(self.p, self.l, self.u, self.b)
        elif self.solver == "lu_solver":
             solver_return = mylin.gs(self.A, self.b, x_0, tol, max_iter)
        self.x         = solver_return[0]
        self.x_old_old = self.x_old
        
        # find max absolute residual
        diff_ = abs(self.x - self.x_old)
        max_diff_ = max(diff_)
        if max_diff_ == 0.:
            self.residuals.append(exchange_zero)
        else:
            self.residuals.append(max_diff_)
        print 'Residual for ' + self.field.name + ': ' + str(max(diff_))
        
        #update volume field
        self.field.V = self.x_old + self.under_relax*(self.x - self.x_old)
#        self.field.V = self.x
        
        return True
Exemplo n.º 9
0
def linear_solver(Afun=None, ATfun=None, B=None, x0=None, par=None,
                  solver=None, callback=None):
    if callback is not None:
        callback(x0)
    if solver == 'CG':
        x, info = CG(Afun, B, x0=x0, par=par, callback=callback)
    elif solver == 'iterative':
        x, info = richardson(Afun, B, x0, par=par, callback=callback)
    else:
        from scipy.sparse.linalg import LinearOperator, cg, bicg
        if solver == 'scipy_cg':
            Afun.define_operand(B)
            Afunvec = LinearOperator(Afun.shape, matvec=Afun.matvec,
                                     dtype=np.float64)
            xcol, info = cg(Afunvec, B.vec(), x0=x0.vec(),
                            tol=par['tol'],
                            maxiter=par['maxiter'],
                            xtype=None, M=None, callback=callback)
        elif solver == 'scipy_bicg':
            Afun.define_operand(B)
            ATfun.define_operand(B)
            Afunvec = LinearOperator(Afun.shape, matvec=Afun.matvec,
                                     rmatvec=ATfun.matvec, dtype=np.float64)
            xcol, info = bicg(Afunvec, B.vec(), x0=x0.vec(),
                              tol=par['tol'],
                              maxiter=par['maxiter'],
                              xtype=None, M=None, callback=callback)
        res = dict()
        res['info'] = info
        x = VecTri(val=np.reshape(xcol, B.dN()))
    return x, info
Exemplo n.º 10
0
    def solve(self, x_0=None, tol=1e-05, max_iter=100, exchange_zero=1e-16):
        """
        Solve the equation *A * x = b* using an linear equation solver. After
        solving old unknown vectors and volume field values are overwritten.
        """
        if self.solver == "cg":
            solver_return = lin.cg(self.A, self.b, x_0, tol, max_iter)
        elif self.solver == "bicg":
            solver_return = lin.bicg(self.A, self.b, x_0, tol, max_iter)
        elif self.solver == "lu_solver":
            solver_return = mylin.lu_solver_plu(self.p, self.l, self.u, self.b)
        elif self.solver == "lu_solver":
            solver_return = mylin.gs(self.A, self.b, x_0, tol, max_iter)
        self.x = solver_return[0]
        self.x_old_old = self.x_old

        # find max absolute residual
        diff_ = abs(self.x - self.x_old)
        max_diff_ = max(diff_)
        if max_diff_ == 0.:
            self.residuals.append(exchange_zero)
        else:
            self.residuals.append(max_diff_)
        print 'Residual for ' + self.field.name + ': ' + str(max(diff_))

        #update volume field
        self.field.V = self.x_old + self.under_relax * (self.x - self.x_old)
        #        self.field.V = self.x

        return True
Exemplo n.º 11
0
def main():
    # init_rand()
    # x = np.linalg.solve(A, b)
    # conjgrad(A, b, x)
    # x, exitCode = cg(A, b, tol=1e-8)
    x, exitCode = bicg(A, b, tol=1e-8)
    #x, exitCode = bicgstab(A, b, tol=1e-8)
    return x
Exemplo n.º 12
0
def linear_solver(Afun=None,
                  ATfun=None,
                  B=None,
                  x0=None,
                  par=None,
                  solver=None,
                  callback=None):
    """
    Wraper for various linear solvers suited for FFT-based homogenization.
    """
    if callback is not None:
        callback(x0)

    if solver.lower() in ['cg']:  # conjugate gradients
        x, info = CG(Afun, B, x0=x0, par=par, callback=callback)
    elif solver.lower() in ['bicg']:  # biconjugate gradients
        x, info = BiCG(Afun, ATfun, B, x0=x0, par=par, callback=callback)
    elif solver.lower() in ['iterative']:  # iterative solver
        x, info = richardson(Afun, B, x0, par=par, callback=callback)
    elif solver.split('_')[0].lower() in ['scipy']:  # solvers in scipy
        from scipy.sparse.linalg import LinearOperator, cg, bicg
        if solver == 'scipy_cg':
            Afun.define_operand(B)
            Afunvec = LinearOperator(Afun.shape,
                                     matvec=Afun.matvec,
                                     dtype=np.float64)
            xcol, info = cg(Afunvec,
                            B.vec(),
                            x0=x0.vec(),
                            tol=par['tol'],
                            maxiter=par['maxiter'],
                            xtype=None,
                            M=None,
                            callback=callback)
        elif solver == 'scipy_bicg':
            Afun.define_operand(B)
            ATfun.define_operand(B)
            Afunvec = LinearOperator(Afun.shape,
                                     matvec=Afun.matvec,
                                     rmatvec=ATfun.matvec,
                                     dtype=np.float64)
            xcol, info = bicg(Afunvec,
                              B.vec(),
                              x0=x0.vec(),
                              tol=par['tol'],
                              maxiter=par['maxiter'],
                              xtype=None,
                              M=None,
                              callback=callback)
        res = dict()
        res['info'] = info
        x = VecTri(val=np.reshape(xcol, B.dN()))
    else:
        msg = "This kind (%s) of linear solver is not implemented" % solver
        raise NotImplementedError(msg)

    return x, info
Exemplo n.º 13
0
    def get_circulation_on_panel(self):
        for i in range(self.p_size):
            self.b[i] = self.get_velocity_from_vortex(
                self.ref[i],
                dist_vector=-self.delta[i] / self.len[i],
                include_panel=False)  # panel上の渦分布は未知

        self.b[self.p_size] = -self.get_circulation_sum()

        self.gamma = spla.bicg(self.tAA, np.dot(self.tA, self.b))[0]
        error = np.dot(self.tA.T, self.gamma) - self.b
Exemplo n.º 14
0
def linear_solver(Afun, B, ATfun=None, x0=None, par=None,
                  solver=None, callback=None):
    """
    Wraper for various linear solvers suited for FFT-based homogenization.
    """
    tim = Timer('Solving linsys by %s' % solver)
    if x0 is None:
        x0 = B.zeros_like()

    if callback is not None:
        callback(x0)

    if solver.lower() in ['cg']: # conjugate gradients
        x, info = CG(Afun, B, x0=x0, par=par, callback=callback)
    elif solver.lower() in ['bicg']: # biconjugate gradients
        x, info = BiCG(Afun, ATfun, B, x0=x0, par=par, callback=callback)
    elif solver.lower() in ['iterative', 'richardson']: # iterative solver
        x, info = richardson(Afun, B, x0, par=par, callback=callback)
    elif solver.lower() in ['chebyshev', 'cheby']: # iterative solver
        x, info = cheby2TERM(A=Afun, B=B, x0=x0, par=par, callback=callback)
    elif solver.split('_')[0].lower() in ['scipy']: # solvers in scipy
        if isinstance(x0, np.ndarray):
            x0vec=x0.ravel()
        else:
            x0vec=x0.vec()

        if solver in ['scipy.sparse.linalg.cg','scipy_cg']:
            Afun.define_operand(B)
            Afunvec = spslin.LinearOperator(Afun.matshape, matvec=Afun.matvec,
                                            dtype=np.float64)
            xcol, info = spslin.cg(Afunvec, B.vec(), x0=x0vec,
                                   tol=par['tol'], maxiter=par['maxiter'],
                                   M=None, callback=callback)
            info = {'info': info}
        elif solver in ['scipy.sparse.linalg.bicg','scipy_bicg']:
            Afun.define_operand(B)
            ATfun.define_operand(B)
            Afunvec = spslin.LinearOperator(Afun.shape, matvec=Afun.matvec,
                                            rmatvec=ATfun.matvec, dtype=np.float64)
            xcol, info = spslin.bicg(Afunvec, B.vec(), x0=x0.vec(),
                                     tol=par['tol'], maxiter=par['maxiter'],
                                     M=None, callback=callback)
        res = dict()
        res['info'] = info
        x = B.empty_like(name='x')
        x.val = np.reshape(xcol, B.val.shape)
    else:
        msg = "This kind (%s) of linear solver is not implemented" % solver
        raise NotImplementedError(msg)

    tim.measure(print_time=False)
    info.update({'time': tim.vals})
    return x, info
Exemplo n.º 15
0
def test(mesh, normalize=False, scipy_solver='lu'):
    V = FunctionSpace(mesh, 'Lagrange', 1)
    bc = DirichletBC(V, Constant(0.0), DomainBoundary())

    u = TrialFunction(V)
    v = TestFunction(V)

    f = Constant(1.0)
    a = inner(grad(u), grad(v)) * dx
    L = f * v * dx

    A, b = assemble_system(a, L, bc)

    if normalize:
        max = A.array().max()
        A /= max
        b /= max

    u = Function(V)
    solve(A, u.vector(), b)
    plot(u, interactive=True, title='dolfin')

    x = A.array()
    print "Value of A are [%g, %g]" % (x.min(), x.max())
    print "Num of entries in A larger theb 100", np.where(x > 1E2)[0].sum()
    print "Number of mesh cells", mesh.num_cells()

    # see about scipy
    rows, cols, values = A.data()
    B = csr_matrix((values, cols, rows))
    d = b.array().T

    if scipy_solver == 'cg':
        v_, info = cg(B, d)
    elif scipy_solver == 'bicg':
        v_, info = bicg(B, d)
    elif scipy_solver == 'bicgstab':
        v_, info = bicgstab(B, d)
    elif scipy_solver == 'gmres':
        v_, info = gmres(B, d)
    elif scipy_solver == 'minres':
        v_, info = minres(B, d)
    else:
        v_ = spsolve(B, d)

    v = Function(V)
    v.vector()[:] = v_
    plot(v, interactive=True, title='scipy')
    try:
        print "info", info, 'v_max', v_.max()
    except:
        pass
Exemplo n.º 16
0
def test(mesh, normalize=False, scipy_solver='lu'):
  V = FunctionSpace(mesh, 'Lagrange', 1)
  bc= DirichletBC(V, Constant(0.0), DomainBoundary())

  u  =TrialFunction(V)
  v = TestFunction(V)

  f = Constant(1.0)
  a = inner(grad(u), grad(v))*dx
  L = f*v*dx

  A, b = assemble_system(a, L, bc)

  if normalize:
    max = A.array().max()
    A /= max
    b /= max

  u = Function(V)
  solve(A, u.vector(), b)
  plot(u, interactive=True, title='dolfin')

  x = A.array()
  print "Value of A are [%g, %g]" %(x.min(), x.max())
  print "Num of entries in A larger theb 100", np.where(x > 1E2)[0].sum()
  print "Number of mesh cells", mesh.num_cells()

  # see about scipy
  rows, cols, values = A.data()
  B = csr_matrix((values, cols, rows))
  d = b.array().T

  if scipy_solver == 'cg':
    v_, info = cg(B, d)              
  elif scipy_solver == 'bicg':
    v_, info = bicg(B, d)              
  elif scipy_solver == 'bicgstab':
    v_, info = bicgstab(B, d)              
  elif scipy_solver == 'gmres':
    v_, info = gmres(B, d)              
  elif scipy_solver == 'minres':
    v_, info = minres(B, d)              
  else:
    v_ = spsolve(B, d)              

  v = Function(V)
  v.vector()[:] = v_
  plot(v, interactive=True, title='scipy')
  try:
    print "info", info, 'v_max', v_.max()
  except:
    pass
Exemplo n.º 17
0
def solve_lienar_ode_python(A, B, C, D, v0, dx, bc, impose_bc):
    LHS, RHS = construct_matrix(A,
                                B,
                                C,
                                D,
                                v0,
                                1.,
                                dx,
                                bc,
                                impose_bc,
                                linear_ode=True)
    v, exit_code = bicg(csc_matrix(LHS), RHS)
    return v
Exemplo n.º 18
0
def bicg_solve(A, u, b, tol=1e-08):
    print("Solving system using BICG solver")
    """ Solves the linear system A*u = b
        Input
            A: numpy array of NxN components (LHS)
            b: numpy array of Nx1 components (RHS)
            u: numpy array of Nx1 components (Solution)
    """

    # Change RHS representation
    A = sp.csr_matrix(A)

    # Solve system
    u[:] = spla.bicg(A, b, tol=tol)[0]
Exemplo n.º 19
0
    def iterative_solver_list(self, which, rhs, *args):
        """Solves the linear problem Ab = x using the sparse matrix

            Parameters
            ----------
            rhs : ndarray
                the right hand side
            which : string
                choose which solver is used
                    bicg(A, b[, x0, tol, maxiter, xtype, M, ...])
                        Use BIConjugate Gradient iteration to solve A x = b

                    bicgstab(A, b[, x0, tol, maxiter, xtype, M, ...])
                        Use BIConjugate Gradient STABilized iteration to solve A x = b

                    cg(A, b[, x0, tol, maxiter, xtype, M, callback])
                        Use Conjugate Gradient iteration to solve A x = b

                    cgs(A, b[, x0, tol, maxiter, xtype, M, callback])
                        Use Conjugate Gradient Squared iteration to solve A x = b

                    gmres(A, b[, x0, tol, restart, maxiter, ...])
                        Use Generalized Minimal RESidual iteration to solve A x = b.

                    lgmres(A, b[, x0, tol, maxiter, M, ...])
                        Solve a matrix equation using the LGMRES algorithm.

                    minres(A, b[, x0, shift, tol, maxiter, ...])
                        Use MINimum RESidual iteration to solve Ax=b

                    qmr(A, b[, x0, tol, maxiter, xtype, M1, M2, ...])
                        Use Quasi-Minimal Residual iteration to solve A x = b
        """
        if which == 'bicg':
            return spla.bicg(self.sp_matrix, rhs, args)
        elif which == "cg":
            return spla.cg(self.sp_matrix, rhs, args)
        elif which == "bicgstab":
            return spla.bicgstab(self.sp_matrix, rhs, args)
        elif which == "cgs":
            return spla.cgs(self.sp_matrix, rhs, args)
        elif which == "gmres":
            return spla.gmres(self.sp_matrix, rhs, args)
        elif which == "lgmres":
            return spla.lgmres(self.sp_matrix, rhs, args)
        elif which == "qmr":
            return spla.qmr(self.sp_matrix, rhs, args)
        else:
            raise NotImplementedError("this solver is unknown")
Exemplo n.º 20
0
def LinSolve(A,b,x0,method):
    if method=='bicg':
        x,info = bicg(A,b,x0)
    if method=='cgs':
        x,info = cgs(A,b,x0)
    if method=='bicgstab':
        x,info = bicgstab(A,b,x0)
        if (info): print 'INFO=',info
    if method=='superLU':
        x = linsolve.spsolve(A,b,use_umfpack=False) 
    if method=='umfpack':
        x = linsolve.spsolve(A,b,use_umfpack=True) 
    if method=='gmres':
        x,info = gmres(A,b,x0) 
    if method=='lgmres':
        x,info = lgmres(A,b,x0) 
    return x
Exemplo n.º 21
0
 def solve(self):
     G = self.__matrix.getMatrix()
     f = self.__matrix.getfv()
     
     if self.__algorithm == 'linalg':
         self.__lam = np.linalg.solve(G,f)
     elif self.__algorithm == 'bicgstab':
         A = sps.csr_matrix(G)
         self.__lam = spla.bicgstab(A,f)[0]
     elif self.__algorithm == 'bicg':
         A = sps.csr_matrix(G)
         self.__lam = spla.bicg(A,f)[0]
     elif self.__algorithm == 'cg':
         A = sps.csr_matrix(G)
         self.__lam = spla.cg(A,f)[0]
     elif self.__algorithm == 'gmres':
         A = sps.csr_matrix(G)
         self.__lam = spla.gmres(A,f)[0]
    def dqMisfit(self, obss, xibars=None, returnSum=True):

        if xibars is None:
            xibars = self.fwdOp()
        dqs = []
        for nn, xibar in enumerate(xibars):
            rhs = np.zeros(xibar.shape)
            rhs[self.indObslist[nn]] = xibar[self.indObslist[nn]] - obss[nn]
            if self.cachedMatrix == False:
                raise Exception(
                    "trying to execute dqMisfit, but no cached matrix found")
            lambdastar = bicg(self._Abar.transpose(), -rhs, tol=1e-9)[0]
            Dres = self.assembleGradient(xibar, self._xihat)
            dqs.append(Dres.transpose().dot(lambdastar))
        if returnSum:
            return sum(dqs)
        else:
            return dqs
def mm_block_coordinate(x0,
                        y,
                        J,
                        H,
                        G,
                        theta,
                        lamb,
                        delta,
                        discount=1,
                        maxit=1000,
                        maxiter=10,
                        eps=1e-4 * np.sqrt(N)):
    timing_list = []
    grad_norms = []
    start = time.clock()
    x = x0.copy()
    gradf = gradient(H, G, x, y, delta, lamb)
    grad_norm = np.linalg.norm(gradf)
    K, r = N // J * np.arange(J + 1, dtype=int), np.zeros(J + 1, dtype=int)
    r[:N % J] = np.arange(1, N % J + 1)
    K += r
    it = 0
    while grad_norm > eps and it < maxit:
        if it != 0:
            start = time.clock()
        grad_norms.append(grad_norm)
        # print('grad_norm', grad_norm)
        Gx = G.dot(x)
        D = sparse.diags(psi_prime(np.abs(Gx), delta) / np.abs(Gx)).tocsr()
        GD = G.T.dot(D)
        j = it % J
        rows_up = np.arange(K[j], K[j + 1])
        linop = blockMM_linear_op(G, GD[rows_up], H, lamb, rows_up)
        xsol, success = sparselinalg.bicg(linop,
                                          b=gradf[rows_up],
                                          maxiter=maxiter)
        x[rows_up] = x[rows_up] - theta * xsol
        it, theta = it + 1, theta * discount
        gradf = gradient(H, G, x, y, delta, lamb)
        grad_norm = np.linalg.norm(gradf)
        end = time.clock()
        timing_list.append(end - start)
        print(grad_norm)
    return x, grad_norms, np.cumsum(timing_list)
Exemplo n.º 24
0
    def solve(self, tol=1e-08, maxiter=20000):
        """
            Solve discretized system with BiCG.
            Input parameters:
                - "tol" - tolerence for the error
                - "maxiter" - needed to tune iterations properly
        """

        nn = self.n**2
        mtx = csr_matrix((self.a, self.ja, self.ia), shape=(nn, nn))
        self.x_appr, info = bicg(mtx,
                                 self.fg,
                                 x0=np.zeros(nn),
                                 tol=tol,
                                 maxiter=maxiter)
        if info > 0:
            print("Iterations number: ", info)
            self.iter = info
        return info
Exemplo n.º 25
0
def img_merge_poisson(img1, img2, shift):
    newimg, img2 = arrange_image(img1, img2, shift)
    if abs(shift[0]) < 10 and abs(shift[1]) < 10:
        return newimg
    # Get corner positions for img2 INCLUDING boundary.
    shape = np.squeeze(img2.shape)
    corner = _get_corner(get_roughshift(shift), shape)
    img2_boo_part = _find_bound(shape, corner, newimg)
    img2_boo = np.ones([shape[0], shape[1]], dtype='bool')
    img2_boo[0, :] = False
    img2_boo[:, 0] = False
    img2_boo[-1, :] = False
    img2_boo[:, -1] = False
    # Overwrite overlapping boundary with img1
    bound_y, bound_x = np.nonzero(np.invert(img2_boo_part))
    bound_y += corner[0, 0]
    bound_x += corner[0, 1]
    newimg[[bound_y, bound_x]] = img1[[bound_y, bound_x]]
    # Embroider non-overlapping part with blurred img2
    bound_y, bound_x = np.nonzero(
        np.invert(img2_boo) - np.invert(img2_boo_part))
    img2_blur = scipy.ndimage.filters.gaussian_filter(img2, 10)
    bound_y += corner[0, 0]
    bound_x += corner[0, 1]
    newimg[[bound_y, bound_x
            ]] = img2_blur[[bound_y - corner[0, 0], bound_x - corner[0, 1]]]
    ##
    spot = newimg[corner[0, 0]:corner[1, 0] + 1, corner[0, 1]:corner[1, 1] + 1]
    print("    Blend: Building matrix... ", end="")
    t0 = time.time()
    A = _matrix_builder(img2_boo)
    print("Done in " + str(time.time() - t0) + " sec.")
    print("    Blend: Building constant vector... ", end="")
    t0 = time.time()
    b = _const_builder(img2_boo, spot, img2)
    print("Done in " + str(time.time() - t0) + " sec.")
    print("    Blend: Solving linear system... ", end="")
    t0 = time.time()
    x = lng.bicg(A, b)[0]
    print("Done in " + str(time.time() - t0) + " sec.")
    spot[img2_boo] = x
    newimg[corner[0, 0]:corner[1, 0] + 1, corner[0, 1]:corner[1, 1] + 1] = spot
    return newimg
Exemplo n.º 26
0
def img_merge_poisson(img1, img2, shift):
    newimg, img2 = morph.arrange_image(img1, img2, shift)
    if abs(shift[0]) < 10 and abs(shift[1]) < 10:
        return newimg
    # Get corner positions for img2 INCLUDING boundary.
    shape = np.squeeze(img2.shape)
    corner = _get_corner(morph.get_roughshift(shift), shape)
    img2_boo_part = _find_bound(shape, corner, newimg)
    img2_boo = np.ones([shape[0], shape[1]], dtype='bool')
    img2_boo[0, :] = False
    img2_boo[:, 0] = False
    img2_boo[-1, :] = False
    img2_boo[:, -1] = False
    # Overwrite overlapping boundary with img1
    bound_y, bound_x = np.nonzero(np.invert(img2_boo_part))
    bound_y += corner[0, 0]
    bound_x += corner[0, 1]
    newimg[[bound_y, bound_x]] = img1[[bound_y, bound_x]]
    # Embroider non-overlapping part with blurred img2
    bound_y, bound_x = np.nonzero(np.invert(img2_boo) - np.invert(img2_boo_part))
    img2_blur = scipy.ndimage.filters.gaussian_filter(img2, 10)
    bound_y += corner[0, 0]
    bound_x += corner[0, 1]
    newimg[[bound_y, bound_x]] = img2_blur[[bound_y - corner[0, 0], bound_x - corner[0, 1]]]
    ##
    spot = newimg[corner[0, 0]:corner[1, 0] + 1, corner[0, 1]:corner[1, 1] + 1]
    print("    Blend: Building matrix... ", end="")
    t0 = time.time()
    A = _matrix_builder(img2_boo)
    print("Done in " + str(time.time() - t0) + " sec.")
    print("    Blend: Building constant vector... ", end="")
    t0 = time.time()
    b = _const_builder(img2_boo, spot, img2)
    print("Done in " + str(time.time() - t0) + " sec.")
    print("    Blend: Solving linear system... ", end="")
    t0 = time.time()
    x = lng.bicg(A, b)[0]
    print("Done in " + str(time.time() - t0) + " sec.")
    spot[img2_boo] = x
    newimg[corner[0, 0]:corner[1, 0] + 1, corner[0, 1]:corner[1, 1] + 1] = spot
    return newimg
Exemplo n.º 27
0
def linear_solver(Afun=None, ATfun=None, B=None, x0=None, par=None,
                  solver=None, callback=None):
    """
    Wraper for various linear solvers suited for FFT-based homogenization.
    """
    if callback is not None:
        callback(x0)

    if solver.lower() in ['cg']: # conjugate gradients
        x, info = CG(Afun, B, x0=x0, par=par, callback=callback)
    elif solver.lower() in ['bicg']: # biconjugate gradients
        x, info = BiCG(Afun, ATfun, B, x0=x0, par=par, callback=callback)
    elif solver.lower() in ['iterative']: # iterative solver
        x, info = richardson(Afun, B, x0, par=par, callback=callback)
    elif solver.split('_')[0].lower() in ['scipy']: # solvers in scipy
        from scipy.sparse.linalg import LinearOperator, cg, bicg
        if solver == 'scipy_cg':
            Afun.define_operand(B)
            Afunvec = LinearOperator(Afun.shape, matvec=Afun.matvec,
                                     dtype=np.float64)
            xcol, info = cg(Afunvec, B.vec(), x0=x0.vec(),
                            tol=par['tol'],
                            maxiter=par['maxiter'],
                            xtype=None, M=None, callback=callback)
        elif solver == 'scipy_bicg':
            Afun.define_operand(B)
            ATfun.define_operand(B)
            Afunvec = LinearOperator(Afun.shape, matvec=Afun.matvec,
                                     rmatvec=ATfun.matvec, dtype=np.float64)
            xcol, info = bicg(Afunvec, B.vec(), x0=x0.vec(),
                              tol=par['tol'],
                              maxiter=par['maxiter'],
                              xtype=None, M=None, callback=callback)
        res = dict()
        res['info'] = info
        x = VecTri(val=np.reshape(xcol, B.dN()))
    else:
        msg = "This kind (%s) of linear solver is not implemented" % solver
        raise NotImplementedError(msg)

    return x, info
    def fwdOp(self):
        # solve PDE for p, given coeff_k, for all coeff_f in list_coeff_f
        xibars = []

        if self._coeff_k is None:
            raise Exception("No coeff_k found while trying to execute fwdOp")

        if self.cachedMatrix == False:
            warnings.warn(
                "fwdOp is being executed, but no precomputed cache was found. Computing cache now."
            )
            self.assembleLHS(self._coeff_k)

        Abar = self._Abar
        Ahat = self._Ahat
        xihat = self._xihat
        for qbar in self._qbars:
            bb = qbar - Ahat.dot(xihat)
            xibar = bicg(Abar, bb, tol=1e-9)[0]
            xibars.append(xibar)
        return xibars
Exemplo n.º 29
0
Arquivo: npr.py Projeto: ralucas/npr
    def poisson_solver(self, G, I):
        div_G = cv2.Laplacian(G, cv2.CV_64F, borderType=cv2.BORDER_REFLECT_101)
        G_pyr = self.reduce(div_G)
        dst_pyr = self.reduce(I)
        idx = len(G_pyr) - 1
        for i, fp in enumerate(G_pyr):
            if np.sum(np.array(fp.shape) - MAX_SIZE) < 0:
                idx = i
                break
        h, w = G_pyr[idx].shape
        M = (np.eye(h * w, h * w) * 4) + (np.eye(h * w, h * w, k=1) * -1) + (
            np.eye(h * w, h * w, k=-1) * -1)
        b = np.zeros(h * w)
        count = 0
        H = h - 1
        W = w - 1
        for r in xrange(0, H):
            for c in xrange(0, W):
                i = ((r - 1) * H) + c
                if r == 0:
                    b[count] = b[count] + dst_pyr[idx][r + 1][c - 1]
                if r == H:
                    b[count] = b[count] + dst_pyr[idx][r + 1][c]

                if c == 0:
                    b[count] = b[count] + dst_pyr[idx][r][c - 1]
                if c == W:
                    b[count] = b[count] + dst_pyr[idx][r][c + 1]

                xv = c - 1
                yv = r - 1

                v = G_pyr[idx][yv][xv]
                b[count] = b[count] + v
                count += 1

        X = lg.bicg(M, b.T)
        im = np.reshape(X[0], (h, w))
        dst = self.expand(im)[idx]
        return np.abs(dst[:G.shape[0], :G.shape[1]])
Exemplo n.º 30
0
def GenPencil(im, P, J):
    h, w = im.shape
    P = cv2.resize(P, (w, h))
    bP = P
    P = np.reshape(P, (h * w, 1))
    logP = np.log(P)
    logP = logP.T
    logP = spdiags(logP, 0, h * w, h * w)

    J = cv2.resize(J, (w, h))
    J = J.reshape(h * w, 1)
    logJ = np.log(J)
    e = np.ones((1, h * w))
    ddata = np.vstack((-e, e))
    Dx = spdiags(ddata, [0, h], h * w, h * w)
    Dy = spdiags(ddata, [0, 1], h * w, h * w)
    A = 0.2 * (Dx.dot(Dx.T) + Dy.dot(Dy.T)) + np.dot(logP.T, logP)
    b = logP.T.dot(logJ)
    beta = bicg(A, b, tol=1)  # tol parameter
    beta = beta[0].reshape(h, w)
    T = bP**beta
    T = (T - T.min()) / (T.max() - T.min())
    return T
Exemplo n.º 31
0
    def optimize(self, x0):
        x_n = x0.copy()
        self.n = len(x_n)

        self.init_time()
        for _ in tqdm(range(self.max_iter), disable=self.disable_progressbar):
            x_prev = x_n.copy()

            qmaj = self.get_operator(x_n)
            right_term = bicg(A=qmaj, b=self.grad_f(x_n))
            right_term = right_term[0]
            x_n = x_n - self.theta * right_term

            x_n = np.array(x_n)  # x_n was a matrix and not an array
            x_n = x_n.reshape(-1)
            self.f_eval(x_n)
            assert x_n.shape == x_prev.shape

            if self.has_converged(x_n):
                print('Method has converged')
                break

        return x_n, (self.times, self.f_vals)
Exemplo n.º 32
0
    def calc_dC_galerkin(self, gbasis, diffs, dC0):
        """
        Calculate the differential change in the C coefficients
        using the spectral method 

        Input:
            gbasis: Instance of Basis_function containing the basis set representing a particular RK step

        Output:
            dC: Nbasis long vector of time-derivatives of coefficients
            
        """

        #Calculate the time derivative of the overlap matrix
        I0, H, overlap_dt = gbasis.calc_H_and_odt(self.model, diffs,
                                                  self.galerkin_approx,
                                                  self.mass)

        #Construct normal equations for TDSE
        #in non-orthogonal time-dependent basis

        aA = np.dot(I0.T.conj(), I0)
        Bvec = -1.0j * np.dot(I0.T.conj(),
                              np.dot(H - 1.0j * overlap_dt, gbasis.c[:, 0]))
        if self.solver == 'lstsq':
            dC = np.linalg.lstsq(aA, Bvec, rcond=self.svd_threshold)[0]
        elif self.solver == 'bicg':
            spdc = spla.bicg(aA, Bvec, x0=dC0, maxiter=100000)
            dC = spdc[0]
            if spdc[1] != 0:
                with open(self.outfile, 'a+') as f:
                    f.write(
                        'Warning!! conjugate gradient solver did not converge for dC\n'
                    )
                    f.write('Solver output is {}\n'.format(spdc[1:]))

        return dC.reshape(-1, 1)
Exemplo n.º 33
0
def main():
    """docstring for main"""
    A, b = setup_linear_system()

    # using bicg
    conv = ConvergenceMonitor(action=lambda x: b - A.dot(x), increment=2)
    x, info = la.bicg(A, b, maxiter=1000000, callback=conv)
    conv.scale(1.0 / np.linalg.norm(b))
    print('bicg ', end='')
    conv.printInfo()

    # using bicgstab
    conv = ConvergenceMonitor(action=lambda x: b - A.dot(x), increment=2)
    x, info = la.bicgstab(A, b, maxiter=1000000, callback=conv)
    conv.scale(1.0 / np.linalg.norm(b))
    print('bicgstab ', end='')
    conv.printInfo()

    # using gmres
    conv = ConvergenceMonitor()
    x, info = la.gmres(A, b, maxiter=1000000, restart=250, callback=conv)
    conv.scale(1.0 / np.linalg.norm(b))
    print('full GMRES ', end='')
    conv.printInfo()
Exemplo n.º 34
0
            eqIndOther = indToEqInd[indOther]
            currConn[eqIndOther] = 1 / R
            weightSum -= 1 / R
            pOther = p + np.array((d_ix, d_iy)) * params.dX
            rhsVal -= calc_du(params.e_add_f, pOther, p,
                              params.nStep_for_du) / R

        currConn[eqInd] = weightSum
        eqIndToConn.append(currConn)
        eqIndToRHS.append(rhsVal)

print("%.2fs Building connection Matrix" % (time.clock() - t))
#connMat = buildConnMat(eqIndToConn)
connMat = buildSparseConnMat(eqIndToConn)
print("%.2fs Solving Equation System" % (time.clock() - t))
#res= np.linalg.solve(connMat, eqIndToRHS)
res, _ = bicg(connMat, eqIndToRHS)
res = res - np.min(res)
print("%.2fs Writing to File" % (time.clock() - t))

if not os.path.exists(params.outDirPath):
    os.makedirs(params.outDirPath)

data = []
for eqInd, pot in enumerate(res):
    p = indToP[eqIndToInd[eqInd]]
    data.append((p[0], p[1], pot))
data = pd.DataFrame(data, columns=["x", "y", "pot"])
data.to_excel(params.solPath)

print("%.2fs Finished" % (time.clock() - t))
Exemplo n.º 35
0
 def _action(self, act=1):
     if QSMODE == MODE_MPMATH:
         args = {}
         if act==0:
             self.typeStr = "mpmath_qr_solve_dps"+getArgDesc(mpmath.qr_solve, args)+" DPS"+str(DPS)
             self.matrixType = 1
             self.indexType = 1
         else:
             self.coeffVec = mpmath.qr_solve(self.sysMat, self.resVec, **args)
             self.printCalStr()
     else:
         if PYTYPE_COEFF_SOLVE_METHOD == "numpy_solve":
             args = {}
             if act==0:
                 self.typeStr = "numpy_solve"+getArgDesc(np.linalg.solve, args)
                 self.matrixType = 0
                 self.indexType = 0
             else:
                 self.coeffVec = np.linalg.solve(self.sysMat, self.resVec, **args)
                 self.printCalStr()
         elif PYTYPE_COEFF_SOLVE_METHOD == "numpy_lstsq":
             args = {}
             if act==0:
                 self.typeStr = "numpy_lstsq"+getArgDesc(np.linalg.lstsq, args)
                 self.matrixType = 0
                 self.indexType = 0
             else:
                 self.coeffVec = np.linalg.lstsq(self.sysMat, self.resVec, **args)[0]
                 self.printCalStr()
         elif PYTYPE_COEFF_SOLVE_METHOD == "numpy_sparse_bicg": 
             args = {}
             if act==0:
                 self.typeStr = "numpy_sparse_bicg"+getArgDesc(sp_sparse_linalg.bicg, args)
                 self.matrixType = 0
                 self.indexType = 1
             else:
                 self.coeffVec = self._sparseRet(sp_sparse_linalg.bicg(self.sysMat, self.resVec, **args))#, tol=1e-05, maxiter=10*len(self.resVec)
         elif PYTYPE_COEFF_SOLVE_METHOD == "numpy_sparse_bicgstab":
             args = {}
             if act==0:
                 self.typeStr = "numpy_sparse_bicgstab"+getArgDesc(sp_sparse_linalg.bicgstab, args)
                 self.matrixType = 0
                 self.indexType = 1
             else:
                 self.coeffVec = self._sparseRet(sp_sparse_linalg.bicgstab(self.sysMat, self.resVec, **args))#, tol=1e-05, maxiter=10*len(self.resVec)
         elif PYTYPE_COEFF_SOLVE_METHOD == "numpy_sparse_lgmres":
             args = {}
             if act==0:
                 self.typeStr = "numpy_sparse_lgmres"+getArgDesc(sp_sparse_linalg.lgmres, args)
                 self.matrixType = 0
                 self.indexType = 1
             else:
                 self.coeffVec = self._sparseRet(sp_sparse_linalg.lgmres(self.sysMat, self.resVec, **args))#, tol=1e-05, maxiter=1000
         elif PYTYPE_COEFF_SOLVE_METHOD == "numpy_sparse_minres":
             args = {}
             if act==0:
                 self.typeStr = "numpy_sparse_minres"+getArgDesc(sp_sparse_linalg.minres, args)
                 self.matrixType = 0
                 self.indexType = 1
             else:
                 self.coeffVec = self._sparseRet(sp_sparse_linalg.minres(self.sysMat, self.resVec, **args))#, tol=1e-05, maxiter=5*self.sysMat.shape[0]
         elif PYTYPE_COEFF_SOLVE_METHOD == "numpy_sparse_qmr":
             args = {}
             if act==0:
                 self.typeStr = "numpy_sparse_qmr"+getArgDesc(sp_sparse_linalg.qmr, args)
                 self.matrixType = 0
                 self.indexType = 1
             else:
                 self.coeffVec = self._sparseRet(sp_sparse_linalg.qmr(self.sysMat, self.resVec, **args))#, tol=1e-05, maxiter=10*len(self.resVec)
         elif PYTYPE_COEFF_SOLVE_METHOD == "numpy_qr":
             args_qr = {}
             args_s = {}
             if act==0:
                 self.typeStr = "numpy_qr"+getArgDesc(np.linalg.qr, args_qr)+",numpy_solve"+getArgDesc(np.linalg.solve, args_s)
                 self.matrixType = 0
                 self.indexType = 0
             else:
                 Q,R = np.linalg.qr(self.sysMat, **args_qr)
                 y = np.dot(Q.T,self.resVec)
                 self.coeffVec = np.linalg.solve(R,y, **args_s) 
                 self.printCalStr()
Exemplo n.º 36
0
def deconvolve_reads(mapped_reads,mean_frag_length):
    G = len(mapped_reads)
    lamb = 1.0/mean_frag_length
    M = conv_mat(G,lamb,sigma=0)
    config = linalg.bicg(M,mapped_reads)
    return config
Exemplo n.º 37
0
def steady(L, maxiter=100, tol=1e-6, method='solve'):
    """Steady state for the evolution subject to the 
	supplied Louvillian.
    
    Parameters
    ----------
    L : qobj
        Liouvillian superoperator.
              
    maxiter : int 
        Maximum number of iterations to perform, default = 100.

    tol : float 
        Tolerance used by iterative solver, default = 1e-6.
    
    method : str
        Method for solving linear equations. Direct solver 'solve' (default) or 
        iterative biconjugate gradient method 'bicg'.
    
    Returns
    --------
    ket : qobj
        Ket vector for steady state.
    
    Notes
    -----
    Uses the inverse power method. 
    See any Linear Algebra book with an iterative methods section.
    
    """
    eps = finfo(float).eps
    if (not isoper(L)) & (not issuper(L)):
        raise TypeError(
            'Steady states can only be found for operators or superoperators.')
    rhoss = Qobj()
    sflag = issuper(L)
    if sflag:
        rhoss.dims = L.dims[0]
        rhoss.shape = [prod(rhoss.dims[0]), prod(rhoss.dims[1])]
    else:
        rhoss.dims = [L.dims[0], 1]
        rhoss.shape = [prod(rhoss.dims[0]), 1]
    n = prod(rhoss.shape)
    L1 = L.data + eps * sp_inf_norm(L) * sp.eye(n, n, format='csr')
    v = randn(n, 1)
    it = 0
    while (la.norm(L.data * v, inf) > tol) and (it < maxiter):
        if method == 'bicg':
            v, check = bicg(L1, v, tol=tol)
        else:
            v = spsolve(L1, v, use_umfpack=False)
        v = v / la.norm(v, inf)
        it += 1
    if it >= maxiter:
        raise ValueError('Failed to find steady state after ' + str(maxiter) +
                         ' iterations')
    #normalise according to type of problem
    if sflag:
        trow = sp.eye(rhoss.shape[0], rhoss.shape[0], format='lil')
        trow = trow.reshape((1, n)).tocsr()
        data = v / sum(trow.dot(v))
    else:
        data = data / la.norm(v)
    data = reshape(data, (rhoss.shape[0], rhoss.shape[1])).T
    data = sp.csr_matrix(data)
    rhoss.data = 0.5 * (data + data.conj().T)
    #data=sp.triu(data,format='csr')#take only upper triangle
    #rhoss.data=0.5*sp.eye(rhoss.shape[0],rhoss.shape[1],format='csr')*(data+data.conj().T) #output should be hermitian, but not guarenteed using iterative meth
    if qset.auto_tidyup:
        return Qobj(rhoss).tidyup()
    else:
        return Qobj(rhoss)
Exemplo n.º 38
0
def solve_ode(A, By, Cyy, D, y_grid, ϕ_prev, ϵ, boundspec):
    LHS, RHS = get_coeff(A, By, Cyy, D, y_grid, ϕ_prev, ϵ, boundspec)
    phi_grid, exit_code = bicg(csc_matrix(LHS), RHS)
    #     phi_grid = np.linalg.solve(LHS, RHS)
    return phi_grid
Exemplo n.º 39
0
def steady(L,maxiter=100,tol=1e-6,method='solve'):
	"""Steady state for the evolution subject to the 
	supplied Louvillian.
    
    Parameters
    ----------
    L : qobj
        Liouvillian superoperator.
              
    maxiter : int 
        Maximum number of iterations to perform, default = 100.

    tol : float 
        Tolerance used by iterative solver, default = 1e-6.
    
    method : str
        Method for solving linear equations. Direct solver 'solve' (default) or 
        iterative biconjugate gradient method 'bicg'.
    
    Returns
    --------
    ket : qobj
        Ket vector for steady state.
    
    Notes
    -----
    Uses the inverse power method. 
    See any Linear Algebra book with an iterative methods section.
    
    """
	eps=finfo(float).eps
	if (not isoper(L)) & (not issuper(L)):
		raise TypeError('Steady states can only be found for operators or superoperators.')
	rhoss=Qobj()
	sflag=issuper(L)
	if sflag:
		rhoss.dims=L.dims[0]
		rhoss.shape=[prod(rhoss.dims[0]),prod(rhoss.dims[1])]
	else:
		rhoss.dims=[L.dims[0],1]
		rhoss.shape=[prod(rhoss.dims[0]),1]
	n=prod(rhoss.shape)
	L1=L.data+eps*_sp_inf_norm(L)*sp.eye(n,n,format='csr')
	v=randn(n,1)
	it=0
	while (la.norm(L.data*v,np.inf)>tol) and (it<maxiter):
		if method=='bicg':
		    v,check=bicg(L1,v,tol=tol)
		else:
		    v=spsolve(L1,v,use_umfpack=False)
		v=v/la.norm(v,np.inf)
		it+=1
	if it>=maxiter:
		raise ValueError('Failed to find steady state after ' + str(maxiter) +' iterations')
	#normalise according to type of problem
	if sflag:
		trow=sp.eye(rhoss.shape[0],rhoss.shape[0],format='lil')
		trow=trow.reshape((1,n)).tocsr()
		data=v/sum(trow.dot(v))
	else:
		data=data/la.norm(v)
	data=reshape(data,(rhoss.shape[0],rhoss.shape[1])).T
	data=sp.csr_matrix(data)
	rhoss.data=0.5*(data+data.conj().T)
	#data=sp.triu(data,format='csr')#take only upper triangle
	#rhoss.data=0.5*sp.eye(rhoss.shape[0],rhoss.shape[1],format='csr')*(data+data.conj().T) #output should be hermitian, but not guarenteed using iterative meth
	if qset.auto_tidyup:
	    return Qobj(rhoss).tidyup()
	else:
	    return Qobj(rhoss)
Exemplo n.º 40
0
 def solve(self, x_0=None, tol=1e-5, max_iter=100, exchange_zero=1e-16):
     """
     Solve the equation *A * x = b* using an iterative solver. After solving
     old unknown vectors and volume field values are overwritten.
     """
     if x_0 == None:
         x_0X = x_0
         x_0Y = x_0
         x_0Z = x_0
     else:
         x_0X = x_0[:,0]
         x_0Y = x_0[:,1]
         x_0Z = x_0[:,2]
     if self.solver == "cg":
         solver_return_x = lin.cg(self.A, self.bX, x_0X, tol, max_iter)
         solver_return_y = lin.cg(self.A, self.bY, x_0Y, tol, max_iter)
         solver_return_z = lin.cg(self.A, self.bZ, x_0Z, tol, max_iter)
     elif self.solver == "bicg":
         solver_return_x = lin.bicg(self.A, self.bX, x_0X, tol, max_iter)
         solver_return_y = lin.bicg(self.A, self.bY, x_0Y, tol, max_iter)
         solver_return_z = lin.bicg(self.A, self.bZ, x_0Z, tol, max_iter)
     elif self.solver == "gs":
         solver_return_x = mylin.gs(self.A, self.bX, x_0X, tol, max_iter)
         solver_return_y = mylin.gs(self.A, self.bY, x_0Y, tol, max_iter)
         solver_return_z = mylin.gs(self.A, self.bZ, x_0Z, tol, max_iter)
     
     self.xX         = solver_return_x[0]
     self.xX_old_old = self.xX_old
     
     self.xY         = solver_return_y[0]
     self.xY_old_old = self.xY_old
     
     self.xZ         = solver_return_z[0]
     self.xZ_old_old = self.xZ_old
     
     # find max absolute residual for x
     diff_x = abs(self.xX - self.xX_old)
     max_diff_x = max(diff_x)
     if max_diff_x == 0.:
         self.residualsX.append(exchange_zero)
     else:
         self.residualsX.append(max_diff_x)
     print 'Residual for ' + self.field.name + ' x: ' + str(max(diff_x))
     
     # find max absolute residual for y
     diff_y = abs(self.xY - self.xY_old)
     max_diff_y = max(diff_y)
     if max_diff_y == 0.:
         self.residualsY.append(exchange_zero)
     else:
         self.residualsY.append(max_diff_y)
     print 'Residual for ' + self.field.name + ' y: ' + str(max(diff_y))
     
     # find max absolute residual for z
     diff_z = abs(self.xZ - self.xZ_old)
     max_diff_z = max(diff_z)
     if max_diff_z == 0.:
         self.residualsZ.append(exchange_zero)
     else:
         self.residualsZ.append(max_diff_z)
     print 'Residual for ' + self.field.name + ' z: ' + str(max(diff_z))
     
     #update volume field
     self.field.V[:,0] = self.xX_old + self.under_relax*(self.xX - self.xX_old)
     self.field.V[:,1] = self.xY_old + self.under_relax*(self.xY - self.xY_old)
     self.field.V[:,2] = self.xZ_old + self.under_relax*(self.xZ - self.xZ_old)
     
     return True
Exemplo n.º 41
0
PDE = poisson(geometry=geo, bc_dirichlet=bc_dirichlet, bc_neumann=bc_neumann,
              AllDirichlet=AllDirichlet, metric=Metric)
PDE.assembly()
PDE.solve()

# getting scipy matrix
A = PDE.system.get()

b = np.ones(PDE.size)

print "Using cg."
x = cg(A, b, tol=tol, maxiter=maxiter)

print "Using cgs."
x = cgs(A, b, tol=tol, maxiter=maxiter)

print "Using bicg."
x = bicg(A, b, tol=tol, maxiter=maxiter)

print "Using bicgstab."
x = bicgstab(A, b, tol=tol, maxiter=maxiter)

print "Using gmres."
x = gmres(A, b, tol=tol, maxiter=maxiter)

print "Using splu."
op = splu(A.tocsc())
x = op.solve(b)

PDE.free()
Exemplo n.º 42
0
timeVol = timer() - timeA
print("done: %f s " %timeVol)

timeMesh = timer()

print ('----------- Condicoes de contorno -----------\n')

## -- Computa infos de condicoes de contorno
NameBCs, TipoBCs, nFaces, startFace = read_bcs_mesh()

## -- Computa a matriz dos coeficientes e vetor lado direito
A, Su = assembly()

## -- Solucao do sistema linear
StartTimeSisLin = timer()
Solucao = bicg(A, Su)
#Solucao = bicgstab(A, Su)
T = Solucao[0]
TimeFinal = timer()
WallTimeSisLin = TimeFinal - StartTimeSisLin
WallTimeTot = TimeFinal - StartTimeTot
WallTimeFiles = timeFiles - StartTimeTot
WallTimeMesh = timeMesh - timeFiles
WallTimeAssembly = StartTimeSisLin - timeMesh

print ('Volumes: %d' %Nvolumes)
final1 = '\n============================================='
final1 += '\n---------- Matriz dos coeficientes ----------\n\n'
final2 = '\n\n--------- Lado direito das equacoes ---------\n\n'
final3 = '\n============================================='
final3 += '\n--------------- Solucao de T ----------------\n\n'
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
Exemplo n.º 44
0
    def averageTime(self, x0=None, maxiter=None):

        startTime = time.time()

        if self.solveToggle == 1:
            firstpassagetimes, info = bicg(self.rate_matrix_csr,
                                           self.b,
                                           x0=x0,
                                           maxiter=maxiter)

        elif self.solveToggle == 2:
            firstpassagetimes, info = bicg(self.rate_matrix_csr,
                                           self.b,
                                           M=self.rate_matrix_inverse,
                                           x0=x0,
                                           maxiter=maxiter)

        elif self.solveToggle == 3:
            firstpassagetimes, info = bicgstab(self.rate_matrix_csr,
                                               self.b,
                                               x0=x0,
                                               maxiter=maxiter)

        elif self.solveToggle == 4:
            firstpassagetimes, info = bicgstab(self.rate_matrix_csr,
                                               self.b,
                                               M=self.rate_matrix_inverse,
                                               x0=x0,
                                               maxiter=maxiter)

        elif self.solveToggle == 5:
            firstpassagetimes, info = gmres(self.rate_matrix_csr,
                                            self.b,
                                            x0=x0,
                                            maxiter=maxiter)

        elif self.solveToggle == 6:
            firstpassagetimes, info = gmres(self.rate_matrix_csr,
                                            self.b,
                                            M=self.rate_matrix_inverse,
                                            x0=x0,
                                            maxiter=maxiter)

        elif self.solveToggle == 7:
            firstpassagetimes, info = cg(self.rate_matrix_csr,
                                         self.b,
                                         x0=x0,
                                         maxiter=maxiter)

        elif self.solveToggle == 8:
            firstpassagetimes, info = cg(self.rate_matrix_csr,
                                         self.b,
                                         M=self.rate_matrix_inverse,
                                         x0=x0,
                                         maxiter=maxiter)

        elif self.solveToggle == 9:
            firstpassagetimes, info = lgmres(self.rate_matrix_csr,
                                             self.b,
                                             x0=x0,
                                             maxiter=maxiter)

        elif self.solveToggle == 10:
            firstpassagetimes, info = lgmres(self.rate_matrix_csr,
                                             self.b,
                                             M=self.rate_matrix_inverse,
                                             x0=x0,
                                             maxiter=maxiter)

        else:

            global floatT
            floatT = np.float64

            self.setMatrix()
            firstpassagetimes = spsolve(self.rate_matrix_csr, self.b)

            floatT = np.longdouble

        self.matrixTime = time.time() - startTime

        return firstpassagetimes