def run(name): Calculator = get_calculator(name) par = required.get(name, {}) calc = Calculator(label=name + '_bandgap', xc='PBE', # abinit, aims, elk - do not recognize the syntax below: # https://trac.fysik.dtu.dk/projects/ase/ticket/98 # kpts={'size': kpts, 'gamma': True}, **par) kpts=kpts, **par) si = bulk('Si', crystalstructure='diamond', a=5.43) si.calc = calc si.get_potential_energy() print(name, bandgap(si.calc)) del si.calc # test spin-polarization calc = Calculator(label=name + '_bandgap_spinpol', xc='PBE', # abinit, aims, elk - do not recognize the syntax below: # https://trac.fysik.dtu.dk/projects/ase/ticket/98 # kpts={'size': kpts, 'gamma': True}, **par) kpts=kpts, **par) si.set_initial_magnetic_moments([-0.1, 0.1]) # this should not be necessary in the new ase interface standard ... if si.get_initial_magnetic_moments().any(): # spin-polarization if name == 'aims': calc.set(spin='collinear') if name == 'elk': calc.set(spinpol=True) si.set_calculator(calc) si.get_potential_energy() print(name, bandgap(si.calc))
def test_coulG(self): numpy.random.seed(19) kpt = numpy.random.random(3) ase_atom = bulk('C', 'diamond', a=3.5668) cell = pbcgto.Cell() cell.unit = 'A' cell.atom = pyscf_ase.ase_atoms_to_pyscf(ase_atom) cell.a = ase_atom.cell + numpy.random.random((3,3)).T cell.basis = 'gth-szv' cell.pseudo = 'gth-pade' cell.gs = [5,4,3] cell.verbose = 5 cell.output = '/dev/null' cell.build() coulG = tools.get_coulG(cell, kpt) self.assertAlmostEqual(finger(coulG), 62.75448804333378, 9) cell.a = numpy.eye(3) cell.unit = 'B' coulG = tools.get_coulG(cell, numpy.array([0, numpy.pi, 0])) self.assertAlmostEqual(finger(coulG), 4.6737453679713905, 9) coulG = tools.get_coulG(cell, numpy.array([0, numpy.pi, 0]), wrap_around=False) self.assertAlmostEqual(finger(coulG), 4.5757877990664744, 9) coulG = tools.get_coulG(cell, exx='ewald') self.assertAlmostEqual(finger(coulG), 4.888843468914021, 9)
def get_elastic_constants(pot_path=None, calculator=None, delta=1e-2, symbol="W"): """ return lattice parameter, and cubic elastic constants: C11, C12, 44 using matscipy function pot_path - path to the potential symbol : string Symbol of the element to pass to ase.lattuce.cubic.SimpleCubicFactory default is "W" for tungsten """ unit_cell = bulk(symbol) if (pot_path is not None) and (calculator is None): # create lammps calculator with the potential lammps = LAMMPSlib(lmpcmds=["pair_style eam/fs", "pair_coeff * * %s W" % pot_path], atom_types={'W': 1}, keep_alive=True) calculator = lammps unit_cell.set_calculator(calculator) # simple calculation to get the lattice constant and cohesive energy # alat0 = W.cell[0][1] - W.cell[0][0] sf = StrainFilter(unit_cell) # or UnitCellFilter(W) -> to minimise wrt pos, cell opt = FIRE(sf) opt.run(fmax=1e-4) # max force in eV/A alat = unit_cell.cell[0][1] - unit_cell.cell[0][0] # print("a0 relaxation %.4f --> %.4f" % (a0, a)) # e_coh = W.get_potential_energy() # print("Cohesive energy %.4f" % e_coh) Cij, Cij_err = fit_elastic_constants(unit_cell, symmetry="cubic", delta=delta) Cij = Cij/GPa # unit conversion to GPa elasticMatrix3x3 = Cij[:3, :3] # average of diagonal elements: C11, C22, C33 C11 = elasticMatrix3x3.diagonal().mean() # make mask to extract non diagonal elements mask = np.ones((3, 3), dtype=bool) np.fill_diagonal(mask, False) # average of all non diagonal elements from 1 to 3 C12 = elasticMatrix3x3[mask].mean() # average of diagonal elements from 4 till 6: C44, C55, C66, C44 = Cij[3:, 3:].diagonal().mean() # A = 2.*C44/(C11 - C12) if (pot_path is not None) and (calculator is None): lammps.lmp.close() return alat, C11, C12, C44
def surface(lattice, indices, layers, vacuum=None, tol=1e-10): """Create surface from a given lattice and Miller indices. lattice: Atoms object or str Bulk lattice structure of alloy or pure metal. Note that the unit-cell must be the conventional cell - not the primitive cell. One can also give the chemical symbol as a string, in which case the correct bulk lattice will be generated automatically. indices: sequence of three int Surface normal in Miller indices (h,k,l). layers: int Number of equivalent layers of the slab. vacuum: float Amount of vacuum added on both sides of the slab. """ indices = np.asarray(indices) if indices.shape != (3,) or not indices.any() or indices.dtype != int: raise ValueError('%s is an invalid surface type' % indices) if isinstance(lattice, basestring): lattice = bulk(lattice, cubic=True) h, k, l = indices h0, k0, l0 = (indices == 0) if h0 and k0 or h0 and l0 or k0 and l0: # if two indices are zero if not h0: c1, c2, c3 = [(0, 1, 0), (0, 0, 1), (1, 0, 0)] if not k0: c1, c2, c3 = [(0, 0, 1), (1, 0, 0), (0, 1, 0)] if not l0: c1, c2, c3 = [(1, 0, 0), (0, 1, 0), (0, 0, 1)] else: p, q = ext_gcd(k, l) a1, a2, a3 = lattice.cell # constants describing the dot product of basis c1 and c2: # dot(c1,c2) = k1+i*k2, i in Z k1 = np.dot(p * (k * a1 - h * a2) + q * (l * a1 - h * a3), l * a2 - k * a3) k2 = np.dot(l * (k * a1 - h * a2) - k * (l * a1 - h * a3), l * a2 - k * a3) if abs(k2) > tol: i = -int(round(k1 / k2)) # i corresponding to the optimal basis p, q = p + i * l, q - i * k a, b = ext_gcd(p * k + q * l, h) c1 = (p * k + q * l, -p * h, -q * h) c2 = np.array((0, l, -k)) // abs(gcd(l, k)) c3 = (b, a * p, a * q) surf = build(lattice, np.array([c1, c2, c3]), layers, tol) if vacuum is not None: surf.center(vacuum=vacuum, axis=2) return surf
def exafs_reference_path(z, feff_options): atoms = bulk(z, orthorhombic=True, cubic=True) atoms = atoms.repeat((4,4,4)) center = numpy.argmin(numpy.sum((atoms.get_scaled_positions() - numpy.array( (.5,.5,.5) ))**2.0, axis=1)) #do the bulk reference scattering calculation and get the path #data from feff path = run_feff(atoms, center, feff_options, get_path=True)[2] return path
def estimate_lattice_constant(name, crystalstructure, covera): from ase.build import bulk atoms = bulk(name, crystalstructure, 1.0, covera) v0 = atoms.get_volume() v = 0.0 for Z in atoms.get_atomic_numbers(): r = covalent_radii[Z] v += 4 * np.pi / 3 * r**3 * 1.5 return (v / v0)**(1.0 / 3)
def test_ASE(): """Socket client for ASE.""" # create ASE atoms and calculator atoms = build.bulk('Ar', cubic=True) calculator = LennardJones(epsilon=0.997 * units.kJ / units.mol, sigma=3.4, rc=10.0) atoms.set_calculator(calculator) # try to get potential energy atoms.get_potential_energy() # create the socket client ClientASE(atoms, address='ase', _socket=False)
def build_bulk(args): L = args.lattice_constant.replace(',', ' ').split() d = dict([(key, float(x)) for key, x in zip('ac', L)]) atoms = bulk(args.name, crystalstructure=args.crystal_structure, a=d.get('a'), c=d.get('c'), orthorhombic=args.orthorhombic, cubic=args.cubic) M, X = {'Fe': (2.3, 'bcc'), 'Co': (1.2, 'hcp'), 'Ni': (0.6, 'fcc')}.get(args.name, (None, None)) if M is not None and args.crystal_structure == X: atoms.set_initial_magnetic_moments([M] * len(atoms)) return atoms
def ase_vol_relax(): Al = bulk('Al', 'fcc', a=4.5, cubic=True) calc = Vasp(xc='LDA') Al.set_calculator(calc) from ase.constraints import StrainFilter sf = StrainFilter(Al) qn = QuasiNewton(sf, logfile='relaxation.log') qn.run(fmax=0.1, steps=5) print('Stress:\n', calc.read_stress()) print('Al post ASE volume relaxation\n', calc.get_atoms().get_cell()) return Al
def test_eam(self): for calc in [EAM('Au-Grochola-JCP05.eam.alloy')]: a = bulk('Au') a *= (2, 2, 2) a.rattle(0.1) a.set_calculator(calc) e = a.get_potential_energy() f = a.get_forces() s = a.get_stress() a.set_calculator(SupercellCalculator(calc, (3, 3, 3))) self.assertAlmostEqual(e, a.get_potential_energy()) self.assertArrayAlmostEqual(f, a.get_forces()) self.assertArrayAlmostEqual(s, a.get_stress())
def test_coulG_ws(self): ase_atom = bulk('C', 'diamond', a=3.5668) cell = pbcgto.Cell() cell.unit = 'A' cell.atom = pyscf_ase.ase_atoms_to_pyscf(ase_atom) cell.a = ase_atom.cell cell.basis = 'gth-szv' cell.pseudo = 'gth-pade' cell.gs = [5]*3 cell.verbose = 5 cell.output = '/dev/null' cell.build() mf = khf.KRHF(cell, exxdiv='vcut_ws') mf.kpts = cell.make_kpts([2,2,2]) coulG = tools.get_coulG(cell, mf.kpts[2], True, mf) self.assertAlmostEqual(finger(coulG), 1.3245117871351604, 9)
def build_bulk(name, opts): L = opts.lattice_constant.replace(",", " ").split() d = dict([(key, float(x)) for key, x in zip("ac", L)]) atoms = bulk( name, crystalstructure=opts.crystal_structure, a=d.get("a"), c=d.get("c"), orthorhombic=opts.orthorhombic, cubic=opts.cubic, ) M, X = {"Fe": (2.3, "bcc"), "Co": (1.2, "hcp"), "Ni": (0.6, "fcc")}.get(name, (None, None)) if M is not None and opts.crystal_structure == X: atoms.set_initial_magnetic_moments([M] * len(atoms)) return atoms
def run(name): Calculator = get_calculator(name) par = required.get(name, {}) calc = Calculator(label=name, xc='LDA', kpts=1.0, **par) al = bulk('AlO', crystalstructure='rocksalt', a=4.5) al.calc = calc e = al.get_potential_energy() calc.set(xc='PBE', kpts=(2, 2, 2)) epbe = al.get_potential_energy() print(e, epbe) calc = Calculator(name) print(calc.parameters, calc.results, calc.atoms) assert not calc.calculation_required(al, ['energy']) al = calc.get_atoms() print(al.get_potential_energy()) label = 'dir/' + name + '-2' calc = Calculator(label=label, atoms=al, xc='LDA', kpts=1.0, **par) print(al.get_potential_energy()) print(Calculator.read_atoms(label).get_potential_energy())
def main(): from ase.build import bulk from ase.calculators.interfacechecker import check_interface system = bulk('Si', 'diamond', orthorhombic=True) calc = Octopus(Spacing=0.275, KPointsGrid=[[2, 2, 2]], KPointsUseSymmetries=True, Smearing=0.1, SmearingFunction='fermi_dirac', ExtraStates=2, stdout='"stdout.log"', stderr='"stderr.log"', Output='density + potential + wfs', OutputFormat='xcrysden') system.set_calculator(calc) system.get_potential_energy() check_interface(calc)
def test_ASE(): """Socket client for ASE.""" try: from ase import build from ase import units from ase.calculators.lj import LennardJones except ImportError: raise nose.SkipTest # create ASE atoms and calculator atoms = build.bulk('Ar', cubic=True) calculator = LennardJones(epsilon=0.997 * units.kJ / units.mol, sigma=3.4, rc=10.0) atoms.set_calculator(calculator) # try to get potential energy atoms.get_potential_energy() # create the socket client client = ClientASE(atoms, address='ase', _socket=False)
def vasp_vol_relax(): Al = bulk('Al', 'fcc', a=4.5, cubic=True) calc = Vasp(xc='LDA', isif=7, nsw=5, ibrion=1, ediffg=-1e-3, lwave=False, lcharg=False) calc.calculate(Al) # Explicitly parse atomic position output file from Vasp CONTCAR_Al = io.read('CONTCAR', format='vasp') print('Stress after relaxation:\n', calc.read_stress()) print('Al cell post relaxation from calc:\n', calc.get_atoms().get_cell()) print('Al cell post relaxation from atoms:\n', Al.get_cell()) print('Al cell post relaxation from CONTCAR:\n', CONTCAR_Al.get_cell()) # All the cells should be the same. assert (calc.get_atoms().get_cell() == CONTCAR_Al.get_cell()).all() assert (Al.get_cell() == CONTCAR_Al.get_cell()).all() return Al
# creates: a1.png a2.png a3.png cnt1.png cnt2.png gnr1.png gnr2.png from ase.io import write from ase.build import bulk from ase.build import nanotube, graphene_nanoribbon import numpy as np for i, a in enumerate( [bulk('Cu', 'fcc', a=3.6), bulk('Cu', 'fcc', a=3.6, orthorhombic=True), bulk('Cu', 'fcc', a=3.6, cubic=True)]): write('a%d.pov' % (i + 1), a, show_unit_cell=2, display=False, run_povray=True) cnt1 = nanotube(6, 0, length=4, vacuum=2.5) cnt1.rotate('x', 'z', rotate_cell=True) cnt2 = nanotube(3, 3, length=6, bond=1.4, symbol='Si', vacuum=2.5) cnt2.rotate('x', 'z', rotate_cell=True) for i, a in enumerate([cnt1, cnt2]): write('cnt%d.pov' % (i + 1), a, show_unit_cell=2, display=False, run_povray=True) ind = [2, 0, 1] gnr1 = graphene_nanoribbon(3, 4, type='armchair', saturated=True, vacuum=2.5) gnr1.set_cell(np.diag(gnr1.cell)[ind]) gnr1.positions = gnr1.positions[:, ind] gnr2 = graphene_nanoribbon(2, 6, type='zigzag', saturated=True, C_H=1.1, C_C=1.4, vacuum=3.0, magnetic=True, initial_mag=1.12) gnr2.set_cell(np.diag(gnr2.cell)[ind]) gnr2.positions = gnr2.positions[:, ind]
""" Check the many ways of specifying KPOINTS """ import os import filecmp from ase.calculators.vasp import Vasp from ase.build import bulk Al = bulk('Al', 'fcc', a=4.5, cubic=True) def check_kpoints_line(n, contents): """Assert the contents of a line""" with open('KPOINTS', 'r') as f: lines = f.readlines() assert lines[n] == contents # Default to (1 1 1) calc = Vasp(gamma=True) calc.write_kpoints() check_kpoints_line(2, 'Gamma\n') check_kpoints_line(3, '1 1 1 \n') calc.clean() # 3-tuple prints mesh calc = Vasp(gamma=False, kpts=(4, 4, 4))
""" # Import modules from ase import Atom from ase.build import bulk from icet import ClusterSpace from icet.tools.structure_generation import (generate_sqs, generate_sqs_from_supercells, generate_sqs_by_enumeration, generate_target_structure) from icet.input_output.logging_tools import set_log_config set_log_config(level='INFO') # Generate SQS for binary fcc, 50 % concentration primitive_structure = bulk('Au') cs = ClusterSpace(primitive_structure, [8.0, 4.0], ['Au', 'Pd']) target_concentrations = {'Au': 0.5, 'Pd': 0.5} sqs = generate_sqs(cluster_space=cs, max_size=8, target_concentrations=target_concentrations) print('Cluster vector of generated structure:', cs.get_cluster_vector(sqs)) # Generate SQS for binary fcc with specified supercells supercells = [primitive_structure.repeat((1, 2, 4))] sqs = generate_sqs_from_supercells(cluster_space=cs, supercells=supercells, n_steps=10000, target_concentrations=target_concentrations) print('Cluster vector of generated structure:', cs.get_cluster_vector(sqs))
assert np.allclose(correct_pos, positions) # Test center away from values 0, 0.5 result_positions = wrap_positions(positions, cell, pbc=[True, True, False], center=0.2) correct_pos = [[4.7425, 1.2575, 8.7425], [2.0275, 3.9725, 8.7425], [3.385, 2.615, 10.1], [-0.6875, 1.2575, 8.7425], [6.1, -0.1, 10.1], [3.385, -2.815, 10.1], [2.0275, -1.4575, 8.7425], [0.67, -0.1, 10.1]] assert np.allclose(correct_pos, result_positions) # Get the correct crystal structure from a range of different cells assert crystal_structure_from_cell(bulk('Al').get_cell()) == 'fcc' assert crystal_structure_from_cell(bulk('Fe').get_cell()) == 'bcc' assert crystal_structure_from_cell(bulk('Zn').get_cell()) == 'hexagonal' cell = [[1, 0, 0], [0, 1, 0], [0, 0, 1]] assert crystal_structure_from_cell(cell) == 'cubic' cell = [[1, 0, 0], [0, 1, 0], [0, 0, 2]] assert crystal_structure_from_cell(cell) == 'tetragonal' cell = [[1, 0, 0], [0, 2, 0], [0, 0, 3]] assert crystal_structure_from_cell(cell) == 'orthorhombic' cell = [[1, 0, 0], [0, 2, 0], [0, 1, 3]] assert crystal_structure_from_cell(cell) == 'monoclinic'
import numpy as np from ase.calculators.emt import EMT from ase.build import bulk from ase.optimize import FIRE a = bulk('Au') a *= (2, 2, 2) a[0].x += 0.5 a.set_calculator(EMT()) opt = FIRE(a, dtmax=1.0, dt=1.0, maxmove=100.0, downhill_check=False) opt.run(fmax=0.001) e1 = a.get_potential_energy() n1 = opt.nsteps a = bulk('Au') a *= (2, 2, 2) a[0].x += 0.5 a.set_calculator(EMT()) reset_history = [] def callback(a, r, e, e_last): reset_history.append([e - e_last])
# Refer to G. Kresse, Phys. Rev. B 73, 045112 (2006) # for comparison of macroscopic and microscopic dielectric constant # and absorption peaks. from __future__ import print_function from ase.build import bulk from ase.parallel import paropen from gpaw import GPAW, FermiDirac from gpaw.response.df import DielectricFunction # Ground state calculation a = 5.431 atoms = bulk('Si', 'diamond', a=a) calc = GPAW(mode='pw', kpts={ 'density': 5.0, 'gamma': True }, parallel={'band': 1}, xc='LDA', occupations=FermiDirac(0.001)) # Use small FD smearing atoms.set_calculator(calc) atoms.get_potential_energy() # Get ground state density # Restart Calculation with fixed density and dense kpoint sampling calc.set( kpts={ 'density': 15.0, 'gamma': False
from numpy.random import RandomState from ase.phonons import Phonons from ase.data import atomic_numbers from ase.optimize import FIRE #from asap3 import EMT from ase.calculators.emt import EMT from ase.build import bulk from ase.md.velocitydistribution import PhononHarmonics from ase import units # Tests the phonon-based perturbation and velocity distribution # for thermal equilibration in MD. rng = RandomState(17) atoms = bulk('Pd') atoms *= (3, 3, 3) avail = [atomic_numbers[sym] for sym in ['Ni', 'Cu', 'Pd', 'Ag', 'Pt', 'Au']] atoms.numbers[:] = rng.choice(avail, size=len(atoms)) atoms.calc = EMT() opt = FIRE(atoms, trajectory='relax.traj') opt.run(fmax=0.001) positions0 = atoms.positions.copy() phonons = Phonons(atoms, EMT(), supercell=(1, 1, 1), delta=0.05) try: phonons.run() phonons.read() # Why all this boilerplate? finally:
# creates: cu.png from ase.build import bulk from ase.calculators.test import FreeElectrons a = bulk('Cu') a.calc = FreeElectrons(nvalence=1, kpts={'path': 'GXWLGK', 'npoints': 200}) a.get_potential_energy() bs = a.calc.band_structure() bs.plot(emax=10, filename='cu.png')
from __future__ import print_function from ase import Atoms from ase.build import bulk from gpaw import GPAW from gpaw import PW cell = bulk('Si', 'fcc', a=5.421).get_cell() a = Atoms('Si2', cell=cell, pbc=True, scaled_positions=((0, 0, 0), (0.25, 0.25, 0.25))) for x in [100, 200, 300, 400, 500, 600, 700, 800]: # for x in [0.24, 0.22, 0.20, 0.18, 0.16, 0.14, 0.12, 0.1]: calc = GPAW( mode=PW(x), # h=x, xc='PBE', kpts=(4, 4, 4), txt='convergence_%s.txt' % x) a.set_calculator(calc) print(x, a.get_potential_energy())
def system(): return bulk('Al', 'fcc', a=4.5, cubic=True)
from __future__ import print_function from ase.build import bulk import os import sys sys.path.append('/home/efefer/WORKS/my_github_repos/') from qeManager import * atoms = bulk('Fe') pspFiles = ['Fe.pbe-spn-kjpaw_psl.0.2.1.UPF'] pwinput = PWSCFInput(atoms, pspFiles, filename='PWINPUT', kpt_automatic=True, Nk=[8, 8, 8]) pwinput.filename = 'PWINPUT_scf' pwinput.CONTROL.pseudo_dir = '/home/efefer/pseudo' pwinput.set_smearing() pwinput.write() #os.system('pw.x < PWINPUT_scf > LOG_scf') pwinput.set_calc_bands('fcc', Nkpts=100) pwinput.filename = 'PWINPUT_bands' pwinput.write() #os.system('pw.x < PWINPUT_bands > LOG_bands') xcoords = pwinput.bands_xcoords
from numpy import linspace from ase.calculators.fleur import FLEUR from ase.build import bulk from ase.io.trajectory import Trajectory atoms = bulk('Ni', a=3.52) calc = FLEUR(xc='PBE', kmax=3.6, kpts=(10, 10, 10), workdir='lat_const') atoms.set_calculator(calc) traj = Trajectory('Ni.traj','w', atoms) cell0 = atoms.get_cell() for s in linspace(0.95, 1.05, 7): cell = cell0 * s atoms.set_cell((cell)) ene = atoms.get_potential_energy() traj.write()
def test_hcp(): import numpy as np from ase.io import read, Trajectory from ase.build import bulk from ase.calculators.emt import EMT class NDPoly: def __init__(self, ndims=1, order=3): """Multivariate polynomium. ndims: int Number of dimensions. order: int Order of polynomium.""" if ndims == 0: exponents = [()] else: exponents = [] for i in range(order + 1): E = NDPoly(ndims - 1, order - i).exponents exponents += [(i, ) + tuple(e) for e in E] self.exponents = np.array(exponents) self.c = None def __call__(self, *x): """Evaluate polynomial at x.""" return np.dot(self.c, (x**self.exponents).prod(1)) def fit(self, x, y): """Fit polynomium at points in x to values in y.""" A = (x**self.exponents[:, np.newaxis]).prod(2) self.c = np.linalg.solve(np.inner(A, A), np.dot(A, y)) def polyfit(x, y, order=3): """Fit polynomium at points in x to values in y. With D dimensions and N points, x must have shape (N, D) and y must have length N.""" p = NDPoly(len(x[0]), order) p.fit(x, y) return p a0 = 3.52 / np.sqrt(2) c0 = np.sqrt(8 / 3.0) * a0 print('%.4f %.3f' % (a0, c0 / a0)) for i in range(3): traj = Trajectory('Ni.traj', 'w') eps = 0.01 for a in a0 * np.linspace(1 - eps, 1 + eps, 4): for c in c0 * np.linspace(1 - eps, 1 + eps, 4): ni = bulk('Ni', 'hcp', a=a, covera=c / a) ni.set_calculator(EMT()) ni.get_potential_energy() traj.write(ni) traj.close() configs = read('Ni.traj', index=':') energies = [config.get_potential_energy() for config in configs] ac = [(config.cell[0, 0], config.cell[2, 2]) for config in configs] p = polyfit(ac, energies, 2) from scipy.optimize import fmin_bfgs a0, c0 = fmin_bfgs(p, (a0, c0)) print('%.4f %.3f' % (a0, c0 / a0)) assert abs(a0 - 2.466) < 0.001 assert abs(c0 / a0 - 1.632) < 0.005
'Test ase.dft.wannier module with k-points.' from __future__ import print_function from ase.build import bulk from ase.dft.wannier import Wannier from gpaw import GPAW from gpaw.mpi import world, serial_comm si = bulk('Si', 'diamond', a=5.43) k = 4 if 1: si.calc = GPAW(kpts=(k, k, k), txt='Si-ibz.txt') e1 = si.get_potential_energy() si.calc.write('Si-ibz.gpw', mode='all') si.calc.set(symmetry={'point_group': False, 'time_reversal': False}, txt='Si-bz.txt') e2 = si.get_potential_energy() si.calc.write('Si-bz.gpw', mode='all') print((e1, e2)) def wan(calc): centers = [([0.125, 0.125, 0.125], 0, 1.5), ([0.125, 0.625, 0.125], 0, 1.5), ([0.125, 0.125, 0.625], 0, 1.5), ([0.625, 0.125, 0.125], 0, 1.5)] w = Wannier(4, calc, nbands=4, verbose=1, initialwannier=centers)
The molecules are first converted to molecular graphs using an 'adjacency rule' as described in Tang & de Jong https://doi.org/10.1063/1.5078640, then computed using the marginalized graph kernel. """ import numpy as np import pandas as pd from ase.build import molecule, bulk from graphdot import Graph from graphdot.kernel.molecular import Tang2019MolecularKernel # build sample molecules small_title = ['H2O', 'HCl', 'NaCl'] bulk_title = ['NaCl-bulk', 'NaCl-bulk2'] bulk = [ bulk('NaCl', 'rocksalt', a=5.64), bulk('NaCl', 'rocksalt', a=5.66), ] molecules = [molecule(name) for name in small_title] + bulk # convert to molecular graphs graphs = [Graph.from_ase(m) for m in molecules] # use pre-defined molecular kernel kernel = Tang2019MolecularKernel(edge_length_scale=0.1) R = kernel(graphs) # normalize the similarity matrix d = np.diag(R)**-0.5 K = np.diag(d).dot(R).dot(np.diag(d))
from ase.build import bulk from gpaw import GPAW, FermiDirac, PW a = bulk('Cu', 'fcc') calc = GPAW(mode=PW(600), xc='PBE', occupations=FermiDirac(width=0.1), kpts=(12, 12, 12), txt='Cu_scf.txt') a.set_calculator(calc) a.get_potential_energy() calc.set(kpts={ 'size': (4, 4, 4), 'gamma': True }, nbands=30, symmetry='off', fixdensity=True, txt='Cu_nscf.txt', convergence={'bands': 20}) calc.get_potential_energy() calc.write('Cu.gpw', mode='all')
""" Add a short description of what is actually being tested here. """ import itertools import numpy.testing as npt from ase.build import bulk, cut from icet import ClusterSpace # initializes cluster space and get the internal primitive structure prim = bulk('Au', a=4.0, crystalstructure='hcp') subelements = ['Au', 'Pd'] cutoffs = [0.0] cs = ClusterSpace(prim, cutoffs, subelements) structure_prim = cs.primitive_structure # create a supercell using permutation matrix p_trial = [[1, 0, 0], [0, 1, 5], [0, 0, 2]] supercell = cut(structure_prim, p_trial[0], p_trial[1], p_trial[2]) # setup cartesian input to generate a random population cartesian_product_input = [] for i in range(len(supercell)): cartesian_product_input.append(['Pd', 'Au']) # loop over element combinations and assert expected singlet value for subset in itertools.product(*cartesian_product_input): for atom, element in zip(supercell, subset): atom.symbol = element
# additional tests of the extended XYZ file I/O # (which is also included in oi.py test case) # maintainted by James Kermode <*****@*****.**> import os import numpy as np import ase.io from ase.atoms import Atoms from ase.build import bulk # array data of shape (N, 1) squeezed down to shape (N, ) -- bug fixed # in commit r4541 at = bulk('Si') ase.io.write('to.xyz', at, format='extxyz') at.arrays['ns_extra_data'] = np.zeros((len(at), 1)) assert at.arrays['ns_extra_data'].shape == (2, 1) ase.io.write('to_new.xyz', at, format='extxyz') at_new = ase.io.read('to_new.xyz') assert at_new.arrays['ns_extra_data'].shape == (2,) os.unlink('to.xyz') os.unlink('to_new.xyz') # write sequence of images with different numbers of atoms -- bug fixed # in commit r4542 images = [at, at * (2, 1, 1), at * (3, 1, 1)] ase.io.write('multi.xyz', images, format='extxyz') read_images = ase.io.read('multi.xyz@:')
def make_supercell_cu(): crys = bulk('Cu', 'fcc', a=3.6, orthorhombic=True) P = np.array([[1, 0, 0], [0, 1, 0], [0, 0, 1]]) * 5 return make_supercell(crys, P)
# creates: s1.png s2.png s3.png s4.png general_surface.pdf from ase.build import surface s1 = surface('Au', (2, 1, 1), 9) s1.center(vacuum=10, axis=2) from ase.build import bulk Mobulk = bulk('Mo', 'bcc', a=3.16, cubic=True) s2 = surface(Mobulk, (3, 2, 1), 9) s2.center(vacuum=10, axis=2) a = 4.0 from ase import Atoms Pt3Rh = Atoms('Pt3Rh', scaled_positions=[(0, 0, 0), (0.5, 0.5, 0), (0.5, 0, 0.5), (0, 0.5, 0.5)], cell=[a, a, a], pbc=True) s3 = surface(Pt3Rh, (2, 1, 1), 9) s3.center(vacuum=10, axis=2) Pt3Rh.set_chemical_symbols('PtRhPt2') s4 = surface(Pt3Rh, (2, 1, 1), 9) s4.center(vacuum=10, axis=2) from ase.io import write for atoms, name in [(s1, 's1'), (s2, 's2'), (s3, 's3'), (s4, 's4')]: write(name + '.pov', atoms, rotation='-90x', show_unit_cell=2,
def make_supercell_li(): crys = bulk('Li', 'bcc', a=3.51, orthorhombic=True) P = np.array([[1, 0, 0], [0, 1, 0], [0, 0, 1]]) * 10 return make_supercell(crys, P)
from gpaw import GPAW, ConvergenceError, restart from gpaw.mixer import MixerSum from gpaw.test import equal from ase.build import bulk # bulk Fe with k-point, band, and domain parallelization a = 2.87 atoms = bulk('Fe', 'bcc', a=a) atoms.set_initial_magnetic_moments([2.2]) calc = GPAW(h=0.20, eigensolver='rmm-diis', mixer=MixerSum(0.1, 3), nbands=6, kpts=(4, 4, 4), parallel={'band': 2, 'domain': (2, 1, 1)}, maxiter=4) atoms.set_calculator(calc) try: atoms.get_potential_energy() except ConvergenceError: pass calc.write('tmp.gpw', mode='all') # Continue calculation for few iterations atoms, calc = restart('tmp.gpw', eigensolver='rmm-diis', mixer=MixerSum(0.1, 3), parallel={'band': 2, 'domain': (1, 1, 2)}, maxiter=4) try: atoms.get_potential_energy()
from ase.build import bulk from gpaw import GPAW si = bulk('Si', 'diamond', a=5.5, cubic=not True) si.set_calculator(GPAW(setups='ah', kpts=(2, 2, 2))) si.get_potential_energy() si.calc.write('Si.gpw', 'all') GPAW('Si.gpw')
from ase.build import bulk from gpaw import GPAW, FermiDirac from gpaw.wavefunctions.pw import PW # Plane wave cutoff pwcutoff = 400.0 # NxNxN k-point sampling k = 4 # Si lattice constant alat = 5.421 # bulk calculation bulk_crystal = bulk('Si', 'diamond', a=alat) bulk_calc = GPAW( mode=PW(pwcutoff), parallel={ 'domain': 1, 'band': 1 }, kpts={ 'size': (k, k, k), 'gamma': True }, # gamma-centred grid xc='PBE', occupations=FermiDirac(0.01), txt='si.rpa.pbe_output.txt') bulk_crystal.set_calculator(bulk_calc) e0_bulk_pbe = bulk_crystal.get_potential_energy()
def test_periodic_images(self): """Tests that periodic images are handled correctly. """ decay = 1 desc = MBTR( species=[1], periodic=True, k1={ "geometry": {"function": "atomic_number"}, "grid": {"min": 0, "max": 2, "sigma": 0.1, "n": 21} }, k2={ "geometry": {"function": "inverse_distance"}, "grid": {"min": 0, "max": 1.0, "sigma": 0.02, "n": 21}, "weighting": {"function": "exp", "scale": decay, "cutoff": 1e-4} }, k3={ "geometry": {"function": "cosine"}, "grid": {"min": -1.0, "max": 1.0, "sigma": 0.02, "n": 21}, "weighting": {"function": "exp", "scale": decay, "cutoff": 1e-4}, }, normalization="l2_each", # This normalizes the spectrum flatten=True ) # Tests that a system has the same spectrum as the supercell of # the same system. molecule = H.copy() a = 1.5 molecule.set_cell([ [a, 0.0, 0.0], [0.0, a, 0.0], [0.0, 0.0, a] ]) cubic_cell = desc.create(molecule) suce = molecule * (2, 1, 1) cubic_suce = desc.create(suce) diff = abs(np.sum(cubic_cell[0, :] - cubic_suce[0, :])) cubic_sum = abs(np.sum(cubic_cell[0, :])) self.assertTrue(diff/cubic_sum < 0.05) # A 5% error is tolerated # Same test but for triclinic cell molecule.set_cell([ [0.0, 2.0, 1.0], [1.0, 0.0, 1.0], [1.0, 2.0, 0.0] ]) triclinic_cell = desc.create(molecule) suce = molecule * (2, 1, 1) triclinic_suce = desc.create(suce) diff = abs(np.sum(triclinic_cell[0, :] - triclinic_suce[0, :])) tricl_sum = abs(np.sum(triclinic_cell[0, :])) self.assertTrue(diff/tricl_sum < 0.05) # Testing that the same crystal, but different unit cells will have a # similar spectrum when they are normalized. There will be small # differences in the shape (due to not double counting distances) a1 = bulk('H', 'fcc', a=2.0) a2 = bulk('H', 'fcc', a=2.0, orthorhombic=True) a3 = bulk('H', 'fcc', a=2.0, cubic=True) triclinic_cell = desc.create(a1) orthorhombic_cell = desc.create(a2) cubic_cell = desc.create(a3) diff1 = abs(np.sum(triclinic_cell[0, :] - orthorhombic_cell[0, :])) diff2 = abs(np.sum(triclinic_cell[0, :] - cubic_cell[0, :])) tricl_sum = abs(np.sum(triclinic_cell[0, :])) self.assertTrue(diff1/tricl_sum < 0.05) self.assertTrue(diff2/tricl_sum < 0.05) # Tests that the correct peak locations are present in a cubic periodic desc = MBTR( species=["H"], periodic=True, k3={ "geometry": {"function": "cosine"}, "grid": {"min": -1.1, "max": 1.1, "sigma": 0.010, "n": 600}, "weighting": {"function": "exp", "scale": decay, "cutoff": 1e-4} }, normalization="l2_each", # This normalizes the spectrum flatten=True ) a = 2.2 system = Atoms( cell=[ [a, 0.0, 0.0], [0.0, a, 0.0], [0.0, 0.0, a] ], positions=[ [0, 0, 0], ], symbols=["H"], ) cubic_spectrum = desc.create(system)[0, :] x3 = desc.get_k3_axis() peak_ids = find_peaks_cwt(cubic_spectrum, [2]) peak_locs = x3[peak_ids] assumed_peaks = np.cos(np.array( [ 180, 90, np.arctan(np.sqrt(2))*180/np.pi, 45, np.arctan(np.sqrt(2)/2)*180/np.pi, 0 ])*np.pi/180 ) self.assertTrue(np.allclose(peak_locs, assumed_peaks, rtol=0, atol=5*np.pi/180)) # Tests that the correct peak locations are present in a system with a # non-cubic basis desc = MBTR( species=["H"], periodic=True, k3={ "geometry": {"function": "cosine"}, "grid": {"min": -1.0, "max": 1.0, "sigma": 0.030, "n": 200}, "weighting": {"function": "exp", "scale": 1.5, "cutoff": 1e-4} }, normalization="l2_each", # This normalizes the spectrum flatten=True, sparse=False ) a = 2.2 system = Atoms( cell=[ [a, 0.0, 0.0], [0.0, a, 0.0], [0.0, 0.0, a] ], positions=[ [0, 0, 0], ], symbols=["H"], ) angle = 30 system = Atoms( cell=ase.geometry.cellpar_to_cell([3*a, a, a, angle, 90, 90]), positions=[ [0, 0, 0], ], symbols=["H"], ) tricl_spectrum = desc.create(system) x3 = desc.get_k3_axis() peak_ids = find_peaks_cwt(tricl_spectrum[0, :], [3]) peak_locs = x3[peak_ids] angle = (6)/(np.sqrt(5)*np.sqrt(8)) assumed_peaks = np.cos(np.array([180, 105, 75, 51.2, 30, 0])*np.pi/180) self.assertTrue(np.allclose(peak_locs, assumed_peaks, rtol=0, atol=5*np.pi/180))
from dscribe.descriptors import SineMatrix # Setting up the sine matrix descriptor sm = SineMatrix(n_atoms_max=6, permutation="sorted_l2", sparse=False, flatten=True) # Creation from ase.build import bulk # NaCl crystal created as an ASE.Atoms nacl = bulk("NaCl", "rocksalt", a=5.64) # Create output for the system nacl_sine = sm.create(nacl) # Create output for multiple system al = bulk("Al", "fcc", a=4.046) fe = bulk("Fe", "bcc", a=2.856) samples = [nacl, al, fe] sine_matrices = sm.create(samples) # Serial sine_matrices = sm.create(samples, n_jobs=2) # Parallel # Visualization import numpy as np from ase import Atoms import matplotlib.pyplot as mpl from mpl_toolkits.axes_grid1 import make_axes_locatable # FCC aluminum crystal
def test_fcc_bcc(comparator): s1 = bulk("Al", crystalstructure="fcc") s2 = bulk("Al", crystalstructure="bcc", a=4.05) s1 = s1 * (2, 2, 2) s2 = s2 * (2, 2, 2) assert not comparator.compare(s1, s2)
def test_new_style_interface(): calc = LennardJones() atoms = bulk('Cu') rattle_calc(atoms, calc)
from ase.db import connect from al_mlp.base_calcs.morse import MultiMorse from al_mlp.atomistic_methods import Relaxation from amptorch.trainer import AtomsTrainer parent_calc = EMT() # Make a simple C on Cu slab. # Sets calculator to parent_calc. energies = [] volumes = [] LC = [3.5, 3.55, 3.6, 3.65, 3.7, 3.75] for a in LC: cu_bulk = bulk("Cu", "fcc", a=a) calc = EMT() cu_bulk.set_calculator(calc) e = cu_bulk.get_potential_energy() energies.append(e) volumes.append(cu_bulk.get_volume()) eos = EquationOfState(volumes, energies) v0, e0, B = eos.fit() aref = 3.6 vref = bulk("Cu", "fcc", a=aref).get_volume()
from ase.db import connect from ase.build import bulk DB_NAME = 'kanzaki.db' atoms = bulk('Al', cubic=True) * (3, 3, 3) db = connect(DB_NAME) # db.write(atoms, group=0, comment="Pure aluminium reference") # atoms[0].symbol = 'Mg' # db.write(atoms, group=1, comment="Single Mg") # atoms[0].symbol = 'Si' # db.write(atoms, group=2, comment="Single Si")
because newer versions do not include eigenvalues, Fermi levels, ... in the 'results.tag' file, which the ASE interface relies upon. """ import os import numpy as np from ase.build import bulk from ase.io import write from ase.io.jsonio import write_json, read_json from ase.units import Bohr from ase.data import atomic_numbers, covalent_radii from hotcent.atomic_dft import AtomicDFT from hotcent.confinement import PowerConfinement from hotcent.tools import ConfinementOptimizer, DftbPlusBandStructure atoms = bulk('NO', 'zincblende', a=3.6) atoms.set_initial_magnetic_moments([1., 0.]) write('NO.traj', atoms) if not os.path.exists('bs_dft.json'): from ase.dft.kpoints import bandpath from ase.dft.band_structure import get_band_structure from gpaw import GPAW, PW, MixerSum, FermiDirac from gpaw.eigensolvers import CG calc = GPAW( mode=PW(400), maxiter=250, spinpol=True, kpts=(3, 3, 3), xc='LDA',
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
def test_cache(): atoms = bulk('Ni', crystalstructure='fcc', cubic=True) symbols = atoms.get_chemical_symbols() rc = 4.6 nij_max = 4678 max_occurs = Counter({'Ni': 108, "Mo": 54}) angular = False eta = np.array([0.05, 4.0, 20.0, 80.0]) omega = np.array([0.0]) beta = np.array([ 0.005, ]) gamma = np.array([1.0, -1.0]) zeta = np.array([1.0, 4.0]) params = { 'eta': eta, 'omega': omega, 'gamma': gamma, 'zeta': zeta, 'beta': beta } with tf.Graph().as_default(): vap = VirtualAtomMap(max_occurs, symbols) sf = BatchSymmetryFunction(rc, max_occurs, nij_max, 0, batch_size=1, angular=angular, **params) positions = vap.map_array_to_gsl(atoms.positions).astype(np.float32) cells = atoms.cell.array.astype(np.float32) atom_masks = vap.atom_masks.astype(np.float32) g2_map = get_g2_map(atoms, rc, nij_max, sf.all_kbody_terms, vap, sf.offsets, for_prediction=False) composition = np.zeros(len(sf.elements), dtype=np.float32) for element, count in Counter(symbols).items(): composition[sf.elements.index(element)] = np.float32(count) cache_dict = { 'positions': bytes_feature(positions.tostring()), 'cells': bytes_feature(cells.tostring()), 'n_atoms': int32_feature(len(atoms)), 'volume': float_feature(np.float32(atoms.get_volume())), 'y_true': float_feature(np.float32(0.0)), 'mask': bytes_feature(atom_masks.tostring()), 'composition': bytes_feature(composition.tostring()), 'pulay': float_feature(np.float32(0.0)), } for key, value in g2_map.items(): cache_dict[key] = bytes_feature(value.tostring()) forces = vap.map_array_to_gsl(np.zeros((4, 3))).astype(np.float32) cache_dict['f_true'] = bytes_feature(forces.tostring()) virial = np.zeros(6, np.float32) cache_dict['stress'] = bytes_feature(virial.tostring()) with tf.python_io.TFRecordWriter("test.tfrecords") as writer: example = tf.train.Example(features=tf.train.Features( feature=cache_dict)) writer.write(example.SerializeToString())
# creates: precon.png from ase.build import bulk from ase.calculators.emt import EMT from ase.optimize.precon import Exp, PreconLBFGS from ase.calculators.loggingcalc import LoggingCalculator import matplotlib.pyplot as plt a0 = bulk('Cu', cubic=True) a0 *= [3, 3, 3] del a0[0] a0.rattle(0.1) nsteps = [] energies = [] log_calc = LoggingCalculator(EMT()) for precon, label in [(None, 'None'), (Exp(A=3), 'Exp(A=3)')]: log_calc.label = label atoms = a0.copy() atoms.set_calculator(log_calc) opt = PreconLBFGS(atoms, precon=precon, use_armijo=True) opt.run(fmax=1e-3) log_calc.plot(markers=['r-', 'b-'], energy=False, lw=2) plt.savefig('precon.png')
def main(): """Adopted from ase/test/stress.py""" if "ASE_CP2K_COMMAND" not in os.environ: raise NotAvailable('$ASE_CP2K_COMMAND not defined') # setup a Fist Lennard-Jones Potential inp = """&FORCE_EVAL &MM &FORCEFIELD &SPLINE EMAX_ACCURACY 500.0 EMAX_SPLINE 1000.0 EPS_SPLINE 1.0E-9 &END &NONBONDED &LENNARD-JONES atoms Ar Ar EPSILON [eV] 1.0 SIGMA [angstrom] 1.0 RCUT [angstrom] 10.0 &END LENNARD-JONES &END NONBONDED &CHARGE ATOM Ar CHARGE 0.0 &END CHARGE &END FORCEFIELD &POISSON &EWALD EWALD_TYPE none &END EWALD &END POISSON &END MM &END FORCE_EVAL""" calc = CP2K(label="test_stress", inp=inp, force_eval_method="Fist") vol0 = 4 * 0.91615977036 # theoretical minimum a0 = vol0 ** (1 / 3) a = bulk('Ar', 'fcc', a=a0) a.calc = calc a.set_cell(np.dot(a.cell, [[1.02, 0, 0.03], [0, 0.99, -0.02], [0.1, -0.01, 1.03]]), scale_atoms=True) a *= (1, 2, 3) a.rattle() sigma_vv = a.get_stress(voigt=False) # print(sigma_vv) # print(a.get_potential_energy() / len(a)) vol = a.get_volume() # compare stress tensor with numeric derivative deps = 1e-5 cell = a.cell.copy() for v in range(3): x = np.eye(3) x[v, v] += deps a.set_cell(np.dot(cell, x), scale_atoms=True) ep = a.calc.get_potential_energy(a, force_consistent=True) x[v, v] -= 2 * deps a.set_cell(np.dot(cell, x), scale_atoms=True) em = a.calc.get_potential_energy(a, force_consistent=True) s = (ep - em) / 2 / deps / vol # print(v, s, abs(s - sigma_vv[v, v])) assert abs(s - sigma_vv[v, v]) < 1e-7 for v1 in range(3): v2 = (v1 + 1) % 3 x = np.eye(3) x[v1, v2] = deps x[v2, v1] = deps a.set_cell(np.dot(cell, x), scale_atoms=True) ep = a.calc.get_potential_energy(a, force_consistent=True) x[v1, v2] = -deps x[v2, v1] = -deps a.set_cell(np.dot(cell, x), scale_atoms=True) em = a.calc.get_potential_energy(a, force_consistent=True) s = (ep - em) / deps / 4 / vol # print(v1, v2, s, abs(s - sigma_vv[v1, v2])) assert abs(s - sigma_vv[v1, v2]) < 1e-7 # run a cell optimization, see if it finds back original crystal structure opt = MDMin(UnitCellFilter(a), dt=0.01, logfile=None) opt.run(fmax=0.1) # print(a.cell) for i in range(3): for j in range(3): x = np.dot(a.cell[i], a.cell[j]) y = (i + 1) * (j + 1) * a0 ** 2 / 2 if i != j: y /= 2 # print(i, j, x, (x - y) / x) assert abs((x - y) / x) < 0.01 print('passed test "stress"')
1, ], 'eta': [0.036, 0.071] }, 'G5': { 'Rs': [0], 'lambda': [1], 'zeta': [ 1, ], 'eta': [0.036, 0.071] }, } for a in [5.0]: #, 5.4, 5.8]: si = bulk('Si', 'diamond', a=a, cubic=True) cell = si.get_cell() #cell[0,1] += 0.2 si.set_cell(cell) print(si.get_cell()) bp = ACSF(symmetry, Rc=Rc, derivative=True, stress=True, atom_weighted=False) des = bp.calculate(si, system=[14]) #print("G:", des['x'][0]) #print("Sequence", des['seq'][0]) #print("GPrime", des['dxdr'][0])
print("nbands = ", nbnd) spath = elem_list[3] print("path = ", spath) nkpts = elem_list[4] print("kpts = ", nkpts) kpts = ast.literal_eval(nkpts) La = float(elem_list[5]) print("lattice constant a = ", La) Lb = float(elem_list[6]) print("lattice constant b = ", Lb) Lc = float(elem_list[7]) print("lattice constant c = ", Lc) Lalpha = float(elem_list[8]) print("alpha angle = ", Lalpha) atoms = bulk(element, struct, a=La, b=Lb, c=Lc, alpha=Lalpha) #atoms = bulk(element,struct) # sc,fcc,bcc,tetragonal,bct,hcp,rhmbohedral,orthorhombic # mlc, diamond,zincblende,rocksalt,cesiumchloride, fluorite, wurtzite # First perform a regular SCF run gbrv_pp = {} ppdir = os.environ['ESPRESSO_PSEUDO'] sym = list(set(atoms.get_chemical_symbols())) for s in sym: for f in os.listdir(ppdir): keys = f.split('_') if keys[0] == s.lower() and keys[1] == xc.lower(): gbrv_pp[s] = f
# creates: lattice_constant.csv import numpy as np a0 = 3.52 / np.sqrt(2) c0 = np.sqrt(8 / 3.0) * a0 from ase.io import Trajectory traj = Trajectory('Ni.traj', 'w') from ase.build import bulk from ase.calculators.emt import EMT eps = 0.01 for a in a0 * np.linspace(1 - eps, 1 + eps, 3): for c in c0 * np.linspace(1 - eps, 1 + eps, 3): ni = bulk('Ni', 'hcp', a=a, c=c) ni.set_calculator(EMT()) ni.get_potential_energy() traj.write(ni) from ase.io import read configs = read('Ni.traj@:') energies = [config.get_potential_energy() for config in configs] a = np.array([config.cell[0, 0] for config in configs]) c = np.array([config.cell[2, 2] for config in configs]) functions = np.array([a**0, a, c, a**2, a * c, c**2]) p = np.linalg.lstsq(functions.T, energies)[0] p0 = p[0] p1 = p[1:3] p2 = np.array([(2 * p[3], p[4]),
def Cbulk(): Cbulk = bulk('C', crystalstructure='fcc', a=2 * 1.221791471) Cbulk = Cbulk.repeat([2, 1, 1]) Cbulk.calc = EMT() return Cbulk
-2.51338548e+00, -2.39650817e+00, -2.25058831e+00]) m_phi = np.array([6.27032242e+01, 3.49638589e+01, 1.79007014e+01, 8.69001383e+00, 4.51545250e+00, 2.83260884e+00, 1.93216616e+00, 1.06795515e+00, 3.37740836e-01, 1.61087890e-02, -6.20816372e-02, -6.51314297e-02, -5.35210341e-02, -5.20950200e-02, -5.51709524e-02, -4.89093894e-02, -3.28051688e-02, -1.13738785e-02, 2.33833655e-03, 4.19132033e-03, 1.68600692e-04]) m_densityf = spline(rs, m_density) m_embeddedf = spline(rhos, m_embedded) m_phif = spline(rs, m_phi) a = 4.05 # Angstrom lattice spacing al = bulk('Al', 'fcc', a=a) mishin_approx = EAM(elements=['Al'], embedded_energy=np.array([m_embeddedf]), electron_density=np.array([m_densityf]), phi=np.array([[m_phif]]), cutoff=cutoff, form='alloy', # the following terms are only required to write out a file Z=[13], nr=n, nrho=n, dr=cutoff / n, drho=2. / n, lattice=['fcc'], mass=[26.982], a=[a]) al.set_calculator(mishin_approx) mishin_approx_energy = al.get_potential_energy() mishin_approx.write_potential('Al99-test.eam.alloy') mishin_check = EAM(potential='Al99-test.eam.alloy') al.set_calculator(mishin_check)
name, 'gw-' + name, nbands=8, integrate_gamma=0, kpts=[(0, 0, 0), (0.5, 0.5, 0)], # Gamma, X ecut=40, domega0=0.1, eta=0.2, bands=(3, 7), # h**o, lumo, lumo+1, lumo+2 ) results = gw.calculate() return e, results a = 5.43 si1 = bulk('Si', 'diamond', a=a) si2 = si1.copy() si2.positions -= a / 8 i = 0 results = [] for si in [si1, si2]: for symm in [{}, 'off', {'time_reversal': False}, {'point_group': False}]: e, r = run(si, symm, str(i)) G, X = r['eps'][0] results.append([e, G[0], G[1] - G[0], X[1] - G[0], X[2] - X[1]]) G, X = r['qp'][0] results[-1].extend([G[0], G[1] - G[0], X[1] - G[0], X[2] - X[1]]) i += 1 equal(
def test_compare(comparator): s1 = bulk("Al") s1 = s1 * (2, 2, 2) s2 = bulk("Al") s2 = s2 * (2, 2, 2) assert comparator.compare(s1, s2)
models_list = [] sites_list = [] classes_list = [] for i in range(num_examples): buildclass = randint(0, 1) L_wire = randint(100, 200) # Wire length 20 nm W_wire = 50 #Wire width 100 Å a_wire = 5.6 #Lattice constant # # Create structure if buildclass == 'WZ': atoms = bulk('GaAs', 'wurtzite', a_wire, a_wire, a_wire * 1.63, orthorhombic=True) atoms = atoms.repeat((round(W_wire / a_wire), round(W_wire / a_wire), round(L_wire / (a_wire * 1.63)))) else: atoms = bulk('GaAs', 'zincblende', a_wire, a_wire, a_wire, orthorhombic=True) atoms = atoms.repeat((round(W_wire / a_wire), round(W_wire / a_wire), round(L_wire / a_wire))) atoms.center(vacuum=0.0)