Beispiel #1
0
    def write_input_files(self, at, label):
        write_xyz(os.path.join(self.subdir, 'atoms.%d.xyz' % self.client_id), at)

        # copy in parameter files
        if self.param_files is not None:
            for param_file in self.param_files:
                param_file_basename = os.path.basename(param_file)
                shutil.copyfile(param_file, os.path.join(self.subdir, param_file_basename))
Beispiel #2
0
def pack_atoms_to_xyz_str(at, label):
    at.info['label'] = label
    buffer = StringIO.StringIO()
    write_xyz(buffer, at)
    data = str(buffer)
    buffer.close()    
    # preceed message by its length
    data_length = ('%8d' % len(data)).encode('ascii')
    data = data_length + data.encode('ascii')
    return data
Beispiel #3
0
    def from_ase(cls, atoms, *args: str):
        """Loading ASE Atoms object by using extXYZ as an intermediate data format."""

        from io import StringIO
        from ase.io.extxyz import write_xyz

        with StringIO() as f:
            write_xyz(f, atoms)
            xyz_str = f.getvalue()

        return cls.from_str(xyz_str, *args)
Beispiel #4
0
def write(filename, images, format=None, **kwargs):
    """Write Atoms object(s) to file.

    filename: str
        Name of the file to write to.
    images: Atoms object or list of Atoms objects
        A single Atoms object or a list of Atoms objects.
    format: str
        Used to specify the file-format.  If not given, the
        file-format will be taken from suffix of the filename.

    The accepted output formats:

    =========================  ===========
    format                     short name
    =========================  ===========
    ASE pickle trajectory      traj
    ASE bundle trajectory      bundle
    CUBE file                  cube
    XYZ-file                   xyz
    VASP POSCAR/CONTCAR file   vasp
    ABINIT input file          abinit
    Protein Data Bank          pdb
    CIF-file                   cif
    XCrySDen Structure File    xsf
    FHI-aims geometry file     aims
    gOpenMol .plt file         plt
    Python script              py
    Encapsulated Postscript    eps
    Portable Network Graphics  png
    Persistance of Vision      pov
    VTK XML Image Data         vti
    VTK XML Structured Grid    vts
    VTK XML Unstructured Grid  vtu
    TURBOMOLE coord file       tmol
    exciting                   exi
    AtomEye configuration      cfg
    WIEN2k structure file      struct
    CASTEP cell file           cell
    DftbPlus input file        dftb
    ETSF                       etsf.nc
    DFTBPlus GEN format        gen
    CMR db/cmr-file            db
    CMR db/cmr-file            cmr
    EON reactant.con file      eon
    Gromacs coordinates        gro
    GROMOS96 (only positions)  g96
    X3D                        x3d
    X3DOM HTML                 html
    Extended XYZ file          extxyz
    =========================  ===========

    The use of additional keywords is format specific.

    The ``cube`` and ``plt`` formats accept (plt requires it) a ``data``
    keyword, which can be used to write a 3D array to the file along
    with the nuclei coordinates.

    The ``vti``, ``vts`` and ``vtu`` formats are all specifically directed
    for use with MayaVi, and the latter is designated for visualization of
    the atoms whereas the two others are intended for volume data. Further,
    it should be noted that the ``vti`` format is intended for orthogonal
    unit cells as only the grid-spacing is stored, whereas the ``vts`` format
    additionally stores the coordinates of each grid point, thus making it
    useful for volume date in more general unit cells.

    The ``eps``, ``png``, and ``pov`` formats are all graphics formats,
    and accept the additional keywords:

    rotation: str (default '')
      The rotation angles, e.g. '45x,70y,90z'.

    show_unit_cell: int (default 0)
      Can be 0, 1, 2 to either not show, show, or show all of the unit cell.

    radii: array or float (default 1.0)
      An array of same length as the list of atoms indicating the sphere radii.
      A single float specifies a uniform scaling of the default covalent radii.

    bbox: 4 floats (default None)
      Set the bounding box to (xll, yll, xur, yur) (lower left, upper right).

    colors: array (default None)
      An array of same length as the list of atoms, indicating the rgb color
      code for each atom. Default is the jmol_colors of ase/data/colors.

    scale: int (default 20)
      Number of pixels per Angstrom.

    For the ``pov`` graphics format, ``scale`` should not be specified.
    The elements of the color array can additionally be strings, or 4
    and 5 vectors for named colors, rgb + filter, and rgb + filter + transmit
    specification. This format accepts the additional keywords:

    ``run_povray``, ``display``, ``pause``, ``transparent``,
    ``canvas_width``, ``canvas_height``, ``camera_dist``,
    ``image_plane``, ``camera_type``, ``point_lights``,
    ``area_light``, ``background``, ``textures``, ``celllinewidth``,
    ``bondlinewidth``, ``bondatoms``

    The ``xyz`` format accepts a comment string using the ``comment`` keyword:

    comment: str (default '')
      Optional comment written on the second line of the file.
    """

    if format is None:
        if filename == '-':
            format = 'xyz'
            filename = sys.stdout
        elif 'POSCAR' in filename or 'CONTCAR' in filename:
            format = 'vasp'
        elif 'OUTCAR' in filename:
            format = 'vasp_out'
        elif filename.endswith('etsf.nc'):
            format = 'etsf'
        elif filename.lower().endswith('.con'):
            format = 'eon'
        elif os.path.basename(filename) == 'coord':
            format = 'tmol'
        else:
            suffix = filename.split('.')[-1]
            format = {
                'cell': 'castep_cell',
            }.get(suffix, suffix)  # XXX this does not make sense
            # Maybe like this:


##             format = {'traj': 'trajectory',
##                       'nc': 'netcdf',
##                       'exi': 'exciting',
##                       'in': 'aims',
##                       'tmol': 'turbomole',
##                       }.get(suffix, suffix)

    if format in ['json', 'db']:
        from ase.db import connect
        connect(filename, format).write(images)
        return
    if format == 'castep_cell':
        from ase.io.castep import write_cell
        write_cell(filename, images, **kwargs)
        return
    if format == 'exi':
        from ase.io.exciting import write_exciting
        write_exciting(filename, images)
        return
    if format == 'cif':
        from ase.io.cif import write_cif
        write_cif(filename, images)
    if format == 'xyz':
        from ase.io.extxyz import write_xyz
        write_xyz(filename,
                  images,
                  columns=['symbols', 'positions'],
                  write_info=False,
                  **kwargs)
        return
    if format == 'extxyz':
        from ase.io.extxyz import write_xyz
        write_xyz(filename, images, **kwargs)
        return
    if format == 'gen':
        from ase.io.gen import write_gen
        write_gen(filename, images)
        return
    elif format == 'in':
        format = 'aims'
    elif format == 'tmol':
        from ase.io.turbomole import write_turbomole
        write_turbomole(filename, images)
        return
    elif format == 'dftb':
        from ase.io.dftb import write_dftb
        write_dftb(filename, images)
        return
    elif format == 'struct':
        from ase.io.wien2k import write_struct
        write_struct(filename, images, **kwargs)
        return
    elif format == 'findsym':
        from ase.io.findsym import write_findsym
        write_findsym(filename, images)
        return
    elif format == 'etsf':
        from ase.io.etsf import ETSFWriter
        writer = ETSFWriter(filename)
        if not isinstance(images, (list, tuple)):
            images = [images]
        writer.write_atoms(images[0])
        writer.close()
        return
    elif format == 'cmr':
        from ase.io.cmr_io import write_db
        return write_db(filename, images, **kwargs)
    elif format == 'eon':
        from ase.io.eon import write_reactant_con
        write_reactant_con(filename, images)
        return
    elif format == 'gro':
        from ase.io.gromacs import write_gromacs
        write_gromacs(filename, images)
        return
    elif format == 'g96':
        from ase.io.gromos import write_gromos
        write_gromos(filename, images)
        return
    elif format == 'html':
        from ase.io.x3d import write_html
        write_html(filename, images)
        return

    format = {
        'traj': 'trajectory',
        'nc': 'netcdf',
        'bundle': 'bundletrajectory'
    }.get(format, format)
    name = 'write_' + format

    if format in ['vti', 'vts', 'vtu']:
        format = 'vtkxml'

    if format is None:
        format = filetype(filename)

    try:
        write = getattr(__import__('ase.io.%s' % format, {}, {}, [name]), name)
    except ImportError:
        raise TypeError('Unknown format: "%s".' % format)

    write(filename, images, **kwargs)
