def print_from_file(self, modesfile):
        env.logger.info("Printing modes from file", modesfile)
        import matplotlib.pyplot as plt
        from matplotlib.path import Path
        import matplotlib.patches as patches
        modes, atm_group = prody.parseNMD(modesfile)

        title=modesfile.split(".")
        modes.setTitle(title[0])
        print_offset = 1
        #print_offset = 738
        plt.rcParams.update({'font.size': 24}) 
        plt.rcParams['xtick.major.pad'] = 10
        plt.rcParams['ytick.major.pad'] = 10
        
        for count in range(6):
            #array with lenghtes of vectors
            a3d = (modes[count].getArrayNx3()**2).sum(axis=1)**0.5
            plt.plot(a3d[:], label=("Mode "+str(count+1)))
        plt.xlabel('Residue index')
        plt.ylabel('Lenght of fluctuation vector')
        
        locs,labels = plt.xticks()
        new_labels = ['%d' % (a+print_offset) for a in locs]
        plt.xticks(locs,new_labels)
        plt.ylim([0,0.8])
        plt.xlim([print_offset, modes.numAtoms()])
        
        lgd = plt.legend(loc='center right', bbox_to_anchor=(1.6,0.5))
        plt.savefig(str(modes.getTitle())+"_mode_1_to_6.pdf", bbox_extra_artists=(lgd, ), bbox_inches='tight')
        
        env.logger.info("Printing modes to file finished")
Пример #2
0
 def read_prody_normal_modes(self):
     prody_molecule, chimera2prody = convert_chimera_molecule_to_prody(
         self.molecule)
     modes = prody.parseNMD(self.path)[0]
     samples = prody.sampleModes(modes=modes[self.modes],
                                 atoms=prody_molecule,
                                 n_confs=self.n_samples,
                                 rmsd=self.rmsd)
     samples.addCoordset(prody_molecule)
     samples_coords = [sample.getCoords() for sample in samples]
     return modes, samples_coords, chimera2prody, prody_molecule
Пример #3
0
def NMA_plots(filename, outfile):
    """Creates a plot of the most important modes for a system.
    Parameters
    ----------
    filename : str
        An NMD file.
    outfile: str
        Name of the output PNG.

    Returns
    -------
    outfile : png
        The rendered normal mode plot.
    """
    NMA_data, Atom_Group = prd.parseNMD(filename)
    eigens = NMA_data.getEigvals()

    # If you have specific X-tick labels, set them up in plot_ticks
    #labels_top, places_top = plot_ticks(NMA_data)

    scales = []
    temp = open(filename)
    lines = temp.readlines()
    temp.close()
    for line in lines:
        if 'mode' in line[:5]:
            scales.append(float(line.split()[:3][-1]))

    # Make an array of the number of atoms for plotting
    x_vals = np.arange(0, NMA_data.numAtoms(), 1)

    fig = plt.figure(figsize=(10, 8), dpi=300)
    ax = fig.add_subplot(1, 1, 1)
    for i in range(num_of_modes):
        dataset = [
            np.linalg.norm(NMA_data.getEigvecs()[:, i][n:n + 3]) * scales[i] *
            eigens[i] for n in range(0, NMA_data.numEntries(), 3)
        ]
        ax.bar(x_vals, dataset, width=1.0, label="Mode " + str(i + 1))

    ax_top = ax.twiny()
    ax_top.set_xticks(places_top)
    ax_top.set_xticklabels(labels_top, fontdict=None, minor=False)

    ax.legend()
    ax.set_xlabel("Residue Number")
    ax.set_ylabel("PCA Square Fluctuations")
    # Remove white space at edge
    ax.set_xlim([0, x_vals.size])
    plt.tight_layout()
    fig.savefig(outfile, dpi=300)
    plt.close()
