예제 #1
0
def test_set_get_angle():
    "Test that set_angle() and get_angle() in Atoms are consistent"

    from ase import Atoms

    atoms = Atoms(
        'HHCCHH',
        [[-1, 1, 0], [-1, -1, 0], [0, 0, 0], [1, 0, 0], [2, 1, 0], [2, -1, 0]])

    list = [2, 3, 4]
    theta = 20
    old_angle = atoms.get_angle(*list)
    atoms.set_angle(*list, angle=old_angle + theta)
    new_angle = atoms.get_angle(*list)

    assert abs(new_angle - (old_angle + theta)) < 1.0e-9
예제 #2
0
def test_qmmm_acn():
    import numpy as np

    import ase.units as units
    from ase import Atoms
    from ase.calculators.acn import (ACN, m_me, r_cn, r_mec,
                                     sigma_me, sigma_c, sigma_n,
                                     epsilon_me, epsilon_c, epsilon_n)
    from ase.calculators.qmmm import SimpleQMMM, LJInteractionsGeneral, EIQMMM
    from ase.constraints import FixLinearTriatomic
    from ase.optimize import BFGS

    # From https://www.sciencedirect.com/science/article/pii/S0166128099002079
    eref = 4.9 * units.kcal / units.mol
    dref = 3.368
    aref = 79.1

    sigma = np.array([sigma_me, sigma_c, sigma_n])
    epsilon = np.array([epsilon_me, epsilon_c, epsilon_n])
    inter = LJInteractionsGeneral(sigma, epsilon, sigma, epsilon, 3)

    for calc in [ACN(),
                 SimpleQMMM([0, 1, 2], ACN(), ACN(), ACN()),
                 SimpleQMMM([0, 1, 2], ACN(), ACN(), ACN(), vacuum=3.0),
                 EIQMMM([0, 1, 2], ACN(), ACN(), inter),
                 EIQMMM([0, 1, 2], ACN(), ACN(), inter, vacuum=3.0),
                 EIQMMM([3, 4, 5], ACN(), ACN(), inter, vacuum=3.0)]:
        dimer = Atoms('CCNCCN',
                      [(-r_mec, 0, 0),
                       (0, 0, 0),
                       (r_cn, 0, 0),
                       (r_mec, 3.7, 0),
                       (0, 3.7, 0),
                       (-r_cn, 3.7, 0)])

        masses = dimer.get_masses()
        masses[::3] = m_me
        dimer.set_masses(masses)

        dimer.calc = calc

        fixd = FixLinearTriatomic(triples=[(0, 1, 2), (3, 4, 5)])

        dimer.set_constraint(fixd)

        opt = BFGS(dimer, maxstep=0.04,
                   trajectory=calc.name + '.traj', logfile=calc.name + 'd.log')
        opt.run(0.001, steps=1000)

        e0 = dimer.get_potential_energy()
        d0 = dimer.get_distance(1, 4)
        a0 = dimer.get_angle(2, 1, 4)
        fmt = '{0:>25}: {1:.3f} {2:.3f} {3:.1f}'
        print(fmt.format(calc.name, -e0, d0, a0))
        assert abs(e0 + eref) < 0.013
        assert abs(d0 - dref) < 0.224
        assert abs(a0 - aref) < 2.9

    print(fmt.format('reference', eref, dref, aref))
예제 #3
0
def test_atoms_angle():
    from ase import Atoms
    import numpy as np

    atoms = Atoms(['O', 'H', 'H'],
                  positions=[[0., 0., 0.119262], [0., 0.763239, -0.477047],
                             [0., -0.763239, -0.477047]])

    # Angle no pbc
    assert abs(atoms.get_angle(1, 0, 2) - 104) < 1e-3

    atoms.set_cell([2, 2, 2])

    # Across different pbcs
    atoms.set_pbc([True, False, True])
    atoms.wrap()
    assert abs(atoms.get_angle(1, 0, 2, mic=True) - 104) < 1e-3

    # Across all True pbc
    atoms.set_pbc(True)
    atoms.wrap()
    assert abs(atoms.get_angle(1, 0, 2, mic=True) - 104) < 1e-3

    # Change Angle
    old = atoms.get_angle(1, 0, 2, mic=False)
    atoms.set_angle(1, 0, 2, -10, indices=[2], add=True)
    new = atoms.get_angle(1, 0, 2, mic=False)
    diff = old - new - 10
    assert abs(diff) < 10e-3

    # don't actually change angle using indices
    old = atoms.get_angle(1, 0, 2, mic=False)
    atoms.set_angle(1, 0, 2, -10, indices=[2, 1], add=True)
    new = atoms.get_angle(1, 0, 2, mic=False)
    diff = old - new
    assert abs(diff) < 10e-3

    # Simple tetrahedron
    tetra_pos = np.array([[0, 0, 0], [1, 0, 0], [.5, np.sqrt(3) * .5, 0],
                          [.5, np.sqrt(1 / 3.) * .5,
                           np.sqrt(2 / 3.)]])
    atoms = Atoms(['H', 'H', 'H', 'H'],
                  positions=tetra_pos - np.array([.2, 0, 0]))
    angle = 70.5287793655
    assert abs(atoms.get_dihedral(0, 1, 2, 3) - angle) < 1e-3

    atoms.set_cell([3, 3, 3])
    atoms.set_pbc(True)
    atoms.wrap()
    assert abs(atoms.get_dihedral(0, 1, 2, 3, mic=True) - angle) < 1e-3
예제 #4
0
from ase import Atoms
import numpy as np

atoms = Atoms(['O', 'H', 'H'], positions=[[0., 0., 0.119262],
                                          [0., 0.763239, -0.477047],
                                          [0., -0.763239, -0.477047]])

# Angle no pbc
assert abs(atoms.get_angle(1, 0, 2) - 104) < 1e-3

atoms.set_cell([2, 2, 2])

# Across different pbcs
atoms.set_pbc([True, False, True])
atoms.wrap()
assert abs(atoms.get_angle(1, 0, 2, mic=True) - 104) < 1e-3

# Across all True pbc
atoms.set_pbc(True)
atoms.wrap()
assert abs(atoms.get_angle(1, 0, 2, mic=True) - 104) < 1e-3

# Simple tetrahedron
tetra_pos = np.array([[0, 0, 0], [1, 0, 0], [.5, np.sqrt(3) * .5, 0],
                      [.5, np.sqrt(1/3.) * .5, np.sqrt(2/3.)]])
atoms = Atoms(['H', 'H', 'H', 'H'],
              positions=tetra_pos - np.array([.2, 0, 0]))
angle = 70.5287793655
assert abs(atoms.get_dihedral(0, 1, 2, 3) - angle) < 1e-3

