Example #1
0
def MakeAtoms(elem1, elem2=None):
    if elem2 is None:
        elem2 = elem1
    a1 = reference_states[elem1]['a']
    a2 = reference_states[elem2]['a']
    a0 = (0.5 * a1**3 + 0.5 * a2**3)**(1.0/3.0) * 1.03
    if ismaster:
        # 50*50*50 would be big enough, but some vacancies are nice.
        print "Z1 = %i,  Z2 = %i,  a0 = %.5f" % (elem1, elem2, a0)
        atoms = FaceCenteredCubic(symbol='Cu', size=(51,51,51))
        nremove = len(atoms) - 500000
        assert nremove > 0
        remove = np.random.choice(len(atoms), nremove, replace=False)
        del atoms[remove]
        if isparallel:
            atoms = atoms.repeat(cpuLayout)
        if elem1 != elem2:
            z = atoms.get_atomic_numbers()
            z[np.random.choice(len(atoms), len(atoms)/2, replace=False)] = elem2
            atoms.set_atomic_numbers(z)
    else:
        atoms = None
    if isparallel:
        atoms = MakeParallelAtoms(atoms, cpuLayout)
    MaxwellBoltzmannDistribution(atoms, T * units.kB)
    return atoms
Example #2
0
def test_calculator():

  # create calculator
  #modelname = 'ex_model_Ar_P_MLJ_C'
  modelname = 'ex_model_Ar_P_Morse_07C'

  calc = KIMCalculator(modelname)

  # create a SC cyrstal
  argon = SimpleCubic(directions=[[1,0,0], [0,1,0], [0,0,1]], size=(2,2,2),
                      symbol='Ar', pbc=(1,1,0), latticeconstant=3.0)

  # attach calculator to atoms
  argon.set_calculator(calc)

  # compute energy and forces
  print_values(argon, 'SC argon, pbc=(1,1,0)')

  # change pbc, and then compute energy and forces
  argon.set_pbc([0,0,0])
  print_values(argon, 'SC argon, pbc=(0,0,0)')

  # create a FCC crystal
  argon2 = FaceCenteredCubic(directions=[[1,0,0], [0,1,0], [0,0,1]], size=(2,2,2),
                             symbol='Ar', pbc=(1,1,0), latticeconstant=3.0)

  # attach the SAME calculator to the new atoms
  argon2.set_calculator(calc)

  # compute energy and forces
  print_values(argon2, 'FCC argon, pbc=(1,1,0)')
Example #3
0
    def setCrystal(self):
        crys = self.setting['structure']
        if crys == 'rnd':
            print 'rnd implemented'
            self.genRandomPositions()
            d = 1.104  # N2 bondlength
            formula =  'Cu'+str(len(self.pos))
            cell =[(self.px*self.a0,0,0),(0,self.py*self.a0,0),(0,0,self.pz*self.a0)] 
            self.bulk = ase.Atoms(formula, self.pos, pbc=True, cell=cell)

        if crys == 'fcc':
            print 'fcc implemented'
            from ase.lattice.cubic import FaceCenteredCubic
            self.bulk = FaceCenteredCubic(directions=[[1,0,0], [0,1,0], [0,0,1]],
                                        size=(self.px,self.py,self.pz), symbol='Cu',
                    pbc=(1,1,1), latticeconstant=self.a0)

        if crys == 'bcc':
            print 'bcc implemented'
            from ase.lattice.cubic import BodyCenteredCubic
            self.bulk = BodyCenteredCubic(directions=[[1,0,0], [0,1,0], [0,0,1]],
                                        size=(self.px,self.py,self.pz), symbol='Cu',
                    pbc=(1,1,1), latticeconstant=self.a0)

        if self.setting['structure'] == 'hcp':
            print 'hcp no implemented'
            sys.exit(0)


        self.setting['nAtoms'] =  self.bulk.get_number_of_atoms()
        self.calcAtoms2()
        self.genStructure()
        self.pos = self.bulk.get_positions()
Example #4
0
def test_matplotlib_plot(plt):
    slab = FaceCenteredCubic('Au', size=(2, 2, 2))

    fig, ax = plt.subplots()
    plot_atoms(slab, ax, radii=0.5, rotation=('10x,10y,10z'), show_unit_cell=0)

    assert len(ax.patches) == len(slab)
    print(ax)
Example #5
0
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_numpy_array():
    # Tests Issue #787
    atoms = FaceCenteredCubic(size=[1, 1, 1],
                              symbol='Cu',
                              latticeconstant=2,
                              pbc=True)

    find_mic(atoms.positions, np.array(atoms.cell), pbc=True)
