コード例 #1
0
def load_mols(dataset, path):
    if os.path.exists(path+"val_mol.xyz"):
        val_mols = aio.iread(path+"val_mol.xyz")
        pre_mols = aio.iread(path+"pre_mol.xyz")
        
        return list(val_mols), list(pre_mols)
    else:
        dataset = choose_set(dataset)
        net = Net(8)
        best_model = torch.load(path+"best_model.pth")
        net.load_state_dict(best_model["Model"])
        
        #Using CUDA if available
        device = torch.device("cuda:0" if torch.cuda.is_available()\
                                            else "cpu")
        print("Compute device: ")
        print(device)
        
        net.to(device)
        
        
        torch.manual_seed(42)
        train_set, test_set = torch.utils.data.random_split(dataset,
                                            [len(dataset)-167, 167]) 
        torch.manual_seed(np.random.randint(100000))
        
        
        loader = torch.utils.data.DataLoader(test_set,
                                             batch_size=1,
                                             num_workers=0,
                                             shuffle=False,
                                             collate_fn=collate_none)
    
        val_mols = []
        pre_mols = []
    
        for item in loader:
            try:
                tensors, atoms = item
                inputs, targets = tensors
            except TypeError:
                print("Molecule is too big")
                continue
            
            # Moving the tensors to device
            inputs, targets = inputs.to(device).float(),\
                              targets.to(device).long()
            
            outputs = net(inputs)
            pre_mols.append(atoms_reconstruction(outputs))
            val_mols.append(atoms[0])
            
        aio.write(path+"val_mol.xyz", val_mols)
        aio.write(path+"pre_mol.xyz", pre_mols)
        return val_mols, pre_mols
コード例 #2
0
ファイル: mode.py プロジェクト: seenivasanh/interphon
    def plot(self, out_folder='.', unit_cell='POSCAR', code_name='vasp'):
        try:
            from ase.io.trajectory import Trajectory
            from ase.io import read, iread
            from ase.visualize import view
        except ImportError:
            raise ImportError(
                "\nThe parent directory of ase package must be included in 'sys.path'"
            )

        if code_name == 'espresso':
            code_name = 'espresso-in'  # aims, espresso-in, vasp

        atom = read(unit_cell, format=code_name)
        _current_position_true = atom.positions.copy()[
            self.process.unit_cell.atom_true]
        _mass_weight = self.process.unit_cell.mass_true.reshape(
            (-1, 3)) / self.process.unit_cell.mass_true.max()
        for mode_ind in self.mode_inds:
            traj = Trajectory(
                out_folder + "/Trajectory_{0}.traj".format(mode_ind), 'w')
            for ind, x in enumerate(
                    np.linspace(0, 2 * np.pi, self.num_images, endpoint=False),
                    1):
                atom.positions[self.process.unit_cell.atom_true] = _current_position_true \
                    + np.sin(x) * self.mode[mode_ind, :].reshape((-1, 3)).real / np.sqrt(_mass_weight)
                traj.write(atom)
            traj.close()
            atoms = iread(out_folder + "/Trajectory_{0}.traj".format(mode_ind))
            view(atoms)
コード例 #3
0
def test_dlp3():
    cells = []
    cells.append(
        np.array([[23.9999973028, 0.0, 0.0], [0.0, 23.9999973028, 0.0],
                  [0.0, 0.0, 23.9999973028]]))
    cells.append(
        np.array([[23.9999947494, 0.0, 0.0], [0.0, 23.9999947494, 0.0],
                  [0.0, 0.0, 23.9999947494]]))
    cells.append(
        np.array([[23.9999911871, 0.0, 0.0], [0.0, 23.9999911871, 0.0],
                  [0.0, 0.0, 23.9999911871]]))

    traj = aseIO.read(fd3, format='dlp-history', index=slice(0, None))
    assert len(traj) == 3

    traj = aseIO.iread(fd3, format='dlp-history', index=slice(0, None))
    for i, frame in enumerate(traj):
        assert len(frame) == 4
        assert all(frame.symbols == 'OHHX')
        assert np.isclose(frame.get_cell(), cells[i]).all()

    symbols = frame.get_chemical_symbols()

    traj = iread_dlp_history(fd3, symbols)
    for i, frame in enumerate(traj):
        assert len(frame) == 4
        assert all(frame.symbols == 'OHHX')
        assert np.isclose(frame.get_cell(), cells[i]).all()
        assert frame.has('initial_charges')
コード例 #4
0
def test_dlp():

    cells = []
    cells.append(
        np.array([[23.01, -0.3943E-01, 0.4612E-01],
                  [-0.9486E-01, 22.98, 0.4551], [0.6568, 0.7694, 19.21]]))
    cells.append(
        np.array([[22.90, -0.3925E-01, 0.4591E-01],
                  [-0.9443E-01, 22.88, 0.4531], [0.6538, 0.7660, 19.12]]))
    cells.append(
        np.array([[22.73, -0.3896E-01, 0.4557E-01],
                  [-0.9374E-01, 22.71, 0.4497], [0.6490, 0.7603, 18.98]]))

    traj = aseIO.read(fd, format='dlp-history', index=slice(0, None))
    assert len(traj) == 3

    traj = aseIO.iread(fd, format='dlp-history', index=slice(0, None))
    for i, frame in enumerate(traj):
        assert len(frame) == 2
        assert all(frame.symbols == 'ONi')
        assert np.isclose(frame.get_cell(), cells[i]).all()

    symbols = frame.get_chemical_symbols()

    traj = iread_dlp_history(fd, symbols)
    for i, frame in enumerate(traj):
        assert len(frame) == 2
        assert all(frame.symbols == 'ONi')
        assert np.isclose(frame.get_cell(), cells[i]).all()
コード例 #5
0
def test_vasp_out(outcar):
    tol = 1e-6

    a1 = read(outcar, index=-1)
    assert isinstance(a1, Atoms)
    assert np.isclose(a1.get_potential_energy(force_consistent=True),
                      -68.22868532,
                      atol=tol)
    assert np.isclose(a1.get_potential_energy(force_consistent=False),
                      -68.23102426,
                      atol=tol)

    a2 = read(outcar, index=':')
    assert isinstance(a2, list)
    assert isinstance(a2[0], Atoms)
    assert len(a2) == 1

    gen = iread(outcar, index=':')
    assert inspect.isgenerator(gen)
    for fc in (True, False):
        for a3 in gen:
            assert isinstance(a3, Atoms)
            assert np.isclose(a3.get_potential_energy(force_consistent=fc),
                              a1.get_potential_energy(force_consistent=fc),
                              atol=tol)
