Exemple #1
0
 def compute_q_mu(self):
     """
     Computes the q and mu vectors using the Conjugate Gradient method for sparse linear systems.
     """
     if self._sparsify_P:
         idxs = self._Lambda_sparse.to('cpu')._indices().numpy()
         vals = self._Lambda_sparse.to('cpu')._values().numpy()
         Lambda = coo_matrix((vals, (idxs[0, :], idxs[1, :])),
                             dtype=NP_DTYPE)
     else:
         Lambda = self._Lambda.to('cpu').numpy()
     rewards = self._rewards.to('cpu').numpy()
     eps_0 = self._eps_0.data.to('cpu').numpy()
     # Compute q
     q, info = bicgstab(
         Lambda,
         rewards,
         x0=self._q.to('cpu').numpy() if self._q is not None else None,
         tol=1e-4)
     self._q = torch.tensor(q.reshape(-1, 1),
                            device=self._policy.device,
                            dtype=TORCH_DTYPE)
     # Compute mu
     eps_0 = eps_0.mean(axis=1, keepdims=True)
     mu, info = bicgstab(
         Lambda.T,
         eps_0,
         x0=self._mu.to('cpu').numpy() if self._mu is not None else None,
         tol=1e-4)
     self._mu = torch.tensor(mu.reshape(-1, 1),
                             device=self._policy.device,
                             dtype=TORCH_DTYPE)
Exemple #2
0
def scoreBoth(s,lap,pts,lap_t,pst_t,wt):
    try:
        f = lin.spsolve(lap, pts)
        h = lin.spsolve(lap_t, pst_t)
    except:
        # a singular matrix ... must solve each vector separately
        vecs = pts.shape[1]
        vlen = pts.shape[0]
        #print(vecs)
        fsolns = []
        hsolns = []
        for i in range(vecs):
            pts2   = pts[:,i].todense()
            pst_t2 = pst_t[:,i].todense()
            f1 = lin.bicgstab(lap, pts2)[0]
            h1 = lin.bicgstab(lap_t, pst_t2)[0]
            fsolns.append(f1)
            hsolns.append(h1)
        f = np.matrix(fsolns)
        h = np.matrix(hsolns)
        f = f.transpose()
        h = h.transpose()
    if type(f) == type(np.array([])): # came back as an array
        fh = f+h
        score = fh.sum()
        touch = (fh > s["tx"]).sum()
    else: # came back as a sparse matrix
        fsum = np.array(f.sum(1)).flatten()
        hsum = np.array(h.sum(1)).flatten()
        fh = fsum + hsum
        touch = sum(fh > s["tx"])
        #  best score; best touch #
    return((touch+wt, touch))
Exemple #3
0
def scoreBoth(s,lap,pts,lap_t,pst_t,wt):
    try:
        f = lin.spsolve(lap, pts)
        h = lin.spsolve(lap_t, pst_t)
    except:
        # a singular matrix ... must solve each vector separately
        vecs = pts.shape[1]
        vlen = pts.shape[0]
        #print(vecs)
        fsolns = []
        hsolns = []
        for i in range(vecs):
            pts2   = pts[:,i].todense()
            pst_t2 = pst_t[:,i].todense()
            f1 = lin.bicgstab(lap, pts2)[0]
            h1 = lin.bicgstab(lap_t, pst_t2)[0]
            fsolns.append(f1)
            hsolns.append(h1)
        f = np.matrix(fsolns)
        h = np.matrix(hsolns)
        f = f.transpose()
        h = h.transpose()
    if type(f) == type(np.array([])): # came back as an array
        fh = f+h
        score = fh.sum()
        touch = (fh > s["tx"]).sum()
    else: # came back as a sparse matrix
        fsum = np.array(f.sum(1)).flatten()
        hsum = np.array(h.sum(1)).flatten()
        fh = fsum + hsum
        touch = sum(fh > s["tx"])
        #  best score; best touch #
    return((touch+wt, touch))
Exemple #4
0
def calc_t(t, uvwf, rho_cap, kappa, dt, dxyz, obst):
    # --------------------------------------------------------------------------
    """
    Docstring.
    """

    # Unpack tuple(s)
    dx, dy, dz = dxyz

    # Fetch the resolution
    rc = t.val.shape

    # Discretize the diffusive part
    A_t, b_t = create_matrix(t, rho_cap / dt, kappa, dxyz, obst, 'n')

    # The advective fluxes
    c_t = advection(rho_cap, t, uvwf, dxyz, dt, 'minmod')

    # Innertial term for enthalpy
    i_t = t.old * rho_cap * dx * dy * dz / dt

    # The entire source term
    f_t = b_t - c_t + i_t

    # Solve for temperature
    res0 = bicgstab(A_t, reshape(f_t, prod(rc)), tol=TOL)
    t.val[:] = reshape(res0[0], rc)

    adj_n_bnds(t)

    return  # end of function
    def integrate(self, u0_h, v0_h, w0_h, dt, debug=False, tol=1e-6):
        uvw0 = self.ravel(u0_h, v0_h, w0_h)
        uvw1 = uvw0.copy()
        ddt0, ddt1 = self.ddt(0, uvw0), self.ddt(0, uvw1)
        res = (uvw1 - uvw0) - dt/2 * (ddt0 + ddt1)

        if debug:
            print '  ires = {:.3e}'.format( norm(res) )

        def matvec(uvwp):
            u1_h, v1_h, w1_h = self.unravel(uvw1)
            up_h, vp_h, wp_h = self.unravel(uvwp)
            dupdt_h, dvpdt_h, dwpdt_h = \
                self.navierTan(u1_h, v1_h, w1_h, up_h, vp_h, wp_h)
            return uvwp - dt/2 * self.ravel(dupdt_h, dvpdt_h, dwpdt_h)

        for iiter in range(12):   # newton ralphson
            shape = (res.size, res.size)
            A = splinalg.LinearOperator(shape, matvec=matvec, dtype=float)
            duvw, info = splinalg.bicgstab(A, res, tol=tol)
            uvw1 -= duvw
            res = (uvw1 - uvw0) - dt/2 * (ddt0 + self.ddt(0, uvw1))

            nr = norm(res)
            #if debug:
            #    print nr
            if nr < tol and iiter > 3:
                if debug:
                    print '{:d}: res = {:.3e}'.format(iiter, nr)
                break


        assert norm(res) < tol
        return self.unravel(uvw1)
Exemple #6
0
 def solve_kernel(self, regparam):
     self.regparam = regparam
     K1 = mat(self.resource_pool['kmatrix1'])
     K2 = mat(self.resource_pool['kmatrix2'])
     lsize = len(self.label_row_inds) #n
     
     if 'maxiter' in self.resource_pool: maxiter = int(self.resource_pool['maxiter'])
     else: maxiter = None
     
     label_row_inds = self.label_row_inds
     label_col_inds = self.label_col_inds
     
     temp = zeros((K1.shape[1], K2.shape[0]))
     v_after = zeros((len(self.label_row_inds),))
     #Y = self.Y
     #self.itercount = 0
     def mv(v):
         assert v.shape[0] == len(self.label_row_inds)
         temp = zeros((K1.shape[1], K2.shape[0]))
         sparse_kronecker_multiplication_tools.sparse_mat_from_left(temp, v, K2, label_row_inds, label_col_inds, lsize, K2.shape[0])
         v_after = zeros(v.shape[0])
         #print K1.shape, temp.shape
         sparse_kronecker_multiplication_tools.compute_subset_of_matprod_entries(v_after, K1, temp, label_row_inds, label_col_inds, lsize, K1.shape[0])
         return v_after + regparam * v
     
     def mvr(v):
         foofoo
         raise Exception('You should not be here!')
         return None
     
     G = LinearOperator((len(self.label_row_inds), len(self.label_row_inds)), matvec=mv, rmatvec=mvr, dtype=float64)
     self.A = bicgstab(G, self.Y, maxiter = maxiter)[0]
     self.model = KernelPairwiseModel(self.A, self.label_row_inds, self.label_col_inds)
Exemple #7
0
 def calc_PPinv(self, x, p=0, out=None, left=False):
     if out is None:
         out = np.ones_like(self.A[0])
     
     op = PPInvOp(self, p, left)
     
     if left:
         res = m.H(out).ravel()
         x = m.H(x).ravel()
     else:
         res = out.ravel()
         x = x.ravel()
     
     res, info = las.bicgstab(op, x, x0=res, maxiter=1000, 
                              tol=self.itr_rtol)
     
     if info > 0:
         print "Warning: Did not converge on solution for ppinv!"
     
     #Test
     if self.sanity_checks:
         RHS_test = op.matvec(res)
         if not np.allclose(RHS_test, x, rtol=self.itr_rtol*self.check_fac,
                             atol=self.itr_atol*self.check_fac):
             print "Sanity check failed: Bad ppinv solution! Off by: " + str(
                     la.norm(RHS_test - x))
     
     res = res.reshape((self.D, self.D))
     
     if left:
         res = m.H(res)
     
     out[:] = res
     
     return out