Example #7
0
def main():
	for x in fccs+bccs+hcps+diamonds+rocksalts+zincblendes+cscls:
		f = x in fccs
		b = x in bccs
		h = x in hcps
		d = x in diamonds
		r = x in rocksalts
		z = x in zincblendes
		c = x in cscls
		
		try: 
			if   f: a = FaceCenteredCubic(x[0]).get_cell()[0][0]/2
			elif b: a = BodyCenteredCubic(x[0]).get_cell()[0][0]/2
			elif d: a = Diamond(x[0]).get_cell()[0][0]/2
			elif h: 
					cell = HexagonalClosedPacked(x[0]).get_cell()
					a,c = cell[0][0],cell[2][2]

			elif r | z | c: a = dataLookup(x[0])
			else: raise NotImplementedError

		except ValueError: 
			a = sum([radDict[e] for e in elems])/len(elems)
			print "Had to guess lattice constant of "+x[0]

		if   f: name,struc,pos,cell,n = '-fcc',       'fcc',        [[0,0,0]],                  [[0,a,a],[a,0,a],[a,a,0]],   1
		elif b: name,struc,pos,cell,n = '-bcc',       'bcc',        [[0,0,0]],                  [[a,a,-a],[-a,a,a],[a,-a,a]],1
		elif h: name,struc,pos,cell,n = '-hcp',       'hexagonal',  [[0,0,0],[2./3,1./3,1./2]], [a,a,c,90,90,120],           2
		elif d: name,struc,pos,cell,n = '-diamond',   'diamond',    [[0,0,0],[0.25,0.25,0.25]], [[0,a,a],[a,0,a],[a,a,0]],   2
		elif z: name,struc,pos,cell,n = '-zincblende','zincblende', [[0,0,0],[0.25,0.25,0.25]], [[0,a,a],[a,0,a],[a,a,0]],   1
		elif r: name,struc,pos,cell,n = '-rocksalt',  'rocksalt',   [[0,0,0],[0.5,0.5,0.5]],    [[0,a,a],[a,0,a],[a,a,0]],   1
		elif c: name,struc,pos,cell,n = '-cscl',      'cubic',      [[0,0,0],[0.5,0.5,0.5]],    [a,a,a,90,90,90],            1

		mag     = magLookup(x[0])
		elems 	= parseChemicalFormula(x[0]).keys()*n
		magmoms = [magmomInit if e in magElems else 0 for e in elems] 

		atoms = Atoms(elems,scaled_positions=pos,cell=cell,pbc=[1,1,1],magmoms=magmoms,calculator=EMT())
		
		info = 	{'name': 		x[0]+name
				,'relaxed': 	False
				,'emt': 		atoms.get_potential_energy()/len(elems)	#normalized to per-atom basis
				,'comments':	'Autogenerated by createTrajs'
				,'kind': 		'bulk' # vs surface/molecules
				### Stuff for bulk
				,'structure': 	struc
				### Stuff for surfaces
				,'parent': 		None 
				,'sites': 		None
				,'facet': 		None
				,'xy': 			None
				,'layers': 		None
				,'constrained': None
				,'symmetric': 	None
				,'vacuum': 		None
				,'adsorbates':	None}

		db.write(atoms,key_value_pairs=info)
    def test_hessian_monoatomic(self):
        """Calculate Hessian matrix of pure Cu

        Reference: finite difference approximation of 
        Hessian from ASE
        """
        atoms = FaceCenteredCubic('Cu', size=[4, 4, 4])
        calculator = EAM('CuAg.eam.alloy')
        self._test_hessian(atoms, calculator)
Example #9
0
 def test_forces_random_structure(self):
     atoms = FaceCenteredCubic('H', size=[2,2,2], latticeconstant=2.37126)
     calc = Polydisperse(InversePowerLawPotential(1.0, 1.4, 0.1, 3, 1, 2.22))
     atoms.set_masses(masses=np.repeat(1.0, len(atoms)))       
     atoms.set_array("size", np.random.uniform(1.0, 2.22, size=len(atoms)), dtype=float)
     atoms.set_calculator(calc)
     f = atoms.get_forces()
     fn = calc.calculate_numerical_forces(atoms, d=0.0001)
     self.assertArrayAlmostEqual(f, fn, tol=self.tol)
