Пример #1
0
def gen222(name=None,
           A='Sr',
           B='Mn',
           O='O',
           latticeconstant=3.9,
           mag_order='FM',
           mag_atom=None,
           m=5,
           sort=True):
    if name is not None:
        symbols = string2symbols(name)
        A, B, O, _, _ = symbols

    atoms = PerovskiteCubic([A, B, O], latticeconstant=latticeconstant)
    atoms = atoms.repeat([2, 2, 2])
    if sort:
        my_write_vasp('UCPOSCAR', atoms, vasp5=True, sort=True)
        atoms = read_vasp('UCPOSCAR')

    spin_dn = {
        'FM': [],
        'A': [0, 1, 4, 5],
        'C': [0, 2, 5, 7],
        'G': [0, 3, 5, 6]
    }
    if mag_order != 'PM':
        mag = np.ones(8)
        mag[np.array(spin_dn[mag_order], int)] = -1.0
        if mag_atom is None:
            atoms = set_element_mag(atoms, B, mag * m)
        else:
            atoms = set_element_mag(atoms, mag_atom, mag * m)
    return atoms
Пример #2
0
def viewStructs(name, directory, kind = 'gen'):
    """
    View collection of structures as a "trajectory"

    Args:
        - name (str): substring unique to structures (.gen, POSCAR, slab, etc)
        - directory (str): Directory where the structures live
        - kind: kind of output froim list of (vasp, gen)
        
    Opens viewer with loaded trajectory (if remote, need X server)
    """
    geometries = []
    files = os.listdir(directory)

    if kind == 'gen':
        pattern = r"{}.*.gen".format(name)
    elif kind == 'vasp':
        pattern = r"{}".format(name)
    else:
        raise ValueError("file kind must be from (vasp, gen)")

    for i in files:
        key = re.search(pattern, i)

        if key:
            if kind == 'gen':
                geometries +=  [gen.read_gen(directory + i)]
            elif kind == 'vasp':
                geometries +=  [vasp.read_vasp(directory + i)]
            else:
                raise ValueError("file kind must be from (vasp, gen)")
    view(geometries)
Пример #3
0
    def __elements(self, path='POSCAR'):

        from ase.io import vasp

        f = vasp.read_vasp(path)

        return f.get_chemical_symbols()
Пример #4
0
def make_conventional_cell(file_name_read):
    if file_name_read.split('.')[-1] == 'vasp':
        input_file_format = 'vasp'
    elif file_name_read.split('.')[-1] == 'cif':
        input_file_format = 'cif'
    else:
        print('Please provide correct file name: .vasp or .cif')
        exit(1)

    file_read = open(file_name_read, 'r')

    if input_file_format == 'vasp':
        pos = vasp.read_vasp(file_read)
    elif input_file_format == 'cif':
        pos = io.read(file_read, format='cif')

    if indict['dimensional'][0] == '3D':
        if indict['if_conventional_cell'][0] == 'yes':
            to_primitive = False
        elif indict['if_conventional_cell'][0] == 'no':
            to_primitive = True

        pos_std = standardize_cell(pos, to_primitive=to_primitive)
        pos_conv = Atoms(pos_std[2], scaled_positions=pos_std[1], cell=pos_std[0])

    elif indict['dimensional'][0] == '2D':
        pos_conv = pos

    return pos_conv
    
Пример #5
0
def test():
    parser = argparse.ArgumentParser(description='Decide AFM structure 1 -1')
    parser.add_argument('-f',
                        '--filename',
                        type=str,
                        help='POSCAR filename',
                        default='POSCAR.vasp')
    parser.add_argument('-n',
                        '--nodes',
                        type=str,
                        help='symbol of element on the node',
                        nargs='+')
    parser.add_argument('-o',
                        '--origin',
                        type=str,
                        help='From which symbol_number')
    parser.add_argument('--xmin', type=float, help='xmin', default=0.5)
    parser.add_argument('--xmax', type=float, help='xmax', default=4.8)
    args = parser.parse_args()

    #plot_all_pdos(element_types=args.element,filename=args.filename,ispin=args.ispin,ymin=args.ymin,ymax=args.ymax,xmin=args.xmin,xmax=args.xmax,output_dir=args.output)

    atoms = read_vasp(args.filename)
    symnums, vals = even_or_odd_path(atoms,
                                     args.origin,
                                     args.nodes,
                                     first_neighbor_min=args.xmin,
                                     first_neighbor_max=args.xmax)
    for sym in args.nodes:
        vs = []
        for i, (s, v) in enumerate(zip(symnums, vals)):
            if symnum_to_sym(s) == sym:
                vs.append(v)
        print('%s: %s' % (sym, vs))
Пример #6
0
def main():
    '''Main driver routine.'''

    inpaths = [
        os.path.join(os.getcwd(), '../globalTargets/vaspdata', entry)
        for entry in sorted(os.listdir('../globalTargets/vaspdata'))
    ]

    # start with homogeneous weighting
    weights = np.ones((31, ), dtype=int)
    # possibly, certain datapoints are more important
    weights[4:13] = 3

    strucs = []
    energies = np.empty((len(inpaths), 1))

    for ii, inpath in enumerate(inpaths):
        strucs.append(read_vasp(os.path.join(inpath, 'POSCAR')))
        props = read_vasp_out(os.path.join(inpath, 'OUTCAR'))
        energies[ii, 0] = props.get_total_energy()

    fnetdata = Fortformat(strucs,
                          'fnetdata.xml',
                          targets=energies,
                          atomic=False,
                          frac=True)
    fnetdata.weights = weights
    fnetdata.dump()
Пример #7
0
def calc_elast_dipole_dft(input_file, vasp_calc=True):
    """Reads OUTCAR file in the same directory with one shot forces
    induced by removal of defect. Reads defect position
    from .xyz file (which contains the defect) defined by `input_file`
    calculates and returns the elastic dipole tensor of the defect.

    Args:
      input_file(str): name of input .xyz file containing defect cell.

    Returns:
      Elastic Dipole Tensor 3x3 numpy array.
    """

    elastic = ElasticDipole()
    ats_def = Atoms(input_file)
    defect = find_h_atom(ats_def)
    if vasp_calc:
        import ase.io.vasp as vasp
        ats_pos = vasp.read_vasp()
        ats = vasp.read_vasp_out()
        ats = Atoms(ats)
    else:
        pass

    print 'Defect index', defect.index, 'Position', defect.position, 'Type: ', defect.number
    f = ats.get_forces()
    ats.add_property('force', f.T)
    ats.write('force.xyz')
    return elastic.compute_vacancy_dipole(defect,
                                          ats_pos.copy(),
                                          forces=ats.get_forces())