Exemple #8
0
def solve_psg(states, reqs, prob_vec_c, prob_vec_r):
    reqlen = len(reqs)
    one_step_vecs = vecprob_combined(reqs, prob_vec_c, prob_vec_r)
    a = []
    b = []
    idx = 0
    key2idx = {}
    j = states[-1]
    states1 = [s for s in states if s != j]
    print('creating matrix...')
    prog = Progress(total_iter=len(states1)**2)
    for i in states1:
        key2idx[i] = idx
        idx += 1
        row = []
        for k in states1:
            if k == i:
                row.append(1.0 - get_p(i, i, reqs, one_step_vecs, j))
            else:
                row.append(-1.0 * get_p(i, k, reqs, one_step_vecs, j))
            prog.count()
        a.append(row.copy())
    b = [1] * len(states1)
    a = np.array(a)
    b = np.array(b)
    print('solving linear system...')
    x, info = lin.bicgstab(a, b)
    # print(x)
    print('solve info: ', info)
    # x = np.linalg.solve(a,b)
    v0 = tuple([0] * reqlen)
    return x[key2idx[v0]]
Exemple #9
0
    def MakeHeff(self, A, c, tol=1e-14):
        def P_NullSpace(x):
            """Projecting x on the nullspace of 1 - T
            """
            x = x.reshape(self.bond, self.bond)
            return np.trace(c.conj().T @ x @ c) * np.eye(self.bond)

        def Transfer(x):
            """Doing (1 - (T - P)) @ x
            """
            x = x.reshape(self.bond, self.bond)
            res = x.ravel().copy()
            res += P_NullSpace(x).ravel()
            temp = x @ A.reshape(self.bond, -1)
            res -= (A.reshape(-1, self.bond).conj().T @ temp.reshape(
                -1, self.bond)).ravel()

            return res

        AA = A.reshape(-1, self.bond) @ A.reshape(self.bond, -1)
        HAA = self.H_2site(AA)

        h = AA.reshape(-1, self.bond).conj().T @ HAA.reshape(-1, self.bond)

        LO = LinearOperator((self.bond * self.bond, ) * 2,
                            matvec=Transfer,
                            dtype=self._dtype)

        r, info = bicgstab(LO, (h - P_NullSpace(h)).ravel(), tol=tol)

        # return (1 - P) @ result
        r = r.reshape(self.bond, self.bond)
        return r - P_NullSpace(r), info
Exemple #10
0
    def solve(self, sym=True):
        """
        Resuelve la EDP numéricamente.

        Parameters
        ----------
        opt : bool, optional
            Optimización ¿?. The default is False.
        sym : bool, optional
            Determina si la matriz es simétrica o no. The default is True.
            
        Returns
        -------
        __phi : Array-like
            Solución aproximada de la EDP.
            
        """
        PDE.linsys.constructMat()
        PDE.linsys.constructRHS(self.__phi)

        self.__applyBoundaryConditions()

        if sym:
            sol, info = spla.cg(PDE.linsys.getCSR(), PDE.linsys.RHS)  #,
            # tol=1e-08,
            # maxiter= 100)
        else:
            sol, info = spla.bicgstab(PDE.linsys.getCSR(),
                                      PDE.linsys.RHS,
                                      tol=1e-08,
                                      maxiter=100)
        self.__update(sol)

        return self.__phi
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')
Exemple #12
0
def poifd(f,hy,hx,nx,ny):

    # Sparse Differentiation Matrices (2D Discrete Laplacian)
    l1x=[1]*(nx-1)
    l0x=[-2]*(nx)
    l1y=[1]*(ny-1)
    l0y=[-2]*(ny)
	
    D2_x=sp.diags( [l1x,l0x,l1x], [-1,0,1], format='csr')
    D2_y=sp.diags( [l1y,l0y,l1y], [-1,0,1], format='csr')

    I_x=sp.eye(nx)
    I_y=sp.eye(ny)
    D2x=(hx**-2)*sp.kron(D2_x,I_y)
    D2y=(hy**-2)*sp.kron(I_x,D2_y)
    L=(D2x+D2y)

    #RHS
    f=np.reshape(f,nx*ny)
    
    #krylov methods
    ubicgs,itr=spl.bicgstab(L,f,tol=1e-7)
#    print("\r iter = %d"%itr , end = " ")
    
    return ubicgs.reshape(nx,ny)
Exemple #13
0
def calcF(Q_, R_, way, rho_, muL_, guess):
    chi, chi = Q_.shape
    rhs = - getQrhsQ(Q_, R_, way, rho_, muL_)

    if(guess == None): guess = np.random.rand(chi * chi) - .5
    guess = guess.reshape(chi * chi)

    linOpWrap = functools.partial(linOpForF, Q_, R_, way, rho_)
    linOpForSol = spspla.LinearOperator((chi * chi, chi * chi), 
                                        matvec = linOpWrap, dtype = 'float64')
    try:
        F, info = spspla.lgmres(linOpForSol, rhs, tol = expS, x0 = guess, 
                                maxiter = maxIter, outer_k = 6)
    except (ArpackError, ArpackNoConvergence):
        print "calcF: bicgstab failed, trying gmres\n"
        guess = F if info > 0 else guess

        try:
            F, info = spspla.bicgstab(linOpForSol, rhs, tol = expS, x0 = guess, 
                                      maxiter = maxIter)
        except (ArpackError, ArpackNoConvergence):
            print "calcF: gmres failed, taking lame solution\n"
            F = F if info > 0 else guess

    #print "F\n", F.reshape(chi, chi)
    return F.reshape(chi, chi)
    def _do_one_inner_iteration(self, A, b, **kwargs):
        r'''
        This method solves AX = b and returns the result to the corresponding algorithm.
        '''
        logger.info("Solving AX = b for the sparse matrices")

        if A is None: A = self.A
        if b is None: b = self.b

        if self._iterative_solver is None:
            X = sprslin.spsolve(A, b)
        else:
            params = kwargs.copy()
            solver_params = ['x0', 'tol', 'maxiter', 'xtype', 'M', 'callback']
            [
                params.pop(item, None) for item in kwargs.keys()
                if item not in solver_params
            ]
            tol = kwargs.get('tol')
            if tol is None: tol = 1e-20
            params['tol'] = tol
            if self._iterative_solver == 'cg':
                result = sprslin.cg(A, b, **params)
            elif self._iterative_solver == 'gmres':
                result = sprslin.gmres(A, b, **params)
            elif self._iterative_solver == 'bicgstab':
                result = sprslin.bicgstab(A, b, **params)
            X = result[0]
            self._iterative_solver_info = result[1]
        return X
Exemple #15
0
 def __solve_iterative__(self):
     self.__progress__.set_process('Solving of equation system...', 1, 1)
     self.__global_matrix_stiffness__ = self.__global_matrix_stiffness__.tocsr()
     self.__global_load__, info = bicgstab(self.__global_matrix_stiffness__, self.__global_load__,
                                           self.__global_load__, self.__params__.eps)
     self.__progress__.set_progress(1)
     return True if not info else False
Exemple #16
0
    def _scipy_solver(self, vs, rhs, sol, boundary_val):
        utilities.enforce_boundaries(vs, sol)

        boundary_mask = np.logical_and.reduce(~vs.boundary_mask, axis=2)
        rhs = utilities.where(vs, boundary_mask, rhs, boundary_val) # set right hand side on boundaries
        x0 = sol.flatten()

        try:
            rhs = rhs.copy2numpy()
        except AttributeError:
            pass

        try:
            x0 = x0.copy2numpy()
        except AttributeError:
            pass

        rhs = rhs.flatten() * self._preconditioner.diagonal()
        linear_solution, info = spalg.bicgstab(
            self._matrix, rhs,
            x0=x0, atol=0, tol=vs.congr_epsilon,
            maxiter=vs.congr_max_iterations,
            **self._extra_args
        )

        if info > 0:
            logger.warning('Streamfunction solver did not converge after {} iterations', info)

        if rs.backend == 'bohrium':
            linear_solution = np.asarray(linear_solution)

        sol[...] = linear_solution.reshape(vs.nx + 4, vs.ny + 4)
