def Surface001(self, EMT, PARAMETERS): """ The Method calculates and returns the surface energy for the given element along the [0,0,1] direction in the FCC crystal structure. """ # The size of the crystals are set: S001 = 3, 3, 5 # The surfaces (slabs) are created (pbc=(1,1,0) creates periodic boudry conditions # in two of three directions and thus leaves the last direction as two surfaces. Surface001 = FaceCenteredCubic(size=S001, symbol=self.Element, pbc=(1, 1, 0)) Surface001.set_calculator(EMT) # A structural relaxsation is run for the surface crystal in order to secure # the correct structure of the crystal. dyn001 = BFGS(Surface001, logfile=None) dyn001.run(fmax=0.01) # The referance bulk crystals are created Bulk001 = FaceCenteredCubic(size=S001, symbol=self.Element) # The calculator is assigned Bulk001.set_calculator(EMT) # The surface area is calculated # The cross product between the x and y axis in the crystal is determined Cross001 = numpy.cross(Bulk001.get_cell()[:, 0], Bulk001.get_cell()[:, 1]) # The area of the surface is determined from the formular A = |X x Y|. area001 = numpy.sqrt(numpy.dot(Cross001, Cross001)) # The surface energy is calculated and returned (two surfaces are present in # SurfaceRelaxed) return ((Surface001.get_potential_energy() - Bulk001.get_potential_energy()) / 2 / area001)
def test_mix_eam_alloy(self): if False: source,parameters,F,f,rep = read_eam("CuAu_Zhou.eam.alloy",kind="eam/alloy") source1,parameters1,F1,f1,rep1 = mix_eam(["Cu_Zhou.eam.alloy","Au_Zhou.eam.alloy"],"eam/alloy","weight") write_eam(source1,parameters1,F1,f1,rep1,"CuAu_mixed.eam.alloy",kind="eam/alloy") calc0 = EAM('CuAu_Zhou.eam.alloy') calc1 = EAM('CuAu_mixed.eam.alloy') a = FaceCenteredCubic('Cu', size=[2,2,2]) a.set_calculator(calc0) FIRE(StrainFilter(a, mask=[1,1,1,0,0,0]), logfile=None).run(fmax=0.001) e0 = a.get_potential_energy()/len(a) a = FaceCenteredCubic('Cu', size=[2,2,2]) a.set_calculator(calc1) FIRE(StrainFilter(a, mask=[1,1,1,0,0,0]), logfile=None).run(fmax=0.001) e1 = a.get_potential_energy()/len(a) self.assertTrue(e0-e1 < 0.0005) a = FaceCenteredCubic('Au', size=[2,2,2]) a.set_calculator(calc0) FIRE(StrainFilter(a, mask=[1,1,1,0,0,0]), logfile=None).run(fmax=0.001) e0 = a.get_potential_energy()/len(a) a = FaceCenteredCubic('Au', size=[2,2,2]) a.set_calculator(calc1) FIRE(StrainFilter(a, mask=[1,1,1,0,0,0]), logfile=None).run(fmax=0.001) e1 = a.get_potential_energy()/len(a) self.assertTrue(e0-e1 < 0.0005) a = L1_2(['Au', 'Cu'], size=[2,2,2], latticeconstant=4.0) a.set_calculator(calc0) FIRE(UnitCellFilter(a, mask=[1,1,1,0,0,0]), logfile=None).run(fmax=0.001) e0 = a.get_potential_energy()/len(a) a = L1_2(['Au', 'Cu'], size=[2,2,2], latticeconstant=4.0) a.set_calculator(calc1) FIRE(UnitCellFilter(a, mask=[1,1,1,0,0,0]), logfile=None).run(fmax=0.001) e1 = a.get_potential_energy()/len(a) self.assertTrue(e0-e1 < 0.0005) a = L1_2(['Cu', 'Au'], size=[2,2,2], latticeconstant=4.0) a.set_calculator(calc0) FIRE(UnitCellFilter(a, mask=[1,1,1,0,0,0]), logfile=None).run(fmax=0.001) e0 = a.get_potential_energy()/len(a) a = L1_2(['Cu', 'Au'], size=[2,2,2], latticeconstant=4.0) a.set_calculator(calc1) FIRE(UnitCellFilter(a, mask=[1,1,1,0,0,0]), logfile=None).run(fmax=0.001) e1 = a.get_potential_energy()/len(a) self.assertTrue(e0-e1 < 0.0005) a = B1(['Au', 'Cu'], size=[2,2,2], latticeconstant=4.0) a.set_calculator(calc0) FIRE(UnitCellFilter(a, mask=[1,1,1,0,0,0]), logfile=None).run(fmax=0.001) e0 = a.get_potential_energy()/len(a) a = B1(['Au', 'Cu'], size=[2,2,2], latticeconstant=4.0) a.set_calculator(calc1) FIRE(UnitCellFilter(a, mask=[1,1,1,0,0,0]), logfile=None).run(fmax=0.001) e1 = a.get_potential_energy()/len(a) self.assertTrue(e0-e1 < 0.0005) os.remove("CuAu_mixed.eam.alloy")
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.set_calculator(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 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 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_main(): # create calculator #modelname = 'ex_model_Ar_P_MLJ_C' modelname = 'ex_model_Ar_P_Morse_07C' calc = KIMCalculator(modelname, debug=True) # create an FCC crystal argon = 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 coords of the first atoms argon.positions[0,0] += 0.01 # attach the calculator to the atoms object argon.set_calculator(calc) for i in range(4): print ('step', i) # get energy and forces energy = argon.get_potential_energy() forces = argon.get_forces() # rigidly move the atoms argon.positions[:,0] += 1.629/2. # the cutoff skin is 1.63 # create an FCC crystal with no periodic BC argon = FaceCenteredCubic(directions=[[1,0,0], [0,1,0], [0,0,1]], size=(2,1,1), symbol='Ar', pbc=(0,0,0), latticeconstant=3.0) # attach the SAME calculator to the new atoms object argon.set_calculator(calc) for i in range(4): print('step', i) # get energy and forces energy = argon.get_potential_energy() forces = argon.get_forces() # rigidly move the atoms argon.positions[:,0] += 1.631/2. # the cutoff skin is 1.63
def test_potentiostat(): size = 2 atoms = FaceCenteredCubic(directions=[[1, 0, 0], [0, 1, 0], [0, 0, 1]], symbol='Al', size=(size, size, size), pbc=True) atoms.set_calculator(EMT()) E0 = atoms.get_potential_energy() atoms.rattle(stdev=0.18, seed=312) md_temp = 300 rng = np.random.RandomState(60622) MaxwellBoltzmannDistribution(atoms, temperature_K=md_temp, rng=rng) initial_energy = atoms.get_potential_energy() print("Energy Above Ground State: {: .4f} eV/atom".format( (initial_energy - E0) / len(atoms))) name = 'test_potentiostat' traj_name = name + '.traj' log_name = name + '.log' dyn = contour_exploration( atoms, maxstep=1.0, parallel_drift=0.05, remove_translation=True, force_parallel_step_scale=None, energy_target=initial_energy, angle_limit=20, use_tangent_curvature=False, #trajectory = traj_name, #logfile = log_name, ) for i in range(5): dyn.run(10) energy_error = (atoms.get_potential_energy() - initial_energy) / len(atoms) print('Potentiostat Error {: .4f} eV/atom'.format(energy_error)) assert 0 == pytest.approx(energy_error, abs=0.01)
def test_lammpslib_change_cell_bcs(factory, lattice_params, calc_params_NiH): """Test that a change in unit cell boundary conditions is handled correctly by lammpslib""" atoms = FaceCenteredCubic(**lattice_params) calc = factory.calc(**calc_params_NiH) atoms.calc = calc energy_ppp_ref = -142.400000403 energy_ppp = atoms.get_potential_energy() print("Computed energy with boundary ppp = {}".format(energy_ppp)) assert energy_ppp == pytest.approx(energy_ppp_ref, rel=1e-4) atoms.set_pbc((False, False, True)) energy_ssp_ref = -114.524625705 energy_ssp = atoms.get_potential_energy() print("Computed energy with boundary ssp = {}".format(energy_ssp)) assert energy_ssp == pytest.approx(energy_ssp_ref, rel=1e-4)
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 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_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 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 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 test_lammpslib_change_cell_bcs(): # test that a change in unit cell boundary conditions is # handled correctly by lammpslib import numpy as np from ase.calculators.lammpslib import LAMMPSlib from ase.lattice.cubic import FaceCenteredCubic cmds = ["pair_style eam/alloy", "pair_coeff * * NiAlH_jea.eam.alloy Ni H"] lammps = LAMMPSlib(lmpcmds=cmds, atom_types={ 'Ni': 1, 'H': 2 }, log_file='test.log', keep_alive=True) atoms = FaceCenteredCubic(size=(2, 2, 2), latticeconstant=3.52, symbol="Ni", pbc=True) atoms.calc = lammps energy_ppp_ref = -142.400000403 energy_ppp = atoms.get_potential_energy() print("Computed energy with boundary ppp = {}".format(energy_ppp)) np.testing.assert_allclose(energy_ppp, energy_ppp_ref, atol=1e-4, rtol=1e-4) atoms.set_pbc((False, False, True)) energy_ssp_ref = -114.524625705 energy_ssp = atoms.get_potential_energy() print("Computed energy with boundary ssp = {}".format(energy_ssp)) np.testing.assert_allclose(energy_ssp, energy_ssp_ref, atol=1e-4, rtol=1e-4)
def EvocCalculator(self, EMT, PARAMETERS): # Return 0 is used when the method is not desired to be used # return 0 """ This method calculates the vacancy formation energy for the system of atoms. That is, this method calculates the potential energy for a complete system of atoms, then removes an atom and calculates the potential energy again. Then the energy for the full system (scaled with the number of atoms in the reduced system) are subtracted from that of the reduced system and the vacancy formation energy, Evoc, is returned. """ # The atoms object is initialized for the chosen size and type of system atoms = FaceCenteredCubic(size=(self.Size, self.Size, self.Size), symbol=self.Element) # The EMT calculator given is attached to the atoms object atoms.set_calculator(EMT) # The energy of the full system is calculated E_FullSystem = atoms.get_potential_energy() # an atom is removed from the system atoms.pop() # The energy of the reduced system is calculated E_ReducedSystem = atoms.get_potential_energy() # The energy of a full system compared to the energy pr atom of the reduced system is calculated and returned return E_ReducedSystem - E_FullSystem * len(atoms) / (len(atoms) + 1)
def test_direct_evaluation(self): a = FaceCenteredCubic('Au', size=[2,2,2]) a.rattle(0.1) calc = EAM('Au-Grochola-JCP05.eam.alloy') a.set_calculator(calc) f = a.get_forces() calc2 = EAM('Au-Grochola-JCP05.eam.alloy') i_n, j_n, dr_nc, abs_dr_n = neighbour_list('ijDd', a, cutoff=calc2.cutoff) epot, virial, f2 = calc2.energy_virial_and_forces(a.numbers, i_n, j_n, dr_nc, abs_dr_n) self.assertArrayAlmostEqual(f, f2) a = FaceCenteredCubic('Cu', size=[2,2,2]) calc = EAM('CuAg.eam.alloy') a.set_calculator(calc) FIRE(StrainFilter(a, mask=[1,1,1,0,0,0]), logfile=None).run(fmax=0.001) e_Cu = a.get_potential_energy()/len(a) a = FaceCenteredCubic('Ag', size=[2,2,2]) a.set_calculator(calc) FIRE(StrainFilter(a, mask=[1,1,1,0,0,0]), logfile=None).run(fmax=0.001) e_Ag = a.get_potential_energy()/len(a) self.assertTrue(abs(e_Ag+2.85)<1e-6) a = L1_2(['Ag', 'Cu'], size=[2,2,2], latticeconstant=4.0) a.set_calculator(calc) FIRE(UnitCellFilter(a, mask=[1,1,1,0,0,0]), logfile=None).run(fmax=0.001) e = a.get_potential_energy() syms = np.array(a.get_chemical_symbols()) self.assertTrue(abs((e-(syms=='Cu').sum()*e_Cu- (syms=='Ag').sum()*e_Ag)/len(a)-0.096)<0.0005) a = B1(['Ag', 'Cu'], size=[2,2,2], latticeconstant=4.0) a.set_calculator(calc) FIRE(UnitCellFilter(a, mask=[1,1,1,0,0,0]), logfile=None).run(fmax=0.001) e = a.get_potential_energy() syms = np.array(a.get_chemical_symbols()) self.assertTrue(abs((e-(syms=='Cu').sum()*e_Cu- (syms=='Ag').sum()*e_Ag)/len(a)-0.516)<0.0005) a = B2(['Ag', 'Cu'], size=[2,2,2], latticeconstant=4.0) a.set_calculator(calc) FIRE(UnitCellFilter(a, mask=[1,1,1,0,0,0]), logfile=None).run(fmax=0.001) e = a.get_potential_energy() syms = np.array(a.get_chemical_symbols()) self.assertTrue(abs((e-(syms=='Cu').sum()*e_Cu- (syms=='Ag').sum()*e_Ag)/len(a)-0.177)<0.0003) a = L1_2(['Cu', 'Ag'], size=[2,2,2], latticeconstant=4.0) a.set_calculator(calc) FIRE(UnitCellFilter(a, mask=[1,1,1,0,0,0]), logfile=None).run(fmax=0.001) e = a.get_potential_energy() syms = np.array(a.get_chemical_symbols()) self.assertTrue(abs((e-(syms=='Cu').sum()*e_Cu- (syms=='Ag').sum()*e_Ag)/len(a)-0.083)<0.0005)
def test_CuAg(self): a = FaceCenteredCubic('Cu', size=[2, 2, 2]) calc = EAM('CuAg.eam.alloy') a.set_calculator(calc) FIRE(StrainFilter(a, mask=[1, 1, 1, 0, 0, 0]), logfile=None).run(fmax=0.001) e_Cu = a.get_potential_energy() / len(a) a = FaceCenteredCubic('Ag', size=[2, 2, 2]) a.set_calculator(calc) FIRE(StrainFilter(a, mask=[1, 1, 1, 0, 0, 0]), logfile=None).run(fmax=0.001) e_Ag = a.get_potential_energy() / len(a) self.assertTrue(abs(e_Ag + 2.85) < 1e-6) a = L1_2(['Ag', 'Cu'], size=[2, 2, 2], latticeconstant=4.0) a.set_calculator(calc) FIRE(UnitCellFilter(a, mask=[1, 1, 1, 0, 0, 0]), logfile=None).run(fmax=0.001) e = a.get_potential_energy() syms = np.array(a.get_chemical_symbols()) self.assertTrue( abs((e - (syms == 'Cu').sum() * e_Cu - (syms == 'Ag').sum() * e_Ag) / len(a) - 0.096) < 0.0005) a = B1(['Ag', 'Cu'], size=[2, 2, 2], latticeconstant=4.0) a.set_calculator(calc) FIRE(UnitCellFilter(a, mask=[1, 1, 1, 0, 0, 0]), logfile=None).run(fmax=0.001) e = a.get_potential_energy() syms = np.array(a.get_chemical_symbols()) self.assertTrue( abs((e - (syms == 'Cu').sum() * e_Cu - (syms == 'Ag').sum() * e_Ag) / len(a) - 0.516) < 0.0005) a = B2(['Ag', 'Cu'], size=[2, 2, 2], latticeconstant=4.0) a.set_calculator(calc) FIRE(UnitCellFilter(a, mask=[1, 1, 1, 0, 0, 0]), logfile=None).run(fmax=0.001) e = a.get_potential_energy() syms = np.array(a.get_chemical_symbols()) self.assertTrue( abs((e - (syms == 'Cu').sum() * e_Cu - (syms == 'Ag').sum() * e_Ag) / len(a) - 0.177) < 0.0003) a = L1_2(['Cu', 'Ag'], size=[2, 2, 2], latticeconstant=4.0) a.set_calculator(calc) FIRE(UnitCellFilter(a, mask=[1, 1, 1, 0, 0, 0]), logfile=None).run(fmax=0.001) e = a.get_potential_energy() syms = np.array(a.get_chemical_symbols()) self.assertTrue( abs((e - (syms == 'Cu').sum() * e_Cu - (syms == 'Ag').sum() * e_Ag) / len(a) - 0.083) < 0.0005)
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 EfccEbccCalculator(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 difference in energy between a system of atoms placed in the BCC 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 Constant for the BCC lattice is here given so that the volume pr atom of the system is # held fixed for the FCC and BCC lattice, that is Vol_pr_atom_BCC = Vol_pr_atom_FCC. atoms1 = FaceCenteredCubic(size=(self.Size, self.Size, self.Size), symbol=self.Element) atoms1.set_calculator(EMT) # The Lattice constant which produces the same volume pr atom for an BCC crystal is calculated LCBcc = 1. / (2.**(1. / 3.)) * beta * PARAMETERS[ self.Element][1] * Bohr * numpy.sqrt(2) atoms2 = BodyCenteredCubic(size=(self.Size, self.Size, self.Size), symbol=self.Element, latticeconstant=LCBcc) atoms2.set_calculator(EMT) # The energy difference pr atom is calculated and returned return atoms2.get_potential_energy() / len( atoms2) - atoms1.get_potential_energy() / len(atoms1)
def test_CuAg(self): a = FaceCenteredCubic('Cu', size=[2,2,2]) calc = EAM('CuAg.eam.alloy') a.set_calculator(calc) FIRE(StrainFilter(a, mask=[1,1,1,0,0,0]), logfile=None).run(fmax=0.001) e_Cu = a.get_potential_energy()/len(a) a = FaceCenteredCubic('Ag', size=[2,2,2]) a.set_calculator(calc) FIRE(StrainFilter(a, mask=[1,1,1,0,0,0]), logfile=None).run(fmax=0.001) e_Ag = a.get_potential_energy()/len(a) self.assertTrue(abs(e_Ag+2.85)<1e-6) a = L1_2(['Ag', 'Cu'], size=[2,2,2], latticeconstant=4.0) a.set_calculator(calc) FIRE(UnitCellFilter(a, mask=[1,1,1,0,0,0]), logfile=None).run(fmax=0.001) e = a.get_potential_energy() syms = np.array(a.get_chemical_symbols()) self.assertTrue(abs((e-(syms=='Cu').sum()*e_Cu- (syms=='Ag').sum()*e_Ag)/len(a)-0.096)<0.0005) a = B1(['Ag', 'Cu'], size=[2,2,2], latticeconstant=4.0) a.set_calculator(calc) FIRE(UnitCellFilter(a, mask=[1,1,1,0,0,0]), logfile=None).run(fmax=0.001) e = a.get_potential_energy() syms = np.array(a.get_chemical_symbols()) self.assertTrue(abs((e-(syms=='Cu').sum()*e_Cu- (syms=='Ag').sum()*e_Ag)/len(a)-0.516)<0.0005) a = B2(['Ag', 'Cu'], size=[2,2,2], latticeconstant=4.0) a.set_calculator(calc) FIRE(UnitCellFilter(a, mask=[1,1,1,0,0,0]), logfile=None).run(fmax=0.001) e = a.get_potential_energy() syms = np.array(a.get_chemical_symbols()) self.assertTrue(abs((e-(syms=='Cu').sum()*e_Cu- (syms=='Ag').sum()*e_Ag)/len(a)-0.177)<0.0003) a = L1_2(['Cu', 'Ag'], size=[2,2,2], latticeconstant=4.0) a.set_calculator(calc) FIRE(UnitCellFilter(a, mask=[1,1,1,0,0,0]), logfile=None).run(fmax=0.001) e = a.get_potential_energy() syms = np.array(a.get_chemical_symbols()) self.assertTrue(abs((e-(syms=='Cu').sum()*e_Cu- (syms=='Ag').sum()*e_Ag)/len(a)-0.083)<0.0005)
from asap3 import * from ase.lattice.cubic import FaceCenteredCubic from numpy import * from asap3.testtools import ReportTest print_version(1) #set_verbose(1) atoms = FaceCenteredCubic(directions=[[1,0,0],[0,1,0],[0,0,1]], size=(6,6,6), symbol="Cu", pbc=(1,1,0)) atoms.set_calculator(EMT()) ecorrect = atoms.get_potential_energy() atoms2 = FaceCenteredCubic(directions=[[1,0,0],[0,1,0],[0,0,1]], size=(6,6,6), symbol="Cu", pbc=(0,0,0)) atoms2.set_pbc((1,1,0)) atoms2.set_calculator(EMT()) e1= atoms2.get_potential_energy() ReportTest("e1 correct", e1, ecorrect, 0.001) atoms.set_pbc((0,1,0)) atoms.set_pbc((1,1,0)) e2 = atoms.get_potential_energy() ReportTest("e2 correct", e2, ecorrect, 0.001) print "Setting pbc" atoms.set_pbc((0,1,0)) print "Calculating energy" dummy = atoms.get_potential_energy() assert(fabs(dummy - ecorrect) > 1.0) atoms.set_pbc((1,1,0))
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 for i in numbers: #print i, count[i]
for j in range(3): if i != j and np.abs(uc[i, j]) > 1e-15: diagonal = False if not (self.allow_mi_opbc and atoms.get_pbc().all() and diagonal): # Minimum Image Orthogonal Periodic Boundary Conditions # are not allowed remove.extend(["MI_OPBC_H", "MI_OPBC_F"]) if atoms.get_pbc().any(): # Cluster method is not allowed remove.append("CLUSTER") for rem in remove: if rem in allowed: allowed.remove(rem) if self.verbose: print "Allowed PBC:", allowed return allowed if __name__ == '__main__': from ase.lattice.cubic import FaceCenteredCubic atoms = FaceCenteredCubic(size=(10, 10, 10), symbol='Cu') print "Creating calculator" pot = OpenKIMcalculator( 'EMT_Asap_Standard_AlAgAuCuNiPdPt__MO_118428466217_000') print "Setting atoms" atoms.set_calculator(pot) print "Calculating energy" print atoms.get_potential_energy() print atoms.get_forces()[10:] print atoms.get_stress()
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 for i in range(nsteps): atoms.arrays['positions'][50][0] += d d = -d f = atoms.get_forces() wall = time.time() - start if cmd in "SM": master = world.rank == 0 wall = world.sum(wall) wall /= world.size else:
def BM_LC_Calculator(self, EMT, PARAMETERS): # Return 0 is used when the method is not desired to be used # return 0 """ The method BM_LC_Calculator uses the EMT calculator to find the lattice constant which gives the lowest possible energy for a system of atoms and from a polynomial fit of the energy as a function of the lattice constant it calculates and returns the Bulk modulus, the volume of the system at the lowest possible energy and this energy """ # Three values for the lattice constant, a0, are chosen. The highest and lowest value is chosen so that it # is certain that these are to high/low respectively compared to the "correct" value. This is done by using the # experimental value of the lattice constant, a0_exp, as the middle value and to high/low values are then: # a0_exp +- a0_mod, a0_mod = a0_exp/10 a0_exp = numpy.sqrt(2) * beta * PARAMETERS[self.Element][1] * Bohr a0_mod = a0_exp * 0.10 a0_guesses = numpy.array([a0_exp - a0_mod, a0_exp, a0_exp + a0_mod]) # An atoms object consisting of atoms of the chosen element is initialized atoms = FaceCenteredCubic(size=(self.Size, self.Size, self.Size), symbol=self.Element) atoms.set_calculator(EMT) # An identity matrix for the system is saved to a variable IdentityMatrix = numpy.array([[1, 0, 0], [0, 1, 0], [0, 0, 1]]) # An array for the energy for the chosen guesses for a0 is initialized: E_guesses = numpy.zeros(5) # The energies are calculated for i in range(3): # Changes the lattice constant for the atoms object atoms.set_cell(a0_guesses[i] * self.Size * IdentityMatrix, scale_atoms=True) # Calculates the energy of the system for the new lattice constant E_guesses[i] = atoms.get_potential_energy() # Bisection is used in order to find a small interval of the lattice constant for the minimum of the energy (an # abitrary interval length is chosen), This is possible because we are certian from theory that there is only # one minimum of the energy function in the interval of interest and thus we wont "fall" into a local minimum # and stay there by accident. while (a0_guesses[2] - a0_guesses[0]) >= self.Tol: if min([E_guesses[0], E_guesses[2]]) == E_guesses[0]: # A new guess for the lattice constant is introduced a0_new_guess = 0.67 * a0_guesses[1] + 0.33 * a0_guesses[2] # The energy for this new guess is calculated atoms.set_cell(a0_new_guess * self.Size * IdentityMatrix, scale_atoms=True) E_new_guess = atoms.get_potential_energy() # A check for changes in the energy minimum is made and the guesses for a0 and their corrosponding # energies are ajusted. if min(E_new_guess, min(E_guesses[0:3])) != E_new_guess: a0_guesses[2] = a0_new_guess E_guesses[2] = E_new_guess else: a0_guesses[0] = a0_guesses[1] a0_guesses[1] = a0_new_guess E_guesses[0] = E_guesses[1] E_guesses[1] = E_new_guess elif min([E_guesses[0], E_guesses[2]]) == E_guesses[2]: # A new guess for the lattice constant is introduced a0_new_guess = 0.33 * a0_guesses[0] + 0.67 * a0_guesses[1] # The energy for this new guess is calculated atoms.set_cell(a0_new_guess * self.Size * IdentityMatrix, scale_atoms=True) E_new_guess = atoms.get_potential_energy() # A check for changes in the energy minimum is made and the guesses for a0 and their corrosponding # energies are ajusted. if min(E_new_guess, min(E_guesses[0:3])) != E_new_guess: a0_guesses[0] = a0_new_guess E_guesses[0] = E_new_guess else: a0_guesses[2] = a0_guesses[1] a0_guesses[1] = a0_new_guess E_guesses[2] = E_guesses[1] E_guesses[1] = E_new_guess # An estimate of the minimum energy can now be found from a second degree polynomial fit through the three # current guesses for a0 and the corresponding values of the energy. Poly = numpyfit.polyfit(a0_guesses, E_guesses[0:3], 2) # The lattice constant corresponding to the lowest energy from the Polynomiel fit is found a0 = -Poly[1] / (2 * Poly[0]) # Now five guesses for a0 and the corresponding energy are evaluated from and around the current a0. a0_guesses = a0 * numpy.array([ 1 - 2 * self.Tol / 5, 1 - self.Tol / 5, 1, 1 + self.Tol / 5, 1 + 2 * self.Tol / 5 ]) for i in range(5): # Changes the lattice constant for the atoms object atoms.set_cell(a0_guesses[i] * self.Size * IdentityMatrix, scale_atoms=True) # Calculates the energy of the system for the new lattice constant E_guesses[i] = atoms.get_potential_energy() # The method EquationOfState is now used to find the Bulk modulus and the minimum energy for the system. # The volume of the sample for the given a0_guesses Vol = (self.Size * a0_guesses)**3 # The equilibrium volume, energy and bulk modulus are calculated (Vol0, E0, B) = EquationOfState(Vol.tolist(), E_guesses.tolist()).fit() return (Vol0, E0, B, Vol0**(1. / 3) / self.Size)
"""Check that energy is correct even after wrapping through periodic boundary conditions. """ from ase.lattice.cubic import FaceCenteredCubic from asap3 import * from asap3.testtools import * import random ref_atoms = FaceCenteredCubic(size=(7,7,7), symbol="Cu", pbc=(True, False, True)) ref_atoms.set_calculator(EMT()) ref_energy = ref_atoms.get_potential_energy() ref_energies = ref_atoms.get_potential_energies() ref_forces = ref_atoms.get_forces() passes = 5 for ps in range(passes): print "Pass", ps, "of", passes atoms = ref_atoms.copy() atoms.set_calculator(EMT()) nat = random.randint(0, len(atoms)) assert nat < len(atoms) pos0 = atoms[nat].position cell = atoms.get_cell() for d in range(1,4): for dx in (-d, 0, d): #for dy in (-d, 0, d): for dy in (0,): for dz in (-d, 0 ,d): deltar = dx * cell[0] + dy * cell[1] + dz * cell[2]
"""Check that energy is correct even after wrapping through periodic boundary conditions. """ from ase.lattice.cubic import FaceCenteredCubic from asap3 import * from asap3.testtools import * import random ref_atoms = FaceCenteredCubic(size=(7, 7, 7), symbol="Cu", pbc=(True, False, True)) ref_atoms.set_calculator(EMT()) ref_energy = ref_atoms.get_potential_energy() ref_energies = ref_atoms.get_potential_energies() ref_forces = ref_atoms.get_forces() passes = 5 for ps in range(passes): print "Pass", ps, "of", passes atoms = ref_atoms.copy() atoms.set_calculator(EMT()) nat = random.randint(0, len(atoms)) assert nat < len(atoms) pos0 = atoms[nat].position cell = atoms.get_cell() for d in range(1, 4): for dx in (-d, 0, d): #for dy in (-d, 0, d): for dy in (0, ):
import numpy as np from ase.lattice.cubic import FaceCenteredCubic from ase.calculators.emt import EMT from ase.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.calc = 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,
from ase.lattice.cubic import FaceCenteredCubic from ase.calculators.kim.kim import KIM atoms = FaceCenteredCubic(symbol='Ar', latticeconstant=5.25, size=(1, 1, 1)) calc = KIM('LJ_ElliottAkerson_2015_Universal__MO_959249795837_003') atoms.calc = calc energy = atoms.get_potential_energy() print('Potential energy: {} eV'.format(energy))
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 calc = Vasp('bulk/Ni-PBE', ismear=-5, kpts=[5, 5, 5], xc='PBE', ispin=2, lorbit=11, lwave=True, lcharg=True, # store for reuse atoms=atoms) e = atoms.get_potential_energy() print('PBE energy: ',e) calc.stop_if(e is None) dos = DOS(calc, width=0.2) e_pbe = dos.get_energies() d_pbe = dos.get_dos() calc.clone('bulk/Ni-PBE0') calc.set(xc='pbe0') atoms = calc.get_atoms() pbe0_e = atoms.get_potential_energy() if atoms.get_potential_energy() is not None: dos = DOS(calc, width=0.2) e_pbe0 = dos.get_energies() d_pbe0 = dos.get_dos() ## HSE06 calc = Vasp('bulk/Ni-PBE')
atoms.set_calculator(calc) print "el:", el1, "str:", str, "lp:", lp if str == "hcp": print "catoi:", catoi v1 = atoms.get_volume() print "v1:", v1 n1 = atoms.get_number_of_atoms() print "n1:", n1 v1pa = v1 / n1 print "v1pa:", v1pa # initial ene0 = atoms.get_potential_energy() print "ene0:", ene0 print "ene0pa:", ene0 / atoms.get_number_of_atoms() ene0pa = ene0 / atoms.get_number_of_atoms() # vacancy atoms.pop(0) nm1 = n1 - 1 ene1nm = atoms.get_potential_energy() print "ene1nm:", ene1nm print "ene1nmpa:", ene1nm / nm1 # minimize pos model.parameters["minimize"] = "1.0e-25 1.0e-25 10000 10000" #model.parameters["minimize"] = "1.0e-5 1.0e-5 10000 10000" ene2m = atoms.get_potential_energy()
#!/usr/bin/env python from jasp import * from ase.lattice.cubic import FaceCenteredCubic atoms = FaceCenteredCubic(symbol='Al') with jasp('bulk/Al-bulk', xc='PBE', kpts=(12, 12, 12), encut=350, prec='High', isif=3, nsw=30, ibrion=1, atoms=atoms) as calc: print atoms.get_potential_energy() print atoms.get_stress()
for boundary in ((1,1,1), (0,0,0), (0,1,1), (1,0,0)): print ("CPU Layout: %s. Periodic boundary conditions: %s." % (str(cpulayout), str(boundary))) if ismaster: atoms = FaceCenteredCubic(size=(160,20,20), symbol="Cu", pbc=boundary, latticeconstant=3.61*1.04) else: atoms = None if isparallel: atoms = MakeParallelAtoms(atoms, cpulayout) natoms = atoms.get_number_of_atoms() atoms.set_calculator(EMT()) MaxwellBoltzmannDistribution(atoms, 3000*units.kB) if ismaster: print "Initializing" e_st_pot = atoms.get_potential_energy()/natoms try: e_start_pot = e_start_dict[boundary] except KeyError: e_start_pot = e_start_dict[boundary] = e_st_pot else: ReportTest("Initial energy ", e_st_pot, e_start_pot, 1e-4, silent=True) dyn = VelocityVerlet(atoms, logfile="-", dt=3*units.fs, loginterval=1) dyn.run(50) e_start = (atoms.get_potential_energy() + atoms.get_kinetic_energy())/natoms if ismaster: print "Running" dyn = VelocityVerlet(atoms, dt=5*units.fs) logger = MDLogger(dyn, atoms, '-', peratom=True)
from kimcalculator import * from numpy import * symbol = 'Ar' cells = 15 ar = FaceCenteredCubic(symbol, pbc=[(1,1,1)], directions=[[1,0,0],[0,1,0],[0,0,1]], size=[cells,cells,1]) for m in listmodels(): if symbol in m: try: print "Try model: ", m calc1 = KIMCalculator(m) ar.set_calculator(calc1) N = ar.get_number_of_atoms() ar.set_pbc([(1,1,1)]) bulk_energy = ar.get_potential_energy() / N ar.set_pbc([(1,1,0)]) surf_energy = ar.get_potential_energy() / N print "\tsurface = ", surf_energy - bulk_energy #virial = ar.get_stresses() #print "\tvirial = ", virial print except SupportError, e: print "\tskipping ", m, "\n\t", e, " ...\n" continue
for i2, p2 in enumerate(positions[:i1]): diff = p2 - p1 d2 = np.dot(diff, diff) c6 = (self.sigma**2 / d2)**3 c12 = c6**2 if d2 < self.cutoff**2: self.energy += 4 * self.epsilon * (c12 - c6) - self.shift F = 24 * self.epsilon * (2 * c12 - c6) / d2 * diff self._forces[i1] -= F self._forces[i2] += F self.positions = positions.copy() N = 5 ar = FaceCenteredCubic('Ar', pbc=[(0,0,0)], directions=[[1,0,0],[0,1,0],[0,0,1]], size=[N,N,N]) print ar.get_cell() #view(ar) calc1 = KIMCalculator("ex_model_Ar_P_LJ") ar.set_calculator(calc1) kim_energy = ar.get_potential_energy() print "kim energy = ", kim_energy calc2 = LennardJones(epsilon=epsilon, sigma=sigma, cutoff=cutoff) ar.set_calculator(calc2) ase_energy = ar.get_potential_energy() print "ase energy = ", ase_energy print "difference = ", kim_energy - ase_energy
from kimservice import * import ase from ase.lattice.cubic import FaceCenteredCubic, SimpleCubic from ase.visualize import view from kimcalculator import * from numpy import * from ase.calculators.emt import EMT N = 10 ar = FaceCenteredCubic('Ar', pbc=[(1,1,1)], directions=[[1,0,0],[0,1,0],[1,1,1]], size=[N,N,N]) calc1 = KIMCalculator("ex_model_Ar_P_LJ") ar.set_calculator(calc1) print "energy = ", ar.get_potential_energy()
from asap3 import Atoms, EMT, units from ase.lattice.cubic import FaceCenteredCubic from asap3.md.verlet import VelocityVerlet # Create the atoms atoms = FaceCenteredCubic(size=(3,3,3), symbol="Cu", pbc=False) # Give the first atom a non-zero momentum atoms[0].set_momentum(array([0, -11.3, 0])) print "Kinetic energies of all atoms:" p = atoms.get_momenta() kinenergies = 0.5 * (p * p).sum(1) / atoms.get_masses() print kinenergies # Associate the EMT potential with the atoms atoms.set_calculator(EMT()) # Now do molecular dynamics, printing kinetic, potential and total # energy every ten timesteps. dyn = VelocityVerlet(atoms, 5.0*units.fs) print "" print "Energy per atom:" print " %15s %15s %15s" % ("Pot. energy", "Kin. energy", "Total energy") for i in range(25): dyn.run(10) epot = atoms.get_potential_energy()/len(atoms) ekin = atoms.get_kinetic_energy()/len(atoms) print "%15.5f %15.5f %15.5f" % (epot, ekin, epot+ekin)
atoms_kim = FaceCenteredCubic(size=(10,10,10), symbol='Cu') #atoms_kim = FaceCenteredCubic(directions=[[1,0,0],[0,1,0],[0,0,1]], # size=(30, 30, 30), # symbol="Cu") natoms = len(atoms_kim) atoms_kim.set_pbc(pbc) r = atoms_kim.get_positions() r.flat[:] += 0.1 * np.sin(np.arange(3*natoms)) atoms_kim.set_positions(r) atoms_emt = atoms_kim.copy() kim = OpenKIMcalculator(openkimmodel, allowed=nbltype) emt = EMT() emt.set_subtractE0(False) atoms_kim.set_calculator(kim) atoms_emt.set_calculator(emt) ek = atoms_kim.get_potential_energy() ee = atoms_emt.get_potential_energy() ReportTest(txt+"Total energy", ek, ee, 1e-8) ek = atoms_kim.get_potential_energies() ee = atoms_emt.get_potential_energies() for i in range(0, natoms, step): ReportTest(txt+"Energy of atom %i" % (i,), ek[i], ee[i], 1e-8) fk = atoms_kim.get_forces() fe = atoms_emt.get_forces() n = 0 for i in range(0, natoms, step): n = (n + 1) % 3 ReportTest(txt+"Force(%i) of atom %i" % (n, i), fk[i, n], fe[i, n], 1e-8) sk = atoms_kim.get_stress() se = atoms_emt.get_stress() for i in range(6):
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:
def test_mix_eam_alloy(self): if False: source, parameters, F, f, rep = read_eam("CuAu_Zhou.eam.alloy", kind="eam/alloy") source1, parameters1, F1, f1, rep1 = mix_eam( ["Cu_Zhou.eam.alloy", "Au_Zhou.eam.alloy"], "eam/alloy", "weight") write_eam(source1, parameters1, F1, f1, rep1, "CuAu_mixed.eam.alloy", kind="eam/alloy") calc0 = EAM('CuAu_Zhou.eam.alloy') calc1 = EAM('CuAu_mixed.eam.alloy') a = FaceCenteredCubic('Cu', size=[2, 2, 2]) a.set_calculator(calc0) FIRE(StrainFilter(a, mask=[1, 1, 1, 0, 0, 0]), logfile=None).run(fmax=0.001) e0 = a.get_potential_energy() / len(a) a = FaceCenteredCubic('Cu', size=[2, 2, 2]) a.set_calculator(calc1) FIRE(StrainFilter(a, mask=[1, 1, 1, 0, 0, 0]), logfile=None).run(fmax=0.001) e1 = a.get_potential_energy() / len(a) self.assertTrue(e0 - e1 < 0.0005) a = FaceCenteredCubic('Au', size=[2, 2, 2]) a.set_calculator(calc0) FIRE(StrainFilter(a, mask=[1, 1, 1, 0, 0, 0]), logfile=None).run(fmax=0.001) e0 = a.get_potential_energy() / len(a) a = FaceCenteredCubic('Au', size=[2, 2, 2]) a.set_calculator(calc1) FIRE(StrainFilter(a, mask=[1, 1, 1, 0, 0, 0]), logfile=None).run(fmax=0.001) e1 = a.get_potential_energy() / len(a) self.assertTrue(e0 - e1 < 0.0005) a = L1_2(['Au', 'Cu'], size=[2, 2, 2], latticeconstant=4.0) a.set_calculator(calc0) FIRE(UnitCellFilter(a, mask=[1, 1, 1, 0, 0, 0]), logfile=None).run(fmax=0.001) e0 = a.get_potential_energy() / len(a) a = L1_2(['Au', 'Cu'], size=[2, 2, 2], latticeconstant=4.0) a.set_calculator(calc1) FIRE(UnitCellFilter(a, mask=[1, 1, 1, 0, 0, 0]), logfile=None).run(fmax=0.001) e1 = a.get_potential_energy() / len(a) self.assertTrue(e0 - e1 < 0.0005) a = L1_2(['Cu', 'Au'], size=[2, 2, 2], latticeconstant=4.0) a.set_calculator(calc0) FIRE(UnitCellFilter(a, mask=[1, 1, 1, 0, 0, 0]), logfile=None).run(fmax=0.001) e0 = a.get_potential_energy() / len(a) a = L1_2(['Cu', 'Au'], size=[2, 2, 2], latticeconstant=4.0) a.set_calculator(calc1) FIRE(UnitCellFilter(a, mask=[1, 1, 1, 0, 0, 0]), logfile=None).run(fmax=0.001) e1 = a.get_potential_energy() / len(a) self.assertTrue(e0 - e1 < 0.0005) a = B1(['Au', 'Cu'], size=[2, 2, 2], latticeconstant=4.0) a.set_calculator(calc0) FIRE(UnitCellFilter(a, mask=[1, 1, 1, 0, 0, 0]), logfile=None).run(fmax=0.001) e0 = a.get_potential_energy() / len(a) a = B1(['Au', 'Cu'], size=[2, 2, 2], latticeconstant=4.0) a.set_calculator(calc1) FIRE(UnitCellFilter(a, mask=[1, 1, 1, 0, 0, 0]), logfile=None).run(fmax=0.001) e1 = a.get_potential_energy() / len(a) self.assertTrue(e0 - e1 < 0.0005) os.remove("CuAu_mixed.eam.alloy")
from ase.lattice.cubic import FaceCenteredCubic from vasp import Vasp import numpy as np atoms = FaceCenteredCubic('Ag') KPTS = [2, 3, 4, 5, 6, 8, 10] TE = [] for k in KPTS: calc = Vasp('bulk/Ag-kpts-{0}'.format(k), xc='PBE', kpts=[k, k, k], # specifies the Monkhorst-Pack grid encut=300, atoms=atoms) TE.append(atoms.get_potential_energy()) if None in TE: calc.abort() 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')
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: calc.set(lhfcalc=True, hfscreen=0.2, algo="D", time=0.4) atoms = calc.get_atoms() print("HSE06 energy: ", atoms.get_potential_energy()) dos = DOS(calc, width=0.2) e_hse06 = dos.get_energies() d_hse06 = dos.get_dos() import pylab as plt plt.plot(e_pbe, d_pbe, label="PBE") plt.plot(e_pbe0, d_pbe0, label="PBE0")
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)
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: pass
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()
from vasp import Vasp 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') calc = Vasp('bulk/bulk-rh', xc='PBE', encut=350, kpts=[4, 4, 4], isif=3, ibrion=2, nsw=10, atoms=atoms) bulk_energy = atoms.get_potential_energy() # atomic system atoms = Atoms([Atom('Rh', [5, 5, 5])], cell=(7, 8, 9)) calc = Vasp('bulk/atomic-rh', xc='PBE', encut=350, kpts=[1, 1, 1], atoms=atoms) atomic_energy = atoms.get_potential_energy() calc.stop_if(None in (bulk_energy, atomic_energy)) cohesive_energy = atomic_energy - bulk_energy print 'The cohesive energy is {0:1.3f} eV'.format(cohesive_energy)
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 for i in range(nsteps): atoms.arrays['positions'][50][0] += d d = -d f = atoms.get_forces() wall = time.time() - start if cmd in "SM": master = world.rank == 0 wall = world.sum(wall) wall /= world.size else:
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),
(str(cpulayout), str(boundary))) if ismaster: atoms = FaceCenteredCubic(size=(160, 20, 20), symbol="Cu", pbc=boundary, latticeconstant=3.61 * 1.04) else: atoms = None if isparallel: atoms = MakeParallelAtoms(atoms, cpulayout) natoms = atoms.get_number_of_atoms() atoms.set_calculator(EMT()) MaxwellBoltzmannDistribution(atoms, 3000 * units.kB) if ismaster: print "Initializing" e_st_pot = atoms.get_potential_energy() / natoms try: e_start_pot = e_start_dict[boundary] except KeyError: e_start_pot = e_start_dict[boundary] = e_st_pot else: ReportTest("Initial energy ", e_st_pot, e_start_pot, 1e-4, silent=True) dyn = VelocityVerlet(atoms, logfile="-", dt=3 * units.fs, loginterval=1) dyn.run(50)
atoms.set_calculator(calc) print "el:", el1, "str:", str, "lp:", lp if str == "hcp": print "catoi:", catoi v1 = atoms.get_volume() print "v1:", v1 n1 = atoms.get_number_of_atoms() print "n1:", n1 v1pa = v1 / n1 print "v1pa:", v1pa # initial ene0 = atoms.get_potential_energy() print "ene0:", ene0 print "ene0pa:", ene0 / atoms.get_number_of_atoms() ene0pa = ene0 / atoms.get_number_of_atoms() # vacancy atoms.pop(0) nm1 = n1 - 1 ene1nm = atoms.get_potential_energy() print "ene1nm:", ene1nm print "ene1nmpa:", ene1nm / nm1 # minimize pos model.parameters["minimize"] = "1.0e-25 1.0e-25 10000 10000" # model.parameters["minimize"] = "1.0e-5 1.0e-5 10000 10000" ene2m = atoms.get_potential_energy()
from numpy import * symbol = 'Ar' cells = 15 ar = FaceCenteredCubic(symbol, pbc=[(1, 1, 1)], directions=[[1, 0, 0], [0, 1, 0], [0, 0, 1]], size=[cells, cells, 1]) for m in listmodels(): if symbol in m: try: print "Try model: ", m calc1 = KIMCalculator(m) ar.set_calculator(calc1) N = ar.get_number_of_atoms() ar.set_pbc([(1, 1, 1)]) bulk_energy = ar.get_potential_energy() / N ar.set_pbc([(1, 1, 0)]) surf_energy = ar.get_potential_energy() / N print "\tsurface = ", surf_energy - bulk_energy #virial = ar.get_stresses() #print "\tvirial = ", virial print except SupportError, e: print "\tskipping ", m, "\n\t", e, " ...\n" continue