Beispiel #1
0
def test_fire():
    a = bulk('Au')
    a *= (2, 2, 2)

    a[0].x += 0.5

    a.set_calculator(EMT())

    opt = FIRE(a, dtmax=1.0, dt=1.0, maxmove=100.0, downhill_check=False)
    opt.run(fmax=0.001)
    e1 = a.get_potential_energy()
    n1 = opt.nsteps

    a = bulk('Au')
    a *= (2, 2, 2)

    a[0].x += 0.5

    a.set_calculator(EMT())

    reset_history = []

    def callback(a, r, e, e_last):
        reset_history.append([e - e_last])

    opt = FIRE(a, dtmax=1.0, dt=1.0, maxmove=100.0, downhill_check=True,
               position_reset_callback=callback)
    opt.run(fmax=0.001)
    e2 = a.get_potential_energy()
    n2 = opt.nsteps

    assert abs(e1 - e2) < 1e-6
    assert n2 < n1
    assert (np.array(reset_history) > 0).all
Beispiel #2
0
def test_mirror():
    from ase.build import molecule
    from ase.constraints import MirrorForce, FixBondLength, MirrorTorque
    from ase.constraints import ExternalForce
    from ase.optimize import FIRE
    from ase.calculators.emt import EMT

    atoms = molecule('cyclobutene')
    dist = atoms.get_distance(0, 1)
    con1 = MirrorForce(2, 3, max_dist=5., fmax=0.05)
    con2 = FixBondLength(0, 1)
    atoms.set_constraint([con1, con2])
    atoms.calc = EMT()
    opt = FIRE(atoms)
    opt.run(fmax=0.05)
    assert round(dist - atoms.get_distance(0, 1), 5) == 0

    atoms = molecule('butadiene')
    # Break symmetry
    atoms[0].position[2] += 0.2
    dist = atoms.get_distance(1, 2)
    con1 = MirrorTorque(0, 1, 2, 3, fmax=0.05)
    con2 = ExternalForce(9, 4, f_ext=0.1)
    atoms.set_constraint([con1, con2])
    atoms.calc = EMT()
    opt = FIRE(atoms)
    opt.run(fmax=0.05, steps=300)
Beispiel #3
0
def getPath(Reac,Prod,gl):
    xyzfile3 = open(("IRC3.xyz"), "w")
    Path = []
    Path.append(Reac.copy())
    for i in range(0,30):
        image = Reac.copy()
        image = tl.setCalc(image,"DOS/", gl.lowerMethod, gl.lowerLevel)
        Path.append(image)
    image = Prod.copy()
    image = tl.setCalc(image,"DOS/", gl.lowerMethod, gl.lowerLevel)
    Path.append(image)

    neb1 = NEB(Path,k=1.0,remove_rotation_and_translation = True)
    try:
        neb1.interpolate('idpp',optimizer="MDMin",k=1.0)
    except:
        neb1.interpolate()

    optimizer = FIRE(neb1)
    optimizer.run(fmax=0.07, steps = 500)
    neb2 = NEB(Path,k=1.0, climb=True, remove_rotation_and_translation = True )
    optimizer = FIRE(neb2)
    optimizer.run(fmax=0.07, steps = 1500)
    for i in range(0,len(Path)):
        tl.printTraj(xyzfile3, Path[i])
    xyzfile3.close()



    return Path
def relax(atoms, cellbounds=None):
    # Performs a variable-cell relaxation of the structure
    calc = EMT()
    atoms.set_calculator(calc)

    converged = False
    niter = 0
    while not converged and niter < 10:
        if cellbounds is not None:
            cell = atoms.get_cell()
            if not cellbounds.is_within_bounds(cell):
                niggli_reduce(atoms)
            cell = atoms.get_cell()
            if not cellbounds.is_within_bounds(cell):
                # Niggli reduction did not bring the unit cell
                # within the specified bounds; this candidate should
                # be discarded so we set an absurdly high energy
                finalize(atoms, 1e9)
                return

        ecf = ExpCellFilter(atoms)
        dyn = FIRE(ecf, maxmove=0.2, logfile=None, trajectory=None)
        dyn.run(fmax=1e-3, steps=100)

        converged = dyn.converged()
        niter += 1

    dyn = FIRE(atoms, maxmove=0.2, logfile=None, trajectory=None)
    dyn.run(fmax=1e-2, steps=100)

    e = atoms.get_potential_energy()
    f = atoms.get_forces()
    s = atoms.get_stress()
    finalize(atoms, energy=e, forces=f, stress=s)