atoms.set_cell([3, 3, 3])
예제 #5
0
class Conformer():
    """
    A class for generating and editing 3D conformers of molecules
    """

    def __init__(self, smiles=None, rmg_molecule=None, index=0):

        self.energy = None
        self.index = index

        if (smiles or rmg_molecule):
            if smiles and rmg_molecule:
                assert rmg_molecule.isIsomorphic(RMGMolecule(
                    SMILES=smiles)), "SMILES string did not match RMG Molecule object"
                self.smiles = smiles
                self.rmg_molecule = rmg_molecule

            elif rmg_molecule:
                self.rmg_molecule = rmg_molecule
                self.smiles = rmg_molecule.toSMILES()

            else:
                self.smiles = smiles
                self.rmg_molecule = RMGMolecule(SMILES=smiles)

            self.rmg_molecule.updateMultiplicity()
            self.get_molecules()
            self.get_geometries()
            self._symmetry_number = None

        else:
            self.smiles = None
            self.rmg_molecule = None
            self.rdkit_molecule = None
            self.ase_molecule = None
            self.bonds = []
            self.angles = []
            self.torsions = []
            self.cistrans = []
            self.chiral_centers = []
            self._symmetry_number = None

    def __repr__(self):
        return '<Conformer "{}">'.format(self.smiles)

    def copy(self):
        copy_conf = Conformer()
        copy_conf.smiles = self.smiles
        copy_conf.rmg_molecule = self.rmg_molecule.copy()
        copy_conf.rdkit_molecule = self.rdkit_molecule.__copy__()
        copy_conf.ase_molecule = self.ase_molecule.copy()
        copy_conf.get_geometries()
        copy_conf.energy = self.energy
        return copy_conf

    @property
    def symmetry_number(self):
        if not self._symmetry_number:
            self._symmetry_number = self.calculate_symmetry_number()
        return self._symmetry_number

    def get_rdkit_mol(self):
        """
        A method for creating an rdkit geometry from an rmg mol
        """

        assert self.rmg_molecule, "Cannot create an RDKit geometry without an RMG molecule object"

        RDMol = self.rmg_molecule.toRDKitMol(removeHs=False)
        rdkit.Chem.AllChem.EmbedMolecule(RDMol)
        self.rdkit_molecule = RDMol

        mol_list = AllChem.MolToMolBlock(self.rdkit_molecule).split('\n')
        for i, atom in enumerate(self.rmg_molecule.atoms):
            j = i + 4
            coords = mol_list[j].split()[:3]
            for k, coord in enumerate(coords):
                coords[k] = float(coord)
            atom.coords = np.array(coords)

        return self.rdkit_molecule

    def get_ase_mol(self):
        """
        A method for creating an ase atoms object from an rdkit mol
        """

        if not self.rdkit_molecule:
            self.get_rdkit_mol()

        mol_list = AllChem.MolToMolBlock(self.rdkit_molecule).split('\n')
        ase_atoms = []
        for i, line in enumerate(mol_list):
            if i > 3:
                try:
                    atom0, atom1, bond, rest = line
                    atom0 = int(atom0)
                    atom0 = int(atom1)
                    bond = float(bond)
                except ValueError:
                    try:
                        x, y, z, symbol = line.split()[0:4]
                        x = float(x)
                        y = float(y)
                        z = float(z)
                        ase_atoms.append(
                            Atom(symbol=symbol, position=(x, y, z)))
                    except BaseException:
                        continue

        self.ase_molecule = Atoms(ase_atoms)

        return self.ase_molecule

    def get_molecules(self):
        if not self.rmg_molecule:
            self.rmg_molecule = RMGMolecule(SMILES=self.smiles)
        self.rdkit_molecule = self.get_rdkit_mol()
        self.ase_molecule = self.get_ase_mol()
        self.get_geometries()

        return self.rdkit_molecule, self.ase_molecule

    def view(self):
        """
        A method designed to create a 3D figure of the AutoTST_Molecule with py3Dmol from the rdkit_molecule
        """
        mb = Chem.MolToMolBlock(self.rdkit_molecule)
        p = py3Dmol.view(width=600, height=600)
        p.addModel(mb, "sdf")
        p.setStyle({'stick': {}})
        p.setBackgroundColor('0xeeeeee')
        p.zoomTo()
        return p.show()

    def get_bonds(self):
        """
        A method for identifying all of the bonds in a conformer
        """
        bond_list = []
        for bond in self.rdkit_molecule.GetBonds():
            bond_list.append((bond.GetBeginAtomIdx(), bond.GetEndAtomIdx()))

        bonds = []
        for index, indices in enumerate(bond_list):
            i, j = indices

            length = self.ase_molecule.get_distance(i, j)
            center = False
            if ((self.rmg_molecule.atoms[i].label) and (
                    self.rmg_molecule.atoms[j].label)):
                center = True

            bond = Bond(index=index,
                        atom_indices=indices,
                        length=length,
                        reaction_center=center)
            mask = self.get_mask(bond)
            bond.mask = mask

            bonds.append(bond)

        self.bonds = bonds

        return self.bonds

    def get_angles(self):
        """
        A method for identifying all of the angles in a conformer
        """

        angle_list = []
        for atom1 in self.rdkit_molecule.GetAtoms():
            for atom2 in atom1.GetNeighbors():
                for atom3 in atom2.GetNeighbors():
                    if atom1.GetIdx() == atom3.GetIdx():
                        continue

                    to_add = (atom1.GetIdx(), atom2.GetIdx(), atom3.GetIdx())
                    if (to_add in angle_list) or (
                            tuple(reversed(to_add)) in angle_list):
                        continue
                    angle_list.append(to_add)

        angles = []
        for index, indices in enumerate(angle_list):
            i, j, k = indices

            degree = self.ase_molecule.get_angle(i, j, k)
            ang = Angle(index=index,
                        atom_indices=indices,
                        degree=degree,
                        mask=[])
            mask = self.get_mask(ang)
            reaction_center = False

            angles.append(Angle(index=index,
                                atom_indices=indices,
                                degree=degree,
                                mask=mask,
                                reaction_center=reaction_center))
        self.angles = angles
        return self.angles

    def get_torsions(self):
        """
        A method for identifying all of the torsions in a conformer
        """
        torsion_list = []
        for bond1 in self.rdkit_molecule.GetBonds():
            atom1 = bond1.GetBeginAtom()
            atom2 = bond1.GetEndAtom()
            if atom1.IsInRing() or atom2.IsInRing():
                # Making sure that bond1 we're looking at are not in a ring
                continue

            bond_list1 = list(atom1.GetBonds())
            bond_list2 = list(atom2.GetBonds())

            if not len(bond_list1) > 1 and not len(bond_list2) > 1:
                # Making sure that there are more than one bond attached to
                # the atoms we're looking at
                continue

            # Getting the 0th and 3rd atom and insuring that atoms
            # attached to the 1st and 2nd atom are not terminal hydrogens
            # We also make sure that all of the atoms are properly bound
            # together

            # If the above are satisfied, we append a tuple of the torsion our
            # torsion_list
            got_atom0 = False
            got_atom3 = False

            for bond0 in bond_list1:
                atomX = bond0.GetOtherAtom(atom1)
                # if atomX.GetAtomicNum() == 1 and len(atomX.GetBonds()) == 1:
                # This means that we have a terminal hydrogen, skip this
                # NOTE: for H_abstraction TSs, a non teminal H should exist
                #    continue
                if atomX.GetIdx() != atom2.GetIdx():
                    got_atom0 = True
                    atom0 = atomX

            for bond2 in bond_list2:
                atomY = bond2.GetOtherAtom(atom2)
                # if atomY.GetAtomicNum() == 1 and len(atomY.GetBonds()) == 1:
                # This means that we have a terminal hydrogen, skip this
                #    continue
                if atomY.GetIdx() != atom1.GetIdx():
                    got_atom3 = True
                    atom3 = atomY

            if not (got_atom0 and got_atom3):
                # Making sure atom0 and atom3 were not found
                continue

            # Looking to make sure that all of the atoms are properly bonded to
            # eached
            if (
                "SINGLE" in str(
                    self.rdkit_molecule.GetBondBetweenAtoms(
                        atom1.GetIdx(),
                        atom2.GetIdx()).GetBondType()) and self.rdkit_molecule.GetBondBetweenAtoms(
                    atom0.GetIdx(),
                    atom1.GetIdx()) and self.rdkit_molecule.GetBondBetweenAtoms(
                    atom1.GetIdx(),
                    atom2.GetIdx()) and self.rdkit_molecule.GetBondBetweenAtoms(
                        atom2.GetIdx(),
                    atom3.GetIdx())):

                torsion_tup = (atom0.GetIdx(), atom1.GetIdx(),
                               atom2.GetIdx(), atom3.GetIdx())

                already_in_list = False
                for torsion_entry in torsion_list:
                    a, b, c, d = torsion_entry
                    e, f, g, h = torsion_tup

                    if (b, c) == (f, g) or (b, c) == (g, f):
                        already_in_list = True

                if not already_in_list:
                    torsion_list.append(torsion_tup)

        torsions = []
        for index, indices in enumerate(torsion_list):
            i, j, k, l = indices

            dihedral = self.ase_molecule.get_dihedral(i, j, k, l)
            tor = Torsion(index=index,
                          atom_indices=indices,
                          dihedral=dihedral,
                          mask=[])
            mask = self.get_mask(tor)
            reaction_center = False

            torsions.append(Torsion(index=index,
                                    atom_indices=indices,
                                    dihedral=dihedral,
                                    mask=mask,
                                    reaction_center=reaction_center))

        self.torsions = torsions
        return self.torsions

    def get_cistrans(self):
        """
        A method for identifying all possible cistrans bonds in a molecule
        """
        torsion_list = []
        cistrans_list = []
        for bond1 in self.rdkit_molecule.GetBonds():
            atom1 = bond1.GetBeginAtom()
            atom2 = bond1.GetEndAtom()
            if atom1.IsInRing() or atom2.IsInRing():
                # Making sure that bond1 we're looking at are not in a ring
                continue

            bond_list1 = list(atom1.GetBonds())
            bond_list2 = list(atom2.GetBonds())

            if not len(bond_list1) > 1 and not len(bond_list2) > 1:
                # Making sure that there are more than one bond attached to
                # the atoms we're looking at
                continue

            # Getting the 0th and 3rd atom and insuring that atoms
            # attached to the 1st and 2nd atom are not terminal hydrogens
            # We also make sure that all of the atoms are properly bound
            # together

            # If the above are satisfied, we append a tuple of the torsion our
            # torsion_list
            got_atom0 = False
            got_atom3 = False

            for bond0 in bond_list1:
                atomX = bond0.GetOtherAtom(atom1)
                # if atomX.GetAtomicNum() == 1 and len(atomX.GetBonds()) == 1:
                # This means that we have a terminal hydrogen, skip this
                # NOTE: for H_abstraction TSs, a non teminal H should exist
                #    continue
                if atomX.GetIdx() != atom2.GetIdx():
                    got_atom0 = True
                    atom0 = atomX

            for bond2 in bond_list2:
                atomY = bond2.GetOtherAtom(atom2)
                # if atomY.GetAtomicNum() == 1 and len(atomY.GetBonds()) == 1:
                # This means that we have a terminal hydrogen, skip this
                #    continue
                if atomY.GetIdx() != atom1.GetIdx():
                    got_atom3 = True
                    atom3 = atomY

            if not (got_atom0 and got_atom3):
                # Making sure atom0 and atom3 were not found
                continue

            # Looking to make sure that all of the atoms are properly bonded to
            # eached
            if (
                "DOUBLE" in str(
                    self.rdkit_molecule.GetBondBetweenAtoms(
                        atom1.GetIdx(),
                        atom2.GetIdx()).GetBondType()) and self.rdkit_molecule.GetBondBetweenAtoms(
                    atom0.GetIdx(),
                    atom1.GetIdx()) and self.rdkit_molecule.GetBondBetweenAtoms(
                    atom1.GetIdx(),
                    atom2.GetIdx()) and self.rdkit_molecule.GetBondBetweenAtoms(
                        atom2.GetIdx(),
                    atom3.GetIdx())):

                torsion_tup = (atom0.GetIdx(), atom1.GetIdx(),
                               atom2.GetIdx(), atom3.GetIdx())

                already_in_list = False
                for torsion_entry in torsion_list:
                    a, b, c, d = torsion_entry
                    e, f, g, h = torsion_tup

                    if (b, c) == (f, g) or (b, c) == (g, f):
                        already_in_list = True

                if not already_in_list:
                    cistrans_list.append(torsion_tup)

        cistrans = []

        for ct_index, indices in enumerate(cistrans_list):
            i, j, k, l = indices

            b0 = self.rdkit_molecule.GetBondBetweenAtoms(i, j)
            b1 = self.rdkit_molecule.GetBondBetweenAtoms(j, k)
            b2 = self.rdkit_molecule.GetBondBetweenAtoms(k, l)

            b0.SetBondDir(Chem.BondDir.ENDUPRIGHT)
            b2.SetBondDir(Chem.BondDir.ENDDOWNRIGHT)

            Chem.AssignStereochemistry(self.rdkit_molecule, force=True)

            if "STEREOZ" in str(b1.GetStereo()):
                if round(self.ase_molecule.get_dihedral(i, j, k, l), -1) == 0:
                    atom = self.rdkit_molecule.GetAtomWithIdx(k)
                    bonds = atom.GetBonds()
                    for bond in bonds:
                        indexes = [
                            bond.GetBeginAtomIdx(),
                            bond.GetEndAtomIdx()]
                        if not ((sorted([j, k]) == sorted(indexes)) or (
                                sorted([k, l]) == sorted(indexes))):
                            break

                    for index in indexes:
                        if not (index in indices):
                            l = index
                            break

                indices = [i, j, k, l]
                stero = "Z"

            else:
                if round(
                    self.ase_molecule.get_dihedral(
                        i, j, k, l), -1) == 180:
                    atom = self.rdkit_molecule.GetAtomWithIdx(k)
                    bonds = atom.GetBonds()
                    for bond in bonds:
                        indexes = [
                            bond.GetBeginAtomIdx(),
                            bond.GetEndAtomIdx()]
                        if not ((sorted([j, k]) == sorted(indexes)) or (
                                sorted([k, l]) == sorted(indexes))):
                            break

                    for index in indexes:
                        if not (index in indices):
                            l = index
                            break

                indices = [i, j, k, l]
                stero = "E"

            dihedral = self.ase_molecule.get_dihedral(i, j, k, l)
            tor = CisTrans(index=ct_index,
                           atom_indices=indices,
                           dihedral=dihedral,
                           mask=[],
                           stero=stero)
            mask = self.get_mask(tor)
            reaction_center = False

            cistrans.append(CisTrans(index=ct_index,
                                     atom_indices=indices,
                                     dihedral=dihedral,
                                     mask=mask,
                                     stero=stero
                                     )
                            )

        self.cistrans = cistrans
        return self.cistrans

    def get_mask(self, geometry):
        """
        Getting the right hand mask for a geometry object:

        - self: an AutoTST Conformer object
        - geometry: a Bond, Angle, Dihedral, or Torsion object 


        """

        rdkit_atoms = self.rdkit_molecule.GetAtoms()
        if (isinstance(geometry, autotst.geometry.Torsion) or
                isinstance(geometry, autotst.geometry.CisTrans)):

            L1, L0, R0, R1 = geometry.atom_indices

            # trying to get the left hand side of this torsion
            LHS_atoms_index = [L0, L1]
            RHS_atoms_index = [R0, R1]

        elif isinstance(geometry, autotst.geometry.Angle):
            a1, a2, a3 = geometry.atom_indices
            LHS_atoms_index = [a2, a1]
            RHS_atoms_index = [a2, a3]

        elif isinstance(geometry, autotst.geometry.Bond):
            a1, a2 = geometry.atom_indices
            LHS_atoms_index = [a1]
            RHS_atoms_index = [a2]

        complete_RHS = False
        i = 0
        atom_index = RHS_atoms_index[0]
        while complete_RHS is False:
            try:
                RHS_atom = rdkit_atoms[atom_index]
                for neighbor in RHS_atom.GetNeighbors():
                    if (neighbor.GetIdx() in RHS_atoms_index) or (
                            neighbor.GetIdx() in LHS_atoms_index):
                        continue
                    else:
                        RHS_atoms_index.append(neighbor.GetIdx())
                i += 1
                atom_index = RHS_atoms_index[i]

            except IndexError:
                complete_RHS = True

        mask = [index in RHS_atoms_index for index in range(
            len(self.ase_molecule))]

        return mask

    def get_chiral_centers(self):
        """
        A method to identify
        """

        centers = rdkit.Chem.FindMolChiralCenters(
            self.rdkit_molecule, includeUnassigned=True)
        chiral_centers = []

        for index, center in enumerate(centers):
            atom_index, chirality = center

            chiral_centers.append(
                ChiralCenter(
                    index=index,
                    atom_index=atom_index,
                    chirality=chirality))

        self.chiral_centers = chiral_centers
        return self.chiral_centers

    def get_geometries(self):
        """
        A helper method to obtain all geometry things
        """

        self.bonds = self.get_bonds()
        self.angles = self.get_angles()
        self.torsions = self.get_torsions()
        self.cistrans = self.get_cistrans()
        self.chiral_centers = self.get_chiral_centers()

        return (
            self.bonds,
            self.angles,
            self.torsions,
            self.cistrans,
            self.chiral_centers)

    def update_coords(self):
        """
        A function that creates distance matricies for the RMG, ASE, and RDKit molecules and finds which
        (if any) are different. If one is different, this will update the coordinates of the other two
        with the different one. If all three are different, nothing will happen. If all are the same,
        nothing will happen.
        """
        rdkit_dm = rdkit.Chem.rdmolops.Get3DDistanceMatrix(self.rdkit_molecule)
        ase_dm = self.ase_molecule.get_all_distances()
        l = len(self.rmg_molecule.atoms)
        rmg_dm = np.zeros((l, l))

        for i, atom_i in enumerate(self.rmg_molecule.atoms):
            for j, atom_j in enumerate(self.rmg_molecule.atoms):
                rmg_dm[i][j] = np.linalg.norm(atom_i.coords - atom_j.coords)

        d1 = round(abs(rdkit_dm - ase_dm).max(), 3)
        d2 = round(abs(rdkit_dm - rmg_dm).max(), 3)
        d3 = round(abs(ase_dm - rmg_dm).max(), 3)

        if np.all(np.array([d1, d2, d3]) > 0):
            return False, None

        if np.any(np.array([d1, d2, d3]) > 0):
            if d1 == 0:
                diff = "rmg"
                self.update_coords_from("rmg")
            elif d2 == 0:
                diff = "ase"
                self.update_coords_from("ase")
            else:
                diff = "rdkit"
                self.update_coords_from("rdkit")

            return True, diff
        else:
            return True, None

    def update_coords_from(self, mol_type="ase"):
        """
        A method to update the coordinates of the RMG, RDKit, and ASE objects with a chosen object.
        """

        possible_mol_types = ["ase", "rmg", "rdkit"]

        assert (mol_type.lower() in possible_mol_types), "Please specifiy a valid mol type. Valid types are {}".format(
            possible_mol_types)

        if mol_type.lower() == "rmg":
            conf = self.rdkit_molecule.GetConformers()[0]
            ase_atoms = []
            for i, atom in enumerate(self.rmg_molecule.atoms):
                x, y, z = atom.coords
                symbol = atom.symbol

                conf.SetAtomPosition(i, [x, y, z])

                ase_atoms.append(Atom(symbol=symbol, position=(x, y, z)))

            self.ase_molecule = Atoms(ase_atoms)
            # self.calculate_symmetry_number()

        elif mol_type.lower() == "ase":
            conf = self.rdkit_molecule.GetConformers()[0]
            for i, position in enumerate(self.ase_molecule.get_positions()):
                self.rmg_molecule.atoms[i].coords = position
                conf.SetAtomPosition(i, position)

            # self.calculate_symmetry_number()

        elif mol_type.lower() == "rdkit":

            mol_list = AllChem.MolToMolBlock(self.rdkit_molecule).split('\n')
            for i, atom in enumerate(self.rmg_molecule.atoms):
                j = i + 4
                coords = mol_list[j].split()[:3]
                for k, coord in enumerate(coords):
                    coords[k] = float(coord)
                atom.coords = np.array(coords)

            self.get_ase_mol()
            # self.calculate_symmetry_number()

    def set_bond_length(self, bond_index, length):
        """
        This is a method to set bond lengths
        Variabels:
        - bond_index (int): the index of the bond you want to edit
        - length (float, int): the distance you want to set the bond (in angstroms)
        """

        assert isinstance(length, (float, int))

        matched = False
        for bond in self.bonds:
            if bond.index == bond_index:
                matched = True
                break

        if not matched:
            logging.info("Angle index provided is out of range. Nothing was changed.")
            return self

        i, j = bond.atom_indices
        self.ase_molecule.set_distance(
            a0=i,
            a1=j,
            distance=length,
            mask=bond.mask,
            fix=0
        )

        bond.length = length

        self.update_coords_from(mol_type="ase")
        return self

    def set_angle(self, angle_index, angle):
        """
        A method that will set the angle of an Angle object accordingly
        """

        assert isinstance(
            angle, (int, float)), "Plese provide a float or an int for the angle"

        matched = False
        for a in self.angles:
            if a.index == angle_index:
                matched = True
                break

        if not matched:
            logging.info("Angle index provided is out of range. Nothing was changed.")
            return self

        i, j, k = a.atom_indices
        self.ase_molecule.set_angle(
            a1=i,
            a2=j,
            a3=k,
            angle=angle,
            mask=a.mask
        )

        a.degree = angle

        self.update_coords_from(mol_type="ase")

        return self

    def set_torsion(self, torsion_index, dihedral):
        """
        A method that will set the diehdral angle of a Torsion object accordingly.
        """

        assert isinstance(
            dihedral, (int, float)), "Plese provide a float or an int for the diehdral angle"

        matched = False
        for torsion in self.torsions:
            if torsion.index == torsion_index:
                matched = True
                break

        if not matched:
            logging.info("Torsion index provided is out of range. Nothing was changed.")
            return self

        i, j, k, l = torsion.atom_indices
        self.ase_molecule.set_dihedral(
            a1=i,
            a2=j,
            a3=k,
            a4=l,
            angle=dihedral,
            mask=torsion.mask
        )
        torsion.dihedral = dihedral

        self.update_coords_from(mol_type="ase")

        return self

    def set_cistrans(self, cistrans_index, stero="E"):
        """
        A module that will set a corresponding cistrans bond to the proper E/Z config
        """

        assert stero.upper() in [
            "E", "Z"], "Please specify a valid stero direction."

        matched = False
        for cistrans in self.cistrans:
            if cistrans.index == cistrans_index:
                matched = True
                break

        if not matched:
            logging.info("CisTrans index provided is out of range. Nothing was changed.")
            return self

        if cistrans.stero == stero.upper():
            self.update_coords_from("ase")
            return self

        else:
            cistrans.stero = stero.upper()
            i, j, k, l = cistrans.atom_indices
            self.ase_molecule.rotate_dihedral(
                a1=i,
                a2=j,
                a3=k,
                a4=l,
                angle=float(180),
                mask=cistrans.mask
            )
            cistrans.stero = stero.upper()

            self.update_coords_from(mol_type="ase")
            return self

    def set_chirality(self, chiral_center_index, stero="R"):
        """
        A module that can set the orientation of a chiral center.
        """
        assert stero.upper() in ["R", "S"], "Specify a valid stero orientation"

        centers_dict = {
            'R': Chem.rdchem.ChiralType.CHI_TETRAHEDRAL_CW,
            'S': Chem.rdchem.ChiralType.CHI_TETRAHEDRAL_CCW
        }

        assert isinstance(chiral_center_index,
                          int), "Please provide an integer for the index"

        rdmol = self.rdkit_molecule.__copy__()

        match = False
        for chiral_center in self.chiral_centers:
            if chiral_center.index == chiral_center_index:
                match = True
                break

        if not match:
            logging.info("ChiralCenter index provided is out of range. Nothing was changed")
            return self

        rdmol.GetAtomWithIdx(chiral_center.atom_index).SetChiralTag(
            centers_dict[stero.upper()])

        rdkit.Chem.rdDistGeom.EmbedMolecule(rdmol)

        old_torsions = self.torsions[:] + self.cistrans[:]

        self.rdkit_molecule = rdmol
        self.update_coords_from(mol_type="rdkit")

        # Now resetting dihedral angles in case if they changed.

        for torsion in old_torsions:
            i, j, k, l = torsion.atom_indices

            self.ase_molecule.set_dihedral(
                a1=i,
                a2=j,
                a3=k,
                a4=l,
                mask=torsion.mask,
                angle=torsion.dihedral,
            )

        self.update_coords_from(mol_type="ase")

        return self

    def calculate_symmetry_number(self):
        from rmgpy.qm.symmetry import PointGroupCalculator
        from rmgpy.qm.qmdata import QMData

        atom_numbers = self.ase_molecule.get_atomic_numbers()
        coordinates = self.ase_molecule.get_positions()

        qmdata = QMData(
            groundStateDegeneracy=1,  # Only needed to check if valid QMData
            numberOfAtoms=len(atom_numbers),
            atomicNumbers=atom_numbers,
            atomCoords=(coordinates, str('angstrom')),
            energy=(0.0, str('kcal/mol'))  # Only needed to avoid error
        )
        settings = type(str(''), (), dict(symmetryPath=str(
            'symmetry'), scratchDirectory="."))()  # Creates anonymous class
        pgc = PointGroupCalculator(settings, self.smiles, qmdata)
        pg = pgc.calculate()
        #os.remove("{}.symm".format(self.smiles))

        if pg is not None:
            symmetry_number = pg.symmetryNumber
        else:
            symmetry_number = 1

        return symmetry_number