コード例 #6
0
 def parse_loose_molecules(self, directory, energy_file):
     """
     Args:
         directory (str): Root directory of filetree of
             crystal/molecule data.
         energy_file: Dictionary of filename-value pairs.
     """
     libver = self.settings['libver']
     index = self.settings['index']
     form = self.settings['input_format']
     if form == '':
         form = None
     if os.path.isfile(self.output_name):
         self.combine_collated(self.output_name, add_to_output=False)
     else:
         self.entries = []
         self.sources = []
         self.m_count = 0
     m_count_start = int(self.m_count)
     with open(energy_file, 'r') as energy_handle:
         energy_text = energy_handle.read()
     energy_data = find_energy_in_text(energy_text, loose=True)
     with h5py.File(self.output_name, 'a', libver=libver) as h5f:
         for root, dirs, files in os.walk(directory):
             sorted_files = sorted(files)
             for filename in sorted_files[slice_from_str(index)]:
                 try:
                     molecules = iread(os.path.join(root, filename),
                                       format=form)
                 except (ValueError, IOError, IndexError):
                     continue
                 for molecule in molecules:
                     m_name = '{}.{}'.format(filename, self.m_count)
                     try:
                         path = 'molecules/{}'.format(m_name)
                         energy_val = energy_data[filename]
                         mol = CollatedMolecule()
                         mol.from_ase(molecule, self.sys_elements,
                                      self.element_order)
                         mol.set_energy(energy_val)
                         entry = mol.to_file(h5f, path)
                         self.entries.append(entry)
                         self.sources.append(filename)
                         self.m_count += 1
                         print('read',
                               self.m_count - m_count_start,
                               end='\r')
                     except KeyError:
                         print('no corresponding energy_data:', m_name)
                         continue
                     except AssertionError:
                         print('error in', m_name, end='\n\n')
                         traceback.print_exc()
                         continue
         self.update_system_details(h5f)
コード例 #7
0
def test_nomad(datadir):
    from ase.io import iread

    path = datadir / 'nomad-images.nomad-json'
    images = list(iread(path))
    assert len(images) == 3

    for atoms in images:
        assert all(atoms.pbc)
        assert (atoms.cell > 0).sum() == 3
        assert atoms.get_chemical_formula() == 'As24Sr32'
コード例 #8
0
def main():
    if not shutil.which("cp2k"):
        raise unittest.SkipTest('cp2k command not available')

    inp = """&MOTION
               &PRINT
                 &TRAJECTORY SILENT
                   FORMAT DCD_ALIGNED_CELL
                 &END TRAJECTORY
               &END PRINT
               &MD
                 STEPS 5
               &END MD
             &END MOTION
             &GLOBAL
               RUN_TYPE MD
             &END GLOBAL"""
    calc = CP2K(label='test_dcd', max_scf=1, inp=inp)
    h2 = molecule('H2', calculator=calc)
    h2.center(vacuum=2.0)
    h2.set_cell([10.0, 10.0, 10.0, 90.0, 90.0, 90.0])
    h2.set_pbc(True)
    energy = h2.get_potential_energy()
    assert not energy == None
    subprocess.call(['cp2k', '-i', 'test_dcd.inp', '-o', 'test_dcd.out'])
    h2_end = io.read('test_dcd-pos-1.dcd')
    assert (h2_end.symbols == 'X').all()
    traj = io.read('test_dcd-pos-1.dcd',
                   ref_atoms=h2,
                   index=slice(0, None),
                   aligned=True)
    ioITraj = io.iread('test_dcd-pos-1.dcd',
                       ref_atoms=h2,
                       index=slice(0, None),
                       aligned=True)

    with open('test_dcd-pos-1.dcd', 'rb') as f:
        itraj = iread_cp2k_dcd(f,
                               indices=slice(0, None),
                               ref_atoms=h2,
                               aligned=True)
        for i, iMol in enumerate(itraj):
            ioIMol = next(ioITraj)
            assert compare_atoms(iMol, traj[i]) == []
            assert compare_atoms(iMol, ioIMol) == []
            assert iMol.get_pbc().all()

    traj = io.read('test_dcd-pos-1.dcd', ref_atoms=h2, index=slice(0, None))
    pbc = [mol.get_pbc() for mol in traj]
    assert not np.any(pbc)
    print('passed test "CP2K_DCD"')
コード例 #9
0
    def upload(self, file: Path, extra_infos=None, store_calc=True):

        if isinstance(file, str):
            file = Path(file)

        extra_info = {}
        if extra_infos:
            for info in extra_infos:
                extra_info.update(extras.parser.parse(info))

        extra_info['filename'] = str(file)

        data = iread(str(file))
        self.push(data, extra_info, store_calc=store_calc)
コード例 #10
0
ファイル: test_nomad.py プロジェクト: martin-stoehr/ase-devel
def test_nomad():
    fname = 'nmd.test.nomad-json'
    with open(fname, 'w') as fd:
        fd.write(nomad_data)

    from ase.io import iread

    images = list(iread(fname))
    assert len(images) == 3

    for atoms in images:
        assert all(atoms.pbc)
        assert (atoms.cell > 0).sum() == 3
        assert atoms.get_chemical_formula() == 'As24Sr32'
コード例 #11
0
def read(filename, format='auto', log=None, emap=None, top=None, units='real'):
    from ase.io import iread
    if format == 'auto':
        if filename.endswith('.yml'):
            format = 'pinn'
        elif filename.endswith('.dump'):
            format = 'dump'
        elif filename.endswith('.trr'):
            format = 'trr'

    if format == 'pinn':
        ds = pinn_reader(filename)
    elif format == 'dump':
        ds = map(atoms2dict, iread(filename, units=units))
        if log is not None:
            update_energy = lambda struct, energy: dict(struct, e_data=energy)
            energies = read_lammps_log(log, units=units)
            ds = map(update_energy, ds, energies)
    elif format == 'trr':
        ds = read_trr(filename, top)
        if log is not None:
            update_energy = lambda struct, energy: dict(struct, e_data=energy)
            energies = read_gromacs_xvg(log)
            ds = map(update_energy, ds, energies)
    else:
        ds = map(atoms2dict, iread(filename))

    if emap is not None:
        emap = {
            int(s.split(':')[0]): int(s.split(':')[1])
            for s in emap.split(',')
        }
        map_elems = lambda data: dict(data,
                                      elems=[emap[e] for e in data['elems']])
        ds = map(map_elems, ds)
    return ds