Beispiel #5
0
    def relax_defect_cell(self,
                          ats,
                          output_name='defect_cell_relaxed.xyz',
                          force_tol=0.0001,
                          relax_cell=False):
        """
        Accepts atoms object with an attached calculator.Minimize forces.

        Args:
          ats (:obj:`Atoms`): Atoms with defect to relax.
          output_name (str, optional): Filename to print relaxed atoms structure to.
          force_tol (float, optional): Force tolerance to stop relaxation.
          relax_cell (bool, optional): Relax lattice parameters.

        Returns:
          :class:`Atoms`: A relaxed Atoms object.
        """
        from ase.optimize import FIRE
        if relax_cell:
            strain_mask = [1, 1, 1, 0, 0, 0]
            ucf = UnitCellFilter(ats, strain_mask)
            opt = FIRE(ucf)
        else:
            strain_mask = [0, 0, 0, 0, 0, 0]
            ucf = UnitCellFilter(ats, strain_mask)
            opt = FIRE(ucf)
        opt.run(fmax=force_tol)
        ats.write(output_name)
        return ats
def test_combine_mm2():
    # More biased initial positions for faster test. Set
    # to false for a slower, harder test.
    fast_test = True

    atoms = make_4mer()
    atoms.constraints = FixBondLengths([(3 * i + j, 3 * i + (j + 1) % 3)
                                        for i in range(int(len(atoms) // 3))
                                        for j in [0, 1, 2]])
    atoms.calc = TIP3P(np.Inf)
    tag = '4mer_tip3_opt.'
    opt = FIRE(atoms, logfile=tag + 'log', trajectory=tag + 'traj')
    opt.run(fmax=0.05)
    tip3_pos = atoms.get_positions()

    sig = np.array([sigma0, 0, 0])
    eps = np.array([epsilon0, 0, 0])
    rc = np.Inf
    idxes = [[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10, 11],
             list(range(6)),
             list(range(9)),
             list(range(6, 12))]

    for ii, idx in enumerate(idxes):
        atoms = make_4mer()
        if fast_test:
            atoms.set_positions(tip3_pos)
        atoms.constraints = FixBondLengths([(3 * i + j, 3 * i + (j + 1) % 3)
                                            for i in range(len(atoms) // 3)
                                            for j in [0, 1, 2]])

        atoms.calc = CombineMM(idx,
                               3,
                               3,
                               TIP3P(rc),
                               TIP3P(rc),
                               sig,
                               eps,
                               sig,
                               eps,
                               rc=rc)

        tag = '4mer_combtip3_opt_{0:02d}.'.format(ii)
        opt = FIRE(atoms, logfile=tag + 'log', trajectory=tag + 'traj')
        opt.run(fmax=0.05)
        assert ((abs(atoms.positions - tip3_pos) < 1e-8).all())
        print('{0}: {1!s:>28s}: Same Geometry as TIP3P'.format(
            atoms.calc.name, idx))
Beispiel #7
0
def Minimisation_Function(cluster):
    cluster.pbc = False
    # Perform the local optimisation method on the cluster.
    # Parameter sequence: [p, q, a, xi, r0]
    Pt_parameters = {'Pt': [10.71, 3.845, 0.27443, 2.6209, 2.77]}
    Gupta_parameters = Pt_parameters
    cutoff = 1000
    calculator = Gupta(Gupta_parameters, cutoff=cutoff, debug=False)
    cluster.set_calculator(calculator)
    original_cluster = cluster.copy()
    dyn = FIRE(cluster, logfile=None)
    #startTime = time.time();
    converged = False
    try:
        dyn.run(fmax=0.01, steps=5000)
        converged = dyn.converged()
        if not converged:
            cluster_name = 'issue_cluster.xyz'
            errorMessage = 'The optimisation of cluster ' + str(
                original_cluster) + ' did not optimise completely.\n'
            errorMessage += 'The cluster of issue before optimisation has been saved as: ' + str(
                cluster_name)
            write(cluster_name, original_cluster)
            raise Exception(errorMessage)
    except Exception as exception_message:
        cluster_name = 'issue_cluster.xyz'
        errorMessage = 'The optimisation of cluster ' + str(
            original_cluster) + ' did not optimise completely.\n'
        errorMessage += 'The cluster of issue before optimisation has been saved as: ' + str(
            cluster_name) + '\n'
        errorMessage += exception_message
        write(cluster_name, original_cluster)
        raise Exception(errorMessage)
    #endTime = time.time()
    return cluster
    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 Minimisation_Function(cluster,collection,cluster_name):
	####################################################################################################################
	cluster.pbc = False
	####################################################################################################################
	# Perform the local optimisation method on the cluster.
	# Parameter sequence: [p, q, a, xi, r0]
	#Gupta_parameters = {'Au': [10.529999999999999, 4.2999999999999998, 0.21970000000000001, 1.855, 2.8779245994292486]}
	Gupta_parameters = {'Pd': [10.867, 3.742, 0.1746, 1.718, 2.7485], 'Au': [10.229, 4.036, 0.2061, 1.79, 2.884], ('Au','Pd'): [10.54, 3.89, 0.19, 1.75, 2.816]}
	cluster.set_calculator(Gupta(Gupta_parameters, cutoff=1000, debug=False))
	dyn = FIRE(cluster,logfile=None)
	startTime = time.time(); converged = False
	try:
		dyn.run(fmax=0.01,steps=5000)
		converged = dyn.converged()
		if not converged:
			errorMessage = 'The optimisation of cluster ' + str(cluster_name) + ' did not optimise completely.'
			print(errorMessage, file=sys.stderr)
			print(errorMessage)
	except Exception:
		print('Local Optimiser Failed for some reason.')
	endTime = time.time()
	####################################################################################################################
	# Write information about the algorithm
	Info = {}
	Info["INFO.txt"] = ''
	Info["INFO.txt"] += ("No of Force Calls: " + str(dyn.get_number_of_steps()) + '\n')
	Info["INFO.txt"] += ("Time (s): " + str(endTime - startTime) + '\n')
	#Info["INFO.txt"] += ("Cluster converged?: " + str(dyn.converged()) + '\n')
	####################################################################################################################
	return cluster, converged, Info
Beispiel #10
0
    def test_anisotropic_near_field_solution(self):
        """
        Run an atomistic calculation of a harmonic solid and compare to
        continuum solution.
        """

        if not atomistica:
            print('Atomistica not available. Skipping test.')
            return

        for nx in [ 8, 16, 32, 64 ]:
            for calc, a, C11, C12, C44, surface_energy, bulk_coordination in [
                #( atomistica.DoubleHarmonic(k1=1.0, r1=1.0, k2=1.0,
                #                            r2=math.sqrt(2), cutoff=1.6),
                #  clusters.sc('He', 1.0, [nx,nx,1], [1,0,0], [0,1,0]),
                #  3, 1, 1, 0.05, 6 ),
                ( atomistica.Harmonic(k=1.0, r0=1.0, cutoff=1.3, shift=True),
                  clusters.fcc('He', math.sqrt(2.0), [nx,nx,1], [1,0,0],
                               [0,1,0]),
                  math.sqrt(2), 1.0/math.sqrt(2), 1.0/math.sqrt(2), 0.05, 12)
                ]:
                clusters.set_groups(a, (nx, nx, 1), 0.5, 0.5)
                crack = CubicCrystalCrack([1,0,0], [0,1,0], C11, C12, C44)

                a.center(vacuum=20.0, axis=0)
                a.center(vacuum=20.0, axis=1)
                a.set_calculator(calc)

                sx, sy, sz = a.cell.diagonal()
                tip_x = sx/2
                tip_y = sy/2

                k1g = crack.k1g(surface_energy)
                r0 = a.positions.copy()

                u, v = crack.displacements(a.positions[:,0], a.positions[:,1],
                                           tip_x, tip_y, k1g)
                a.positions[:,0] += u
                a.positions[:,1] += v

                g = a.get_array('groups')
                a.set_constraint(FixAtoms(mask=g==0))

                #ase.io.write('initial_{}.xyz'.format(nx), a, format='extxyz')

                x1, y1, z1 = a.positions.copy().T
                FIRE(a, logfile=None).run(fmax=1e-3)
                x2, y2, z2 = a.positions.T

                # Get coordination numbers and find properly coordinated atoms
                coord = calc.nl.get_coordination_numbers(calc.particles, 1.1)
                mask=coord == bulk_coordination

                residual = np.sqrt(((x2-x1)/u)**2 + ((y2-y1)/v)**2)
                
                #a.set_array('residual', residual)
                #ase.io.write('final_{}.xyz'.format(nx), a, format='extxyz')

                #print(np.max(residual[mask]))
                self.assertTrue(np.max(residual[mask]) < 0.2)
def Minimisation_Function(cluster, collection, cluster_dir):
    cluster.pbc = False
    rCut = 1000
    #sigma = 1; epsilon = 1; lj_calc = LennardJones(sigma=sigma, epsilon=epsilon,rc=rCut)
    elements = [atomic_numbers[cluster[0].symbol]]
    sigma = [1]
    epsilon = [1]
    lj_calc = LennardJones(elements, epsilon, sigma, rCut=rCut, modified=True)
    cluster.set_calculator(lj_calc)
    dyn = FIRE(cluster, logfile=None)
    startTime = time.time()
    converged = False
    try:
        dyn.run(fmax=0.01, steps=5000)
        converged = dyn.converged()
        if not converged:
            errorMessage = 'The optimisation of cluster ' + str(
                cluster_dir) + ' did not optimise completely.'
            print(errorMessage, file=sys.stderr)
            print(errorMessage)
    except Exception:
        print('Local Optimiser Failed for some reason.')
    endTime = time.time()
    # Write information about the algorithm
    Info = {}
    Info["INFO.txt"] = ''
    Info["INFO.txt"] += ("No of Force Calls: " +
                         str(dyn.get_number_of_steps()) + '\n')
    Info["INFO.txt"] += ("Time (s): " + str(endTime - startTime) + '\n')
    #Info.write("Cluster converged?: " + str(dyn.converged()) + '\n')
    return cluster, converged, Info
Beispiel #12
0
def Minimisation_Function(cluster):
	cluster.pbc = False
	# Perform the local optimisation method on the cluster.
	# Parameter sequence: [p, q, a, xi, r0]
	#Au_parameters = {'Au': [10.229, 4.0360, 0.2061, 1.7900, 2.884]}
	r0 = 4.07/(2.0 ** 0.5)
	Au_parameters = {'Au': [10.53, 4.30, 0.2197, 1.855, r0]} # Baletto
	Gupta_parameters = Au_parameters
	cutoff = 1000
	calculator = Gupta(Gupta_parameters, cutoff=cutoff, debug=False)
	cluster.set_calculator(calculator)
	original_cluster = cluster.copy()
	dyn = FIRE(cluster,logfile=None)
	converged = False
	try:
		dyn.run(fmax=0.01,steps=5000)
		converged = dyn.converged()
		if not converged:
			cluster_name = 'issue_cluster.xyz'
			errorMessage = 'The optimisation of cluster ' + str(original_cluster) + ' did not optimise completely.\n'
			errorMessage += 'The cluster of issue before optimisation has been saved as: '+str(cluster_name)
			write(cluster_name,original_cluster)
			raise Exception(errorMessage)
	except Exception as exception_message:
		cluster_name = 'issue_cluster.xyz'
		errorMessage = 'The optimisation of cluster ' + str(original_cluster) + ' did not optimise completely.\n'
		errorMessage += 'The cluster of issue before optimisation has been saved as: '+str(cluster_name)+'\n'
		errorMessage += exception_message
		write(cluster_name,original_cluster)
		raise Exception(errorMessage)
	return cluster
Beispiel #13
0
	def adjust_z_axis(self, cluster):
		if self.surface == None:
			return
		'''
		surface_constraints = []
		for atom in self.surface:
			surface_constraints.append(MyConstraint(atom.index,(0,0,1)))
		'''
		surface_constraints = []
		#surface_constraints.append(ExternalForce(0, 0, 10))
		all_bonds = []
		all_angles = []
		all_dihedrals = []
		for index_1 in range(len(self.surface)):
			for index_2 in range(index_1+1,len(self.surface)):
				bonds_distance = get_distance(self.surface[index_1],self.surface[index_2])
				bond = [bonds_distance, [index_1,index_2]]
				all_bonds.append(bond)
				"""
				for index_3 in range(index_2+1,len(self.surface)): 
					angle_indices = [[index_1,index_2,index_3],[index_3,index_1,index_2],[index_2,index_3,index_1]]
					for angle_indice in angle_indices:
						angle = [self.surface.get_angle(*angle_indice) * pi / 180, angle_indice]
						all_angles.append(angle)
					'''
					for index_4 in range(index_3+1,len(self.surface)):  
						dihedral_indices = [[index_1,index_2,index_3,index_4],[index_1,index_2,index_3,index_4],[index_1,index_2,index_3,index_4]]
						for dihedral_indice in dihedral_indices:
							dihedral = [self.surface.get_dihedral(*dihedral_indice) * pi / 180, dihedral_indice]
							all_dihedrals.append(dihedral)
					'''
				"""
		surface_constraints.append(FixInternals(bonds=all_bonds, angles=all_angles, dihedrals=all_dihedrals))
		#self.surface.set_constraint(surface_constraints)

		c = FixAtoms(indices=range(len(self.surface),len(self.surface)+len(cluster)))
		cluster_constraints = [c]
		#cluster.set_constraint(cluster_constraints)

		for atom in self.surface:
			atom.z -= 40.0

		system = self.surface + cluster
		system.set_calculator(EMT())
		system.set_constraint(surface_constraints+cluster_constraints)
		dyn = FIRE(system)
		converged = False
		import pdb; pdb.set_trace()
		try:
			dyn.run(fmax=0.01,steps=5000)
			converged = dyn.converged()
			if not converged:
				import os
				name = os.path.basename(os.getcwd())
				errorMessage = 'The optimisation of cluster ' + name + ' did not optimise completely.'
				print(errorMessage, file=sys.stderr)
				print(errorMessage)
		except:
			print('Local Optimiser Failed for some reason.')
		import pdb; pdb.set_trace()
Beispiel #14
0
def test_fix_bond_length_mic():
    import ase
    from ase.calculators.lj import LennardJones
    from ase.constraints import FixBondLength
    from ase.optimize import FIRE

    for wrap in [False, True]:
        a = ase.Atoms('CCC',
                      positions=[[1, 0, 5],
                                 [0, 1, 5],
                                 [-1, 0.5, 5]],
                      cell=[10, 10, 10],
                      pbc=True)

        if wrap:
            a.set_scaled_positions(a.get_scaled_positions() % 1.0)
        a.calc = LennardJones()
        a.set_constraint(FixBondLength(0, 2))

        d1 = a.get_distance(0, 2, mic=True)

        FIRE(a, logfile=None).run(fmax=0.01)
        e = a.get_potential_energy()
        d2 = a.get_distance(0, 2, mic=True)
        assert abs(e - -2.034988) < 1e-6
        assert abs(d1 - d2) < 1e-6
Beispiel #15
0
def Minimisation_Function(cluster, collection, cluster_name):
    cluster.pbc = False
    ####################################################################################################################
    # Perform the local optimisation method on the cluster.
    # Parameter sequence: [p, q, a, xi, r0]
    Gupta_parameters = {'Cu': [10.960, 2.2780, 0.0855, 1.224, 2.556]}
    cluster.set_calculator(Gupta(Gupta_parameters, cutoff=1000, debug=False))
    dyn = FIRE(cluster, logfile=None)
    startTime = time.time()
    converged = False
    try:
        dyn.run(fmax=0.01, steps=5000)
        converged = dyn.converged()
        if not converged:
            errorMessage = 'The optimisation of cluster ' + str(
                cluster_name) + ' did not optimise completely.'
            print(errorMessage, file=sys.stderr)
            print(errorMessage)
    except:
        print('Local Optimiser Failed for some reason.')
    endTime = time.time()
    ####################################################################################################################
    # Write information about the algorithm
    Info = {}
    Info["INFO.txt"] = ''
    Info["INFO.txt"] += ("No of Force Calls: " +
                         str(dyn.get_number_of_steps()) + '\n')
    Info["INFO.txt"] += ("Time (s): " + str(endTime - startTime) + '\n')
    #Info["INFO.txt"] += ("Cluster converged?: " + str(dyn.converged()) + '\n')
    ####################################################################################################################
    return cluster, converged, Info
Beispiel #16
0
def get_elastic_constants(pot_path=None,
                          calculator=None,
                          delta=1e-2,
                          symbol="W"):
    """
    return lattice parameter, and cubic elastic constants: C11, C12, 44
    using matscipy function
    pot_path - path to the potential

    symbol : string
        Symbol of the element to pass to ase.lattuce.cubic.SimpleCubicFactory
        default is "W" for tungsten
    """

    unit_cell = bulk(symbol)

    if (pot_path is not None) and (calculator is None):
        # create lammps calculator with the potential
        lammps = LAMMPSlib(lmpcmds=["pair_style eam/fs",
                           "pair_coeff * * %s W" % pot_path],
                           atom_types={'W': 1}, keep_alive=True)
        calculator = lammps

    unit_cell.set_calculator(calculator)

#   simple calculation to get the lattice constant and cohesive energy
#    alat0 = W.cell[0][1] - W.cell[0][0]
    sf = StrainFilter(unit_cell)  # or UnitCellFilter(W) -> to minimise wrt pos, cell
    opt = FIRE(sf)
    opt.run(fmax=1e-4)  # max force in eV/A
    alat = unit_cell.cell[0][1] - unit_cell.cell[0][0]
#    print("a0 relaxation %.4f --> %.4f" % (a0, a))
#    e_coh = W.get_potential_energy()
#    print("Cohesive energy %.4f" % e_coh)

    Cij, Cij_err = fit_elastic_constants(unit_cell,
                                         symmetry="cubic",
                                         delta=delta)

    Cij = Cij/GPa  # unit conversion to GPa

    elasticMatrix3x3 = Cij[:3, :3]
    # average of diagonal elements: C11, C22, C33
    C11 = elasticMatrix3x3.diagonal().mean()
    # make mask to extract non diagonal elements
    mask = np.ones((3, 3), dtype=bool)
    np.fill_diagonal(mask, False)

    # average of all non diagonal elements from 1 to 3
    C12 = elasticMatrix3x3[mask].mean()

    # average of diagonal elements from 4 till 6: C44, C55, C66,
    C44 = Cij[3:, 3:].diagonal().mean()

    # A = 2.*C44/(C11 - C12)

    if (pot_path is not None) and (calculator is None):
        lammps.lmp.close()

    return alat, C11, C12, C44
Beispiel #17
0
def minimize_energy(atoms, nstep, pressure_interval=10):
    bulkmodulus = 140e9 / 1e5  # Bulk modulus of typical metal (Cu), in bar.
    dyn = FIRE(atoms)
    unstress = Inhomogeneous_NPTBerendsen(atoms,
                                          50 * units.fs,
                                          0,
                                          taup=5000 * units.fs,
                                          compressibility=1 / bulkmodulus)
    dyn.attach(unstress.scale_positions_and_cell, interval=10)
    dyn.run(steps=nstep)
Beispiel #18
0
    def test_CuZr(self):
        # This is a test for the potential published in:
        # Mendelev, Sordelet, Kramer, J. Appl. Phys. 102, 043501 (2007)
        a = FaceCenteredCubic('Cu', size=[2, 2, 2])
        calc = EAM('CuZr_mm.eam.fs', kind='eam/fs')
        a.set_calculator(calc)
        FIRE(StrainFilter(a, mask=[1, 1, 1, 0, 0, 0]),
             logfile=None).run(fmax=0.001)
        a_Cu = a.cell.diagonal().mean() / 2
        #print('a_Cu (3.639) = ', a_Cu)
        self.assertAlmostEqual(a_Cu, 3.639, 3)

        a = HexagonalClosedPacked('Zr', size=[2, 2, 2])
        a.set_calculator(calc)
        FIRE(StrainFilter(a, mask=[1, 1, 1, 0, 0, 0]),
             logfile=None).run(fmax=0.001)
        a, b, c = a.cell / 2
        #print('a_Zr (3.220) = ', norm(a), norm(b))
        #print('c_Zr (5.215) = ', norm(c))
        self.assertAlmostEqual(norm(a), 3.220, 3)
        self.assertAlmostEqual(norm(b), 3.220, 3)
        self.assertAlmostEqual(norm(c), 5.215, 3)

        # CuZr3
        a = L1_2(['Cu', 'Zr'], 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)
        self.assertAlmostEqual(a.cell.diagonal().mean() / 2, 4.324, 3)

        # Cu3Zr
        a = L1_2(['Zr', '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)
        self.assertAlmostEqual(a.cell.diagonal().mean() / 2, 3.936, 3)

        # CuZr
        a = B2(['Zr', 'Cu'], size=[2, 2, 2], latticeconstant=3.3)
        a.set_calculator(calc)
        FIRE(UnitCellFilter(a, mask=[1, 1, 1, 0, 0, 0]),
             logfile=None).run(fmax=0.001)
        self.assertAlmostEqual(a.cell.diagonal().mean() / 2, 3.237, 3)
Beispiel #19
0
 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)
Beispiel #20
0
 def _optimize(self):
     """Perform an optimization."""
     self._atoms.set_momenta(np.zeros(self._atoms.get_momenta().shape))
     geo_opt = FIRE(self._atoms)
     geo_opt.run(fmax=5e-02)
     ecf = ExpCellFilter(self._atoms)
     opt = self._optimizer(ecf,
                           trajectory='qn%05i.traj' % self._counter,
                           logfile='qn%05i.log' % self._counter)
     self._log('msg', 'Optimization: qn%05i' % self._counter)
     opt.run(fmax=self._fmax)
     self._log('ene')
Beispiel #21
0
def calc_gap():
    oraxis = '0,0,1'
    pot_param = PotentialParameters()
    ener_per_atom = pot_param.gs_ener_per_atom()
    selected_grains = GrainBoundary.select().where(
        GrainBoundary.orientation_axis == oraxis).where(
            GrainBoundary.boundary_plane != oraxis)

    f = open('./locenviron/gap_energies.dat', 'a')
    for gb in selected_grains.order_by(GrainBoundary.angle)[2:]:
        subgbs = (gb.subgrains.select(
            GrainBoundary,
            SubGrainBoundary).where(SubGrainBoundary.potential ==
                                    'PotBH.xml').join(GrainBoundary).dicts())
        subgbs = [
            (16.02 * (subgb['E_gb'] -
                      float(subgb['n_at'] * ener_per_atom['PotBH.xml'])) /
             (2.0 * subgb['area']), subgb) for subgb in subgbs
        ]
        subgbs.sort(key=lambda x: x[0])
        try:
            print subgbs[0][1]['path']
            continue

            target_dir = os.path.join('./grain_boundaries',
                                      subgbs[0][1]['path'])
            struct_file = os.path.join(target_dir,
                                       subgbs[0][1]['gbid']) + '_traj.xyz'
            print struct_file
            ats = AtomsReader(struct_file)[-1]
            pot = Potential('IP GAP', param_filename='gp33b.xml')
            ats.set_calculator(pot)
            print subgbs[0][1]['n_at'], subgbs[0][1]['area']
            strain_mask = [0, 0, 1, 0, 0, 0]
            ucf = UnitCellFilter(ats, strain_mask)
            opt = FIRE(ucf)
            FORCE_TOL = 0.1
            opt.run(fmax=FORCE_TOL)
            gap_en = ats.get_potential_energy()
            print gap_en
            print round(gb.angle * (180.0 / 3.14159), 3), round(
                subgbs[0][0], 3), 16.02 * (gap_en - float(
                    subgbs[0][1]['n_at'] * ener_per_atom['gp33b.xml'])) / (
                        2.0 * subgbs[0][1]['area'])
            print >> f, round(gb.angle * (180.0 / 3.14159), 3), round(
                subgbs[0][0], 3), 16.02 * (gap_en - float(
                    subgbs[0][1]['n_at'] * ener_per_atom['gp33b.xml'])) / (
                        2.0 * subgbs[0][1]['area'])
            ats.write('./locenviron/{}.xyz'.format(subgbs[0][1]['gbid']))
        except IndexError:
            print '\t', round(gb.angle * (180.0 / 3.14159), 3), subgbs
Beispiel #22
0
def _calc_quick(atoms, supercell=(1, 1, 1), delta=0.01):
    """Calculates the Hessian for a given atoms object just like :func:`calc`,
    *but*, it uses symmetry to speed up the calculation. Depending on the
    calculator being used, it is possible that the symmetrized result may be
    different from the full result with all displacements, done manually by
    :func:`calc`.

    Args:
        atoms (matdb.atoms.Atoms): atomic structure of the *primitive*.
        supercell (list): or `tuple` or :class:`numpy.ndarray` specifying the
          integer supercell matrix.
        delta (float): displacement in Angstroms of each atom when computing the
          phonons. 

    Returns:
        numpy.ndarray: Hessian matrix that has dimension `(natoms*3, natoms*3)`,
        where `natoms` is the number of atoms in the *supercell*.
    """
    #We need to make sure we are at the zero of the potential before
    ratoms = atoms.copy()
    try:
        with open("phonons.log", 'w') as f:
            with redirect_stdout(f):
                print(ratoms.get_forces())
                minim = FIRE(ratoms)
                minim.run(fmax=1e-4, steps=100)
    except:
        #The potential is unstable probably. Issue a warning.
        msg.warn(
            "Couldn't optimize the atoms object. Potential may be unstable.")

    primitive = matdb_to_phonopy(ratoms)
    phonon = Phonopy(primitive, conform_supercell(supercell))
    phonon.generate_displacements(distance=delta)
    supercells = phonon.get_supercells_with_displacements()
    pot = atoms.get_calculator()
    assert pot is not None

    forces = []
    for scell in supercells:
        matoms = phonopy_to_matdb(scell)
        #Call a manual reset of the calculator so that we explicitly recalculate
        #the forces for the current atoms object.
        pot.reset()
        matoms.set_calculator(pot)
        forces.append(matoms.get_forces())

    phonon.set_forces(forces)
    phonon.produce_force_constants()
    return unroll_fc(phonon._force_constants)
Beispiel #23
0
    def build_h_nebpath(self, struct_path="fe_bcc.xyz", neb_path=np.array([0.25, 0.0, -0.25]), 
                        alat=2.8297, knots=5, sup_cell=5, fmax=1.e-4):
        """
        Takes a vector neb_path, and generates n intermediate images along the minimum energy path.
        the struct path should point to the relaxed structure.
        """
        POT_DIR = os.path.join(app.root_path, 'potentials')
        eam_pot = os.path.join(POT_DIR, 'PotBH.xml')
        r_scale = 1.00894848312
        mm_pot = Potential('IP EAM_ErcolAd do_rescale_r=T r_scale={0}'.format(r_scale), param_filename=eam_pot)

        ats_ini = AtomsReader(struct_path)[-1]
        #Pick the top tetrahedral H position in the cell [[1,0,0],[0,1,0],[0,0,1]]
        tetra_pos = alat*np.array([0.5, 0.0, 0.75])
        mid_point = 0.5*(np.diag(ats_ini.get_cell()))
        mid_point = [((sup_cell-1)/2.)*alat for sp in range(3)]
        h_pos = tetra_pos + mid_point

        disloc_ini = ats_ini.copy()
        h_tmp = h_pos
        disloc_ini.add_atoms(np.array(h_tmp), 1)

        disloc_fin = ats_ini.copy()
        h_tmp = h_pos + neb_path*alat
        disloc_fin.add_atoms(h_tmp,1)

#Relax images at the start and end of trajectory.
        disloc_ini.set_calculator(mm_pot)
        opt = FIRE(disloc_ini)
        opt.run(fmax=fmax)

        disloc_fin.set_calculator(mm_pot)
        opt = FIRE(disloc_fin)
        opt.run(fmax=fmax)

        return disloc_ini, disloc_fin
Beispiel #24
0
    def test_symmetry_sparse(self):
        """
        Test the symmetry of the dense Hessian matrix 

        """
        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)
        dyn = FIRE(atoms)
        dyn.run(fmax=1e-5)
        H = calc.hessian_matrix(atoms)
        H = H.todense()
        self.assertArrayAlmostEqual(np.sum(np.abs(H-H.T)), 0, tol=1e-5)
def relax_atoms(atoms,
                tol=1e-3,
                method='lbfgs_precon',
                max_steps=1000,
                traj_file=None,
                **kwargs):
    import model
    atoms.set_calculator(model.calculator)
    if hasattr(model, 'Optimizer'):
        method = 'model_optimizer'
        opt = model.Optimizer(atoms)
        opt.run(tol, max_steps)
    elif method.startswith('lbfgs') or method == 'fire' or method == 'cg_n':
        if method == 'lbfgs_ASE':
            from ase.optimize import LBFGS
            opt = LBFGS(atoms, **kwargs)
        elif method == 'cg_n':
            from quippy import Minim
            opt = Minim(atoms,
                        relax_positions=True,
                        relax_cell=False,
                        method='cg_n')
        else:
            from ase.optimize.precon.precon import Exp
            from ase.optimize.precon.lbfgs import PreconLBFGS
            precon = None
            if method.endswith('precon'):
                precon = Exp(3.0, recalc_mu=True)
            if method.startswith('lbfgs'):
                opt = PreconLBFGS(atoms, precon=precon, **kwargs)
            else:
                opt = FIRE(atoms, **kwargs)
        if traj_file is not None and method != 'cg_n':
            traj = open(traj_file, 'w')

            def write_trajectory():
                write(traj, atoms, format='extxyz')

            opt.attach(write_trajectory)
        opt.run(tol, max_steps)
        try:
            traj.close()
        except:
            pass
    else:
        raise ValueError('unknown method %s!' % method)

    return atoms
Beispiel #26
0
 def test_hessian_random_structure(self):
     """
     Test the computation of the Hessian matrix 
     """
     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)
     dyn = FIRE(atoms)
     dyn.run(fmax=1e-5)
     H_analytical = calc.hessian_matrix(atoms)
     H_analytical = H_analytical.todense()
     H_numerical = fd_hessian(atoms, dx=1e-5, indices=None)
     H_numerical = H_numerical.todense()
     self.assertArrayAlmostEqual(H_analytical, H_numerical, tol=self.tol)
Beispiel #27
0
    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 Minimisation_Function(cluster, calculator):
    cluster.pbc = False
    cluster.set_calculator(calculator)
    from ase.optimize import FIRE
    dyn = FIRE(cluster, logfile=None)
    try:
        dyn.run(fmax=0.01, steps=5000)
        converged = dyn.converged()
        if not converged:
            errorMessage = 'The optimisation of cluster ' + str(
                cluster_name) + ' did not optimise completely.'
            print(errorMessage, file=sys.stderr)
            print(errorMessage)
    except Exception:
        print('Local Optimiser Failed for some reason.')
    return cluster
Beispiel #29
0
def optimize(neb="", name=''):
    optimizer = FIRE(neb, trajectory=name + '.traj')
    optimizer.run(fmax=100000)
    optimizer.run(fmax=50000)
    optimizer.run(fmax=10000)
    optimizer.run(fmax=5000)
    optimizer.run(fmax=1000)
    optimizer.run(fmax=500)
    optimizer.run(fmax=100)
    optimizer.run(fmax=50)
    optimizer.run(fmax=10)
    optimizer.run(fmax=0.5)
    optimizer.run(fmax=0.1)
    optimizer.run(fmax=0.09)
    optimizer.run(fmax=0.07)
    optimizer.run(fmax=0.05)
Beispiel #30
0
    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)