예제 #1
0
def read_gromacs(filename):
    """ From:
    http://manual.gromacs.org/current/online/gro.html
    C format
    "%5d%5s%5s%5d%8.3f%8.3f%8.3f%8.4f%8.4f%8.4f"
    python: starting from 0, including first excluding last
    0:4 5:10 10:15 15:20 20:28 28:36 36:44 44:52 52:60 60:68

    Import gromacs geometry type files (.gro).
    Reads atom positions,
    velocities(if present) and
    simulation cell (if present)
    """

    from ase.data import chemical_symbols
    from ase import units

    atoms = Atoms()
    filed = open(filename, 'r')
    lines = filed.readlines()
    filed.close()
    positions = []
    gromacs_velocities = []
    symbols = []
    gromacs_residuenames = []
    gromacs_atomtypes = []
    for line in (lines[2:-1]):
        #print line[0:5]+':'+line[5:11]+':'+line[11:15]+':'+line[15:20]
        inp = line.split()
        floatvect = float(line[20:28]) * 10.0, \
            float(line[28:36]) * 10.0, \
            float(line[36:44]) * 10.0
        positions.append(floatvect)
        try:
            #velocities from nm/ps to ase units
            floatvect = \
                float(line[44:52]) * units.nm / (1000.0 * units.fs), \
                float(line[52:60]) * units.nm / (1000.0 * units.fs), \
                float(line[60:68]) * units.nm / (1000.0 * units.fs)
        except:
            floatvect = 0.0, 0.0, 0.0
        gromacs_velocities.append(floatvect)
        symbols.append(inp[1][0:2])
        gromacs_residuenames.append(inp[0])
        gromacs_atomtypes.append(inp[1])
    line = lines[-1]
    symbols_ok = []
    for isymbol in symbols:
        if isymbol in chemical_symbols:
            #ok atom name
            symbols_ok.append(isymbol)
        else:
            #not ok atom name
            symbols_ok.append(isymbol[0])
    atoms = Atoms(symbols_ok, positions)
    atoms.set_velocities(gromacs_velocities)

    if not atoms.has('residuenames'):
        atoms.new_array('residuenames', gromacs_residuenames, str)
        atoms.set_array('residuenames', gromacs_residuenames, str)
    if not atoms.has('atomtypes'):
        atoms.new_array('atomtypes', gromacs_atomtypes, str)
        atoms.set_array('atomtypes', gromacs_atomtypes, str)
    try:
        line = lines[-1]
        inp = line.split()
        floatvect0 = \
            float(inp[0]) * 10.0, \
            float(inp[1]) * 10.0, \
            float(inp[2]) * 10.0
        try:
            floatvect1 = \
                float(inp[3]) * 10.0, \
                float(inp[4]) * 10.0, \
                float(inp[5]) * 10.0
            floatvect2 = \
                float(inp[6]) * 10.0, \
                float(inp[7]) * 10.0, \
                float(inp[8]) * 10.0
            mycell = []
            #gromacs manual (manual.gromacs.org/online/gro.html) says:
            #v1(x) v2(y) v3(z) v1(y) v1(z) v2(x) v2(z) v3(x) v3(y)
            #
            #v1(x) v2(y) v3(z) fv0[0 1 2]  v1(x) v2(x) v3(x)
            #v1(y) v1(z) v2(x) fv1[0 1 2]  v1(y) v2(y) v3(y)
            #v2(z) v3(x) v3(y) fv2[0 1 2]  v1(z) v2(z) v3(z)
            mycell += [[floatvect0[0], floatvect1[2], floatvect2[1]]]
            mycell += [[floatvect1[0], floatvect0[1], floatvect2[2]]]
            mycell += [[floatvect1[1], floatvect2[0], floatvect0[2]]]
            atoms.set_cell(mycell)
            atoms.set_pbc(True)
        except:
            mycell = []
            #gromacs manual (manual.gromacs.org/online/gro.html) says:
            #v1(x) v2(y) v3(z) v1(y) v1(z) v2(x) v2(z) v3(x) v3(y)
            mycell += [[floatvect0[0], 0.0, 0.0]]
            mycell += [[0.0, floatvect0[1], 0.0]]
            mycell += [[0.0, 0.0, floatvect0[2]]]
            atoms.set_cell(floatvect0)
            atoms.set_pbc(True)
    except:
        atoms.set_pbc(False)
    return atoms