예제 #6
0
class AutoTST_Molecule():
    """
    A class that allows for one to create RMG, RDKit and ASE
    molecules from a single string with identical atom indicies

    Inputs:
    * smiles (str): a SMILES string that describes the molecule of interest
    * rmg_molecule (RMG Molecule object): an rmg molecule that we can extract information from
    """
    def __init__(self, smiles=None, rmg_molecule=None):

        assert (
            smiles or rmg_molecule
        ), "Please provide a SMILES string and / or an RMG Molecule object."

        if smiles and rmg_molecule:
            assert rmg_molecule.isIsomorphic(
                Molecule(SMILES=smiles
                         )), "SMILES string did not match RMG Molecule object"
            self.smiles = smiles
            self.rmg_molecule = rmg_molecule

        elif rmg_molecule:
            self.rmg_molecule = rmg_molecule
            self.smiles = rmg_molecule.toSMILES()

        else:
            self.smiles = smiles
            self.rmg_molecule = Molecule(SMILES=smiles)

        self.get_rdkit_molecule()
        self.set_rmg_coords("RDKit")
        self.get_ase_molecule()
        self.get_torsions()
        self.get_angles()
        self.get_bonds()

    def __repr__(self):
        return '<AutoTST Molecule "{0}">'.format(self.smiles)

    def get_rdkit_molecule(self):
        """
        A method to create an RDKit Molecule from the rmg_molecule.
        Indicies will be the same as in the RMG Molecule
        """

        RDMol = self.rmg_molecule.toRDKitMol(removeHs=False)

        rdkit.Chem.AllChem.EmbedMolecule(RDMol)

        self.rdkit_molecule = RDMol

    def get_ase_molecule(self):
        """
        A method to create an ASE Molecule from the rdkit_molecule.
        Indicies will be the same as in the RMG and RDKit Molecule.
        """
        mol_list = AllChem.MolToMolBlock(self.rdkit_molecule).split('\n')
        ase_atoms = []
        for i, line in enumerate(mol_list):

            if i > 3:
                try:
                    atom0, atom1, bond, rest = line
                    atom0 = int(atom0)
                    atom0 = int(atom1)
                    bond = float(bond)

                except ValueError:
                    try:
                        x, y, z, symbol = line.split()[0:4]
                        x = float(x)
                        y = float(y)
                        z = float(z)

                        ase_atoms.append(
                            Atom(symbol=symbol, position=(x, y, z)))
                    except:
                        continue

        self.ase_molecule = Atoms(ase_atoms)
        return self.ase_molecule

    def view_mol(self):
        """
        A method designed to create a 3D figure of the AutoTST_Molecule with py3Dmol from the rdkit_molecule
        """
        mb = Chem.MolToMolBlock(self.rdkit_molecule)
        p = py3Dmol.view(width=400, height=400)
        p.addModel(mb, "sdf")
        p.setStyle({'stick': {}})
        p.setBackgroundColor('0xeeeeee')
        p.zoomTo()
        return p.show()

