コード例 #1
0
    def build_sparse_solver(self):
		
		if self.sparse_solver == 'scipy_slu':
			print "Using scipy superlu solver..."
			luobj = ssl.splu(self.Asel.tocsc())
		elif self.sparse_solver == 'PyKLU':
			print "Using klu solver..."
			try:
				import PyKLU.klu as klu
				luobj = klu.Klu(self.Asel.tocsc())
			except StandardError, e: 
				print "Got exception: ", e
				print "Falling back on scipy superlu solver:"
				luobj = ssl.splu(self.Asel.tocsc())
コード例 #2
0
    def build_sparse_solver(self):

        if self.sparse_solver == 'scipy_slu':
            print("Using scipy superlu solver...")
            luobj = ssl.splu(self.Asel.tocsc())
        elif self.sparse_solver == 'PyKLU':
            print("Using klu solver...")
            try:
                import PyKLU.klu as klu
                luobj = klu.Klu(self.Asel.tocsc())
            except Exception as e:
                print("Got exception: ", e)
                print("Falling back on scipy superlu solver:")
                luobj = ssl.splu(self.Asel.tocsc())
        else:
            raise ValueError(
                'Solver not recognized!!!!\nsparse_solver must be "scipy_slu" or "PyKLU"\n'
            )

        self.luobj = luobj
コード例 #3
0
    def __init__(self,
                 mesh,
                 context,
                 laplacian_stencil=laplacian_3D_7stencil,
                 symmetrize=True):
        '''Assumes that the mesh can accommodate all particles
        on its nodes. Dirichlet boundaries will overwrite all boundary
        nodes for the charge density rho with 0!
        '''
        self.symmetrize = symmetrize
        self.mesh = mesh
        self._context = context
        self._cusolver_handle = curf.cusolverRfCreate()

        self.mesh_inner = gpuarray.to_gpu(~mesh.boundary_nodes())

        lapl_data, lapl_rows, lapl_cols = self.assemble_laplacian(
            mesh, laplacian_stencil)
        A = sps.coo_matrix((lapl_data, (lapl_rows, lapl_cols)),
                           shape=(mesh.n_nodes, mesh.n_nodes),
                           dtype=np.float64).tocsc()
        if symmetrize:
            """Remove all trivial equations (rows of the matrix where the
            only non-zero element is a 1 on the diagonal. This symmetrizes
            the matrix"""
            N_full = A.shape[0]
            diagonal = A.diagonal()
            indices_non_boundary = np.where(diagonal != 1.)[0]
            N_sel = len(indices_non_boundary)
            Msel = sps.lil_matrix((N_full, N_sel))
            for ii, ind in enumerate(indices_non_boundary):
                Msel[ind, ii] = 1.
            Msel = Msel.tocsc()
            A = (Msel.T * A * Msel).tocsc()
            self.Msel = Msel
            self.MselT = Msel.T
        self.lu_obj = klu.Klu(A.tocsc())