Example #10
0
def create_fcc_argon(alat=5.26):
    argon = FaceCenteredCubic(
        directions=[[1, 0, 0], [0, 1, 0], [0, 0, 1]],
        size=(2, 2, 2),
        symbol='Ar',
        pbc=(0, 0, 0),
        latticeconstant=alat,
    )
    return argon
Example #11
0
def test_isolation_3D():
    atoms = FaceCenteredCubic(size=(2, 2, 2), symbol='Cu', pbc=(1, 1, 1))

    result = isolate_components(atoms)
    assert len(result) == 1
    key, components = list(result.items())[0]
    assert key == '3D'
    assert len(components) == 1
    bulk = components[0]
    assert bulk.get_chemical_formula() == atoms.get_chemical_formula()
Example #12
0
def atoms():
    # (100) oriented block
    atoms = FaceCenteredCubic(size=(5, 5, 5), symbol=symb, pbc=(1, 1, 0))
    assert len(atoms) == 5 * 5 * 5 * 4
    c = atoms.get_cell()
    checkang(c[0], c[1], pi / 2)
    checkang(c[0], c[2], pi / 2)
    checkang(c[1], c[2], pi / 2)
    assert np.abs(5 * a0 - c[2, 2]) < 1e-10
    return atoms
Example #13
0
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
Example #14
0
def make_fcc_110_cell(size=(1, 1, 1), symbols=['Ni'], pbc=(1, 1, 1)):
    direction_x = [0, 0, 1]
    direction_y = [1, -1, 0]
    direction_z = [1, 1, 0]

    atoms = FaceCenteredCubic(\
            directions=[direction_x,direction_y,direction_z],
            size=size,
            symbol=symbols[0],
            pbc=pbc)
    return atoms
def test_maxwellboltzmann():
    from ase.md.velocitydistribution import MaxwellBoltzmannDistribution
    from ase.lattice.cubic import FaceCenteredCubic

    atoms = FaceCenteredCubic(size=(50, 50, 50), symbol="Cu", pbc=False)
    print("Number of atoms:", len(atoms))
    MaxwellBoltzmannDistribution(atoms, temperature_K=0.1 / kB)
    temp = atoms.get_kinetic_energy() / (1.5 * len(atoms))

    print("Temperature", temp, " (should be 0.1)")
    assert abs(temp - 0.1) < 1e-3
 def test_hessian_sparse(self):
     for calc in [{(1, 1): LennardJonesCut(1, 1, 3)}]:
         atoms = FaceCenteredCubic('H',
                                   size=[2, 2, 2],
                                   latticeconstant=1.550)
         a = calculator.PairPotential(calc)
         atoms.set_calculator(a)
         H_analytical = a.calculate_hessian_matrix(atoms, "sparse")
         H_numerical = fd_hessian(atoms, dx=1e-5, indices=None)
         self.assertArrayAlmostEqual(H_analytical.todense(),
                                     H_numerical.todense(),
                                     tol=self.tol)
Example #17
0
    def test_stress(self):
        a = FaceCenteredCubic('Au', size=[2,2,2])
        calc = EAM('Au-Grochola-JCP05.eam.alloy')
        a.set_calculator(calc)
        self.assertArrayAlmostEqual(a.get_stress(), calc.calculate_numerical_stress(a), tol=self.tol)

        sx, sy, sz = a.cell.diagonal()
        a.set_cell([sx, 0.9*sy, 1.2*sz], scale_atoms=True)
        self.assertArrayAlmostEqual(a.get_stress(), calc.calculate_numerical_stress(a), tol=self.tol)

        a.set_cell([[sx, 0.1*sx, 0], [0, 0.9*sy, 0], [0, -0.1*sy, 1.2*sz]], scale_atoms=True)
        self.assertArrayAlmostEqual(a.get_stress(), calc.calculate_numerical_stress(a), tol=self.tol)
Example #18
0
def test_matplotlib_plot(plt):
    from ase.visualize.plot import plot_atoms
    from ase.lattice.cubic import FaceCenteredCubic

    slab = FaceCenteredCubic('Au', size=(2, 2, 2))

    fig, ax = plt.subplots()
    plot_atoms(slab, ax, radii=0.5, rotation=('10x,10y,10z'),
               show_unit_cell=0)

    assert len(ax.patches) == len(slab)
    print(ax)
Example #19
0
def make_fcc_100_slab(size=(2, 2, 3), symbol='Cu', pbc=(1, 1, 0)):
    direction_x = [1, 0, 0]
    direction_y = [0, 1, 0]
    direction_z = [0, 0, 1]

    atoms = FaceCenteredCubic(\
            directions=[direction_x,
                        direction_y,
                        direction_z],
            size=size,
            symbol=symbol,
            pbc=pbc)