Пример #4
0
    def prody_anm(self, variables, txtOutput):
        '''
        PRODY DRIVER is the function to read in variables from GUI input and
        used to run a prody normal mode calculation using the anisotropic network model
        (ANM) on a structure provide in a pdb file.

        INPUT:  variable descriptions:

        pdbfile:          input pdb file (reference)

        OUTPUT:
                        model_anm_extended_bb.nmd
                        model_traverse.dcd
                        model_samp.dcd
                        model_samp.pdb
                        model_anm_sqflucts.txt
                        model_anm_kirchhoff.txt
                        model_anm_hessian.txt
                        model_anm_cross-correlations.hm
                        model_anm_cross-correlations.txt
                        model_anm_covariance.txt
                        model_anm_beta.txt
                        model_anm_evalues.txt
                        model_anm_evectors.txt
                        model_anm_extended_all.nmd
                        model_anm.nmd

        txtOutput:        TK handler for output to GUI textbox

        files stored in ~/runname/prody directory:
        outfile:          output filename

        '''
        log = self.log
        pgui = self.run_utils.print_gui

        # start gui output
        pgui("\n%s \n" % ('=' * 60))
        pgui("DATA FROM RUN: %s \n\n" % time.asctime( time.gmtime( time.time() ) ))

        mvars = self.mvars
        #path = os.path.join(os.getcwd(),mvars.runname, 'prody')
        path = os.path.join(mvars.runname, 'prody')
        direxist = os.path.exists(path)
        if(direxist == 0):
            try:
                result = os.system('mkdir -p ' + path)
            except:
                message = 'can not create project directory: ' + path
                message += '\nstopping here\n'
                print_failure(message, txtOutput)
            if(result != 0):
                message = 'can not create project directory: ' + path
                message += '\nstopping here\n'
                print_failure(message, txtOutput)
        if mvars.advanced_usage == 1:
            run_cmd = prody_exe + mvars.advanced_usage_cmd
            os.system(run_cmd)
            run_cmd = 'mv *.nmd *.txt *.hm prody'
            os.system(run_cmd)
            exit()

        # display progress
        fraction_done = (0 + 1) * 1.0 / 10.0
        report_string = 'STATUS\t%f' % fraction_done
        pgui(report_string)

        prody.confProDy(verbosity='none')  #option to set silent verbosity
        model = mvars.pdbfile[0:len(mvars.pdbfile) - 4]
        run_cmd = prody_exe + ' anm ' + \
            mvars.pdbfile + ' -t all -n ' + str(mvars.number_modes) + ' -a'
        log.info('staring prody_exe %s' % run_cmd)
        prody_run = subprocess.Popen(run_cmd,shell=True,executable='/bin/bash')
        prody_run.wait() 
        #prody.confProDy(verbosity='none')  #option to set silent verbosity
        file_anm = model + '_anm_extended_all.nmd'

        # display progress
        fraction_done = (1 + 1) * 1.0 / 10.0
        report_string = 'STATUS\t%f' % fraction_done
        pgui(report_string)

        # parse nmd file with resuts extended to all atoms
        log.info('staring prody.parseNMD %s' % file_anm)
        mod, ag = prody.parseNMD(file_anm, type=None)
        allatoms = ag.copy()
        # set up to randomly sample number_conformations_samp modes
        log.info('staring prody.sampleModes')
        ensemble = prody.sampleModes(mod[:mvars.number_modes],
                                     ag,
                                     n_confs=mvars.number_conformations_samp,
                                     rmsd=mvars.rmsd_conformations_samp)
        ensemble
        log.info('staring prody ensemble and writing pdb/dcd files')
        allatoms.addCoordset(ensemble)
        prody.writePDB('model_samp.pdb', allatoms)
        prody.writeDCD('model_samp.dcd', allatoms)
        trajectory_names = []
        
        # display progress
        fraction_done = (1 + 2) * 1.0 / 10.0
        report_string = 'STATUS\t%f' % fraction_done
        pgui(report_string)

        log.info('starting prody traverse')
        for i in xrange(0, mvars.number_modes):
            #print i
            # setup to tranverse slowest mode
            traverse = prody.traverseMode(
                mod[i],
                allatoms,
                n_steps=mvars.number_steps_traverse,
                rmsd=mvars.rmsd_traverse)
            traverse
            prody.writeDCD('traverse.dcd', traverse)
            this_dcd = str(os.path.join(path, 'traverse_' + str(i) + '.dcd'))
            cmd = 'mv traverse.dcd ' + this_dcd
            os.system(cmd)
            trajectory_names.append(this_dcd)

        # display progress
        fraction_done = (1 + 7) * 1.0 / 10.0
        report_string = 'STATUS\t%f' % fraction_done
        pgui(report_string)

        m1 = sasmol.SasMol(0)
        m2 = sasmol.SasMol(0)
        m1.read_pdb(mvars.pdbfile)
        m2.read_pdb(mvars.pdbfile,fastread=True)

        mvars.dcdfile = mvars.runname + '.dcd'
        log.info('opening new dcd file to store trajectory: %s' %
                 os.path.join(self.runpath, mvars.dcdfile))

        outfile_name = str(os.path.join(path, mvars.dcdfile))
        dcdoutfile = m2.open_dcd_write(outfile_name)
        count = 0
        coor = numpy.zeros((1,m2.natoms(),3),numpy.float32)
        for this_trajectory_name in trajectory_names:

            dcdfile = m1.open_dcd_read(this_trajectory_name)
            number_of_frames = dcdfile[2]

            for j in xrange(number_of_frames):
                m1.read_dcd_step(dcdfile,j)
                coor[0,:,:] = m1.coor()[0]
                m2.setCoor(coor)
                m2.write_dcd_step(dcdoutfile,0, count + 1)
                count += 1

        m2.close_dcd_write(dcdoutfile)

        log.info('moving files to runname / prody')

        file_anm = model + '_anm.nmd'
        mod, ag = prody.parseNMD(file_anm, type=None)
        mod1 = prody.parsePDB(mvars.pdbfile)
        calphas = mod1.select('calpha')
        bb_anm, bb_atoms = prody.extendModel(mod, calphas, mod1.select(
            'backbone'))  # extend model to backbone atoms
        prody.writeNMD('model_anm_extended_bb.nmd', bb_anm, bb_atoms)

        cmd = 'mv model_samp.pdb ' + path + os.sep + os.path.basename(model) + '_samp.pdb'
        os.system(cmd)

        cmd = 'mv model_samp.dcd ' + path + os.sep + os.path.basename(model) + '_samp.dcd'
        os.system(cmd)

        cmd = 'mv model_anm_extended_bb.nmd ' + \
            model + '_anm_extended_bb.nmd'
        os.system(cmd)

        cmd = 'mv *.hm *.nmd *.txt ' + path + os.sep
        os.system(cmd)
        
        # display progress
        fraction_done = (1 + 9) * 1.0 / 10.0
        report_string = 'STATUS\t%f' % fraction_done
        pgui(report_string)

        return