Exemple #17
0
    def py_initialize(self, dst, t, dt):
        import scipy.sparse as sp
        from scipy.sparse.linalg import bicgstab

        coeff = declare('object')
        cond = declare('object')
        n = declare('int')
        n = dst.np[0]

        # Mask all indices which are not used in the construction.
        cond = (dst.col_idx != -1)

        coeff = sp.csr_matrix(
            (dst.coeff[cond], (dst.row_idx[cond], dst.col_idx[cond])),
            shape=(n, n)
        )
        # Add tiny random noise so the matrix is not singular.
        cond = abs(dst.rhs) > 1e-9
        dst.diag[cond] -= numpy.random.random(n)[cond]

        coeff += sp.diags(dst.diag)

        # Pseudo-Neumann boundary conditions
        dst.rhs[cond] -= dst.rhs[cond].mean()

        dst.p[:], ec = bicgstab(coeff, dst.rhs, x0=dst.p)
        assert ec == 0, "Not converging!"
Exemple #18
0
def calcF(Q_, R_, way, rho_, muL_, guess):
    chi, chi = Q_.shape
    rhs = -getQrhsQ(Q_, R_, way, rho_, muL_)

    if (guess == None): guess = np.random.rand(chi * chi) - .5
    guess = guess.reshape(chi * chi)

    linOpWrap = functools.partial(linOpForF, Q_, R_, way, rho_)
    linOpForSol = spspla.LinearOperator((chi * chi, chi * chi),
                                        matvec=linOpWrap,
                                        dtype='float64')
    try:
        F, info = spspla.lgmres(linOpForSol,
                                rhs,
                                tol=expS,
                                x0=guess,
                                maxiter=maxIter,
                                outer_k=6)
    except (ArpackError, ArpackNoConvergence):
        print "calcF: bicgstab failed, trying gmres\n"
        guess = F if info > 0 else guess

        try:
            F, info = spspla.bicgstab(linOpForSol,
                                      rhs,
                                      tol=expS,
                                      x0=guess,
                                      maxiter=maxIter)
        except (ArpackError, ArpackNoConvergence):
            print "calcF: gmres failed, taking lame solution\n"
            F = F if info > 0 else guess

    #print "F\n", F.reshape(chi, chi)
    return F.reshape(chi, chi)
Exemple #19
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 timestep(self,dt): #performs one timestep, i.e. calculates a new surface elev, thickness from prev one
     D = np.zeros(self.num_nodes)
     slopes = tools.calculate_slopes(self.surface_elev, self.dx) 
     for i in range(0,self.num_nodes):
         if(i<20):
             D[i] = (((-2*self.glenns_a*(self.p*self.g)**self.glenns_n)/(self.glenns_n+2))*(self.ice_thickness[i]**(self.glenns_n+2))*(abs((slopes[i])**(self.glenns_n-1))))-(self.bslip_1*self.p*self.g*(self.ice_thickness[i]**2))
         elif(i<40):
             D[i] = (((-2*self.glenns_a*(self.p*self.g)**self.glenns_n)/(self.glenns_n+2))*(self.ice_thickness[i]**(self.glenns_n+2))*(abs((slopes[i])**(self.glenns_n-1))))-(self.bslip_2*self.p*self.g*(self.ice_thickness[i]**2))
         else:
             D[i] = (((-2*self.glenns_a*(self.p*self.g)**self.glenns_n)/(self.glenns_n+2))*(self.ice_thickness[i]**(self.glenns_n+2))*(abs((slopes[i])**(self.glenns_n-1))))-(self.bslip_3*self.p*self.g*(self.ice_thickness[i]**2))
     
     A = sparse.lil_matrix((self.num_nodes,self.num_nodes)) 
     A[0, 0] = 1 
     A[self.num_nodes-1, self.num_nodes-1] = 1 
     B = np.zeros(self.num_nodes)
     B[0] = self.bed_elev[0] 
     B[self.num_nodes-1] = self.bed_elev[self.num_nodes-1] 
     
     for i in range(1, self.num_nodes-1): 
         alpha = (dt/(4.0*self.dx**2))*(D[i] + D[i+1]) 
         beta = (dt/(4.0*self.dx**2))*(D[i-1] + D[i]) 
         A[i, i-1] = beta
         A[i, i] = 1 - alpha - beta
         A[i, i+1] = alpha
         B[i] = (-alpha*self.surface_elev[i+1]) + ((1 + alpha + beta)*self.surface_elev[i]) - (beta*self.surface_elev[i-1]) + (self.mass_balance[i]*dt)
     
     self.surface_elev, info=linalg.bicgstab(A, B) 
     
     for i in range(self.num_nodes):
         if(self.surface_elev[i] < self.bed_elev[i]):
             self.surface_elev[i] = self.bed_elev[i]
     self.ice_thickness = self.surface_elev - self.bed_elev
     self.time += dt
Exemple #21
0
    def solve_for_phi_dirichlet_boltzmann(self):
        '''
        Solves for the electric potential from the charge density using
        Boltzmann (AKA adiabatic) electrons assuming dirichlet-dirichlet BCs.

        Tests:
            Tests are hard to write for the boltzmann solver. This one just
            enforces zero electric potential in a perfectly neutral plasma.
            >>> grid = Grid(5, 4.0, 1.0)
            >>> grid.n0 = 1.0/e
            >>> grid.rho[:] = np.ones(5)
            >>> grid.n[:] = np.ones(5)/e
            >>> grid.solve_for_phi_dirichlet_boltzmann()
            >>> grid.phi
            array([0., 0., 0., 0., 0.])
        '''
        residual = 1.0
        tolerance = 1e-9
        iter_max = 1000
        iter = 0


        #for faster convergence use an advance guess
        phi = self.phi.copy()

        dx2 = self.dx*self.dx
        c0 = e*self.n0/epsilon0
        c1 = e/kb/self.Te
        c2 = self.rho/epsilon0
        J  = np.zeros((self.ng,self.ng),dtype=float)

        while (residual > tolerance) and (iter < iter_max):

            F = np.dot(self.A,phi)
            for i in range(1,self.ng-1):
                F[i]+= -dx2*c0*np.exp(c1*(phi[i])) + dx2*c2[i]

            F[0]  -= self.BC0
            F[-1] -= self.BC1


            J= self.A.copy()

            for i in range(1,self.ng-1):
                J[i][i] -= dx2*c0*c1*np.exp(c1*phi[i])

            J = spp.csc_matrix(J)
            #dphi = sppla.inv(J).dot(F)

            dphi, _ = sppla.bicgstab(J, F, x0=phi)
            #the ignored return might be useful to check for convergence.


            phi = phi - dphi
            residual = dphi.dot(dphi)
            residual = np.sqrt(residual)
            iter += 1
        #end while
        self.phi = phi.copy()
Exemple #22
0
 def scipy_solver(rhs, x0):
     rhs = rhs.flatten() * preconditioner.diagonal()
     solution, info = spalg.bicgstab(matrix, rhs,
                                     x0=x0.flatten(), tol=vs.congr_epsilon,
                                     maxiter=vs.congr_max_iterations,
                                     **extra_args)
     if info > 0:
         warnings.warn("Streamfunction solver did not converge after {} iterations".format(info))
     return solution
Exemple #23
0
    def solve_linear(self, regparam):
        self.regparam = regparam
        X1 = self.resource_pool['xmatrix1']
        X2 = self.resource_pool['xmatrix2']
        self.X1, self.X2 = X1, X2

        if 'maxiter' in self.resource_pool:
            maxiter = int(self.resource_pool['maxiter'])
        else:
            maxiter = None

        x1tsize, x1fsize = X1.shape  #m, d
        x2tsize, x2fsize = X2.shape  #q, r
        lsize = len(self.label_row_inds)  #n

        kronfcount = x1fsize * x2fsize

        label_row_inds = np.array(self.label_row_inds, dtype=np.int32)
        label_col_inds = np.array(self.label_col_inds, dtype=np.int32)

        def mv(v):
            v_after = sparse_kronecker_multiplication_tools_python.x_gets_subset_of_A_kron_B_times_v(
                v, X1, X2.T, label_row_inds, label_col_inds)
            v_after = sparse_kronecker_multiplication_tools_python.x_gets_A_kron_B_times_sparse_v(
                v_after, X1.T, X2, label_row_inds,
                label_col_inds) + regparam * v
            return v_after

        def mvr(v):
            raise Exception('You should not be here!')
            return None

        def cgcb(v):
            self.W = v.reshape((x1fsize, x2fsize), order='F')
            self.callback()

        G = LinearOperator((kronfcount, kronfcount),
                           matvec=mv,
                           rmatvec=mvr,
                           dtype=np.float64)

        v_init = np.array(self.Y).reshape(self.Y.shape[0])
        v_init = sparse_kronecker_multiplication_tools_python.x_gets_A_kron_B_times_sparse_v(
            v_init, X1.T, X2, label_row_inds, label_col_inds)
        v_init = np.array(v_init).reshape(kronfcount)
        if self.resource_pool.has_key('warm_start'):
            x0 = np.array(self.resource_pool['warm_start']).reshape(kronfcount,
                                                                    order='F')
        else:
            x0 = None
        self.W = bicgstab(G, v_init, x0=x0, maxiter=maxiter,
                          callback=cgcb)[0].reshape((x1fsize, x2fsize),
                                                    order='F')
        self.model = LinearPairwiseModel(self.W, X1.shape[1], X2.shape[1])
        self.finished()
