def testProteinLigand(self): from htmd.builder.solvate import solvate from parameterize.parameterization.fftype import fftype from parameterize.parameterization.writers import writeFRCMOD # Test protein ligand building with parametrized ligand refdir = home(dataDir=join('test-amber-build', 'protLig')) tmpdir = os.path.join(self.testDir, 'protLig') os.makedirs(tmpdir) mol = Molecule(join(refdir, '3ptb_mod.pdb')) lig = Molecule(join(refdir, 'benzamidine.pdb'), guess=('bonds', 'angles', 'dihedrals')) prm, lig = fftype(lig, method='GAFF2') writeFRCMOD(lig, prm, join(tmpdir, 'mol.frcmod')) lig.segid[:] = 'L' # params = newmol = Molecule() newmol.append(lig) newmol.append(mol) smol = solvate(newmol) params = defaultParam() + [ join(tmpdir, 'mol.frcmod'), ] _ = build(smol, outdir=tmpdir, param=params, ionize=False) refdir = home(dataDir=join('test-amber-build', 'protLig', 'results')) _TestAmberBuild._compareResultFolders(refdir, tmpdir, '3PTB')
def testProteinLigand(self): from htmd.builder.solvate import solvate # Test protein ligand building with parametrized ligand refdir = home(dataDir=join("test-amber-build", "protLig")) tmpdir = os.path.join(self.testDir, "protLig") os.makedirs(tmpdir) mol = Molecule(join(refdir, "3ptb_mod.pdb")) lig = Molecule(join(refdir, "benzamidine.mol2")) lig.segid[:] = "L" # params = newmol = Molecule() newmol.append(lig) newmol.append(mol) smol = solvate(newmol) params = defaultParam() + [ join(refdir, "benzamidine.frcmod"), ] _ = build(smol, outdir=tmpdir, param=params, ionize=False) refdir = home(dataDir=join("test-amber-build", "protLig", "results")) _TestAmberBuild._compareResultFolders(refdir, tmpdir, "3PTB")
def sampleRegion( self, point=None, radius=None, limits=None, nsamples=20, singlemol=False ): """Samples conformations from a region in the projected space. Parameters ---------- point : list or np.ndarray A point in the projected space. Undefined dimensions should have None value. radius : float The radius in around the point in which to sample conformations. limits : np.ndarray A (2, ndim) dimensional array containing the min (1st row) and max (2nd row) limits for each dimension. None values will be interpreted as no limit in that dimension, or min/max value. nsamples : int The number of conformations to sample. singlemol : bool If True it will return all samples within a single Molecule instead of a list of Molecules. Returns ------- absFrames : list A list of the absolute frame indexes sampled relFrames : list of tuples A list of (trajNum, frameNum) tuples sampled mols : Molecule or list of Molecules The conformations stored in a Molecule or a list of Molecules Examples -------- >>> # Working with 4 dimensional data for example >>> abs, rel, mols = data.sampleRegion(point=(0.5, 3, None, None), radius=0.1) # Point undefined in dim 3, 4 >>> minlims = [-1, None, None, 4] # No min limit for 2, 3 dim >>> maxlims = [2, 3, None, 7] # No max limit for 3 dim >>> abs, rel, mols = data.sampleRegion(limits=np.array([minlims, maxlims])) """ from scipy.spatial.distance import cdist datconcat = np.concatenate(self.dat) numdim = datconcat.shape[1] if point is not None: if radius is None: raise RuntimeError("You must define a radius with a point.") point = np.array(point) if len(point) != numdim: raise RuntimeError( "Argument `point` should be same dimensionality as your data ({} dimensions)".format( numdim ) ) keepdim = np.array([p is not None for p in point]) dists = cdist(datconcat[:, keepdim], [point[keepdim]]) confs = np.where(dists < radius)[0] elif limits is not None: if limits.shape != (2, numdim): raise RuntimeError( "Argument `limits` should be of shape (2, {})".format(numdim) ) mask = np.ones(datconcat.shape[0], dtype=bool) for i in range(numdim): if limits[0, i] is not None: mask &= datconcat[:, i] > limits[0, i] if limits[1, i] is not None: mask &= datconcat[:, i] < limits[1, i] confs = np.where(mask)[0] if len(confs) > nsamples: confs = np.random.choice(confs, nsamples, replace=False) sims = self.abs2sim(confs) from moleculekit.molecule import Molecule if singlemol: mol = Molecule(sims[0]) for i in range(1, len(sims)): m = Molecule(sims[i]) mol.appendFrames(m) else: mol = [] for s in sims: mol.append(Molecule(s)) return confs, self.abs2rel(confs), mol
def tileMembrane(memb, xmin, ymin, xmax, ymax, buffer=1.5): """ Tile a membrane in the X and Y dimensions to reach a specific size. Parameters ---------- memb : :class:`Molecule <moleculekit.molecule.Molecule>` object The membrane to be tiled xmin : float Minimum x coordinate ymin : float Minimum y coordinate xmax : float Maximum x coordinate ymax : float Maximum y coordinate buffer : float Buffer distance between tiles Returns ------- megamemb : A big membrane Molecule """ from tqdm import tqdm memb = memb.copy() memb.resid = sequenceID( (memb.resid, memb.insertion, memb.chain, memb.segid)) minmemb = np.min(memb.get('coords', 'water'), axis=0).flatten() size = np.max(memb.get('coords', 'water'), axis=0) - np.min( memb.get('coords', 'water'), axis=0) size = size.flatten() xreps = int(np.ceil((xmax - xmin) / size[0])) yreps = int(np.ceil((ymax - ymin) / size[1])) logger.info('Replicating Membrane {}x{}'.format(xreps, yreps)) from moleculekit.molecule import Molecule megamemb = Molecule() bar = tqdm(total=xreps * yreps, desc='Replicating Membrane') k = 0 for x in range(xreps): for y in range(yreps): tmpmemb = memb.copy() xpos = xmin + x * (size[0] + buffer) ypos = ymin + y * (size[1] + buffer) tmpmemb.moveBy( [-float(minmemb[0]) + xpos, -float(minmemb[1]) + ypos, 0]) tmpmemb.remove('same resid as (x > {} or y > {})'.format( xmax, ymax), _logger=False) if tmpmemb.numAtoms == 0: continue tmpmemb.set('segid', 'M{}'.format(k), sel='not water') tmpmemb.set('segid', 'MW{}'.format(k), sel='water') megamemb.append(tmpmemb) k += 1 bar.update(1) bar.close() # Membranes don't tile perfectly. Need to remove waters that clash with lipids of other tiles # Some clashes will still occur between periodic images however megamemb.remove('same resid as water and within 1.5 of not water', _logger=False) return megamemb
from htmd.builder.amber import defaultParam, build # Test protein ligand building with parametrized ligand refdir = home(dataDir=join('test-amber-build', 'protLig')) tmpdir = './protLig' mol = Molecule(join(refdir, '3ptb_mod.pdb')) mol.center() lig = Molecule(join(refdir, 'benzamidine.pdb'), guess=('bonds', 'angles', 'dihedrals')) prm, lig = fftype(lig, method='GAFF2') writeFRCMOD(lig, prm, join(tmpdir, 'mol.frcmod')) lig.segid[:] = 'L' lig.center() from moleculekit.util import maxDistance D = maxDistance(mol, 'all') D += 6 lig.moveBy([0, 0, D]) newmol = Molecule() newmol.append(lig) newmol.append(mol) smol = solvate(newmol, posz=3) params = defaultParam() + [ join(tmpdir, 'mol.frcmod'), ] _ = build(smol, outdir=tmpdir, param=params, ionize=False)
def generateCrystalPacking(pdbid, hexagonal=False, visualize=False, viewerhandle=None): """ Generates the crystal packing of a PDB protein. It is possible to inspect it immediately with the visualize option. It can only be generated if there is crystallographic information in the PDB entry. Parameters ---------- pdbid : str ID from the Protein Databank hexagonal : bool # TODO: Undocumented visualize : bool If True, this function also visualizes the crystal packing viewerhandle : :class:`VMD <moleculekit.vmdviewer.VMD>` object, optional A specific viewer in which to visualize the molecule. If None it will use the current default viewer. Returns ------- mol : :class:`Molecule` Molecule object with the crystal packing """ if not isinstance(pdbid, str): raise ValueError('pdbid should be a string') filename, _ = _getPDB(pdbid) mol = Molecule(filename) if viewerhandle is not None and not visualize: logger.warning('A viewerhandle was passed. Setting visualize to True.') visualize = True if visualize and viewerhandle is None: from moleculekit.vmdviewer import getCurrentViewer viewerhandle = getCurrentViewer() if mol.crystalinfo is None or 'numcopies' not in mol.crystalinfo: raise RuntimeError('No crystallography data found in Molecule.') ci = mol.crystalinfo alpha, beta, gamma, a, b, c = ci['alpha'], ci['beta'], ci['gamma'], ci['a'], ci['b'], ci['c'] alpha = np.deg2rad(float(alpha)) beta = np.deg2rad(float(beta)) gamma = np.deg2rad(float(gamma)) caux = (np.cos(alpha) - np.cos(beta) * np.cos(gamma)) / np.sin(gamma) axes = np.array([[a, 0, 0], [b * np.cos(gamma), b * np.sin(gamma), 0], [c * np.cos(beta), c * caux, c * np.sqrt(1 - np.cos(beta) ** 2 - caux ** 2)]]) size = np.array([axes[0][0], axes[1][1], axes[2][2]]) molunit = Molecule() # Creates copies of the molecule and places them correctly inside the complete Unit Cell hexagonal_molunit = None for i in tqdm(range(ci['numcopies']), desc='Generating symmetry mates'): molecule = mol.copy() molecule.segid[:] = str(i+1) # apply SMTRY (Crystal Symmetry) operations molecule.rotateBy(ci['rotations'][i]) molecule.moveBy(ci['translations'][i]) # apply translation to inside of same Unit Cell. _place_crystal(molecule, size, [alpha, beta, gamma], axes) # pack copies to target Unit Cell molunit.append(molecule) if ci['sGroup'][0] == 'H' and hexagonal: hexagonal_molunit = Molecule() _build_hexagon(molunit, hexagonal_molunit) if hexagonal_molunit is not None: if visualize: hexagonal_molunit.view(style='NewCartoon', viewerhandle=viewerhandle) else: return hexagonal_molunit else: if visualize: molunit.view(style='NewCartoon', viewerhandle=viewerhandle) else: return molunit if visualize: _draw_cell(axes, ci['sGroup'], viewerhandle, hexagonal=hexagonal)