Пример #8
0
def sound_velocity(elastic_constants_dict, cwd):
    try:
        pos = vasp.read_vasp('%s/OPT/CONTCAR'%cwd)
        volume = pos.get_volume()/0.529177**3.0
        M = sum(pos.get_masses())
        B = elastic_constants_dict['B_vrh']
        G = elastic_constants_dict['G_vrh']

        V_s = 0.001*G**0.5*(10**9/(M*10**(-3)/volume/(0.529177*10**(-10))**3/(6.02*10**23)))**0.5
        V_b = 0.001*B**0.5*(10**9/(M*10**(-3)/volume/(0.529177*10**(-10))**3/(6.02*10**23)))**0.5
        V_p = 0.001*(B+4.*G/3.)**0.5*(10**9/(M*10**(-3)/volume/(0.529177*10**(-10))**3/(6.02*10**23)))**0.5
        V_m = ((2./V_s**3.+1/V_p**3)/3.)**(-1./3.)

        T_D = (6.626*10**(-34)/(1.381*10**(-23)))*(3./(volume*(.529177*10**(-10))**3.)/4./3.1415926)**(1./3.)*V_m*1000

        elastic_constants_dict['V_s'] = V_s
        elastic_constants_dict['V_b'] = V_b
        elastic_constants_dict['V_p'] = V_p
        elastic_constants_dict['V_m'] = V_m
        elastic_constants_dict['T_D'] = T_D
    except:
        pass

    return elastic_constants_dict
    
Пример #9
0
def main():
    '''Main driver routine.'''

    np.random.seed(42)

    inpaths = [
        os.path.join(os.getcwd(), '../globalTargets/vaspdata', entry)
        for entry in sorted(os.listdir('../globalTargets/vaspdata'))
    ]

    strucs = []
    features = []
    energies = np.empty((len(inpaths), 1))

    for ii, inpath in enumerate(inpaths):
        struc = read_vasp(os.path.join(inpath, 'POSCAR'))
        strucs.append(struc)
        props = read_vasp_out(os.path.join(inpath, 'OUTCAR'))
        energies[ii, 0] = props.get_total_energy()
        features.append(np.random.random_sample((len(struc), 3)))

    fnetdata = Fortformat(strucs,
                          'fnetdata.xml',
                          targets=energies,
                          features=features,
                          atomic=False,
                          frac=True)
    fnetdata.dump()
Пример #10
0
def main():
    '''Main driver routine.'''

    nndists = np.arange(2.00, 3.50 + 0.05, 0.05)

    inpaths = [
        os.path.join(os.getcwd(), 'vaspdata', entry)
        for entry in sorted(os.listdir('vaspdata'))
    ]
    outpaths = [
        os.path.join(os.getcwd(), 'dataset', 'nndist_{:.3f}'.format(nndist))
        for nndist in nndists
    ]

    strucs = []
    energies = []

    for ii, inpath in enumerate(inpaths):
        struc = read_vasp(os.path.join(inpath, 'POSCAR'))
        strucs.append(struc)
        props = read_vasp_out(os.path.join(inpath, 'OUTCAR'))
        tmp = np.empty((len(struc), 1))
        tmp[:, 0] = props.get_total_energy() / 2.0
        energies.append(tmp)

    fnetdata = Fortformat(strucs,
                          outpaths,
                          targets=energies,
                          atomic=True,
                          frac=True)
    fnetdata.dump()
Пример #11
0
def gen_forceconstants(species,
                       index,
                       cart,
                       displacement=0.1,
                       hour=5,
                       np=48,
                       template_dir='templates'):
    """
    generate directory and POSCAR perturbation

    Args:
        species(str): Name of perturbed atom.
        
    """
    target_dir = "{spec}_{index}_{cart}_disp".format(spec=species,
                                                     index=index,
                                                     cart=cart[1])
    dir_util.copy_tree(template_dir, target_dir)
    with pushd(target_dir) as ctx0:
        #Fix the pbs string
        with open('vasp.sh', 'r') as f:
            pbs_str = f.read()
        pbs_str = pbs_str.format(hour=hour,
                                 index=index,
                                 np=np,
                                 species=species)
        with open('vasp.sh', 'w') as f:
            print >> f, pbs_str

        ats = vasp.read_vasp('POSCAR')
        print "before pert", ats[index].position[:]
        ats[index].position[cart[0]] += displacement
        print "after pert", ats[index].position[:]
        vasp.write_vasp("POSCAR", ats)
Пример #12
0
def read_poscar_and_unsort(filename='CONTCAR'):
    """
    read poscar and unsort. return the symbols,positions and cell in unsorted order.
    """
    atoms = read_vasp(filename)
    symbols = get_unsorted(atoms.get_chemical_symbols())
    positions = get_unsorted(atoms.get_positions())
    cell = atoms.get_cell()
    return symbols, positions, cell
Пример #13
0
 def read_cont(self):
     '''read CONTCAR for output structure'''
     from ase.io.vasp import read_vasp
     structure = DataFactory('structure')()
     cont = self.get_file('CONTCAR')
     if not cont:
         self.logger.info('CONTCAR not found!')
         return None
     structure.set_ase(read_vasp(cont))
     return structure
Пример #14
0
 def test_write_poscar_cif(self):
     calc = self._get_calc('c', 'm')
     inp = calc.get_inputs_dict()
     from ase.io.vasp import read_vasp
     calc.write_poscar(inp, self.tmpf)
     wd = os.getcwd()
     os.chdir(os.path.dirname(self.tmpf))
     poscar = None
     poscar = read_vasp(self.tmpf)
     os.chdir(os.path.dirname(wd))
     self.assertIsNotNone(poscar)
Пример #15
0
def my_read_vasp(filename):
    from ase.io.vasp import read_vasp
    import types

    atoms = read_vasp(filename)
    with open(filename, 'r') as f:
        atoms.pos_a0 = float(f.readlines()[1])

    atoms.get_cn = types.MethodType(get_cn, atoms)
    atoms.get_nelem = types.MethodType(get_nelem, atoms)

    return atoms
Пример #16
0
 def test_write_poscar_cif(self):
     """Check that POSCAR is written when the input is a .cif file"""
     calc = self._get_calc('c', 'm')
     inp = calc.get_inputs_dict()
     from ase.io.vasp import read_vasp
     calc.write_poscar(inp, self.tmpf)
     working_dir = os.getcwd()
     os.chdir(os.path.dirname(self.tmpf))
     poscar = None
     poscar = read_vasp(self.tmpf)
     os.chdir(os.path.dirname(working_dir))
     self.assertIsNotNone(poscar)
Пример #17
0
def main(dirname, v, nOut = 1):
    # specify directory

    dirPath = Path(dirname)

    #specify velocity 

    v = float(v) #in vasp units

    #number of outputs per CONTCAR
    nOut = int(nOut)



    for fileName in os.listdir(dirPath):
        if ".out" in fileName:
            continue
        print(dirPath, fileName, Path(fileName))
            
        filePath = dirPath / Path(fileName)
        temp = vasp.read_vasp(filePath)
        headerLen = 9 #nlines of header block; index of first coordinate line

        Arindex = [atom.index for atom in temp if atom.symbol == 'Ar'][0]

        # accounts for header block, all positions + all velos + gap between, goes to last line of velo block
        veloLine = headerLen + len(temp) + Arindex + 1
        arLine = headerLen + Arindex

        for i in range(nOut):
            #phi is angle relative to z axis; theta is angle in xy plane
            #phi between 180 and 90 degrees, theta between 0 and 360
            phi, theta = np.random.uniform(-np.pi, -np.pi/2), np.random.uniform(0, 2*np.pi)

            vx = v * np.sin(phi) * np.cos(theta)
            vy = v * np.sin(phi) * np.sin(theta)
            vz = v * np.cos(phi)

            # random fractional coordinates for x and y positions of Ar
            x, y = np.random.random(size = 2)

            # write output files
            with open(filePath, 'r') as f:
                outputName = fileName + "-" + str(i) + ".out"
                with open(dirPath / Path(outputName), 'w') as fout:
                    for i, line in enumerate(f):
                        if i == veloLine:
                            fout.write(" ".join(np.array([vx, vy, vz], dtype = str)))
                        elif i == arLine:
                            z = line.split()[2] # same z position as input Ar
                            fout.write(" ".join(np.array([x, y, z, "T T T \n"], dtype = str)))
                        else:
                            fout.write(line)