#############################################################################

    def get_bonds(self):

        rdmol_copy = self.rdkit_molecule
        bond_list = []
        for bond in rdmol_copy.GetBonds():
            bond_list.append((bond.GetBeginAtomIdx(), bond.GetEndAtomIdx()))

        bonds = []
        for indices in bond_list:
            i, j = indices

            length = self.ase_molecule.get_distance(i, j)

            reaction_center = "No"

            bond = Bond(indices=indices,
                        length=length,
                        reaction_center=reaction_center)

            bonds.append(bond)
        self.bonds = bonds
        return self.bonds

    def get_angles(self):

        rdmol_copy = self.rdkit_molecule

        angle_list = []
        for atom1 in rdmol_copy.GetAtoms():
            for atom2 in atom1.GetNeighbors():
                for atom3 in atom2.GetNeighbors():
                    if atom1.GetIdx() == atom3.GetIdx():
                        continue

                    to_add = (atom1.GetIdx(), atom2.GetIdx(), atom3.GetIdx())
                    if (to_add in angle_list) or (tuple(reversed(to_add))
                                                  in angle_list):
                        continue
                    angle_list.append(to_add)

        angles = []
        for indices in angle_list:
            i, j, k = indices

            degree = self.ase_molecule.get_angle(i, j, k)
            ang = Angle(indices=indices,
                        degree=degree,
                        left_mask=[],
                        right_mask=[])
            left_mask = self.get_left_mask(ang)
            right_mask = self.get_right_mask(ang)

            reaction_center = "No"

            angles.append(
                Angle(indices, degree, left_mask, right_mask, reaction_center))
        self.angles = angles
        return self.angles

    def get_torsions(self):
        rdmol_copy = self.rdkit_molecule

        torsion_list = []
        cistrans_list = []
        for bond1 in rdmol_copy.GetBonds():
            atom1 = bond1.GetBeginAtom()
            atom2 = bond1.GetEndAtom()
            if atom1.IsInRing() or atom2.IsInRing():
                # Making sure that bond1 we're looking at are not in a ring
                continue

            bond_list1 = list(atom1.GetBonds())
            bond_list2 = list(atom2.GetBonds())

            if not len(bond_list1) > 1 and not len(bond_list2) > 1:
                # Making sure that there are more than one bond attached to
                # the atoms we're looking at
                continue

            # Getting the 0th and 3rd atom and insuring that atoms
            # attached to the 1st and 2nd atom are not terminal hydrogens
            # We also make sure that all of the atoms are properly bound together

            # If the above are satisfied, we append a tuple of the torsion our torsion_list
            got_atom0 = False
            got_atom3 = False

            for bond0 in bond_list1:
                atomX = bond0.GetOtherAtom(atom1)
                # if atomX.GetAtomicNum() == 1 and len(atomX.GetBonds()) == 1:
                # This means that we have a terminal hydrogen, skip this
                # NOTE: for H_abstraction TSs, a non teminal H should exist
                #    continue
                if atomX.GetIdx() != atom2.GetIdx():
                    got_atom0 = True
                    atom0 = atomX

            for bond2 in bond_list2:
                atomY = bond2.GetOtherAtom(atom2)
                # if atomY.GetAtomicNum() == 1 and len(atomY.GetBonds()) == 1:
                # This means that we have a terminal hydrogen, skip this
                #    continue
                if atomY.GetIdx() != atom1.GetIdx():
                    got_atom3 = True
                    atom3 = atomY

            if not (got_atom0 and got_atom3):
                # Making sure atom0 and atom3 were not found
                continue

            # Looking to make sure that all of the atoms are properly bonded to eached
            if ("SINGLE" in str(
                    rdmol_copy.GetBondBetweenAtoms(
                        atom1.GetIdx(), atom2.GetIdx()).GetBondType())
                    and rdmol_copy.GetBondBetweenAtoms(atom0.GetIdx(),
                                                       atom1.GetIdx())
                    and rdmol_copy.GetBondBetweenAtoms(atom1.GetIdx(),
                                                       atom2.GetIdx())
                    and rdmol_copy.GetBondBetweenAtoms(atom2.GetIdx(),
                                                       atom3.GetIdx())):

                torsion_tup = (atom0.GetIdx(), atom1.GetIdx(), atom2.GetIdx(),
                               atom3.GetIdx())

                already_in_list = False
                for torsion_entry in torsion_list:
                    a, b, c, d = torsion_entry
                    e, f, g, h = torsion_tup

                    if (b, c) == (f, g) or (b, c) == (g, f):
                        already_in_list = True

                if not already_in_list:
                    torsion_list.append(torsion_tup)

            if ("DOUBLE" in str(
                    rdmol_copy.GetBondBetweenAtoms(
                        atom1.GetIdx(), atom2.GetIdx()).GetBondType())
                    and rdmol_copy.GetBondBetweenAtoms(atom0.GetIdx(),
                                                       atom1.GetIdx())
                    and rdmol_copy.GetBondBetweenAtoms(atom1.GetIdx(),
                                                       atom2.GetIdx())
                    and rdmol_copy.GetBondBetweenAtoms(atom2.GetIdx(),
                                                       atom3.GetIdx())):

                torsion_tup = (atom0.GetIdx(), atom1.GetIdx(), atom2.GetIdx(),
                               atom3.GetIdx())

                already_in_list = False
                for torsion_entry in torsion_list:
                    a, b, c, d = torsion_entry
                    e, f, g, h = torsion_tup

                    if (b, c) == (f, g) or (b, c) == (g, f):
                        already_in_list = True

                if not already_in_list:
                    cistrans_list.append(torsion_tup)

        torsions = []
        cistrans = []
        for indices in torsion_list:
            i, j, k, l = indices

            dihedral = self.ase_molecule.get_dihedral(i, j, k, l)
            tor = Torsion(indices=indices,
                          dihedral=dihedral,
                          left_mask=[],
                          right_mask=[])
            left_mask = self.get_left_mask(tor)
            right_mask = self.get_right_mask(tor)
            reaction_center = "No"

            torsions.append(
                Torsion(indices, dihedral, left_mask, right_mask,
                        reaction_center))

        for indices in cistrans_list:
            i, j, k, l = indices

            dihedral = self.ase_molecule.get_dihedral(i, j, k, l)
            tor = CisTrans(indices=indices,
                           dihedral=dihedral,
                           left_mask=[],
                           right_mask=[])
            left_mask = self.get_left_mask(tor)
            right_mask = self.get_right_mask(tor)
            reaction_center = "No"

            cistrans.append(
                CisTrans(indices, dihedral, left_mask, right_mask,
                         reaction_center))
        self.torsions = torsions
        self.cistrans = cistrans
        return self.torsions

    def get_right_mask(self, torsion_or_angle):

        rdmol_copy = self.rdkit_molecule

        rdkit_atoms = rdmol_copy.GetAtoms()

        if (isinstance(torsion_or_angle, autotst.geometry.Torsion)
                or isinstance(torsion_or_angle, autotst.geometry.CisTrans)):

            L1, L0, R0, R1 = torsion_or_angle.indices

            # trying to get the left hand side of this torsion
            LHS_atoms_index = [L0, L1]
            RHS_atoms_index = [R0, R1]

        elif isinstance(torsion_or_angle, autotst.geometry.Angle):
            a1, a2, a3 = torsion_or_angle.indices
            LHS_atoms_index = [a2, a1]
            RHS_atoms_index = [a2, a3]

        complete_RHS = False
        i = 0
        atom_index = RHS_atoms_index[0]
        while complete_RHS is False:
            try:
                RHS_atom = rdkit_atoms[atom_index]
                for neighbor in RHS_atom.GetNeighbors():
                    if (neighbor.GetIdx()
                            in RHS_atoms_index) or (neighbor.GetIdx()
                                                    in LHS_atoms_index):
                        continue
                    else:
                        RHS_atoms_index.append(neighbor.GetIdx())
                i += 1
                atom_index = RHS_atoms_index[i]

            except IndexError:
                complete_RHS = True

        right_mask = [
            index in RHS_atoms_index for index in range(len(self.ase_molecule))
        ]

        return right_mask

    def get_left_mask(self, torsion_or_angle):

        rdmol_copy = self.rdkit_molecule

        rdkit_atoms = rdmol_copy.GetAtoms()

        if (isinstance(torsion_or_angle, autotst.geometry.Torsion)
                or isinstance(torsion_or_angle, autotst.geometry.CisTrans)):

            L1, L0, R0, R1 = torsion_or_angle.indices

            # trying to get the left hand side of this torsion
            LHS_atoms_index = [L0, L1]
            RHS_atoms_index = [R0, R1]

        elif isinstance(torsion_or_angle, autotst.geometry.Angle):
            a1, a2, a3 = torsion_or_angle.indices
            LHS_atoms_index = [a2, a1]
            RHS_atoms_index = [a2, a3]

        complete_LHS = False
        i = 0
        atom_index = LHS_atoms_index[0]
        while complete_LHS is False:
            try:
                LHS_atom = rdkit_atoms[atom_index]
                for neighbor in LHS_atom.GetNeighbors():
                    if (neighbor.GetIdx()
                            in LHS_atoms_index) or (neighbor.GetIdx()
                                                    in RHS_atoms_index):
                        continue
                    else:
                        LHS_atoms_index.append(neighbor.GetIdx())
                i += 1
                atom_index = LHS_atoms_index[i]

            except IndexError:
                complete_LHS = True

        left_mask = [
            index in LHS_atoms_index for index in range(len(self.ase_molecule))
        ]

        return left_mask

    def set_rmg_coords(self, molecule_base):

        if molecule_base == "RDKit":
            mol_list = AllChem.MolToMolBlock(self.rdkit_molecule).split('\n')
            for i, atom in enumerate(self.rmg_molecule.atoms):
                j = i + 4
                coords = mol_list[j].split()[:3]
                for k, coord in enumerate(coords):
                    coords[k] = float(coord)
                atom.coords = np.array(coords)

        elif molecule_base == "ASE":
            for i, position in enumerate(self.ase_molecule.get_positions()):
                self.rmg_molecule.atoms[i].coords = position

    def update_from_rdkit_mol(self):

        # In order to update the ase molecule you simply need to rerun the get_ase_molecule method
        self.get_ase_molecule()
        self.set_rmg_coords("RDKit")
        # Getting the new torsion angles
        self.get_torsions()

    def update_from_ase_mol(self):

        self.set_rmg_coords("ASE")
        # setting the geometries of the rdkit molecule
        positions = self.ase_molecule.get_positions()
        conf = self.rdkit_molecule.GetConformers()[0]
        for i, atom in enumerate(self.rdkit_molecule.GetAtoms()):
            conf.SetAtomPosition(i, positions[i])

        # Getting the new torsion angles
        self.get_torsions()

    def update_from_rmg_mol(self):

        conf = self.rdkit_molecule.GetConformers()[0]
        ase_atoms = []
        for i, atom in enumerate(self.rmg_molecule.atoms):
            x, y, z = atom.coords
            symbol = atom.symbol

            conf.SetAtomPosition(i, [x, y, z])

            ase_atoms.append(Atom(symbol=symbol, position=(x, y, z)))

        self.ase_molecule = Atoms(ase_atoms)

        # Getting the new torsion angles
        self.get_torsions()
