def EfccEhcpCalculator(self, EMT, PARAMETERS): # Return 0 is used when the method is not desired to be used # return 0 """ This method uses the EMT calculator to calculate and return the difference in energy between a system of atoms placed in the HCP and FCC structure. """ # The atoms objects are created using the input size and element and the energy calculator # is set to the EMT calculator # The Lattice Constants, a,c, for the HCP lattice is here given by the nearest neighbor distance of # the system in the FCC crystal structure, a = dnn, and the ideal relation between a and # c: a/c = sqrt(8/3) => c = dnn / sqrt(8/3) a = beta * PARAMETERS[self.Element][1] * Bohr c = a * numpy.sqrt(8. / 3.) # The HCP crystal is created, the size of the crystal is defined as 5,5,5, any smaller crystal will result in # Neighborlist errors. atoms1 = HexagonalClosedPacked(size=(5, 5, 5), directions=[[2, -1, -1, 0], [0, 1, -1, 0], [0, 0, 0, 1]], symbol=self.Element, latticeconstant={ 'a': a, 'c': c }) atoms1.set_calculator(EMT) # The FCC crystal is created atoms2 = FaceCenteredCubic(size=(self.Size, self.Size, self.Size), symbol=self.Element) atoms2.set_calculator(EMT) # The energy difference pr atom is calculated and returned return atoms1.get_potential_energy() / len( atoms1) - atoms2.get_potential_energy() / len(atoms2)
def equilShape(element,params,size=(10,10,10),distance=25.0,corrections=0,structure='fcc'): """ this is to use the ratio of energies to calculate the equilibrium crystal shape, cycle through a bunch of (h,k,l) indices """ slab = FaceCenteredCubic(element,directions=([[1,0,0],[0,1,0],[0,0,1]]),size=(10,10,10)) energy100 = fitFunction([1,0,0],params,corrections,structure) h100 = distance orig_positions = slab.get_positions() kept_positions = list(orig_positions) center = slab.get_center_of_mass() for h in range(-12,12): for k in range(0,9): for l in range(0,9): nvector=list([h,k,l]/numpy.sqrt(h**2+k**2+l**2)) energyhkl = fitFunction(nvector,params,corrections,structure) distancehkl = energyhkl/energy100*h100 for i in range(0,len(kept_positions)): list_to_pop = [] if numpy.dot(kept_positions[i],nvector) > distancehkl: list_to_pop.append(i) for i in list_to_pop: kept_positions.pop(i) # set up new slab with new positions number_of_atoms = len(kept_positions) elstring = str(number_of_atoms)+'Pt' new_slab = Atoms(elstring,positions=kept_positions) return new_slab
def E_cohCalculator(self, EMT, PARAMETERS): # Return 0 is used when the method is not desired to be used # return 0 """ Calculates the Cohesive energy of a system of atoms using the EMT calculator specified. """ # As the EMT calculator calculates the energy of the system such that the energy of the individual atoms in # their equilibrium distance in the crystal is zero it is only needed to calculate the energy of a single atom # in an empty system. # The crystal is created atoms = FaceCenteredCubic(size=(self.Size, self.Size, self.Size), symbol=self.Element) # a single atom is taken out of the crystal atoms2 = atoms[[ 0, ]] # The calculator is attached to the atoms objects atoms.set_calculator(EMT) atoms2.set_calculator(EMT) # The energy difference between the atom alone in vacuum and in the crystal structure is calculated and returned return atoms2.get_potential_energy( ) - atoms.get_potential_energy() / len(atoms)
def test_calculator(): # create calculator #modelname = 'ex_model_Ar_P_MLJ_C' modelname = 'ex_model_Ar_P_Morse_07C' calc = KIMCalculator(modelname) # create a SC cyrstal argon = SimpleCubic(directions=[[1,0,0], [0,1,0], [0,0,1]], size=(2,2,2), symbol='Ar', pbc=(1,1,0), latticeconstant=3.0) # attach calculator to atoms argon.set_calculator(calc) # compute energy and forces print_values(argon, 'SC argon, pbc=(1,1,0)') # change pbc, and then compute energy and forces argon.set_pbc([0,0,0]) print_values(argon, 'SC argon, pbc=(0,0,0)') # create a FCC crystal argon2 = FaceCenteredCubic(directions=[[1,0,0], [0,1,0], [0,0,1]], size=(2,2,2), symbol='Ar', pbc=(1,1,0), latticeconstant=3.0) # attach the SAME calculator to the new atoms argon2.set_calculator(calc) # compute energy and forces print_values(argon2, 'FCC argon, pbc=(1,1,0)')
def atoms(): # (100) oriented block atoms = FaceCenteredCubic(size=(5, 5, 5), symbol=symb, pbc=(1, 1, 0)) assert len(atoms) == 5 * 5 * 5 * 4 c = atoms.get_cell() checkang(c[0], c[1], pi / 2) checkang(c[0], c[2], pi / 2) checkang(c[1], c[2], pi / 2) assert np.abs(5 * a0 - c[2, 2]) < 1e-10 return atoms
def test_isolation_3D(): atoms = FaceCenteredCubic(size=(2, 2, 2), symbol='Cu', pbc=(1, 1, 1)) result = isolate_components(atoms) assert len(result) == 1 key, components = list(result.items())[0] assert key == '3D' assert len(components) == 1 bulk = components[0] assert bulk.get_chemical_formula() == atoms.get_chemical_formula()
def relax(input_atoms, ref_db): atoms_string = input_atoms.get_chemical_symbols() # Open connection to the database with reference data db = connect(ref_db) # Load our model structure which is just FCC atoms = FaceCenteredCubic('X', latticeconstant=1.) atoms.set_chemical_symbols(atoms_string) # Compute the average lattice constant of the metals in this individual # and the sum of energies of the constituent metals in the fcc lattice # we will need this for calculating the heat of formation a = 0 ei = 0 for m in set(atoms_string): dct = db.get(metal=m) count = atoms_string.count(m) a += count * dct.latticeconstant ei += count * dct.energy_per_atom a /= len(atoms_string) atoms.set_cell([a, a, a], scale_atoms=True) # Since calculations are extremely fast with EMT we can also do a volume # relaxation atoms.calc = EMT() eps = 0.05 volumes = (a * np.linspace(1 - eps, 1 + eps, 9))**3 energies = [] for v in volumes: atoms.set_cell([v**(1. / 3)] * 3, scale_atoms=True) energies.append(atoms.get_potential_energy()) eos = EquationOfState(volumes, energies) v1, ef, B = eos.fit() latticeconstant = v1**(1. / 3) # Calculate the heat of formation by subtracting ef with ei hof = (ef - ei) / len(atoms) # Place the calculated parameters in the info dictionary of the # input_atoms object input_atoms.info['key_value_pairs']['hof'] = hof # Raw score must always be set # Use one of the following two; they are equivalent input_atoms.info['key_value_pairs']['raw_score'] = -hof # set_raw_score(input_atoms, -hof) input_atoms.info['key_value_pairs']['latticeconstant'] = latticeconstant # Setting the atoms_string directly for easier analysis atoms_string = ''.join(input_atoms.get_chemical_symbols()) input_atoms.info['key_value_pairs']['atoms_string'] = atoms_string
def relax(input_atoms, ref_db): atoms_string = input_atoms.get_chemical_symbols() # Open connection to the database with reference data db = connect(ref_db) # Load our model structure which is just FCC atoms = FaceCenteredCubic('X', latticeconstant=1.) atoms.set_chemical_symbols(atoms_string) # Compute the average lattice constant of the metals in this individual # and the sum of energies of the constituent metals in the fcc lattice # we will need this for calculating the heat of formation a = 0 ei = 0 for m in set(atoms_string): dct = db.get(metal=m) count = atoms_string.count(m) a += count * dct.latticeconstant ei += count * dct.energy_per_atom a /= len(atoms_string) atoms.set_cell([a, a, a], scale_atoms=True) # Since calculations are extremely fast with EMT we can also do a volume # relaxation atoms.set_calculator(EMT()) eps = 0.05 volumes = (a * np.linspace(1 - eps, 1 + eps, 9))**3 energies = [] for v in volumes: atoms.set_cell([v**(1. / 3)] * 3, scale_atoms=True) energies.append(atoms.get_potential_energy()) eos = EquationOfState(volumes, energies) v1, ef, B = eos.fit() latticeconstant = v1**(1. / 3) # Calculate the heat of formation by subtracting ef with ei hof = (ef - ei) / len(atoms) # Place the calculated parameters in the info dictionary of the # input_atoms object input_atoms.info['key_value_pairs']['hof'] = hof # Raw score must always be set # Use one of the following two; they are equivalent input_atoms.info['key_value_pairs']['raw_score'] = -hof # set_raw_score(input_atoms, -hof) input_atoms.info['key_value_pairs']['latticeconstant'] = latticeconstant # Setting the atoms_string directly for easier analysis atoms_string = ''.join(input_atoms.get_chemical_symbols()) input_atoms.info['key_value_pairs']['atoms_string'] = atoms_string
def test_maxwellboltzmann(): from ase.md.velocitydistribution import MaxwellBoltzmannDistribution from ase.lattice.cubic import FaceCenteredCubic atoms = FaceCenteredCubic(size=(50, 50, 50), symbol="Cu", pbc=False) print("Number of atoms:", len(atoms)) MaxwellBoltzmannDistribution(atoms, temperature_K=0.1 / kB) temp = atoms.get_kinetic_energy() / (1.5 * len(atoms)) print("Temperature", temp, " (should be 0.1)") assert abs(temp - 0.1) < 1e-3
def test_hessian_sparse(self): for calc in [{(1, 1): LennardJonesCut(1, 1, 3)}]: atoms = FaceCenteredCubic('H', size=[2, 2, 2], latticeconstant=1.550) a = calculator.PairPotential(calc) atoms.set_calculator(a) H_analytical = a.calculate_hessian_matrix(atoms, "sparse") H_numerical = fd_hessian(atoms, dx=1e-5, indices=None) self.assertArrayAlmostEqual(H_analytical.todense(), H_numerical.todense(), tol=self.tol)
def test_stress(self): a = FaceCenteredCubic('Au', size=[2,2,2]) calc = EAM('Au-Grochola-JCP05.eam.alloy') a.set_calculator(calc) self.assertArrayAlmostEqual(a.get_stress(), calc.calculate_numerical_stress(a), tol=self.tol) sx, sy, sz = a.cell.diagonal() a.set_cell([sx, 0.9*sy, 1.2*sz], scale_atoms=True) self.assertArrayAlmostEqual(a.get_stress(), calc.calculate_numerical_stress(a), tol=self.tol) a.set_cell([[sx, 0.1*sx, 0], [0, 0.9*sy, 0], [0, -0.1*sy, 1.2*sz]], scale_atoms=True) self.assertArrayAlmostEqual(a.get_stress(), calc.calculate_numerical_stress(a), tol=self.tol)
def test_Grochola(self): a = FaceCenteredCubic('Au', size=[2,2,2]) calc = EAM('Au-Grochola-JCP05.eam.alloy') a.set_calculator(calc) FIRE(StrainFilter(a, mask=[1,1,1,0,0,0]), logfile=None).run(fmax=0.001) a0 = a.cell.diagonal().mean()/2 self.assertTrue(abs(a0-4.0701)<2e-5) self.assertTrue(abs(a.get_potential_energy()/len(a)+3.924)<0.0003) C, C_err = fit_elastic_constants(a, symmetry='cubic', verbose=False) C11, C12, C44 = Voigt_6x6_to_cubic(C) self.assertTrue(abs((C11-C12)/GPa-32.07)<0.7) self.assertTrue(abs(C44/GPa-45.94)<0.5)
def MakeCu(T=300, size=(29,29,30)): print "Preparing", T, "K Copper system." atoms = FaceCenteredCubic(directions=[[1,0,0],[0,1,0],[0,0,1]], symbol='Cu', size=size) atoms.set_calculator(EMT()) MaxwellBoltzmannDistribution(atoms, 2*T * units.kB) #dyn = VelocityVerlet(atoms, 5*units.fs) dyn = Langevin(atoms, 5*units.fs, T*units.kB, 0.05) dyn.run(50) print "Done. Temperature =", temperature(atoms), \ "K. Number of atoms: ", len(atoms) return atoms
def test_forces_random_structure(self): atoms = FaceCenteredCubic('H', size=[2,2,2], latticeconstant=2.37126) calc = Polydisperse(InversePowerLawPotential(1.0, 1.4, 0.1, 3, 1, 2.22)) atoms.set_masses(masses=np.repeat(1.0, len(atoms))) atoms.set_array("size", np.random.uniform(1.0, 2.22, size=len(atoms)), dtype=float) atoms.set_calculator(calc) f = atoms.get_forces() fn = calc.calculate_numerical_forces(atoms, d=0.0001) self.assertArrayAlmostEqual(f, fn, tol=self.tol)
def MakeCu(T=300, size=(29, 29, 30)): print "Preparing", T, "K Copper system." atoms = FaceCenteredCubic(directions=[[1, 0, 0], [0, 1, 0], [0, 0, 1]], symbol='Cu', size=size) atoms.set_calculator(EMT()) MaxwellBoltzmannDistribution(atoms, 2 * T * units.kB) #dyn = VelocityVerlet(atoms, 5*units.fs) dyn = Langevin(atoms, 5 * units.fs, T * units.kB, 0.05) dyn.run(50) print "Done. Temperature =", temperature(atoms), \ "K. Number of atoms: ", len(atoms) return atoms
def test_symmetry_sparse(self): for calc in [{(1, 1): LennardJonesCut(1, 1, 3)}]: atoms = FaceCenteredCubic('H', size=[2, 2, 2], latticeconstant=1.550) a = calculator.PairPotential(calc) atoms.set_calculator(a) H_numerical = fd_hessian(atoms, dx=1e-5, indices=None) H_numerical = H_numerical.todense() self.assertArrayAlmostEqual(np.sum( np.abs(H_numerical - H_numerical.T)), 0, tol=1e-5)
def makePerturbedLattice(self, shape=(2,2,2)): """ to make perturbed bulk structure lattice positions """ a = self.getFCCLattice() slab = FaceCenteredCubic(size = shape, symbol=self.element, latticeconstant=a) positions=slab.get_positions() perturbations = numpy.random.standard_normal(scipy.shape(positions))*a*0.05 positions += perturbations return positions
def test_antisymmetry(): size = 2 atoms = FaceCenteredCubic(size=[size, size, size], symbol='Cu', latticeconstant=2, pbc=(1, 1, 1)) vmin, vlen = get_distances(atoms.get_positions(), cell=atoms.cell, pbc=True) assert (vlen == vlen.T).all() for i, j in itertools.combinations(range(len(atoms)), 2): assert (vmin[i, j] == -vmin[j, i]).all()
def test_calcenergy(self): atoms = FaceCenteredCubic(directions=[[1, 0, 0], [0, 1, 0], [0, 0, 1]], symbol="Cu", size=(3, 3, 3), pbc=True) atoms.calc = EMT() ekin, epot = calcenergy(atoms) if ekin is not None and epot is not None: self.assertTrue(True) else: self.assertTrue(False)
def fcc211(symbol, size, a=None, vacuum=None, orthogonal=True): """FCC(211) surface. Does not currently support special adsorption sites. Currently only implemented for *orthogonal=True* with size specified as (i, j, k), where i, j, and k are number of atoms in each direction. i must be divisible by 3 to accommodate the step width. """ if not orthogonal: raise NotImplementedError('Only implemented for orthogonal ' 'unit cells.') if size[0] % 3 != 0: raise NotImplementedError('First dimension of size must be ' 'divisible by 3.') atoms = FaceCenteredCubic(symbol, directions=[[1, -1, -1], [0, 2, -2], [2, 1, 1]], miller=(None, None, (2, 1, 1)), latticeconstant=a, size=(1, 1, 1), pbc=True) z = (size[2] + 1) // 2 atoms = atoms.repeat((size[0] // 3, size[1], z)) if size[2] % 2: # Odd: remove bottom layer and shrink cell. remove_list = [atom.index for atom in atoms if atom.z < atoms[1].z] del atoms[remove_list] dz = atoms[0].z atoms.translate((0., 0., -dz)) atoms.cell[2][2] -= dz atoms.cell[2] = 0.0 atoms.pbc[2] = False if vacuum: atoms.center(vacuum, axis=2) # Renumber systematically from top down. orders = [(atom.index, round(atom.x, 3), round(atom.y, 3), -round(atom.z, 3), atom.index) for atom in atoms] orders.sort(key=itemgetter(3, 1, 2)) newatoms = atoms.copy() for index, order in enumerate(orders): newatoms[index].position = atoms[order[0]].position.copy() # Add empty 'sites' dictionary for consistency with other functions newatoms.info['adsorbate_info'] = {'sites': {}} return newatoms
def test_energy_forces_stress(): """ To test that the calculator can produce correct energy and forces. This is done by comparing the energy for an FCC argon lattice with an example model to the known value; the forces/stress returned by the model are compared to numerical estimates via finite difference. """ import numpy as np from pytest import importorskip importorskip('kimpy') from ase.calculators.kim import KIM from ase.lattice.cubic import FaceCenteredCubic # Create an FCC atoms crystal atoms = FaceCenteredCubic( directions=[[1, 0, 0], [0, 1, 0], [0, 0, 1]], size=(1, 1, 1), symbol="Ar", pbc=(1, 0, 0), latticeconstant=3.0, ) # Perturb the x coordinate of the first atom by less than the cutoff distance atoms.positions[0, 0] += 0.01 calc = KIM("ex_model_Ar_P_Morse_07C") atoms.calc = calc # Get energy and analytical forces/stress from KIM model energy = atoms.get_potential_energy() forces = atoms.get_forces() stress = atoms.get_stress() # Previously computed energy for this configuration for this model energy_ref = 19.7196709065 # eV # Compute forces and virial stress numerically forces_numer = calc.calculate_numerical_forces(atoms, d=0.0001) stress_numer = calc.calculate_numerical_stress(atoms, d=0.0001, voigt=True) tol = 1e-6 assert np.isclose(energy, energy_ref, tol) assert np.allclose(forces, forces_numer, tol) assert np.allclose(stress, stress_numer, tol) # This has been known to segfault atoms.set_pbc(True) atoms.get_potential_energy()
def test_matplotlib_plot(plt): slab = FaceCenteredCubic('Au', size=(2, 2, 2)) fig, ax = plt.subplots() plot_atoms(slab, ax, radii=0.5, rotation=('10x,10y,10z'), show_unit_cell=0) assert len(ax.patches) == len(slab)
def setCrystal(self): crys = self.setting['structure'] if crys == 'rnd': print 'rnd implemented' self.genRandomPositions() d = 1.104 # N2 bondlength formula = 'Cu'+str(len(self.pos)) cell =[(self.px*self.a0,0,0),(0,self.py*self.a0,0),(0,0,self.pz*self.a0)] self.bulk = ase.Atoms(formula, self.pos, pbc=True, cell=cell) if crys == 'fcc': print 'fcc implemented' from ase.lattice.cubic import FaceCenteredCubic self.bulk = FaceCenteredCubic(directions=[[1,0,0], [0,1,0], [0,0,1]], size=(self.px,self.py,self.pz), symbol='Cu', pbc=(1,1,1), latticeconstant=self.a0) if crys == 'bcc': print 'bcc implemented' from ase.lattice.cubic import BodyCenteredCubic self.bulk = BodyCenteredCubic(directions=[[1,0,0], [0,1,0], [0,0,1]], size=(self.px,self.py,self.pz), symbol='Cu', pbc=(1,1,1), latticeconstant=self.a0) if self.setting['structure'] == 'hcp': print 'hcp no implemented' sys.exit(0) self.setting['nAtoms'] = self.bulk.get_number_of_atoms() self.calcAtoms2() self.genStructure() self.pos = self.bulk.get_positions()
def test_rotation(self): for make_atoms, calc in [ # ( lambda a0,x : # FaceCenteredCubic('He', size=[1,1,1], # latticeconstant=3.5 if a0 is None else a0, # directions=x), # LJCut(epsilon=10.2, sigma=2.28, cutoff=5.0, shift=True) ), ( lambda a0,x : FaceCenteredCubic('Au', size=[1,1,1], latticeconstant=a0, directions=x), EAM('Au-Grochola-JCP05.eam.alloy') ), # ( lambda a0,x : Diamond('Si', size=[1,1,1], latticeconstant=a0, # directions=x), # Kumagai() ) #( lambda a0,x : FaceCenteredCubic('Au', size=[1,1,1], # latticeconstant=a0, directions=x), # EAM(potential='Au-Grochola-JCP05.eam.alloy') ), ]: a = make_atoms(None, [[1,0,0], [0,1,0], [0,0,1]]) a.set_calculator(calc) FIRE(StrainFilter(a, mask=[1,1,1,0,0,0]), logfile=None) \ .run(fmax=self.fmax) latticeconstant = np.mean(a.cell.diagonal()) C6 = measure_triclinic_elastic_constants(a, delta=self.delta, fmax=self.fmax) C11, C12, C44 = Voigt_6x6_to_cubic(C6)/GPa el = CubicElasticModuli(C11, C12, C44) C_m = measure_triclinic_elastic_constants(a, delta=self.delta, fmax=self.fmax)/GPa self.assertArrayAlmostEqual(el.stiffness(), C_m, tol=0.01) for directions in [ [[1,0,0], [0,1,0], [0,0,1]], [[0,1,0], [0,0,1], [1,0,0]], [[1,1,0], [0,0,1], [1,-1,0]], [[1,1,1], [-1,-1,2], [1,-1,0]] ]: a, b, c = directions directions = np.array([ np.array(x)/np.linalg.norm(x) for x in directions ]) a = make_atoms(latticeconstant, directions) a.set_calculator(calc) C = el.rotate(directions) C_check = el._rotate_explicit(directions) C_check2 = rotate_cubic_elastic_constants(C11, C12, C44, directions) C_check3 = \ rotate_elastic_constants(cubic_to_Voigt_6x6(C11, C12, C44), directions) self.assertArrayAlmostEqual(C, C_check, tol=1e-6) self.assertArrayAlmostEqual(C, C_check2, tol=1e-6) self.assertArrayAlmostEqual(C, C_check3, tol=1e-6) C_m = measure_triclinic_elastic_constants(a, delta=self.delta, fmax=self.fmax)/GPa self.assertArrayAlmostEqual(C, C_m, tol=1e-2)
def __init__(self, size, centers, rotations, delta=0.0, min=2.0, unit=None, symbol=None, latticeconstant=None): try: assert len(size) == 3 except TypeError: # Not a sequence size = (size, size, size) self.size = np.array(size) assert self.size.shape == (3, ) self.centers = centers self.rotations = rotations self.delta = delta self.min = min assert len(centers) == len(rotations) self.centers *= self.size if unit is None: unit = FaceCenteredCubic(symbol=symbol, size=(1, 1, 1), pbc=True, latticeconstant=latticeconstant) self.unit = unit
def test_funcfl(self): """Test eam kind 'eam' (DYNAMO funcfl format) variable da equal 0.02775 variable amin equal 2.29888527117067752084 variable amax equal 5.55*sqrt(2.0) variable i loop 201 label loop_head clear variable lattice_parameter equal ${amin}+${da}*${i} units metal atom_style atomic boundary p p p lattice fcc ${lattice_parameter} region box block 0 5 0 5 0 5 create_box 1 box pair_style eam pair_coeff * * Au_u3.eam create_atoms 1 box thermo 1 run 0 variable x equal pe variable potential_energy_fmt format x "%.14f" print "#a,E: ${lattice_parameter} ${potential_energy_fmt}" next i jump SELF loop_head # use # grep '^#a,E' log.lammps | awk '{print $2,$3}' > aE.txt # to extract info from log file The reference data was calculated using Lammps (git commit a73f1d4f037f670cd4295ecc1a576399a31680d2). """ da = 0.02775 amin = 2.29888527117067752084 amax = 5.55 * np.sqrt(2.0) for i in range(1, 202): latticeconstant = amin + i * da atoms = FaceCenteredCubic(symbol='Au', size=[5, 5, 5], pbc=(1, 1, 1), latticeconstant=latticeconstant) calc = EAM('Au-Grochola-JCP05.eam.alloy') atoms.set_calculator(calc) energy = atoms.get_potential_energy() print(energy)
def test_numpy_array(): # Tests Issue #787 atoms = FaceCenteredCubic(size=[1, 1, 1], symbol='Cu', latticeconstant=2, pbc=True) find_mic(atoms.positions, np.array(atoms.cell), pbc=True)
def main(): for x in fccs+bccs+hcps+diamonds+rocksalts+zincblendes+cscls: f = x in fccs b = x in bccs h = x in hcps d = x in diamonds r = x in rocksalts z = x in zincblendes c = x in cscls try: if f: a = FaceCenteredCubic(x[0]).get_cell()[0][0]/2 elif b: a = BodyCenteredCubic(x[0]).get_cell()[0][0]/2 elif d: a = Diamond(x[0]).get_cell()[0][0]/2 elif h: cell = HexagonalClosedPacked(x[0]).get_cell() a,c = cell[0][0],cell[2][2] elif r | z | c: a = dataLookup(x[0]) else: raise NotImplementedError except ValueError: a = sum([radDict[e] for e in elems])/len(elems) print "Had to guess lattice constant of "+x[0] if f: name,struc,pos,cell,n = '-fcc', 'fcc', [[0,0,0]], [[0,a,a],[a,0,a],[a,a,0]], 1 elif b: name,struc,pos,cell,n = '-bcc', 'bcc', [[0,0,0]], [[a,a,-a],[-a,a,a],[a,-a,a]],1 elif h: name,struc,pos,cell,n = '-hcp', 'hexagonal', [[0,0,0],[2./3,1./3,1./2]], [a,a,c,90,90,120], 2 elif d: name,struc,pos,cell,n = '-diamond', 'diamond', [[0,0,0],[0.25,0.25,0.25]], [[0,a,a],[a,0,a],[a,a,0]], 2 elif z: name,struc,pos,cell,n = '-zincblende','zincblende', [[0,0,0],[0.25,0.25,0.25]], [[0,a,a],[a,0,a],[a,a,0]], 1 elif r: name,struc,pos,cell,n = '-rocksalt', 'rocksalt', [[0,0,0],[0.5,0.5,0.5]], [[0,a,a],[a,0,a],[a,a,0]], 1 elif c: name,struc,pos,cell,n = '-cscl', 'cubic', [[0,0,0],[0.5,0.5,0.5]], [a,a,a,90,90,90], 1 mag = magLookup(x[0]) elems = parseChemicalFormula(x[0]).keys()*n magmoms = [magmomInit if e in magElems else 0 for e in elems] atoms = Atoms(elems,scaled_positions=pos,cell=cell,pbc=[1,1,1],magmoms=magmoms,calculator=EMT()) info = {'name': x[0]+name ,'relaxed': False ,'emt': atoms.get_potential_energy()/len(elems) #normalized to per-atom basis ,'comments': 'Autogenerated by createTrajs' ,'kind': 'bulk' # vs surface/molecules ### Stuff for bulk ,'structure': struc ### Stuff for surfaces ,'parent': None ,'sites': None ,'facet': None ,'xy': None ,'layers': None ,'constrained': None ,'symmetric': None ,'vacuum': None ,'adsorbates': None} db.write(atoms,key_value_pairs=info)
def C44_Calculator(self, EMT, PARAMETERS): # Return 0 is used when the method is not desired to be used # return 0 """ This method uses the given EMT calculator to calculate and return the value of the matrix element C44 for a system of atoms of a given element type. The calculation is done by using that: C44 = 1 / Volume * d^2/depsilon^2 (E_system) where epsilon is the displacement in one direction of the system along one axis diveded by the highth of the system. """ # An atom object is created and the calculator attached atoms = FaceCenteredCubic(size=(self.Size, self.Size, self.Size), symbol=self.Element) atoms.set_calculator(EMT) # The volume of the sample is calculated Vol = atoms.get_volume() # The value of the relative displacement, epsilon, is set epsilon = 1. / 1000 # The matrix used to change the unitcell by n*epsilon is initialized LMM = numpy.array([[1, 0, -10 * epsilon], [0, 1, 0], [0, 0, 1]]) # The original unit cell is conserved OCell = atoms.get_cell() # The array for storing the energies is initialized E_calc = numpy.zeros(20) # The numerical value of C44 is calculated for i in range(20): # The new system cell based on the pertubation epsilon is set atoms.set_cell(numpy.dot(OCell, LMM), scale_atoms=True) # The energy of the system is calculated E_calc[i] = atoms.get_potential_energy() # The value of LMM is updated LMM[0, 2] += epsilon # A polynomial fit is made for the energy as a function of epsilon # The displaced axis is defined da = numpy.arange(-10, 10) * epsilon # The fit is made Poly = numpyfit.polyfit(da, E_calc, 2) # Now C44 can be estimated from this fit by the second derivative of Poly = a * x^2 + b * x + c , multiplied # with 1 / (2 * Volume) of system C44 = 2. / Vol * Poly[0] return C44
def MakeAtoms(elem1, elem2=None): if elem2 is None: elem2 = elem1 a1 = reference_states[elem1]['a'] a2 = reference_states[elem2]['a'] a0 = (0.5 * a1**3 + 0.5 * a2**3)**(1.0/3.0) * 1.03 if ismaster: # 50*50*50 would be big enough, but some vacancies are nice. print "Z1 = %i, Z2 = %i, a0 = %.5f" % (elem1, elem2, a0) atoms = FaceCenteredCubic(symbol='Cu', size=(51,51,51)) nremove = len(atoms) - 500000 assert nremove > 0 remove = np.random.choice(len(atoms), nremove, replace=False) del atoms[remove] if isparallel: atoms = atoms.repeat(cpuLayout) if elem1 != elem2: z = atoms.get_atomic_numbers() z[np.random.choice(len(atoms), len(atoms)/2, replace=False)] = elem2 atoms.set_atomic_numbers(z) else: atoms = None if isparallel: atoms = MakeParallelAtoms(atoms, cpuLayout) MaxwellBoltzmannDistribution(atoms, T * units.kB) return atoms
def test_hessian_monoatomic(self): """Calculate Hessian matrix of pure Cu Reference: finite difference approximation of Hessian from ASE """ atoms = FaceCenteredCubic('Cu', size=[4, 4, 4]) calculator = EAM('CuAg.eam.alloy') self._test_hessian(atoms, calculator)
def create_fcc_argon(alat=5.26): argon = FaceCenteredCubic( directions=[[1, 0, 0], [0, 1, 0], [0, 0, 1]], size=(2, 2, 2), symbol='Ar', pbc=(0, 0, 0), latticeconstant=alat, ) return argon
def make_fcc_110_cell(size=(1, 1, 1), symbols=['Ni'], pbc=(1, 1, 1)): direction_x = [0, 0, 1] direction_y = [1, -1, 0] direction_z = [1, 1, 0] atoms = FaceCenteredCubic(\ directions=[direction_x,direction_y,direction_z], size=size, symbol=symbols[0], pbc=pbc) return atoms
def fcc211(symbol, size, a=None, vacuum=None, orthogonal=True): """FCC(211) surface. Does not currently support special adsorption sites. Currently only implemented for *orthogonal=True* with size specified as (i, j, k), where i, j, and k are number of atoms in each direction. i must be divisible by 3 to accommodate the step width. """ if not orthogonal: raise NotImplementedError('Only implemented for orthogonal ' 'unit cells.') if size[0] % 3 != 0: raise NotImplementedError('First dimension of size must be ' 'divisible by 3.') atoms = FaceCenteredCubic(symbol, directions=[[1, -1, -1], [0, 2, -2], [2, 1, 1]], miller=(None, None, (2, 1, 1)), latticeconstant=a, size=(1, 1, 1), pbc=True) z = (size[2] + 1) // 2 atoms = atoms.repeat((size[0] // 3, size[1], z)) if size[2] % 2: # Odd: remove bottom layer and shrink cell. remove_list = [atom.index for atom in atoms if atom.z < atoms[1].z] del atoms[remove_list] dz = atoms[0].z atoms.translate((0., 0., -dz)) atoms.cell[2][2] -= dz atoms.cell[2] = 0.0 atoms.pbc[1] = False if vacuum: atoms.center(vacuum, axis=2) # Renumber systematically from top down. orders = [(atom.index, round(atom.x, 3), round(atom.y, 3), -round(atom.z, 3), atom.index) for atom in atoms] orders.sort(key=itemgetter(3, 1, 2)) newatoms = atoms.copy() for index, order in enumerate(orders): newatoms[index].position = atoms[order[0]].position.copy() return newatoms
def test_matplotlib_plot(plt): from ase.visualize.plot import plot_atoms from ase.lattice.cubic import FaceCenteredCubic slab = FaceCenteredCubic('Au', size=(2, 2, 2)) fig, ax = plt.subplots() plot_atoms(slab, ax, radii=0.5, rotation=('10x,10y,10z'), show_unit_cell=0) assert len(ax.patches) == len(slab) print(ax)
def myfcc(symbol, pbc): "Make an fcc lattice with standard lattice constant" if ismaster: a = FaceCenteredCubic(symbol=symbol, size=(10,10,10), pbc=pbc) dx = 0.01 * np.sin(0.1 * np.arange(len(a) * 3)) dx.shape = (len(a),3) a.set_positions(a.get_positions() + dx) a.set_momenta(np.zeros((len(a),3))) #view(a) else: a = None if isparallel: a = MakeParallelAtoms(a, cpulayout) return a
from ase.lattice.cubic import FaceCenteredCubic from ase.md.velocitydistribution import MaxwellBoltzmannDistribution from ase.md.verlet import VelocityVerlet from ase import units # Use Asap for a huge performance increase if it is installed useAsap = False if useAsap: from asap3 import EMT size = 10 else: size = 3 # Set up a crystal atoms = FaceCenteredCubic(directions=[[1,0,0],[0,1,0],[0,0,1]], symbol="Cu", size=(size,size,size), pbc=True) # Describe the interatomic interactions with the Effective Medium Theory atoms.set_calculator(EMT()) # Set the momenta corresponding to T=300K MaxwellBoltzmannDistribution(atoms, 300*units.kB) # We want to run MD with constant energy using the VelocityVerlet algorithm. dyn = VelocityVerlet(atoms, 5*units.fs) # 5 fs time step. #Function to print the potential, kinetic and total energy def printenergy(a): epot = a.get_potential_energy() / len(a) ekin = a.get_kinetic_energy() / len(a) print ("Energy per atom: Epot = %.3feV Ekin = %.3feV (T=%3.0fK) Etot = %.3feV" %
import numpy as np from ase.lattice.cubic import FaceCenteredCubic from ase.calculators.emt import EMT from ase.utils.eos import EquationOfState from ase.db import connect db = connect('refs.db') metals = ['Al', 'Au', 'Cu', 'Ag', 'Pd', 'Pt', 'Ni'] for m in metals: atoms = FaceCenteredCubic(m) atoms.set_calculator(EMT()) e0 = atoms.get_potential_energy() a = atoms.cell[0][0] eps = 0.05 volumes = (a * np.linspace(1 - eps, 1 + eps, 9))**3 energies = [] for v in volumes: atoms.set_cell([v**(1. / 3)] * 3, scale_atoms=True) energies.append(atoms.get_potential_energy()) eos = EquationOfState(volumes, energies) v1, e1, B = eos.fit() atoms.set_cell([v1**(1. / 3)] * 3, scale_atoms=True) ef = atoms.get_potential_energy() db.write(atoms, metal=m, latticeconstant=v1**(1. / 3),
if len(sys.argv) == 2: arg = sys.argv[1] else: arg = 'Wrong number of arguments.' if arg == 'EMT': filename = 'small_EMT.dat' elif arg == 'EMT2013': filename = 'small_EMT2013.dat' else: print __doc__ sys.exit(1) T = 450 atoms = FaceCenteredCubic(size=(10,10,10), symbol='Cu', pbc=False) if arg == 'EMT': atoms.set_calculator(EMT()) else: atoms.set_calculator(EMT2013(EMT2013_parameters)) print "Setting temperature:", T, "K" MaxwellBoltzmannDistribution(atoms, 2*T*units.kB) Stationary(atoms) dyn1 = Langevin(atoms, 2*units.fs, temperature=T*units.kB, friction=0.05) dyn1.run(200) dyn = VelocityVerlet(atoms, 3*units.fs, logfile=filename, loginterval=25) dyn.run(10000000) # 10^7 timesteps is 3 ns.
catoi = float(sys.argv[4]) species = [el1] import model from model import pick_elements pick_elements(model, species) from ase.calculators.lammps import LAMMPS calc = LAMMPS(parameters=model.parameters, files=model.files, specorder=species) if str == "fcc": from ase.lattice.cubic import FaceCenteredCubic atoms = FaceCenteredCubic(symbol=el1, latticeconstant=lp, size=(5, 5, 5)) elif str == "bcc": from ase.lattice.cubic import BodyCenteredCubic atoms = BodyCenteredCubic(symbol=el1, latticeconstant=lp, size=(5, 5, 5)) elif str == "dia": from ase.lattice.cubic import Diamond atoms = Diamond(symbol=el1, latticeconstant=lp, size=(3, 3, 3)) elif str == "hcp": from math import sqrt a = lp b = sqrt(3.0) * lp c = lp * sqrt(8.0 / 3.0) * catoi # this did not work
conv = {'eigenstates' : 1e-4, 'density' : 1e-2, 'energy' : 1e-3} # output benchmark parameters if rank == 0: print("#"*60) print("GPAW benchmark: Copper Sheet") print(" dimensions: x=%d, y=%d, z=%d" % (x, y, z)) print(" grid spacing: h=%f" % h) print(" Brillouin-zone sampling: kpts=" + str(kpts)) print(" MPI task: %d out of %d" % (rank, size)) print(" using MICs: " + str(use_mic)) print("#"*60) print("") # setup the system atoms = FaceCenteredCubic(directions=[[1,-1,0], [1,1,-2], [1,1,1]], size=(x,y,z), symbol='Cu', pbc=(1,1,0)) #add_vacuum(atoms, 10.0) atoms.center(vacuum=6.0, axis=2) calc = GPAW(h=h, nbands=-20, width=0.2, kpts=kpts, xc='PBE', maxiter=maxiter, txt=txt, eigensolver=RMM_DIIS(niter=2), parallel={'sl_auto': True}, mixer=Mixer(0.1, 5, 100), ) atoms.set_calculator(calc) # execute the run try: atoms.get_potential_energy() except ConvergenceError:
from __future__ import print_function, division from ase.lattice.cubic import FaceCenteredCubic from ase.lattice.hexagonal import HexagonalClosedPacked from ase.test import must_raise with must_raise(ValueError): # The Miller indices of the surfaces are linearly dependent atoms = FaceCenteredCubic(symbol='Cu', miller=[[1, 1, 0], [1, 1, 0], [0, 0, 1]]) # This one should be OK: atoms = FaceCenteredCubic(symbol='Cu', miller=[[1, 1, 0], [0, 1, 0], [0, 0, 1]]) print(atoms.get_cell()) with must_raise(ValueError): # The directions spanning the unit cell are linearly dependent atoms = FaceCenteredCubic(symbol='Cu', directions=[[1, 1, 0], [1, 1, 0], [0, 0, 1]]) with must_raise(ValueError): # The directions spanning the unit cell are linearly dependent atoms = FaceCenteredCubic(symbol='Cu', directions=[[1, 1, 0], [1, 0, 0], [0, 1, 0]]) # This one should be OK: atoms = FaceCenteredCubic(symbol='Cu', directions=[[1, 1, 0], [0, 1, 0], [0, 0, 1]]) print(atoms.get_cell())
ncpu = world.size if ncpu == 1: layout = (1,1,1) elif ncpu == 2: layout = (2,1,1) elif ncpu == 4: layout = (2,2,1) elif ncpu == 8: layout = (2,2,2) else: raise ValueError("Cannot run on %i CPUs." % ncpu) if cmd == "M": if world.rank == 0: atoms = FaceCenteredCubic(size=size*layout, symbol='Cu') else: atoms = None atoms = MakeParallelAtoms(atoms, layout) else: atoms = FaceCenteredCubic(size=size*layout, symbol='Cu') atoms.set_calculator(EMT()) natoms = atoms.get_number_of_atoms() print "Number of atoms:", natoms assert natoms == ncpu * 500000 print "Potential energy:", atoms.get_potential_energy() start = time.time() d = 0.1
catoi = float(sys.argv[5]) print "bulk: ", el1, str, lp print "interst: ", el1 species = [el1] import model from model import pick_elements pick_elements(model, species) from ase.calculators.lammps import LAMMPS calc = LAMMPS(parameters=model.parameters, files=model.files) if str == "fcc" : from ase.lattice.cubic import FaceCenteredCubic atoms = FaceCenteredCubic(symbol=el1,latticeconstant=lp,size=(5,5,5)) elif str == "bcc" : from ase.lattice.cubic import BodyCenteredCubic atoms = BodyCenteredCubic(symbol=el1,latticeconstant=lp,size=(5,5,5)) elif str == "dia" : from ase.lattice.cubic import Diamond atoms = Diamond(symbol=el1,latticeconstant=lp,size=(3,3,3)) elif str == "hcp" : from math import sqrt a=lp b=sqrt(3.)*lp c=lp*sqrt(8./3.)*catoi # this did not work # maybe wrong setting of LAMMPS volume optimization for triclinic cell # from ase.lattice.hexagonal import HexagonalClosedPacked # atoms = HexagonalClosedPacked(symbol=el1,latticeconstant=(lp,c),size=(5,5,5))
print_version(1) #set_verbose(1) ismaster = world.rank == 0 isparallel = world.size != 1 if world.size == 1: cpulayout = None elif world.size == 2: cpulayout = [2,1,1] elif world.size == 3: cpulayout = [1,3,1] elif world.size == 4: cpulayout = [2,1,2] if ismaster: init = FaceCenteredCubic(size=(10,10,10), symbol='Cu', pbc=False) z = init.get_positions()[:,2] fixedatoms = np.less(z, 0.501*z.max()) print len(init), sum(fixedatoms) MaxwellBoltzmannDistribution(init, 6000*units.kB) init.set_tags(fixedatoms) else: init = None print print "Running simulation with Filter" atoms1 = MakeParallelAtoms(init, cpulayout) atoms1.arrays['r_init'] = atoms1.get_positions() atoms1.set_calculator(EMT()) atoms1a = Filter(atoms1, mask=np.logical_not(atoms1.get_tags()))
# Set up atoms in a regular simple-cubic lattice. ismaster = world.rank == 0 isparallel = world.size != 1 if world.size == 1: cpulayout = None elif world.size == 2: cpulayout = [1,2,1] elif world.size == 3: cpulayout = [1,3,1] elif world.size == 4: cpulayout = [1,2,2] print_version(1) if ismaster: atoms = FaceCenteredCubic(size=(2,10,10), symbol="Cu", pbc=False, latticeconstant = 3.5) else: atoms = None if isparallel: atoms = MakeParallelAtoms(atoms, cpulayout) atoms.set_calculator(asap3.EMT()) natoms = atoms.get_number_of_atoms() ReportTest("Number of atoms", natoms, 800, 0) # Make a small perturbation of the momenta atoms.set_momenta(1e-6 * random.random([len(atoms), 3])) print "Initializing ..." predyn = VelocityVerlet(atoms, 0.5) try:
from jasp import * from ase.lattice.cubic import FaceCenteredCubic from ase.dft import DOS atoms = FaceCenteredCubic(directions=[[0,1,1], [1,0,1], [1,1,0]], size=(1,1,1), symbol='Ni') atoms[0].magmom = 1 with jasp('bulk/Ni-PBE', ismear=-5, kpts=(5,5,5), xc='PBE', ispin=2,lorbit=11, atoms=atoms) as calc: print 'PBE energy: ',atoms.get_potential_energy() dos = DOS(calc, width=0.2) e_pbe = dos.get_energies() d_pbe = dos.get_dos() calc.clone('bulk/Ni-PBE0') calc.clone('bulk/Ni-HSE06') with jasp('bulk/Ni-PBE0') as calc: calc.set(lhfcalc=True, algo='D', time=0.4) atoms = calc.get_atoms() print 'PBE0 energy: ',atoms.get_potential_energy() dos = DOS(calc, width=0.2) e_pbe0 = dos.get_energies() d_pbe0 = dos.get_dos() with jasp('bulk/Ni-HSE06') as calc:
#! /usr/bin/env python import numpy as np from ase.constraints import UnitCellFilter from ase.lattice.cubic import FaceCenteredCubic from ase.optimize import FIRE from ase.utils.eos import EquationOfState from atomistica import TabulatedAlloyEAM ### n = 2 a = FaceCenteredCubic('Au', size=[n, n, n]) x0 = a.cell[0, 0]/n c = TabulatedAlloyEAM(fn='Au-Grochola-JCP05.eam.alloy') a.set_calculator(c) # Vary volume and fit minimum def en(a, x): a.set_cell([x, x, x], scale_atoms=True) return a.get_potential_energy() x = np.linspace(0.9*x0, 1.1*x0, 101) e = [ en(a, n*_x)/(n**3) for _x in x ] eos = EquationOfState(x**3, e) v0, e0, B = eos.fit() print 'lattice constant (from equation of state) =', v0**(1./3) # Keep cell rectangular during optimization
j = int(jj) ReportTest.BoolTest("Atom %d on list %d (forward)" % (j, i), j in fnb[i], silent=True) ReportTest.BoolTest("Atom %d on list %d (reverse)" % (i, j), i in fnb[j], silent=True) if ReportTest.GetNumberOfErrors() > 10: print "*** Too many errors - giving up! ***" break print_version(1) element = "Cu" latconst = ase.data.reference_states[ase.data.atomic_numbers[element]]['a'] atoms = FaceCenteredCubic(directions=[[1,0,0],[0,1,1],[0,0,1]], size=(9,7,5), symbol=element, debug=0) atoms.set_calculator(EMT(minimum_image=True)) epot = atoms.get_potential_energy() nblist = atoms.get_calculator().get_neighborlist() count = {} for lst in nblist: n = len(lst) try: count[n] += 1 except KeyError: count[n] = 1 # print "Histogram:" numbers = count.keys() numbers.sort() sum = 0
targettime = 30.0 laststeps = 5000 lastsize = sizes[0] lasttime = targettime results = {} for nthreads in threads: try: AsapThreads(nthreads) except ValueError: break maxthread = nthreads for natoms in sizes: print "Timing with %i atoms (%i threads)" % (natoms, nthreads) blocksize = int(np.ceil((natoms/4)**(1./3.))) atoms = FaceCenteredCubic(symbol='Cu', size=(blocksize,blocksize,blocksize), pbc=False) print "Creating block with %i atoms, cutting to %i atoms" % (len(atoms), natoms) atoms = atoms[:natoms] assert len(atoms) == natoms atoms.set_calculator(EMT()) MaxwellBoltzmannDistribution(atoms, 2 * T * units.kB) dyn = VelocityVerlet(atoms, 5*units.fs) ptsteps = int(laststeps * (0.1 * targettime / lasttime) * lastsize / natoms) if ptsteps < 100: ptsteps = 100 print "Running pre-timing (%i steps)..." % (ptsteps,) t1 = time.time() dyn.run(ptsteps - 50) MaxwellBoltzmannDistribution(atoms, (2 * T - atoms.get_temperature()) * units.kB) dyn.run(50) t1 = time.time() - t1
"""Test force calculations alone with the purpose of optimizing threading.""" from asap3 import * from asap3.Timing import report_timing from ase.lattice.cubic import FaceCenteredCubic import time nsteps = 10 start = time.time() if len(sys.argv) >= 2 and sys.argv[1] == '-t': AsapThreads() if len(sys.argv) >= 2 and sys.argv[1] == '-T': AsapThreads(6) atoms = FaceCenteredCubic(size=(100,100,50), symbol='Cu') atoms.set_calculator(EMT()) print "Number of atoms:", len(atoms) d = 0.1 pos = atoms.arrays['positions'] # Nasty! for i in range(nsteps): pos[50][0] += d d = -d f = atoms.get_forces() report_timing() print "Wall time elapsed:", time.time() - start
#!/usr/bin/env python from ase.lattice.cubic import FaceCenteredCubic from ase.calculators.aims import Aims import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt import numpy as np atoms = FaceCenteredCubic('Pt') kpts = [2, 3, 5, 7, 9, 11, 15, 19, 25] energies = [] ready = True for k in kpts: calc = Aims(label='bulk/pt-kpts-{0}'.format(k), xc='pbe', spin='none', relativistic = 'atomic_zora scalar', kpts=(k, k, k), # specifies the Monkhorst-Pack grid sc_accuracy_etot=1e-5, sc_accuracy_eev=1e-2, sc_accuracy_rho=1e-4,) atoms.set_calculator(calc) try: energies.append(atoms.get_potential_energy()) except: print('aims failed when k = {0}'.format(k)) ready = False if not ready: import sys; sys.exit() print '# pt-fcc-latt'
if re.match("^n\d\d\d.dcsc.fysik.dtu.dk$", host): print " This is a d512 node on Niflheim." fullhost = "niflheim-d512/%s" % (host.split(".")[0]) host = "niflheim-d512" elif re.match("^[stu]\d\d\d.dcsc.fysik.dtu.dk$", host): print " This is an s50 node on Niflheim." fullhost = "niflheim-s50/%s" % (host.split(".")[0]) host = "niflheim-s50" else: fullhost = host print "Current time is "+when print "" print "Preparing system" initial = FaceCenteredCubic(directions=[[1,0,0],[0,1,0],[0,0,1]], size=(30, 30, 30), symbol="Pt") ReportTest("Number of atoms", len(initial), 108000, 0) r = initial.get_positions() r.flat[:] += 0.14 * sin(arange(3*len(initial))) initial.set_positions(r) print "Running self-test." atoms = Atoms(initial) atoms.set_calculator(EMT2013(PtY_parameters)) e = atoms.get_potential_energies() f = atoms.get_forces() if os.access(selfcheckfilename, os.F_OK): olde, oldf = cPickle.load(open(selfcheckfilename)) de = max(fabs(e - olde)) df = max(fabs(f.flat[:] - oldf.flat[:]))
print "Energy: ", energy if t is not None: t.write() return e def checktraj(t, e, cpus=None): i = 0 for energy in e: atoms = t.get_atoms(i, cpus) atoms.set_calculator(EMT()) ReportTest("Checking frame %d / cpus=%s" % (i, str(cpus)), atoms.get_potential_energy(), energy, precision) i += 1 if ismaster: initial = FaceCenteredCubic(size=(10,10,10), symbol="Cu", pbc=(1,0,0)) else: initial = None if isparallel: atoms = MakeParallelAtoms(initial, cpulayout) else: atoms = initial.copy() atoms.set_calculator(EMT()) print "Writing trajectory" traj = PickleTrajectory("traj1.nc", "w", atoms) traj.write() energies = maketraj(atoms, traj, 10) traj.close() if ismaster:
from ase.lattice.cubic import FaceCenteredCubic from jasp import * atoms = FaceCenteredCubic('Ag') KPTS = [2, 3, 4, 5, 6, 8, 10] TE = [] ready = True for k in KPTS: with jasp('bulk/Ag-kpts-{0}'.format(k), xc='PBE', kpts=(k, k, k), #specifies the Monkhorst-Pack grid encut=300, atoms=atoms) as calc: try: TE.append(atoms.get_potential_energy()) except (VaspSubmitted, VaspQueued): ready = False if not ready: import sys; sys.exit() import matplotlib.pyplot as plt # consider the change in energy from lowest energy state TE = np.array(TE) TE -= TE.min() plt.plot(KPTS, TE) plt.xlabel('number of k-points in each dimension') plt.ylabel('Total Energy (eV)') plt.savefig('images/Ag-kpt-convergence.png') plt.show()
print " Periodic boundary conditions: %s" % (str(v),) elif k == 'natoms': print " Number of atoms: %i" % (v,) elif hasattr(v, 'shape'): print " %s: shape = %s, type = %s" % (k, str(v.shape), str(v.dtype)) else: print " %s: %s" % (k, str(v)) # Read info from separate files. for k, v in metadata['datatypes'].items(): if v and not k in small: info = backend.read_info(frame, k) if info and isinstance(info[0], tuple): shape, dtype = info else: shape = info dtype = 'unknown' print " %s: shape = %s, type = %s" % (k, str(shape), dtype) if __name__ == '__main__': from ase.lattice.cubic import FaceCenteredCubic from ase.io import read, write atoms = FaceCenteredCubic(size=(5, 5, 5), symbol='Au') write('test.bundle', atoms) atoms2 = read('test.bundle') assert (atoms.get_positions() == atoms2.get_positions()).all() assert (atoms.get_atomic_numbers() == atoms2.get_atomic_numbers()).all()
from jasp import * from ase.lattice.cubic import FaceCenteredCubic from ase import Atoms, Atom # bulk system atoms = FaceCenteredCubic(directions=[[0,1,1], [1,0,1], [1,1,0]], size=(1,1,1), symbol='Rh') with jasp('bulk/bulk-rh', xc='PBE', encut=350, kpts=(4,4,4), isif=3, ibrion=2, nsw=10, atoms=atoms) as calc: bulk_energy = atoms.get_potential_energy() # atomic system atoms = Atoms([Atom('Rh',[5, 5, 5])], cell=(7, 8, 9)) with jasp('bulk/atomic-rh', xc='PBE', encut=350, kpts=(1, 1, 1), atoms=atoms) as calc: atomic_energy = atoms.get_potential_energy() cohesive_energy = atomic_energy - bulk_energy print 'The cohesive energy is {0:1.3f} eV'.format(cohesive_energy)