def _create_dodecane_acrylate_topology(self):
     if self._topology is None:
         topology = Topology()
         if self.box_vectors is not None:
             topology.setPeriodicBoxVectors(self.box_vectors)
         for chain_option in self.chains:
             id_to_sequence = chain_option.add_chain_to_topology(topology)
             self.id_to_sequence.update(id_to_sequence)
         for branched_chain_option in self.branched_chains:
             branched_chain_option.add_chain_to_topology(topology)
         for _ in range(self.numDodecane):
             dodecane_id = self._add_dodecane_to_topology(topology)
             self.id_to_sequence[dodecane_id] = "C12"
         for _ in range(self.numSqualane):
             squalane_id = self._add_squalane_to_topology(topology)
             self.id_to_sequence[squalane_id] = "squalane"
         self._topology = topology
Exemple #2
0
    def __init__(self, file, periodicBoxVectors=None, unitCellDimensions=None, includeDir=None, defines=None):
        """Load a top file.

        Parameters
        ----------
        file : str
            the name of the file to load
        periodicBoxVectors : tuple of Vec3=None
            the vectors defining the periodic box
        unitCellDimensions : Vec3=None
            the dimensions of the crystallographic unit cell.  For
            non-rectangular unit cells, specify periodicBoxVectors instead.
        includeDir : string=None
            A directory in which to look for other files included from the
            top file. If not specified, we will attempt to locate a gromacs
            installation on your system. When gromacs is installed in
            /usr/local, this will resolve to /usr/local/gromacs/share/gromacs/top
        defines : dict={}
            preprocessor definitions that should be predefined when parsing the file
         """
        if includeDir is None:
            includeDir = _defaultGromacsIncludeDir()
        self._includeDirs = (os.path.dirname(file), includeDir)
        # Most of the gromacs water itp files for different forcefields,
        # unless the preprocessor #define FLEXIBLE is given, don't define
        # bonds between the water hydrogen and oxygens, but only give the
        # constraint distances and exclusions.
        self._defines = OrderedDict()
        self._defines['FLEXIBLE'] = True
        self._genpairs = True
        if defines is not None:
            for define, value in defines.iteritems():
                self._defines[define] = value

        # Parse the file.

        self._currentCategory = None
        self._ifStack = []
        self._elseStack = []
        self._moleculeTypes = {}
        self._molecules = []
        self._currentMoleculeType = None
        self._atomTypes = {}
        self._bondTypes= {}
        self._angleTypes = {}
        self._dihedralTypes = {}
        self._implicitTypes = {}
        self._pairTypes = {}
        self._cmapTypes = {}
        self._processFile(file)

        # Create the Topology from it.

        top = Topology()
        ## The Topology read from the prmtop file
        self.topology = top
        if periodicBoxVectors is not None:
            if unitCellDimensions is not None:
                raise ValueError("specify either periodicBoxVectors or unitCellDimensions, but not both")
            top.setPeriodicBoxVectors(periodicBoxVectors)
        else:
            top.setUnitCellDimensions(unitCellDimensions)
        PDBFile._loadNameReplacementTables()
        for moleculeName, moleculeCount in self._molecules:
            if moleculeName not in self._moleculeTypes:
                raise ValueError("Unknown molecule type: "+moleculeName)
            moleculeType = self._moleculeTypes[moleculeName]
            if moleculeCount > 0 and moleculeType.has_virtual_sites:
                raise ValueError('Virtual sites not yet supported by Gromacs parsers')

            # Create the specified number of molecules of this type.

            for i in range(moleculeCount):
                atoms = []
                lastResidue = None
                c = top.addChain()
                for index, fields in enumerate(moleculeType.atoms):
                    resNumber = fields[2]
                    if resNumber != lastResidue:
                        lastResidue = resNumber
                        resName = fields[3]
                        if resName in PDBFile._residueNameReplacements:
                            resName = PDBFile._residueNameReplacements[resName]
                        r = top.addResidue(resName, c)
                        if resName in PDBFile._atomNameReplacements:
                            atomReplacements = PDBFile._atomNameReplacements[resName]
                        else:
                            atomReplacements = {}
                    atomName = fields[4]
                    if atomName in atomReplacements:
                        atomName = atomReplacements[atomName]

                    # Try to guess the element.

                    upper = atomName.upper()
                    if upper.startswith('CL'):
                        element = elem.chlorine
                    elif upper.startswith('NA'):
                        element = elem.sodium
                    elif upper.startswith('MG'):
                        element = elem.magnesium
                    else:
                        try:
                            element = elem.get_by_symbol(atomName[0])
                        except KeyError:
                            element = None
                    atoms.append(top.addAtom(atomName, element, r))

                # Add bonds to the topology

                for fields in moleculeType.bonds:
                    top.addBond(atoms[int(fields[0])-1], atoms[int(fields[1])-1])