예제 #2
0
파일: gromacs.py 프로젝트: jboes/ase
def read_gromacs(filename):
    """ From:
    http://manual.gromacs.org/current/online/gro.html
    C format
    "%5d%5s%5s%5d%8.3f%8.3f%8.3f%8.4f%8.4f%8.4f" 
    python: starting from 0, including first excluding last
    0:4 5:10 10:15 15:20 20:28 28:36 36:44 44:52 52:60 60:68 

    Import gromacs geometry type files (.gro).
    Reads atom positions,
    velocities(if present) and
    simulation cell (if present)
    """

    from ase.data import chemical_symbols
    from ase import units

    atoms = Atoms()
    filed = open(filename, "r")
    lines = filed.readlines()
    filed.close()
    positions = []
    gromacs_velocities = []
    symbols = []
    gromacs_residuenames = []
    gromacs_atomtypes = []
    for line in lines[2:-1]:
        # print line[0:5]+':'+line[5:11]+':'+line[11:15]+':'+line[15:20]
        inp = line.split()
        floatvect = float(line[20:28]) * 10.0, float(line[28:36]) * 10.0, float(line[36:44]) * 10.0
        positions.append(floatvect)
        try:
            # velocities from nm/ps to ase units
            floatvect = (
                float(line[44:52]) * units.nm / (1000.0 * units.fs),
                float(line[52:60]) * units.nm / (1000.0 * units.fs),
                float(line[60:68]) * units.nm / (1000.0 * units.fs),
            )
        except:
            floatvect = 0.0, 0.0, 0.0
        gromacs_velocities.append(floatvect)
        symbols.append(inp[1][0:2])
        gromacs_residuenames.append(inp[0])
        gromacs_atomtypes.append(inp[1])
    line = lines[-1]
    symbols_ok = []
    for isymbol in symbols:
        if isymbol in chemical_symbols:
            # ok atom name
            symbols_ok.append(isymbol)
        else:
            # not ok atom name
            symbols_ok.append(isymbol[0])
    atoms = Atoms(symbols_ok, positions)
    atoms.set_velocities(gromacs_velocities)

    if not atoms.has("residuenames"):
        atoms.new_array("residuenames", gromacs_residuenames, str)
        atoms.set_array("residuenames", gromacs_residuenames, str)
    if not atoms.has("atomtypes"):
        atoms.new_array("atomtypes", gromacs_atomtypes, str)
        atoms.set_array("atomtypes", gromacs_atomtypes, str)
    try:
        line = lines[-1]
        inp = line.split()
        floatvect0 = float(inp[0]) * 10.0, float(inp[1]) * 10.0, float(inp[2]) * 10.0
        try:
            floatvect1 = float(inp[3]) * 10.0, float(inp[4]) * 10.0, float(inp[5]) * 10.0
            floatvect2 = float(inp[6]) * 10.0, float(inp[7]) * 10.0, float(inp[8]) * 10.0
            mycell = []
            # gromacs manual (manual.gromacs.org/online/gro.html) says:
            # v1(x) v2(y) v3(z) v1(y) v1(z) v2(x) v2(z) v3(x) v3(y)
            #
            # v1(x) v2(y) v3(z) fv0[0 1 2]  v1(x) v2(x) v3(x)
            # v1(y) v1(z) v2(x) fv1[0 1 2]  v1(y) v2(y) v3(y)
            # v2(z) v3(x) v3(y) fv2[0 1 2]  v1(z) v2(z) v3(z)
            mycell += [[floatvect0[0], floatvect1[2], floatvect2[1]]]
            mycell += [[floatvect1[0], floatvect0[1], floatvect2[2]]]
            mycell += [[floatvect1[1], floatvect2[0], floatvect0[2]]]
            atoms.set_cell(mycell)
            atoms.set_pbc(True)
            print("9N")
        except:
            mycell = []
            # gromacs manual (manual.gromacs.org/online/gro.html) says:
            # v1(x) v2(y) v3(z) v1(y) v1(z) v2(x) v2(z) v3(x) v3(y)
            mycell += [[floatvect0[0], 0.0, 0.0]]
            mycell += [[0.0, floatvect0[1], 0.0]]
            mycell += [[0.0, 0.0, floatvect0[2]]]
            atoms.set_cell(floatvect0)
            atoms.set_pbc(True)
    except:
        atoms.set_pbc(False)
    return atoms
