Exemple #1
0
 def loadDataPushed(self):
     """Loads the trajectory data with the chosen initial parameters."""
     self.config, result = FileLoaderDialog.getConfig()
     if result == 1:
         QApplication.processEvents()
         self.setInfoLabel(
             "Loading trajectory and running atomic contact analysis...")
         nproc = int(self.settingsView.coreBox.value())
         self.analysis = Analyzer(self.config.psf, self.config.dcd,
                                  self.config.cutoff,
                                  self.config.hbondcutoff,
                                  self.config.hbondcutangle,
                                  self.config.sel1text,
                                  self.config.sel2text)
         QApplication.processEvents()
         try:
             self.analysis.runFrameScan(nproc)
         except:
             box = ErrorBox(
                 "Error while loading data: Probably you specified an atom selection with 0 atoms or invalid input files."
             )
             box.exec_()
             self.loadDataPushed()
         self.setInfoLabel("%d frames loaded." %
                           len(self.analysis.contactResults))
         self.updateSelectionLabels(self.config.sel1text,
                                    self.config.sel2text)
         self.sasaView.setFilePaths(*self.analysis.getFilePaths())
         self.exportWidget.setFilePaths(*self.analysis.getFilePaths())
Exemple #2
0
 def showStatistics(self):
     """Shows general statistics of the analyzed data over all frames."""
     if len(self.contacts) == 0 or self.contacts is None:
         box = ErrorBox(ErrorMessages.NOSCORES_PROMPTANALYSIS)
         box.exec_()
         return
     self.statisticsView = Statistics(self.contacts)
     self.statisticsView.showNormal()
 def savePlot(self):
     """Saves the current plot."""
     fileName = QFileDialog.getSaveFileName(self, 'Save Path')
     path, file_extension = os.path.splitext(fileName[0])
     if file_extension == "":
         file_extension = "png"
     else:
         file_extension = file_extension[1:]
     try:
         self.contactPlotter.saveFigure(path, file_extension)
     except ValueError:
         box = ErrorBox("File format " + file_extension + " is not supported.\nPlease choose from eps, pdf, pgf,"
                                                          " png, ps, raw, rgba, svg, svgz. ")
         box.exec_()
Exemple #4
0
 def exportSession(self):
     """Exports the current session to file."""
     fileName = QFileDialog.getSaveFileName(self, 'Export file')
     filestring = fileName[0]
     if filestring == "":
         return
     if self.contacts is not None and self.analysis is not None:
         self.setInfoLabel("Exporting current session...")
         DataHandler.writeSessionToFile(filestring, self.analysis)
         self.cleanInfoLabel()
     else:
         box = ErrorBox(ErrorMessages.NOEXPDATA)
         box.exec_()
         return
Exemple #5
0
 def savePlot(self):
     """Saves the generated SASA plot over all frames."""
     fileName = QFileDialog.getSaveFileName(self, 'Export Path')
     if len(fileName[0]) > 0:
         path, file_extension = os.path.splitext(fileName[0])
         if file_extension == "":
             file_extension = ".png"
         file_extension = file_extension[1:]
         try:
             self.previewPlot.saveFigure(path, file_extension)
         except ValueError:
             box = ErrorBox("File format " + file_extension + " is not supported.\nPlease choose from eps, pdf, pgf,"
                                                              " png, ps, raw, rgba, svg, svgz. ")
             box.exec_()
Exemple #6
0
 def savePlot(self):
     """Saves the generated SASA plot over all frames."""
     fileName = QFileDialog.getSaveFileName(self, 'Export Path')
     if len(fileName[0]) > 0:
         path, file_extension = os.path.splitext(fileName[0])
         if file_extension == "":
             file_extension = ".png"
         file_extension = file_extension[1:]
         try:
             self.previewPlot.saveFigure(path, file_extension)
         except ValueError:
             box = ErrorBox(
                 "File format " + file_extension +
                 " is not supported.\nPlease choose from eps, pdf, pgf,"
                 " png, ps, raw, rgba, svg, svgz. ")
             box.exec_()
