def normalmodes_prody(selection, cutoff=15, first=7, last=10, guide=1, prefix='prody', states=7, factor=-1, quiet=1): ''' DESCRIPTION Anisotropic Network Model (ANM) analysis with ProDy. Based on: http://www.csb.pitt.edu/prody/examples/dynamics/enm/anm.html ''' try: import prody except ImportError: print('Failed to import prody, please add to PYTHONPATH') raise CmdException first, last, guide = int(first), int(last), int(guide) states, factor, quiet = int(states), float(factor), int(quiet) assert first > 6 if guide: selection = '(%s) and guide and alt A+' % (selection) tmpsele = cmd.get_unused_name('_') cmd.select(tmpsele, selection) f = StringIO(cmd.get_pdbstr(tmpsele)) conf = prody.parsePDBStream(f) modes = prody.ANM() modes.buildHessian(conf, float(cutoff)) modes.calcModes(last - first + 1) if factor < 0: from math import log natoms = modes.numAtoms() factor = log(natoms) * 10 if not quiet: print(' set factor to %.2f' % (factor)) for mode in range(first, last + 1): name = prefix + '%d' % mode cmd.delete(name) if not quiet: print(' normalmodes: object "%s" for mode %d' % (name, mode)) for state in range(1, states+1): xyz_it = iter(modes[mode-7].getArrayNx3() * (factor * ((state-1.0)/(states-1.0) - 0.5))) cmd.create(name, tmpsele, 1, state, zoom=0) cmd.alter_state(state, name, '(x,y,z) = next(xyz_it) + (x,y,z)', space={'xyz_it': xyz_it, 'next': next}) cmd.delete(tmpsele) if guide: cmd.set('ribbon_trace_atoms', 1, prefix + '*') cmd.show_as('ribbon', prefix + '*') else: cmd.show_as('lines', prefix + '*')
def prody_modes(molecule, max_modes, algorithm=None, **options): """ Parameters ---------- molecule : prody.AtomGroup nax_modes : int number of modes to calculate algorithm : callable, optional, default=None coarseGrain(prm) wich make molecule.select().setBetas(i) where i is the index Coarse Grain group Where prm is prody AtomGroup options : dict, optional Parameters for algorithm callable Returns ------- modes : ProDy modes ANM or RTB """ modes = None if algorithm in ['residues', 'mass']: title = 'normal modes for {}'.format(molecule.getTitle()) molecule = algorithm(molecule, **options) modes = prody.RTB(title) modes.buildHessian(molecule.getCoords(), molecule.getBetas()) modes.calcModes(n_modes=max_modes) elif algorithm == 'calpha': calphas_modes = prody.ANM('normal modes for {}'.format( molecule.getTitle())) calphas = molecule = molecule.select(algorithm) calphas_modes.buildHessian(calphas) calphas_modes.calcModes(n_modes=max_modes) modes = prody.extendModel(calphas_modes, calphas, molecule, norm=True)[0] else: modes = prody.ANM('normal modes for {}'.format(molecule.getTitle())) modes.buildHessian(molecule) modes.calcModes(n_modes=max_modes) return modes
def calc_ensembles(structure_orig): structure_ca = structure_orig.select('ca or name P') structure_anm = pr.ANM('structure ca') structure_anm.buildHessian(structure_ca) structure_anm.calcModes(n_modes=5) structure_anm_ext, structure_all = pr.extendModel(structure_anm, structure_ca, structure_orig, norm=True) ens = pr.sampleModes(structure_anm_ext, atoms=structure_all.all, n_confs=1, rmsd=1.5) return ens, structure_all
def computeNormalMode(userfilenamein="",userfilenameout="NMA.pdb", usermode=0,userrmsd=0.8, usernbconf=5, conf="allatom", usercutoff=15.0, usergamma=1.0) : mystruct = prody.parsePDB(userfilenamein, model=1) mystruct_ca = mystruct.select('protein and name CA') anm = prody.ANM(userfilenamein+str(usermode)) anm.buildHessian(mystruct_ca, gamma=usergamma, cutoff=usercutoff) anm.calcModes() bb_anm, bb_atoms = extrapolateModel(anm, mystruct_ca, mystruct.select(conf)) ensemble = sampleModes(bb_anm[usermode], bb_atoms, n_confs=usernbconf, rmsd=userrmsd) nmastruct = mystruct.copy( bb_atoms ) nmastruct.addCoordset(ensemble) writePDB(userfilenameout, nmastruct)
def calcANM(self, structure, logger): ''' calcANM: #structure: prody PDB-structure calculate ANM for one specific structure return: prody.anm object ''' logger.info("Calculate ANM") ANMname = structure.getLabel() anm = prody.ANM(ANMname) anm.buildHessian(structure, cutoff=15.0) anm.calcModes() # write out the three lowest modes as NMD file (visualize with NMWizard in VMD outputname = ANMname + "_anm_modes.nmd" prody.writeNMD(outputname, anm[:10], self.selection_ref_structure) if self.vmd == True: prody.viewNMDinVMD(outputname) logger.info(f"ANM is saved in: {outputname}") return anm
def nma_analysis(calphas, nodes_pos, masses, cutoff, mode=0): ''' Uses a modified version of ProDy where mass weighting of the hessian is done in buildHessian() takes as input to build an hessian and perform normal mode analysis: - coordinates of nodes to build geometric network - cutoff as edges threshold - masses to perform mass weighting in the hessian - calphas and nodes_pos are just to build the classes for the NMD file returns: - slowest mode eigenvector already divided in an array of eigenvectors for which entry i is the slowest mode eigenvector for atom i ''' anm = prody.ANM("nd") anm.buildHessian(nodes_pos, cutoff=cutoff, masses=masses) anm.calcModes(3) slowest_mode = anm[mode] ev = slowest_mode.getEigvec().round(3) vectors = [[ev[i], ev[i + 1], ev[i + 2]] for i in range(0, len(ev), 3)] return np.asarray(vectors)
def prody_anm(pdb, **kwargs): """Perform ANM calculations for *pdb*. """ for key in DEFAULTS: if not key in kwargs: kwargs[key] = DEFAULTS[key] from os.path import isdir, join outdir = kwargs.get('outdir') if not isdir(outdir): raise IOError('{0} is not a valid path'.format(repr(outdir))) import numpy as np import prody LOGGER = prody.LOGGER selstr = kwargs.get('select') prefix = kwargs.get('prefix') cutoff = kwargs.get('cutoff') gamma = kwargs.get('gamma') nmodes = kwargs.get('nmodes') selstr = kwargs.get('select') model = kwargs.get('model') pdb = prody.parsePDB(pdb, model=model) if prefix == '_anm': prefix = pdb.getTitle() + '_anm' select = pdb.select(selstr) if select is None: LOGGER.warn('Selection {0} did not match any atoms.'.format( repr(selstr))) return LOGGER.info('{0} atoms will be used for ANM calculations.'.format( len(select))) anm = prody.ANM(pdb.getTitle()) anm.buildHessian(select, cutoff, gamma) anm.calcModes(nmodes) LOGGER.info('Writing numerical output.') if kwargs.get('outnpz'): prody.saveModel(anm, join(outdir, prefix)) prody.writeNMD(join(outdir, prefix + '.nmd'), anm, select) extend = kwargs.get('extend') if extend: if extend == 'all': extended = prody.extendModel(anm, select, pdb) else: extended = prody.extendModel(anm, select, select | pdb.bb) prody.writeNMD(join(outdir, prefix + '_extended_' + extend + '.nmd'), *extended) outall = kwargs.get('outall') delim = kwargs.get('numdelim') ext = kwargs.get('numext') format = kwargs.get('numformat') if outall or kwargs.get('outeig'): prody.writeArray(join(outdir, prefix + '_evectors' + ext), anm.getArray(), delimiter=delim, format=format) prody.writeArray(join(outdir, prefix + '_evalues' + ext), anm.getEigvals(), delimiter=delim, format=format) if outall or kwargs.get('outbeta'): from prody.utilities import openFile fout = openFile(prefix + '_beta.txt', 'w', folder=outdir) fout.write( '{0[0]:1s} {0[1]:4s} {0[2]:4s} {0[3]:5s} {0[4]:5s}\n'.format( ['C', 'RES', '####', 'Exp.', 'The.'])) for data in zip(select.getChids(), select.getResnames(), select.getResnums(), select.getBetas(), prody.calcTempFactors(anm, select)): fout.write( '{0[0]:1s} {0[1]:4s} {0[2]:4d} {0[3]:5.2f} {0[4]:5.2f}\n'. format(data)) fout.close() if outall or kwargs.get('outcov'): prody.writeArray(join(outdir, prefix + '_covariance' + ext), anm.getCovariance(), delimiter=delim, format=format) if outall or kwargs.get('outcc') or kwargs.get('outhm'): cc = prody.calcCrossCorr(anm) if outall or kwargs.get('outcc'): prody.writeArray(join(outdir, prefix + '_cross-correlations' + ext), cc, delimiter=delim, format=format) if outall or kwargs.get('outhm'): prody.writeHeatmap(join(outdir, prefix + '_cross-correlations.hm'), cc, resnum=select.getResnums(), xlabel='Residue', ylabel='Residue', title=anm.getTitle() + ' cross-correlations') if outall or kwargs.get('hessian'): prody.writeArray(join(outdir, prefix + '_hessian' + ext), anm.getHessian(), delimiter=delim, format=format) if outall or kwargs.get('kirchhoff'): prody.writeArray(join(outdir, prefix + '_kirchhoff' + ext), anm.getKirchhoff(), delimiter=delim, format=format) if outall or kwargs.get('outsf'): prody.writeArray(join(outdir, prefix + '_sqflucts' + ext), prody.calcSqFlucts(anm), delimiter=delim, format=format) figall = kwargs.get('figall') cc = kwargs.get('figcc') sf = kwargs.get('figsf') bf = kwargs.get('figbeta') cm = kwargs.get('figcmap') if figall or cc or sf or bf or cm: try: import matplotlib.pyplot as plt except ImportError: LOGGER.warning('Matplotlib could not be imported. ' 'Figures are not saved.') else: prody.SETTINGS['auto_show'] = False LOGGER.info('Saving graphical output.') format = kwargs.get('figformat') width = kwargs.get('figwidth') height = kwargs.get('figheight') dpi = kwargs.get('figdpi') format = format.lower() if figall or cc: plt.figure(figsize=(width, height)) prody.showCrossCorr(anm) plt.savefig(join(outdir, prefix + '_cc.' + format), dpi=dpi, format=format) plt.close('all') if figall or cm: plt.figure(figsize=(width, height)) prody.showContactMap(anm) plt.savefig(join(outdir, prefix + '_cm.' + format), dpi=dpi, format=format) plt.close('all') if figall or sf: plt.figure(figsize=(width, height)) prody.showSqFlucts(anm) plt.savefig(join(outdir, prefix + '_sf.' + format), dpi=dpi, format=format) plt.close('all') if figall or bf: plt.figure(figsize=(width, height)) bexp = select.getBetas() bcal = prody.calcTempFactors(anm, select) plt.plot(bexp, label='Experimental') plt.plot(bcal, label=('Theoretical (R={0:.2f})'.format( np.corrcoef(bcal, bexp)[0, 1]))) plt.legend(prop={'size': 10}) plt.xlabel('Node index') plt.ylabel('Experimental B-factors') plt.title(pdb.getTitle() + ' B-factors') plt.savefig(join(outdir, prefix + '_bf.' + format), dpi=dpi, format=format) plt.close('all')
def calc_ANM_CA_prody(CAcoords): anm = prd.ANM() anm.buildHessian(CAcoords, cutoff=15.0) # default = 15 anm.calcModes(n_modes=None) return anm.getEigvals().round(6), anm.getEigvecs().round(6)
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with ePMV. If not, see <http://www.gnu.org/licenses/gpl-3.0.html>. """ # -*- coding: utf-8 -*- """ Created on Wed Jul 13 14:14:58 2011 @author: - """ #http://www.csb.pitt.edu/ProDy/contents.html import prody p38ca = prody.parsePDB('1p38', subset='ca') anm = prody.ANM('1p38') anm.buildHessian(p38ca) anm.calcModes() #traverseMode() function generates conformations along a single normal mode. #Conformations are generated in both directions along the given mode. #rmsd argument is used to set the RMSD distance to the farthest conformation. #Let’s generate 10 conformations along ANM mode 1: trajectory = prody.traverseMode(anm[0], p38ca, n_steps=5, rmsd=2.0) coords=trajectory.getCoordsets() #conformation... #dumb->read in epmv or read on the fly? p38traj = p38ca.copy() p38traj.delCoordset(0) p38traj.addCoordset( trajectory )
def setNM(self, ): self.anm = prody.ANM(self.filname + str(self.id))
def calculate_vibrations(molecule, max_modes=20, algorithm='calpha', queue=None, mass_weighted=False, cutoff=15.0, gamma=1.0, **options): """ Parameters ---------- molecule : prody.AtomGroup nax_modes : int number of modes to calculate algorithm : callable, optional, default=None coarseGrain(prm) which make molecule.select().setBetas(i) where i is the index Coarse Grain group and prm is prody AtomGroup options : dict, optional Parameters for algorithm callable Returns ------- modes : ProDy modes ANM or RTB """ if queue is None: queue = Queue() modes = None hessian_kwargs = dict(cutoff=cutoff, gamma=gamma) if algorithm in ('residues', 'mass', 'graph'): queue.put('Building model...') title = 'normal modes for {}'.format(molecule.getTitle()) molecule = GROUPERS[algorithm](molecule, **options) modes = prody.RTB(title) queue.put('Building hessian...') modes.buildHessian(molecule.getCoords(), molecule.getBetas(), **hessian_kwargs) if mass_weighted: queue.put('Mass weighting...') _mass_weighted_hessian(molecule, modes) queue.put('Calculating {} modes...'.format(max_modes)) modes.calcModes(n_modes=max_modes) elif algorithm == 'calpha': queue.put('Building model...') calphas_modes = prody.ANM('normal modes for {}'.format( molecule.getTitle())) calphas = molecule = molecule.select(algorithm) queue.put('Building hessian...') calphas_modes.buildHessian(calphas, **hessian_kwargs) if mass_weighted: queue.put('Mass weighting...') _mass_weighted_hessian(molecule, modes) queue.put('Calculating {} modes...'.format(max_modes)) calphas_modes.calcModes(n_modes=max_modes) queue.put('Extending model...') modes = prody.extendModel(calphas_modes, calphas, molecule, norm=True)[0] else: queue.put('Building model...') modes = prody.ANM('normal modes for {}'.format(molecule.getTitle())) queue.put('Building hessian...') modes.buildHessian(molecule, **hessian_kwargs) if mass_weighted: queue.put('Mass weighting...') _mass_weighted_hessian(molecule, modes) queue.put('Calculating {} modes...'.format(max_modes)) modes.calcModes(n_modes=max_modes) print(modes) return modes