예제 #3
0
def read_gromacs(filename):
    """ From:
    http://manual.gromacs.org/current/online/gro.html
    C format
    "%5d%-5s%5s%5d%8.3f%8.3f%8.3f%8.4f%8.4f%8.4f"
    python: starting from 0, including first excluding last
    0:4 5:10 10:15 15:20 20:28 28:36 36:44 44:52 52:60 60:68

    Import gromacs geometry type files (.gro).
    Reads atom positions,
    velocities(if present) and
    simulation cell (if present)
    """

    atoms = Atoms()
    filed = open(filename, 'r')
    lines = filed.readlines()
    filed.close()
    positions = []
    gromacs_velocities = []
    symbols = []
    tags = []
    gromacs_residuenumbers = []
    gromacs_residuenames = []
    gromacs_atomtypes = []
    sym2tag = {}
    tag = 0
    for line in (lines[2:-1]):
        # print(line[0:5]+':'+line[5:11]+':'+line[11:15]+':'+line[15:20])
        # it is not a good idea to use the split method with gromacs input
        # since the fields are defined by a fixed column number. Therefore,
        # they may not be space between the fields
        # inp = line.split()

        floatvect = float(line[20:28]) * 10.0, \
            float(line[28:36]) * 10.0, \
            float(line[36:44]) * 10.0
        positions.append(floatvect)

        # read velocities
        velocities = np.array([0.0, 0.0, 0.0])
        vx = line[44:52].strip()
        vy = line[52:60].strip()
        vz = line[60:68].strip()

        for iv, vxyz in enumerate([vx, vy, vz]):
            if len(vxyz) > 0:
                try:
                    velocities[iv] = float(vxyz)
                except ValueError:
                    raise ValueError("can not convert velocity to float")
            else:
                velocities = None

        if velocities is not None:
            # velocities from nm/ps to ase units
            velocities *= units.nm / (1000.0 * units.fs)
            gromacs_velocities.append(velocities)

        gromacs_residuenumbers.append(int(line[0:5]))
        gromacs_residuenames.append(line[5:11].strip())

        symbol_read = line[11:16].strip()[0:2]
        if symbol_read not in sym2tag.keys():
            sym2tag[symbol_read] = tag
            tag += 1

        tags.append(sym2tag[symbol_read])
        if symbol_read in atomic_numbers:
            symbols.append(symbol_read)
        elif symbol_read[0] in atomic_numbers:
            symbols.append(symbol_read[0])
        elif symbol_read[-1] in atomic_numbers:
            symbols.append(symbol_read[-1])
        else:
            # not an atomic symbol
            # if we can not determine the symbol, we use
            # the dummy symbol X
            symbols.append("X")

        gromacs_atomtypes.append(line[11:16].strip())

    line = lines[-1]
    atoms = Atoms(symbols, positions, tags=tags)

    if len(gromacs_velocities) == len(atoms):
        atoms.set_velocities(gromacs_velocities)
    elif len(gromacs_velocities) != 0:
        raise ValueError("Some atoms velocities were not specified!")

    if not atoms.has('residuenumbers'):
        atoms.new_array('residuenumbers', gromacs_residuenumbers, int)
        atoms.set_array('residuenumbers', gromacs_residuenumbers, int)
    if not atoms.has('residuenames'):
        atoms.new_array('residuenames', gromacs_residuenames, str)
        atoms.set_array('residuenames', gromacs_residuenames, str)
    if not atoms.has('atomtypes'):
        atoms.new_array('atomtypes', gromacs_atomtypes, str)
        atoms.set_array('atomtypes', gromacs_atomtypes, str)

    # determine PBC and unit cell
    atoms.pbc = False
    inp = lines[-1].split()
    try:
        grocell = list(map(float, inp))
    except ValueError:
        return atoms

    if len(grocell) < 3:
        return atoms

    cell = np.diag(grocell[:3])

    if len(grocell) >= 9:
        cell.flat[[1, 2, 3, 5, 6, 7]] = grocell[3:9]

    atoms.cell = cell * 10.
    atoms.pbc = True
    return atoms