Beispiel #5
0
def write(filename, images, format=None, **kwargs):
    """Write Atoms object(s) to file.

    filename: str
        Name of the file to write to.
    images: Atoms object or list of Atoms objects
        A single Atoms object or a list of Atoms objects.
    format: str
        Used to specify the file-format.  If not given, the
        file-format will be taken from suffix of the filename.

    The accepted output formats:

    =========================  ===========
    format                     short name
    =========================  ===========
    ASE pickle trajectory      traj
    ASE bundle trajectory      bundle
    CUBE file                  cube
    XYZ-file                   xyz
    VASP POSCAR/CONTCAR file   vasp
    ABINIT input file          abinit
    Protein Data Bank          pdb
    CIF-file                   cif
    XCrySDen Structure File    xsf
    FHI-aims geometry file     aims
    gOpenMol .plt file         plt
    Python script              py
    Encapsulated Postscript    eps
    Portable Network Graphics  png
    Persistance of Vision      pov
    VTK XML Image Data         vti
    VTK XML Structured Grid    vts
    VTK XML Unstructured Grid  vtu
    TURBOMOLE coord file       tmol
    exciting                   exi
    AtomEye configuration      cfg
    WIEN2k structure file      struct
    CASTEP cell file           cell
    DftbPlus input file        dftb
    ETSF                       etsf.nc
    DFTBPlus GEN format        gen
    CMR db/cmr-file            db
    CMR db/cmr-file            cmr
    EON reactant.con file      eon
    Gromacs coordinates        gro
    GROMOS96 (only positions)  g96
    X3D                        x3d
    X3DOM HTML                 html
    Extended XYZ file          extxyz
    =========================  ===========

    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.

    The use of additional keywords is format specific.

    The ``cube`` and ``plt`` formats accept (plt requires it) a ``data``
    keyword, which can be used to write a 3D array to the file along
    with the nuclei coordinates.

    The ``vti``, ``vts`` and ``vtu`` formats are all specifically directed
    for use with MayaVi, and the latter is designated for visualization of
    the atoms whereas the two others are intended for volume data. Further,
    it should be noted that the ``vti`` format is intended for orthogonal
    unit cells as only the grid-spacing is stored, whereas the ``vts`` format
    additionally stores the coordinates of each grid point, thus making it
    useful for volume date in more general unit cells.

    The ``eps``, ``png``, and ``pov`` formats are all graphics formats,
    and accept the additional keywords:

    rotation: str (default '')
      The rotation angles, e.g. '45x,70y,90z'.

    show_unit_cell: int (default 0)
      Can be 0, 1, 2 to either not show, show, or show all of the unit cell.

    radii: array or float (default 1.0)
      An array of same length as the list of atoms indicating the sphere radii.
      A single float specifies a uniform scaling of the default covalent radii.

    bbox: 4 floats (default None)
      Set the bounding box to (xll, yll, xur, yur) (lower left, upper right).

    colors: array (default None)
      An array of same length as the list of atoms, indicating the rgb color
      code for each atom. Default is the jmol_colors of ase/data/colors.

    scale: int (default 20)
      Number of pixels per Angstrom.

    For the ``pov`` graphics format, ``scale`` should not be specified.
    The elements of the color array can additionally be strings, or 4
    and 5 vectors for named colors, rgb + filter, and rgb + filter + transmit
    specification. This format accepts the additional keywords:

    ``run_povray``, ``display``, ``pause``, ``transparent``,
    ``canvas_width``, ``canvas_height``, ``camera_dist``,
    ``image_plane``, ``camera_type``, ``point_lights``,
    ``area_light``, ``background``, ``textures``, ``celllinewidth``,
    ``bondlinewidth``, ``bondatoms``

    The ``xyz`` format accepts a comment string using the ``comment`` keyword:

    comment: str (default '')
      Optional comment written on the second line of the file.
    """

    if format is None:
        if filename == '-':
            format = 'xyz'
            filename = sys.stdout
        elif 'POSCAR' in filename or 'CONTCAR' in filename:
            format = 'vasp'
        elif 'OUTCAR' in filename:
            format = 'vasp_out'
        elif filename.endswith('etsf.nc'):
            format = 'etsf'
        elif filename.lower().endswith('.con'):
            format = 'eon'
        elif os.path.basename(filename) == 'coord':
            format = 'tmol'
        else:
            suffix = filename.split('.')[-1]
            format = {'cell': 'castep_cell',
                      }.get(suffix, suffix)  # XXX this does not make sense
            # Maybe like this:
##             format = {'traj': 'trajectory',
##                       'nc': 'netcdf',
##                       'exi': 'exciting',
##                       'in': 'aims',
##                       'tmol': 'turbomole',
##                       }.get(suffix, suffix)
            
    if format in ['json', 'db']:
        from ase.db import connect
        connect(filename, format).write(images)
        return
    if format == 'castep_cell':
        from ase.io.castep import write_cell
        write_cell(filename, images, **kwargs)
        return
    if format == 'exi':
        from ase.io.exciting import write_exciting
        write_exciting(filename, images)
        return
    if format == 'cif':
        from ase.io.cif import write_cif
        write_cif(filename, images)
    if format == 'xyz':
        from ase.io.extxyz import write_xyz
        write_xyz(filename, images, columns=['symbols', 'positions'],
                  write_info=False, write_results=False, **kwargs)
        return
    if format == 'extxyz':
        from ase.io.extxyz import write_xyz
        write_xyz(filename, images, **kwargs)
        return
    if format == 'gen':
        from ase.io.gen import write_gen
        write_gen(filename, images)
        return
    elif format == 'in':
        format = 'aims'
    elif format == 'tmol':
        from ase.io.turbomole import write_turbomole
        write_turbomole(filename, images)
        return
    elif format == 'dftb':
        from ase.io.dftb import write_dftb
        write_dftb(filename, images)
        return
    elif format == 'struct':
        from ase.io.wien2k import write_struct
        write_struct(filename, images, **kwargs)
        return
    elif format == 'findsym':
        from ase.io.findsym import write_findsym
        write_findsym(filename, images)
        return
    elif format == 'etsf':
        from ase.io.etsf import ETSFWriter
        writer = ETSFWriter(filename)
        if not isinstance(images, (list, tuple)):
            images = [images]
        writer.write_atoms(images[0])
        writer.close()
        return
    elif format == 'cmr':
        from ase.io.cmr_io import write_db
        return write_db(filename, images, **kwargs)
    elif format == 'eon':
        from ase.io.eon import write_reactant_con
        write_reactant_con(filename, images)
        return
    elif format == 'gro':
        from ase.io.gromacs import write_gromacs
        write_gromacs(filename, images)
        return
    elif format == 'g96':
        from ase.io.gromos import write_gromos
        write_gromos(filename, images)
        return
    elif format == 'html':
        from ase.io.x3d import write_html
        write_html(filename, images)
        return

    format = {'traj': 'trajectory',
              'nc': 'netcdf',
              'bundle': 'bundletrajectory'
              }.get(format, format)
    name = 'write_' + format

    if format in ['vti', 'vts', 'vtu']:
        format = 'vtkxml'
    elif format == 'trj':
        name = 'write_trajectory'
        format = 'pickletrajectory'
    elif format is None:
        format = filetype(filename)

    try:
        write = getattr(__import__('ase.io.%s' % format, {}, {}, [name]), name)
    except ImportError:
        raise TypeError('Unknown format: "%s".' % format)

    write(filename, images, **kwargs)
Beispiel #6
0
        print('(111)surface')
        atoms_info += Atoms(numbers=[1],
                            positions=[(r2[0], r2[1], r2[2] - r_SiH)])

print("Symbols = {}".format(atoms_info.symbols))
print("natoms = {}".format(len(atoms_info)))
### Get cell info ###
#  The input XYZ file is assumed to have the cell info
#  at the last two lines
a1 = input_main["lattice"]["unit_vec"][0]
a2 = input_main["lattice"]["unit_vec"][1]
a3 = np.array([0.0, 0.0, slab_size + input_main["param"]["slab_margin"]])
atoms_info.set_cell(np.array([a1, a2, a3]))
comment = "Lattice= \"{} {} {} {} {} {} {} {} {}\" Properties=species:S:1:pos:R:3 pbc=\"T T T\"".format(
    a1[0], a1[1], a1[2], a2[0], a2[1], a2[2], a3[0], a3[1], a3[2])
write_xyz(open(wfile_name + ".xyz", "w"), atoms_info, comment)
from ase.io import read, write

ase_union = read(wfile_name + ".xyz")
### CIF file ###
ase_union.write(wfile_name + '.cif', format='cif')
### Constraints ###
from ase.constraints import FixAtoms

z_atoms = atoms_info.get_positions()[:, 2]
ase_union.set_constraint(
    FixAtoms(indices=np.where(z_atoms <= z_bottom_2nd[1])[0]))

### Quantum Espresso ###
from ase.calculators.espresso import Espresso
Beispiel #7
0
    if os.path.isfile("neb_path.xyz"):
        os.remove("neb_path.xyz")
    
    images = []
    print "shape of potential array", np.shape(potentials)
    #print "Final image potentials:", potentials[-1,1:]
    if np.shape(potentials)[0] > 1:
        final_pots = (potentials)[-1,1:]
    else:
        final_pots = potentials[0][1:]
    print final_pots, potentials
    for potential, pos_file, force_file in zip(final_pots, positions, forces):
        print pos_file, force_file, potential
        ats = io.read(pos_file,index="-1")
        alat = 14.35
        ats.cell = np.array([[alat,0.0,0.0],[0.0,alat,0.0],[0.0,0.0,alat]])
        ats.set_pbc(True) 
        forces = io.read(force_file,index="-1")
        #if conversion required:
        #forces *= units.Hartree/units.Bohr
        #bit of a hack but the positions of the force images are the forces:
        calc = Calculator(ats,potential,forces=forces.get_positions())
        ats.set_calculator(calc)
        forces = ats.get_forces()
        ats.arrays['forces'] = forces
        write_xyz("neb_path.xyz",ats, append=True)
        images.append(ats)
    
    calc_neb_barriers(prefix, images)