コード例 #12
0
 def parse_molecules(self, filename, energy_file):
     """
     Args:
         filename (str): Filename of crystal/molecule data.
         energy_file: File with property values as floats.
     """
     libver = self.settings['libver']
     index = self.settings['index']
     keyword = self.settings['keyword']
     form = self.settings['input_format']
     if form == '':
         form = None
     if os.path.isfile(self.output_name):
         self.combine_collated(self.output_name, add_to_output=False)
     else:
         self.entries = []
         self.sources = []
         self.m_count = 0
     m_count_start = int(self.m_count)
     with open(energy_file, 'r') as energy_handle:
         energy_text = energy_handle.read()
     energy_data = find_energy_in_text(energy_text, keyword=keyword)
     with h5py.File(self.output_name, 'a', libver=libver) as h5f:
         molecules = iread(filename, format=form, index=index)
         for molecule in molecules:
             m_name = '{}.{}'.format(filename, self.m_count)
             try:
                 path = 'molecules/{}'.format(m_name)
                 energy_val = energy_data[self.m_count - m_count_start]
                 mol = CollatedMolecule()
                 mol.from_ase(molecule, self.sys_elements,
                              self.element_order)
                 mol.set_energy(energy_val)
                 entry = mol.to_file(h5f, path)
                 self.entries.append(entry)
                 self.m_count += 1
                 print('read', self.m_count - m_count_start, end='\r')
             except IndexError:
                 print('no corresponding energy_data:', m_name)
                 continue
             except AssertionError:
                 print('error in', m_name, end='\n\n')
                 traceback.print_exc()
                 continue
         self.sources.append(filename)
         self.update_system_details(h5f)
コード例 #13
0
def traj_fp_vasp(traj_file, work_path, chemical_symbol=None, index="::"):
    """
    Export VASP POSCAR files from trajectory.
    :param traj_file:
    :param work_path:
    :param chemical_symbol:
    :param index:
    :return:
    """
    stcs = iread(os.path.abspath(traj_file), index=index)
    os.makedirs(work_path, exist_ok=True)
    for i, j in enumerate(stcs):
        if chemical_symbol:
            j.set_chemical_symbols(chemical_symbol)
        task_path = os.path.join(work_path, f'task.{str(i).zfill(6)}')
        os.makedirs(task_path, exist_ok=True)
        write(os.path.join(task_path, 'POSCAR'), j, vasp5=True)
コード例 #14
0
    def plot(self, out_folder='.', unit_cell='POSCAR', code_name='vasp'):
        """
        Visualize phonon Mode using modules of the `Atomic Simulation Environment (ASE) <https://wiki.fysik.dtu.dk/ase/index.html>`_.

        :param out_folder: Folder path for **Trajectory.traj** to be stored, defaults to .
        :type out_folder: str
        :param unit_cell: Path of unit cell input file, defaults to POSCAR
        :type unit_cell: str
        :param code_name: Specification of the file-format by a DFT program, defaults to vasp
        :type code_name: str
        """
        try:
            from ase.io.trajectory import Trajectory
            from ase.io import read, iread
            from ase.visualize import view
        except ImportError:
            raise ImportError(
                "\nThe parent directory of ase package must be included in 'sys.path'"
            )

        if code_name == 'espresso':
            code_name = 'espresso-in'  # aims, espresso-in, vasp

        atom = read(unit_cell, format=code_name)
        _current_position_true = np.transpose(
            atom.positions.copy()[self.process.unit_cell.atom_true, :])
        _mass_weight = np.transpose(
            self.process.unit_cell.mass_true.reshape(
                (-1, 3))) / self.process.unit_cell.mass_true.max()
        for mode_ind in self.mode_inds:
            traj = Trajectory(
                out_folder + "/Trajectory_{0}.traj".format(mode_ind), 'w')
            for _, x in enumerate(
                    np.linspace(0, 2 * np.pi, self.num_images, endpoint=False),
                    1):
                atom.positions[self.process.unit_cell.atom_true, :] = \
                    np.transpose(_current_position_true + np.sin(x)
                                 * np.transpose(self.mode[mode_ind, :].reshape((-1, 3)).real) / np.sqrt(_mass_weight))
                # np.sin(x + np.dot(_q, _current_position_true))

                traj.write(atom)

            traj.close()
            atoms = iread(out_folder + "/Trajectory_{0}.traj".format(mode_ind))
            view(atoms)
コード例 #15
0
def test_dcd(factory, factories):
    # (Should the cp2k_main executable live on the cp2k factory?)
    exes = factories.executables

    cp2k_main = exes.get('cp2k_main')
    if cp2k_main is None:
        pytest.skip('Please define "cp2k_main" in testing executables.  '
                    'It should point to the main cp2k executable '
                    '(not the shell)')

    calc = factory.calc(label='test_dcd', max_scf=1, inp=inp)
    h2 = molecule('H2', calculator=calc)
    h2.center(vacuum=2.0)
    h2.set_pbc(True)
    energy = h2.get_potential_energy()
    assert energy is not None
    subprocess.check_call(
        [cp2k_main, '-i', 'test_dcd.inp', '-o', 'test_dcd.out'])
    h2_end = io.read('test_dcd-pos-1.dcd')
    assert (h2_end.symbols == 'X').all()
    traj = io.read('test_dcd-pos-1.dcd',
                   ref_atoms=h2,
                   index=slice(0, None),
                   aligned=True)
    ioITraj = io.iread('test_dcd-pos-1.dcd',
                       ref_atoms=h2,
                       index=slice(0, None),
                       aligned=True)

    with open('test_dcd-pos-1.dcd', 'rb') as fd:
        itraj = iread_cp2k_dcd(fd,
                               indices=slice(0, None),
                               ref_atoms=h2,
                               aligned=True)
        for i, iMol in enumerate(itraj):
            ioIMol = next(ioITraj)
            assert compare_atoms(iMol, traj[i]) == []
            assert compare_atoms(iMol, ioIMol) == []
            assert iMol.get_pbc().all()

    traj = io.read('test_dcd-pos-1.dcd', ref_atoms=h2, index=slice(0, None))
    pbc = [mol.get_pbc() for mol in traj]
    assert not np.any(pbc)