Пример #18
0
def main(filename, source, x=1, y=1, z=1):
    temp = list(xyz.read_xyz(filename))[0]

    if source == "NA":
        temp.cell = Cell([[x, 0, 0], [0, y, 0], [0, 0, z]])

    else:
        try:
            temp.cell = vasp.read_vasp(source).cell
        except:
            raise Exception("source is neither valid POSCAR nor NA")

    vasp.write_vasp("../POSCAR_ec", temp, sort=True, vasp5=True)
Пример #19
0
def get_insb_input(configure, sample, get_queue_name_from_code):  # pylint: disable=unused-argument
    """
    Create input for the VASP InSb sample.
    """
    from aiida.plugins import DataFactory
    from aiida.orm import Code
    from aiida.orm import Dict

    res = dict()

    structure = orm.StructureData()
    structure.set_ase(read_vasp(sample('InSb/POSCAR')))
    res['structure'] = structure

    PotcarData = DataFactory('vasp.potcar')  # pylint: disable=invalid-name
    res['potentials'] = {
        'In': PotcarData.find_one(family='pbe', symbol='In_d'),
        'Sb': PotcarData.find_one(family='pbe', symbol='Sb')
    }

    res['parameters'] = Dict(dict=dict(
        ediff=1e-3,
        lsorbit=True,
        isym=0,
        ismear=0,
        sigma=0.05,
        gga='PE',
        encut=380,
        magmom='600*0.0',
        nbands=36,
        kpar=4,
        nelmin=0,
        lwave=False,
        aexx=0.25,
        lhfcalc=True,
        hfscreen=0.23,
        algo='N',
        time=0.4,
        precfock='normal',
    ))

    res['code'] = Code.get_from_string('vasp')
    res['calculation_kwargs'] = dict(
        options=dict(resources={
            'num_machines': 2,
            'num_mpiprocs_per_machine': 18
        },
                     queue_name=get_queue_name_from_code('vasp'),
                     withmpi=True,
                     max_wallclock_seconds=1200))
    return res
def main():
    jobn, Etot, Eent, pres = vf.vasp_read_post_data()

    ASE_Atoms = read_vasp('../y_full_relax/CONTCAR')
    atoms_pos = ASE_Atoms.get_positions()
    natoms = atoms_pos.shape[0]

    V0 = np.linalg.det(ASE_Atoms.cell) / natoms
    Etot = Etot / natoms

    latoms = vf.get_list_of_atoms()
    latoms2 = vf.get_list_of_outcar()

    V = np.array([])
    magtot = np.array([])
    for i in np.arange(len(latoms)):
        temp = latoms[i].get_volume() / natoms
        V = np.append(V, temp)

        if np.abs(temp - V0) < 1e-10:
            E0 = Etot[i]

        try:
            temp = latoms2[i].get_magnetic_moment() / natoms
        except:
            temp = 0
        magtot = np.append(magtot, temp)

    magtot = np.abs(magtot)

    # scale
    k = np.array([])
    for i in np.arange(len(jobn)):
        k = np.append(k, float(jobn[i]))

    if np.linalg.norm(k - (V / V0)**(1 / 3)) > 1e-10:
        sys.exit('==> ABORT. wrong scaling. ')

    # check
    if Etot.min() != E0:
        sys.exit('E0 is wrong. Abort!')

    if Etot[-5:].std() > 5e-4:
        print('WARNING: Eatom might be wrong!')

    Eatom = Etot[-1]
    Ecoh = E0 - Eatom

    Vp, p, VB, B, p0, B0 = calc_p_B(V, Etot, V0)
    write_output(E0, Eatom, Ecoh, V0, p0, B0)
    plot_output(E0, Eatom, Ecoh, V0, k, Etot, Vp, p, VB, B, p0, B0, magtot)
Пример #21
0
 def read_structure(self, structfile):
     # returns ase structure from proper structure file
     structure = ""
     if self.calculator == "VASP":
         structure = read_vasp(
             structfile)  # structure - instance of ASE.Atom class
     if self.calculator == "siesta":
         structure = xv_to_atoms(structfile)
     if self.calculator == "openmx":  # hashfile of openmx.dat (openmx.dat#)
         pos, species, cell = read_openmx_hashfile(structfile)
         structure = Atoms(species)
         structure.set_positions(pos)
         structure.set_cell(cell)
     return structure
Пример #22
0
def gridVasp(adsorbate, slab, directory='tempout/', spacing=0.2):
    """
    Takes in slab, adsorbate, and desired output directory.
    Writes numbered POSCAR files to output directory with adsorbate 
    placed in grid pattern

    Args:
        adsorbate: either path (str) for POS/CONTCAR or Atoms obj
        slab: either path (str) for POS/CONTCAR or Atoms obj
        directory: path (str) for desired output location
        spacing: spacing between grid points (eg, 0.2 is a 5x5 grid)
    Returns:
        None
    """
    if type(adsorbate) == str:
        adsorbate = vasp.read_vasp(adsorbate)

    if type(slab) == str:
        slab = vasp.read_vasp(slab)
    # TODO: make this work with path objects?

    i = 0  # 0 index written POSCAR{i} files
    for _x in np.arange(0, 1 - spacing, spacing):
        for _y in np.arange(0, 1 - spacing, spacing):
            s = slab.copy()
            x, y, z = slab.cell.cartesian_positions([_x, _y, 0])
            add_adsorbate(s, adsorbate, height=2, position=(x, y))
            s = Atoms(sorted(s, key=lambda x: x.symbol))
            s.cell = slab.cell
            vasp.write_vasp(directory + "POSCAR" + str(i),
                            s,
                            label='{} on {}'.format(
                                adsorbate.get_chemical_formula(),
                                slab.get_chemical_formula()),
                            vasp5=True)

            i += 1
Пример #23
0
 def get_soap(file, rcut=7, nmax=5, lmax=8):
     print('./' + file)
     ml = vasp.read_vasp('./' + file)
     species = ['Cd', 'Te']
     periodic_soap = SOAP(periodic=True,
                          species=species,
                          rcut=rcut,
                          nmax=nmax,
                          lmax=lmax,
                          rbf='gto',
                          sigma=0.125,
                          average=True)
     soap = periodic_soap.create(ml)
     #soap = 1
     return soap
Пример #24
0
 def _set_default_structure(self, structure):
     """Set a structure depending on what was given, empty if nothing was given"""
     if not structure:
         self._structure = self.calc_cls.new_structure()
     elif isinstance(structure, (str, unicode)):
         structure = os.path.abspath(os.path.expanduser(structure))
         if os.path.splitext(structure)[1] == '.cif':
             self._structure = DataFactory('cif').get_or_create(
                 structure)[0]
         elif os.path.basename(structure) == 'POSCAR':
             from ase.io.vasp import read_vasp
             atoms = read_vasp(os.path.abspath(structure))
             self._structure = self.calc_cls.new_structure()
             self._structure.set_ase(atoms)
     else:
         self._structure = structure