Exemple #24
0
    def integrate(self, t, y0=None, t0=None):
        if y0 is not None:
            # set initial condition
            y0 = ravel(y0)
            self.y, self.y0, self.y00 = y0.copy(), y0.copy(), y0.copy()
            self.dt0 = 0
            self.I = scipy.sparse.eye(self.y.size, self.y.size)
            if t0 is None: t0 = 0.
            self.t = t0

        # time advance to t
        while self.t < t:
            t0 = self.t
            self.t = min(t, self.t + self.dt)
            dt, dt0 = self.t - t0, self.dt0
            dt0 = dt
            print self.t, t0, self.dt
            # Coefficients, y = b0 * y0 + b00 * y00 + a * f(y)
            # BDF2 if dt == dt0, Backward Euler if dt0 == 0
            b00 = -1 / max(3., dt0 * (dt0 + 2 * dt) / dt**2)
            a, b0 = dt + b00 * dt0, 1 - b00
            # newton iteration
            nIterMin, nIterMax = 4, 10
            for i in range(nIterMax+1):
                dydt = self.ddt(self.y)


                if not isfinite(dydt).all():
                    nIter = nIterMax + 1
                    break
                res = self.y - b0 * self.y0 - b00 * self.y00 - a * dydt
                resNorm = sqrt((res**2).sum() / (self.y**2).sum())
                print 'iter {0:d} with dt={1:.2e}, log_10(res)= {2:.2f}'.format(i, dt, log10(resNorm) )
                if resNorm < 1E-9 or resNorm < self.tol or i >= nIterMax:
                    nIter = i + 1
                    break

                J = self.J(self.y)

                tmp = self.I - a*J;
                dy, err = splinalg.bicgstab( tmp, res , maxiter=30)
                self.y -= dy

            if nIter > nIterMax:
                self.t = t0
                self.y[:] = self.y0[:]
                self.dt *= 0.8
                print 'bad, dt = ', self.dt
            else:
                self.dt0 = dt
                self.y00[:] = self.y0
                self.y0[:] = self.y
                if nIter < nIterMin:
                    self.dt = min(self.dtMax, max(dt, self.dt / 0.8))
        return self.y
Exemple #25
0
def var_from_P(P_, angle_bins_, observable_f):
    #P_ = LA.matrix_power(P_, 2)
    D = P_.shape[0]
    #f_ = np.array([2*x for x in angle_bins_]) - np.pi
    f_ = np.array([observable_f(x) for x in angle_bins_])
    IMP_ = np.identity(D) - P_

    g_, inf_ = SSLA.bicgstab(IMP_, f_, tol=10**(-2))

    v_est = inner_prod(f_, f_) + 2 * inner_prod(np.matmul(P_, f_), g_)
    return v_est
    def fit(self, adjacency: Union[sparse.csr_matrix, np.ndarray],
            seeds: Optional[Union[dict, np.ndarray]] = None, initial_state: Optional = None) -> 'Diffusion':
        """Compute the diffusion (temperature at equilibrium).

        Parameters
        ----------
        adjacency :
            Adjacency matrix of the graph.
        seeds :
            Temperatures of border nodes (dictionary or vector). Negative temperatures ignored.
        initial_state :
            Initial state of temperatures.

        Returns
        -------
        self: :class:`Diffusion`
        """
        adjacency = check_format(adjacency)
        check_square(adjacency)
        n: int = adjacency.shape[0]
        if seeds is None:
            self.scores_ = np.ones(n) / n
            return self

        seeds = check_seeds(seeds, n)
        b, border = limit_conditions(seeds)
        tmin, tmax = np.min(b[border]), np.max(b)

        interior: sparse.csr_matrix = sparse.diags(~border, shape=(n, n), format='csr', dtype=float)
        diffusion_matrix = interior.dot(normalize(adjacency))

        if initial_state is None:
            if tmin != tmax:
                initial_state = b[border].mean() * np.ones(n)
            else:
                initial_state = np.zeros(n)
            initial_state[border] = b[border]

        if self.n_iter > 0:
            scores = initial_state
            for i in range(self.n_iter):
                scores = diffusion_matrix.dot(scores)
                scores[border] = b[border]

        else:
            a = sparse.eye(n, format='csr', dtype=float) - diffusion_matrix
            scores, info = bicgstab(a, b, atol=0., x0=initial_state)
            self._scipy_solver_info(info)

        if tmin != tmax:
            self.scores_ = np.clip(scores, tmin, tmax)
        else:
            self.scores_ = scores
        return self
Exemple #27
0
    def test_preconditioner(self):
        A, rhs = make_problem(100)

        for rtype in ('spai0', 'ilu0'):
            P = amg.amgcl(A, prm={'relax.type': rtype})
            # Solve
            x,info = bicgstab(A, rhs, M=P, tol=1e-3)
            self.assertTrue(info == 0)

            # Check residual
            self.assertTrue(norm(rhs - A * x) / norm(rhs) < 1e-3)
Exemple #28
0
    def test_preconditioner(self):
        A, rhs = make_problem(100)

        for rtype in ('spai0', 'ilu0'):
            P = amg.amgcl(A, prm={'relax.type': rtype})
            # Solve
            x, info = bicgstab(A, rhs, M=P, tol=1e-3)
            self.assertTrue(info == 0)

            # Check residual
            self.assertTrue(norm(rhs - A * x) / norm(rhs) < 1e-3)
Exemple #29
0
def mixedcg(A, B, f, g):
    Asolve = ssld.factorized(A)
    Aif = Asolve(f.flatten())
    BAf = B * Aif
    
    def BAiBt(p):
        return B * Asolve(B.transpose() * p)
    
    p, info = ssl.bicgstab(ssl.LinearOperator((B.shape[0],)*2, matvec = BAiBt, dtype=float), BAf - g.flatten())
    print "bicgstab result ",info
    u = Aif - Asolve(B.transpose() * p)
    return u,p
	def stepTime(self):
		# solve for intermediate velocity
		self.calculateRN()
		self.qStar, _ = sla.bicgstab(self.A, self.rn, tol=1e-8)

		# solve for pressure
		self.rhs2 = self.QT*self.qStar
		#self.phi, _ = sla.cg(self.QTBNQ, self.rhs2)
		self.phi = self.ml.solve(self.rhs2, tol=1e-8)

		# projection step
		self.q = self.qStar - self.BNQ*self.phi
 def timeEvolution(self,tau,duration):
   self.duration = duration
   # Define A and B matrices
   A = sp.identity(self.gridLength) - tau/(2j)*self.H
   B = sp.identity(self.gridLength) + tau/(2j)*self.H
   self.time_evolved_psi = np.zeros((self.gridLength,duration),dtype=complex)
   # Start time evolution
   for i in range(0,duration):
     self.time_evolved_psi[:,i],_ = linalg.bicgstab(A,B.dot(self.psi).transpose(),tol=1e-10)
     self.psi = self.time_evolved_psi[:,i]
   if str.lower(self.potentialName) == "rectangular barrier":
     return np.trapz(np.abs(self.psi[self.barrierEnd:])**2)
 def generate_firing_script(self, configuration_start,
                            configuration_target):
     '''sigma = L^-1 (c - c') iff c = c' mod L '''
     print('Generating firing script')
     x = la.bicgstab(self.get_reduced_laplacian(),
                     configuration_start - configuration_target,
                     tol=1e-2)
     if x[1] == 0:
         print('Sucessfully found a script')
         return x[0]
     else:
         return np.zeros(length(configuration_start))