예제 #7
0
mol.set_calculator(calc)

fix = {fix}
change = {change}

bonds = []
angles = []
dihedrals = []
for fi in fix:
    if len(fi) == 2:
        #careful: atom indices in the fix lists start at 1
        bondlength = mol.get_distance(fi[0] - 1, fi[1] - 1)
        bonds.append([bondlength,[fi[0] - 1, fi[1] - 1]])
    if len(fi) == 3:
        #careful: atom indices in the fix lists start at 1
        angle = mol.get_angle(fi[0]-1,fi[1]-1,fi[2]-1) * np.pi / 180
        angles.append([angle,[fi[0]-1,fi[1]-1,fi[2]-1]])
    if len(fi) == 4:
        #careful: atom indices in the fix lists start at 1
        dihed = mol.get_dihedral(fi[0]-1,fi[1]-1,fi[2]-1,fi[3]-1) * np.pi / 180
        dihedrals.append([dihed,[fi[0]-1,fi[1]-1,fi[2]-1,fi[3]-1]])
for ci in change:
    if len(ci) == 3:
        #careful: atom indices in the fix lists start at 1
        bondlength = ci[2]
        bonds.append([bondlength,[ci[0] - 1, ci[1] - 1]])
    if len(ci) == 4:
        #careful: atom indices in the fix lists start at 1
        angle = ci[3] * np.pi / 180
        angles.append([angle,[ci[0]-1,ci[1]-1,ci[2]-1]])
    if len(ci) == 5:
예제 #8
0
from ase import Atoms
import numpy as np

atoms = Atoms(['O', 'H', 'H'],
              positions=[[0., 0., 0.119262], [0., 0.763239, -0.477047],
                         [0., -0.763239, -0.477047]])

# Angle no pbc
assert abs(atoms.get_angle(1, 0, 2) - 104) < 1e-3

atoms.set_cell([2, 2, 2])

# Across different pbcs
atoms.set_pbc([True, False, True])
atoms.wrap()
assert abs(atoms.get_angle(1, 0, 2, mic=True) - 104) < 1e-3

# Across all True pbc
atoms.set_pbc(True)
atoms.wrap()
assert abs(atoms.get_angle(1, 0, 2, mic=True) - 104) < 1e-3

# Change Angle
old = atoms.get_angle(1, 0, 2, mic=False)
atoms.set_angle(1, 0, 2, -10, indices=[2], add=True)
new = atoms.get_angle(1, 0, 2, mic=False)
diff = old - new - 10
assert abs(diff) < 10e-3

#don't actually change angle using indices
old = atoms.get_angle(1, 0, 2, mic=False)
#apply the constraints:
fix = {fix}
change = {change}
release = {release}

bonds = []
angles = []
dihedrals = []

for f in fix:
    if len(f) == 3:
        dist = mol.get_distance(f[0] - 1, f[1] -
                                1)  #ase enumerates atoms starting from zero
        bonds.append([dist, [f[0] - 1, f[1] - 1]])
    if len(f) == 3:
        angle = mol.get_angle(f[0] - 1, f[1] - 1, f[2] -
                              1)  #ase enumerates atoms starting from zero
        angle *= pi / 180.
        angles.append([angle, [f[0] - 1, f[1] - 1, f[2] - 1]])
    if len(f) == 4:
        dih = mol.get_dihedral(f[0] - 1, f[1] - 1, f[2] - 1, f[3] -
                               1)  #ase enumerates atoms starting from zero
        dih *= pi / 180.
        dihedrals.append([dih, [f[0] - 1, f[1] - 1, f[2] - 1, f[3] - 1]])
