示例#1
0
def main(argv):
    format = None
    zmat = None

    while argv[0].startswith("--"):
        if argv[0] == '--format':
            format = argv[1]
            argv = argv[2:]
        elif argv[0] == '--zmatrix':
            __, zmat, v_name, __, __, __,__ = read_zmt_from_file(argv[1])
            argv = argv[2:]
        elif argv[0] == '--help':
            print __doc__
            return



    geo1 = read(argv[0], format = format)
    geos = [read(arg, format = format) for arg in argv[1:]]

    if zmat == None:
         fun = Cartesian()
    else:
         fun = ZMat(zmat)

    symbols = geo1.get_chemical_symbols()
    assert len(geos) > 0

    for geo in geos:
        assert geo.get_chemical_symbols() == symbols
        compare(geo1.get_positions(), geo.get_positions(), symbols, fun)
示例#2
0
    def check(self, filename='FORCE_CONSTANTS'):
        ref = io.read('SPOSCAR')
        files = shell_exec("ls dirs").split('\n')
        fc2 = readfc2(filename)
        np.set_printoptions(precision=2, suppress=True)
        vasprunxml = "dir_SPOSCAR/vasprun.xml"
        if exists(vasprunxml):
            vasprun = etree.iterparse(vasprunxml, tag='varray')
            forces0 = parseVasprun(vasprun, 'forces')
            print(forces0.max())
        else:
            forces0 = 0.0
        for file in files:
            print(file)
            POSCAR = 'dirs/%s/POSCAR' % file
            vasprunxml = "dirs/%s/vasprun.xml" % file
            atoms = io.read(POSCAR)
            u = atoms.positions - ref.positions
            f = -np.einsum('ijkl,jl', fc2, u)

            vasprun = etree.iterparse(vasprunxml, tag='varray')
            forces = parseVasprun(vasprun, 'forces') - forces0
            print(np.abs(f).max(), "\n")
            print(np.abs(forces - f).max())
            print(np.allclose(f, forces, atol=1e-2))
示例#3
0
def main(argv=[]):
    kwargs = getArgs(argv)
    nam = kwargs['file']
    fix = kwargs['layers']
    pad = kwargs['pad']
    v = kwargs['v']
    format = kwargs['format']

    if format:
        atoms = read(nam, format=format)
    elif "vasp" in nam or "POSCAR" in nam or "CONTCAR" in nam:
        atoms = read(nam, format="vasp")
    else:
        atoms = read(nam)
    if v: print "-file loaded."
    # TODO: ameliorate
    layerz = {round(a.z, 2): None for a in atoms}
    layerz_list = [None] + [z for z in sorted(layerz)]
    if v: print "layerz list:", layerz_list
    n_layers = len(layerz)
    atoms.set_tags([layerz_list.index(round(a.z, 2)) for a in atoms])
    if v: print "-tags set."
    constraint = FixAtoms(mask=[a.tag <= fix for a in atoms])

    atoms.set_constraint(constraint)
    if v: print "-constraints set."
    write('POSCAR' + pad, atoms, format='vasp', direct=True)