예제 #4
0
    def __init__(self, geometry=None, **kwargs) -> None:
        if geometry == None:
            atoms = Atoms(**kwargs)
        elif type(geometry) == ase.atoms.Atoms:
            atoms = geometry.copy()
        elif Path(geometry).is_file():
            if str(Path(geometry).parts[-1]) == "geometry.in.next_step":
                atoms = ase.io.read(geometry, format="aims")
            else:
                try:
                    atoms = ase.io.read(geometry)
                except Exception as excpt:
                    logger.error(str(excpt))
                    raise Exception(
                        "ASE was not able to recognize the file format, e.g., a non-standard cif-format."
                    )
        elif Path(geometry).is_dir():
            raise Exception(
                "You specified a directory as input. The geometry must be a file."
            )
        else:
            atoms = None

        assert type(atoms) == ase.atoms.Atoms, "Atoms not read correctly."
        # Get data from another Atoms object:
        numbers = atoms.get_atomic_numbers()
        positions = atoms.get_positions()
        cell = atoms.get_cell()
        celldisp = atoms.get_celldisp()
        pbc = atoms.get_pbc()
        constraint = [c.copy() for c in atoms.constraints]
        masses = atoms.get_masses()
        magmoms = None
        charges = None
        momenta = None
        if atoms.has("initial_magmoms"):
            magmoms = atoms.get_initial_magnetic_moments()
        if atoms.has("initial_charges"):
            charges = atoms.get_initial_charges()
        if atoms.has("momenta"):
            momenta = atoms.get_momenta()
        self.arrays = {}
        super().__init__(
            numbers=numbers,
            positions=positions,
            cell=cell,
            celldisp=celldisp,
            pbc=pbc,
            constraint=constraint,
            masses=masses,
            magmoms=magmoms,
            charges=charges,
            momenta=momenta,
        )
        self._is_1d = None
        self._is_2d = None
        self._is_3d = None
        self._periodic_axes = None
        self._check_lattice_vectors()

        try:
            self.sg = ase.spacegroup.get_spacegroup(self, symprec=1e-2)
        except:
            self.sg = ase.spacegroup.Spacegroup(1)
        self.lattice = self.cell.get_bravais_lattice().crystal_family
예제 #5
0
def read_dlp4(f):
    """Read a DL_POLY_4 config/revcon file.

    Typically used indirectly through read('filename', atoms, format='dlp4').

    Can be unforgiven with custom chemical element names.
    Please complain to [email protected] for bugs."""
    line = f.readline()
    line = f.readline().split()
    levcfg = int(line[0])
    imcon = int(line[1])
    pbc = False
    if imcon > 0:
        pbc = True
    cell = zeros((3, 3))
    if pbc:
        for j in range(3):
            line = f.readline().split()
            for i in range(3):
                try:
                    cell[j, i] = float(line[i])
                except ValueError:
                    raise RuntimeError("error reading cell")
    symbols = []
    positions = []
    velocities = []
    forces = []
    line = f.readline()
    while line:
        symbol = line.split()[0]
        if symbol in chemical_symbols:
            symbols.append(symbol)
        else:
            ns = symbol[0]
            if ns in chemical_symbols:
                symbols.append(ns)
            else:
                ns = symbol[0:2]
                if ns in chemical_symbols:
                    symbols.append(ns)
                else:
                    symbols.append('X')
        x, y, z = f.readline().split()[:3]
        positions.append([float(x), float(y), float(z)])
        if levcfg > 0:
            vx, vy, vz = f.readline().split()[:3]
            velocities.append([float(vx), float(vy), float(vz)])
        if levcfg > 1:
            fx, fy, fz = f.readline().split()[:3]
            forces.append([float(fx), float(fy), float(fz)])
        line = f.readline()

    ats = Atoms(positions=positions,
                symbols=symbols,
                cell=cell,
                pbc=pbc)

    # XXX Fix this once atom labels are a thing.
    if not ats.has('names'):
        ats.new_array('names', symbols, str)
        ats.set_array('names', symbols, str)
    f.readline()
    if levcfg > 0:
        ats.set_velocities(velocities)
    if levcfg > 1:
        ats.set_calculator(SinglePointCalculator(ats, forces=forces))
    return ats