コード例 #16
0
def test_traj_bytesio():
    from ase.io import iread, write
    from ase.build import bulk
    from ase.collections import g2
    import io

    images = [bulk('Si') + bulk('Fe')] + list(g2)

    buf = io.BytesIO()
    write(buf, images, format='traj')
    txt = buf.getvalue()

    buf = io.BytesIO()
    buf.write(txt)
    buf.seek(0)

    images2 = list(iread(buf, format='traj'))

    for atoms1, atoms2 in zip(images, images2):
        assert atoms1 == atoms2
コード例 #17
0
def accSuccess(runs=30, directory="runs0", tolerance=5):  #Max spaghetti
    convergenceIndecies = []
    lengths = []
    for i in range(0, runs):
        try:
            structures = iread(directory + "/run" + str(i) +
                               "/structures.traj")
            energies = [
                structure.get_total_energy() for structure in structures
            ]
            lengths.append(len(energies))
        except:
            continue
        emin = np.amin(energies)
        relativeEnergies = [e - emin for e in energies]
        # convergenceEnergy = np.amin(relativeEnergies) #Den er naturligvis 0 for den valgte reference
        convergence = np.where(
            np.array(relativeEnergies) < tolerance, 1, 0
        )  #Skal have fundet en bedre reference, men denne virker i tilfælde, hvor problemet er garanteret konvergens. Eventuelt brug Emin fra baseCase som reference i CrapGrænsen.
        convergenceIndex = np.nonzero(convergence)
        convergenceIndecies.append(convergenceIndex[0][0])

    space = np.linspace(0, np.amin(lengths) - 1, np.amin(lengths))

    accSucces = []
    a = 0
    for index in space:
        for convindex in convergenceIndecies:
            if convindex == int(index):
                a += 1
        accSucces.append(a / len(convergenceIndecies))

    plt.plot(space, accSucces, color="black")
    plt.xlabel("Iterations")
    plt.ylabel("Accumulated Succes (%)")
    plt.show()


# accSuccess()
コード例 #18
0
def test_ioformat(format, atoms, catch_warnings):
    if format in ['proteindatabank', 'netcdftrajectory']:
        warnings.simplefilter('ignore', UserWarning)
        # netCDF4 uses np.bool which may cause warnings in new numpy.
        warnings.simplefilter('ignore', DeprecationWarning)

    if format == 'dlp4':
        atoms.pbc = (1, 1, 0)

    images = [atoms, atoms]

    io = ioformats[format]
    print('{0:20}{1}{2}{3}{4}'.format(format, ' R'[io.can_read],
                                      ' W'[io.can_write], '+1'[io.single],
                                      'SF'[io.acceptsfd]))
    fname1 = 'io-test.1.{}'.format(format)
    fname2 = 'io-test.2.{}'.format(format)
    if io.can_write:
        write(fname1, atoms, format=format)
        if not io.single:
            write(fname2, images, format=format)

        if io.can_read:
            for a in [read(fname1, format=format), read(fname1)]:
                check(a, atoms, format)

            if not io.single:
                if format in ['json', 'db']:
                    aa = read(fname2, index='id=1') + read(fname2,
                                                           index='id=2')
                else:
                    aa = [read(fname2), read(fname2, 0)]
                aa += read(fname2, ':')
                for a in iread(fname2, format=format):
                    aa.append(a)
                assert len(aa) == 6, aa
                for a in aa:
                    check(a, atoms, format)
コード例 #19
0
    def run(args, parser):

        files = [os.path.split(path)[1] for path in args.filenames]
        lmax = max([len(f) for f in files]) + 2

        print('file'.ljust(lmax) +
              'type   score     a      b      component counts')
        print('=' * lmax + '===============================================')

        merge = not args.no_merge

        # reading CIF files can produce a ton of distracting warnings
        with warnings.catch_warnings():
            warnings.filterwarnings('ignore')
            for path, f in zip(args.filenames, files):
                for atoms in iread(path):
                    result = analyze_dimensionality(atoms, merge=merge)
                    if not args.full:
                        result = result[:1]

                    for i, entry in enumerate(result):
                        dimtype = entry.dimtype.rjust(4)
                        score = '{:.3f}'.format(entry.score).ljust(5)
                        a = '{:.3f}'.format(entry.a).ljust(5)
                        b = '{:.3f}'.format(entry.b).ljust(5)
                        if i == 0:
                            name = f.ljust(lmax)
                        else:
                            name = ' ' * lmax

                        line = ('{}{}' + '   {}' * 4).format(
                            name, dimtype, score, a, b, entry.h)
                        print(line)

                    if args.full:
                        print()
コード例 #20
0
ファイル: oi.py プロジェクト: rchiechi/QuantumParse
    images = [atoms, atoms]

    io = get_ioformat(format)
    print('{0:20}{1}{2}{3}{4}'.format(format,
                                      ' R'[bool(io.read)],
                                      ' W'[bool(io.write)],
                                      '+1'[io.single],
                                      'SF'[io.acceptsfd]))
    fname1 = '{}/io-test.1.{}'.format(testdir, format)
    fname2 = '{}/io-test.2.{}'.format(testdir, format)
    if io.write:
        write(fname1, atoms, format=format)
        if not io.single:
            write(fname2, images, format=format)

        if io.read:
            for a in [read(fname1, format=format), read(fname1)]:
                check(a, atoms, format)

            if not io.single:
                if format in ['json', 'db']:
                    aa = read(fname2 + '@id=1') + read(fname2 + '@id=2')
                else:
                    aa = [read(fname2), read(fname2, 0)]
                aa += read(fname2, ':')
                for a in iread(fname2, format=format):
                    aa.append(a)
                assert len(aa) == 6, aa
                for a in aa:
                    check(a, atoms, format)
コード例 #21
0
def parse_images(data, format=None, **kwargs):
    """Parse string or bytes into list of atoms objects."""
    buf = BytesIO(data)
    images = list(iread(buf, format=format, **kwargs))
    return images