Exemple #7
0
 def savePlot(self):
     """Saves the current plot."""
     fileName = QFileDialog.getSaveFileName(self, 'Save Path')
     path, file_extension = os.path.splitext(fileName[0])
     if file_extension == "":
         file_extension = "png"
     else:
         file_extension = file_extension[1:]
     try:
         self.contactPlotter.saveFigure(path, file_extension)
     except ValueError:
         box = ErrorBox(
             "File format " + file_extension +
             " is not supported.\nPlease choose from eps, pdf, pgf,"
             " png, ps, raw, rgba, svg, svgz. ")
         box.exec_()
Exemple #8
0
    def analyzeDataPushed(self):
        """Handles the Analyzer after the Accumulation maps have been set."""
        if self.analysis is None:
            box = ErrorBox(ErrorMessages.NODATA_PROMPTLOAD)
            box.exec_()
            return

        self.maps, result = AnalysisDialog.getMapping()
        if result == 1:
            self.analysis.frameUpdate.connect(self.updateAnalyzedFrames)
            self.setInfoLabel("Analyzing contacts...")
            map1 = self.maps[0]
            map2 = self.maps[1]
            nproc = int(self.settingsView.coreBox.value())
            self.contacts = self.analysis.runContactAnalysis(map1, map2, nproc)
            self.progressBar.setValue(0)
            self.setInfoLabel("Updating timeline...")
            QApplication.processEvents()
            self.updateSettings()
            self.updateFilters()
            self.cleanInfoLabel()
 def plotMap(self):
     """Plots the contact map."""
     sip.delete(self.tab3.mapPlot)
     self.tab3.mapPlot = MapPlotter(None, width=8, height=5, dpi=60)
     self.grid2.addWidget(self.tab3.mapPlot, 3, 0, 1, 4)
     if self.map1 is None or self.map2 is None or self.contacts is None or len(
             self.contacts) == 0:
         box = ErrorBox(ErrorMessages.RESID_REQUIRED)
         box.exec_()
         return
     res = self.tab3.mapPlot.plotMap(self.contacts, self.map1, self.map2,
                                     self.label1, self.label2,
                                     self.tab3.attributeBox.currentText(),
                                     self.threshold, self.nsPerFrame)
     if res == -1:
         box = ErrorBox(ErrorMessages.RESID_REQUIRED)
         box.exec_()
     self.tab3.mapPlot.update()
 def plotMap(self):
     """Plots the contact map."""
     sip.delete(self.tab3.mapPlot)
     self.tab3.mapPlot = MapPlotter(None, width=8, height=5, dpi=60)
     self.grid2.addWidget(self.tab3.mapPlot, 3, 0, 1, 4)
     if self.map1 is None or self.map2 is None or self.contacts is None or len(self.contacts) == 0:
         box = ErrorBox(ErrorMessages.RESID_REQUIRED)
         box.exec_()
         return
     res = self.tab3.mapPlot.plotMap(self.contacts, self.map1, self.map2, self.label1, self.label2,
                                     self.tab3.attributeBox.currentText(), self.threshold, self.nsPerFrame)
     if res == -1:
         box = ErrorBox(ErrorMessages.RESID_REQUIRED)
         box.exec_()
     self.tab3.mapPlot.update()
    def createTclScriptVis(self):
        """Creates the Tcl script for VMD visualization of the selections."""
        if len(self.contacts) == 0:
            box = ErrorBox(ErrorMessages.NOCONTACTS)
            box.exec_()
            return

        fileName = QFileDialog.getSaveFileName(self, 'Save Path')
        if len(fileName[0]) > 0:
            path, file_extension = os.path.splitext(fileName[0])
            if file_extension != ".tcl":
                file_extension = ".tcl"

            path += file_extension

            f = open(path, 'w')
            f.write('mol new %s \n' % self.psf)
            f.write('mol addfile %s \n' % self.dcd)
            f.write('mol delrep 0 top \n')
            f.write('mol representation NewCartoon \n')
            f.write('mol Color ColorID 3 \n')
            f.write('mol selection {all} \n')
            f.write('mol addrep top \n')

            if self.tab4.splitVisCheckbox.isChecked():
                for cont in self.contacts:
                    currentSel1 = []
                    index = 0
                    for item in cont.key1:
                        if item != "none":
                            currentSel1.append(
                                AccumulationMapIndex.vmdsel[index] + " " +
                                item)
                        index += 1
                    currentSel1String = " and ".join(currentSel1)
                    currentSel2 = []
                    index = 0
                    for item in cont.key2:
                        if item != "none":
                            currentSel2.append(
                                AccumulationMapIndex.vmdsel[index] + " " +
                                item)
                        index += 1
                    currentSel2String = " and ".join(currentSel2)
                    add1 = ("" if self.tab4.additionalText1.text() == "" else
                            (" and " + self.tab4.additionalText1.text()))
                    add2 = ("" if self.tab4.additionalText2.text() == "" else
                            (" and " + self.tab4.additionalText2.text()))
                    sel = "(" + currentSel1String + add1 + ") or (" + currentSel2String + add2 + ")"
                    f.write('mol representation Licorice \n')
                    f.write('mol Color Name \n')
                    f.write('mol selection {%s} \n' % sel)
                    f.write('mol addrep top \n')
            else:
                total = []
                for cont in self.contacts:
                    currentSel1 = []
                    index = 0
                    for item in cont.key1:
                        if item != "none":
                            currentSel1.append(
                                AccumulationMapIndex.vmdsel[index] + " " +
                                item)
                        index += 1
                    currentSel1String = " and ".join(currentSel1)
                    currentSel2 = []
                    index = 0
                    for item in cont.key2:
                        if item != "none":
                            currentSel2.append(
                                AccumulationMapIndex.vmdsel[index] + " " +
                                item)
                        index += 1
                    currentSel2String = " and ".join(currentSel2)
                    add1 = ("" if self.tab4.additionalText1.text() == "" else
                            (" and " + self.tab4.additionalText1.text()))
                    add2 = ("" if self.tab4.additionalText2.text() == "" else
                            (" and " + self.tab4.additionalText2.text()))
                    sel = "(" + currentSel1String + add1 + ") or (" + currentSel2String + add2 + ")"
                    total.append(sel)
                seltext = " or ".join(total)
                f.write('mol representation Licorice \n')
                f.write('mol Color Name \n')
                f.write('mol selection {%s} \n' % seltext)
                f.write('mol addrep top \n')
            f.close()