예제 #6
0
파일: dlp4.py 프로젝트: essil1/ase-laser
def read_dlp4(f):
    """Read a DL_POLY_4 config/revcon file.

    Typically used indirectly through read('filename', atoms, format='dlp4').

    Can be unforgiven with custom chemical element names.
    Please complain to [email protected] for bugs."""
    line = f.readline()
    line = f.readline().split()
    levcfg = int(line[0])
    imcon = int(line[1])
    pbc = False
    if imcon > 0:
        pbc = True
    cell = zeros((3, 3))
    if pbc:
        for j in range(3):
            line = f.readline().split()
            for i in range(3):
                try:
                    cell[j, i] = float(line[i])
                except ValueError:
                    raise RuntimeError("error reading cell")
    symbols = []
    positions = []
    velocities = []
    forces = []
    line = f.readline()
    while line:
        symbol = line.split()[0]
        if symbol in chemical_symbols:
            symbols.append(symbol)
        else:
            ns = symbol[0]
            if ns in chemical_symbols:
                symbols.append(ns)
            else:
                ns = symbol[0:2]
                if ns in chemical_symbols:
                    symbols.append(ns)
                else:
                    symbols.append('X')
        x, y, z = f.readline().split()[:3]
        positions.append([float(x), float(y), float(z)])
        if levcfg > 0:
            vx, vy, vz = f.readline().split()[:3]
            velocities.append([float(vx), float(vy), float(vz)])
        if levcfg > 1:
            fx, fy, fz = f.readline().split()[:3]
            forces.append([float(fx), float(fy), float(fz)])
        line = f.readline()

    ats = Atoms(positions=positions, symbols=symbols, cell=cell, pbc=pbc)

    # XXX Fix this once atom labels are a thing.
    if not ats.has('names'):
        ats.new_array('names', symbols, str)
        ats.set_array('names', symbols, str)
    f.readline()
    if levcfg > 0:
        ats.set_velocities(velocities)
    if levcfg > 1:
        ats.set_calculator(SinglePointCalculator(ats, forces=forces))
    return ats