for c in change:
    if len(c) == 3:
        bonds.append([c[2], [c[0] - 1, c[1] - 1]])
    if len(c) == 4:
        angle = c[3] * pi / 180.
        angles.append([angle, [c[0] - 1, c[1] - 1, c[2] - 1]])
    if len(c) == 5:
        dih = c[4] * pi / 180.
예제 #10
0
def Gradient(Elements, Image, ImageNo, GuessNo, output,
             dummy_variable):  #output is for labeling the process

    #Creates a directory for each image, at each stage

    omitoutput = os.system('mkdir -p  ./Molecule-%s/Image%s' %
                           (str(GuessNo), str(ImageNo)))
    os.chdir('Molecule-%s/Image%s' % (str(GuessNo), str(ImageNo)))

    #If a gradient has already been generated for a given image it will skip it
    SaveGradient = 'Gradient-%s-%s' % (str(GuessNo), str(ImageNo))

    os.system('ls --ignore \'INPUT*\' > CheckGradTemp')
    if SaveGradient in open('CheckGradTemp').read():
        os.system('rm CheckGradTemp')

        f1 = open('Gradient-%s-%s' % (str(GuessNo), str(ImageNo)), 'r')
        Ftemp = f1.readlines()
        F = []
        for i in range(0, len(Ftemp)):
            force = filter(None, Ftemp[i][2:-2].split(' '))
            Newline = []
            for k in range(0, len(force)):
                Newline.append(float(force[k]))
            F.append(Newline)

        print 'Gradient obtained for Guess No %s and Image No %s' % (
            str(GuessNo), str(ImageNo))
    else:
        os.system('rm CheckGradTemp')

        # Set up the molecule by specifying atomic positions and atomic number

        Molecule = Atoms(numbers=Elements, positions=Image, pbc=(0, 0, 0))
        write('Molecule-%s-%s-start.xyz' % (str(GuessNo), str(ImageNo)),
              Molecule)
        # Center the molecule in the cell with some vacuum around
        Molecule.center(vacuum=6.0)
        ##FIX:
        const = FixAtoms(mask=Molecule.positions[22, :])  #blah
        Molecule.set_constraint(const)  #HERE!!!

        # Run the relaxation for each energy shift, and print out the
        # corresponding total energy, bond length and angle
        starttime = time.time()
        calc = LAMMPS('Molecule',
                      parameters={
                          'pair_style': 'airebo 3.0 1 1',
                          'pair_coeff': ['* * ../../CH.airebo C H'],
                          'mass': ['1 12.0107', '2 1.00794']
                      },
                      tmp_dir='./',
                      keep_tmp_files=True,
                      no_data_file=False)
        #files = ['../CH.airebo'] \n min_style fire \n  unfix fix_nve','run': '1', , 'minimize': '10e-12 10e-14 100000 100000'

        Molecule.set_calculator(calc)

        F = Molecule.get_forces()
        #print calculation_required(Molecule, 'energy')
        E = Molecule.get_potential_energy()

        #print 'F-%s-%s' % (str(GuessNo), str(ImageNo)), 'is', F, 'type F is; ',type(F), np.shape(F)

        f2 = open(SaveGradient, 'w').write(str(F))
        f3 = open('Energy', 'w').write(str(E))

        AngleCNNC = Molecule.get_dihedral([3, 1, 0, 2])
        AngleCCNN = Molecule.get_dihedral([7, 3, 1, 0])
        AngleNNCC = Molecule.get_dihedral([1, 0, 2, 6])

        AngleCNN = Molecule.get_angle([3, 1, 0])
        AngleNNC = Molecule.get_angle([1, 0, 2])
        AngleCCN = Molecule.get_angle([7, 3, 1])

        f4 = open('CNNCandCCNNandNNCC', 'w').write(
            str(AngleCNNC) + '\t' + str(AngleCCNN) + '\t' + str(AngleNNCC))
        f5 = open('CNNandNNCandCCN', 'w').write(
            str(AngleCNN) + '\t' + str(AngleNNC) + '\t' + str(AngleCCN))