コード例 #22
0
ファイル: oi.py プロジェクト: btodac/ase
def test(format):
    if format in ['abinit', 'castep-cell', 'dftb', 'eon', 'gaussian']:
        # Someone should do something ...
        return

    if format in ['v-sim', 'mustem']:
        # Standalone test used as not compatible with 1D periodicity
        return

    if format in ['mustem']:
        # Standalone test used as specific arguments are required
        return

    if format in ['dmol-arc', 'dmol-car', 'dmol-incoor']:
        # We have a standalone dmol test
        return

    if format in ['gif', 'mp4']:
        # Complex dependencies; see animate.py test
        return

    if format in ['postgresql', 'trj', 'vti', 'vtu']:
        # Let's not worry about these.
        return

    if not matplotlib and format in ['eps', 'png']:
        return

    if not etree and format == 'exciting':
        return

    if not Scientific and format == 'etsf':
        return

    if not netCDF4 and format == 'netcdftrajectory':
        return

    atoms = get_atoms()

    if format == 'dlp4':
        atoms.pbc = (1, 1, 0)

    images = [atoms, atoms]

    io = get_ioformat(format)
    print('{0:20}{1}{2}{3}{4}'.format(format, ' R'[bool(io.read)],
                                      ' W'[bool(io.write)], '+1'[io.single],
                                      'SF'[io.acceptsfd]))
    fname1 = '{}/io-test.1.{}'.format(testdir, format)
    fname2 = '{}/io-test.2.{}'.format(testdir, format)
    if io.write:
        write(fname1, atoms, format=format)
        if not io.single:
            write(fname2, images, format=format)

        if io.read:
            for a in [read(fname1, format=format), read(fname1)]:
                check(a, atoms, format)

            if not io.single:
                if format in ['json', 'db']:
                    aa = read(fname2 + '@id=1') + read(fname2 + '@id=2')
                else:
                    aa = [read(fname2), read(fname2, 0)]
                aa += read(fname2, ':')
                for a in iread(fname2, format=format):
                    aa.append(a)
                assert len(aa) == 6, aa
                for a in aa:
                    check(a, atoms, format)
コード例 #23
0
def test_iread_path():
    path = Path('hello')
    iterator = iread(path)
    with pytest.raises(FileNotFoundError):
        next(iterator)
コード例 #24
0
            count = 1
        else:
            count += 1
    sc.append((psym, count))
    return sc


args = sys.argv
file = args[1]
tag = args[2]
dir = args[3]

os.makedirs(dir, exist_ok=True)
counter = 1

atoms = iread(file, index=':', format='xyz')

# file for make binary data step
with open("input_tag.dat", "w") as tagfile:
    for a in atoms:
        forces = a.get_forces()
        positions = a.get_positions()
        scaled_position = a.get_scaled_positions()
        energy = a.get_total_energy()
        natom = len(forces)
        tagfile.write(tag + str(natom) + "atoms" + "_" + str(counter) + "\n")
        xdatcar = dir + '/positions_' + tag + str(natom) + "atoms" + "_" + str(
            counter) + ".dat"
        with open(xdatcar, "w") as xdat:
            symbol_count = _symbol_count_from_symbols(a.get_chemical_symbols())
            label = ' '.join([s for s, _ in symbol_count])
コード例 #25
0
            if 'Total valence charge' in line:
                elm[lst_elm] = float(line.split()[-1])
            if 'mulliken: Atomic and Orbital Populations' in line:
                in_mulliken = True

                charge = []
            lo = True
            if in_mulliken and 'Species:' in line:
                chg_0 = elm[line.split()[-1]]
            try:
                test = int(line.split()[0])
            except ValueError:
                lo = False
            if in_mulliken and lo:
                x = line.split()[:2]
                x.append(chg_0)
                charge.append(x)
            if 'mulliken: Qtot =' in line:
                Qtot.append(float(line.split()[-1]))
                next(f)
                if 'mulliken' not in next(f):
                    in_mulliken = False
                    # append for each md steps
                    total_sets.append(np.array(charge, dtype='float'))

total = np.array(total_sets)

a = iread('siesta.AXSF')
for i, j in zip(a, total[1:]):
    i.set_initial_charges(j[:, 1] - j[:, 2])
    write('total_charges.xyz', i, append=True)
コード例 #26
0
final.positions[2:5] = initial.positions[[3, 4, 2]]
# Generate blank images.
images = [initial]
for i in range(9):
    images.append(initial.copy())
for image in images:
    image.calc = EMT()
images.append(final)

neb = NEB(images, climb=True)
neb.interpolate(method='idpp')  #idpp插值,设置初猜

# set calculator
for atoms in images:
    atoms.calc = EMT()
    atoms.get_potential_energy()

# Optimize:
py_fname = os.path.splitext(sys.argv[0])[0]
traj_fname = "{}.traj".format(py_fname)
log_fname = "{}.log".format(py_fname)
optimizer = FIRE(neb, trajectory=traj_fname, logfile=log_fname)
optimizer.run(fmax=0.04)

neb_result = list(iread(traj_fname))
for i in neb_result:
    #print(i.get_potential_energy())
    pass
neb_result = NEBTools(neb_result)
neb_result.plot_bands(True, True, label=py_fname)
print(neb_result.get_barrier(), neb_result.get_fmax())
コード例 #27
0
import matplotlib.pyplot as plt
from ase.io import iread

energies = []
distances = []

for atoms in iread('binding_curve.traj'):
    energies.append(atoms.get_potential_energy())
    distances.append(atoms.positions[1, 2] - atoms.positions[0, 2])

ax = plt.gca()
ax.plot(distances, energies)
ax.set_xlabel('Distance [Å]')
ax.set_ylabel('Total energy [eV]')
plt.show()
コード例 #28
0
ファイル: dlp.py プロジェクト: martin-stoehr/ase-devel
  7.7056E+00 -3.4445E+00  2.0241E+00
  2.4898E+00 -4.4453E+00  3.0289E+01
  2.8009E+04 -4.5827E+04  3.0655E+05