Пример #25
0
def poscar_to_ase(poscar_string):
    """
    Parse POSCAR using ase

    Returns:
        Refined ASE structure (object) *or* None
        None *or* error (str)
    """
    ase_obj, error = None, None
    buff = cStringIO.StringIO(poscar_string)
    try:
        ase_obj = read_vasp(buff)
    except AttributeError:
        error = 'Types of atoms cannot be neither found nor inferred'
    except Exception:
        error = 'Cannot process POSCAR: invalid or missing data'
    buff.close()
    return ase_obj, error
Пример #26
0
 def _set_default_structure(self, structure):
     if not structure:
         self._structure = self.calc_cls.new_structure()
     elif isinstance(structure, (str, unicode)):
         structure = os.path.abspath(structure)
         if os.path.splitext(structure)[1] == '.cif':
             self._structure = DataFactory('cif').get_or_create(
                 structure)[0]
         elif os.path.basename(structure) == 'POSCAR':
             from ase.io.vasp import read_vasp
             pwd = os.path.abspath(os.curdir)
             os.chdir(os.path.dirname(structure))
             atoms = read_vasp('POSCAR')
             os.chdir(pwd)
             self._structure = self.calc_cls.new_structure()
             self._structure.set_ase(atoms)
     else:
         self._structure = structure
Пример #27
0
def get_framework(fname, rep):
    #Define openbabel file conversion type. "from" and "to"
    obConversion = openbabel.OBConversion()
    obConversion.SetInAndOutFormats("cif", "CONTCAR")

    #Define openbabel molecule type object.
    mol = openbabel.OBMol()
    obConversion.ReadFile(mol, fname)

    #Convert and write
    obConversion.WriteFile(mol, 'CONTCAR_frame')

    #Read using ASE, generate atoms type object.
    frmwrk_atoms = vasp.read_vasp('CONTCAR_frame')

    #Repeat atoms.
    if len(rep) > 0:
        frmwrk_rep = frmwrk_atoms.repeat(rep)

    return frmwrk_rep
Пример #28
0
def get_soap(calculation, rcut=7, nmax=6, lmax=8, fmt='MW'):
    if fmt == 'MW':
        urlp = 'http://materialsweb.org/' + calculation['path'][22:] + '/POSCAR'
        file = urllib.request.urlopen(urlp)
        file = file.read().decode("utf-8")
        file = io.StringIO(file)
    elif fmt == 'poscar':
        file = calculation
    ml = vasp.read_vasp(file)
    periodic_soap = SOAP(periodic=True,
                         species=np.unique(ml.get_atomic_numbers()),
                         rcut=rcut,
                         nmax=nmax,
                         lmax=lmax,
                         rbf='gto',
                         sigma=0.125,
                         average=True)
    soap = periodic_soap.create(ml)
    # soap = 1
    return soap
Пример #29
0
def sound_velocity(elastic_constants_dict, cwd):
    try:
        pos = vasp.read_vasp('%s/OPT/CONTCAR' % cwd)
        # The Planck's constant in m^2 Kg s^-1
        h = 6.626E-34
        # The Boltzmann constant in m^2 Kg s^-2 K-1
        k = 1.381E-23
        # The Avogadro's Constant
        Na = 6.02E+23
        # The number of atoms in the supercell (molecule)
        n = pos.get_global_number_of_atoms()
        # The total volume of the supercell (molecule)
        volume = pos.get_volume()
        # The total mass of all atoms in the supercell (molecule), in AMU
        M = sum(pos.get_masses())
        # The density in Kg/m^3
        rho = M * 1E-3 / Na / volume / 1E-30

        B = elastic_constants_dict['B_vrh']
        G = elastic_constants_dict['G_vrh']
        V_s = 1E-3 * G**0.5 * (1E+9 / (M * 1E-3 / volume / 1E-30 /
                                       (6.02E+23)))**0.5
        V_b = 1E-3 * B**0.5 * (1E+9 / (M * 1E-3 / volume / 1E-30 /
                                       (6.02E+23)))**0.5
        V_p = 1E-3 * (B + 4. * G / 3.)**0.5 * (1E+9 /
                                               (M * 1E-3 / volume / 1E-30 /
                                                (6.02E+23)))**0.5
        V_m = ((2. / V_s**3. + 1. / V_p**3) / 3.)**(-1. / 3.)
        T_D = h / k * (3. * n / 4. / pi * Na * rho / M /
                       1E-3)**(1. / 3.) * V_m * 1E+3

        elastic_constants_dict['V_s'] = V_s
        elastic_constants_dict['V_b'] = V_b
        elastic_constants_dict['V_p'] = V_p
        elastic_constants_dict['V_m'] = V_m
        elastic_constants_dict['T_D'] = T_D
    except:
        pass

    return elastic_constants_dict
def get_framework(fname, rep):
    #Define openbabel file conversion type. "from" and "to"
    #obConversion = openbabel.OBConversion()
    #obConversion.SetInAndOutFormats("cif", "CONTCAR")

    #Define openbabel molecule type object.
    #mol = openbabel.OBMol()
    #obConversion.ReadFile(mol, fname)

    #Convert and write
    #obConversion.WriteFile(mol, 'CONTCAR_frame')

    #Read using ASE, generate atoms type object.
    frmwrk_atoms = vasp.read_vasp(
        '/home/chr218/materials_bandgap_workflow/materials_bandgap_workflow-master/example/frameworks/adjusted_vaccum/CONTCAR_frame'
    )

    #Repeat atoms.
    if len(rep) > 0:
        frmwrk_rep = frmwrk_atoms.repeat(rep)

    return frmwrk_rep
Пример #31
0
def read_xdatcar(filename='XDATCAR',poscarfile='CONTCAR'):
    """Import XDATCAR type file.

    Reads unitcell, atom positions and constraints from the POSCAR/CONTCAR
    file and tries to read atom types from POSCAR/CONTCAR header, if this fails
    the atom types are read from OUTCAR or POTCAR file.

    Then reads in positions from an XDATCAR file and returns an array of 
    Atoms() objects with the positions from this file.
    """
 
    import os
    from ase.io import vasp
    import numpy as np

    atoms=vasp.read_vasp(poscarfile)
    natoms = len(atoms)
   
    if isinstance(filename, str):
        f = open(filename)
    else: # Assume it's a file-like object
        f = filename

    data=f.readlines()

    nimages=(len(data)-5)/(natoms+1)

    images = []
    for i in range(nimages):
        images.append(atoms.copy())
        pos=np.zeros((natoms,3),np.float)
        for j in range(natoms):
            pos[j,0]=float(data[6+i*(natoms+1)+j].split()[0])
            pos[j,1]=float(data[6+i*(natoms+1)+j].split()[1])
            pos[j,2]=float(data[6+i*(natoms+1)+j].split()[2])
        images[i].set_scaled_positions(pos)

    return images