Exemple #3
0
    def __init__(self, file):
        """Load a prmtop file."""
        top = Topology()
        ## The Topology read from the prmtop file
        self.topology = top
        self.elements = []

        # Load the prmtop file

        prmtop = amber_file_parser.PrmtopLoader(file)
        self._prmtop = prmtop

        # Add atoms to the topology

        PDBFile._loadNameReplacementTables()
        lastResidue = None
        c = top.addChain()
        for index in range(prmtop.getNumAtoms()):
            resNumber = prmtop.getResidueNumber(index)
            if resNumber != lastResidue:
                lastResidue = resNumber
                resName = prmtop.getResidueLabel(iAtom=index).strip()
                if resName in PDBFile._residueNameReplacements:
                    resName = PDBFile._residueNameReplacements[resName]
                r = top.addResidue(resName, c)
                if resName in PDBFile._atomNameReplacements:
                    atomReplacements = PDBFile._atomNameReplacements[resName]
                else:
                    atomReplacements = {}
            atomName = prmtop.getAtomName(index).strip()
            if atomName in atomReplacements:
                atomName = atomReplacements[atomName]

            # Get the element from the prmtop file if available
            if prmtop.has_atomic_number:
                try:
                    element = elem.Element.getByAtomicNumber(int(prmtop._raw_data['ATOMIC_NUMBER'][index]))
                except KeyError:
                    element = None
            else:
                # Try to guess the element from the atom name.

                upper = atomName.upper()
                if upper.startswith('CL'):
                    element = elem.chlorine
                elif upper.startswith('NA'):
                    element = elem.sodium
                elif upper.startswith('MG'):
                    element = elem.magnesium
                elif upper.startswith('ZN'):
                    element = elem.zinc
                else:
                    try:
                        element = elem.get_by_symbol(atomName[0])
                    except KeyError:
                        element = None

            top.addAtom(atomName, element, r)
            self.elements.append(element)

        # Add bonds to the topology

        atoms = list(top.atoms())
        for bond in prmtop.getBondsWithH():
            top.addBond(atoms[bond[0]], atoms[bond[1]])
        for bond in prmtop.getBondsNoH():
            top.addBond(atoms[bond[0]], atoms[bond[1]])

        # Set the periodic box size.

        if prmtop.getIfBox():
            box = prmtop.getBoxBetaAndDimensions()
            top.setPeriodicBoxVectors(computePeriodicBoxVectors(*(box[1:4] + box[0:1]*3)))