Exemple #12
0
    def calculateSasa(self):
        """Computes the SASA of the given selections."""
        print("calculate SASA")

        self.allSasas = []

        # load psf and trajectory, make lists with radii and coordinates
        if self.psf == "" or self.dcd == "":
            e = ErrorBox(ErrorMessages.CHOOSEFILE)
            e.exec_()
            return

        try:
            u = MDAnalysis.Universe(self.psf, self.dcd)
        except IOError:
            e = ErrorBox(ErrorMessages.FILE_NOT_FOUND)
            e.exec_()
            return

        probeRadius = 1.4

        # seltext = "segid UBQ"
        # resseltext = "segid UBQ and same residue as around 5.0 (segid RN11)"
        seltext = self.sasaSelection1TextField.text()
        seltext2 = self.sasaSelection2TextField.text()
        resseltext = self.sasaRestrictionTextField.text()

        # 0=spiral, 1=random (VMD)
        pointstyle = 1
        # number of points to approximate the sphere
        surfacePoints = 50
        # pair distance
        pairdist = 2.0 * (2.0 + 1.4)

        if resseltext != "":
            restricted = 1
        else:
            restricted = 0

        selection = u.select_atoms(seltext)

        # natoms = len(selection.atoms)
        radius = []
        restrictedList = []
        if restricted:
            ressel = u.select_atoms(resseltext)
            for s in selection.atoms:
                if s in ressel.atoms:
                    restrictedList.append(1)
                else:
                    restrictedList.append(0)
                radius.append(vdwRadius(s.name[0]))
        else:
            restrictedList = [0]
            for s in selection.atoms:
                radius.append(vdwRadius(s.name[0]))
        natoms = len(selection)
        nprad = np.array(radius, dtype=np.float32)
        restrictedList = np.array(restrictedList, dtype=np.int32)

        # TODO: bug if selection is not static for all frames
        # TODO: dynamic allocation of positions in every frame!
        input_coords = []
        for ts in u.trajectory:
            # ressel = u.select_atoms(resseltext)
            # print("restricted: ", len(ressel.atoms))
            input_coords.append(selection.positions)

        nprocs = self.coreBox.value()
        input_chunks = chunks(input_coords, nprocs)
        pool = LoggingPool(nprocs)
        results = []
        rank = 0
        trajLength = len(u.trajectory)
        self.totalFramesToProcess = trajLength
        for input_coords_chunk in input_chunks:
            results.append(pool.apply_async(calculate_sasa_parallel, args=(input_coords_chunk, natoms, pairdist, nprad,
                                                                           surfacePoints, probeRadius, pointstyle,
                                                                           restricted, restrictedList, rank)))
            rank += 1
        print("ranks", rank)
        self.state = True
        self.sasaEventListener()
        pool.close()
        pool.join()

        self.state = False
        for r in results:
            self.allSasas.extend(r.get())

        del radius

        if self.calculateContactAreaCheckbox.isChecked():
            print("Calculate contact area")
            selection2 = u.select_atoms(seltext2)

            # natoms2 = len(selection2.atoms)
            radius2 = []
            restrictedList2 = []
            if restricted:
                ressel = u.select_atoms(resseltext)
                for s in selection2.atoms:
                    if s in ressel.atoms:
                        restrictedList2.append(1)
                    else:
                        restrictedList2.append(0)
                    radius2.append(vdwRadius(s.name[0]))
            else:
                print("You need a restricted selection for contact areas!")

            natoms2 = len(selection2)
            nprad = np.array(radius2, dtype=np.float32)
            restrictedList2 = np.array(restrictedList2, dtype=np.int32)

            input_coords2 = []
            for ts in u.trajectory:
                input_coords2.append(selection2.positions)

            input_chunks2 = chunks(input_coords2, nprocs)
            pool = LoggingPool(nprocs)
            results = []
            rank = 0
            trajLength = len(u.trajectory)
            self.totalFramesToProcess = trajLength
            for input_coords_chunk2 in input_chunks2:
                results.append(pool.apply_async(calculate_sasa_parallel, args=(input_coords_chunk2, natoms2, pairdist,
                                                                               nprad, surfacePoints, probeRadius,
                                                                               pointstyle, restricted, restrictedList2,
                                                                               rank)))
                rank += 1
            print("ranks", rank)
            self.state = True
            self.sasaEventListener()
            pool.close()
            pool.join()

            all_sasas2 = []
            for r in results:
                all_sasas2.extend(r.get())

            diff_list = []
            for sasa_value1, sasa_value2 in zip(self.allSasas, all_sasas2):
                diff_list.append(sasa_value1 - sasa_value2)
            self.allSasas = diff_list

        sip.delete(self.previewPlot)
        self.previewPlot = SimplePlotter(None, width=4, height=2, dpi=70)
        self.previewPlot.plot(np.arange(0, trajLength, 1), self.allSasas)
        self.previewPlot.axes.set_xlabel("frame")
        if self.calculateContactAreaCheckbox.isChecked():
            self.previewPlot.axes.set_ylabel(r'Contact Area [A$^{\circ}$$^{2}$]')
        else:
            self.previewPlot.axes.set_ylabel(r'SASA [A$^{\circ}$$^{2}$]')
        self.graphGridLayout.addWidget(self.previewPlot)
        self.previewPlot.update()
    def createTclScriptVis(self):
        """Creates the Tcl script for VMD visualization of the selections."""
        if len(self.contacts) == 0:
            box = ErrorBox(ErrorMessages.NOCONTACTS)
            box.exec_()
            return

        fileName = QFileDialog.getSaveFileName(self, 'Save Path')
        if len(fileName[0]) > 0:
            path, file_extension = os.path.splitext(fileName[0])
            if file_extension != ".tcl":
                file_extension = ".tcl"

            path += file_extension

            f = open(path, 'w')
            f.write('mol new %s \n' % self.psf)
            f.write('mol addfile %s \n' % self.dcd)
            f.write('mol delrep 0 top \n')
            f.write('mol representation NewCartoon \n')
            f.write('mol Color ColorID 3 \n')
            f.write('mol selection {all} \n')
            f.write('mol addrep top \n')

            if self.tab4.splitVisCheckbox.isChecked():
                for cont in self.contacts:
                    currentSel1 = []
                    index = 0
                    for item in cont.key1:
                        if item != "none":
                            currentSel1.append(AccumulationMapIndex.vmdsel[index] + " " + item)
                        index += 1
                    currentSel1String = " and ".join(currentSel1)
                    currentSel2 = []
                    index = 0
                    for item in cont.key2:
                        if item != "none":
                            currentSel2.append(AccumulationMapIndex.vmdsel[index] + " " + item)
                        index += 1
                    currentSel2String = " and ".join(currentSel2)
                    add1 = ("" if self.tab4.additionalText1.text() == "" else (" and " + self.tab4.additionalText1.text()))
                    add2 = ("" if self.tab4.additionalText2.text() == "" else (" and " + self.tab4.additionalText2.text()))
                    sel = "("+currentSel1String + add1 + ") or (" + currentSel2String + add2 + ")"
                    f.write('mol representation Licorice \n')
                    f.write('mol Color Name \n')
                    f.write('mol selection {%s} \n' % sel)
                    f.write('mol addrep top \n')
            else:
                total = []
                for cont in self.contacts:
                    currentSel1 = []
                    index = 0
                    for item in cont.key1:
                        if item != "none":
                            currentSel1.append(AccumulationMapIndex.vmdsel[index] + " " + item)
                        index += 1
                    currentSel1String = " and ".join(currentSel1)
                    currentSel2 = []
                    index = 0
                    for item in cont.key2:
                        if item != "none":
                            currentSel2.append(AccumulationMapIndex.vmdsel[index] + " " + item)
                        index += 1
                    currentSel2String = " and ".join(currentSel2)
                    add1 = ("" if self.tab4.additionalText1.text() == "" else (" and " + self.tab4.additionalText1.text()))
                    add2 = ("" if self.tab4.additionalText2.text() == "" else (" and " + self.tab4.additionalText2.text()))
                    sel = "(" + currentSel1String + add1 + ") or (" + currentSel2String + add2 + ")"
                    total.append(sel)
                seltext = " or ".join(total)
                f.write('mol representation Licorice \n')
                f.write('mol Color Name \n')
                f.write('mol selection {%s} \n' % seltext)
                f.write('mol addrep top \n')
            f.close()