#endtime = time.time()
#walltime = endtime - starttime
#print 'Wall time: %.5f' % walltime
#print                                # Make the output more readable
#client.close()
    output.put((ImageNo, F))
예제 #11
0
def fix_cyclopropenyl(atoms: Atoms, mol: pybel.Molecule) -> Atoms:
    """Detect cyclopropenyl groups and assure they are planar.
    
    Args:
        atoms: Object holding the 3D positions
        mol: Object holidng the bonding information
    Returns:
        Version of atoms with the rings flattened
    """

    # Find cyclopropenyl groups
    smarts = pybel.Smarts('C1=C[C+]1')
    rings = smarts.findall(mol)
    if len(rings) == 0:
        return atoms  # no changes

    # For each ring, flatten it
    atoms = atoms.copy()
    g = get_bonding_graph(mol)
    for ring in rings:
        ring = tuple(x - 1 for x in rings[0])  # Pybel is 1-indexed

        # Get the normal of the ring
        normal = np.cross(*np.subtract(atoms.positions[ring[:2], :],
                                       atoms.positions[ring[2], :]))
        normal /= np.linalg.norm(normal)

        # Adjust the groups attached to each member of the ring
        for ring_atom in ring:
            # Get the ID of the group bonded to it
            bonded_atom = next(r for r in g[ring_atom] if r not in ring)

            # Determine the atoms that are part of that functional group
            h = g.copy()
            h.remove_edge(ring_atom, bonded_atom)
            a, b = nx.connected_components(h)
            mask = np.zeros((len(atoms), ), dtype=bool)
            if bonded_atom in a:
                mask[list(a)] = True
            else:
                mask[list(b)] = True

            # Get the rotation angle
            bond_vector = atoms.positions[bonded_atom, :] - atoms.positions[
                ring_atom, :]
            angle = np.dot(bond_vector, normal) / np.linalg.norm(bond_vector)
            rot_angle = np.arccos(angle) - np.pi / 2
            logger.debug(f'Rotating by {rot_angle} radians')

            # Perform the rotation
            rotation_axis = np.cross(bond_vector, normal)
            atoms._masked_rotate(atoms.positions[ring_atom], rotation_axis,
                                 rot_angle, mask)

            # make the atom at a 150 angle with the the ring too
            another_ring = next(r for r in ring if r != ring_atom)
            atoms.set_angle(another_ring,
                            ring_atom,
                            bonded_atom,
                            150,
                            mask=mask)
            assert np.isclose(
                atoms.get_angle(another_ring, ring_atom, bonded_atom),
                150).all()

            # Make sure it worked
            bond_vector = atoms.positions[bonded_atom, :] - atoms.positions[
                ring_atom, :]
            angle = np.dot(bond_vector, normal) / np.linalg.norm(bond_vector)
            final_angle = np.arccos(angle)
            assert np.isclose(final_angle, np.pi / 2).all()

        logger.info(
            f'Detected {len(rings)} cyclopropenyl rings. Ensured they are planar.'
        )
        return atoms
예제 #12
0
"Test that set_angle() and get_angle() in Atoms are consistent"

from ase import Atoms

atoms = Atoms(
    'HHCCHH',
    [[-1, 1, 0], [-1, -1, 0], [0, 0, 0], [1, 0, 0], [2, 1, 0], [2, -1, 0]])

list = [2, 3, 4]
theta = 0.1
old_angle = atoms.get_angle(list)
atoms.set_angle(list, old_angle + theta)
new_angle = atoms.get_angle(list)

assert abs(new_angle - (old_angle + theta)) < 1.0e-9
예제 #13
0
"Test that set_angle() and get_angle() in Atoms are consistent"

from ase import Atoms

atoms = Atoms('HHCCHH', [[-1, 1, 0], [-1, -1, 0], [0, 0, 0],
                        [1, 0, 0], [2, 1, 0], [2, -1, 0]])

list = [2, 3, 4]
theta = 0.1
old_angle = atoms.get_angle(list)
atoms.set_angle(list, old_angle + theta)
new_angle = atoms.get_angle(list)

assert abs(new_angle - (old_angle + theta)) < 1.0e-9
예제 #14
0
파일: atoms_angle.py 프로젝트: yfyh2013/ase
from ase import Atoms
import numpy as np

atoms = Atoms(['O', 'H', 'H'],
              positions=[[0., 0., 0.119262], [0., 0.763239, -0.477047],
                         [0., -0.763239, -0.477047]])

# Angle no pbc
assert abs(atoms.get_angle(1, 0, 2) - 104) < 1e-3

atoms.set_cell([2, 2, 2])

# Across different pbcs
atoms.set_pbc([True, False, True])
atoms.wrap()
assert abs(atoms.get_angle(1, 0, 2, mic=True) - 104) < 1e-3

# Across all True pbc
atoms.set_pbc(True)
atoms.wrap()
assert abs(atoms.get_angle(1, 0, 2, mic=True) - 104) < 1e-3

# Simple tetrahedron
tetra_pos = np.array([[0, 0, 0], [1, 0, 0], [.5, np.sqrt(3) * .5, 0],
                      [.5, np.sqrt(1 / 3.) * .5,
                       np.sqrt(2 / 3.)]])
atoms = Atoms(['H', 'H', 'H', 'H'], positions=tetra_pos - np.array([.2, 0, 0]))
angle = 70.5287793655
assert abs(atoms.get_dihedral(0, 1, 2, 3) - angle) < 1e-3

atoms.set_cell([3, 3, 3])