Exemple #4
0
    def remove_molecules(self, simulation_old, system_options, ensemble_options):
        topology_old = simulation_old.topology
        system_old = simulation_old.system
        state = simulation_old.context.getState(getPositions=True, getVelocities=True)
        positions_old = state.getPositions(asNumpy=True)
        velocities_old = state.getVelocities(asNumpy=True)
        periodic_box_vectors = state.getPeriodicBoxVectors(asNumpy=True)

        # randomly determine which molecules are removed
        removed_molecules = random.sample(range(topology_old.getNumChains()), self.numVoid)

        # create new topology and dictionary mapping old atom indices to new atom indices
        removed_atoms = []
        topology_new = Topology()
        old_to_new = {}
        atom_index_new = 0
        for chain_index, chain_old in enumerate(topology_old.chains()):
            if chain_index not in removed_molecules:
                chain_id = chain_old.id.split('-', 1)[-1]
                chain_new = topology_new.addChain(id="{}-{}".format(topology_new.getNumChains()+1, chain_id))
                for residue_old in chain_old.residues():
                    residue_new = topology_new.addResidue(residue_old.name, chain_new)
                    for atom_old in residue_old.atoms():
                        topology_new.addAtom(atom_old.name, atom_old.element, residue_new)
                        old_to_new[atom_old.index] = atom_index_new
                        atom_index_new += 1
            else:
                for atom_old in chain_old.atoms():
                    removed_atoms.append(atom_old.index)

        # add bonds to new topology
        atoms_new = list(topology_new.atoms())
        for bond_old in topology_old.bonds():
            atom1_index_old = bond_old[0].index
            atom2_index_old = bond_old[1].index
            try:
                atom1_new = atoms_new[old_to_new[atom1_index_old]]
                atom2_new = atoms_new[old_to_new[atom2_index_old]]
                topology_new.addBond(atom1_new, atom2_new)
            except KeyError:
                pass

        # set box vectors for topology
        topology_new.setPeriodicBoxVectors(periodic_box_vectors)

        # create system
        system_new = system_options.create_system_with_new_topology(topology_new)

        # check if old system had barostat and add to new system if applicable
        if self._has_barostat(system_old):
            barostat_old = self._get_barostat(system_old)
            defaultPressure = barostat_old.getDefaultPressure()
            defaultTemperature = barostat_old.getDefaultTemperature()
            frequency = barostat_old.getFrequency()
            if isinstance(barostat_old, MonteCarloAnisotropicBarostat):
                scaleX = barostat_old.getScaleX()
                scaleY = barostat_old.getScaleY()
                scaleZ = barostat_old.getScaleZ()
                barostat_new = MonteCarloAnisotropicBarostat(defaultPressure, defaultTemperature,
                                                             scaleX, scaleY, scaleZ, frequency)
            else:
                barostat_new = MonteCarloBarostat(defaultPressure, defaultTemperature, frequency)
            system_new.addForce(barostat_new)
            barostat_new.setForceGroup(system_new.getNumForces() - 1)

        # create integrator
        integrator = ensemble_options.create_integrator()

        # create new positions and velocities arrays
        positions_new = np.delete(positions_old, removed_atoms, axis=0)
        velocities_new = np.delete(velocities_old, removed_atoms, axis=0)

        # create new simulation
        simulation_new = Simulation(topology_new, system_new, integrator)
        simulation_new.context.setPositions(positions_new)
        simulation_new.context.setVelocities(velocities_new)
        simulation_new.context.setPeriodicBoxVectors(*periodic_box_vectors)

        # move reporters from old simulation to new simulation
        while simulation_old.reporters:
            simulation_new.reporters.append(simulation_old.reporters.pop(0))

        # create pdb file if specified
        if self.file is not None:
            PDBFile.writeFile(topology_new, positions_new, open(self.file, 'w'))

        return simulation_new
    def __init__(self, file):
        """Load a prmtop file."""
        top = Topology()
        ## The Topology read from the prmtop file
        self.topology = top
        self.elements = []

        # Load the prmtop file

        prmtop = amber_file_parser.PrmtopLoader(file)
        self._prmtop = prmtop

        # Add atoms to the topology

        PDBFile._loadNameReplacementTables()
        lastResidue = None
        c = top.addChain()
        for index in range(prmtop.getNumAtoms()):
            resNumber = prmtop.getResidueNumber(index)
            if resNumber != lastResidue:
                lastResidue = resNumber
                resName = prmtop.getResidueLabel(iAtom=index).strip()
                if resName in PDBFile._residueNameReplacements:
                    resName = PDBFile._residueNameReplacements[resName]
                r = top.addResidue(resName, c)
                if resName in PDBFile._atomNameReplacements:
                    atomReplacements = PDBFile._atomNameReplacements[resName]
                else:
                    atomReplacements = {}
            atomName = prmtop.getAtomName(index).strip()
            if atomName in atomReplacements:
                atomName = atomReplacements[atomName]

            # Get the element from the prmtop file if available
            if prmtop.has_atomic_number:
                try:
                    element = elem.Element.getByAtomicNumber(
                        int(prmtop._raw_data['ATOMIC_NUMBER'][index]))
                except KeyError:
                    element = None
            else:
                # Try to guess the element from the atom name.

                upper = atomName.upper()
                if upper.startswith('CL'):
                    element = elem.chlorine
                elif upper.startswith('NA'):
                    element = elem.sodium
                elif upper.startswith('MG'):
                    element = elem.magnesium
                elif upper.startswith('ZN'):
                    element = elem.zinc
                else:
                    try:
                        element = elem.get_by_symbol(atomName[0])
                    except KeyError:
                        element = None

            top.addAtom(atomName, element, r)
            self.elements.append(element)

        # Add bonds to the topology

        atoms = list(top.atoms())
        for bond in prmtop.getBondsWithH():
            top.addBond(atoms[bond[0]], atoms[bond[1]])
        for bond in prmtop.getBondsNoH():
            top.addBond(atoms[bond[0]], atoms[bond[1]])

        # Set the periodic box size.

        if prmtop.getIfBox():
            box = prmtop.getBoxBetaAndDimensions()
            top.setPeriodicBoxVectors(
                computePeriodicBoxVectors(*(box[1:4] + box[0:1] * 3)))