""")

cells = []
cells.append(np.array([[23.01, -0.3943E-01, 0.4612E-01], [-0.9486E-01, 22.98, 0.4551], [0.6568, 0.7694, 19.21]]))
cells.append(np.array([[22.90, -0.3925E-01, 0.4591E-01], [-0.9443E-01, 22.88, 0.4531], [0.6538, 0.7660, 19.12]]))
cells.append(np.array([[22.73, -0.3896E-01, 0.4557E-01], [-0.9374E-01, 22.71, 0.4497], [0.6490, 0.7603, 18.98]]))



traj = aseIO.read(fd, format='dlp-history', index=slice(0,None))
assert len(traj) == 3

traj = aseIO.iread(fd, format='dlp-history', index=slice(0,None))
for i, frame in enumerate(traj):
    assert len(frame) == 2
    assert frame[0].symbol == 'O'
    assert frame[1].symbol == 'Ni'
    assert np.isclose(frame.get_cell(),cells[i]).all()

symbols = frame.get_chemical_symbols()

traj = iread_dlp_history(fd, symbols)
for i, frame in enumerate(traj):
    assert len(frame) == 2
    assert frame[0].symbol == 'O'
    assert frame[1].symbol == 'Ni'
    assert np.isclose(frame.get_cell(),cells[i]).all()
コード例 #29
0
ファイル: nomad.py プロジェクト: shuchingou/ase
# Stripped (minimal) version of nomad entry with 3 images.
# The images are actually identical for some reason, but we want to be sure
# that they are extracted correctly.

nomad_data = """{"uri": "nmd://N9Jqc1y-Bzf7sI1R9qhyyyoIosJDs/C74RJltyQeM9_WFuJYO49AR4gKuJ2", "section_run": [{"name": "section_run", "uri": "nmd://N9Jqc1y-Bzf7sI1R9qhyyyoIosJDs/C74RJltyQeM9_WFuJYO49AR4gKuJ2/section_run/0c", "gIndex": 0, "section_system": [{"configuration_periodic_dimensions": [{"flatData": [true, true, true]}], "uri": "nmd://N9Jqc1y-Bzf7sI1R9qhyyyoIosJDs/C74RJltyQeM9_WFuJYO49AR4gKuJ2/section_run/0c/section_system/0c", "gIndex": 0, "lattice_vectors": {"flatData": [1.289082e-09, 0.0, 0.0, 0.0, 1.2238921e-09, 0.0, 0.0, 0.0, 1.103065e-09]}, "name": "section_system", "atom_positions": {"flatData": [1.8369957336276003e-10, 1.6999517355319901e-10, 0.0, 8.282405733627601e-10, 4.41950876446801e-10, 0.0, 4.6084142663724006e-10, 7.81941223553199e-10, 0.0, 1.1053824266372401e-09, 1.053896926446801e-09, 0.0, 6.44541e-10, 0.0, 1.2892214482885e-10, 0.0, 6.1194605e-10, 1.2892214482885e-10, 1.0605776359825801e-09, 1.98497527706708e-10, 2.5802171766295004e-10, 4.1603663598258003e-10, 4.13448522293292e-10, 2.5802171766295004e-10, 8.730453640174201e-10, 8.10443577706708e-10, 2.5802171766295004e-10, 2.2850436401742e-10, 1.025394572293292e-09, 2.5802171766295004e-10, 5.2517352791676e-10, 4.6602249641989005e-11, 5.515325e-10, 1.4685300778002002e-10, 1.66342369669381e-10, 5.515325e-10, 7.9139400778002e-10, 4.45603680330619e-10, 5.515325e-10, 1.1697145279167601e-09, 5.65343800358011e-10, 5.515325e-10, 1.1936747208324e-10, 6.58548299641989e-10, 5.515325e-10, 4.976879922199801e-10, 7.78288419669381e-10, 5.515325e-10, 1.14222899221998e-09, 1.057549730330619e-09, 5.515325e-10, 7.6390847208324e-10, 1.177289850358011e-09, 5.515325e-10, 1.0605776359825801e-09, 1.98497527706708e-10, 8.450432823370501e-10, 4.1603663598258003e-10, 4.13448522293292e-10, 8.450432823370501e-10, 8.730453640174201e-10, 8.10443577706708e-10, 8.450432823370501e-10, 2.2850436401742e-10, 1.025394572293292e-09, 8.450432823370501e-10, 6.44541e-10, 0.0, 9.7414285517115e-10, 0.0, 6.1194605e-10, 9.7414285517115e-10, 9.1056464993268e-10, 1.25465107864641e-10, 0.0, 5.4589940120358e-10, 2.7689366691594603e-10, 0.0, 1.19044040120358e-09, 3.35052383084054e-10, 0.0, 2.6602364993268e-10, 4.86480942135359e-10, 0.0, 1.0230583500673202e-09, 7.37411157864641e-10, 0.0, 9.864159879642e-11, 8.88839716915946e-10, 0.0, 7.431825987964201e-10, 9.469984330840542e-10, 0.0, 3.7851735006732003e-10, 1.098426992135359e-09, 0.0, 0.0, 0.0, 2.0246975378805e-10, 6.44541e-10, 6.1194605e-10, 2.0246975378805e-10, 3.4046283730566e-10, 1.17495575349518e-10, 3.040167815311e-10, 9.8500383730566e-10, 4.944504746504821e-10, 3.040167815311e-10, 3.0407816269434e-10, 7.29441625349518e-10, 3.040167815311e-10, 9.486191626943402e-10, 1.106396524650482e-09, 3.040167815311e-10, 7.3089033824148e-10, 2.12568186818173e-10, 3.5617527624000004e-10, 8.634933824148001e-11, 3.9937786318182705e-10, 3.5617527624000004e-10, 1.2027326617585201e-09, 8.24514236818173e-10, 3.5617527624000004e-10, 5.581916617585201e-10, 1.011323913181827e-09, 3.5617527624000004e-10, 1.11810587223036e-09, 1.51565512577295e-10, 5.515325e-10, 4.7356487223036e-10, 4.60380537422705e-10, 5.515325e-10, 8.155171277696401e-10, 7.63511562577295e-10, 5.515325e-10, 1.7097612776964e-10, 1.072326587422705e-09, 5.515325e-10, 7.3089033824148e-10, 2.12568186818173e-10, 7.468897237600001e-10, 8.634933824148001e-11, 3.9937786318182705e-10, 7.468897237600001e-10, 1.2027326617585201e-09, 8.24514236818173e-10, 7.468897237600001e-10, 5.581916617585201e-10, 1.011323913181827e-09, 7.468897237600001e-10, 3.4046283730566e-10, 1.17495575349518e-10, 7.990482184689e-10, 9.8500383730566e-10, 4.944504746504821e-10, 7.990482184689e-10, 3.0407816269434e-10, 7.29441625349518e-10, 7.990482184689e-10, 9.486191626943402e-10, 1.106396524650482e-09, 7.990482184689e-10, 0.0, 0.0, 9.005952462119501e-10, 6.44541e-10, 6.1194605e-10, 9.005952462119501e-10]}, "atom_species": [33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38]}, {"configuration_periodic_dimensions": [{"flatData": [true, true, true]}], "uri": "nmd://N9Jqc1y-Bzf7sI1R9qhyyyoIosJDs/C74RJltyQeM9_WFuJYO49AR4gKuJ2/section_run/0c/section_system/1c", "lattice_vectors": {"flatData": [1.289082e-09, 0.0, 0.0, 0.0, 1.2238921e-09, 0.0, 0.0, 0.0, 1.103065e-09]}, "gIndex": 1, "name": "section_system", "atom_positions": {"flatData": [1.8369957336276003e-10, 1.6999517355319901e-10, 0.0, 8.282405733627601e-10, 4.41950876446801e-10, 0.0, 4.6084142663724006e-10, 7.81941223553199e-10, 0.0, 1.1053824266372401e-09, 1.053896926446801e-09, 0.0, 6.44541e-10, 0.0, 1.2892214482885e-10, 0.0, 6.1194605e-10, 1.2892214482885e-10, 1.0605776359825801e-09, 1.98497527706708e-10, 2.5802171766295004e-10, 4.1603663598258003e-10, 4.13448522293292e-10, 2.5802171766295004e-10, 8.730453640174201e-10, 8.10443577706708e-10, 2.5802171766295004e-10, 2.2850436401742e-10, 1.025394572293292e-09, 2.5802171766295004e-10, 5.2517352791676e-10, 4.6602249641989005e-11, 5.515325e-10, 1.4685300778002002e-10, 1.66342369669381e-10, 5.515325e-10, 7.9139400778002e-10, 4.45603680330619e-10, 5.515325e-10, 1.1697145279167601e-09, 5.65343800358011e-10, 5.515325e-10, 1.1936747208324e-10, 6.58548299641989e-10, 5.515325e-10, 4.976879922199801e-10, 7.78288419669381e-10, 5.515325e-10, 1.14222899221998e-09, 1.057549730330619e-09, 5.515325e-10, 7.6390847208324e-10, 1.177289850358011e-09, 5.515325e-10, 1.0605776359825801e-09, 1.98497527706708e-10, 8.450432823370501e-10, 4.1603663598258003e-10, 4.13448522293292e-10, 8.450432823370501e-10, 8.730453640174201e-10, 8.10443577706708e-10, 8.450432823370501e-10, 2.2850436401742e-10, 1.025394572293292e-09, 8.450432823370501e-10, 6.44541e-10, 0.0, 9.7414285517115e-10, 0.0, 6.1194605e-10, 9.7414285517115e-10, 9.1056464993268e-10, 1.25465107864641e-10, 0.0, 5.4589940120358e-10, 2.7689366691594603e-10, 0.0, 1.19044040120358e-09, 3.35052383084054e-10, 0.0, 2.6602364993268e-10, 4.86480942135359e-10, 0.0, 1.0230583500673202e-09, 7.37411157864641e-10, 0.0, 9.864159879642e-11, 8.88839716915946e-10, 0.0, 7.431825987964201e-10, 9.469984330840542e-10, 0.0, 3.7851735006732003e-10, 1.098426992135359e-09, 0.0, 0.0, 0.0, 2.0246975378805e-10, 6.44541e-10, 6.1194605e-10, 2.0246975378805e-10, 3.4046283730566e-10, 1.17495575349518e-10, 3.040167815311e-10, 9.8500383730566e-10, 4.944504746504821e-10, 3.040167815311e-10, 3.0407816269434e-10, 7.29441625349518e-10, 3.040167815311e-10, 9.486191626943402e-10, 1.106396524650482e-09, 3.040167815311e-10, 7.3089033824148e-10, 2.12568186818173e-10, 3.5617527624000004e-10, 8.634933824148001e-11, 3.9937786318182705e-10, 3.5617527624000004e-10, 1.2027326617585201e-09, 8.24514236818173e-10, 3.5617527624000004e-10, 5.581916617585201e-10, 1.011323913181827e-09, 3.5617527624000004e-10, 1.11810587223036e-09, 1.51565512577295e-10, 5.515325e-10, 4.7356487223036e-10, 4.60380537422705e-10, 5.515325e-10, 8.155171277696401e-10, 7.63511562577295e-10, 5.515325e-10, 1.7097612776964e-10, 1.072326587422705e-09, 5.515325e-10, 7.3089033824148e-10, 2.12568186818173e-10, 7.468897237600001e-10, 8.634933824148001e-11, 3.9937786318182705e-10, 7.468897237600001e-10, 1.2027326617585201e-09, 8.24514236818173e-10, 7.468897237600001e-10, 5.581916617585201e-10, 1.011323913181827e-09, 7.468897237600001e-10, 3.4046283730566e-10, 1.17495575349518e-10, 7.990482184689e-10, 9.8500383730566e-10, 4.944504746504821e-10, 7.990482184689e-10, 3.0407816269434e-10, 7.29441625349518e-10, 7.990482184689e-10, 9.486191626943402e-10, 1.106396524650482e-09, 7.990482184689e-10, 0.0, 0.0, 9.005952462119501e-10, 6.44541e-10, 6.1194605e-10, 9.005952462119501e-10]}, "atom_species": [33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38]}, {"configuration_periodic_dimensions": [{"flatData": [true, true, true]}], "uri": "nmd://N9Jqc1y-Bzf7sI1R9qhyyyoIosJDs/C74RJltyQeM9_WFuJYO49AR4gKuJ2/section_run/0c/section_system/2c", "gIndex": 2, "lattice_vectors": {"flatData": [1.289082e-09, 0.0, 0.0, 0.0, 1.2238921e-09, 0.0, 0.0, 0.0, 1.103065e-09]}, "name": "section_system", "atom_positions": {"flatData": [1.8369957336276003e-10, 1.6999517355319901e-10, 0.0, 8.282405733627601e-10, 4.41950876446801e-10, 0.0, 4.6084142663724006e-10, 7.81941223553199e-10, 0.0, 1.1053824266372401e-09, 1.053896926446801e-09, 0.0, 6.44541e-10, 0.0, 1.2892214482885e-10, 0.0, 6.1194605e-10, 1.2892214482885e-10, 1.0605776359825801e-09, 1.98497527706708e-10, 2.5802171766295004e-10, 4.1603663598258003e-10, 4.13448522293292e-10, 2.5802171766295004e-10, 8.730453640174201e-10, 8.10443577706708e-10, 2.5802171766295004e-10, 2.2850436401742e-10, 1.025394572293292e-09, 2.5802171766295004e-10, 5.2517352791676e-10, 4.6602249641989005e-11, 5.515325e-10, 1.4685300778002002e-10, 1.66342369669381e-10, 5.515325e-10, 7.9139400778002e-10, 4.45603680330619e-10, 5.515325e-10, 1.1697145279167601e-09, 5.65343800358011e-10, 5.515325e-10, 1.1936747208324e-10, 6.58548299641989e-10, 5.515325e-10, 4.976879922199801e-10, 7.78288419669381e-10, 5.515325e-10, 1.14222899221998e-09, 1.057549730330619e-09, 5.515325e-10, 7.6390847208324e-10, 1.177289850358011e-09, 5.515325e-10, 1.0605776359825801e-09, 1.98497527706708e-10, 8.450432823370501e-10, 4.1603663598258003e-10, 4.13448522293292e-10, 8.450432823370501e-10, 8.730453640174201e-10, 8.10443577706708e-10, 8.450432823370501e-10, 2.2850436401742e-10, 1.025394572293292e-09, 8.450432823370501e-10, 6.44541e-10, 0.0, 9.7414285517115e-10, 0.0, 6.1194605e-10, 9.7414285517115e-10, 9.1056464993268e-10, 1.25465107864641e-10, 0.0, 5.4589940120358e-10, 2.7689366691594603e-10, 0.0, 1.19044040120358e-09, 3.35052383084054e-10, 0.0, 2.6602364993268e-10, 4.86480942135359e-10, 0.0, 1.0230583500673202e-09, 7.37411157864641e-10, 0.0, 9.864159879642e-11, 8.88839716915946e-10, 0.0, 7.431825987964201e-10, 9.469984330840542e-10, 0.0, 3.7851735006732003e-10, 1.098426992135359e-09, 0.0, 0.0, 0.0, 2.0246975378805e-10, 6.44541e-10, 6.1194605e-10, 2.0246975378805e-10, 3.4046283730566e-10, 1.17495575349518e-10, 3.040167815311e-10, 9.8500383730566e-10, 4.944504746504821e-10, 3.040167815311e-10, 3.0407816269434e-10, 7.29441625349518e-10, 3.040167815311e-10, 9.486191626943402e-10, 1.106396524650482e-09, 3.040167815311e-10, 7.3089033824148e-10, 2.12568186818173e-10, 3.5617527624000004e-10, 8.634933824148001e-11, 3.9937786318182705e-10, 3.5617527624000004e-10, 1.2027326617585201e-09, 8.24514236818173e-10, 3.5617527624000004e-10, 5.581916617585201e-10, 1.011323913181827e-09, 3.5617527624000004e-10, 1.11810587223036e-09, 1.51565512577295e-10, 5.515325e-10, 4.7356487223036e-10, 4.60380537422705e-10, 5.515325e-10, 8.155171277696401e-10, 7.63511562577295e-10, 5.515325e-10, 1.7097612776964e-10, 1.072326587422705e-09, 5.515325e-10, 7.3089033824148e-10, 2.12568186818173e-10, 7.468897237600001e-10, 8.634933824148001e-11, 3.9937786318182705e-10, 7.468897237600001e-10, 1.2027326617585201e-09, 8.24514236818173e-10, 7.468897237600001e-10, 5.581916617585201e-10, 1.011323913181827e-09, 7.468897237600001e-10, 3.4046283730566e-10, 1.17495575349518e-10, 7.990482184689e-10, 9.8500383730566e-10, 4.944504746504821e-10, 7.990482184689e-10, 3.0407816269434e-10, 7.29441625349518e-10, 7.990482184689e-10, 9.486191626943402e-10, 1.106396524650482e-09, 7.990482184689e-10, 0.0, 0.0, 9.005952462119501e-10, 6.44541e-10, 6.1194605e-10, 9.005952462119501e-10]}, "atom_species": [33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38]}]}], "name": "calculation_context"}"""

fname = 'nmd.test.nomad-json'
with open(fname, 'w') as fd:
    fd.write(nomad_data)

from ase.io import iread

images = list(iread(fname))
assert len(images) == 3

for atoms in images:
    assert all(atoms.pbc)
    assert (atoms.cell > 0).sum() == 3
    assert atoms.get_chemical_formula() == 'As24Sr32'


# Code for cleaning up nomad files so their size is reasonable for inclusion
# in test suite:
"""
ourkeys = {'section_run', 'section_system', 'name', 'atom_species',
           'atom_positions', 'flatData', 'uri', 'gIndex',
           'configuration_periodic_dimensions', 'lattice_vectors'}