Exemple #33
0
    def stepTime(self):
        # solve for intermediate velocity
        self.calculateRN()
        self.qStar, _ = sla.bicgstab(self.A, self.rn, tol=1e-8)

        # solve for pressure
        self.rhs2 = self.QT * self.qStar
        #self.phi, _ = sla.cg(self.QTBNQ, self.rhs2)
        self.phi = self.ml.solve(self.rhs2, tol=1e-8)

        # projection step
        self.q = self.qStar - self.BNQ * self.phi
Exemple #34
0
    def fit(self,
            adjacency: Union[sparse.csr_matrix, np.ndarray],
            seeds: Optional[Union[dict, np.ndarray]] = None,
            init: Optional[float] = None) -> 'Dirichlet':
        """Compute the solution to the Dirichlet problem (temperatures at equilibrium).

        Parameters
        ----------
        adjacency :
            Adjacency matrix of the graph.
        seeds :
            Temperatures of seed nodes (dictionary or vector). Negative temperatures ignored.
        init :
            Temperature of non-seed nodes in initial state.
            If ``None``, use the average temperature of seed nodes (default).

        Returns
        -------
        self: :class:`Dirichlet`
        """
        adjacency = check_format(adjacency)
        check_square(adjacency)
        n: int = adjacency.shape[0]
        if seeds is None:
            self.scores_ = np.ones(n) / n
            return self

        seeds = check_seeds(seeds, n)
        border = (seeds >= 0)

        if init is None:
            scores = seeds[border].mean() * np.ones(n)
        else:
            scores = init * np.ones(n)
        scores[border] = seeds[border]

        if self.n_iter > 0:
            diffusion = DirichletOperator(adjacency, self.damping_factor,
                                          border)
            for i in range(self.n_iter):
                scores = diffusion.dot(scores)
                scores[border] = seeds[border]
        else:
            a = DeltaDirichletOperator(adjacency, self.damping_factor, border)
            b = -seeds
            b[~border] = 0
            scores, info = bicgstab(a, b, atol=0., x0=scores)
            self._scipy_solver_info(info)

        tmin, tmax = seeds[border].min(), seeds[border].max()
        self.scores_ = np.clip(scores, tmin, tmax)

        return self
Exemple #35
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
Exemple #36
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
def solveMomentumViscousTerms(us, vs, dt, dx, dy, nu, A_u, A_v, rhs_u, rhs_v,
                              rhs_u_bound, rhs_v_bound, solver, tol, ml_u, ml_v,
                              M_u, M_v):

    # Right hand sides
    rhs_u[:, :] = us[1:-1, 1:-1] + rhs_u_bound[:, :]
    rhs_v[:, :] = vs[1:-1, 1:-1] + rhs_v_bound[:, :]

    # Solve linear systems
    if solver == 'amg_precond_bicgstab':
        [us[1:-1, 1:-1].flat[:], info] = spla.bicgstab(
            A_u, rhs_u.ravel(), x0=u[1:-1, 1:-1].ravel(), tol=tol, M=M_u)
        [vs[1:-1, 1:-1].flat[:], info] = spla.bicgstab(
            A_v, rhs_v.ravel(), x0=v[1:-1, 1:-1].ravel(), tol=tol, M=M_v)
    elif solver == 'amg':
        us[1:-1, 1:-1].flat[:] = ml_u.solve(rhs_u.ravel(), tol=tol)
        vs[1:-1, 1:-1].flat[:] = ml_v.solve(rhs_v.ravel(), tol=tol)
    else:
        us[1:-1, 1:-1].flat[:] = spla.spsolve(A_u, rhs_u.ravel())
        vs[1:-1, 1:-1].flat[:] = spla.spsolve(A_v, rhs_v.ravel())

    return us, vs, rhs_u, rhs_v
Exemple #38
0
    def test_preconditioner(self):
        (A, rhs) = make_problem(256)

        # Setup preconditioner
        P = amg.make_preconditioner(A)

        # Solve
        x, info = bicgstab(A, rhs, M=P, tol=1e-8)
        self.assertTrue(info == 0)

        # Check residual
        self.assertTrue(
            np.linalg.norm(rhs - A * x) / np.linalg.norm(rhs) < 1e-8)
Exemple #39
0
 def block_Jacobi_prec_bicgstab_solve(self, b):
     a = LinearOperator((self._n_dof, self._n_dof),
                        lambda v: self.matvec(v))
     p = LinearOperator((self._n_dof, self._n_dof),
                        lambda rhs: self.block_diag_solve(rhs))
     self._iteration_count = 0
     x, i = bicgstab(a,
                     b,
                     M=p,
                     tol=1.e-14,
                     maxiter=8,
                     callback=self._increment_iteration_count)
     return x, self._iteration_count, not i
Exemple #40
0
def BICGSTAB_PageRank(H, alpha, tol):
    """
    input hyperlink matrix `H`, teleportation parameter `alpha` and iteration times
    return the error list of PageRank vector calculated by BICGSTAB Mathod
    (I-alpha*S)pi^{T} = (1-alpha) * 1/n * e^T
    """
    n = matrix_size(H)
    I = np.identity(n)
    S = adjust_matrix(H)
    A = I - alpha * S.transpose()
    b = (1 - alpha) / n * np.ones((n, 1), dtype=int)
    x0 = 1 / n * np.ones((n, 1))
    return spla.bicgstab(A, b, x0, tol)
Exemple #41
0
 def default_solver(A, RHS):
     assert isinstance(A, NumpyLinearOperator)
     assert isinstance(RHS, NumpyLinearOperator)
     A = A._matrix
     RHS = RHS._matrix
     assert len(RHS) == 1
     if RHS.shape[1] == 0:
         return NumpyVectorArray(RHS)
     RHS = RHS.ravel()
     if issparse(A):
         U, _ = bicgstab(A, RHS, tol=defaults.bicgstab_tol, maxiter=defaults.bicgstab_maxiter)
     else:
         U = np.linalg.solve(A, RHS)
     return NumpyVectorArray(U)
Exemple #42
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")
Exemple #43
0
def calcHmeanval(MPS, R, C):
    chir, chic, aux = MPS.shape
    QHAAAAR = getQHaaaaR(MPS, R, C)

    linOpWrapped = functools.partial(linearOpForK, MPS, R)
    linOpForBicg = spspla.LinearOperator((chir * chir, chic * chic), 
                                         matvec = linOpWrapped, 
                                         dtype = MPS.dtype)
    K, info = spspla.bicgstab(linOpForBicg, QHAAAAR, tol = expS, 
                              maxiter = maxIter)
    if info != 0: print "\nWARNING: bicgstab failed!\n"; exit()

    K = np.reshape(K, (chir, chic))
    print "QHAAAAR", QHAAAAR.shape, "K\n", K

    return K
Exemple #44
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
Exemple #45
0
    def iterative_solve(self, **kwargs):
        self._apply_bcs()

        num_i, num_j = self.var.shape
        num = num_i*num_j

        diags = self.a[:, :, 0].flatten(order='F')[:-1], \
                self.a[:, :, 1].flatten(order='F')[0:num - num_i], \
                self.a[:, :, 2].flatten(order='F')[1:], \
                self.a[:, :, 3].flatten(order='F')[num_i:], \
                self.a[:, :, 4].flatten(order='F')

        spmat = sp.diags(diags, [1, num_i, -1, -num_i, 0], format='csr')
        rhs = self.b.flatten(order='F')

        self.var[:, :] = spla.bicgstab(spmat, rhs, **kwargs)[0].reshape(self.var.shape, order='F')

        return self.var
Exemple #46
0
def simulation(nx, its, dt, psi, V):

    import numpy as np
    import scipy.sparse.linalg as sp

    dx = np.divide(1.0, nx)
    absdata = np.zeros((its+1, nx))
    angdata = np.zeros((its+1, nx))

    # Force boundaries
    m = 1  # Mass
    absdata[0, :] = np.absolute(psi)
    angdata[0, :] = np.angle(psi)
    """
    We want to solve the system A * psi [t+1] = B * psi [t]
    Here A = 1-iH * dt/2, B = 1 + iH * dt/2.
    Note hbar = 1
    """
    # Initialization of Crank-Nicholson Matrix
    diagzeroA = 1 - dt / (2 * 1j * m * dx**2) - (dt / (2 * 1j)) * V
    diagoneA = dt / (4 * 1j * m * dx**2) * np.ones(nx-1)
    diagzeroB = -1 * diagzeroA + 2
    diagoneB = -1 * diagoneA

    def tridiagmatcreator(a, b, c, k1=-1, k2=0, k3=1):
        return np.diag(a, k1) + np.diag(b, k2) + np.diag(c, k3)

    A = tridiagmatcreator(diagoneA, diagzeroA, diagoneA)
    B = tridiagmatcreator(diagoneB, diagzeroB, diagoneB)

    #  Periodic boundary conditions
    B[0, -1] = diagoneB[0]
    B[-1, 0] = diagoneB[0]
    A[0, -1] = diagoneA[0]
    A[-1, 0] = diagoneA[0]

    for t in range(its):
        newb = np.dot(B, psi)
        psi, info = sp.bicgstab(A, newb)
        absdata[t+1, :] = np.absolute(psi)
        angdata[t+1, :] = np.angle(psi)

    return absdata, angdata