コード例 #4
0
    def __init__(self, chamb, Dh, sparse_solver = 'scipy_slu', remove_external_nodes_from_mat=True, include_solver = True):
        
        print('Start PIC init.:')
        print('Finite Differences, Square Grid')


        self.Dh = Dh
        if hasattr(chamb, 'x_min') and hasattr(chamb, 'x_max') and hasattr(chamb, 'y_min') and hasattr(chamb, 'y_max'):
            super(FiniteDifferences_Staircase_SquareGrid, self).__init__(dx = self.Dh, dy = self.Dh, 
                x_min = chamb.x_min, x_max = chamb.x_max, y_min = chamb.y_min, y_max = chamb.y_max)
        else:
            super(FiniteDifferences_Staircase_SquareGrid, self).__init__(chamb.x_aper, chamb.y_aper, self.Dh, self.Dh)

        Nyg, Nxg = self.Nyg, self.Nxg
        
        
        [xn, yn]=np.meshgrid(self.xg,self.yg)

        xn=xn.T
        xn=xn.flatten()

        yn=yn.T
        yn=yn.flatten()
        #% xn and yn are stored such that the external index is on x 

        flag_outside_n=chamb.is_outside(xn,yn)
        flag_inside_n=~(flag_outside_n)


        flag_outside_n_mat=np.reshape(flag_outside_n,(Nyg,Nxg),'F');
        flag_outside_n_mat=flag_outside_n_mat.T
        [gx,gy]=np.gradient(np.double(flag_outside_n_mat));
        gradmod=abs(gx)+abs(gy);
        flag_border_mat=np.logical_and((gradmod>0), flag_outside_n_mat);
        flag_border_n = flag_border_mat.flatten()
        
        
        if include_solver:
            A=scsp.lil_matrix((Nxg*Nyg,Nxg*Nyg)); #allocate a sparse matrix

            list_internal_force_zero = []

            # Build A matrix
            for u in range(0,Nxg*Nyg):
                if np.mod(u, Nxg*Nyg//20)==0:
                    print(('Mat. assembly %.0f'%(float(u)/ float(Nxg*Nyg)*100)+"""%"""))
                if flag_inside_n[u]:
                    A[u,u] = -(4./(Dh*Dh))
                    A[u,u-1]=1./(Dh*Dh);     #phi(i-1,j)nx
                    A[u,u+1]=1./(Dh*Dh);     #phi(i+1,j)
                    A[u,u-Nyg]=1./(Dh*Dh);    #phi(i,j-1)
                    A[u,u+Nyg]=1./(Dh*Dh);    #phi(i,j+1)
                else:
                    # external nodes
                    A[u,u]=1.
                    
            A=A.tocsr() #convert to csr format
            
            #Remove trivial equtions 
            if remove_external_nodes_from_mat:
                diagonal = A.diagonal()
                N_full = len(diagonal)
                indices_non_id = np.where(diagonal!=1.)[0]
                N_sel = len(indices_non_id)
                Msel = scsp.lil_matrix((N_full, N_sel))
                for ii, ind in enumerate(indices_non_id):
                    Msel[ind, ii] =1.
            else:
                diagonal = A.diagonal()
                N_full = len(diagonal)
                Msel = scsp.lil_matrix((N_full, N_full))
                for ii in range(N_full):
                    Msel[ii, ii] =1.
            Msel = Msel.tocsc()
            Asel = Msel.T*A*Msel
            Asel=Asel.tocsc() 
            

            if sparse_solver == 'scipy_slu':
                print("Using scipy superlu solver...")
                luobj = ssl.splu(Asel.tocsc())
            elif sparse_solver == 'PyKLU':
                print("Using klu solver...")
                try:
                    import PyKLU.klu as klu
                    luobj = klu.Klu(Asel.tocsc())
                except Exception as e: 
                    print("Got exception: ", e)
                    print("Falling back on scipy superlu solver:")
                    luobj = ssl.splu(Asel.tocsc())
            else:
                raise ValueError('Solver not recognized!!!!\nsparse_solver must be "scipy_slu" or "PyKLU"\n')
                
            self.xn = xn
            self.yn = yn
            
            self.flag_inside_n = flag_inside_n
            self.flag_outside_n = flag_outside_n
            self.flag_outside_n_mat = flag_outside_n_mat
            self.flag_inside_n_mat = np.logical_not(flag_outside_n_mat)
            self.flag_border_mat = flag_border_mat
            self.Asel = Asel
            self.luobj = luobj
            self.U_sc_eV_stp=0.;
            self.sparse_solver = sparse_solver
            self.Msel = Msel.tocsc()
            self.Msel_T = (Msel.T).tocsc()
            self.flag_border_n = flag_border_n
            
            print('Done PIC init.')
            
        else:
            self.solve = self._solve_for_states          


        self.rho = np.zeros((self.Nxg,self.Nyg));
        self.phi = np.zeros((self.Nxg,self.Nyg));
        self.efx = np.zeros((self.Nxg,self.Nyg));
        self.efy = np.zeros((self.Nxg,self.Nyg));
        self.chamb = chamb
コード例 #5
0
    def __init__(self,chamb, Dh, sparse_solver = 'scipy_slu'):
        
		print 'Start PIC init.:'
		print 'Finite Differences, Square Grid'


		super(FiniteDifferences_Staircase_SquareGrid, self).__init__(chamb.x_aper, chamb.y_aper, Dh)
		Nyg, Nxg = self.Nyg, self.Nxg
		
		
		[xn, yn]=np.meshgrid(self.xg,self.yg)

		xn=xn.T
		xn=xn.flatten()

		yn=yn.T
		yn=yn.flatten()
		#% xn and yn are stored such that the external index is on x 

		flag_outside_n=chamb.is_outside(xn,yn)
		flag_inside_n=~(flag_outside_n)


		flag_outside_n_mat=np.reshape(flag_outside_n,(Nyg,Nxg),'F');
		flag_outside_n_mat=flag_outside_n_mat.T
		[gx,gy]=np.gradient(np.double(flag_outside_n_mat));
		gradmod=abs(gx)+abs(gy);
		flag_border_mat=np.logical_and((gradmod>0), flag_outside_n_mat);
		flag_border_n = flag_border_mat.flatten()

		A=scsp.lil_matrix((Nxg*Nyg,Nxg*Nyg)); #allocate a sparse matrix

		list_internal_force_zero = []

		# Build A matrix
		for u in range(0,Nxg*Nyg):
			if np.mod(u, Nxg*Nyg/20)==0:
				print ('Mat. assembly %.0f'%(float(u)/ float(Nxg*Nyg)*100)+"""%""")
			if flag_inside_n[u]:
				A[u,u] = -(4./(Dh*Dh))
				A[u,u-1]=1./(Dh*Dh);     #phi(i-1,j)nx
				A[u,u+1]=1./(Dh*Dh);     #phi(i+1,j)
				A[u,u-Nyg]=1./(Dh*Dh);    #phi(i,j-1)
				A[u,u+Nyg]=1./(Dh*Dh);    #phi(i,j+1)
			else:
				# external nodes
				A[u,u]=1.
				
		A=A.tocsr() #convert to csr format
		
		#Remove trivial equtions 
		diagonal = A.diagonal()
		N_full = len(diagonal)
		indices_non_id = np.where(diagonal!=1.)[0]
		N_sel = len(indices_non_id)

		Msel = scsp.lil_matrix((N_full, N_sel))
		for ii, ind in enumerate(indices_non_id):
			Msel[ind, ii] =1.
			
		Msel = Msel.tocsc()

		Asel = Msel.T*A*Msel
		Asel=Asel.tocsc()
		

		if sparse_solver == 'scipy_slu':
			print "Using scipy superlu solver..."
			luobj = ssl.splu(Asel.tocsc())
		elif sparse_solver == 'PyKLU':
			print "Using klu solver..."
			try:
				import PyKLU.klu as klu
				luobj = klu.Klu(Asel.tocsc())
			except StandardError, e: 
				print "Got exception: ", e
				print "Falling back on scipy superlu solver:"
				luobj = ssl.splu(Asel.tocsc())
コード例 #6
0
    def __init__(self,
                 chamb,
                 Dh,
                 sparse_solver='scipy_slu',
                 ext_boundary=False):
        # mimics the super() call in the old version
        params = compute_new_mesh_properties(chamb.x_aper,
                                             chamb.y_aper,
                                             Dh,
                                             ext_boundary=ext_boundary)
        self.Dh, self.xg, self.Nxg, self.bias_x, self.yg, self.Nyg, self.bias_y = params
        self.chamb = chamb

        [xn, yn] = np.meshgrid(self.xg, self.yg)
        xn = xn.T
        xn = xn.flatten()
        self.xn = xn

        yn = yn.T
        yn = yn.flatten()
        self.yn = yn

        #% xn and yn are stored such that the external index is on x

        self.flag_outside_n = chamb.is_outside(xn, yn)
        self.flag_inside_n = ~(self.flag_outside_n)

        flag_outside_n_mat = np.reshape(self.flag_outside_n,
                                        (self.Nyg, self.Nxg), 'F')
        flag_outside_n_mat = flag_outside_n_mat.T
        [gx, gy] = np.gradient(np.double(flag_outside_n_mat))
        gradmod = abs(gx) + abs(gy)
        self.flag_border_mat = np.logical_and((gradmod > 0),
                                              flag_outside_n_mat)
        self.flag_border_n = self.flag_border_mat.flatten()

        A = self.assemble_laplacian()

        diagonal = A.diagonal()
        N_full = len(diagonal)
        indices_non_id = np.where(diagonal != 1.)[0]
        N_sel = len(indices_non_id)

        Msel = sps.lil_matrix((N_full, N_sel))
        for ii, ind in enumerate(indices_non_id):
            Msel[ind, ii] = 1.
        Msel = Msel.tocsc()

        Asel = Msel.T * A * Msel
        Asel = Asel.tocsc()
        if sparse_solver == 'scipy_slu':
            print("Using scipy superlu solver...")
            self.luobj = spl.splu(Asel.tocsc())
        elif sparse_solver == 'PyKLU':
            print("Using klu solver...")
            try:
                import PyKLU.klu as klu
                self.luobj = klu.Klu(Asel.tocsc())
            except Exception as e:
                print(("Got exception: " + str(e)))
                print("Falling back on scipy superlu solver:")
                self.luobj = spl.splu(Asel.tocsc())
        else:
            raise ValueError(
                'Solver not recognized!!!!\nsparse_solver must be "scipy_klu" or "PyKLU"\n'
            )
        self.Msel = Msel.tocsc()
        self.Msel_T = (Msel.T).tocsc()
        print('Done PIC init.')
コード例 #7
0
    def __init__(self, chamb, Dh, sparse_solver='scipy_slu'):

        print 'Start PIC init.:'
        print 'Finite Differences, Shortley-Weller, Square Grid'
        print 'Using Shortley-Weller boundary approx.'

        super(FiniteDifferences_ShortleyWeller_SquareGrid,
              self).__init__(chamb.x_aper, chamb.y_aper, Dh)
        Nyg, Nxg = self.Nyg, self.Nxg

        [xn, yn] = np.meshgrid(self.xg, self.yg)

        xn = xn.T
        xn = xn.flatten()

        yn = yn.T
        yn = yn.flatten()
        #% xn and yn are stored such that the external index is on x

        flag_outside_n = chamb.is_outside(xn, yn)
        flag_inside_n = ~(flag_outside_n)
        #flag_inside_n=(((xn/x_aper)**2 + (yn/y_aper)**2)<1);
        #flag_outside_n= ~(flag_inside_n);

        flag_outside_n_mat = np.reshape(flag_outside_n, (Nyg, Nxg), 'F')
        flag_outside_n_mat = flag_outside_n_mat.T
        [gx, gy] = np.gradient(np.double(flag_outside_n_mat))
        gradmod = abs(gx) + abs(gy)
        flag_border_mat = np.logical_and((gradmod > 0), flag_outside_n_mat)
        flag_border_n = flag_border_mat.flatten()

        A = scsp.lil_matrix((Nxg * Nyg, Nxg * Nyg))
        #allocate a sparse matrix
        Dx = scsp.lil_matrix((Nxg * Nyg, Nxg * Nyg))
        #allocate a sparse matrix
        Dy = scsp.lil_matrix((Nxg * Nyg, Nxg * Nyg))
        #allocate a sparse matrix

        list_internal_force_zero = []

        # Build A Dx Dy matrices
        for u in range(0, Nxg * Nyg):
            if np.mod(u, Nxg * Nyg / 20) == 0:
                print(
                    'Mat. assembly %.0f' %
                    (float(u) / float(Nxg * Nyg) * 100) + """%""")
            if flag_inside_n[u]:

                #Compute Shortley-Weller coefficients
                if flag_inside_n[u - 1]:  #phi(i-1,j)
                    hw = Dh
                else:
                    x_int, y_int, z_int, Nx_int, Ny_int, i_found_int = chamb.impact_point_and_normal(
                        na(xn[u]),
                        na(yn[u]),
                        na(0.),
                        na(xn[u - 1]),
                        na(yn[u - 1]),
                        na(0.),
                        resc_fac=.995,
                        flag_robust=False)
                    hw = np.abs(y_int[0] - yn[u])

                if flag_inside_n[u + 1]:  #phi(i+1,j)
                    he = Dh
                else:
                    x_int, y_int, z_int, Nx_int, Ny_int, i_found_int = chamb.impact_point_and_normal(
                        na(xn[u]),
                        na(yn[u]),
                        na(0.),
                        na(xn[u + 1]),
                        na(yn[u + 1]),
                        na(0.),
                        resc_fac=.995,
                        flag_robust=False)
                    he = np.abs(y_int[0] - yn[u])

                if flag_inside_n[u - Nyg]:  #phi(i,j-1)
                    hs = Dh
                else:
                    x_int, y_int, z_int, Nx_int, Ny_int, i_found_int = chamb.impact_point_and_normal(
                        na(xn[u]),
                        na(yn[u]),
                        na(0.),
                        na(xn[u - Nyg]),
                        na(yn[u - Nyg]),
                        na(0.),
                        resc_fac=.995,
                        flag_robust=False)
                    hs = np.abs(x_int[0] - xn[u])
                    #~ print hs

                if flag_inside_n[u + Nyg]:  #phi(i,j+1)
                    hn = Dh
                else:
                    x_int, y_int, z_int, Nx_int, Ny_int, i_found_int = chamb.impact_point_and_normal(
                        na(xn[u]),
                        na(yn[u]),
                        na(0.),
                        na(xn[u + Nyg]),
                        na(yn[u + Nyg]),
                        na(0.),
                        resc_fac=.995,
                        flag_robust=False)
                    hn = np.abs(x_int[0] - xn[u])
                    #~ print hn

                # Build A matrix
                if hn < Dh / 100. or hs < Dh / 100. or hw < Dh / 100. or he < Dh / 100.:  # nodes very close to the bounday
                    A[u, u] = 1.
                    list_internal_force_zero.append(u)
                    #print u, xn[u], yn[u]
                else:
                    A[u, u] = -(2. / (he * hw) + 2 / (hs * hn))
                    A[u, u - 1] = 2. / (hw * (hw + he))
                    #phi(i-1,j)nx
                    A[u, u + 1] = 2. / (he * (hw + he))
                    #phi(i+1,j)
                    A[u, u - Nyg] = 2. / (hs * (hs + hn))
                    #phi(i,j-1)
                    A[u, u + Nyg] = 2. / (hn * (hs + hn))
                    #phi(i,j+1)

                # Build Dx matrix
                if hn < Dh / 100.:
                    if hs >= Dh / 100.:
                        Dx[u, u] = -1. / hs
                        Dx[u, u - Nyg] = 1. / hs
                elif hs < Dh / 100.:
                    if hn >= Dh / 100.:
                        Dx[u, u] = 1. / hn
                        Dx[u, u + Nyg] = -1. / hn
                else:
                    Dx[u, u] = (1. / (2 * hn) - 1. / (2 * hs))
                    Dx[u, u - Nyg] = 1. / (2 * hs)
                    Dx[u, u + Nyg] = -1. / (2 * hn)

                # Build Dy matrix
                if he < Dh / 100.:
                    if hw >= Dh / 100.:
                        Dy[u, u] = -1. / hw
                        Dy[u, u - 1] = 1. / hw
                elif hw < Dh / 100.:
                    if he >= Dh / 100.:
                        Dy[u, u] = 1. / he
                        Dy[u, u + 1] = -1. / (he)
                else:
                    Dy[u, u] = (1. / (2 * he) - 1. / (2 * hw))
                    Dy[u, u - 1] = 1. / (2 * hw)
                    Dy[u, u + 1] = -1. / (2 * he)

            else:
                # external nodes
                A[u, u] = 1.
                if flag_border_n[u]:
                    handle_border(u, flag_inside_n, Nxg, Nyg, xn, yn, chamb,
                                  Dh, Dx, Dy)

        for u in list_internal_force_zero:
            handle_border(u, flag_inside_n, Nxg, Nyg, xn, yn, chamb, Dh, Dx,
                          Dy)

        #~ A = A.tocsc()
        #~ Dx = Dx.tocsc()
        #~ Dy = Dy.tocsc()

        flag_force_zero = flag_outside_n.copy()
        for ind in list_internal_force_zero:
            flag_force_zero[ind] = True

        flag_force_zero_mat = np.reshape(flag_force_zero, (Nyg, Nxg), 'F')
        flag_force_zero_mat = flag_force_zero_mat.T
        [gxc, gyc] = np.gradient(np.double(flag_force_zero_mat))
        gradmodc = abs(gxc) + abs(gyc)
        flag_border_mat_c = np.logical_and((gradmodc > 0), flag_force_zero_mat)

        sumcurr = np.sum(flag_border_mat_c, axis=0)
        jj_max_border = np.max((np.where(sumcurr > 0))[0])
        jj_min_border = np.min((np.where(sumcurr > 0))[0])

        sumcurr = np.sum(
            flag_border_mat_c, axis=1
        )  # corrected in version 4.05. I it was: sumcurr = np.sum(flag_border_mat_c, axis=1)
        ii_max_border = np.max((np.where(sumcurr > 0))[0])
        ii_min_border = np.min((np.where(sumcurr > 0))[0])

        print 'Internal nodes with 0 potential'
        print list_internal_force_zero

        A = A.tocsr()  #convert to csr format

        #Remove trivial equtions
        diagonal = A.diagonal()
        N_full = len(diagonal)
        indices_non_id = np.where(diagonal != 1.)[0]
        N_sel = len(indices_non_id)

        Msel = scsp.lil_matrix((N_full, N_sel))
        for ii, ind in enumerate(indices_non_id):
            Msel[ind, ii] = 1.

        Msel = Msel.tocsc()

        Asel = Msel.T * A * Msel
        Asel = Asel.tocsc()

        if sparse_solver == 'scipy_slu':
            print "Using scipy superlu solver..."
            luobj = ssl.splu(Asel.tocsc())
        elif sparse_solver == 'PyKLU':
            print "Using klu solver..."
            try:
                import PyKLU.klu as klu
                luobj = klu.Klu(Asel.tocsc())
            except StandardError, e:
                print "Got exception: ", e
                print "Falling back on scipy superlu solver:"
                luobj = ssl.splu(Asel.tocsc())