Beispiel #8
0
import os
import sys
import glob
import numpy as np
from ase import io
from ase.io.extxyz import write_xyz

prefix = sys.argv[1]
positions = glob.glob("{prefix}.pos_*xyz".format(prefix=prefix))
positions.sort(key=func)
func = lambda x: int(x.split("_")[1].split(".")[0])

if os.path.isfile("neb_restart.xyz"):
    os.remove("neb_restart.xyz")

for pos_file in positions:
    ats = io.read(pos_file, index="-1")
    write_xyz("neb_restart.xyz", ats, append=True)
Beispiel #9
0
    np.savetxt(prefix + "_fit.txt", np.array([Sfit, Efit]))
    np.savetxt(prefix + "_lines.txt", np.vstack(lines))
    fig.savefig(prefix + "_barrier.eps")


if __name__ == '__main__':
    prefix = sys.argv[1]
    job_dirs = glob.glob("{prefix}*".format(prefix=prefix))
    job_dirs = filter(os.path.isdir, job_dirs)
    func = lambda x: int(x.split("_")[1])
    job_dirs.sort(key=func)

    images = []
    print "Removing old neb path"
    if os.path.isfile("neb_path.xyz"):
        os.remove("neb_path.xyz")
    for job in job_dirs:
        print "pulling ", job
        with pushd(job) as ctx0:
            try:
                ats = io.read('OUTCAR', index='-1')
                ats.arrays['forces'] = ats.get_forces()
            except StopIteration:
                print "Could not pull OUTCAR for:", job
            else:
                images.append(ats)

    for image in images:
        write_xyz("neb_path.xyz", image, append=True)
    calc_neb_barriers(prefix, images)
Beispiel #10
0
def xdatcar_to_xyz(argv):
    """Convert XDATCAR file to xyz.

    Each comment line begins with #.
    After frame number is printed. If timestep is given, actual time is written; assumes fs.
    First comment line contains ASE object info as well.

    Result is written on stdout."""

    #-------------------------------------------------------------------------------
    # Argument parser
    #-------------------------------------------------------------------------------
    parser = argparse.ArgumentParser(description=__doc__)
    # Positional arguments
    parser.add_argument('filename',
                        default='XDATCAR',
                        type=str,
                        nargs='?',
                        help='input file. If not given XDATCAR is used;'
                        )  # if NULL is given, stdin is used.')
    # Optional args
    parser.add_argument('--dt',
                        dest='dt',
                        type=float,
                        default=None,
                        help='timestep in femptosecon;')
    parser.add_argument('--debug',
                        action='store_true',
                        dest='debug',
                        help='show debug informations.')

    #-------------------------------------------------------------------------------
    # Initialize and check variables
    #-------------------------------------------------------------------------------
    args = parser.parse_args(argv)

    # Set up LOGGER
    c_log = logging.getLogger(__name__)
    # Adopted format: level - current function name - mess. Width is fixed as visual aid
    std_format = '[%(levelname)5s - %(funcName)10s] %(message)s'
    logging.basicConfig(format=std_format)
    c_log.setLevel(logging.INFO)
    # Set debug option
    if args.debug: c_log.setLevel(logging.DEBUG)

    c_log.debug(args)

    # Set time variable properly
    t_unit = "fs"
    if args.dt is None:
        args.dt = 1
        t_unit = ""

    #-------------------------------------------------------------------------------
    # Load file and print xyz to stdout
    #-------------------------------------------------------------------------------
    # Load xdatcar as list of Atoms obj
    # For some reason we need to put index=0 to load all of it, otherwise is just the first.
    for t, frame in enumerate(read_vasp_xdatcar(args.filename, index=0)):
        c_line = "# %.6f %s " % (t * args.dt, t_unit)
        # If it's the first line, print first atoms object info
        # Here we are assuming that since it's MD, cell and compositions are not changing.
        if t == 0:
            c_line += "%s %s" % (frame, frame.info)

        write_xyz(sys.stdout, frame, append=True, comment=c_line)