예제 #7
0
def read_gromacs(filename):
    """ From:
    http://manual.gromacs.org/current/online/gro.html
    C format
    "%5d%-5s%5s%5d%8.3f%8.3f%8.3f%8.4f%8.4f%8.4f"
    python: starting from 0, including first excluding last
    0:4 5:10 10:15 15:20 20:28 28:36 36:44 44:52 52:60 60:68

    Import gromacs geometry type files (.gro).
    Reads atom positions,
    velocities(if present) and
    simulation cell (if present)
    """

    from ase.data import atomic_numbers
    from ase import units

    atoms = Atoms()
    filed = open(filename, 'r')
    lines = filed.readlines()
    filed.close()
    positions = []
    gromacs_velocities = []
    symbols = []
    tags = []
    gromacs_residuenumbers = []
    gromacs_residuenames = []
    gromacs_atomtypes = []
    sym2tag = {}
    tag = 0
    for line in (lines[2:-1]):
        #print line[0:5]+':'+line[5:11]+':'+line[11:15]+':'+line[15:20]
        # it is not a good idea to use the split method with gromacs input
        # since the fields are defined by a fixed column number. Therefore,
        # they may not be space between the fields
        #inp = line.split()

        floatvect = float(line[20:28]) * 10.0, \
            float(line[28:36]) * 10.0, \
            float(line[36:44]) * 10.0
        positions.append(floatvect)

        # read velocities
        velocities = np.array([0.0, 0.0, 0.0])
        vx = line[44:52].strip()
        vy = line[52:60].strip()
        vz = line[60:68].strip()

        for iv, vxyz in enumerate([vx, vy, vz]):
            if len(vxyz) > 0:
                try:
                    velocities[iv] = float(vxyz)
                except ValueError:
                    raise ValueError("can not convert velocity to float")
            else:
                velocities = None

        if velocities is not None:
            # velocities from nm/ps to ase units
            velocities *= units.nm / (1000.0 * units.fs)
            gromacs_velocities.append(velocities)

        gromacs_residuenumbers.append(int(line[0:5]))
        gromacs_residuenames.append(line[5:11].strip())

        symbol_read = line[11:16].strip()[0:2]
        if symbol_read not in sym2tag.keys():
            sym2tag[symbol_read] = tag
            tag += 1

        tags.append(sym2tag[symbol_read])
        if symbol_read in atomic_numbers:
            symbols.append(symbol_read)
        elif symbol_read[0] in atomic_numbers:
            symbols.append(symbol_read[0])
        elif symbol_read[-1] in atomic_numbers:
            symbols.append(symbol_read[-1])
        else:
            # not an atomic symbol
            # if we can not determine the symbol, we use
            # the dummy symbol X
            symbols.append("X")

        gromacs_atomtypes.append(line[11:16].strip())

    line = lines[-1]
    atoms = Atoms(symbols, positions, tags=tags)

    if len(gromacs_velocities) == len(atoms):
        atoms.set_velocities(gromacs_velocities)
    elif len(gromacs_velocities) != 0:
        raise ValueError("Some atoms velocities were not specified!")

    if not atoms.has('residuenumbers'):
        atoms.new_array('residuenumbers', gromacs_residuenumbers, int)
        atoms.set_array('residuenumbers', gromacs_residuenumbers, int)
    if not atoms.has('residuenames'):
        atoms.new_array('residuenames', gromacs_residuenames, str)
        atoms.set_array('residuenames', gromacs_residuenames, str)
    if not atoms.has('atomtypes'):
        atoms.new_array('atomtypes', gromacs_atomtypes, str)
        atoms.set_array('atomtypes', gromacs_atomtypes, str)

    try:
        line = lines[-1]
        inp = line.split()
        floatvect0 = \
            float(inp[0]) * 10.0, \
            float(inp[1]) * 10.0, \
            float(inp[2]) * 10.0
        try:
            floatvect1 = \
                float(inp[3]) * 10.0, \
                float(inp[4]) * 10.0, \
                float(inp[5]) * 10.0
            floatvect2 = \
                float(inp[6]) * 10.0, \
                float(inp[7]) * 10.0, \
                float(inp[8]) * 10.0
            mycell = []
            #gromacs manual (manual.gromacs.org/online/gro.html) says:
            #v1(x) v2(y) v3(z) v1(y) v1(z) v2(x) v2(z) v3(x) v3(y)
            #
            #v1(x) v2(y) v3(z) fv0[0 1 2]  v1(x) v2(x) v3(x)
            #v1(y) v1(z) v2(x) fv1[0 1 2]  v1(y) v2(y) v3(y)
            #v2(z) v3(x) v3(y) fv2[0 1 2]  v1(z) v2(z) v3(z)
            mycell += [[floatvect0[0], floatvect1[2], floatvect2[1]]]
            mycell += [[floatvect1[0], floatvect0[1], floatvect2[2]]]
            mycell += [[floatvect1[1], floatvect2[0], floatvect0[2]]]
            atoms.set_cell(mycell)
            atoms.set_pbc(True)
        except:
            mycell = []
            #gromacs manual (manual.gromacs.org/online/gro.html) says:
            #v1(x) v2(y) v3(z) v1(y) v1(z) v2(x) v2(z) v3(x) v3(y)
            mycell += [[floatvect0[0], 0.0, 0.0]]
            mycell += [[0.0, floatvect0[1], 0.0]]
            mycell += [[0.0, 0.0, floatvect0[2]]]
            atoms.set_cell(floatvect0)
            atoms.set_pbc(True)
    except:
        atoms.set_pbc(False)
    return atoms