def update(self): # Define transport and transverse directions p_dir, t_dirs = self.get_directions() # K-points in the transport direction offset_p_c = np.zeros((3, )) offset_p_c[p_dir] = self.offset_c[p_dir] bzk_p_kc = monkhorst_pack((self.Nk_c[p_dir], 1, 1)) + offset_p_c # K-points in the transverse directions offset_t_c = np.zeros((3, )) offset_t_c[:len(t_dirs)] = self.offset_c[t_dirs] bzk_t_kc = monkhorst_pack(tuple(self.Nk_c[t_dirs]) + (1, )) + offset_t_c # Time-reversal symmetry ibzk_p_kc, bzk2ibzk_p_k = symm_reduce(bzk_p_kc) ibzk_t_kc = symm_reduce(bzk_t_kc)[0] # Take dimensions self.bzk_p_k = bzk_p_kc[:, 0] # self.ibzk_t_kc = ibzk_t_kc[:, :2] self.ibzk_t_kc = bzk_t_kc[:, :2] self.bzk_t_kc = bzk_t_kc[:, :2] # Update number of cells self.set_num_cells()
def get_transport_kpts(bzk_kc, dir='x'): from ase.dft.kpoints import get_monkhorst_pack_size_and_offset, \ monkhorst_pack dir = 'xyz'.index(direction) transverse_dirs = np.delete([0, 1, 2], [dir]) dtype = float if len(bzk_kc) > 1 or np.any(bzk_kc[0] != [0, 0, 0]): dtype = complex kpts_grid, kpts_shift = get_monkhorst_pack_size_and_offset(bzk_kc) # kpts in the transport direction nkpts_p = kpts_grid[dir] bzk_p_kc = monkhorst_pack((nkpts_p, 1, 1))[:, 0] + kpts_shift[dir] weight_p_k = 1. / nkpts_p # kpts in the transverse directions offset = np.zeros((3, )) offset[:len(transverse_dirs)] = kpts_shift[transverse_dirs] bzk_t_kc = monkhorst_pack(tuple(kpts_grid[transverse_dirs]) + (1, )) + offset return (bzk_p_kc, weight_p_k), (bzk_t_kc, )
def kpts2ndarray(kpts, atoms=None): """Convert kpts keyword to 2-d ndarray of scaled k-points.""" if kpts is None: return np.zeros((1, 3)) if isinstance(kpts, dict): size, offsets = kpts2sizeandoffsets(atoms=atoms, **kpts) return monkhorst_pack(size) + offsets if isinstance(kpts[0], int): return monkhorst_pack(kpts) return np.array(kpts)
def test_things(): from ase.dft.kpoints import monkhorst_pack from ase.units import Hartree, Bohr, kJ, mol, kcal, kB, fs from ase.build import bulk assert [0, 0, 0] in monkhorst_pack((1, 3, 5)).tolist() assert [0, 0, 0] not in monkhorst_pack((1, 3, 6)).tolist() assert len(monkhorst_pack((3, 4, 6))) == 3 * 4 * 6 print(Hartree, Bohr, kJ / mol, kcal / mol, kB * 300, fs, 1 / fs) hcp = bulk('X', 'hcp', a=1) * (2, 2, 1) assert abs(hcp.get_distance(0, 3, mic=True) - 1) < 1e-12 assert abs(hcp.get_distance(0, 4, mic=True) - 1) < 1e-12 assert abs(hcp.get_distance(2, 5, mic=True) - 1) < 1e-12
def __init__(self, restart=None, ignore_bad_restart_file=False, label='dftb', atoms=None, kpts=None, **kwargs): """Construct a DFTB+ calculator. """ from ase.dft.kpoints import monkhorst_pack if 'DFTB_PREFIX' in os.environ: slako_dir = os.environ['DFTB_PREFIX'] else: slako_dir = './' self.default_parameters = dict( Hamiltonian_='DFTB', Driver_='ConjugateGradient', Driver_MaxForceComponent='1E-4', Driver_ConvergentForcesOnly='No', Driver_MaxSteps=0, Hamiltonian_SlaterKosterFiles_='Type2FileNames', Hamiltonian_SlaterKosterFiles_Prefix=slako_dir, Hamiltonian_SlaterKosterFiles_Separator='"-"', Hamiltonian_SlaterKosterFiles_Suffix='".skf"', Hamiltonian_SCC='No', Hamiltonian_Eigensolver='RelativelyRobust{}') FileIOCalculator.__init__(self, restart, ignore_bad_restart_file, label, atoms, **kwargs) self.kpts = kpts # kpoint stuff by ase if self.kpts != None: mpgrid = kpts2mp(atoms, self.kpts) mp = monkhorst_pack(mpgrid) initkey = 'Hamiltonian_KPointsAndWeights' self.parameters[initkey + '_'] = '' for i, imp in enumerate(mp): key = initkey + '_empty' + str(i) self.parameters[key] = str(mp[i]).strip('[]') + ' 1.0' #the input file written only once if restart == None: self.write_dftb_in() else: if os.path.exists(restart): os.system('cp ' + restart + ' dftb_in.hsd') if not os.path.exists('dftb_in.hsd'): raise IOError('No file "dftb_in.hsd", use restart=None') #indexes for the result file self.first_time = True self.index_energy = None self.index_force_begin = None self.index_force_end = None self.index_charge_begin = None self.index_charge_end = None
def getMPKpts(atoms, grid): """ Generate the Monkhorst-Pack k point with grid[0] \times grid[1] \times grid[2] """ from ase.dft.kpoints import monkhorst_pack reciprocal_vectors = 2*np.pi*atoms.get_reciprocal_cell() return np.dot(monkhorst_pack(grid),reciprocal_vectors)
def kpts_changed(calc, x): ''' check if kpt grid has changed. we have to take care to generate the right k-points from x if needed. if a user provides (4,4,4) we need to generate the MP grid, etc... Since i changed the MP code in set_kpts, there is some incompatibility with old jacapo calculations and their MP grids. ''' #chadi-cohen if isinstance(x, str): listofkpts = getattr(ase.dft.kpoints, x) #monkhorst-pack grid elif np.array(x).shape == (3,): from ase.dft.kpoints import monkhorst_pack N1, N2, N3 = x listofkpts = monkhorst_pack((N1, N2, N3)) #user-defined list is provided elif len(np.array(x).shape) == 2: listofkpts = np.array(x) else: raise Exception('apparent invalid setting for kpts') grid = calc.get_kpts() if grid.shape != listofkpts.shape: return True if (abs(listofkpts - grid) < 1e-6).all(): return False else: return True
def kpts_changed(calc, x): ''' check if kpt grid has changed. we have to take care to generate the right k-points from x if needed. if a user provides (4,4,4) we need to generate the MP grid, etc... Since i changed the MP code in set_kpts, there is some incompatibility with old jacapo calculations and their MP grids. ''' #chadi-cohen if isinstance(x, basestring): listofkpts = getattr(ase.dft.kpoints, x) #monkhorst-pack grid elif np.array(x).shape == (3, ): from ase.dft.kpoints import monkhorst_pack N1, N2, N3 = x listofkpts = monkhorst_pack((N1, N2, N3)) #user-defined list is provided elif len(np.array(x).shape) == 2: listofkpts = np.array(x) else: raise Exception('apparent invalid setting for kpts') grid = calc.get_kpts() if grid.shape != listofkpts.shape: return True if (abs(listofkpts - grid) < 1e-6).all(): return False else: return True
def get_kpoints( size: Tuple[int, int, int], get_uniq_kpts: bool = False) -> Tuple[int, Optional[np.ndarray]]: ''' Returns number of unique k-points for a given size of the slab Parameters ---------- size : Tuple[int, int, int] a size or repeats of the slab, e.g. >>> size = (3, 3, 1) get_uniq_kpts : bool, optional If True, return size and an ndarray of unique kpoints Otherwise False. By default False Returns ------- m_uniq_kpts : int a number of unique k-points uniq : ndarray an array with unique k-points, optional ''' kpts = monkhorst_pack(size) half_kpts = len(kpts) // 2 uniq = kpts[half_kpts:, ] m_uniq_kpts = len(uniq) return (m_uniq_kpts, uniq) if get_uniq_kpts else m_uniq_kpts
def __init__( self, tbmodel, kmesh, # [ikpt, 3] efermi, # efermi k_sym=False): """ :param tbmodel: A tight binding model :param kmesh: size of monkhorst pack. e.g [6,6,6] :param efermi: fermi energy. """ self.tbmodel = tbmodel self.R2kfactor = tbmodel.R2kfactor self.k2Rfactor = -tbmodel.R2kfactor self.efermi = efermi if kmesh is not None: self.kpts = monkhorst_pack(size=kmesh) else: self.kpts = tbmodel.get_kpts() self.nkpts = len(self.kpts) self.kweights = [1.0 / self.nkpts] * self.nkpts self.norb = tbmodel.norb self.nbasis = tbmodel.nbasis self.k_sym = k_sym self._prepare_eigen()
def test(): g=GPAWWrapper(gpw_fname='/home/hexu/projects/gpaw/bccFe/atoms_nscf.gpw') H, E, V=g.H_and_eigen(kpts=monkhorst_pack([2,2,2])) print(H.shape) print(E.shape) print(E) print(V.shape)
def __init__( self, tbmodel, kmesh, # [ikpt, 3] efermi, # efermi k_sym=False, use_cache=False, cache_path='TB2J_results/cache' ): """ :param tbmodel: A tight binding model :param kmesh: size of monkhorst pack. e.g [6,6,6] :param efermi: fermi energy. """ self.tbmodel = tbmodel self.is_orthogonal = tbmodel.is_orthogonal self.R2kfactor = tbmodel.R2kfactor self.k2Rfactor = -tbmodel.R2kfactor self.efermi = efermi self._use_cache = use_cache self.cache_path = cache_path if use_cache: self._prepare_cache() if kmesh is not None: self.kpts = monkhorst_pack(size=kmesh) else: self.kpts = tbmodel.get_kpts() self.nkpts = len(self.kpts) self.kweights = [1.0 / self.nkpts] * self.nkpts self.norb = tbmodel.norb self.nbasis = tbmodel.nbasis self.k_sym = k_sym self._prepare_eigen()
def test_find_index_k(): kpts = monkhorst_pack(size=[1, 2, 3]) q = np.array((0., 0.5, 1.0 / 3)) print(np.mod(kpts + 1e-9, 1)) print("k+q:") print(kpts + q + 1e-9) js = find_index_k(kpts, q) print(kpts[js])
def get_bz_q_points(self, first=False): """Return the q=k1-k2. q-mesh is always Gamma-centered.""" shift_c = 0.5 * ((self.N_c + 1) % 2) / self.N_c bzq_qc = monkhorst_pack(self.N_c) + shift_c if first: return to1bz(bzq_qc, self.cell_cv) else: return bzq_qc
def get_bz_q_points(self, first=False): """Return the q=k1-k2. q-mesh is always Gamma-centered.""" shift_c = 0.5 * ((self.N_c + 1) % 2) / self.N_c bzq_qc = monkhorst_pack(self.N_c) + shift_c if first: return to1bz(bzq_qc, self.symmetry.cell_cv) else: return bzq_qc
def make_builder(model, kmesh, nwann, has_phase=False, weight_func='unity', mu=0, sigma=0.01, exclude_bands=[], use_proj=False, method='projected', selected_basis=[], anchor_kpt=(0, 0, 0), anchors=None): k = kmesh[0] kpts = monkhorst_pack(kmesh) evals, evecs = model.solve_all(kpts) try: positions = model.positions except Exception: positions = None weight_func = occupation_func(ftype=weight_func, mu=mu, sigma=sigma) if method == "scdmk": wann_builder = WannierScdmkBuilder(evals=evals, wfn=evecs, positions=positions, kpts=kpts, nwann=nwann, weight_func=weight_func, has_phase=has_phase, Rgrid=kmesh, exclude_bands=exclude_bands, use_proj=use_proj) if selected_basis: wann_builder.set_selected_cols(selected_basis) elif anchors: wann_builder.set_anchors(anchors) else: wann_builder.auto_set_anchors(anchor_kpt) elif method == "projected": wann_builder = WannierProjectedBuilder( evals=evals, wfn=evecs, has_phase=has_phase, positions=positions, kpts=kpts, nwann=nwann, weight_func=weight_func, Rgrid=kmesh, exclude_bands=exclude_bands, ) if selected_basis: wann_builder.set_projectors_with_basis(selected_basis) elif anchors: wann_builder.set_projectors_with_anchors(anchors) else: raise ValueError("method should be scdmk or projected") return wann_builder
def test_Ham(): calc=GPAW('/home/hexu/projects/gpaw/bccFe/atoms_nscf.gpw', fixdensity=True, symmetry='off', txt='nscf.txt') atoms=calc.atoms atoms.calc=calc calc.set(kpts=(3,3,3)) E = atoms.get_potential_energy() tb=TightBinding(atoms, calc) kpath=monkhorst_pack([3,3,3]) evals, evecs=tb.band_structure(kpath, blochstates=True)
def __init__(self, restart=None, ignore_bad_restart_file=False, label='dftb', atoms=None, kpts=None, **kwargs): """Construct a DFTB+ calculator. """ from ase.dft.kpoints import monkhorst_pack if 'DFTB_PREFIX' in os.environ: slako_dir = os.environ['DFTB_PREFIX'] else: slako_dir = './' self.default_parameters = dict( Hamiltonian_='DFTB', Driver_='ConjugateGradient', Driver_MaxForceComponent='1E-4', Driver_ConvergentForcesOnly = 'No', Driver_MaxSteps=0, Hamiltonian_SlaterKosterFiles_='Type2FileNames', Hamiltonian_SlaterKosterFiles_Prefix=slako_dir, Hamiltonian_SlaterKosterFiles_Separator='"-"', Hamiltonian_SlaterKosterFiles_Suffix='".skf"', Hamiltonian_SCC = 'No', Hamiltonian_Eigensolver = 'RelativelyRobust{}' ) FileIOCalculator.__init__(self, restart, ignore_bad_restart_file, label, atoms, **kwargs) self.kpts = kpts # kpoint stuff by ase if self.kpts != None: mpgrid = kpts2mp(atoms, self.kpts) mp = monkhorst_pack(mpgrid) initkey = 'Hamiltonian_KPointsAndWeights' self.parameters[initkey + '_'] = '' for i, imp in enumerate(mp): key = initkey + '_empty' + str(i) self.parameters[key] = str(mp[i]).strip('[]') + ' 1.0' #the input file written only once if restart == None: self.write_dftb_in() else: if os.path.exists(restart): os.system('cp ' + restart + ' dftb_in.hsd') if not os.path.exists('dftb_in.hsd'): raise IOError('No file "dftb_in.hsd", use restart=None') #indexes for the result file self.first_time = True self.index_energy = None self.index_force_begin = None self.index_force_end = None self.index_charge_begin = None self.index_charge_end = None
def test_neighbor_k_search(): kpt_kc = monkhorst_pack((4, 4, 4)) Gdir_dc = [[1, 0, 0], [0, 1, 0], [0, 0, 1], [1, 1, 0], [1, 0, 1], [0, 1, 1]] tol = 1e-4 for d, Gdir_c in enumerate(Gdir_dc): for k, k_c in enumerate(kpt_kc): kk, k0 = neighbor_k_search(k_c, Gdir_c, kpt_kc, tol=tol) assert np.linalg.norm(kpt_kc[kk] - k_c - Gdir_c + k0) < tol
def kpts2kpts(kpts, atoms=None): if kpts is None: return KPoints() if hasattr(kpts, 'kpts'): return kpts if isinstance(kpts, dict): if 'kpts' in kpts: return KPoints(kpts['kpts']) if 'path' in kpts: cell = Cell.ascell(atoms.cell) return cell.bandpath(pbc=atoms.pbc, **kpts) size, offsets = kpts2sizeandoffsets(atoms=atoms, **kpts) return KPoints(monkhorst_pack(size) + offsets) if isinstance(kpts[0], int): return KPoints(monkhorst_pack(kpts)) return KPoints(np.array(kpts))
def __init__(self, JR, Rlist, iM, iL, qmesh): self.JR = JR self.Rlist = Rlist self.nR = len(Rlist) self.nM = len(iM) self.nL = len(iL) self.nsite = self.nM + self.nL self.iM = iM self.iL = iL self.qmesh = qmesh self.qpts = monkhorst_pack(qmesh) self.nqpt = len(self.qpts)
def from_wannier(cls, path, prefix_up, prefix_down, kmesh=[3, 3, 3], weight_func_type='Fermi', mu=None, sigma=None, nwann=None): from banddownfolder.wrapper.myTB import MyTB k = kmesh[0] kpts = monkhorst_pack(kmesh) model_up = MyTB.read_from_wannier_dir(path, prefix_up) model_down = MyTB.read_from_wannier_dir(path, prefix_down) #evals_up, evecs_up = model_up.solve_all(kpts) #evals_down, evecs_down = model_down.solve_all(kpts) hams_up, _, evals_up, evecs_up = model_up.HS_and_eigen(kpts) hams_down, _, evals_down, evecs_down = model_down.HS_and_eigen(kpts) evals = np.array([evals_up, evals_down]) try: positions = model_up.positions except Exception: positions = None weight_func = occupation_func(ftype=weight_func_type, mu=mu, sigma=sigma) nk = len(kpts) rho = np.zeros(shape=(nk, model_up.nbasis, model_down.nbasis), dtype=complex) for ik, k in enumerate(kpts): rho[ik] = evecs_up[ik] @ np.diag(weight_func(evals_up[ ik])) @ evecs_up[ik].T.conj() - evecs_down[ik] @ np.diag( weight_func(evals_down[ik])) @ evecs_down[ik].T.conj() if nwann is None: nwann = model_up.nbasis print(f"{rho.shape=}") return SpinDensityMatricesDownfolder(evals=evals, density_matrices=rho, positions=positions, kmesh=kmesh, nwann=nwann, Hks=np.array([hams_up, hams_down]), Sk=None, has_phase=False, Rgrid=None, sort_cols=True)
def parse(self, opts, args): mp = opts.monkhorst_pack if mp is not None: if mp[-1].lower() == 'g': kpts = np.array([int(k) for k in mp[:-1].split(',')]) shift = 0.5 * ((kpts + 1) % 2) / kpts self.kpts = monkhorst_pack(kpts) + shift else: self.kpts = [int(k) for k in mp.split(',')] self.kptdensity = opts.k_point_density if opts.parameters: self.kwargs.update(str2dict(opts.parameters))
def calculate_gamma(self, vol, alpha): if self.molecule: return 0.0 N_c = self.kd.N_c offset_c = (N_c + 1) % 2 * 0.5 / N_c bzq_qc = monkhorst_pack(N_c) + offset_c qd = KPointDescriptor(bzq_qc) pd = PWDescriptor(self.wfs.pd.ecut, self.wfs.gd, kd=qd) gamma = (vol / (2 * pi)**2 * sqrt(pi / alpha) * self.kd.nbzkpts) for G2_G in pd.G2_qG: if G2_G[0] < 1e-7: G2_G = G2_G[1:] gamma -= np.dot(np.exp(-alpha * G2_G), G2_G**-1) return gamma / self.qstride_c.prod()
def _prepare(self): self.nmagatom = len(self.ind_mag_atoms) #self.qmesh=[3,3,3] self.qmesh = self.kmesh self.qpts = monkhorst_pack(size=self.qmesh) self.Rqlist = kmesh_to_R(self.qmesh) self.nqpt = len(self.qpts) self.ncontour = len(self.contour.path) self.Jqe_list = np.zeros( (self.ncontour, self.nqpt, self.nmagatom, self.nmagatom), dtype=complex) self.Kqe_list = np.zeros_like(self.Jqe_list) self.Xqe_list = np.zeros_like(self.Jqe_list) self.get_rho_atom()
def lithiumBulk(comm): d = 3.5 li = Atoms("Li2", positions=[(0, 0, 0), (0.5 * d, 0.5 * d, 0.5 * d)], cell=np.eye(3) * d) from ase.dft import kpoints kpointList = kpoints.monkhorst_pack((4, 4, 4)) kpointList += np.asarray([0.125, 0.125, 0.125]) w = 1.0 / len(kpointList) if "--gpu" in sys.argv: li.calc = ElectronicMinimizeGPU(atoms=li, log=True, kpts=[(k, w) for k in kpointList], comm=comm) else: li.calc = ElectronicMinimize(atoms=li, log=True, kpts=[(k, w) for k in kpointList], comm=comm) li.calc.dragWavefunctions = False print(li.get_potential_energy() / Hartree)
def get_dos(self, kps_size=None, saveto=None, dos_mesh=None, eta=1e-2): """ Get the density of states. Note: symmetry is not used. Parameters ---------- dos_mesh: ndarray the mesh of dos. default: numpy.linspace(Emax,Emin,500), (Emax, Emin)= (max,min) among all the eigenvalues kps_size: tuple the size of Monkhorst_pack mesh. default: (8,8,8) saveto: string name of the file to save data. eta: float broadening factor. current only Gaussian braodening available, default: 1e-2 Returns ------- dos: density of states Examples:: >>># dos of 2D square lattice >>>aTB=TB.gallery() >>>aTB.get_dos(kps_size=(400,400,1)) """ if kps_size is None: kps_size = (8, 8, 8) kps = kpoints.monkhorst_pack(kps_size) eks = [self.eigens(i, kpt)[0] for i, kpt in enumerate(kps)] if dos_mesh is None: dos_mesh = numpy.linspace(eks.min(), eks.max(), 500) if saveto is None: filename = "dos.dat" else: filename = saveto dos = numpy.zeros(len(dos_mesh), dtype=numpy.float) for ek in numpy.nditer(eks): dos += numpy.exp(-(ek - dos_mesh)**2 / 2.0 / eta**2) dos *= 1.0 / numpy.sqrt(2 * numpy.pi) / eta dos /= len(kps) with open(filename, "w") as f: for idx in xrange(len(dos_mesh)): f.write("%f %f \n" % (dos_mesh[idx], dos[idx]))
def calculate_Kc_q(self, bcell_cv, N_k, q_qc=None, Gvec_c=None, N=100): if q_qc is None: q_qc = np.array([[1.e-12, 0., 0.]]) if Gvec_c is None: Gvec_c = np.array([0, 0, 0]) bcell = bcell_cv.copy() bcell[0] /= N_k[0] bcell[1] /= N_k[1] bcell[2] /= N_k[2] bvol = np.abs(np.linalg.det(bcell)) gamma = np.where(np.sum(abs(q_qc), axis=1) < 1e-5)[0][0] if (Gvec_c == 0).all(): q_qc = q_qc.copy() # Just to avoid zero division q_qc[gamma] = [0.001, 0., 0.] q_qc[:, 0] += Gvec_c[0] q_qc[:, 1] += Gvec_c[1] q_qc[:, 2] += Gvec_c[2] qG = np.dot(q_qc, bcell_cv) K0_q = self.v_Coulomb(qG) if (Gvec_c == 0).all(): R_q0 = (3. * bvol / (4. * np.pi))**(1. / 3.) K0_q[gamma] = 4. * np.pi * R_q0 / bvol bvol = np.abs(np.linalg.det(bcell)) # Integrated Coulomb kernel qt_qc = monkhorst_pack((N, N, N)) qt_qcv = np.dot(qt_qc, bcell) dv = bvol / len(qt_qcv) K_q = np.zeros(len(q_qc), complex) for i in range(len(q_qc)): q = qt_qcv.copy() + qG[i] v_q = v3D_Coulomb(q) K_q[i] = np.sum(v_q) * dv / bvol return 4. * np.pi * K_q, 4. * np.pi * K0_q
def test_dos(): """Check density of states tetrahedron code.""" import numpy as np from ase.dft.dos import linear_tetrahedron_integration as lti from ase.dft.kpoints import monkhorst_pack cell = np.eye(3) shape = (11, 13, 9) kpts = np.dot(monkhorst_pack(shape), np.linalg.inv(cell).T).reshape(shape + (3, )) # Free electron eigenvalues: eigs = 0.5 * (kpts**2).sum(3)[..., np.newaxis] # new axis for 1 band energies = np.linspace(0.0001, eigs.max() + 0.0001, 500) # Do 3-d, 2-d and 1-d: dos3 = lti(cell, eigs, energies) eigs = eigs[:, :, 4:5] dos2 = lti(cell, eigs, energies) eigs = eigs[5:6] dos1 = lti(cell, eigs, energies) # With weights: dos1w = lti(cell, eigs, energies, np.ones_like(eigs)) assert abs(dos1 - dos1w).max() < 2e-14 # Analytic results: ref3 = 4 * np.pi * (2 * energies)**0.5 ref2 = 2 * np.pi * np.ones_like(energies) ref1 = 2 * (2 * energies)**-0.5 mask = np.bitwise_and(energies > 0.02, energies < 0.1) dims = 1 for dos, ref in [(dos1, ref1), (dos2, ref2), (dos3, ref3)]: error = abs(1 - dos / ref)[mask].max() norm = dos.sum() * (energies[1] - energies[0]) print(dims, norm, error) assert error < 0.2, error assert abs(norm - 1) < 0.11**dims, norm if 0: import matplotlib.pyplot as plt plt.plot(energies, dos) plt.plot(energies, ref) plt.show() dims += 1
def __init__(self, evals, density_matrices, positions, kmesh, nwann, Hks, Sk=None, has_phase=True, Rgrid=None, sort_cols=True, atoms=None): self.nspin = 2 self.dm = density_matrices self.positions = positions self.kmesh = kmesh self.kpts = monkhorst_pack(kmesh) self.nkpt = len(self.kpts) self.kweight = [1.0 / self.nkpt] * self.nkpt self.nwann = nwann self.nbasis = self.dm.shape[-1] self.nband = self.nbasis self.Hks = Hks self.Sk = Sk self.Rgrid = Rgrid self.spin_dm = self.dm self.cols = None self.sort_cols = sort_cols self.Rgrid = Rgrid self._prepare_Rlist() self.nR = self.Rlist.shape[0] self.Amn = np.zeros((self.nkpt, self.nband, self.nwann), dtype=complex) self.wannk = np.zeros((self.nkpt, self.nbasis, self.nwann), dtype=complex) self.Hwann_k = np.zeros( (self.nspin, self.nkpt, self.nwann, self.nwann), dtype=complex) self.HwannR = np.zeros((self.nspin, self.nR, self.nwann, self.nwann), dtype=complex) self.wannR = np.zeros((self.nR, self.nbasis, self.nwann), dtype=complex) self.atoms = atoms
def write_Jq(self, kmesh, path,**kwargs): from TB2J.spinham.spin_api import SpinModel from TB2J.io_exchange.io_txt import write_Jq_info m = SpinModel(fname=os.path.join(path, 'Multibinit', 'exchange.xml')) m.set_ham(**kwargs) kpts1 = monkhorst_pack(kmesh) bp = Cell(self.atoms.cell).bandpath(npoints=400) kpts2 = bp.kpts kpts = np.vstack([kpts1, kpts2]) evals, evecs = m.ham.solve_k(kpts, Jq=True) with open(os.path.join(path, 'summary.txt'), 'w') as myfile: myfile.write("=" * 60) myfile.write("\n") myfile.write("Generated by TB2J %s.\n" % (__version__)) myfile.write("=" * 60 + '\n') myfile.write( "The spin ground state is estimated by calculating\n the eigenvalues and eigen vectors of J(q):\n" ) write_Jq_info(self, kpts, evals, evecs, myfile, special_kpoints={})
def get_dos(self, kps_size=None, saveto=None, dos_mesh=None, eta=1e-2): """ get the density of states. Note: symmetry is not used Args: dos_mesh: (optional),the mesh of dos, numpy.array. default: numpy.linspace(Emax,Emin,500), (Emax, Emin)= (max,min) of all the eigenvalues kps_size: (optional),the size of Monkhorst_pack mesh, tuple. default: (8,8,8) saveto: (optional), data is saved to a file. eta : broadening, current only Gaussian braodening available, default: 1e-2 Returns: dos: density of states Examples: ## dos of 2D square lattice aTB=TB.gallery() aTB.get_dos(kps_size=(400,400,1)) """ if kps_size is None: kps_size = (8, 8, 8) kps = kpoints.monkhorst_pack(kps_size) eks, = self.eigens(kps) if dos_mesh is None: dos_mesh = numpy.linspace(eks.min(), eks.max(), 500) if saveto is None: filename = "dos_ek.dat" else: filename = saveto dos = numpy.zeros(len(dos_mesh), dtype=numpy.float) for ek in numpy.nditer(eks): dos += numpy.exp(-(ek - dos_mesh) ** 2 / 2.0 / eta ** 2) dos *= 1.0 / numpy.sqrt(2 * numpy.pi) / eta dos /= len(kps) with open(filename, "w") as f: for idx in xrange(len(dos_mesh)): f.write("%f %f \n" % (dos_mesh[idx], dos[idx]))
def calc_chi0_list(model, qlist, omega=0.0, kmesh=None, supercell_matrix=None): if kmesh is not None: k_list = monkhorst_pack(kmesh) else: k_list = model._kpts evals, evecs = model.solve_all(eig_vectors=True, k_list=k_list, convention=1, zeeman=False) if supercell_matrix is not None: weight = model.unfold(k_list, sc_matrix=supercell_matrix, evals=evals, evecs=evecs) k_list = [np.dot(k, supercell_matrix) for k in k_list] qlist = [np.dot(q, supercell_matrix) for q in qlist] else: weight = None occ = Occupations(model._nel, model._width, model._kweights, nspin=model._actual_nspin) occupations = occ.occupy(evals) ret = [] for iq, q in enumerate(qlist): jkpts = find_index_k(k_list, q) chi_q = calc_chi0(evals, evecs, k_list, jkpts, occupations, q, omega=omega, weight=weight) ret.append(chi_q) return np.array(ret)
def lithiumBulk(comm): d = 3.5 li = Atoms('Li2', positions=[(0, 0, 0), (0.5 * d, 0.5 * d, 0.5 * d)], cell=np.eye(3) * d) from ase.dft import kpoints kpointList = kpoints.monkhorst_pack((4, 4, 4)) kpointList += np.asarray([.125, .125, .125]) w = 1.0 / len(kpointList) if "--gpu" in sys.argv: li.calc = ElectronicMinimizeGPU(atoms=li, log=True, kpts=[(k, w) for k in kpointList], comm=comm) else: li.calc = ElectronicMinimize(atoms=li, log=True, kpts=[(k, w) for k in kpointList], comm=comm) li.calc.dragWavefunctions = False print(li.get_potential_energy() / Hartree)
def get_ifc(self, kmesh, eval_modify_function=None, assure_ASR=False): kpts = monkhorst_pack(kmesh) nk=len(kpts) Rpts = kmesh_to_R(kmesh) natoms = len(self.atoms) HR = np.zeros((len(Rpts), natoms * 3, natoms * 3), dtype=complex) for k in kpts: Hk = self.phonon.get_dynamical_matrix_at_q(k) Hk *= np.exp(-2.0j * np.pi * np.einsum('ijk, k->ij', self.dr, k)) Hk *= self.Mmat if eval_modify_function is not None: evals, evecs =eigh(Hk) sumne=np.sum(evals[evals<0]) if sumne<-1e-18: print(k, sumne) evals = eval_modify_function(evals) Hk= evecs.conj()@np.diag(evals)@evecs.T for iR, R in enumerate(Rpts): HR[iR] += (Hk * np.exp(2.0j * np.pi * np.dot(R, k)))/nk if assure_ASR: HR.imag=0.0 HR[np.abs(HR)<0.001]=0.0 HR=self.assure_ASR(HR, Rpts) return Rpts, HR
from ase import * from ase.lattice import bulk from ase.dft.kpoints import monkhorst_pack from gpaw import * from gpaw.mpi import serial_comm from gpaw.test import equal from gpaw.xc.rpa import RPACorrelation import numpy as np a0 = 5.43 cell = bulk('Si', 'fcc', a=a0).get_cell() Si = Atoms('Si2', cell=cell, pbc=True, scaled_positions=((0,0,0), (0.25,0.25,0.25))) kpts = monkhorst_pack((2,2,2)) kpts += np.array([1/4., 1/4., 1/4.]) calc = GPAW(mode='pw', kpts=kpts, occupations=FermiDirac(0.001), communicator=serial_comm) Si.set_calculator(calc) E = Si.get_potential_energy() calc.diagonalize_full_hamiltonian(nbands=50) ecut = 50 rpa = RPACorrelation(calc, qsym=False, nfrequencies=8) E_rpa_noqsym = rpa.calculate(ecut=[ecut]) rpa = RPACorrelation(calc, qsym=True, nfrequencies=8) E_rpa_qsym = rpa.calculate(ecut=[ecut])
def __init__(self, calc, filename='gw', kpts=None, bands=None, nbands=None, ppa=False, wstc=False, ecut=150.0, eta=0.1, E0=1.0 * Hartree, domega0=0.025, omega2=10.0, world=mpi.world): PairDensity.__init__(self, calc, ecut, world=world, txt=filename + '.txt') self.filename = filename ecut /= Hartree self.ppa = ppa self.wstc = wstc self.eta = eta / Hartree self.E0 = E0 / Hartree self.domega0 = domega0 / Hartree self.omega2 = omega2 / Hartree print(' ___ _ _ _ ', file=self.fd) print(' | || | | |', file=self.fd) print(' | | || | | |', file=self.fd) print(' |__ ||_____|', file=self.fd) print(' |___| ', file=self.fd) print(file=self.fd) self.kpts = select_kpts(kpts, self.calc) if bands is None: bands = [0, self.nocc2] self.bands = bands b1, b2 = bands self.shape = shape = (self.calc.wfs.nspins, len(self.kpts), b2 - b1) self.eps_sin = np.empty(shape) # KS-eigenvalues self.f_sin = np.empty(shape) # occupation numbers self.sigma_sin = np.zeros(shape) # self-energies self.dsigma_sin = np.zeros(shape) # derivatives of self-energies self.vxc_sin = None # KS XC-contributions self.exx_sin = None # exact exchange contributions self.Z_sin = None # renormalization factors if nbands is None: nbands = int(self.vol * ecut**1.5 * 2**0.5 / 3 / pi**2) self.nbands = nbands kd = self.calc.wfs.kd self.mysKn1n2 = None # my (s, K, n1, n2) indices self.distribute_k_points_and_bands(b1, b2, kd.ibz2bz_k[self.kpts]) # Find q-vectors and weights in the IBZ: assert -1 not in kd.bz2bz_ks offset_c = 0.5 * ((kd.N_c + 1) % 2) / kd.N_c bzq_qc = monkhorst_pack(kd.N_c) + offset_c self.qd = KPointDescriptor(bzq_qc) self.qd.set_symmetry(self.calc.atoms, self.calc.wfs.setups, usesymm=self.calc.input_parameters.usesymm, N_c=self.calc.wfs.gd.N_c) assert self.calc.wfs.nspins == 1
from __future__ import print_function import numpy as np from ase.units import Ha from ase.dft.kpoints import monkhorst_pack from ase.parallel import paropen from ase.lattice import bulk from gpaw import GPAW, FermiDirac from gpaw.wavefunctions.pw import PW from gpaw.mpi import size from gpaw.xc.hybridg import HybridXC from ase.io import read for nk in (4,6,8): kpts = monkhorst_pack((nk,nk,nk)) kshift = 1./(2*nk) kpts += np.array([kshift, kshift, kshift]) atoms = bulk('MgO', 'rocksalt', a = 4.212) calc = GPAW(mode=PW(600),dtype=complex, basis='dzp', xc='PBE', maxiter=300, txt='gs_%s.txt'%(nk), kpts=kpts,parallel={'band':1}, occupations=FermiDirac(0.01)) atoms.set_calculator(calc) atoms.get_potential_energy() E = calc.get_potential_energy() E_exx = E + calc.get_xc_difference(HybridXC('EXX', method='acdf')) print(nk, E, E_exx)
import numpy as np from ase.dft.kpoints import monkhorst_pack from gpaw.kpt_descriptor import KPointDescriptor, to1bz k = 70 k_kc = monkhorst_pack((k, k, 1)) kd = KPointDescriptor(k_kc + (0.5 / k, 0.5 / k, 0)) assert (kd.N_c == (k, k, 1)).all() assert abs(kd.offset_c - (0.5 / k, 0.5 / k, 0)).sum() < 1e-9 bzk_kc = np.array([[0.5, 0.5, 0], [0.50000000001, 0.5, 0], [0.49999999999, 0.5, 0], [0.55, -0.275, 0]]) cell_cv = np.array([[1, 0, 0], [-0.5, 3**0.5 / 2, 0], [0, 0, 5]]) bz1k_kc = to1bz(bzk_kc, cell_cv) error_kc = bz1k_kc - np.array([[0.5, -0.5, 0], [0.50000000001, -0.5, 0], [0.49999999999, -0.5, 0], [0.55, -0.275, 0]]) assert abs(error_kc).max() == 0.0 assert KPointDescriptor(np.zeros((1, 3)) + 1e-14).gamma
import numpy as np from ase import Atoms from ase.dft.kpoints import monkhorst_pack from gpaw import GPAW kpts = monkhorst_pack((13, 1, 1)) + [1e-5, 0, 0] calc = GPAW(h=.21, xc='PBE', kpts=kpts, nbands=12, txt='poly.txt', eigensolver='cg', convergence={'bands': 9}) CC = 1.38 CH = 1.094 a = 2.45 x = a / 2. y = np.sqrt(CC**2 - x**2) atoms = Atoms('C2H2', pbc=(True, False, False), cell=(a, 8., 6.), calculator=calc, positions=[[0, 0, 0], [x, y, 0], [x, y+CH, 0], [0, -CH, 0]]) atoms.center() atoms.get_potential_energy() calc.write('poly.gpw', mode='all')
import numpy as np from ase.lattice import bulk from ase.units import Hartree, Bohr from gpaw import GPAW, FermiDirac from ase.dft.kpoints import monkhorst_pack for kpt in (3, 4): kpts = (kpt, kpt, kpt) bzk_kc = monkhorst_pack(kpts) shift_c = [] for Nk in kpts: if Nk % 2 == 0: shift_c.append(0.5 / Nk) else: shift_c.append(0.) bzk_kc += shift_c atoms = bulk('Si', 'diamond', a=5.431) calc = GPAW(h=0.2, kpts=bzk_kc) atoms.set_calculator(calc) atoms.get_potential_energy() kd = calc.wfs.kd bzq_qc = kd.get_bz_q_points() ibzq_qc = kd.get_ibz_q_points(bzq_qc, calc.wfs.symmetry.op_scc)[0] assert np.abs(bzq_qc - kd.bzk_kc).sum() < 1e-8 assert np.abs(ibzq_qc - kd.ibzk_kc).sum() < 1e-8
## import ase module from ase.dft import kpoints import sys sys.path.append("../../../") sys.path.append("/home/ykent/WIEN_GUTZ/bin/") ## import tbBase from tbASE import * from tbGutz import * if __name__=="__main__": #Example . SquareLattice. ### a normal square lattice. default in gallery sTB=TB.gallery().add_spindegeneracy().supercell(extent=(2,2,1)) kps_size=(11,11,1) kps=kpoints.monkhorst_pack(kps_size) # unit cell ### a Gutz TB model on a square lattice. gTB=tbGutz(sTB.Atoms,sTB.Hr,interaction=["Kanamori",(0.0,)]) gTB.output_CyGutz(kps, num_electrons = 2.4) # WH_HS.INP sigma_list = []; U_list = [] norbitals = sTB.Atoms.nspinorbitals/2 for i in range(1): sig_half = (np.arange(norbitals*norbitals)+1).reshape(norbitals,norbitals) sigma_list.append(block_diag(sig_half, sig_half)) # assuming Sz conservation U_list.append(np.identity(norbitals*2, dtype = complex)) from gl_inp import set_wh_hs, set_gl_inp set_wh_hs(sigma_list, U_list)
def get_realspace_hs(h_skmm, s_kmm, bzk_kc, weight_k, R_c=(0, 0, 0), direction='x', usesymm=None): from gpaw.symmetry import Symmetry from ase.dft.kpoints import get_monkhorst_pack_size_and_offset, \ monkhorst_pack if usesymm is True: raise NotImplementedError, 'Only None and False have been implemented' nspins, nk, nbf = h_skmm.shape[:3] dir = 'xyz'.index(direction) transverse_dirs = np.delete([0, 1, 2], [dir]) dtype = float if len(bzk_kc) > 1 or np.any(bzk_kc[0] != [0, 0, 0]): dtype = complex kpts_grid = get_monkhorst_pack_size_and_offset(bzk_kc)[0] # kpts in the transport direction nkpts_p = kpts_grid[dir] bzk_p_kc = monkhorst_pack((nkpts_p,1,1))[:, 0] weight_p_k = 1. / nkpts_p # kpts in the transverse directions bzk_t_kc = monkhorst_pack(tuple(kpts_grid[transverse_dirs]) + (1, )) if usesymm == False: #XXX a somewhat ugly hack: # By default GPAW reduces inversion sym in the z direction. The steps # below assure reduction in the transverse dirs. # For now this part seems to do the job, but it may be written # in a smarter way in the future. symmetry = Symmetry([1], np.eye(3)) symmetry.prune_symmetries(np.zeros((1, 3))) ibzk_kc, ibzweight_k = symmetry.reduce(bzk_kc)[:2] ibzk_t_kc, weights_t_k = symmetry.reduce(bzk_t_kc)[:2] ibzk_t_kc = ibzk_t_kc[:, :2] nkpts_t = len(ibzk_t_kc) else: # usesymm = None ibzk_kc = bzk_kc.copy() ibzk_t_kc = bzk_t_kc nkpts_t = len(bzk_t_kc) weights_t_k = [1. / nkpts_t for k in range(nkpts_t)] h_skii = np.zeros((nspins, nkpts_t, nbf, nbf), dtype) if s_kmm is not None: s_kii = np.zeros((nkpts_t, nbf, nbf), dtype) tol = 7 for j, k_t in enumerate(ibzk_t_kc): for k_p in bzk_p_kc: k = np.zeros((3,)) k[dir] = k_p k[transverse_dirs] = k_t kpoint_list = [list(np.round(k_kc, tol)) for k_kc in ibzk_kc] if list(np.round(k, tol)) not in kpoint_list: k = -k # inversion index = kpoint_list.index(list(np.round(k,tol))) h = h_skmm[:, index].conjugate() if s_kmm is not None: s = s_kmm[index].conjugate() k=-k else: # kpoint in the ibz index = kpoint_list.index(list(np.round(k, tol))) h = h_skmm[:, index] if s_kmm is not None: s = s_kmm[index] c_k = np.exp(2.j * np.pi * np.dot(k, R_c)) * weight_p_k h_skii[:, j] += c_k * h if s_kmm is not None: s_kii[j] += c_k * s if s_kmm is None: return ibzk_t_kc, weights_t_k, h_skii else: return ibzk_t_kc, weights_t_k, h_skii, s_kii
from ase import * from ase.lattice import bulk from ase.dft.kpoints import monkhorst_pack from gpaw import * from gpaw.mpi import serial_comm, world from gpaw.test import equal from gpaw.xc.rpa_correlation_energy import RPACorrelation from gpaw.xc.fxc_correlation_energy import FXCCorrelation import numpy as np a0 = 5.43 Ni = bulk('Ni', 'fcc') Ni.set_initial_magnetic_moments([0.7]) kpts = monkhorst_pack((3,3,3)) calc = GPAW(mode='pw', kpts=kpts, occupations=FermiDirac(0.001), setups={'Ni': '10'}, communicator=serial_comm) Ni.set_calculator(calc) E = Ni.get_potential_energy() calc.diagonalize_full_hamiltonian(nbands=50) rpa = RPACorrelation(calc) E_rpa = rpa.get_rpa_correlation_energy(ecut=50, skip_gamma=True, gauss_legendre=8) fxc = FXCCorrelation(calc, xc='RPA')
def _ase_kgrid(self, k_old, b_old, kmesh): if not ase_found: qtk.exit('ase not found') k = asekpt.monkhorst_pack(kmesh) k_min_ind = np.argmin(np.linalg.norm(k, axis=1)) k_min = k[k_min_ind] k_shifted = k - k_min k_min_old_ind = np.argmin(np.linalg.norm(k_old, axis=1)) k_min_old = k_old[k_min_old_ind] kpoints = k_old - k_min_old new_kpoints = k_shifted + k_min_old k_x = kpoints[:, 0] k_y = kpoints[:, 1] k_z = kpoints[:, 2] zeros = np.zeros(len(k_x)) ind_key_base = range(len(k_x)) k_tmp = [] k_tmp.append(np.stack([ k_x, k_y, k_z]).T) k_tmp.append(np.stack([ k_x, k_y, -k_z]).T) k_tmp.append(np.stack([ k_x, -k_y, k_z]).T) k_tmp.append(np.stack([ k_x, -k_y, -k_z]).T) k_tmp.append(np.stack([-k_x, k_y, k_z]).T) k_tmp.append(np.stack([-k_x, k_y, -k_z]).T) k_tmp.append(np.stack([-k_x, -k_y, k_z]).T) k_tmp.append(np.stack([-k_x, -k_y, -k_z]).T) ind_key_tmp = np.concatenate([ind_key_base for _ in k_tmp]) ind_key = ind_key_tmp ind_key_base = ind_key.copy() k_dup = np.concatenate(k_tmp) k_x = k_dup[:,0] k_y = k_dup[:,1] k_z = k_dup[:,2] k_tmp = [] k_tmp.append(np.stack([k_x, k_y, k_z]).T) k_tmp.append(np.stack([k_z, k_x, k_y]).T) k_tmp.append(np.stack([k_y, k_z, k_x]).T) k_tmp.append(np.stack([k_z, k_y, k_x]).T) k_tmp.append(np.stack([k_x, k_z, k_y]).T) k_tmp.append(np.stack([k_y, k_x, k_z]).T) ind_key_tmp = np.concatenate([ind_key_base for _ in k_tmp]) ind_key = np.concatenate([ind_key, ind_key_tmp]) ind_key_base = ind_key.copy() k_tmp = np.concatenate(k_tmp) k_dup = np.vstack([k_dup, k_tmp]) new_band = np.zeros([len(new_kpoints), len(self.band[0])]) for i in range(len(k_dup)): k = k_dup[i] b = b_old[i] norm = np.linalg.norm(new_kpoints - k, axis=1) key = np.where(norm < 1E-3)[0][0] new_band[key] = b return new_kpoints, new_band
from ase.dft.kpoints import monkhorst_pack assert [0, 0, 0] in monkhorst_pack((1, 3, 5)).tolist() assert [0, 0, 0] not in monkhorst_pack((1, 3, 6)).tolist() assert len(monkhorst_pack((3, 4, 6))) == 3 * 4 * 6 from ase.units import Hartree, Bohr, kJ, mol, kcal, kB, fs print(Hartree, Bohr, kJ/mol, kcal/mol, kB*300, fs, 1/fs) from ase.build import bulk hcp = bulk('X', 'hcp', a=1) * (2, 2, 1) assert abs(hcp.get_distance(0, 3, mic=True) - 1) < 1e-12 assert abs(hcp.get_distance(0, 4, mic=True) - 1) < 1e-12 assert abs(hcp.get_distance(2, 5, mic=True) - 1) < 1e-12
## set up Atom and orbitals. a=AtomsTB("N",[(0,0,0)],cell=(1,1,1)) a.set_orbitals_spindeg() ## set up tight-binding for the spin-unpolarized case. Only interlayer hopping aTB=TB(a) aTB.set_hop([((0,1,0),0,0,1), ((1,0,0),0,0,1), ((0,-1,0),0,0,1), ((-1,0,0),0,0,1)]) ## Hk: fourier transform ### ASE kpoints module could be used Nk=20 kps=kpoints.monkhorst_pack((Nk,Nk,1)) ### Hk for the Brillouin zone Hk=aTB.Hk(kps) ## nambu basis with spin, a constant term of onsite energy is ignored ### nambuTB=aTB.add_spindegeneracy().trans_Nambubasis() kps=kpoints.monkhorst_pack((Nk,Nk,1)) ### Hk for the Brillouin zone Hk_nambu=nambuTB.Hk(kps) ## Umatrix in nambu spin_names=["up","down"] orb_names=["s"] U_matrix=numpy.ones((1,1,1,1))*4.0 #mapop=set_operator_structure(spin_names,orb_names)
from ase.dft.kpoints import monkhorst_pack from ase.units import Bohr from gpaw import GPAW from gpaw.response.chi import CHI from gpaw.response.chi0 import Chi0 from gpaw.mpi import serial_comm omega = np.array([0, 1.0, 2.0]) for k in [2, 3]: q_c = [0, 0, 1.0 / k] for gamma in [False, True]: if k == 3 and gamma: continue kpts = monkhorst_pack((k, k, k)) if gamma: kpts += 0.5 / k for center in [False, True]: a = bulk('Si', 'diamond') if center: a.center() for sym in [None, True]: name = 'si.k%d.g%d.c%d.s%d' % (k, gamma, center, bool(sym)) print(name) if 1: calc = a.calc = GPAW(kpts=kpts, eigensolver='rmm-diis', usesymm=sym, mode='pw', width=0.001,
#Parameters numBands = 2 t1 = t2 = t3 = 1 Ep = 0 t = 4 a = 1.42 # C-C bond length nk = 36 # K mesh grid : 6N x 6N x 1 #Basic setting cell = np.array([[0.5*sqrt(3)*a, 1.5*a, 0],[0.5*sqrt(3)*a, -1.5*a, 0], [0,0,10]]) positions = np.array([[0,0,0],[0,-a,0]]) atoms = ase.Atoms(symbols='C2', cell=cell, positions=positions, pbc=True) recLattice = 2*pi*atoms.get_reciprocal_cell() mesh = monkhorst_pack([nk,nk,1]) + np.array([0.5/nk, 0.5/nk, 0]) #shift to Gamma kpoints = np.dot(mesh,recLattice) #For 3D surface ploting kxs = list(set(mesh[:,0]));kxs.sort() kys = list(set(mesh[:,1]));kys.sort() surfX, surfY = np.meshgrid(kxs,kys) def setupHamiltonian(kx, ky): H = np.zeros([2,2],dtype=complex) H[0,1] = np.sum([t1*exp(-0.5j*(sqrt(3)*a*kx + a*ky)), t2*exp(-0.5j*(-sqrt(3)*a*kx + a*ky)), t3*exp(-1.0j*(a*ky))]) H[1,0] = np.conj(H[0,1]) H[0,0] = Ep
from math import sqrt import numpy as np from gpaw.symmetry import Symmetry from ase.dft.kpoints import monkhorst_pack # Primitive diamond lattice, with Si lattice parameter a = 5.475 cell_cv = .5 * a * np.array([(1, 1, 0), (1, 0, 1), (0, 1, 1)]) spos_ac = np.array([(.00, .00, .00), (.25, .25, .25)]) id_a = [1, 1] # Two identical atoms pbc_c = np.ones(3, bool) bzk_kc = monkhorst_pack((4, 4, 4)) # Do check symm = Symmetry(id_a, cell_cv, pbc_c, fractrans=False) symm.analyze(spos_ac) ibzk_kc, w_k = symm.reduce(bzk_kc)[:2] assert len(symm.op_scc) == 24 assert len(w_k) == 10 a = 3 / 32.; b = 1 / 32.; c = 6 / 32. assert np.all(w_k == [a, b, a, c, c, a, a, a, a, b]) assert not symm.op_scc.sum(0).any() # Rotate unit cell and check again: cell_cv = a / sqrt(2) * np.array([(1, 0, 0), (0.5, sqrt(3) / 2, 0), (0.5, sqrt(3) / 6, sqrt(2.0 / 3))]) symm = Symmetry(id_a, cell_cv, pbc_c, fractrans=False) symm.analyze(spos_ac)
#SaveName = __file__.split('/')[-1].split('.')[0] #for save_type in ['.pdf']: # plt.savefig(SaveName+save_type,transparent=True,dpi=600) import ase.dft.kpoints as adk from ase.calculators.siesta.import_functions import xv_to_atoms from ase.visualize import view from graphene import * import pyramids.plot.PlotUtility as pu atoms = xv_to_atoms('siesta.XV') #view(atoms) reciprocal_vectors = 2*np.pi*atoms.get_reciprocal_cell() N = 24 mesh = adk.monkhorst_pack([N ,N ,1])+ np.array([0.5/N , 0.5/N , 0.0]) shiftK = np.array([1/3.0 , 2/3.0, 0.0]).dot(reciprocal_vectors) kpoints = mesh.dot(reciprocal_vectors)[:,:2]/3.0 args={'t0':10.0,'sigma': 4.0, 'omega':2.0, 'phi':0.0, 'parity':1, 'vFermi' : 6.348} args['A'] = 0.2 args['times'] = np.linspace(0.0, 20.0, 100.0) energyBandDown = [] energyBandUp = [] import os if os.path.exists('function.npy'):
def calculate_Kc_q(acell_cv, bcell_cv, pbc, N_k, vcut=None, integrated=True, q_qc=np.array([[1.e-12, 0., 0.]]), Gvec_c=np.array([0, 0, 0]), N=100): # get cutoff parameters #G_p = np.array(pbc, int) # Normal Direction #G_n = np.array([1,1,1]) - G_p if vcut is None: vcut = '3D' G_p = np.array(pbc, bool).argsort()[-int(vcut[0]):] G_n = np.array(pbc, bool).argsort()[:int(vcut[0])] if vcut is None or vcut == '3D': pass elif vcut == '2D': if pbc.all(): # G_n.sum() < 1e-8: # default dir is z G_n = np.array([2]) G_p = np.array([0, 1]) acell_n = acell_cv[G_n, G_n] R = max(acell_n) / 2. elif vcut == '1D': # R is the radius of the cylinder containing the cell. if pbc.all(): # G_n.sum() < 1e-8: raise ValueError('Check boundary condition ! ') acell_n = acell_cv R = max(acell_n[G_n[0], G_n[0]], acell_n[G_n[1], G_n[1]]) / 2. elif vcut == '0D': # R is the minimum radius of a sphere containing the cell. acell_n = acell_cv R = min(acell_n[0, 0], acell_n[1, 1], acell_n[2, 2]) / 2. else: NotImplemented bcell = bcell_cv.copy() bcell[0] /= N_k[0] bcell[1] /= N_k[1] bcell[2] /= N_k[2] bvol = np.abs(np.linalg.det(bcell)) gamma = np.where(np.sum(abs(q_qc), axis=1) < 1e-5)[0][0] if (Gvec_c[G_p] == 0).all(): q_qc[gamma][G_p[0]] = 1.e-12 # Just to avoid zero division q_qc[:, 0] += Gvec_c[0] q_qc[:, 1] += Gvec_c[1] q_qc[:, 2] += Gvec_c[2] qG = np.dot(q_qc, bcell_cv) if vcut is None or vcut == '3D': K0_q = v3D_Coulomb(qG) if (Gvec_c == 0).all(): R_q0 = (3. * bvol / (4. * np.pi))**(1. / 3.) K0_q[gamma] = 4. * np.pi * R_q0 / bvol elif vcut == '2D': K0_q = v2D_Coulomb(qG, G_p, G_n, R) if (Gvec_c == 0).all(): R_q0 = (3 * bvol / (4. * np.pi))**(1. / 3.) K0_q[gamma] = (4. * np.pi * R_q0 / bvol) elif vcut == '1D': K0_q = v1D_Coulomb(qG, G_p, G_n, R) elif vcut == '0D': K0_q = v0D_Coulomb(qG, R) else: NotImplemented bvol = np.abs(np.linalg.det(bcell)) # Integrated Coulomb kernel qt_qc = monkhorst_pack((N, N, N)) qt_qcv = np.dot(qt_qc, bcell) dv = bvol / len(qt_qcv) K_q = np.zeros(len(q_qc), complex) for i in range(len(q_qc)): q = qt_qcv.copy() + qG[i] if vcut is None or vcut == '3D': v_q = v3D_Coulomb(q) elif vcut == '2D': v_q = v2D_Coulomb(q, G_p, G_n, R) elif vcut == '1D': v_q = v1D_Coulomb(q, G_p, G_n, R) elif vcut == '0D': v_q = v0D_Coulomb(q, R) else: NotImplemented K_q[i] = np.sum(v_q) * dv / bvol return 4. * np.pi * K_q, 4. * np.pi * K0_q
0.55, 2.02, 0.56, 2.01, 1.47, 2.69, 1.46, 2.67, 1.02, 2.38, 1.02, 2.37], 'MgO': ['rocksalt', 4.189, 4.84, 7.31, 4.75, 7.24, 9.15, 11.63, 9.15, 11.67, 8.01, 10.51, 7.91, 10.38], 'NaCl': ['rocksalt', 5.569, 5.08, 7.13, 5.2, 7.26, 7.39, 9.59, 7.6, 9.66, 7.29, 9.33, 7.32, 9.41], 'Ar': ['fcc', 5.26, 8.71, 11.15, 8.68, 11.09]} nk = 12 kpts = monkhorst_pack((nk, nk, nk)) + 0.5 / nk c = ase.db.connect('gaps.db') for name in ['Si', 'C', 'GaAs', 'MgO', 'NaCl', 'Ar']: id = c.reserve(name=name) if id is None: continue x, a = bfb[name][:2] atoms = bulk(name, x, a=a) atoms.calc = GPAW(xc='PBE', mode=PW(500), parallel=dict(band=1), nbands=-8, convergence=dict(bands=-7),
from __future__ import print_function from ase import * from ase.dft.kpoints import monkhorst_pack from ase.lattice import bulk from gpaw import * from gpaw.test import equal import numpy as np from gpaw.mpi import serial_comm, size, rank, world atoms = bulk("Al", "fcc") kpts = monkhorst_pack((4, 4, 4)) kpts += np.array([1 / 8.0, 1 / 8.0, 1 / 8.0]) calc = GPAW(h=0.18, kpts=kpts, occupations=FermiDirac(0.1)) atoms.set_calculator(calc) E = atoms.get_potential_energy() calc.write("Al.gpw", "all") calc = GPAW("Al.gpw", txt=None) E = calc.get_potential_energy() from gpaw.xc.hybridk import HybridXC exx = HybridXC("EXX", acdf=True) E_k = E + calc.get_xc_difference(exx) if 0: # size == 1: calc = GPAW("Al.gpw", txt=None, communicator=serial_comm) from gpaw.xc.hybridq import HybridXC exx = HybridXC("EXX")
from __future__ import print_function import numpy as np from ase.visualize import view from ase.dft.kpoints import monkhorst_pack from ase.parallel import paropen from ase.lattice.surface import * from gpaw import GPAW, PW, FermiDirac, MixerSum from gpaw.xc.exx import EXX kpts = monkhorst_pack((16, 16, 1)) kpts += np.array([1/32., 1/32., 0]) a = 2.51 # Lattice parameter of Co slab = hcp0001('Co', a=a, c=4.07, size=(1,1,4)) pos = slab.get_positions() cell = slab.get_cell() cell[2,2] = 20. + pos[-1, 2] slab.set_cell(cell) slab.set_initial_magnetic_moments([0.7, 0.7, 0.7, 0.7]) ds = [1.75, 2.0, 2.25, 2.5, 2.75, 3.0, 3.25, 3.5, 3.75, 4.0, 5.0, 6.0, 10.0] for d in ds: pos = slab.get_positions() add_adsorbate(slab, 'C', d, position=(pos[3,0], pos[3,1])) add_adsorbate(slab, 'C', d, position=(cell[0,0]/3 + cell[1,0]/3, cell[0,1]/3 + cell[1,1]/3)) #view(slab) calc = GPAW(xc='PBE', eigensolver='cg', mode=PW(600),