Exemple #14
0
    def calculateSasa(self):
        """Computes the SASA of the given selections."""
        print("calculate SASA")

        self.allSasas = []

        # load psf and trajectory, make lists with radii and coordinates
        if self.psf == "" or self.dcd == "":
            e = ErrorBox(ErrorMessages.CHOOSEFILE)
            e.exec_()
            return

        try:
            u = MDAnalysis.Universe(self.psf, self.dcd)
        except IOError:
            e = ErrorBox(ErrorMessages.FILE_NOT_FOUND)
            e.exec_()
            return

        probeRadius = 1.4

        # seltext = "segid UBQ"
        # resseltext = "segid UBQ and same residue as around 5.0 (segid RN11)"
        seltext = self.sasaSelection1TextField.text()
        seltext2 = self.sasaSelection2TextField.text()
        resseltext = self.sasaRestrictionTextField.text()

        # 0=spiral, 1=random (VMD)
        pointstyle = 1
        # number of points to approximate the sphere
        surfacePoints = 50
        # pair distance
        pairdist = 2.0 * (2.0 + 1.4)

        if resseltext != "":
            restricted = 1
        else:
            restricted = 0

        selection = u.select_atoms(seltext)

        # natoms = len(selection.atoms)
        radius = []
        restrictedList = []
        if restricted:
            ressel = u.select_atoms(resseltext)
            for s in selection.atoms:
                if s in ressel.atoms:
                    restrictedList.append(1)
                else:
                    restrictedList.append(0)
                radius.append(vdwRadius(s.name[0]))
        else:
            restrictedList = [0]
            for s in selection.atoms:
                radius.append(vdwRadius(s.name[0]))
        natoms = len(selection)
        nprad = np.array(radius, dtype=np.float32)
        restrictedList = np.array(restrictedList, dtype=np.int32)

        # TODO: bug if selection is not static for all frames
        # TODO: dynamic allocation of positions in every frame!
        input_coords = []
        for ts in u.trajectory:
            # ressel = u.select_atoms(resseltext)
            # print("restricted: ", len(ressel.atoms))
            input_coords.append(selection.positions)

        nprocs = self.coreBox.value()
        input_chunks = chunks(input_coords, nprocs)
        pool = LoggingPool(nprocs)
        results = []
        rank = 0
        trajLength = len(u.trajectory)
        self.totalFramesToProcess = trajLength
        for input_coords_chunk in input_chunks:
            results.append(
                pool.apply_async(calculate_sasa_parallel,
                                 args=(input_coords_chunk, natoms, pairdist,
                                       nprad, surfacePoints, probeRadius,
                                       pointstyle, restricted, restrictedList,
                                       rank)))
            rank += 1
        print("ranks", rank)
        self.state = True
        self.sasaEventListener()
        pool.close()
        pool.join()

        self.state = False
        for r in results:
            self.allSasas.extend(r.get())

        del radius

        if self.calculateContactAreaCheckbox.isChecked():
            print("Calculate contact area")
            selection2 = u.select_atoms(seltext2)

            # natoms2 = len(selection2.atoms)
            radius2 = []
            restrictedList2 = []
            if restricted:
                ressel = u.select_atoms(resseltext)
                for s in selection2.atoms:
                    if s in ressel.atoms:
                        restrictedList2.append(1)
                    else:
                        restrictedList2.append(0)
                    radius2.append(vdwRadius(s.name[0]))
            else:
                print("You need a restricted selection for contact areas!")

            natoms2 = len(selection2)
            nprad = np.array(radius2, dtype=np.float32)
            restrictedList2 = np.array(restrictedList2, dtype=np.int32)

            input_coords2 = []
            for ts in u.trajectory:
                input_coords2.append(selection2.positions)

            input_chunks2 = chunks(input_coords2, nprocs)
            pool = LoggingPool(nprocs)
            results = []
            rank = 0
            trajLength = len(u.trajectory)
            self.totalFramesToProcess = trajLength
            for input_coords_chunk2 in input_chunks2:
                results.append(
                    pool.apply_async(calculate_sasa_parallel,
                                     args=(input_coords_chunk2, natoms2,
                                           pairdist, nprad, surfacePoints,
                                           probeRadius, pointstyle, restricted,
                                           restrictedList2, rank)))
                rank += 1
            print("ranks", rank)
            self.state = True
            self.sasaEventListener()
            pool.close()
            pool.join()

            all_sasas2 = []
            for r in results:
                all_sasas2.extend(r.get())

            diff_list = []
            for sasa_value1, sasa_value2 in zip(self.allSasas, all_sasas2):
                diff_list.append(sasa_value1 - sasa_value2)
            self.allSasas = diff_list

        sip.delete(self.previewPlot)
        self.previewPlot = SimplePlotter(None, width=4, height=2, dpi=70)
        self.previewPlot.plot(np.arange(0, trajLength, 1), self.allSasas)
        self.previewPlot.axes.set_xlabel("frame")
        if self.calculateContactAreaCheckbox.isChecked():
            self.previewPlot.axes.set_ylabel(
                r'Contact Area [A$^{\circ}$$^{2}$]')
        else:
            self.previewPlot.axes.set_ylabel(r'SASA [A$^{\circ}$$^{2}$]')
        self.graphGridLayout.addWidget(self.previewPlot)
        self.previewPlot.update()