示例#4
0
def dcdft():
    os.environ['USER'] = '******'
    con = ase.db.connect('dcdft.json')
    with open('WIEN2k.txt') as fd:
        lines = fd.readlines()
    for line in lines[2:73]:
        words = line.split()
        symbol = words.pop(0)
        vol, B, Bp = (float(x) for x in words)
        filename = 'cif/' + symbol + '.cif'
        atoms = read(filename)
        M = {'Fe': 2.3,
             'Co': 1.2,
             'Ni': 0.6,
             'Cr': 1.5,
             'O': 1.5,
             'Mn': 2.0}.get(symbol)
        if M is not None:
            magmoms = [M] * len(atoms)
            if symbol in ['Cr', 'O', 'Mn']:
                magmoms[len(atoms) // 2:] = [-M] * (len(atoms) // 2)
            atoms.set_initial_magnetic_moments(magmoms)
        con.write(atoms, name=symbol, w2k_B=B, w2k_Bp=Bp, w2k_volume=vol)
        filename = 'pcif/' + symbol + '.cif'
        p = read(filename, primitive_cell=True)
        v = atoms.get_volume() / len(atoms)
        dv = v - p.get_volume() / len(p)
        p2 = read(filename)
        dv2 = v - p2.get_volume() / len(p2)
        print(symbol, vol - atoms.get_volume() / len(atoms),
              len(atoms), len(p), dv, dv2)
        print(p.info)
示例#5
0
def getjvq():
    from np.linalg import norm
    unit = io.read("POSCAR_unit")
    atoms = io.read("POSCAR")
    supercell = map(
        int,
        norm(
            atoms.cell,
            axis=1) /
        norm(
            unit.cell,
            axis=1) +
        [.5] *
        3)
    c = supercell
    q = []
    u = [int(x / 2) * 2 + 1 for x in c]
    for i in range(u[0]):
        for j in range(u[1]):
            for k in range(u[2]):
                b = np.array([float(i - c[0] / 2) / c[0],
                              float(j - c[1] / 2) / c[1],
                              float(k - c[2] / 2) / c[2]])
                q.append(b)
    allpos = np.load('allpos.npy')
    v = np.gradient(allpos)[0]
示例#6
0
 def _resume(self):
     """Attempt to resume a run, based on information in the log
     file. Note it will almost always be interrupted in the middle of
     either a qn or md run or when exceeding totalsteps, so it only has
     been tested in those cases currently."""
     f = paropen(self._logfile, 'r')
     lines = f.read().splitlines()
     f.close()
     self._log('msg', 'Attempting to resume stopped run.')
     self._log('msg', 'Using existing minima file with %i prior '
               'minima: %s' % (len(self._minima), self._minima_traj))
     mdcount, qncount = 0, 0
     for line in lines:
         if (line[:4] == 'par:') and ('Ediff' not in line):
             self._temperature = eval(line.split()[1])
             self._Ediff = eval(line.split()[2])
         elif line[:18] == 'msg: Optimization:':
             qncount = int(line[19:].split('qn')[1])
         elif line[:24] == 'msg: Molecular dynamics:':
             mdcount = int(line[25:].split('md')[1])
     self._counter = max((mdcount, qncount))
     if qncount == mdcount:
         # Either stopped during local optimization or terminated due to
         # max steps.
         self._log('msg', 'Attempting to resume at qn%05i' % qncount)
         if qncount > 0:
             atoms = io.read('qn%05i.traj' % (qncount - 1), index=-1)
             self._previous_optimum = atoms.copy()
             self._previous_energy = atoms.get_potential_energy()
         if os.path.getsize('qn%05i.traj' % qncount) > 0:
             atoms = io.read('qn%05i.traj' % qncount, index=-1)
         else:
             atoms = io.read('md%05i.traj' % qncount, index=-3)
         self._atoms.positions = atoms.get_positions()
         fmax = np.sqrt((atoms.get_forces() ** 2).sum(axis=1).max())
         if fmax < self._fmax:
             # Stopped after a qn finished.
             self._log('msg', 'qn%05i fmax already less than fmax=%.3f'
                       % (qncount, self._fmax))
             self._counter += 1
             return
         self._optimize()
         self._counter += 1
         if qncount > 0:
             self._check_results()
         else:
             self._record_minimum()
             self._log('msg', 'Found a new minimum.')
             self._log('msg', 'Accepted new minimum.')
             self._log('par')
     elif qncount < mdcount:
         # Probably stopped during molecular dynamics.
         self._log('msg', 'Attempting to resume at md%05i.' % mdcount)
         atoms = io.read('qn%05i.traj' % qncount, index=-1)
         self._previous_optimum = atoms.copy()
         self._previous_energy = atoms.get_potential_energy()
         self._molecular_dynamics(resume=mdcount)
         self._optimize()
         self._counter += 1
         self._check_results()
示例#7
0
def main(argv=[]):
    args = getArgs(argv)
    
    atoms = read(args.file, format=args.format) if args.format else read(args.file)
    
    atoms = correct_z(atoms)
    atoms = fix_layers(atoms, args.fix, args.n_layers)
    
    kw = {'format': 'vasp', 'direct': True, 'vasp5': True, 'sort':True}
    write('POSCAR' + args.pad, atoms, **kw)
示例#8
0
def main(argv=None):
    args = getArgs(argv)
    atoms = read(args.file, format=args.f) if args.f else struct = read(args.file)
    atoms = correct_z(atoms)
    kw = {"format": args.format}
    if args.format == 'vasp':
        kw['sort'] = True
        kw['vasp5'] = True
        kw['direct'] = True
    write(args.nam, atoms, **kw)
示例#9
0
 def getdispforce(self, files):
     force = ""
     disp = ""
     orig = io.read('POSCAR-supercell').positions
     for dir0 in files:
         forcearr = read_forces(
             'dirs/dir_%s/vasprun.xml' % dir0) / 25.7110  # in Rd/bohr
         force += matrixFormat(forcearr)
         disparr = (io.read('dirs/dir_%s/POSCAR' % dir0).positions - orig
                    ) * 1.889726  # in bohr
         disp += matrixFormat(disparr)
     tl.write(disp, "disp_all.dat")
     tl.write(force, "force_all.dat")
示例#10
0
文件: cs.py 项目: vanceeasleaf/aces
 def getsatoms(self):
     filename = 'disp_fc3.yaml'
     if (tl.exists(filename)):
         return disp2atoms(filename)
     filename = 'disp.yaml'
     if (tl.exists(filename)):
         return disp2atoms(filename)
     filename = '3RD.SPOSCAR'
     if (tl.exists(filename)):
         from ase import io
         return io.read(filename, format='vasp')
     filename = 'SPOSCAR'
     if (tl.exists(filename)):
         from ase import io
         return io.read(filename, format='vasp')
示例#11
0
    def __cleanup__(self):
        """ Checks if any relaxations are done and load in the structure
            from the traj file. """
        p = Popen(['ps -x -U `whoami`'], shell=True,
                  stdin=PIPE, stdout=PIPE, stderr=PIPE, close_fds=True)
        (_, fout) = (p.stdin, p.stdout)
        lines = fout.readlines()
        lines = [l for l in lines if l.find('defunct') == -1]

        stopped_runs = []
        for i in range(len(self.running_pids) - 1, -1, -1):
            found = False
            for l in lines:
                if l.find(str(self.running_pids[i][1])) != -1:
                    found = True
                    break
            if not found:
                stopped_runs.append(self.running_pids.pop(i))

        # All processes not running any more must be complete and should
        # be loaded in.
        for (confid, _) in stopped_runs:
            try:
                tf = self.tmp_folder
                a = read('{0}/cand{1}_done.traj'.format(tf,
                                                        confid))
                self.dc.add_relaxed_step(a)
            except IOError as e:
                print(e)
示例#12
0
def vasp2xyz():
    try:
        from lxml import etree
    except ImportError:
        print "You need to install python-lxml."
    print "start parse"
    xml = etree.parse("vasprun.xml")
    calculations = xml.xpath('//calculation')
    print 'len(calculations)=', len(calculations)
    from ase.io.trajectory import PickleTrajectory
    atoms = io.read('POSCAR')
    traj = PickleTrajectory('a.traj', 'w', atoms)

    print "start find forces and positions"
    allforce = []
    allpos = []

    def toarr(v):
        x = v.text.split()
        return map(float, x)
    for i, u in enumerate(calculations):
        print "step : ", i
        forces = map(toarr, u.xpath('./varray[@name="forces"]/v'))
        positions = map(toarr, u.xpath(
            './structure/varray[@name="positions"]/v'))
        atoms.set_scaled_positions(positions)
        allforce.append(forces)
        allpos.append(positions)
        traj.write()
    np.save('allforce.npy', allforce)
    np.save('allpos.npy', allpos)
    passthru("ase-gui a.traj -o a.xyz ")
示例#13
0
def getcharge():
    atoms = io.read("POSCAR")
    n = len(atoms) + 10
    size = map(int, shell_exec("head -%s CHG|tail -1" % n).split())
    ch = np.loadtxt("CHG", skiprows=n).reshape([size[2], size[1], size[0]])
    ch = np.einsum('kji', ch)
    return ch
示例#14
0
 def _cleanup(self):
     for r in self.results:
         if r.ready() and r.successful():
             fname = r.get()
             a = read(fname)
             self.dc.add_relaxed_step(a)
             self.results.remove(r)
示例#15
0
def read_nwchem(filename):
    """Method to read geometry from an NWChem input file."""
    f = filename
    if isinstance(filename, str):
        f = open(filename)
    lines = f.readlines()

    # Find geometry region of input file.
    stopline = 0
    for index, line in enumerate(lines):
        if line.startswith('geometry'):
            startline = index + 1
            stopline = -1
        elif (line.startswith('end') and stopline == -1):
            stopline = index
    # Format and send to read_xyz.
    xyz_text = '%i\n' % (stopline - startline)
    xyz_text += ' geometry\n'
    for line in lines[startline:stopline]:
        xyz_text += line
    atoms = read(StringIO(xyz_text), format='xyz')
    atoms.set_cell((0., 0., 0.))  # no unit cell defined

    if type(filename) == str:
        f.close()

    return atoms
 def test_symmetry_dense(self):
     for calc in [{(1, 1): LennardJonesQuadratic(1, 1, 3), (1, 2): LennardJonesQuadratic(1.5, 0.8, 2.4), (2, 2): LennardJonesQuadratic(0.5, 0.88, 2.64)}]:
         a = io.read('KA256_Min.xyz')
         a.center(vacuum=5.0)
         b = calculator.PairPotential(calc)
         H = b.calculate_hessian_matrix(a, "dense")
         self.assertArrayAlmostEqual(np.sum(np.abs(H-H.T)), 0, tol=0)
示例#17
0
def atoms_from_dump(filename, elements=None, index=-1):
    atoms = io.read(filename, format='lammps', index=index)
    if elements:
        s = atoms.numbers
        symbols = [elements[i - 1] for i in s]
        atoms.set_chemical_symbols(symbols)
    return atoms
示例#18
0
def read_nwchem_output(filename):
    """Method to read geometry from a nwchem output."""

    f = filename
    if isinstance(filename, str):
        f = open(filename)

    lines = f.readlines()

    i = 0
    while i < len(lines):
        if lines[i].find('XYZ format geometry') >= 0:
            natoms = int(lines[i + 2].split()[0])
            string = ''
            for j in range(2, natoms + 4):
                xyzstring = lines[i + j]
                symbol = xyzstring.split()[0].strip()
                # replace bq ghost with X: MDTMP can we do better?
                if symbol.startswith('bq'):
                    xyzstring = xyzstring.replace(symbol, 'X')
                string += xyzstring
            atoms = read(StringIO(string), format='xyz')
            i += natoms + 4
        else:
            i += 1

    if isinstance(filename, str):
        f.close()

    return atoms
示例#19
0
    def build(self, name):
        args = self.args
        if "." in name:
            atoms = read(name)
        elif self.build_function:
            atoms = self.build_function(name, self.args)
        elif self.args.crystal_structure:
            atoms = self.build_bulk(name)
        else:
            atoms = self.build_molecule(name)

        if args.magnetic_moment:
            magmoms = np.array([float(m) for m in args.magnetic_moment.split(",")])
            atoms.set_initial_magnetic_moments(np.tile(magmoms, len(atoms) // len(magmoms)))

        if args.modify:
            exec args.modify in {"atoms": atoms}

        if args.repeat is not None:
            r = args.repeat.split(",")
            if len(r) == 1:
                r = 3 * r
            atoms = atoms.repeat([int(c) for c in r])

        return atoms
示例#20
0
文件: STEM.py 项目: uw-cmg/StructOpt
    def generate_target(self):
        """Generates the target STEM image from the parameters. The bulk of
        this code generates the target from an atoms object. """

        # Load the target from a file
        if (self.path is not None
            and os.path.isfile(os.path.join(self.path, 'target.npy'))):
            with open(os.path.join(self.path, 'target.npy'), "rb") as npy:
                self.target = np.load(npy)            
            return

        if self.psf is None:
            self.generate_psf()

        if not self.parameters['kwargs']['target'].endswith('.xyz'):
            self.target = self.read_target(self.parameters['kwargs']['target'])
            self.phantom = False
        else:
            atoms = read(self.parameters['kwargs']['target'])
            self.target = self.get_image(atoms)
            self.phantom = True

        # Try saving the target for future calculations
        if self.path is not None:
            np.save(os.path.join(self.path, 'target'), self.target)

        return
示例#21
0
 def fit(filename):
     configs = read(filename + '@:')
     volumes = [a.get_volume() for a in configs]
     energies = [a.get_potential_energy() for a in configs]
     eos = EquationOfState(volumes, energies)
     v0, e0, B = eos.fit()
     return (4 * v0)**(1 / 3.0)
def get_trajectory(fname):
    """ Extra error tolerance when loading traj files. """
    fname = str(fname)
    try:
        t = read(fname)
    except IOError, e:
        print("get_trajectory error " + e)
示例#23
0
 def read_dimer(self, filename, w_image, fformat):
     """ Read the dimer file with a given file format and call create_fragments after that. """
     
     try:
         self.dimer = read(filename, index=w_image, format=fformat)
     except:
         print("ERROR: The file {0} was not found or the format {1} not known!".format(filename, fformat))
示例#24
0
文件: images.py 项目: grhawk/ASE
 def import_atoms(self, filename, cur_frame):
     if filename:
         filename = filename[0]
         old_a = self.get_atoms(cur_frame)
         imp_a = read(filename, -1)
         new_a = old_a + imp_a
         self.initialize([new_a], [filename])
示例#25
0
	def unit(self):
		write(self.poscar,"POSCAR_ORI")
		atoms=io.read("POSCAR_ORI")
		return atoms
	

		
示例#26
0
文件: elasticity.py 项目: ryokbys/nap
def prepare(infname='POSCAR',dlt1max=0.01,dlt2max=0.06):

    #...original system
    orig_atoms = read(infname,format='vasp')

    #...get deformations
    fmats = get_deformations(dlt1max,dlt2max)

    #...deform original system and save to _prefix_##/POSCAR
    for i,fmat in enumerate(fmats):
        atoms = orig_atoms.copy()
        dname = _prefix +"{0:02d}".format(i)
        os.system('mkdir -p {}'.format(dname))
        print(dname)
        cell0 = atoms.get_cell()
        emat = 0.5 *(np.dot(fmat.T,fmat) -np.identity(3)) +np.identity(3)
        cell = np.dot(emat,cell0)
        # cell = np.dot(cell0,fmat.T)
        atoms.set_cell(cell,scale_atoms=True)
        atoms.write(dname+'/POSCAR',format='vasp',vasp5=True,direct=True,
                    sort=False)
    
    print('prepare done')
    print('')
    print('After performing VASP or pmd calculations in these directories, '
          +'run the following command:')
    print('  $ python elasticity.py analyze str.ref')
    print('or')
    print('  $ python elasticity.py analyze strs.pmd')
    print('')
示例#27
0
def get_potential_energy(in_file='input.traj'):
    """ Performs a ASE get_potential_energy() call with
    the ase-espresso calculator with the keywords
    defined inside the atoms object information.

    This can be a singlepoint calculation or a
    full relaxation depending on the keywords.
    """

    # Read the input file from the current directory
    atoms = read(in_file)

    # Planewave basis set requires periodic boundary conditions
    atoms.set_pbc([1, 1, 1])

    # Assign kpoints to be split across nodes
    if get_nnodes() > 1:
        if not sum(atoms.info['kpts']) == 1:
            atoms.info['parflags'] = '-npool {}'.format(get_nnodes())

    # Setting up the calculator
    calc = espresso(**atoms.info)
    atoms.set_calculator(calc)

    # Perform the calculation and write trajectory from log.
    atoms.get_potential_energy()
    images = log_to_atoms(out_file='output.traj')

    # Save the calculator to the local disk for later use.
    try:
        calc.save_flev_output()
    except(RuntimeError):
        calc.save_output()

    return atoms_to_encode(images)
示例#28
0
    def traj(self):
        """Get a trajectory.

        This reads Atoms objects from vasprun.xml. By default returns
        all images.  If index is an integer, return that image.

        Technically, this is just a list of atoms with a
        SinglePointCalculator attached to them.

        This is usually only relevant if you have done a
        relaxation. If the calculation is an NEB, the images are
        returned.

        """
        from ase.calculators.singlepoint import SinglePointCalculator as SPC
        self.update()

        if self.neb:
            images, energies = self.get_neb()
            tatoms = [x.copy() for x in images]
            for i, x in enumerate(tatoms):
                x.set_calculator(SPC(x, energy=energies[i]))
            return tatoms

        LOA = []
        for atoms in read(os.path.join(self.directory, 'vasprun.xml'), ':'):
            catoms = atoms.copy()
            catoms = catoms[self.resort]
            catoms.set_calculator(SPC(catoms,
                                      energy=atoms.get_potential_energy()))
            LOA += [catoms]
        return LOA
示例#29
0
    def __init__(self, args, prop_fig, YFname):

        if args.tem_iter == 'tem':
            raise ValueError('text format only with iter')

        self.atoms = aio.read(prop_fig.fatoms)
        self.fname = self.determine_fname(args, perso=YFname)
        self.dr, self.origin, self.lbound, self.ubound, self.Array, \
            self.box, self.dim = self.read_txt(args, self.fname)

        if args.quantity != 'polarizability':

            self.mesh3D()
            self.mesh2D()

            self.xy_prof = self.xy_mesh[:, int(self.xy_mesh.shape[1] / 2)]
            self.xz_prof = self.xz_mesh[int(self.xz_mesh.shape[0] / 2), :]

            self.yx_prof = self.yx_mesh[:, int(self.yx_mesh.shape[1] / 2)]
            self.yz_prof = self.yz_mesh[int(self.yz_mesh.shape[0] / 2), :]

            self.zx_prof = self.zx_mesh[:, int(self.zx_mesh.shape[1] / 2)]
            self.zy_prof = self.zy_mesh[int(self.zy_mesh.shape[0] / 2), :]

        self.set_carac(args, prop_fig)
示例#30
0
def butane_single_process():

    try:
        start_point = read('test_files/x0.xyz')
        start_point.set_calculator(EMT())
        end_point = read('test_files/xN.xyz')

        traj = Curve(start_point, end_point, 12, 1E+03)

        compute_trajectory(traj, 9, 1E+03, 0.003, 'Butane', {'processes': 1})

        return True

    except:

        return False
示例#31
0
def run_dftb3_test(test=None, tol=0.05):
    mio_database_folder = os.getenv('MIO')
    if mio_database_folder is None:
        raise RuntimeError(
            'Please use environment variable MIO to specify path to mio Slater-Koster tables.'
        )
    dftb3_database_folder = os.getenv('DFTB3')
    if dftb3_database_folder is None:
        raise RuntimeError(
            'Please use environment variable DFTB3 to specify path to 3ob Slater-Koster tables.'
        )

    dftb2_calc = Atomistica(
        [
            native.TightBinding(
                database_folder=mio_database_folder,
                SolverLAPACK=dict(electronic_T=0.001),
                SCC=dict(
                    dq_crit=1e-6,
                    mixing=0.05,  # 0.2
                    andersen_memory=15,  # 3
                    maximum_iterations=100,
                    log=True)),
            native.DirectCoulomb(),
            native.SlaterCharges(cutoff=10.0)
        ],
        avgn=1000)

    dftb2_XH_calc = Atomistica(
        [
            native.TightBinding(
                database_folder=mio_database_folder,
                SolverLAPACK=dict(electronic_T=0.001),
                SCC=dict(
                    dq_crit=1e-6,
                    mixing=0.05,  # 0.2
                    andersen_memory=15,  # 3
                    maximum_iterations=100,
                    log=True)),
            native.DirectCoulomb(),
            native.SlaterCharges(cutoff=10.0, damp_gamma=True, zeta=3.70)
        ],
        avgn=1000)

    dftb3_calc = Atomistica(
        [
            native.TightBinding(
                database_folder=mio_database_folder,
                SolverLAPACK=dict(electronic_T=0.001),
                SCC=dict(
                    dq_crit=1e-6,
                    mixing=0.05,  # 0.2
                    andersen_memory=15,  # 3
                    maximum_iterations=100,
                    log=True)),
            native.DirectCoulomb(),
            native.SlaterCharges(cutoff=10.0,
                                 dftb3=True,
                                 HubbardDerivatives=dict(H=-0.1857, O=-0.1575))
        ],
        avgn=1000)

    dftb3_XH_calc = Atomistica(
        [
            native.TightBinding(
                database_folder=mio_database_folder,
                SolverLAPACK=dict(electronic_T=0.001),
                SCC=dict(
                    dq_crit=1e-6,
                    mixing=0.05,  # 0.2
                    andersen_memory=15,  # 3
                    maximum_iterations=100,
                    log=True)),
            native.DirectCoulomb(),
            native.SlaterCharges(cutoff=10.0,
                                 dftb3=True,
                                 damp_gamma=True,
                                 zeta=4.05,
                                 HubbardDerivatives=dict(H=-0.1857, O=-0.1575))
        ],
        avgn=1000)

    dftb3_XH_3ob_calc = Atomistica(
        [
            native.TightBinding(
                database_folder=dftb3_database_folder,
                SolverLAPACK=dict(electronic_T=0.001),
                SCC=dict(
                    dq_crit=1e-6,
                    mixing=0.05,  # 0.2
                    andersen_memory=15,  # 3
                    maximum_iterations=100,
                    log=True)),
            native.DirectCoulomb(),
            native.SlaterCharges(cutoff=10.0,
                                 dftb3=True,
                                 damp_gamma=True,
                                 zeta=4.00,
                                 HubbardDerivatives=dict(H=-0.1857, O=-0.1575))
        ],
        avgn=1000)

    if test is None:
        print(
            '    nH2O|    G3B3|    DFTB2 (MIO)  | DFTB2+XH (MIO)  |    DFTB3 (MIO)  | DFTB3+XH (MIO)  | DFTB3+XH (3OB)  |'
        )
        print(
            '        |        |     me    ref.  |     me    ref.  |     me    ref.  |     me    ref.  |     me    ref.  |'
        )
        print(
            '        |        |-----------------|-----------------|-----------------|-----------------|-----------------|'
        )

    for name, data in table5_data.items():
        e0_DFTB2 = 0.0
        e0_DFTB3 = 0.0
        e0_DFTB2_XH = 0.0
        e0_DFTB3_XH = 0.0
        e0_DFTB3_3ob_XH = 0.0
        for structure in data['reference_structures']:
            if os.path.exists(structure):
                a = read(structure)
            else:
                a = molecule(structure)

            a.center(vacuum=10.0)
            a.set_calculator(dftb2_calc)
            FIRE(a, logfile=None).run(fmax=0.001)
            e0_DFTB2 += a.get_potential_energy()

            a.set_calculator(dftb2_XH_calc)
            FIRE(a, logfile=None).run(fmax=0.001)
            e0_DFTB2_XH += a.get_potential_energy()

            a.set_calculator(dftb3_calc)
            FIRE(a, logfile=None).run(fmax=0.001)
            e0_DFTB3 += a.get_potential_energy()

            a.set_calculator(dftb3_XH_calc)
            FIRE(a, logfile=None).run(fmax=0.001)
            e0_DFTB3_XH += a.get_potential_energy()

            a.set_calculator(dftb3_XH_3ob_calc)
            FIRE(a, logfile=None).run(fmax=0.001)
            e0_DFTB3_3ob_XH += a.get_potential_energy()

        eref_G3B3 = data['G3B3']
        eref_DFTB2 = data['DFTB2']
        eref_DFTB2_XH = data['DFTB2+XH']
        eref_DFTB3 = data['DFTB3']
        eref_DFTB3_XH = data['DFTB3+XH']
        eref_DFTB3_3ob_XH = data['DFTB3+XH_3ob']

        a = read(data['structure'])
        a.center(vacuum=10.0)
        a.set_calculator(dftb2_calc)
        FIRE(a, logfile=None).run(fmax=0.001)
        e_DFTB2 = a.get_potential_energy()

        e_DFTB2 = (e_DFTB2 - e0_DFTB2) / (ase.units.kcal / ase.units.mol)

        a.set_calculator(dftb2_XH_calc)
        FIRE(a, logfile=None).run(fmax=0.001)
        e_DFTB2_XH = a.get_potential_energy()

        e_DFTB2_XH = (e_DFTB2_XH - e0_DFTB2_XH) / (ase.units.kcal /
                                                   ase.units.mol)

        a.set_calculator(dftb3_calc)
        FIRE(a, logfile=None).run(fmax=0.001)
        e_DFTB3 = a.get_potential_energy()

        e_DFTB3 = (e_DFTB3 - e0_DFTB3) / (ase.units.kcal / ase.units.mol)

        a.set_calculator(dftb3_XH_calc)
        FIRE(a, logfile=None).run(fmax=0.001)
        e_DFTB3_XH = a.get_potential_energy()

        e_DFTB3_XH = (e_DFTB3_XH - e0_DFTB3_XH) / (ase.units.kcal /
                                                   ase.units.mol)

        a.set_calculator(dftb3_XH_3ob_calc)
        FIRE(a, logfile=None).run(fmax=0.001)
        e_DFTB3_3ob_XH = a.get_potential_energy()

        e_DFTB3_3ob_XH = (e_DFTB3_3ob_XH - e0_DFTB3_3ob_XH) / (ase.units.kcal /
                                                               ase.units.mol)

        success_DFTB2 = abs(e_DFTB2 - eref_G3B3 - eref_DFTB2) < tol
        success_DFTB2_XH = abs(e_DFTB2_XH - eref_G3B3 - eref_DFTB2_XH) < tol
        success_DFTB3 = abs(e_DFTB3 - eref_G3B3 - eref_DFTB3) < tol
        success_DFTB3_XH = abs(e_DFTB3_XH - eref_G3B3 - eref_DFTB3_XH) < tol
        success_DFTB3_3ob_XH = abs(e_DFTB3_3ob_XH - eref_G3B3 -
                                   eref_DFTB3_3ob_XH) < tol

        success_str = {True: ' ', False: 'X'}

        if test is None:
            print(
                '{0:>8}| {1:>7.3f}|{2:>7.3f} {3:>7.3f} {4}|{5:>7.3f} {6:>7.3f} {7}|{8:>7.3f} {9:>7.3f} {10}|{11:>7.3f} {12:>7.3f} {13}|{14:>7.3f} {15:>7.3f} {16}|'
                .format(name, eref_G3B3, e_DFTB2 - eref_G3B3, eref_DFTB2,
                        success_str[success_DFTB2], e_DFTB2_XH - eref_G3B3,
                        eref_DFTB2_XH, success_str[success_DFTB2_XH],
                        e_DFTB3 - eref_G3B3, eref_DFTB3,
                        success_str[success_DFTB3], e_DFTB3_XH - eref_G3B3,
                        eref_DFTB3_XH, success_str[success_DFTB3_XH],
                        e_DFTB3_3ob_XH - eref_G3B3, eref_DFTB3_3ob_XH,
                        success_str[success_DFTB3_3ob_XH]))
        else:
            test.assertTrue(success_DFTB2)
            test.assertTrue(success_DFTB2_XH)
            test.assertTrue(success_DFTB3)
            test.assertTrue(success_DFTB3_XH)
            test.assertTrue(success_DFTB3_3ob_XH)
示例#32
0
os.remove('4.nc')

# Add 'id' field and check if it is read correctly
co.set_array('id', np.array([2, 1]))
traj = NetCDFTrajectory('5.nc', 'w', co)
traj.write(co, arrays=['id'])
traj.close()

traj = NetCDFTrajectory('5.nc', 'r')  #
assert np.all(traj[0].numbers == [8, 6])
assert np.all(
    np.abs(traj[0].positions - np.array([[2, 2, 3.7], [2., 2., 2.5]])) < 1e-6)
traj.close()

a = read('5.nc')
assert (len(a) == 2)

os.remove('5.nc')

# Create a NetCDF file with a per-file definition of atomic numbers. ASE
# NetCDFTrajectory can read but not write these types of files.
import netCDF4
nc = netCDF4.Dataset('6.nc', 'w')
nc.createDimension('frame', None)
nc.createDimension('atom', 2)
nc.createDimension('spatial', 3)
nc.createDimension('cell_spatial', 3)
nc.createDimension('cell_angular', 3)

nc.createVariable('atom_types', 'i', ('atom', ))
示例#33
0
"""Read and write json from/to file descriptor."""
import sys
from io import StringIO, BytesIO

from ase.io import read, write

s = u"""
{"1":
     {"numbers": [1, 1],
      "positions": [[0.0, 0.0, 0.35],
                    [0.0, 0.0, -0.35]]}}
"""

fd = StringIO(s)
a = read(fd, format='json')
assert a.get_chemical_formula() == 'H2'

if sys.version_info[0] == 2:
    fd = BytesIO()
else:
    fd = StringIO()
write(fd, a, format='json')

fd.seek(0)
a = read(fd, format='json')
assert a.get_chemical_formula() == 'H2'
    f.close()
    print(folder, erg)
    return erg

prefix = "sset"
property_name = "energy"
sset = StructuresSet(db_fname=prefix+".json")
sset.read_property_values(property_name, write_to_file=False, read_property=read_property)
sset.serialize(prefix+".json")


refs = StructuresSet(db_fname="refs.json")
refs.read_property_values(property_name, write_to_file=False, read_property=read_property)
refs.serialize("refs.json")
ref_en = refs.get_property_values(property_name)

plot_property_vs_concentration(sset, site_type=0, property_name=property_name,refs=ref_en,scale=0.6)


# See the most stable structure
from ase.visualize import view
import numpy as np
array = sset.get_property_values(property_name)
lowest_energy_structure_index = np.where(array == np.amin(array))[0][0]
# GET STRUCTURES/ GET STRUCTURE IS NOT SHOWING THE CORRECT STRUCTURE
#lowest_energy_structure = sset.get_structures()[lowest_energy_structure_index] # not working for the moment
os.chdir(sset.get_folders()[lowest_energy_structure_index])
lowest_energy_structure = read("geometry.json")
view(lowest_energy_structure)

def main():
    print('Welcome.')

    #global variables
    global superCell
    global trajFileIn
    global trajFileOut

    #get Input from stdin
    if len(sys.argv) is 1:
        trajFileIn, trajFileOut, superCell = getSTDInput()

    #if we have the right amount of arguments
    elif len(sys.argv) is 6:
        print('Provided information as arguments.')
        trajFileIn, trajFileOut, superCell = getArgumentsInput(sys.argv)

    #otherwise something is wrong
    else:
        print('You gave some arguments, but the number of them is wrong. Please provide "<InputFile> <OutFile> <n1> <n2> <n3>"')
        sys.exit(1)

    #check input
    checkInput(trajFileIn, superCell)

    #open files
    inMol = io.read(trajFileIn,index=slice(0,None))

    #if output exists mv to .bak
    if os.path.isfile(trajFileOut):
        print('ATTENTION: Output file exists, moving to *.bak')
        os.rename(trajFileOut, trajFileOut+'.bak')

    #open output for writing
    outFile = open(trajFileOut, 'w')

    #convert input superCell to integer tuple
    try:
        superCell = tuple([int(x) for x in superCell])
    except:
        print('ERROR: SuperCell Vector contains non-integer values!')
        sys.exit(1)

    #check input superCell vector
    if any(x for x in superCell) < 1:
        print('ERROR: SuperCell Tuple contains values smaller than 1!')
        sys.exit(1)

    #calculate number of unit cells
    superCellSize = np.prod(np.array(superCell), dtype='int')
    print('You will end up with '+str(superCellSize)+' unit cells in each frame.')

    #iterate over frames
    nFrames = len(inMol)
    i = 0
    print('Adding Coordinates:')
    for frame in inMol:
        i += 1
        progress(i/nFrames)
        frame *= superCell

    print('Writing to file:')
    i = 0
    for frame in inMol:
        i += 1
        progress(i/nFrames)
        io.extxyz.write_xyz(outFile,frame)

    outFile.close()
示例#36
0
import os
from ase import Atoms
from ase.io import read, write
from ase.calculators.exciting import Exciting
from ase.units import Bohr, Hartree

a = Atoms('N3O', [(0, 0, 0), (1, 0, 0), (0, 0, 1), (0.5, 0.5, 0.5)], pbc=True)

write('geo.exi', a)
b = read('geo.exi')

print a
print a.get_positions()
print b
print b.get_positions()

calculator = Exciting(
    dir='excitingtestfiles',
    kpts=(4, 4, 3),
    maxscl=3,
    #bin='/fshome/chm/git/exciting/bin/excitingser'
)
def parse_info(path_i):
    """
    """
    #| - parse_info
    from ase import io

    files_i = os.listdir(path_i)

    if "init_graphene.cif" in files_i:
        atoms_init_graph_i = io.read(
            os.path.join(
                path_i,
                "init_graphene.cif",
                )
            )
    else:
        atoms_init_graph_i = None

    if "init_support.cif" in files_i:
        atoms_init_supp_i = io.read(
            os.path.join(
                path_i,
                "init_support.cif",
                )
            )
    else:
        atoms_init_supp_i = None

    structures_found = os.path.isdir(
        os.path.join(
            path_i,
            "01_heterostructures",
            )
        )

    if structures_found:
        out_atoms_path_list = os.listdir(os.path.join(
            path_i,
            "01_heterostructures",
            ))

        out_atoms_list = []
        for out_i in out_atoms_path_list:
            out_atoms_i = io.read(
                os.path.join(
                    path_i,
                    "01_heterostructures",
                    out_i,
                    )
                )
            out_atoms_list.append(out_atoms_i)
    else:
        out_atoms_list = None

    out_dict = {
    #     "": ,
        "init_graph_atoms": atoms_init_graph_i,
        "init_support_atoms": atoms_init_supp_i,
        "out_atoms": out_atoms_list,
        }

    return(out_dict)
示例#38
0
from ase import io
from espresso.vibespresso import vibespresso
from ase.vibrations import Vibrations
from ase.thermochemistry import HarmonicThermo

##################
# Inputs #########
##################
vib_atoms = [1, 7]  # List of atoms allowed to vibrate

#Convergence
##################
# Slab ###########
##################

atoms = io.read('qn.traj')  # optimized

atoms.set_masses()

calc = vibespresso(
    pw=800,  # planewave cutoff
    dw=8000,  # density cutoff
    nbands=-10,  # number of bands
    kpts=(8, 8, 8),  # k points
    xc='beef',  # exchange correlation method
    sigma=0.2,  # Fermi temperature
    dipole={'status': False},
    spinpol=False,
    convergence={
        'energy': 0.0005,
        'mixing': 0.1,
示例#39
0
def convert_fil(namefile):
	from ase.io import read
 	from ase.io import write
	slab=read(namefile)
	write('x.xyz', slab)
示例#40
0
butadiene = u"""10

C       3.649801161546418      5.442281389577507      3.863313703750026
C       5.051651240044169      5.368220758269772      4.162165876906096
C       5.750174626862403      4.162261915959347      4.240449977068684
C       7.150130182125531      4.155384186721486      4.537328602062397
H       3.218154657585170      4.565210696328925      3.522601038049320
H       3.077656122062729      6.375092902842770      3.826039498180272
H       5.478464901706067      6.370680001794822      4.422235395756437
H       5.320549047980879      3.220584852467720      3.974551561510350
H       7.723359150977955      3.224855971783890      4.574146712279462
H       7.580803493981530      5.034479218283977      4.877211530909463
"""

h = 0.3
atoms = Cluster(read(io.StringIO(butadiene), format='xyz'))
atoms.minimal_box(3.0, h)
atoms.set_calculator(GPAW(h=h))
if 0:
    dyn = FIRE(atoms)
    dyn.run(fmax=0.05)
    atoms.write('butadiene.xyz')

vibname = 'fcvib'
vib = Vibrations(atoms, name=vibname)
vib.run()

# Modul
a = FranckCondon(atoms, vibname, minfreq=250)

# excited state forces
示例#41
0
        dumpconf()

    elif args['calc']:
        if confname:
            loadconf(confname)
        #...output for checking
        print(' block:')
        for i in range(3):
            print(' {0:8.2f} {1:8.2f} {2:8.2f}'.format(block[i, 0],
                                                       block[i, 1], block[i,
                                                                          2]))
        print(' nei_perf:')
        for i in range(len(nei_perf)):
            print(' {0:4d}:'.format(i) + ' {0:8.2f} {1:8.2f} {2:8.2f}'.format(
                nei_perf[i, 0], nei_perf[i, 1], nei_perf[i, 2]))
        atoms = read(fname, format='lammps-dump')
        nye_tensor(atoms)

    elif args['plot']:
        #...See http://matplotlib.org/examples/pylab_examples/griddata_demo.html
        #...for contour plot example.
        from matplotlib.mlab import griddata
        import matplotlib.pyplot as plt
        if confname:
            loadconf(confname)
        comp = args['--component']
        xo = float(args['-x'])
        yo = float(args['-y'])
        w = int(args['--width'])
        h = int(args['--height'])
        if len(comp) != 2:
示例#42
0
from ase.io import read, write
from ase.visualize import view
from blase.tools import write_blender, get_polyhedra_kinds, get_bondpairs
import numpy as np
from pprint import pprint
from ase.data import covalent_radii


atoms = read('datas/perovskite.xyz')
atoms.pbc = [True, True, True]
atoms = atoms*[2, 2, 2]
# atoms.write('datas/perovskite-2-2-2.in')
print(atoms)
kind_props = {
'Pb': {'radius': 1.0, 'color': [100/255.0, 191/255.0, 56/255.0]},
'O': {'radius': 1.0, }
}


# bond_list = get_bondpairs(atoms, rmbonds = [['Ti', 'Ti']])
kwargs = {'show_unit_cell': 1, 
          'engine': 'BLENDER_WORKBENCH', #'BLENDER_EEVEE' #'BLENDER_WORKBENCH', CYCLES
          'radii': 0.6,
          'bond_cutoff': 1.0,
          # 'bond_list': bond_list,
          'kind_props': kind_props,
          'display': True,
        #   'polyhedra_dict': {'Pb': ['I']},
          # 'search_pbc_atoms': {'bonds_dict':{'I': [['Pb'], -1]}, 'molecule_list':[['C', 'N']]},
          'run_render': False,
          'outfile': 'figs/test-polyhedra',
示例#43
0

def plot_conf(ax, atoms, rot=False):
    colors = np.array([jmol_colors[atom.number] for atom in atoms])
    alp = [None] * colors.shape[0]
    for i, a in enumerate(atoms):
        if a.symbol == 'Ti' or a.symbol == 'O':
            if a.position[2] < 11.95:
                alp[i] = 0.3

    if rot:
        atoms.rotate('x', pi / 2)
    plot_atoms(ax, atoms, [0, 2, 1], colors, alp, z=-1)


data = read('V2O5_TiO2_101_DFTlowlyingsorted.traj@:')
image = data[16] * (2, 2, 1)
#image = read('anataseTi24O48_101surface_optPBEesben.traj') * (2,2,1)
write('221image.traj', image)
# Make array of indices for atoms that should be repeated in x and y directions
plt.figure(figsize=(6.0, 10.0))

gs = gridspec.GridSpec(2, 1, height_ratios=[7.0, 9.5])

cell = image.get_cell()

#image.translate(-cell[:,0]/3.)
#image.translate(-cell[:,1]/3.)
#view(image)
# 0 0
ax = plt.subplot(gs[0, 0])
示例#44
0
    def finish_relaxation(self, structure, fixed_frame, parameters, directory):
        """ Finishes unfinished calculation
        
        Reads the output in logfile and compares to the convergence criteria in
        parameters.json file. If no "finished" reads the trajectory file and 
        relax the structure.
        
        Arguments:
            structure {[type]} -- [description]
            fixed_frame {[type]} -- [description]
            parameters {[type]} -- [description]
            directory {[type]} -- [description]
        """
        def find_traj(directory):
            for output in os.listdir(directory):
                if "trajectory" in output and ".traj" in output and "history" not in output:
                    return output
            else:
                return None

        def send_traj_to_history(name, directory):
            traj = os.path.join(directory, "trajectory_{}.traj".format(name))
            history_trajs = [
                i for i in os.listdir(directory) if "history" in i
            ]
            name_history_traj = "{:05d}_history_trajectory_{}.traj".format(
                len(history_trajs) + 1, name)
            shutil.copyfile(traj, os.path.join(directory, name_history_traj))

        def concatenate_trajs(name, directory):
            traj = "trajectory_{}.traj".format(name)
            trajs = [i for i in os.listdir(directory) if "history" in i]
            history_trajs = " ".join(sorted(trajs))
            temp_traj = "temp.traj"
            os.system("cd {} && ase gui {} {} -o {}".format(
                directory, history_trajs, traj, temp_traj))
            os.rename(os.path.join(directory, temp_traj),
                      os.path.join(directory, traj))
            # Cleaning up
            for i in trajs:
                os.remove(os.path.join(directory, i))

        def finished(directory):
            f = open(os.path.join(directory, "finished"), "w")
            f.write("Calculation was finished")
            f.close()

        def perform_from_last(directory, traj):

            if traj == None:
                return False
            else:
                size = os.path.getsize(os.path.join(directory, traj))
                if size == 0:
                    history_trajs = [
                        i for i in os.listdir(directory) if "history" in i
                    ]
                    if len(history_trajs) > 0:
                        name_history_traj = "{:05d}_history_{}".format(
                            len(history_trajs), traj)
                        os.rename(os.path.join(directory, name_history_traj),
                                  os.path.join(directory, traj))
                        return True
                    else:
                        return False
                else:
                    return True

        if os.path.basename(os.path.normpath(directory)) != format(0, "010d"):
            if not "finished" in os.listdir(
                    directory) and not "known" in os.listdir(directory):
                traj = find_traj(directory)
                if perform_from_last(directory, traj):
                    if len(structure.molecules) > 1:
                        molsize = len(structure.molecules[0]) * len(
                            structure.molecules)
                    else:
                        molsize = len(structure.molecules[0])
                    if parameters["calculator"]["preconditioner"][
                            "rmsd_update"]["activate"]:
                        rmsd_threshhold = parameters["calculator"][
                            "preconditioner"]["rmsd_update"]["value"]
                    else:
                        rmsd_threshhold = 100000000000

                    name = parameters["name"]
                    # Save the history of trajectory
                    send_traj_to_history(name, directory)
                    # Perform relaxation
                    traj = os.path.join(directory,
                                        "trajectory_{}.traj".format(name))
                    t = Trajectory(os.path.join(directory, traj))
                    atoms = t[-1].copy()
                    self.set_constrains(atoms, parameters)
                    atoms.set_calculator(self.calculator)
                    H0 = np.eye(3 * len(atoms)) * 70
                    opt = BFGS_mod(atoms,
                                   trajectory=traj,
                                   initial=atoms[:molsize],
                                   molindixes=list(range(molsize)),
                                   rmsd_dev=rmsd_threshhold,
                                   structure=structure,
                                   fixed_frame=fixed_frame,
                                   parameters=parameters,
                                   H0=H0,
                                   logfile=os.path.join(
                                       directory, "logfile.log"),
                                   restart=os.path.join(directory, 'qn.pckl'))

                    fmax = parameters["calculator"]["fmax"]
                    opt.run(fmax=fmax, steps=1000)
                    concatenate_trajs(name, directory)
                    try:
                        calculator.close()
                    except:
                        pass
                    finished(directory)

                else:
                    # Didn't perform any step - start relaxation
                    #from initial .in  geometry.
                    foldername = os.path.basename(os.path.normpath(directory))
                    structure_file = os.path.join(directory,
                                                  foldername + ".in")
                    for i in os.listdir(directory):
                        if os.path.join(directory, i) != structure_file:
                            os.remove(os.path.join(directory, i))
                    atoms = read(os.path.join(directory, foldername + ".in"),
                                 format="aims")
                    if len(structure.molecules) > 1:
                        molsize = len(structure.molecules[0]) * len(
                            structure.molecules)
                    else:
                        molsize = len(structure.molecules[0])
                    name = parameters["name"]
                    self.set_constrains(atoms, parameters)
                    atoms.set_calculator(self.calculator)
                    traj = os.path.join(directory,
                                        "trajectory_{}.traj".format(name))
                    if parameters["calculator"]["preconditioner"][
                            "rmsd_update"]["activate"]:
                        rmsd_threshhold = parameters["calculator"][
                            "preconditioner"]["rmsd_update"]["value"]
                    else:
                        rmsd_threshhold = 100000000000
                    H0 = np.eye(3 * len(atoms)) * 70
                    opt = BFGS_mod(atoms,
                                   trajectory=traj,
                                   initial=atoms[:molsize],
                                   molindixes=list(range(molsize)),
                                   rmsd_dev=rmsd_threshhold,
                                   structure=structure,
                                   fixed_frame=fixed_frame,
                                   parameters=parameters,
                                   H0=H0,
                                   logfile=os.path.join(
                                       directory, "logfile.log"),
                                   restart=os.path.join(directory, 'qn.pckl'))

                    if not hasattr(structure, "mu"):
                        structure.mu = 1
                    if not hasattr(structure, "A"):
                        structure.A = 1
                    opt.H0 = precon.preconditioned_hessian(structure,
                                                           fixed_frame,
                                                           parameters,
                                                           atoms,
                                                           H0,
                                                           task="initial")
                    np.savetxt(
                        os.path.join(directory, "hes_{}.hes".format(name)),
                        opt.H0)
                    fmax = parameters["calculator"]["fmax"]
                    opt.run(fmax=fmax, steps=1000)
                    try:
                        calculator.close()
                    except:
                        pass
                    finished(directory)
示例#45
0
      #  if (atom.number ==8 and i >= 135+colorlenth*5 and i <colorlenth*6 ):
      #     colors[i] =[102/255, 0/255, 0/255]

    alp = [None] * colors.shape[0]
    for i,a in enumerate(atoms):
        if a.symbol == 'Al' or a.symbol == 'O':
            if a.position[2] < 9.7:
                alp[i] = 0.3

    if rot:
        atoms.rotate('x',pi/2)
    plot_atoms(ax, atoms, [0,2,1], colors, alp, z=-1)



data=read(sys.argv[1]+'@:')
energydif =np.zeros(len(data))
for j in range(len(data)):
    GM_energy = data[0].get_potential_energy()
    energydif[j] = (data[j].get_potential_energy() - GM_energy)
    #print('{:3.3f}'.format(energydif[j]))
for j in range(7,len(data)):
    atoms = data[j]
    colorlenth = len(atoms)
    atoms =atoms*(3,3,1)
    print(colorlenth)
   # write('newimage.traj',atoms)
    #exit()
    a=atoms
    del atoms[[atom.index for atom in atoms if atom.index <=colorlenth*5-14 or atom.index >=colorlenth*5]]
    #view(atoms)
示例#46
0
import numpy as np
from ase import io, atoms

Temp = '300'
atoms = io.read('POSCAR')
pos = atoms.get_positions()
disp = np.loadtxt('thermal_displacements.yaml', skiprows=6, usecols=(2, 3, 4))
pos += disp
atoms.set_positions(pos)
io.write('POSCAR' + Temp, atoms, direct=True)
示例#47
0
 def read_atoms(self, filename):
     """Read the atoms from file located in the VASP
     working directory. Normally called CONTCAR."""
     return read(filename)[self.resort]
示例#48
0
def test_read_write_roundtrip(atoms, vasp5, filename):
    write(filename, atoms, vasp5=vasp5)
    atoms_loaded = read(filename)

    assert len(compare_atoms(atoms, atoms_loaded)) == 0
示例#49
0
        with pushd("image_{}".format(image_num)) as ctx1:
            shutil.copy("../ctrl.dat", "./ctrl.dat")
            atoms_to_site(atoms)


if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument("-i",
                        "--input",
                        help="input format suffix",
                        default="xyz")
    parser.add_argument("-o",
                        "--output",
                        help="output format suffix",
                        default="site")
    parser.add_argument("-s",
                        "--struct_file",
                        help="input file name",
                        required=True)
    args = parser.parse_args()

    print args.input, args.output
    if (args.input == "xyz" and args.output == "site"):
        ats = io.read(args.struct_file)
        atoms_to_site(ats)
    elif (args.input == "pos" and args.output == "xyz"):
        pos_to_xyz(args.struct_file)
    else:
        print "No conversion method available"
示例#50
0
文件: bader.py 项目: jonlym/py_box
from os.path import basename
from os import system
from run_testRun import run_testRun
from set_calc import set_bader_calc

testRun = False
file_name_py = basename(__file__)
file_name = file_name_py.replace('.py', '')
file_traj = file_name + '.traj'
start_file = '../In2O3_110_H-1.traj'
mode = 'a'
try:
    sys = Trajectory(file_traj, 'r')[-1]
except (IOError, RuntimeError):
    print "Importing trajectory file from: %s" % start_file
    sys = read(start_file)
    mode = 'w'
else:
    print "Importing trajectory file from: %s" % file_traj

set_bader_calc(sys, sigma=0.05)
print "Constraints:"
print "	c: Fix bottom two layers."
c = FixAtoms(mask=[atom.z < 8 for atom in sys])
sys.set_constraint(c)
if testRun == True:
    run_testRun(sys)
else:
    geo_traj = Trajectory(file_traj, mode, sys)
    dyn = LBFGS(sys, trajectory=geo_traj)
    dyn.run(fmax=0.05)
示例#51
0
# 2.C Optimize using LBFGS.
initial_lbfgs = atoms.copy()
initial_lbfgs.set_calculator(calc)
lbfgs_opt = LBFGS(initial_lbfgs, trajectory='results_lbfgs.traj')
lbfgs_opt.run(fmax=0.01)

# 2.D Optimize using FIRE.
initial_fire = atoms.copy()
initial_fire.set_calculator(calc)
fire_opt = FIRE(initial_fire, trajectory='results_fire.traj')
fire_opt.run(fmax=0.01)

# 3. Summary of the results:
###############################################################################

print('\n Summary of the results:\n ------------------------------------')

fire_results = read('results_fire.traj', ':')
print('Number of function evaluations using FIRE:', len(fire_results))

lbfgs_results = read('results_lbfgs.traj', ':')
print('Number of function evaluations using LBFGS:', len(lbfgs_results))

gpmin_results = read('results_gpmin.traj', ':')
print('Number of function evaluations using GPMin:', gpmin_opt.function_calls)

catlearn_results = read('results_catlearn.traj', ':')
print('Number of function evaluations using MLMin (CatLearn):',
      len(catlearn_results))
示例#52
0
from ase.vibrations import Vibrations
from ase.thermochemistry import HarmonicThermo

# My Modules
from ase_modules.ase_methods import clean_up_dft, an_ads_vib
#__|

# | - Script Inputs
dipole_corr = False
indices_list = [3]
name = "vib_vasp"
#__|

# | - Read Atoms Object
if os.path.isfile("init.cif"):
    atoms = io.read('init.cif')
elif os.path.isfile("init.traj"):
    atoms = io.read('init.traj')
#__|

# | - Copy Previous OUTCAR and moments.traj
subprocess.call('cp -rf OUTCAR OUTCAR_$(date +%s)', shell=True)
subprocess.call('cp -rf moments.traj moments.traj_$(date +%s)', shell=True)
#__|

# | - Calculator
calc = vasp_calculator.Vasp(
    lwave=False,
    encut=500,
    xc='PBE',
    #setups={'O': '_s', 'C': '_s'},
示例#53
0
#              second atom       first atom

print('PBE energy minimum:')
print('hydrogen molecule energy: %7.3f eV' % e2)
print('bondlength              : %7.3f Ang' % d0)

molecule = GPAW('H2fa.gpw', txt='H2.txt').get_atoms()
relax = BFGS(molecule)
relax.run(fmax=0.05)
e2q = molecule.get_potential_energy()
niter2q = calc.get_number_of_iterations()
positions = molecule.get_positions()
d0q = positions[1, 0] - positions[0, 0]
assert abs(e2 - e2q) < 2e-6
assert abs(d0q - d0) < 4e-4

f0 = molecule.get_forces()
del relax, molecule

from gpaw.mpi import world

world.barrier()  # syncronize before reading text output file
f = read('H2.txt').get_forces()
assert abs(f - f0).max() < 5e-6  # 5 digits in txt file

energy_tolerance = 0.00005
niter_tolerance = 0
equal(e1, -6.287873, energy_tolerance)
equal(e2, -6.290744, energy_tolerance)
equal(e2q, -6.290744, energy_tolerance)
示例#54
0
from __future__ import print_function
from ase.dft.kpoints import bandpath
from ase.io import read
from ase.parallel import paropen
from gpaw import GPAW

a = read('gs_Bi2Se3.gpw')

G = [0.0, 0.0, 0.0]
L = [0.5, 0.0, 0.0]
F = [0.5, 0.5, 0.0]
Z = [0.5, 0.5, 0.5]
kpts, x, X = bandpath([G, Z, F, G, L], a.cell, npoints=200)

calc = GPAW('gs_Bi2Se3.gpw',
            kpts=kpts,
            symmetry='off',
            fixdensity=True,
            txt='Bi2Se3_bands.txt')
calc.get_potential_energy()

calc.write('Bi2Se3_bands.gpw')

with paropen('kpath.dat', 'w') as f:
    for k in x:
        print(k, file=f)

with paropen('highsym.dat', 'w') as f:
    for k in X:
        print(k, file=f)
示例#55
0
    # If the structure is already fully relaxed just return it
    traj = Trajectory(label + '_lcao.traj', 'w', structure)
    while (structure.get_forces()**
           2).sum(axis=1).max()**0.5 > forcemax and niter < niter_max:
        dyn = BFGS(structure, logfile=label + '.log')
        vb = VariansBreak(structure, dyn, min_stdev=0.01, N=15)
        dyn.attach(traj)
        dyn.attach(vb)
        dyn.run(fmax=forcemax, steps=steps)
        niter += 1
    #print('relaxgpaw over',flush=True)
    return structure


calc = GPAW(mode=PW(500),
            xc='PBE',
            setups={'Ti': ':d,3.5'},
            basis='dzp',
            kpts=(2, 2, 1))

traj = Trajectory('V2O5_2H2O_Ovcy_TiO2_101surface_DFTrelaxed.traj', 'w')
name = 'V2O5_2H2O_Ovcy_TiO2_101surface_gm'
data = read('V2O5_2H2O_Ovcy_TiO2_101_newstrufound.traj@:')
for i in range(1, len(data)):
    name = 'V2O5_2H2O_Ovcy_TiO2_101surface_isomer_{}'.format(i)
    a = data[i]
    a.set_calculator(calc)
    a_relaxed = relaxGPAW(a, name, forcemax=0.02, niter_max=3, steps=100)
    traj.write(a_relaxed)
示例#56
0
'''

cutoff = 17

'Load infomration from data dictionary (local)'
try:
	with open("dir_data.json", "r") as read_file:
	    data = json.load(read_file)
	qm = data['qm_region']
except:
	print('dir_data.json is not available')
	exit()

'load qm structure'
try:
	atoms = io.read('input.xyz')
except:
	print('input.xyz is not available')
	exit()

'generate list of atoms outside cutoff'
to_be_deleted = []
for atom in atoms:
	for qm_atom in qm:
		d = atoms.get_distance(atom.index, qm_atom)
		if d > cutoff:
			if atom.index not in to_be_deleted:
				if atom.index not in data['qm_region']:
					to_be_deleted.append(atom.index)

to_be_deleted.reverse() #so we don't mess up the numbering
示例#57
0
def get_infrared_intensities(self):
    """Calculate infrared intensities of vibrational modes.

    Returns an array of normalized intensities for each vibrational
    mode. You should have run the vibrational calculation already. This
    function does not run it for you.

    python translation of # A utility for calculating the vibrational
    intensities from VASP output (OUTCAR) # (C) David Karhanek,
    2011-03-25, ICIQ Tarragona, Spain (www.iciq.es)
    http://homepage.univie.ac.at/david.karhanek/downloads.html#Entry02
    """
    assert self.parameters.get('lepsilon', None) is True
    assert self.parameters.get('nwrite', 0) == 3
    assert self.parameters.get('ibrion', 0) == 7

    self.update()

    atoms = read(os.path.join(self.directory, 'POSCAR'), format='vasp')
    NIONS = len(atoms)
    BORN_NROWS = NIONS * 4 + 1

    with open(os.path.join(self.directory, 'OUTCAR'), 'r') as f:
        alltext = f.read()
        f.seek(0)
        alllines = f.readlines()
        f.close()

    if 'BORN' not in alltext:
        raise Exception('Born effective charges missing. '
                        'Did you use IBRION=7 or 8?')

    if 'Eigenvectors after division by SQRT(mass)' not in alltext:
        raise Exception('You must rerun with NWRITE=3 to get '
                        'sqrt(mass) weighted eigenvectors')

    # get the Born charges
    for i, line in enumerate(alllines):
        if 'BORN EFFECTIVE CHARGES' in line:
            break

    BORN_MATRICES = []
    i += 2  # skip a line
    for j in range(NIONS):
        BM = []
        i += 1  # skips the ion count line
        for k in range(3):
            line = alllines[i]
            fields = line.split()
            BM.append([float(x) for x in fields[1:4]])
            i += 1  # advance a line
        BORN_MATRICES.append(BM)

    BORN_MATRICES = np.array(BORN_MATRICES)

    # Get the eigenvectors and eigenvalues.  maybe I can replace this
    # code with my other code. for now I just reproduce the count
    # number of vibs. this gets the number from outcar. it seems like
    # it should be known in advance unless constraints make it hard to
    # tell.

    # the next code in the shell script just copies code to eigenvectors.txt
    for i, line in enumerate(alllines):
        if 'Eigenvectors after division by SQRT(mass)' in line:
            break

    EIG_NVIBS = 0
    for line in alllines[i:]:
        if ('f' in line and 'THz' in line and 'cm-1' in line):
            EIG_NVIBS += 1

    EIG_NIONS = BORN_NROWS
    # I guess this counts blank rows and non-data rows
    # EIG_NROWS = (EIG_NIONS + 3) * EIG_NVIBS + 3

    # i is where the data starts
    i += 6

    EIGENVALUES = []
    EIGENVECTORS = []
    for j in range(EIG_NVIBS):
        mode = []
        EIGENVALUES.append(alllines[i])  # frequencies are here

        i += 1  # skip the frequency line
        i += 1  # skip the xyz line
        for k in range(3):
            fields = [float(x) for x in alllines[i].split()]
            mode.append(fields[3:])
            i += 1
        EIGENVECTORS.append(mode)
        i += 1  # skip blank line

    EIGENVECTORS = np.array(EIGENVECTORS)

    # now we are ready to compute intensities. see
    # http://othes.univie.ac.at/10117/1/2010-05-05_0547640.pdf, page
    # 21.

    # I(\omega) = \sum_{\alpha=1}^3 |
    # \sum_{l=1}^M \sum_{\beta=1}^3 Z_{\alpha\beta}(l)e_{\beta}(l)|^2

    # omega is the vibrational mode
    # alpha, beta are the cartesian polarizations
    # l is the atom number
    # e_beta is the eigenvector of the mode

    intensities = []

    for mode in range(len(EIGENVECTORS)):
        S = 0  # This is the triple sum
        for alpha in [0, 1, 2]:
            s = 0
            for l in [0, 1, 2]:  # this is the atom number
                for beta in [0, 1, 2]:
                    e = EIGENVECTORS[mode][l]
                    Zab = BORN_MATRICES[l][alpha][beta]

                    s += Zab * e[beta]
            S += s**2
        intensities.append(S)

    intensities = np.array(intensities) / max(intensities)
    return intensities
示例#58
0
from ase.ga.relax_attaches import VariansBreak
from ase.constraints import FixAtoms

from population import population
from parallel_utilities import sync_atoms
from gpaw import GPAW, FermiDirac, PoissonSolver, Mixer, PW
from gpaw import extra_parameters
extra_parameters['blacs'] = True
from gpaw.utilities import h2gpts
import traceback
import sys
import os
import ase.parallel as mpi
world = mpi.world

traj = Trajectory('Pt10_5O2_Al2O3_KRRfund9l_DFTrelaxed.traj', 'w')
for i in range(1, 4):
    data = []
    stru = '../Pt10_5O2_{}/Pt10_5O2_Al2O3_KRRfund9l_DFTrelaxed.traj'.format(i)
    data = read(stru + '@:')
    data.sort(key=lambda x: x.get_potential_energy())
    for j in range(0, len(data)):
        traj.write(data[j])

data1 = read('Pt10_5O2_Al2O3_KRRfund9l_DFTrelaxed.traj@:')
data1.sort(key=lambda x: x.get_potential_energy())
traj = Trajectory('Pt10_5O2_Al2O3_KRRfund9l_DFTrelaxedsorted.traj', 'w')
for j in range(0, len(data1)):
    traj.write(data1[j])
    print(data1[j].get_potential_energy())
def dump_reference_json():
    import ubjson
    from copy import copy
    from itertools import product

    sys.path.insert(0, os.path.join(root, "build/"))
    sys.path.insert(0, os.path.join(root, "tests/"))

    cutoffs = [2, 3]
    gaussian_sigmas = [0.2, 0.5]
    max_radials = [4]
    max_angulars = [3]
    cutoff_smooth_widths = [1.0]
    radial_basis = ["GTO", "DVR"]
    cutoff_function_types = ["ShiftedCosine", "RadialScaling"]
    fns = [
        os.path.join(inputs_path, "CaCrP2O7_mvc-11955_symmetrized.json"),
        os.path.join(inputs_path, "small_molecule.json"),
    ]
    fns_to_write = [
        os.path.join(read_inputs_path, "CaCrP2O7_mvc-11955_symmetrized.json"),
        os.path.join(read_inputs_path, "small_molecule.json"),
    ]
    np.random.seed(0)
    datasets_species = [1, 6, 7, 8, 15, 20, 24]
    projection_matrices = {
        str(sp): np.random.rand(max_angulars[0] + 1, max_radials[0],
                                max_radials[0]).tolist()
        for sp in datasets_species
    }
    optimization = [
        dict(),
        dict(Spline=dict(accuracy=1e-8)),
        dict(
            Spline=dict(accuracy=1e-8),
            RadialDimReduction=dict(projection_matrices=projection_matrices),
        ),
    ]
    data = dict(
        filenames=fns_to_write,
        cutoffs=cutoffs,
        gaussian_sigmas=gaussian_sigmas,
        max_radials=max_radials,
        rep_info=[],
    )

    for fn in fns:
        for cutoff in cutoffs:
            data["rep_info"].append([])
            for (
                    gaussian_sigma,
                    max_radial,
                    max_angular,
                    cutoff_smooth_width,
                    rad_basis,
                    cutoff_function_type,
                    opt_args,
            ) in product(
                    gaussian_sigmas,
                    max_radials,
                    max_angulars,
                    cutoff_smooth_widths,
                    radial_basis,
                    cutoff_function_types,
                    optimization,
            ):
                frames = [read(fn)]
                if cutoff_function_type == "RadialScaling":
                    cutoff_function_parameters = dict(rate=1,
                                                      scale=cutoff * 0.5,
                                                      exponent=3)
                else:
                    cutoff_function_parameters = dict()

                hypers = {
                    "interaction_cutoff": cutoff,
                    "cutoff_smooth_width": cutoff_smooth_width,
                    "max_radial": max_radial,
                    "max_angular": max_angular,
                    "gaussian_sigma_type": "Constant",
                    "cutoff_function_type": cutoff_function_type,
                    "cutoff_function_parameters": cutoff_function_parameters,
                    "gaussian_sigma_constant": gaussian_sigma,
                    "radial_basis": rad_basis,
                    "optimization": opt_args,
                }

                sph_expn = SphericalExpansion(**hypers)
                expansions = sph_expn.transform(frames)
                x = expansions.get_features(sph_expn)
                x[np.abs(x) < 1e-300] = 0.0
                data["rep_info"][-1].append(
                    dict(feature_matrix=x.tolist(),
                         hypers=copy(sph_expn.hypers)))

    with open(
            os.path.join(root, dump_path,
                         "spherical_expansion_reference.ubjson"),
            "wb",
    ) as f:
        ubjson.dump(data, f)
示例#60
0
#!/usr/bin/env python3
from ase import Atom
from ase import Atoms
from ase.io import read


# Read structures
Na6_lowest = read('christmas-tree.xyz')
Na6_2nd_lowest = read('half-decahedron.xyz')

# Get potential energies
E_christmas = Na6_lowest.get_potential_energy()
E_decahedron = Na6_2nd_lowest.get_potential_energy()

print('Potential energy of the two most stable structures before relaxation')
print('Christmas-tree: '+str(E_christmas))
print('Half_decahedron: '+str(E_decahedron))