Пример #32
0
    def read(self, filename='CHG'):
        """Read CHG or CHGCAR file.

        If CHG contains charge density from multiple steps all the
        steps are read and stored in the object. By default VASP
        writes out the charge density every 10 steps.

        chgdiff is the difference between the spin up charge density
        and the spin down charge density and is thus only read for a
        spin-polarized calculation.

        aug is the PAW augmentation charges found in CHGCAR. These are
        not parsed, they are just stored as a string so that they can
        be written again to a CHGCAR format file.

        """

        import ase.io.vasp as aiv
        f = open(filename)
        self.atoms = []
        self.chg = []
        self.chgdiff = []
        self.aug = ''
        self.augdiff = ''
        while True:
            try:
                atoms = aiv.read_vasp(f)
            except (IOError, ValueError, IndexError):
                # Probably an empty line, or we tried to read the
                # augmentation occupancies in CHGCAR
                break
            f.readline()
            ngr = f.readline().split()
            ng = (int(ngr[0]), int(ngr[1]), int(ngr[2]))
            chg = np.empty(ng)
            self._read_chg(f, chg, atoms.get_volume())
            self.chg.append(chg)
            self.atoms.append(atoms)
            # Check if the file has a spin-polarized charge density part, and
            # if so, read it in.
            fl = f.tell()
            # First check if the file has an augmentation charge part (CHGCAR
            # file.)
            line1 = f.readline()
            if line1 == '':
                break
            elif line1.find('augmentation') != -1:
                augs = [line1]
                while True:
                    line2 = f.readline()
                    if line2.split() == ngr:
                        self.aug = ''.join(augs)
                        augs = []
                        chgdiff = np.empty(ng)
                        self._read_chg(f, chgdiff, atoms.get_volume())
                        self.chgdiff.append(chgdiff)
                    elif line2 == '':
                        break
                    else:
                        augs.append(line2)
                if len(self.aug) == 0:
                    self.aug = ''.join(augs)
                    augs = []
                else:
                    self.augdiff = ''.join(augs)
                    augs = []
            elif line1.split() == ngr:
                chgdiff = np.empty(ng)
                self._read_chg(f, chgdiff, atoms.get_volume())
                self.chgdiff.append(chgdiff)
            else:
                f.seek(fl)
        f.close()
Пример #33
0
def read(filename, index=-1, format=None):
    """Read Atoms object(s) from file.

    filename: str
        Name of the file to read from.
    index: int or slice
        If the file contains several configurations, the last configuration
        will be returned by default.  Use index=n to get configuration
        number n (counting from zero).
    format: str
        Used to specify the file-format.  If not given, the
        file-format will be guessed by the *filetype* function. If
        it's 'babel', will try to use the OpenBabel library.

    Known formats:

    =========================  ===========
    format                     short name
    =========================  ===========
    GPAW restart-file          gpw
    Dacapo netCDF output file  dacapo
    Old ASE netCDF trajectory  nc
    Virtual Nano Lab file      vnl
    ASE pickle trajectory      traj
    GPAW text output           gpaw-text
    CUBE file                  cube
    XCrySDen Structure File    xsf  
    Dacapo text output         dacapo-text
    XYZ-file                   xyz
    VASP POSCAR/CONTCAR file   vasp
    Protein Data Bank          pdb
    VTK XML Image Data         vti
    VTK XML Structured Grid    vts
    VTK XML Unstructured Grid  vtu
    =========================  ===========

    """
    p = filename.rfind('@')
    if p != -1:
        try:
            index = string2index(filename[p + 1:])
        except ValueError:
            pass
        else:
            filename = filename[:p]

    if format is None:
        format = filetype(filename)

    if format.startswith('gpw'):
        import gpaw
        r = gpaw.io.open(filename, 'r')
        positions = r.get('CartesianPositions') * Bohr
        numbers = r.get('AtomicNumbers')
        cell = r.get('UnitCell') * Bohr
        pbc = r.get('BoundaryConditions')
        tags = r.get('Tags')
        magmoms = r.get('MagneticMoments')

        atoms = Atoms(positions=positions,
                      numbers=numbers,
                      cell=cell,
                      pbc=pbc)
        if tags.any():
            atoms.set_tags(tags)
        if magmoms.any():
            atoms.set_initial_magnetic_moments(magmoms)

        return atoms

    if format == 'xyz':
        from ase.io.xyz import read_xyz
        return read_xyz(filename, index)

    if format == 'traj':
        from ase.io.trajectory import read_trajectory
        return read_trajectory(filename, index)

    if format == 'cube':
        from ase.io.cube import read_cube
        return read_cube(filename, index)

    if format == 'nc':
        from ase.io.netcdf import read_netcdf
        return read_netcdf(filename, index)

    if format == 'gpaw-text':
        from ase.io.gpawtext import read_gpaw_text
        return read_gpaw_text(filename, index)

    if format == 'dacapo-text':
        from ase.io.dacapo import read_dacapo_text
        return read_dacapo_text(filename)

    if format == 'dacapo':
        from ase.io.dacapo import read_dacapo
        return read_dacapo(filename)
    
    if format == 'xsf':
        from ase.io.xsf import read_xsf
        return read_xsf(filename, index)

    if format == 'vasp':
        from ase.io.vasp import read_vasp
        return read_vasp(filename)
    
    if format == 'mol':
        from ase.io.mol import read_mol
        return read_mol(filename)

    if format == 'pdb':
        from ase.io.pdb import read_pdb
        return read_pdb(filename)

    if format == 'cif':
        from ase.io.cif import read_cif
        return read_cif(filename)

    if format == 'babel':
        from ase.io.babel import read_babel
        return read_babel(filename, index=index)

    if format == 'vti':
        from ase.io.vtkxml import read_vti
        return read_vti(filename)

    if format == 'vts':
        from ase.io.vtkxml import read_vts
        return read_vts(filename)

    if format == 'vtu':
        from ase.io.vtkxml import read_vtu
        return read_vtu(filename)

    if format == 'iwm':
        from ase.io.iwm import read_iwm
        return read_iwm(filename)

    if format == 'Cmdft':
        from ase.io.cmdft import read_I_info
        return read_I_info(filename)

    raise RuntimeError('That can *not* happen!')
Пример #34
0
    def evaluate_indiv(self, Optimizer, individ, relax):
        logger = logging.getLogger(Optimizer.loggername)
        logger.info('Setting up MAST input for individual evaluation with VASP')

        self.setup_mast_inp(Optimizer, individ, self.args, relax)
        num = 0
        for ind in individ:
            totalsol = compose_structure(Optimizer,ind)
            write_vasp('POSCAR_Indiv%s'%num, totalsol, direct=True, vasp5=True)
            num += 1
        #try:
        #    os.mkdir('scratch')
        #    os.mkdir('archive')
        #except OSError:
        #    pass

        cwd = os.getcwd()
        #scratch = os.path.join(cwd,'scratch')
        #archive = os.path.join(cwd,'archive')
        
        #os.environ['MAST_SCRATCH'] = scratch
        #os.environ['MAST_ARCHIVE'] = archive
        scratch = os.getenv('MAST_SCRATCH')
        archive = os.getenv('MAST_ARCHIVE')

        #proc = Popen(['mast','-i','my_mast.inp'])
        #proc.wait()

        mast = MASTInput(inputfile="my_mast.inp")
        ind_folders = mast.check_independent_loops()
        

        for files in glob.glob("loop_*.inp"):
            os.remove(files)
        
        logger.info('Completed setting up MAST jobs for individual evaluation of generation #%s'%Optimizer.generation)
        logger.info("Type 'mast' to manually submit VASP jobs or wait for crontab for submission.")

        while True:

            #proc = Popen(['mast'])
            #proc.wait()
            stats = 'VASP jobs stats:'
            finished = 'Finished jobs: '
            complete = 0
            for d in ind_folders:
                if d in os.listdir(archive):
                    finished += '%s, '%d
                    complete += 1
            running = 'Running jobs: '
            for d in ind_folders:
                if d in os.listdir(scratch):
                    running += '%s, '%d
            logger.info(stats)
            logger.info(finished)
            logger.info(running)
            if complete == len(individ):
               logger.info('Finished VASP jobs for all individuals of generation #%s'%Optimizer.generation) 
               break
            time.sleep(60)
        
        stro = []
        energies = []
        for i in range(len(ind_folders)): 
            ingred = os.path.join(archive,ind_folders[i],'Individual')
            energy_output = check_output(['tail','-n1',os.path.join(ingred, 'OSZICAR')])
            individ[i].energy = float(energy_output.split()[4])
            energies.append(individ[i].energy)
            if relax:
                stro.append('Relaxed structure of individual %s\n'%individ[i].history_index)
            else:
                stro.append('Evaluated energy of individual %s to be %s\n'%(individ[i].history_index,individ[i].energy))
            totalsol = read_vasp(os.path.join(ingred, 'CONTCAR'))
            individ[i], bul = decompose_structure(Optimizer,totalsol,individ[i])
        
            shutil.rmtree(os.path.join(archive,ind_folders[i])) # either remove or zip ??

        

        if relax:
            return individ, stro
        return energies, stro