Example #20
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)
    def Surface111(self, EMT, PARAMETERS):
        """ The Method calculates and returns the surface energy for the given element along the [1,1,1] 
            direction in the FCC crystal structure. """
        # The size of the crystals are set " NEED TO THINK ABOUT THESE LATER! "
        S111 = 4, 4, 4
        # 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.
        Surface111 = FaceCenteredCubic(size=S111,
                                       directions=[[1, -1, 0], [1, 1, -2],
                                                   [1, 1, 1]],
                                       symbol=self.Element,
                                       pbc=(1, 1, 0))
        Surface111.set_calculator(EMT)

        # A structural relaxsation is run for the surface crystal in order to secure
        # the correct structure of the crystal.
        dyn111 = BFGS(Surface111, logfile=None)
        dyn111.run(fmax=0.01)

        # The referance bulk crystals are created
        Bulk111 = FaceCenteredCubic(size=S111,
                                    directions=[[1, -1, 0], [1, 1, -2],
                                                [1, 1, 1]],
                                    symbol=self.Element)

        # The calculator is assigned
        Bulk111.set_calculator(EMT)

        # The surface area is calculated
        # The cross product between the x and y axis in the crystal is determined
        Cross111 = numpy.cross(Bulk111.get_cell()[:, 0],
                               Bulk111.get_cell()[:, 1])
        # The area of the surface is determined from the formular A = |X x Y|.
        area111 = numpy.sqrt(numpy.dot(Cross111, Cross111))

        # The surface energy is calculated and returned (two surfaces are present in
        # SurfaceRelaxed)
        return ((Surface111.get_potential_energy() -
                 Bulk111.get_potential_energy()) / 2 / area111)
 def test_symmetry_sparse(self):
     for calc in [{(1, 1): LennardJonesCut(1, 1, 3)}]:
         atoms = FaceCenteredCubic('H',
                                   size=[2, 2, 2],
                                   latticeconstant=1.550)
         a = calculator.PairPotential(calc)
         atoms.set_calculator(a)
         H_numerical = fd_hessian(atoms, dx=1e-5, indices=None)
         H_numerical = H_numerical.todense()
         self.assertArrayAlmostEqual(np.sum(
             np.abs(H_numerical - H_numerical.T)),
                                     0,
                                     tol=1e-5)
    def test_hessian_monoatomic_with_duplicate_pairs(self):
        """Calculate Hessian matrix of pure Cu

        In a small system, the same pair (i,j) will
        appear multiple times in the neighbor list,
        with different pair distance.

        Reference: finite difference approximation of 
        Hessian from ASE
        """
        atoms = FaceCenteredCubic('Cu', size=[2, 2, 2])
        calculator = EAM('CuAg.eam.alloy')
        self._test_hessian(atoms, calculator)
Example #24
0
def MakeCu(T=300, size=(29, 29, 30)):
    print "Preparing", T, "K Copper system."
    atoms = FaceCenteredCubic(directions=[[1, 0, 0], [0, 1, 0], [0, 0, 1]],
                              symbol='Cu',
                              size=size)
    atoms.set_calculator(EMT())
    MaxwellBoltzmannDistribution(atoms, 2 * T * units.kB)
    #dyn = VelocityVerlet(atoms, 5*units.fs)
    dyn = Langevin(atoms, 5 * units.fs, T * units.kB, 0.05)
    dyn.run(50)
    print "Done.  Temperature =", temperature(atoms), \
          "K.  Number of atoms: ", len(atoms)
    return atoms
Example #25
0
def test_antisymmetry():
    size = 2
    atoms = FaceCenteredCubic(size=[size, size, size],
                              symbol='Cu',
                              latticeconstant=2,
                              pbc=(1, 1, 1))

    vmin, vlen = get_distances(atoms.get_positions(),
                               cell=atoms.cell,
                               pbc=True)
    assert (vlen == vlen.T).all()

    for i, j in itertools.combinations(range(len(atoms)), 2):
        assert (vmin[i, j] == -vmin[j, i]).all()
Example #26
0
def make_fcc_111_cell(size=(1, 1, 1), symbols=['Ni'], pbc=(1, 1, 1)):
    _surface_direction = [1, 1, 1]

    directions = determine_direction_vectors_for_surface(
        direction=_surface_direction)

    size = (1, 1, 1)
    atoms = FaceCenteredCubic(\
            directions=directions,
            size=size,
            symbol=symbols[0],
            pbc=pbc)

    return atoms
    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