Exemple #47
0
 def solve_linear(self, regparam):
     self.regparam = regparam
     X1 = self.resource_pool['xmatrix1']
     X2 = self.resource_pool['xmatrix2']
     self.X1, self.X2 = X1, X2
     
     if 'maxiter' in self.resource_pool: maxiter = int(self.resource_pool['maxiter'])
     else: maxiter = None
     
     x1tsize, x1fsize = X1.shape #m, d
     x2tsize, x2fsize = X2.shape #q, r
     lsize = len(self.label_row_inds) #n
     
     kronfcount = x1fsize * x2fsize
     
     label_row_inds = np.array(self.label_row_inds, dtype = np.int32)
     label_col_inds = np.array(self.label_col_inds, dtype = np.int32)
     
     def mv(v):
         v_after = sparse_kronecker_multiplication_tools_python.x_gets_subset_of_A_kron_B_times_v(v, X1, X2.T, label_row_inds, label_col_inds)
         v_after = sparse_kronecker_multiplication_tools_python.x_gets_A_kron_B_times_sparse_v(v_after, X1.T, X2, label_row_inds, label_col_inds) + regparam * v
         return v_after
     
     def mvr(v):
         raise Exception('You should not be here!')
         return None
     
     def cgcb(v):
         self.W = v.reshape((x1fsize, x2fsize), order = 'F')
         self.callback()
         
     G = LinearOperator((kronfcount, kronfcount), matvec = mv, rmatvec = mvr, dtype = np.float64)
     
     v_init = np.array(self.Y).reshape(self.Y.shape[0])
     v_init = sparse_kronecker_multiplication_tools_python.x_gets_A_kron_B_times_sparse_v(v_init, X1.T, X2, label_row_inds, label_col_inds)
     v_init = np.array(v_init).reshape(kronfcount)
     if self.resource_pool.has_key('warm_start'):
         x0 = np.array(self.resource_pool['warm_start']).reshape(kronfcount, order = 'F')
     else:
         x0 = None
     self.W = bicgstab(G, v_init, x0 = x0, maxiter = maxiter, callback = cgcb)[0].reshape((x1fsize, x2fsize), order='F')
     self.model = LinearPairwiseModel(self.W, X1.shape[1], X2.shape[1])
     self.finished()
Exemple #48
0
def scoreTX(s, lap_t, pst_t, wt):
    try:
        h = lin.spsolve(lap_t, pst_t)
    except:
        # a singular matrix ... must solve each vector separately
        vecs = pst_t.shape[1]
        hsolns = []
        for i in range(vecs):
            pst_t2 = pst_t[:,i].todense()
            h1 = lin.bicgstab(lap_t, pst_t2)[0]
            hsolns.append(h1)
        h = np.matrix(hsolns)
        h = h.transpose()
    if type(h) == type(np.array([])): # came back as an array
        htouch = sum(h > s["tx"])
    else: # came back as a sparse matrix
        hsum = np.array(h.sum(1)).flatten()
        htouch = sum(hsum > s["tx"])
    return((htouch+wt, htouch))
def run(A, B, x, psi, a, L, dx, ims = None):

    y = 2*np.max(abs(psi))**2
    c = cn = i = 0
    while cn>=c or c>10e-6:
        c = cn
        if ims!=None and i%4==0:
            plt.axis((0,L,0,y))
            im, = plt.plot(x, np.abs(psi)**2, 'b')
            ims.append([im])

        # use the sparse stabilized biconjugate gradient method to solve the matrix eq
        [psi, error] = linalg.bicgstab(A, B*psi, x0=psi)
        if error != 0: sys.exit("bicgstab did not converge")

        i = i+1
        # calculate the new norm in the barrier
        cn = sum(abs(psi[int(round((L - a)/(2*dx))):int(round((L + a)/(2*dx)))])**2)*dx

    return psi, sum(abs(psi[int(round((L - a)/(2*dx))):])**2)*dx/(sum(abs(psi)**2)*dx)
Exemple #50
0
def run(psi, A, B, L, n, x1, ax):

    xGrid , yGrid = np.meshgrid(np.linspace(0,L,n),np.linspace(0,L,n))

    psiPlot = np.abs(psi.reshape(n,n)**2)
    interference = psiPlot[:,np.round(3.*n/4.)]
    for i in range(300):

        if i%10 == 0:
            wireFrame = ax.plot_wireframe(xGrid, yGrid, psiPlot, rstride = 2, cstride = 2)
            plt.pause(.001)
            ax.collections.remove(wireFrame)

        [psi, error] = linalg.bicgstab(A, B*psi,x0=psi)
        if error != 0: sys.exit("bicgstab did not converge")

        psiPlot = np.abs(psi.reshape(n,n)**2)
        interference += psiPlot[:,np.round((x1+0.5*L)*n/L)]

    return interference
Exemple #51
0
def solve_linear_numpy_bicgstab(A, U, ind=None, tol=None, maxiter=None):
    assert isinstance(A, NumpyLinearOperator)
    assert isinstance(U, NumpyVectorArray)
    assert A.dim_range == U.dim

    tol =  defaults.bicgstab_tol if tol is None else tol
    maxiter = defaults.bicgstab_maxiter if maxiter is None else maxiter

    A = A._matrix
    U = U._array if ind is None else U._array[ind]
    if U.shape[1] == 0:
        return NumpyVectorArray(U)
    R = np.empty((len(U), A.shape[1]))
    if issparse(A):
        for i, UU in enumerate(U):
            R[i], _ = bicgstab(A, UU, tol=tol, maxiter=maxiter)
    else:
        for i, UU in enumerate(U):
            R[i] = np.linalg.solve(A, UU)
    return NumpyVectorArray(R)
Exemple #52
0
 def solve_linear(self, regparam):
     self.regparam = regparam
     X1 = mat(self.resource_pool['xmatrix1'])
     X2 = mat(self.resource_pool['xmatrix2'])
     self.X1, self.X2 = X1, X2
     
     if 'maxiter' in self.resource_pool: maxiter = int(self.resource_pool['maxiter'])
     else: maxiter = None
     
     x1tsize, x1fsize = X1.shape #m, d
     x2tsize, x2fsize = X2.shape #q, r
     lsize = len(self.label_row_inds) #n
     
     kronfcount = x1fsize * x2fsize
     
     label_row_inds = array(self.label_row_inds, dtype=int32)
     label_col_inds = array(self.label_col_inds, dtype=int32)
     
     def mv(v):
         v_after = u_gets_axb(v, X1, X2.T, label_row_inds, label_col_inds)
         v_after = c_gets_axb(v_after, X1.T, X2, label_row_inds, label_col_inds) + regparam * v
         return v_after
     
     def mvr(v):
         raise Exception('You should not be here!')
         return None
     
     def cgcb(v):
         self.W = mat(v).T.reshape((x1fsize, x2fsize),order='F')
         self.callback()
         
     G = LinearOperator((kronfcount, kronfcount), matvec=mv, rmatvec=mvr, dtype=float64)
     
     v_init = array(self.Y).reshape(self.Y.shape[0])
     v_init = c_gets_axb(v_init, X1.T, X2, label_row_inds, label_col_inds)
     v_init = array(v_init).reshape(kronfcount)
     self.W = mat(bicgstab(G, v_init, maxiter = maxiter, callback = cgcb)[0]).T.reshape((x1fsize, x2fsize),order='F')
     self.model = LinearPairwiseModel(self.W, X1.shape[1], X2.shape[1])
     self.finished()
Exemple #53
0
A = (1.+4.*c1)*sparse.identity(N) \
    - c1*sparse.eye(N,N,1) - c1*sparse.eye(N,N,-1) - c1*sparse.eye(N,N,n) - c1*sparse.eye(N,N,-n)
B = (1.-4.*c1)*sparse.identity(N) \
    + c1*sparse.eye(N,N,1) + c1*sparse.eye(N,N,-1) + c1*sparse.eye(N,N,n) + c1*sparse.eye(N,N,-n)

# generate x-coordinates and initial wave-function
x = np.linspace(0,L,n)
xGrid , yGrid = np.meshgrid(x,x)  # plotting coordinate grids