Пример #35
0
and only along the first unit cell vector
$ repeat.py filename n1
"""


from ase.io.vasp import read_vasp, write_vasp
import sys

nargs = len(sys.argv)
if not nargs in [3, 4, 5]:
    raise SyntaxError('Must specify name of input file and \
direction on command line, e.g. \n \
$ repeat.py POSCAR 2 2 2')

file = sys.argv[1]
n1 = int(sys.argv[2])
if nargs > 3:
    n2 = int(sys.argv[3])
    if nargs > 4:
        n3 = int(sys.argv[4])
    else:
        n3 = 1
else:
    n2 = n3 = 1

atoms = read_vasp(file)
atoms.constraints = []
atoms = atoms.repeat([n1, n2, n3])
write_vasp(file+'-%dx%dx%d' % (n1, n2, n3), atoms)
Пример #36
0
def read(filename, index=-1, format=None):
    """Read Atoms object(s) from file.

    filename: str
        Name of the file to read from.
    index: int or slice
        If the file contains several configurations, the last configuration
        will be returned by default.  Use index=n to get configuration
        number n (counting from zero).
    format: str
        Used to specify the file-format.  If not given, the
        file-format will be guessed by the *filetype* function.

    Known formats:

    =========================  ===========
    format                     short name
    =========================  ===========
    GPAW restart-file          gpw
    Dacapo netCDF output file  dacapo
    Old ASE netCDF trajectory  nc
    Virtual Nano Lab file      vnl
    ASE pickle trajectory      traj
    ASE bundle trajectory      bundle
    GPAW text output           gpaw-text
    CUBE file                  cube
    XCrySDen Structure File    xsf
    Dacapo text output         dacapo-text
    XYZ-file                   xyz
    VASP POSCAR/CONTCAR file   vasp
    VASP OUTCAR file           vasp_out
    SIESTA STRUCT file         struct_out
    ABINIT input file          abinit
    V_Sim ascii file           v_sim
    Protein Data Bank          pdb
    CIF-file                   cif
    FHI-aims geometry file     aims
    FHI-aims output file       aims_out
    VTK XML Image Data         vti
    VTK XML Structured Grid    vts
    VTK XML Unstructured Grid  vtu
    TURBOMOLE coord file       tmol
    TURBOMOLE gradient file    tmol-gradient
    exciting input             exi
    AtomEye configuration      cfg
    WIEN2k structure file      struct
    DftbPlus input file        dftb
    CASTEP geom file           cell
    CASTEP output file         castep
    CASTEP trajectory file     geom
    ETSF format                etsf.nc
    DFTBPlus GEN format        gen
    CMR db/cmr-file            db
    CMR db/cmr-file            cmr
    LAMMPS dump file           lammps
    =========================  ===========

    """
    if isinstance(filename, str):
        p = filename.rfind('@')
        if p != -1:
            try:
                index = string2index(filename[p + 1:])
            except ValueError:
                pass
            else:
                filename = filename[:p]

    if isinstance(index, str):
        index = string2index(index)

    if format is None:
        format = filetype(filename)

    if format.startswith('gpw'):
        import gpaw
        r = gpaw.io.open(filename, 'r')
        positions = r.get('CartesianPositions') * Bohr
        numbers = r.get('AtomicNumbers')
        cell = r.get('UnitCell') * Bohr
        pbc = r.get('BoundaryConditions')
        tags = r.get('Tags')
        magmoms = r.get('MagneticMoments')
        energy = r.get('PotentialEnergy') * Hartree

        if r.has_array('CartesianForces'):
            forces = r.get('CartesianForces') * Hartree / Bohr
        else:
            forces = None

        atoms = Atoms(positions=positions,
                      numbers=numbers,
                      cell=cell,
                      pbc=pbc)
        if tags.any():
            atoms.set_tags(tags)

        if magmoms.any():
            atoms.set_initial_magnetic_moments(magmoms)
        else:
            magmoms = None

        atoms.calc = SinglePointCalculator(energy, forces, None, magmoms,
                                           atoms)

        return atoms

    if format == 'castep':
        from ase.io.castep import read_castep
        return read_castep(filename, index)

    if format == 'castep_cell':
        import ase.io.castep
        return ase.io.castep.read_cell(filename, index)

    if format == 'castep_geom':
        import ase.io.castep
        return ase.io.castep.read_geom(filename, index)

    if format == 'exi':
        from ase.io.exciting import read_exciting
        return read_exciting(filename, index)

    if format == 'xyz':
        from ase.io.xyz import read_xyz
        return read_xyz(filename, index)

    if format == 'traj':
        from ase.io.trajectory import read_trajectory
        return read_trajectory(filename, index)

    if format == 'bundle':
        from ase.io.bundletrajectory import read_bundletrajectory
        return read_bundletrajectory(filename, index)

    if format == 'cube':
        from ase.io.cube import read_cube
        return read_cube(filename, index)

    if format == 'nc':
        from ase.io.netcdf import read_netcdf
        return read_netcdf(filename, index)

    if format == 'gpaw-text':
        from ase.io.gpawtext import read_gpaw_text
        return read_gpaw_text(filename, index)

    if format == 'dacapo-text':
        from ase.io.dacapo import read_dacapo_text
        return read_dacapo_text(filename)

    if format == 'dacapo':
        from ase.io.dacapo import read_dacapo
        return read_dacapo(filename)

    if format == 'xsf':
        from ase.io.xsf import read_xsf
        return read_xsf(filename, index)

    if format == 'vasp':
        from ase.io.vasp import read_vasp
        return read_vasp(filename)

    if format == 'vasp_out':
        from ase.io.vasp import read_vasp_out
        return read_vasp_out(filename, index)

    if format == 'abinit':
        from ase.io.abinit import read_abinit
        return read_abinit(filename)

    if format == 'v_sim':
        from ase.io.v_sim import read_v_sim
        return read_v_sim(filename)

    if format == 'mol':
        from ase.io.mol import read_mol
        return read_mol(filename)

    if format == 'pdb':
        from ase.io.pdb import read_pdb
        return read_pdb(filename, index)

    if format == 'cif':
        from ase.io.cif import read_cif
        return read_cif(filename, index)

    if format == 'struct':
        from ase.io.wien2k import read_struct
        return read_struct(filename)

    if format == 'struct_out':
        from ase.io.siesta import read_struct
        return read_struct(filename)

    if format == 'vti':
        from ase.io.vtkxml import read_vti
        return read_vti(filename)

    if format == 'vts':
        from ase.io.vtkxml import read_vts
        return read_vts(filename)

    if format == 'vtu':
        from ase.io.vtkxml import read_vtu
        return read_vtu(filename)

    if format == 'aims':
        from ase.io.aims import read_aims
        return read_aims(filename)

    if format == 'aims_out':
        from ase.io.aims import read_aims_output
        return read_aims_output(filename, index)

    if format == 'iwm':
        from ase.io.iwm import read_iwm
        return read_iwm(filename)

    if format == 'Cmdft':
        from ase.io.cmdft import read_I_info
        return read_I_info(filename)

    if format == 'tmol':
        from ase.io.turbomole import read_turbomole
        return read_turbomole(filename)

    if format == 'tmol-gradient':
        from ase.io.turbomole import read_turbomole_gradient
        return read_turbomole_gradient(filename)

    if format == 'cfg':
        from ase.io.cfg import read_cfg
        return read_cfg(filename)

    if format == 'dftb':
        from ase.io.dftb import read_dftb
        return read_dftb(filename)

    if format == 'sdf':
        from ase.io.sdf import read_sdf
        return read_sdf(filename)

    if format == 'etsf':
        from ase.io.etsf import ETSFReader
        return ETSFReader(filename).read_atoms()

    if format == 'gen':
        from ase.io.gen import read_gen
        return read_gen(filename)

    if format == 'db':
        from ase.io.cmr_io import read_db
        return read_db(filename, index)

    if format == 'lammps':
        from ase.io.lammps import read_lammps_dump
        return read_lammps_dump(filename, index)

    raise RuntimeError('File format descriptor '+format+' not recognized!')
#!/usr/bin/env python
# encoding=utf8

import sys
import numpy as np
from ase.io import vasp

# Assuming cubic cell !!!

filename = 'POSCAR'
if len(sys.argv) > 1:
    filename = sys.argv[1]

print "Checking",filename

v = vasp.read_vasp(filename)
r0 = v.get_scaled_positions()
a = v.get_cell()[0,0]

natoms = r0.shape[0]
print "Found",natoms,"atoms, lattice parameter is",a

# Shift all positions
x = r0[:,0]
minx = np.min(x[x>0])
invx = 1./minx
print "minx is",minx,"inverse is",invx
kvec = np.array((invx,0,0)) # invers av 1/(4s) der s er supercellestørrelsen

kvec = np.array((8,0,0)) # invers av 1/(4s) der s er supercellestørrelsen
Пример #38
0
#!/usr/bin/env python

import ase.io.vasp as io
from pyspglib import spglib
from optparse import OptionParser

parser = OptionParser()
parser.add_option("-f", "--file",
                  action="store", type="string", dest="file", default="POSCAR",
                  help="Path to input file [default: ./POSCAR]")
parser.add_option("-p", "--prec",
                  action="store", type="float", dest="prec", default=0.001,
                  help="Precision for symmetry test [default: 0.001]")
(options, args) = parser.parse_args()

bulk = io.read_vasp(options.file)
spacegroup = spglib.get_spacegroup(bulk, symprec=options.prec)

print "Spacegroup information."
print "-----------------------"
print spacegroup
print "-----------------------"
Пример #39
0
def read(filename, index=None, format=None):
    """Read Atoms object(s) from file.

    filename: str
        Name of the file to read from.
    index: int or slice
        If the file contains several configurations, the last configuration
        will be returned by default.  Use index=n to get configuration
        number n (counting from zero).
    format: str
        Used to specify the file-format.  If not given, the
        file-format will be guessed by the *filetype* function.

    Known formats:

    =========================  =============
    format                     short name
    =========================  =============
    GPAW restart-file          gpw
    Dacapo netCDF output file  dacapo
    Old ASE netCDF trajectory  nc
    Virtual Nano Lab file      vnl
    ASE pickle trajectory      traj
    ASE bundle trajectory      bundle
    GPAW text output           gpaw-text
    CUBE file                  cube
    XCrySDen Structure File    xsf
    Dacapo text output         dacapo-text
    XYZ-file                   xyz
    VASP POSCAR/CONTCAR file   vasp
    VASP OUTCAR file           vasp_out
    VASP XDATCAR file          vasp_xdatcar
    SIESTA STRUCT file         struct_out
    ABINIT input file          abinit
    V_Sim ascii file           v_sim
    Protein Data Bank          pdb
    CIF-file                   cif
    FHI-aims geometry file     aims
    FHI-aims output file       aims_out
    VTK XML Image Data         vti
    VTK XML Structured Grid    vts
    VTK XML Unstructured Grid  vtu
    TURBOMOLE coord file       tmol
    TURBOMOLE gradient file    tmol-gradient
    exciting input             exi
    AtomEye configuration      cfg
    WIEN2k structure file      struct
    DftbPlus input file        dftb
    CASTEP geom file           cell
    CASTEP output file         castep
    CASTEP trajectory file     geom
    ETSF format                etsf.nc
    DFTBPlus GEN format        gen
    CMR db/cmr-file            db
    CMR db/cmr-file            cmr
    LAMMPS dump file           lammps
    EON reactant.con file      eon
    Gromacs coordinates        gro
    Gaussian com (input) file  gaussian
    Gaussian output file       gaussian_out
    Quantum espresso in file   esp_in
    Quantum espresso out file  esp_out
    Extended XYZ file          extxyz
    NWChem input file          nw
    Materials Studio file      xsd
    =========================  =============

    Many formats allow on open file-like object to be passed instead
    of ``filename``. In this case the format cannot be auto-decected,
    so the ``format`` argument should be explicitly given.
    
    """
    if isinstance(filename, str) and (
        '.json@' in filename or
        '.db@' in filename or
        filename.startswith('pg://') and '@' in filename):
        filename, index = filename.rsplit('@', 1)
        if index.isdigit():
            index = int(index)
    else:
        if isinstance(filename, str):
            p = filename.rfind('@')
            if p != -1:
                try:
                    index = string2index(filename[p + 1:])
                except ValueError:
                    pass
                else:
                    filename = filename[:p]

        if isinstance(index, str):
            index = string2index(index)

    if format is None:
        format = filetype(filename)

    if format.startswith('gpw'):
        import gpaw
        r = gpaw.io.open(filename, 'r')
        positions = r.get('CartesianPositions') * Bohr
        numbers = r.get('AtomicNumbers')
        cell = r.get('UnitCell') * Bohr
        pbc = r.get('BoundaryConditions')
        tags = r.get('Tags')
        magmoms = r.get('MagneticMoments')
        energy = r.get('PotentialEnergy') * Hartree

        if r.has_array('CartesianForces'):
            forces = r.get('CartesianForces') * Hartree / Bohr
        else:
            forces = None

        atoms = Atoms(positions=positions,
                      numbers=numbers,
                      cell=cell,
                      pbc=pbc)
        if tags.any():
            atoms.set_tags(tags)

        if magmoms.any():
            atoms.set_initial_magnetic_moments(magmoms)
        else:
            magmoms = None

        atoms.calc = SinglePointDFTCalculator(atoms, energy=energy,
                                              forces=forces, magmoms=magmoms)
        kpts = []
        if r.has_array('IBZKPoints'):
            for w, kpt, eps_n, f_n in zip(r.get('IBZKPointWeights'),
                                          r.get('IBZKPoints'),
                                          r.get('Eigenvalues'),
                                          r.get('OccupationNumbers')):
                kpts.append(SinglePointKPoint(w, kpt[0], kpt[1],
                                              eps_n[0], f_n[0]))
        atoms.calc.kpts = kpts

        return atoms

    if format in ['json', 'db', 'postgresql']:
        if index == slice(None, None):
            index = None
        from ase.db.core import connect
        images = [row.toatoms()
                  for row in connect(filename, format).select(index)]
        if len(images) == 1:
            return images[0]
        else:
            return images

    if index is None:
        index = -1
        
    if format == 'castep':
        from ase.io.castep import read_castep
        return read_castep(filename, index)

    if format == 'castep_cell':
        import ase.io.castep
        return ase.io.castep.read_cell(filename, index)

    if format == 'castep_geom':
        import ase.io.castep
        return ase.io.castep.read_geom(filename, index)

    if format == 'exi':
        from ase.io.exciting import read_exciting
        return read_exciting(filename, index)

    if format in ['xyz', 'extxyz']:
        from ase.io.extxyz import read_xyz
        return read_xyz(filename, index)

    if format == 'traj':
        from ase.io.trajectory import read_trajectory
        return read_trajectory(filename, index)

    if format == 'trj':
        from ase.io.pickletrajectory import read_trajectory
        return read_trajectory(filename, index)

    if format == 'bundle':
        from ase.io.bundletrajectory import read_bundletrajectory
        return read_bundletrajectory(filename, index)

    if format == 'cube':
        from ase.io.cube import read_cube
        return read_cube(filename, index)

    if format == 'nc':
        from ase.io.netcdf import read_netcdf
        return read_netcdf(filename, index)

    if format == 'gpaw-text':
        from ase.io.gpawtext import read_gpaw_text
        return read_gpaw_text(filename, index)

    if format == 'dacapo-text':
        from ase.io.dacapo import read_dacapo_text
        return read_dacapo_text(filename)

    if format == 'dacapo':
        from ase.io.dacapo import read_dacapo
        return read_dacapo(filename)

    if format == 'xsf':
        from ase.io.xsf import read_xsf
        return read_xsf(filename, index)

    if format == 'vasp':
        from ase.io.vasp import read_vasp
        return read_vasp(filename)

    if format == 'vasp_out':
        from ase.io.vasp import read_vasp_out
        return read_vasp_out(filename, index)

    if format == 'vasp_xdatcar':
        from ase.io.vasp import read_vasp_xdatcar
        return read_vasp_xdatcar(filename, index)

    if format == 'abinit':
        from ase.io.abinit import read_abinit
        return read_abinit(filename)

    if format == 'v_sim':
        from ase.io.v_sim import read_v_sim
        return read_v_sim(filename)

    if format == 'mol':
        from ase.io.mol import read_mol
        return read_mol(filename)

    if format == 'pdb':
        from ase.io.pdb import read_pdb
        return read_pdb(filename, index)

    if format == 'cif':
        from ase.io.cif import read_cif
        return read_cif(filename, index)

    if format == 'struct':
        from ase.io.wien2k import read_struct
        return read_struct(filename)

    if format == 'struct_out':
        from ase.io.siesta import read_struct
        return read_struct(filename)

    if format == 'vti':
        from ase.io.vtkxml import read_vti
        return read_vti(filename)

    if format == 'vts':
        from ase.io.vtkxml import read_vts
        return read_vts(filename)

    if format == 'vtu':
        from ase.io.vtkxml import read_vtu
        return read_vtu(filename)

    if format == 'aims':
        from ase.io.aims import read_aims
        return read_aims(filename)

    if format == 'aims_out':
        from ase.io.aims import read_aims_output
        return read_aims_output(filename, index)

    if format == 'iwm':
        from ase.io.iwm import read_iwm
        return read_iwm(filename)

    if format == 'Cmdft':
        from ase.io.cmdft import read_I_info
        return read_I_info(filename)

    if format == 'tmol':
        from ase.io.turbomole import read_turbomole
        return read_turbomole(filename)

    if format == 'tmol-gradient':
        from ase.io.turbomole import read_turbomole_gradient
        return read_turbomole_gradient(filename)

    if format == 'cfg':
        from ase.io.cfg import read_cfg
        return read_cfg(filename)

    if format == 'dftb':
        from ase.io.dftb import read_dftb
        return read_dftb(filename)

    if format == 'sdf':
        from ase.io.sdf import read_sdf
        return read_sdf(filename)

    if format == 'etsf':
        from ase.io.etsf import ETSFReader
        return ETSFReader(filename).read_atoms()

    if format == 'gen':
        from ase.io.gen import read_gen
        return read_gen(filename)

    if format == 'cmr':
        from ase.io.cmr_io import read_db
        return read_db(filename, index)

    if format == 'lammps':
        from ase.io.lammpsrun import read_lammps_dump
        return read_lammps_dump(filename, index)

    if format == 'eon':
        from ase.io.eon import read_reactant_con
        return read_reactant_con(filename)

    if format == 'gromacs':
        from ase.io.gromacs import read_gromacs
        return read_gromacs(filename)

    if format == 'gaussian':
        from ase.io.gaussian import read_gaussian
        return read_gaussian(filename)

    if format == 'gaussian_out':
        from ase.io.gaussian import read_gaussian_out
        return read_gaussian_out(filename, index)

    if format == 'esp_in':
        from ase.io.espresso import read_espresso_in
        return read_espresso_in(filename)

    if format == 'esp_out':
        from ase.io.espresso import read_espresso_out
        return read_espresso_out(filename, index)

    if format == 'nw':
        from ase.io.nwchem import read_nwchem_input
        return read_nwchem_input(filename)

    if format == 'xsd':
        from ase.io.xsd import read_xsd
        return read_xsd(filename)

    raise RuntimeError('File format descriptor ' + format + ' not recognized!')
Пример #40
0
#!/usr/bin/env python
# -*- coding: utf-8; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- 
# vim:fenc=utf-8:et:sw=4:ts=4:sts=4:tw=0

from ase.io.vasp import read_vasp, write_vasp
atoms = read_vasp('POSCAR')
transvec = atoms.get_cell().diagonal() / -1.
atoms.translate(transvec)
supercell = atoms.repeat((3,3,3))
write_vasp('POSCAR.3',supercell)


 
# import numpy as np
# from oppvasp.vasp.parsers import PoscarParser
# 
# pp = PoscarParser('POSCAR')
# unit_pos = pp.get_positions( coordinates = 'direct' )
# unit_natoms = pos.shape[0]
# print "Num atoms:",num_atoms
# super_size = [2,2,2]
# natoms = np.prod(super_size)*num_atoms
# pos = np.array((natoms,3))
# pos[0:unit_natoms] = unit_pos
# 
# # add atoms in x dir:
# for i = range(unit_natoms):
#     for j = range(1,super_size[0]):
#         pos[unit_natoms+i*j] = pos[i]*[j,1,1]

# f = open('movie.xyz','w')