Example #28
0
    def test_calcenergy(self):

        atoms = FaceCenteredCubic(directions=[[1, 0, 0], [0, 1, 0], [0, 0, 1]],
                                  symbol="Cu",
                                  size=(3, 3, 3),
                                  pbc=True)
        atoms.calc = EMT()

        ekin, epot = calcenergy(atoms)

        if ekin is not None and epot is not None:
            self.assertTrue(True)
        else:
            self.assertTrue(False)
Example #29
0
def phonon_unfold():
    atoms = FaceCenteredCubic(size=(1, 1, 1), symbol="Cu", pbc=True)
    symbols = atoms.get_chemical_symbols()
    #symbols[-1] = 'Ag'
    atoms.set_chemical_symbols(symbols)
    calc = EMT()
    atoms.set_calculator(calc)
    phonon = calculate_phonon(atoms,
                              calc,
                              ndim=np.eye(3) * 2,
                              primitive_matrix=np.eye(3) / 1.0)

    kpts, x, X, names = kpath()
    kpts = [
        np.dot(
            k,
            np.linalg.inv((np.array([[0, 1, 1], [1, 0, 1], [1, 1, 0]]) / 2.0)))
        for k in kpts
    ]
    phonon.set_qpoints_phonon(kpts, is_eigenvectors=True)
    freqs, eigvecs = phonon.get_qpoints_phonon()

    sc = atoms
    sc_mat = np.linalg.inv((np.array([[0, 1, 1], [1, 0, 1], [1, 1, 0]]) / 2.0))
    spos = sc.get_scaled_positions()

    uf = phonon_unfolder(atoms, sc_mat, eigvecs, kpts)
    weights = uf.get_weights()

    ax = None
    ax = plot_band_weight([list(x)] * freqs.shape[1],
                          freqs.T * 33.356,
                          weights[:, :].T * 0.98 + 0.01,
                          xticks=[names, X],
                          axis=ax)

    # print freqs
    # for i in range(freqs.shape[1]):
    #    plt.plot(x, freqs[:, i], color='blue', alpha=0.2, linewidth=2.5)

    plt.xticks(X, names)
    plt.ylabel('Frequency (cm$^{-1}$)')
    plt.ylim([0, 350])
    plt.title('with defect (1/4) (method: reciprocal)')

    get_phonon_prim(ax)
    plt.savefig('defrec4.png')

    plt.show()
Example #30
0
def fcc211(symbol, size, a=None, vacuum=None, orthogonal=True):
    """FCC(211) surface.

    Does not currently support special adsorption sites.

    Currently only implemented for *orthogonal=True* with size specified
    as (i, j, k), where i, j, and k are number of atoms in each direction.
    i must be divisible by 3 to accommodate the step width.
    """
    if not orthogonal:
        raise NotImplementedError('Only implemented for orthogonal '
                                  'unit cells.')
    if size[0] % 3 != 0:
        raise NotImplementedError('First dimension of size must be '
                                  'divisible by 3.')
    atoms = FaceCenteredCubic(symbol,
                              directions=[[1, -1, -1],
                                          [0, 2, -2],
                                          [2, 1, 1]],
                              miller=(None, None, (2, 1, 1)),
                              latticeconstant=a,
                              size=(1, 1, 1),
                              pbc=True)
    z = (size[2] + 1) // 2
    atoms = atoms.repeat((size[0] // 3, size[1], z))
    if size[2] % 2:  # Odd: remove bottom layer and shrink cell.
        remove_list = [atom.index for atom in atoms
                       if atom.z < atoms[1].z]
        del atoms[remove_list]
        dz = atoms[0].z
        atoms.translate((0., 0., -dz))
        atoms.cell[2][2] -= dz

    atoms.cell[2] = 0.0
    atoms.pbc[2] = False
    if vacuum:
        atoms.center(vacuum, axis=2)

    # Renumber systematically from top down.
    orders = [(atom.index, round(atom.x, 3), round(atom.y, 3),
               -round(atom.z, 3), atom.index) for atom in atoms]
    orders.sort(key=itemgetter(3, 1, 2))
    newatoms = atoms.copy()
    for index, order in enumerate(orders):
        newatoms[index].position = atoms[order[0]].position.copy()

    # Add empty 'sites' dictionary for consistency with other functions
    newatoms.info['adsorbate_info'] = {'sites': {}}
    return newatoms