# psi = np.exp(-0.1*((np.tile(x, n)-L/4)**2)) * np.exp(1.j*k*np.tile(x, n))  # gaussian front
psi = np.exp(-0.1*((np.tile(x, n)-L/4)**2 + (np.repeat(x, n)-L/2)**2)) \
      * np.exp(1.j*k*np.tile(x, n))  # gaussian peak

psi /= np.sqrt(sum(abs(psi)**2*dx**2))  # normalize the wave function

# initialize figure for plotting
plt.ion()
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.set_zlim(0,2.*np.amax(np.abs(psi)**2))

for i in range(1000):

    if i%5 == 0:
        psiPlot = np.abs(psi.reshape(n,n)**2)
        wireFrame = ax.plot_wireframe(xGrid, yGrid, psiPlot, rstride = 2, cstride = 2)
        plt.pause(.001)
        ax.collections.remove(wireFrame)

    [psi, garbage] = linalg.bicgstab(A, B*psi)
Exemple #54
0
for j in arange(p):
    sm[j*N,j*N] = sm[j*N,j*N-1] = -3./2./h
    sm[j*N,j*N+1] = sm[j*N,j*N-2] = 4./2./h
    sm[j*N,j*N+2] = sm[j*N,j*N-3] = -1./2./h

for j in arange(p):
    sm[j*N-1,j*N] = 1.
    sm[j*N-1,j*N-1] = -1.
t3 = time.clock()
#smsp= sp.csr_matrix(sm)
t4 = time.clock()
print "NNZ: ", sm.nnz


#fhsol = solve(sm,rhs)
fhsol, info = la.bicgstab(sm,rhs,tol=1e-6, maxiter=10000)
t5 = time.clock()
print "Info: ", info

tauall = t5 - t1
print "mesh:  ", t2-t1, "s -> ", 100.*(t2-t1)/tauall, "%"
print "assem: ", t3-t2, "s -> ", 100.*(t3-t2)/tauall, "%"
print "conv:  ", t4-t3, "s -> ", 100.*(t4-t3)/tauall, "%"
print "solve: ", t5-t4, "s -> ", 100.*(t5-t4)/tauall, "%"

fh = f(xh)
plot(xh, fh, label="exact")
plot(xh, fhsol, label="solution")

legend()
#show()
Exemple #55
0
A = generateA(Nx, Ny, dx, dy)
p = numpy.zeros(Nx * Ny)
f = RHS(X, Y, n)
p_ext = p_extSoln(X, Y, n)

print("A:\n", A.toarray(), "\n")
if args.precd == True:
    M = generateDiaPrec(A)
    print("M:\n", M.toarray(), "\n")
print("p0:\n", p, "\n")
print("f:\n", f ,"\n")
print("Factor:\n", f/p_ext ,"\n")

bg = time.clock()
if args.precd == True:
    p, info = linalg.bicgstab(A, f, p, tol=args.tol, M=M)
else:
    p, info = linalg.bicgstab(A, f, p, tol=args.tol)
ed = time.clock()

print("p:\n", p, "\n")
print("p exact:\n", p_ext, "\n")
print(p.shape, p_ext.shape)

err = abs(p - p_ext)
L2norm = numpy.linalg.norm(err, 2)
LInfnorm = numpy.linalg.norm(err, numpy.inf)

print("err:\n", err, "\n")
print("Info: \t\t", info, "\n")
print("L2Norm:\t\t", L2norm, "\n")
Exemple #56
0
 def solve_dual_symm(self, regparam):
     self.regparam = regparam
     K1 = self.resource_pool['kmatrix1']
     K2 = self.resource_pool['kmatrix2']
     #X1 = self.resource_pool['xmatrix1']
     #X2 = self.resource_pool['xmatrix2']
     #self.X1, self.X2 = X1, X2
     #x1tsize, x1fsize = X1.shape #m, d
     #x2tsize, x2fsize = X2.shape #q, r
     if 'maxiter' in self.resource_pool: maxiter = int(self.resource_pool['maxiter'])
     else: maxiter = 1000
     if 'inneriter' in self.resource_pool: inneriter = int(self.resource_pool['inneriter'])
     else: inneriter = 50
     lsize = len(self.label_row_inds) #n
     
     label_row_inds = np.array(self.label_row_inds, dtype = np.int32)
     label_col_inds = np.array(self.label_col_inds, dtype = np.int32)
     
     Y = self.Y
     rowind = label_row_inds
     colind = label_col_inds
     lamb = self.regparam
     rowind = np.array(rowind, dtype = np.int32)
     colind = np.array(colind, dtype = np.int32)
     ddim = len(rowind)
     #a = np.zeros(ddim)
     a = np.random.random(ddim)
     def func(a):
         #REPLACE
         P =  sparse_kronecker_multiplication_tools_python.x_gets_C_times_M_kron_N_times_B_times_v(a, K2, K1, rowind, colind, rowind, colind)
         z = (1. - Y*P)
         z = np.where(z>0, z, 0)
         Ka = sparse_kronecker_multiplication_tools_python.x_gets_C_times_M_kron_N_times_B_times_v(a, K2, K1, rowind, colind, rowind, colind)
         return 0.5*(np.dot(z,z)+lamb*np.dot(a, Ka))
     def gradient(a):
         P =  sparse_kronecker_multiplication_tools_python.x_gets_C_times_M_kron_N_times_B_times_v(a, K2, K1, rowind, colind, rowind, colind)
         z = (1. - Y*P)
         z = np.where(z>0, z, 0)
         sv = np.nonzero(z)[0]
         v = P[sv]-Y[sv]
         #v_after = sparse_kronecker_multiplication_tools_python.x_gets_C_times_M_kron_N_times_B_times_v(v, K2, K1, rowind, colind, rowind[sv], colind[sv])
         v_after = sparse_kronecker_multiplication_tools_python.x_gets_C_times_M_kron_N_times_B_times_v(v, K2, K1, rowind, colind, rowind[sv], colind[sv])
         Ka = sparse_kronecker_multiplication_tools_python.x_gets_C_times_M_kron_N_times_B_times_v(a, K2, K1, rowind, colind, rowind, colind)
         return v_after + lamb*Ka
     def hessian(u):
         P =  sparse_kronecker_multiplication_tools_python.x_gets_C_times_M_kron_N_times_B_times_v(a, K2, K1, rowind, colind, rowind, colind)            
         z = (1. - Y*P)
         z = np.where(z>0, z, 0)
         sv = np.nonzero(z)[0]
         v = sparse_kronecker_multiplication_tools_python.x_gets_C_times_M_kron_N_times_B_times_v(u, K2, K1, rowind[sv], colind[sv], rowind, colind)
         v_after = sparse_kronecker_multiplication_tools_python.x_gets_C_times_M_kron_N_times_B_times_v(v, K2, K1, rowind, colind, rowind[sv], colind[sv])
         return v_after + lamb * sparse_kronecker_multiplication_tools_python.x_gets_C_times_M_kron_N_times_B_times_v(u, K2, K1, rowind, colind, rowind[sv], colind[sv])
     def mv(v):
         return hessian(v)
     ssize = 1.0
     print "Kronecker SVM"
     for i in range(100):
         g = gradient(a)
         A = LinearOperator((ddim, ddim), matvec=mv, dtype=np.float64)
         a_new = bicgstab(A, g, maxiter=inneriter)[0]
         #a_new = lsqr(A, g)[0]
         obj = func(a)
         a = a - a_new
         self.a = a
         self.dual_model = KernelPairwiseModel(a, rowind, colind)
         #w = sparse_kronecker_multiplication_tools_python.x_gets_A_kron_B_times_sparse_v(a, X1.T, X2, rowind, colind)
         #P2 = sparse_kronecker_multiplication_tools_python.x_gets_subset_of_A_kron_B_times_v(self.W.ravel(), X2, X1.T, colind, rowind)
         #z2 = (1. - Y*P)
         #z2 = np.where(z2>0, z2, 0)
         #print np.dot(z2,z2)
         #self.W = w.reshape((x1fsize, x2fsize), order='F')
         #print w
         #print self.W.ravel()
         #assert False
         #p = func(a)
         #print p[-10:]
         #P2 = sparse_kronecker_multiplication_tools_python.x_gets_subset_of_A_kron_B_times_v(self.W.ravel(), X2, X1.T, colind, rowind)
         #print "predictions 2", P2
         #print "diff", P1-P2
         #z2 = (1. - Y*P)
         #z2 = np.where(z2>0, z2, 0)
         #print np.dot(z2,z2)
         self.callback()
         #print i
     #self.model = LinearPairwiseModel(self.W, X1.shape[1], X2.shape[1])
     self.dual_model = KernelPairwiseModel(a, rowind, colind)
     #z = np.where(a!=0, a, 0)
     #sv = np.nonzero(z)[0]
     #self.model = KernelPairwiseModel([sv], rowind[sv], colind[sv])
     self.finished()    