includekeys = lambda k: k in ourkeys

fname = ...
コード例 #30
0
ファイル: vasp_xml2traj.py プロジェクト: ErpanArkin/my_pylib
#!/usr/bin/env python3

from ase.io import iread,write
import sys

if len(sys.argv) > 1:
    intv =  int(sys.argv[1]) # output every intv steps
    fname = sys.argv[2]
else:
    intv = 1
    fname = 'vasprun1.xml'

a = iread(fname)

for i,j in enumerate(a):
    if i % intv == 0:
        write('XDATCAR.xyz',j,append=True)
コード例 #31
0
#!/usr/bin/env python3
'''
This is a script to plot temperature, energies, pressure, lattice constants
as a function of vasp md steps. This requires XDATCAR, vasprun.xml, OSZICAR
files. This is for single md run, use vasp_md_total.py for multiple runs.
'''

import numpy as np
import matplotlib.pyplot as plt
import os.path
from ase.io import iread

# read vasprun.xml with ase.io.iread
a = iread('vasprun.xml')
latc = []
vol = []
pres = []  # this pressure is not correct for md
for i in a:
    latc.append(i.get_cell_lengths_and_angles())
    vol.append(i.get_volume())
    pres.append(i.get_stress())

# pressure includes kinetic contribution, obatained by following bash command
# LC_ALL=C fgrep  "Total+kin" OUTCAR > total+kin.dat
if os.path.exists('total+kin.dat'):
    pres = []
    with open('total+kin.dat', 'r') as f:
        lines = f.readlines()
    for i, j in enumerate(lines):
        x = [float(y) for y in j.split()[1:]]
        x.insert(0, i)