Exemple #57
0
 def solve_dual(self, regparam):
     self.regparam = regparam
     K1 = self.resource_pool['kmatrix1']
     K2 = self.resource_pool['kmatrix2']
     #X1 = self.resource_pool['xmatrix1']
     #X2 = self.resource_pool['xmatrix2']
     #self.X1, self.X2 = X1, X2
     #x1tsize, x1fsize = X1.shape #m, d
     #x2tsize, x2fsize = X2.shape #q, r
     if 'maxiter' in self.resource_pool: maxiter = int(self.resource_pool['maxiter'])
     else: maxiter = 100
     if 'inneriter' in self.resource_pool: inneriter = int(self.resource_pool['inneriter'])
     else: inneriter = 1000
     lsize = len(self.label_row_inds) #n
     
     label_row_inds = np.array(self.label_row_inds, dtype = np.int32)
     label_col_inds = np.array(self.label_col_inds, dtype = np.int32)
     
     Y = self.Y
     rowind = label_row_inds
     colind = label_col_inds
     lamb = self.regparam
     rowind = np.array(rowind, dtype = np.int32)
     colind = np.array(colind, dtype = np.int32)
     ddim = len(rowind)
     a = np.zeros(ddim)
     a_new = np.zeros(ddim)
     def func(a):
         #REPLACE
         #P = np.dot(X,v)
         P =  sparse_kronecker_multiplication_tools_python.x_gets_C_times_M_kron_N_times_B_times_v(a, K2, K1, rowind, colind, rowind, colind)
         z = (1. - Y*P)
         z = np.where(z>0, z, 0)
         Ka = sparse_kronecker_multiplication_tools_python.x_gets_C_times_M_kron_N_times_B_times_v(a, K2, K1, rowind, colind, rowind, colind)
         return 0.5*(np.dot(z,z)+lamb*np.dot(a, Ka))
     def mv(v):
         rows = rowind[sv]
         cols = colind[sv]
         p = np.zeros(len(rowind))
         A =  sparse_kronecker_multiplication_tools_python.x_gets_C_times_M_kron_N_times_B_times_v(v, K2, K1, rows, cols, rowind, colind)
         p[sv] = A
         return p + lamb * v
     def rv(v):
         rows = rowind[sv]
         cols = colind[sv]
         p = sparse_kronecker_multiplication_tools_python.x_gets_C_times_M_kron_N_times_B_times_v(v[sv], K2, K1, rowind, colind, rows, cols)
         return p + lamb * v
     ssize = 1.0
     for i in range(maxiter):
         P =  sparse_kronecker_multiplication_tools_python.x_gets_C_times_M_kron_N_times_B_times_v(a, K2, K1, rowind, colind, rowind, colind)
         z = (1. - Y*P)
         z = np.where(z>0, z, 0)
         sv = np.nonzero(z)[0]
         B = np.zeros(P.shape)
         B[sv] = P[sv]-Y[sv]
         B = B + lamb*a
         #solve Ax = B
         A = LinearOperator((ddim, ddim), matvec=mv, rmatvec=rv, dtype=np.float64)
         #a_new = lsqr(A, B, iter_lim=inneriter)[0]
         #def callback(xk):
         #    residual = np.linalg.norm(A.dot(xk)-B)
         #    print "redidual is", residual
         a_new = bicgstab(A, B, maxiter=inneriter)[0]
         #a_new = bicgstab(A, B, x0=a, tol=0.01, callback=callback)[0]
         #a_new = lsmr(A, B, maxiter=inneriter)[0]
         ssize = 1.0
         a = a - ssize*a_new
         #print "dual objective", func(a), ssize
         #print "dual objective 2", dual_objective(a, K1, K2, Y, rowind, colind, lamb)
         #print "gradient norm", np.linalg.norm(dual_gradient(a, K1, K2, Y, rowind, colind, lamb))
         self.A = a
         self.dual_model = KernelPairwiseModel(a, rowind, colind)
         self.callback()
         #w = sparse_kronecker_multiplication_tools_python.x_gets_A_kron_B_times_sparse_v(a, X1.T, X2, rowind, colind)
         #P2 = sparse_kronecker_multiplication_tools_python.x_gets_subset_of_A_kron_B_times_v(self.W.ravel(), X2, X1.T, colind, rowind)
         #z2 = (1. - Y*P)
         #z2 = np.where(z2>0, z2, 0)
         #print np.dot(z2,z2)
         #self.W = w.reshape((x1fsize, x2fsize), order='F')
         #print w
         #print self.W.ravel()
         #assert False
         #p = func(a)
         #print p[-10:]
         #P2 = sparse_kronecker_multiplication_tools_python.x_gets_subset_of_A_kron_B_times_v(self.W.ravel(), X2, X1.T, colind, rowind)
         #print "predictions 2", P2
         #print "diff", P1-P2
         #z2 = (1. - Y*P)
         #z2 = np.where(z2>0, z2, 0)
         #print np.dot(z2,z2)
         #print i
     #self.model = LinearPairwiseModel(self.W, X1.shape[1], X2.shape[1])
     self.dual_model = KernelPairwiseModel(a, rowind, colind)
     #z = np.where(a!=0, a, 0)
     #sv = np.nonzero(z)[0]
     #self.model = KernelPairwiseModel([sv], rowind[sv], colind[sv])
     self.finished()
 def solve(self, kper, kstp):
     converged = False
     print 'Solving stress period: {0:5d} time step: {1:5d}'.format(kper+1, kstp+1)
     for outer in xrange(self.outeriterations):
         #--create initial x (x0) from a copy of x
         x0 = np.copy(self.x)
         #--assemble conductance matrix
         self.__assemble()
         #--create sparse matrix for residual calculation and conductance formulation
         self.acsr = csr_matrix((self.a, self.ja, self.ia), shape=(self.neq, self.neq))
         #--save sparse matrix with conductance
         if self.newtonraphson:
             self.ccsr = self.acsr.copy()
         else:
             self.ccsr = self.acsr
         #--calculate initial residual
         #  do not attempt a solution if the initial solution is an order of
         #  magnitude less than rclose
         rmax0 = self.__calculateResidual(x0)
         #if outer == 0 and abs(rmax0) <= 0.1 * self.rclose:
         #    break
         if self.backtracking:
             l2norm0 = np.linalg.norm(self.r)
         if self.newtonraphson:
             self.__assemble(nr=True)
             self.acsr = csr_matrix((self.a, self.ja, self.ia), shape=(self.neq, self.neq))
             b = -self.r.copy()
             self.x.fill(0.0)
         else:
             b = self.rhs.copy()
         #--construct the preconditioner
         #M = self.get_preconditioner()
         M = self.get_preconditioner(fill_factor=3, drop_tol=1e-4)
         #--solve matrix
         info = 0
         if self.newtonraphson:
             self.x[:], info = bicgstab(self.acsr, b, x0=self.x, tol=self.rclose, maxiter=self.inneriterations, M=M)
         else:
             self.x[:], info = cg(self.acsr, b, x0=self.x, tol=self.rclose, maxiter=self.inneriterations, M=M)
         if info < 0:
             raise Exception('illegal input or breakdown in linear solver...')
         #--calculate updated residual
         rmax1 = self.__calculateResidual(self.x)
         #
         if self.bottomflag:
             self.adjusthead(self.x)
         #--back tracking
         if self.backtracking and rmax1 > self.rclose:
             l2norm1 = np.linalg.norm(self.r)
             if l2norm1 > 0.99 * l2norm0:
                 dx = self.x - x0
                 lv = 0.99
                 for ibk in xrange(100):
                     self.x = x0 + lv * dx
                     rt = self.__calculateResidual(self.x, reset_ccsr=True)
                     rmax1 = rt
                     l2norm = np.linalg.norm(self.r)
                     if l2norm < 0.90 * l2norm0:
                         break
                     lv *= 0.95
         #--calculate hmax
         hmax = np.abs(self.x - x0).max()
         #--calculate
         if hmax <= self.hclose and abs(rmax1) <= self.rclose:
             print ' Outer Iterations: {0}'.format(outer+1)
             converged = True
             self.__calculateQNodes(self.x)
             #print self.cellQ[4], self.cellQ[-4]
             break
     return converged