示例#1
0
    def import_hdf5(self, file=None):
        if file is None:
            file = self.filename
        else:
            self.filename = file
        hdf = h5py.File(file)
        msdata = hdf.require_group(self.topname)
        keys = list(msdata.keys())
        self.indexes = []
        for k in keys:
            try:
                self.indexes.append(int(k))
            except:
                pass
        self.indexes = np.array(self.indexes)
        self.indexes = sorted(self.indexes)
        self.len = len(self.indexes)
        hdf.close()

        if ud.isempty(self.spectra):
            for i in self.indexes:
                s = Spectrum(self.topname, i, self.eng)
                s.read_hdf5(file)
                self.spectra.append(s)
        else:
            for s in self.spectra:
                s.read_hdf5(file)
        if not ud.isempty(self.spectra):
            self.data2 = self.spectra[0].data2
            self.import_vars()
示例#2
0
 def makeplot4(self, e=None, plot=None, data=None, pks=None):
     """
     Plots isolated peaks against the data in self.view.plot4.
     Will plot dots at peak positions.
     If possible, will plot full isolated spectra.
     :param e: unused event
     :param plot: Plot object. Default is None, which will set plot to self.view.plot4
     :return: None
     """
     if plot is None:
         plot = self.view.plot4
     if data is None:
         data = self.eng.data.data2
     if pks is None:
         pks = self.eng.pks
     if self.eng.config.batchflag == 0:
         tstart = time.perf_counter()
         plot.plotrefreshtop(data[:, 0],
                             data[:, 1],
                             "Data with Offset Isolated Species",
                             "m/z (Th)",
                             "Normalized and Offset Intensity",
                             "Data",
                             self.eng.config,
                             nopaint=True)
         num = 0
         if self.eng.config.isotopemode == 1:
             try:
                 stickmax = np.amax(
                     np.array([p.stickdat for p in pks.peaks]))
             except (AttributeError, ValueError):
                 stickmax = 1.0
         else:
             stickmax = 1.0
         for i, p in enumerate(pks.peaks):
             if p.ignore == 0:
                 if (not ud.isempty(p.mztab)) and (not ud.isempty(
                         p.mztab2)):
                     mztab = np.array(p.mztab)
                     mztab2 = np.array(p.mztab2)
                     maxval = np.amax(mztab[:, 1])
                     b1 = mztab[:,
                                1] > self.eng.config.peakplotthresh * maxval
                     plot.plotadddot(mztab2[b1, 0], mztab2[b1, 1], p.color,
                                     p.marker)
                 if not ud.isempty(p.stickdat):
                     plot.plotadd(
                         self.eng.data.data2[:, 0],
                         np.array(p.stickdat) / stickmax -
                         (num + 1) * self.eng.config.separation, p.color,
                         "useless label")
                 num += 1
         plot.repaint()
         tend = time.perf_counter()
         print("Plot 4: %.2gs" % (tend - tstart))
示例#3
0
 def on_load_default(self, e=None):
     """
     Resets the configuration then loads the default config file from self.eng.config.defaultconfig.
     Ignores min and max data cutoffs.
     :param e: unused space for event
     :return: None
     """
     self.on_reset(e)
     if os.path.isfile(self.eng.config.defaultconfig):
         try:
             self.import_config(self.eng.config.defaultconfig)
             try:
                 if not ud.isempty(self.eng.data.rawdata):
                     self.view.controls.ctlminmz.SetValue(
                         str(np.amin(self.eng.data.rawdata[:, 0])))
                     self.view.controls.ctlmaxmz.SetValue(
                         str(np.amax(self.eng.data.rawdata[:, 0])))
                     if self.eng.config.imflag == 1:
                         self.view.controls.ctlmindt.SetValue(
                             str(np.amin(self.eng.data.rawdata3[:, 1])))
                         self.view.controls.ctlmaxdt.SetValue(
                             str(np.amax(self.eng.data.rawdata3[:, 1])))
             except:
                 pass
             print("Loaded: ", self.eng.config.defaultconfig)
         except (ValueError, IndexError, TypeError):
             print("Failed to Load: ", self.eng.config.defaultconfig)
     self.view.SetStatusText("Loaded Default", number=5)
     pass
示例#4
0
    def get_data_fast_memory_heavy(self, scan_range=None, time_range=None):
        if self.data is None:
            self.grab_data()

        data = deepcopy(self.data)
        if time_range is not None:
            scan_range = self.get_scans_from_times(time_range)
            print("Getting times:", time_range)

        if scan_range is not None:
            data = data[int(scan_range[0]):int(scan_range[1] + 1)]
            print("Getting scans:", scan_range)
        else:
            print("Getting all scans, length:", len(self.scans), data.shape)

        if data is None or ud.isempty(data):
            print("Error: Empty Data Object")
            return None

        if len(data) > 1:
            try:
                data = merge_spectra(data)
            except Exception as e:
                concat = np.concatenate(data)
                sort = concat[concat[:, 0].argsort()]
                data = ud.removeduplicates(sort)
                print("2", e)
        elif len(data) == 1:
            data = data[0]
        else:
            data = data
        # plt.figure()
        # plt.plot(data)
        # plt.show()
        return data
示例#5
0
 def on_auto_peak_width(self, e=None):
     self.export_config()
     if not ud.isempty(self.eng.data.data2):
         self.eng.get_auto_peak_width()
         self.import_config()
     else:
         print("Need to process data first")
示例#6
0
 def import_mzml(self, paths, timestep=1.0, scanstep=None, starttp=None, endtp=None, name=None,
                 startscan=None, endscan=None):
     """
     Tested
     :param paths:
     :param timestep:
     :return:
     """
     errors = []
     if starttp is not None:
         self.parse_multiple_files(paths, starttp=starttp, endtp=endtp, timestep=timestep, name=name)
     elif startscan is not None:
         self.parse_multiple_files(paths, startscan=startscan, endscan=endscan, name=name)
     else:
         for p in paths:
             try:
                 if scanstep is not None:
                     self.parse_file(p, scanstep=scanstep)
                 else:
                     self.parse_file(p, timestep=float(timestep))
             except Exception, e:
                 errors.append(p)
                 print e
         if not ud.isempty(errors):
             print "Errors:", errors
示例#7
0
    def on_plot(self, e):
        """
        Attempts to correct and plot the manual assignments.
        :param e: Unused event
        :return: None
        """
        # Make initial plot
        if self.config.imflag == 0:
            self.plot1.plotrefreshtop(self.data[:, 0], self.data[:, 1], "",
                                      "m/z (Th)", "Normalized Intensity",
                                      "Data", self.config)
        else:
            self.plot1.contourplot(self.data,
                                   self.config,
                                   xlab="m/z (Th)",
                                   ylab="Arrival Time (ms)",
                                   title="")

        # Get manual assignments from list
        manuallist = self.masslistbox.list.get_list()
        if not ud.isempty(manuallist):
            # Clean up list to remove empties
            manuallist = np.array(manuallist)
            manuallist = manuallist[np.any([manuallist != 0], axis=2)[0], :]
            # Make the color map
            colormap = cm.get_cmap('rainbow', len(manuallist))
            xcolors = colormap(np.arange(len(manuallist)))
            if self.config.imflag == 1:
                # Try to correct for overlapping regions in IM-MS.
                try:
                    if detectoverlap(manuallist):
                        manuallist = correctassignments(
                            manuallist, np.unique(self.data[:, 0]),
                            np.unique(self.data[:, 1]))
                except Exception as e:
                    print(
                        "Error with overlapping assignments. Try making sure regions don't intersect.",
                        e)
            # Plot the appropriate regions on the plot.
            for i, l in enumerate(manuallist):
                if self.config.imflag == 0:
                    y0 = np.amin(self.data[:, 1])
                    ywidth = np.amax(self.data[:, 1]) - y0
                else:
                    y0 = l[2] - l[3]
                    ywidth = l[3] * 2.
                self.plot1.subplot1.add_patch(
                    Rectangle((l[0] - l[1], y0),
                              l[1] * 2.,
                              ywidth,
                              alpha=0.5,
                              facecolor=xcolors[i],
                              edgecolor='black',
                              fill=True))
            self.plot1.repaint()
            # Refill the list with the corrected values
            self.masslistbox.list.populate(manuallist, colors=xcolors)
        pass
示例#8
0
    def on_close(self, e):
        """
        Close the dialog and apply the changes.

        Sets self.config.masslist to the defined mass list.
        Sets self.config.oligomerlist to the defined oligomers.
        Sets self.config.matchlist to the matched values
        :param e: Unused event
        :return: None
        """
        try:
            tolerance = float(self.ctlmatcherror.GetValue())
        except ValueError:
            tolerance = None
        self.config.matchtolerance = tolerance

        newmasslist = self.masslistbox.list.get_list()
        # print newmasslist
        if not ud.isempty(newmasslist):
            newmasslist = np.array(newmasslist)
            newmasslist = newmasslist[newmasslist > 0]
            # print newmasslist
            if len(newmasslist) > 0:
                self.config.masslist = newmasslist
            else:
                self.config.masslist = []
        oligos = self.oligomerlistbox.list.get_list()
        if not ud.isempty(oligos):
            oligos = np.array(oligos)
            oligoshort = oligos[:, :2]
            oligoshort = oligoshort.astype(np.float)
            oligos = oligos[np.any([oligoshort != 0], axis=2)[0], :]
            # oligos=oligos[::-1]
        self.config.oligomerlist = oligos

        matchlist = np.transpose(self.matchlistbox.list.get_list())
        if not ud.isempty(matchlist):
            self.config.matchlist = matchlist

        self.Destroy()
        try:
            self.EndModal(0)
        except Exception as e:
            pass
示例#9
0
 def on_autocorr_window(self, e):
     """
     Opens up an autocorrelation window for the purpose of figuring out mass differences.
     :param e: Unused event
     :return: None
     """
     if not ud.isempty(self.massdat):
         dlg = AutocorrWindow(self)
         dlg.initalize_dialog(self.config, self.massdat)
         dlg.ShowModal()
示例#10
0
 def add_peaks_mz(self, e=None):
     for p in self.pks.peaks:
         if p.ignore == 0:
             list1 = []
             list2 = []
             mztab = p.mztab[self.pos]
             mztab2 = p.mztab2[self.pos]
             if (not ud.isempty(mztab)) and (not ud.isempty(mztab2)):
                 mztab = np.array(mztab)
                 mztab2 = np.array(mztab2)
                 maxval = np.amax(p.mztab[:, :, 1])
                 for k in range(0, len(mztab)):
                     if mztab[k, 1] > self.config.peakplotthresh * maxval:
                         list1.append(mztab2[k, 0])
                         list2.append(mztab2[k, 1])
                         # print mztab[k]
                 self.plot.plotadddot(np.array(list1), np.array(list2),
                                      p.color, p.marker)
     self.plot.repaint()
示例#11
0
 def read_hdf5(self, file=None):
     if file is None:
         file = self.filename
     else:
         self.filename = file
     hdf = h5py.File(file, 'r')
     msdata = hdf.get(self.topname + "/" + str(self.index))
     self.rawdata = get_dataset(msdata, "raw_data")
     # self.fitdat = get_dataset(msdata, "fit_data")
     self.data2 = get_dataset(msdata, "processed_data")
     if ud.isempty(self.data2) and not ud.isempty(self.rawdata):
         self.data2 = deepcopy(self.rawdata)
     self.massdat = get_dataset(msdata, "mass_data")
     self.zdata = get_dataset(msdata, "charge_data")
     if self.eng.config.datanorm == 1:
         try:
             self.data2[:, 1] /= np.amax(self.data2[:, 1])
         except:
             pass
         try:
             self.massdat[:, 1] /= np.amax(self.massdat[:, 1])
         except:
             pass
         try:
             self.zdata[:, 1] /= np.amax(self.zdata[:, 1])
         except:
             pass
     self.mzgrid = get_dataset(msdata, "mz_grid")
     self.massgrid = get_dataset(msdata, "mass_grid")
     try:
         self.ztab = self.zdata[:, 0]
     except:
         pass
     # self.baseline = get_dataset(msdata, "baseline")
     self.peaks = get_dataset(msdata, "peaks")
     self.setup_peaks()
     self.attrs = dict(list(msdata.attrs.items()))
     hdf.close()
示例#12
0
    def scanpeaks_extracts(self):
        if ud.isempty(self.data.exgrid):
            print("Empty extract grid, running UniDec...")
            self.sum_masses()
            self.out = metaunidec_call(self.config, "-scanpeaks")
            self.data.import_hdf5()

        self.data.exgrid = np.zeros(
            (len(self.pks.peaks), len(self.data.spectra)))
        for i, p in enumerate(self.pks.peaks):
            for j, s in enumerate(self.data.spectra):
                ints = 0
                for p2 in s.pks.peaks:
                    if p2.index == i:
                        ints += p2.height
                self.data.exgrid[i, j] = ints

        self.normalize_exgrid()
示例#13
0
 def on_peak_width_tool(self, e=None):
     """
     Open peak width tool window. After it has returned, update the GUI to reflect the new peak widths.
     :param e: unused event
     :return: None
     """
     self.export_config()
     if not ud.isempty(self.eng.data.data2):
         self.export_config(None)
         if self.eng.config.imflag == 0:
             dlg = peakwidthtools.PeakTools1d(self.view)
             dlg.initialize_interface(self.eng.config, self.eng.data.data2)
         else:
             dlg = peakwidthtools.PeakTools2d(self.view)
             dlg.initialize_interface(self.eng.data.data3, self.eng.data.data2, self.eng.config)
         dlg.ShowModal()
         self.import_config(None)
     else:
         print("Need to process data first")
     pass
    def on_close(self, e):
        """
        Get manuallist from listctrl, clean up, write it to self.config.manuallist, and then destroy the window.
        :param e: Unused event
        :return: None
        """
        manuallist = self.masslistbox.list.get_list()
        if not ud.isempty(manuallist):
            manuallist = np.array(manuallist)
            manuallist = manuallist[np.any([manuallist != 0], axis=2)[0], :]

        if manuallist != "":
            if len(manuallist) > 0:
                self.config.manuallist = manuallist
            else:
                self.config.manuallist = []
        else:
            self.config.manuallist = []

        self.Destroy()
        self.EndModal(0)
示例#15
0
    def read_recent(self):
        if os.path.isfile(self.eng.config.recentfile):
            with open(self.eng.config.recentfile, 'r') as file:
                lines = []
                for l in file:
                    p = l.strip("\n")
                    if os.path.isfile(p):
                        lines.append(p)
        else:
            self.eng.config.recentfile = os.path.join(self.eng.config.UniDecDir, "recent.txt")
            with open(self.eng.config.recentfile, 'w') as file:
                pass  # Create empty file
            return []

        if not ud.isempty(lines):
            lines = np.array(lines)
            lines = lines[::-1][:10]
            unique, indexes = np.unique(lines, return_index=True)
            lines = np.array(unique[indexes.argsort()])
        else:
            lines = []
        return lines
示例#16
0
 def on_match_all(self, e):
     """
     Match the peaks in self.pks to all possible combination of oligomers in the oligomerlist.
     Uses ud.make_all_matches function.
     Populated the matchlistbox with the results of the matching.
     :param e: Unused event
     :return: None
     """
     oligos = self.oligomerlistbox.list.get_list()
     try:
         tolerance = float(self.ctlmatcherror.GetValue())
     except ValueError:
         tolerance = None
     oligomasslist, oligonames = ud.make_all_matches(oligos)
     if ud.isempty(oligomasslist):
         print("ERROR: Need to specify the Potential Oligomers")
         return
     matchlist = ud.match(self.pks,
                          oligomasslist,
                          oligonames,
                          tolerance=tolerance)
     self.matchlistbox.list.populate(matchlist[0], matchlist[1],
                                     matchlist[2], matchlist[3])
示例#17
0
    def peak_extract(self):
        """
        Extract the values for local max (height) and area for peaks in pks from each zoff.extract.
        Plot the results.
        Write the results to files.
        :return: None
        """
        # TODO: Add extra peaks here to compensate for shifts in the peaks.
        peakextracts = np.zeros((len(self.zoffs), self.pks.plen))
        peakextractsarea = np.zeros((len(self.zoffs), self.pks.plen))

        try:
            xvals = self.pks.masses
        except AttributeError:
            print("No Peaks to Extract")
            return None

        if xvals is not None:
            # Extraction
            for i, z in enumerate(self.zoffs):
                for j, p in enumerate(self.pks.peaks):
                    x = z.extract[:, 0]
                    y = z.extract[:, 1]
                    index = ud.nearest(x, p.mass)
                    peakextracts[i, j] = ud.localmax2(
                        y, index,
                        int(self.config.peakwindow / self.config.massbins))
                    if not ud.isempty(p.integralrange):
                        integral, intdat = ud.integrate(
                            z.extract, p.integralrange[0], p.integralrange[1])
                        peakextractsarea[i, j] = integral

            # Switch to subunit numbers
            if self.massoffset > 0:
                xvals = np.round(np.array(xvals) / self.massoffset)
                label = "Subunit Number"
            else:
                label = "Mass (Da)"

            # Plots
            # Create height extraction line plot
            sum1 = np.sum(peakextracts, axis=0)
            smax1 = np.amax(sum1)
            if np.amax(sum1) != 0:
                sum1 /= smax1
                self.plot3.plotrefreshtop(xvals,
                                          sum1,
                                          title="Extracted Heights",
                                          xlabel=label,
                                          ylabel="Intensity",
                                          integerticks=True,
                                          test_kda=True)
                for i, z in enumerate(self.zoffs):
                    self.plot3.plotadd(xvals, peakextracts[i] / smax1,
                                       np.array(z.color) / 255., str(i))
                self.plot3.repaint()

                # Create height extraction bar chart
                xvals2 = np.arange(0, len(sum1))
                colormap = cm.get_cmap(self.config.peakcmap, len(xvals))
                peakcolors = colormap(np.arange(len(xvals)))
                self.plot5.barplottop(xvals2, sum1, [int(i) for i in xvals],
                                      peakcolors, label,
                                      "Normalized Intensity",
                                      "Extracted Total Peak Heights")

            # Make Plots for Integrals
            sum2 = np.sum(peakextractsarea, axis=0)
            smax2 = np.amax(sum2)
            if np.amax(sum2) != 0:
                sum2 /= smax2
                # Make line plots
                self.plot4.plotrefreshtop(xvals,
                                          sum2,
                                          title="Extracted Areas",
                                          xlabel=label,
                                          ylabel="Area",
                                          integerticks=True,
                                          test_kda=True)
                for i, z in enumerate(self.zoffs):
                    self.plot4.plotadd(xvals, peakextractsarea[i] / smax2,
                                       np.array(z.color) / 255., str(i))
                self.plot4.repaint()
                # Make bar charts
                self.plot6.barplottop(xvals2, sum2, [int(i) for i in xvals],
                                      peakcolors, label,
                                      "Normalized Intensity",
                                      "Extracted Total Peak Areas")
            else:
                print("No integration provided")

            # Save total outputs for extracted peaks
            try:
                np.savetxt(self.config.outfname + "_extracted_heights.txt",
                           peakextracts)
                np.savetxt(
                    self.config.outfname + "_total_extracted_heights.txt",
                    np.transpose([self.pks.masses, xvals, sum1]))
                if np.amax(sum2) != 0:
                    np.savetxt(self.config.outfname + "_extracted_areas.txt",
                               peakextractsarea)
                    np.savetxt(
                        self.config.outfname + "_total_extracted_areas.txt",
                        np.transpose([self.pks.masses, xvals, sum2]))
            except Exception as e:
                print("Error saving files", e)
示例#18
0
    def __init__(self,
                 parent,
                 data_list,
                 config=None,
                 yvals=None,
                 pks=None,
                 value=None,
                 directory=None):
        """
        Creates a window for visualizing high-mass mass defects.
        :param parent: Passed to wx.Frame
        :param data_list: List of mass distribution data.
        :param config: UniDecConfig object
        :param yvals: List of titles for each mass distribution in data_list
        :param pks: Peaks object
        :param value: Kendrick reference mass (default is 760.076, the mass of POPC)
        :param directory: Directory to save files to (default is os.getcwd())
        :return: None
        """
        wx.Frame.__init__(self, parent, title="Mass Defect")  # ,size=(-1,-1))

        # Setup initial values
        if directory is None:
            self.directory = os.getcwd()
        else:
            self.directory = directory

        self.parent = parent
        self.m0 = deepcopy(value)
        if self.m0 is None:
            self.m0 = 760.076

        if config is None:
            self.config = unidecstructure.UniDecConfig()
            self.config.initialize()
            self.config.discreteplot = 0
            self.config.cmap = u"jet"
            self.config.peakcmap = u"rainbow"
            self.config.separation = 0.025
        else:
            self.config = config

        self.config.publicationmode = 0
        self.pos = -1
        self.yvals = yvals

        self.ylab = "Normalized Mass Defect"
        if self.config.defectparams is not None:
            p = self.config.defectparams
            self.nbins = p[0]
            self.transformmode = p[1]
            self.centermode = p[2]
            self.xtype = p[3]
        else:
            self.nbins = 50
            self.transformmode = 1
            self.centermode = 1
            self.xtype = 0
        self.factor = 1
        self.xlab = ""
        self.outfname = os.path.splitext(self.config.filename)[0]
        if self.outfname is not "":
            self.outfname += "_"

        try:
            self.datalist = [data_list[0]]
        except:
            self.datalist = data_list[0]

        for i in range(1, len(data_list)):
            self.datalist.append(ud.mergedata(data_list[0], data_list[i]))
        self.datalist = np.array(self.datalist)

        if self.yvals is not None:
            try:
                self.yvals = np.array(self.yvals, dtype="float")
            except:
                self.yvals = np.arange(0, len(self.datalist))

        self.datasum = np.transpose(
            [self.datalist[0, :, 0],
             np.sum(self.datalist[:, :, 1], axis=0)])
        print("Data list shape:", self.datalist.shape)

        # Make the menu
        filemenu = wx.Menu()
        if self.datalist.shape[0] > 1:
            extractwindow = filemenu.Append(
                wx.ID_ANY, "Extract Mass Defect Values",
                "Open Window to Extract Mass Defect Values")
            self.Bind(wx.EVT_MENU, self.on_extract_window, extractwindow)
            filemenu.AppendSeparator()

        menu_save_fig_png = filemenu.Append(
            wx.ID_ANY, "Save Figures as PNG",
            "Save all figures as PNG in central directory")
        menu_save_fig_pdf = filemenu.Append(
            wx.ID_ANY, "Save Figures as PDF",
            "Save all figures as PDF in central directory")

        self.Bind(wx.EVT_MENU, self.on_save_fig, menu_save_fig_png)
        self.Bind(wx.EVT_MENU, self.on_save_fig_pdf, menu_save_fig_pdf)

        self.plotmenu = wx.Menu()
        self.menuaddline = self.plotmenu.Append(
            wx.ID_ANY, "Add Horizontal Line",
            "Add Horizontal Line at Specific Y Value")
        self.menufit = self.plotmenu.Append(wx.ID_ANY, "Fit Peaks",
                                            "Fit total mass defect peaks")
        self.menupeaks = self.plotmenu.Append(wx.ID_ANY, "Label Peaks",
                                              "Label peaks")
        self.Bind(wx.EVT_MENU, self.on_add_line, self.menuaddline)
        self.Bind(wx.EVT_MENU, self.on_fit, self.menufit)
        self.Bind(wx.EVT_MENU, self.on_label_peaks, self.menupeaks)

        menu_bar = wx.MenuBar()
        menu_bar.Append(filemenu, "&File")
        menu_bar.Append(self.plotmenu, "Plot")
        self.SetMenuBar(menu_bar)

        # Setup the GUI
        panel = wx.Panel(self)

        self.plot1 = plot1d.Plot1d(panel)
        self.plot2 = plot2d.Plot2d(panel)
        self.plot3 = plot1d.Plot1d(panel)
        self.plot4 = plot1d.Plot1d(panel)

        if self.datalist.shape[0] > 1:
            self.flag2 = True
            self.plot5 = plot1d.Plot1d(panel)
            self.plot6 = plot2d.Plot2d(panel)
        else:
            self.flag2 = False
            self.plot5 = None
            self.plot6 = None

        sizer = wx.BoxSizer(wx.VERTICAL)
        plotsizer1 = wx.BoxSizer(wx.HORIZONTAL)
        plotsizer2 = wx.BoxSizer(wx.HORIZONTAL)
        plotsizer1.Add(self.plot1, 2, wx.EXPAND)
        plotsizer1.Add(self.plot4, 0, wx.EXPAND)

        plotsizer2.Add(self.plot2, 2, wx.EXPAND)
        plotsizer2.Add(self.plot3, 0, wx.EXPAND)

        if self.flag2:
            plotsizer1.Add(self.plot5, 0, wx.EXPAND)
            plotsizer2.Add(self.plot6, 0, wx.EXPAND)
        sizer.Add(plotsizer1, 1, wx.EXPAND)
        sizer.Add(plotsizer2, 1, wx.EXPAND)

        controlsizer = wx.BoxSizer(wx.HORIZONTAL)

        self.ctlm0 = wx.TextCtrl(panel, value=str(self.m0))
        self.ctlwindow = wx.TextCtrl(panel, value=str(self.nbins))
        controlsizer.Add(wx.StaticText(panel, label="Kendrick Mass"), 0,
                         wx.ALIGN_CENTER_VERTICAL)
        controlsizer.Add(self.ctlm0, 0, wx.ALIGN_CENTER_VERTICAL)
        controlsizer.Add(wx.StaticText(panel, label="Number of Defect Bins"),
                         0, wx.ALIGN_CENTER_VERTICAL)
        controlsizer.Add(self.ctlwindow, 0, wx.ALIGN_CENTER_VERTICAL)

        controlsizer2 = wx.BoxSizer(wx.HORIZONTAL)
        if len(data_list) > 1:
            label = "Back"
        else:
            label = "Replot"
        backbutton = wx.Button(panel, label=label)
        controlsizer2.Add(backbutton, 0, wx.EXPAND)
        self.Bind(wx.EVT_BUTTON, self.on_back, backbutton)
        if len(data_list) > 1:
            nextbutton = wx.Button(panel, label="Next")
            controlsizer2.Add(nextbutton, 0, wx.EXPAND)
            self.Bind(wx.EVT_BUTTON, self.on_next, nextbutton)
            totalbutton = wx.Button(panel, label="Total")
            controlsizer2.Add(totalbutton, 0, wx.EXPAND)
            self.Bind(wx.EVT_BUTTON, self.makeplottotal, totalbutton)
        else:
            if not ud.isempty(pks):
                self.pks = pks
                peaksbutton = wx.Button(panel, label="Plot Peaks")
                controlsizer2.Add(peaksbutton, 0, wx.EXPAND)
                self.Bind(wx.EVT_BUTTON, self.on_peaks, peaksbutton)

        self.radiobox = wx.RadioBox(panel,
                                    choices=["Integrate", "Interpolate"],
                                    label="Type of Transform")
        controlsizer.Add(self.radiobox, 0, wx.EXPAND)
        self.radiobox.SetSelection(self.transformmode)

        self.radiobox2 = wx.RadioBox(panel,
                                     choices=["-0.5:0.5", "0:1"],
                                     label="Range")
        controlsizer.Add(self.radiobox2, 0, wx.EXPAND)
        self.radiobox2.SetSelection(self.centermode)

        self.radiobox3 = wx.RadioBox(panel,
                                     choices=["Normalized", "Mass (Da)"],
                                     label="Mass Defect Units")
        controlsizer.Add(self.radiobox3, 0, wx.EXPAND)
        self.radiobox3.SetSelection(self.xtype)

        sizer.Add(controlsizer, 0, wx.EXPAND)
        sizer.Add(controlsizer2, 0, wx.EXPAND)

        panel.SetSizer(sizer)
        sizer.Fit(self)

        self.Bind(wx.EVT_CLOSE, self.on_close)

        try:
            self.makeplottotal(0)
        except Exception as e:
            self.on_next(0)

        self.Centre()
        # self.MakeModal(True)
        self.Show(True)
        self.Raise()
示例#19
0
    def __init__(self, parent, data_list, config=None, yvals=None, directory=None, header=None, params=None):
        """
        Create wx.Frame and initialzie components
        :param parent: Parent window or panel passed to wx.Frame
        :param data_list: Input data for extraction in a list of arrays (N x 2)
        :param config: UniDecConfig object. If None, will use defaults.
        :param yvals: Position values for corresponding data_list elements.
        For plots, these become the titles. For the Weighted-Average-of-Position (WAP) these are the position values.
        :param directory: Directory for saving files. Default is current working directory.
        :param header: Header for files that are written. Default is "Extract"
        :param params: List of 8 values that define the parameters for extraction.

        0=mass 0
        1=mass 1
        2=mass 2
        3=minimum oligomeric state of mass 1
        4=maximum oligomeric state of mass 1
        5=minimum oligomeric state of mass 2
        6=maximum oligomeric state of mass 2
        7=Error window for finding intensity value

        masses = m0 + m1 * range(min m1, max m1 +1) + m2 * range(min m2, max m2 +1)

        :return: None
        """
        wx.Frame.__init__(self, parent, title="2D Grid Extraction", size=(-1, -1))
        # Make Menu
        self.filemenu = wx.Menu()
        self.menuSaveFigPNG = self.filemenu.Append(wx.ID_ANY, "Save Figures as PNG",
                                                   "Save all figures as PNG in central directory")
        self.menuSaveFigPDF = self.filemenu.Append(wx.ID_ANY, "Save Figures as PDF",
                                                   "Save all figures as PDF in central directory")
        self.Bind(wx.EVT_MENU, self.on_save_fig, self.menuSaveFigPNG)
        self.Bind(wx.EVT_MENU, self.on_save_figPDF, self.menuSaveFigPDF)

        self.plotmenu = wx.Menu()
        self.menufit = self.plotmenu.Append(wx.ID_ANY, "Fit Gaussians",
                                            "Fit total distribution to a series of Gaussians")
        self.menufit2 = self.plotmenu.Append(wx.ID_ANY, "Fit Poisson",
                                             "Fit total distribution to a Poisson Distribution")
        self.menufit3 = self.plotmenu.Append(wx.ID_ANY, "Fit Binomial",
                                             "Fit total distribution to a Binomial Distribution")
        self.menufit4 = self.plotmenu.Append(wx.ID_ANY, "Fit Multiple Poissons",
                                             "Fit total distribution to multiple Poisson distributions")
        self.Bind(wx.EVT_MENU, self.on_fit, self.menufit)
        self.Bind(wx.EVT_MENU, self.on_fit2, self.menufit2)
        self.Bind(wx.EVT_MENU, self.on_fit3, self.menufit3)
        self.Bind(wx.EVT_MENU, self.on_fit4, self.menufit4)

        self.menuBar = wx.MenuBar()
        self.menuBar.Append(self.filemenu, "&File")
        self.menuBar.Append(self.plotmenu, "Plot")
        self.SetMenuBar(self.menuBar)
        # Initialize Parameters
        if config is None:
            # Default UniDecConfig object
            self.config = unidecstructure.UniDecConfig()
            self.config.initialize()
        else:
            self.config = config

        if directory is None:
            self.directory = os.getcwd()
        else:
            self.directory = directory

        if header is None:
            self.header = "Extract"
        else:
            self.header = header

        if params is None:
            self.params = [98868, 760.076, 22044, 0, 90, 0, 2, 0]
            self.params = [0, 4493, 678, 1, 20, 0, 30, 10]
        else:
            self.params = params

        self.datalist = data_list
        self.dlen = len(data_list)
        self.pos = -1
        self.yvals = np.array(yvals).astype(np.float)
        if ud.isempty(yvals):
            self.yvals = np.arange(0, len(data_list))
        self.storediscrete = deepcopy(self.config.discreteplot)

        # Setup GUI
        panel = wx.Panel(self)
        sizer = wx.BoxSizer(wx.VERTICAL)
        self.plot1 = plot1d.Plot1d(panel)
        self.plot2 = plot2d.Plot2d(panel)
        sizer.Add(self.plot1, 1, wx.EXPAND)
        sizer.Add(self.plot2, 1, wx.EXPAND)

        controlsizer = wx.BoxSizer(wx.HORIZONTAL)
        controlsizer1 = wx.BoxSizer(wx.HORIZONTAL)

        self.ctlm0 = wx.TextCtrl(panel, value=str(self.params[0]))
        self.ctlm1 = wx.TextCtrl(panel, value=str(self.params[1]))
        self.ctlm2 = wx.TextCtrl(panel, value=str(self.params[2]))
        self.ctlm1min = wx.TextCtrl(panel, value=str(self.params[3]))
        self.ctlm1max = wx.TextCtrl(panel, value=str(self.params[4]))
        self.ctlm2min = wx.TextCtrl(panel, value=str(self.params[5]))
        self.ctlm2max = wx.TextCtrl(panel, value=str(self.params[6]))
        self.ctlwindow = wx.TextCtrl(panel, value=str(self.params[7]))

        controlsizer.Add(wx.StaticText(panel, label="Mass 0"), 0, wx.ALIGN_CENTER_VERTICAL)
        controlsizer.Add(self.ctlm0, 0, wx.EXPAND)
        controlsizer.Add(wx.StaticText(panel, label="Mass 1"), 0, wx.ALIGN_CENTER_VERTICAL)
        controlsizer.Add(self.ctlm1, 0, wx.EXPAND)
        controlsizer.Add(wx.StaticText(panel, label="Mass 2"), 0, wx.ALIGN_CENTER_VERTICAL)
        controlsizer.Add(self.ctlm2, 0, wx.EXPAND)
        controlsizer.Add(wx.StaticText(panel, label="Mass Window"), 0, wx.ALIGN_CENTER_VERTICAL)
        controlsizer.Add(self.ctlwindow, 0, wx.EXPAND)
        if self.dlen > 1:
            self.ctlnorm = wx.CheckBox(panel, label="Normalize")
            controlsizer.Add(self.ctlnorm, 0, wx.EXPAND)
        controlsizer1.Add(wx.StaticText(panel, label="Mass 1 Min #"), 0, wx.ALIGN_CENTER_VERTICAL)
        controlsizer1.Add(self.ctlm1min, 0, wx.EXPAND)
        controlsizer1.Add(wx.StaticText(panel, label="Mass 1 Max #"), 0, wx.ALIGN_CENTER_VERTICAL)
        controlsizer1.Add(self.ctlm1max, 0, wx.EXPAND)
        controlsizer1.Add(wx.StaticText(panel, label="Mass 2 Min #"), 0, wx.ALIGN_CENTER_VERTICAL)
        controlsizer1.Add(self.ctlm2min, 0, wx.EXPAND)
        controlsizer1.Add(wx.StaticText(panel, label="Mass 2 Max #"), 0, wx.ALIGN_CENTER_VERTICAL)
        controlsizer1.Add(self.ctlm2max, 0, wx.EXPAND)

        controlsizer2 = wx.BoxSizer(wx.HORIZONTAL)

        backbutton = wx.Button(panel, label="Back")
        nextbutton = wx.Button(panel, label="Next")
        if self.dlen > 1:
            totalbutton = wx.Button(panel, label="Total")
        else:
            totalbutton = wx.Button(panel, label="Replot")
        #wapbutton = wx.Button(panel, label="WAP")
        if self.dlen > 1:
            controlsizer2.Add(backbutton, 0, wx.EXPAND)
            controlsizer2.Add(nextbutton, 0, wx.EXPAND)
        controlsizer2.Add(totalbutton, 0, wx.EXPAND)
        #if self.dlen > 1:
            #controlsizer2.Add(wapbutton, 0, wx.EXPAND)

        self.Bind(wx.EVT_BUTTON, self.on_back, backbutton)
        self.Bind(wx.EVT_BUTTON, self.on_next, nextbutton)
        self.Bind(wx.EVT_BUTTON, self.on_total, totalbutton)
        #self.Bind(wx.EVT_BUTTON, self.on_wap, wapbutton)

        sizer.Add(controlsizer, 0, wx.EXPAND)
        sizer.Add(controlsizer1, 0, wx.EXPAND)
        sizer.Add(controlsizer2, 0, wx.EXPAND)

        self.Bind(wx.EVT_CLOSE, self.on_close, self)

        panel.SetSizer(sizer)
        sizer.Fit(self)
        # Run initial extraction
        try:
            self.on_total(0)
        except Exception as e:
            try:
                self.on_next(0)
            except:
                pass
            print(e)
        self.Centre()
        self.Show(True)
        self.normflag = 1
示例#20
0
    def export_gui_to_config(self):
        """
        Exports parameters from the GUI to the config object.
        :return: None
        """
        self.config.minmz = ud.string_to_value(self.ctlminmz.GetValue())
        self.config.maxmz = ud.string_to_value(self.ctlmaxmz.GetValue())
        # self.config.smooth = ud.string_to_value(self.ctlsmooth.GetValue())
        self.config.mzbins = ud.string_to_value(self.ctlbinsize.GetValue())
        self.config.subbuff = ud.string_to_value(self.ctlbuff.GetValue())
        # self.config.subtype = self.subtypectl.GetSelection()
        # self.config.intthresh = ud.string_to_value(self.ctlintthresh.GetValue())
        self.config.massbins = ud.string_to_value(self.ctlmassbins.GetValue())
        self.config.endz = ud.string_to_int(self.ctlendz.GetValue())
        self.config.startz = ud.string_to_int(self.ctlstartz.GetValue())
        self.config.zzsig = ud.string_to_value(self.ctlzzsig.GetValue())
        self.config.mzsig = ud.string_to_value(self.ctlmzsig.GetValue())
        self.config.massub = ud.string_to_value(self.ctlmassub.GetValue())
        self.config.masslb = ud.string_to_value(self.ctlmasslb.GetValue())
        self.config.mtabsig = ud.string_to_value(self.ctlmtabsig.GetValue())
        self.config.psfun = self.ctlpsfun.GetSelection()
        self.config.peaknorm = self.ctlnorm.GetSelection()
        self.config.mfileflag = int(self.ctlmasslistflag.GetValue())
        self.config.peakwindow = ud.string_to_value(self.ctlwindow.GetValue())
        self.config.peakthresh = ud.string_to_value(self.ctlthresh.GetValue())
        self.config.peakplotthresh = ud.string_to_value(
            self.ctlthresh2.GetValue())
        self.config.separation = ud.string_to_value(self.ctlsep.GetValue())
        self.config.adductmass = ud.string_to_value(
            self.ctladductmass.GetValue())
        # self.config.detectoreffva = ud.string_to_value(self.ctlaccelvolt.GetValue())
        self.config.msig = ud.string_to_value(self.ctlmsig.GetValue())
        self.config.molig = ud.string_to_value(self.ctlmolig.GetValue())
        self.config.numit = ud.string_to_int(self.ctlnumit.GetValue())
        self.config.nativezlb = ud.string_to_value(
            self.ctlminnativez.GetValue())
        self.config.nativezub = ud.string_to_value(
            self.ctlmaxnativez.GetValue())
        self.config.integratelb = ud.string_to_value(self.ctlintlb.GetValue())
        self.config.integrateub = ud.string_to_value(self.ctlintub.GetValue())

        self.config.crossover = ud.string_to_value(
            self.ctlcrossover.GetValue())
        self.config.numtot = ud.string_to_value(self.ctlnumtot.GetValue())

        self.config.isotopemode = int(self.ctlisotopemode.GetValue())
        self.config.datanorm = int(self.ctldatanorm.GetValue())
        self.config.orbimode = int(self.ctlorbimode.GetValue())
        self.config.manualfileflag = int(self.ctlmanualassign.GetValue())
        # self.config.linflag = self.ctlbintype.GetSelection()
        if self.config.mzbins == 0:
            self.config.linflag = 2
            # self.ctlbintype.SetSelection(int(self.config.linflag))
        self.config.discreteplot = int(self.ctldiscrete.GetValue())
        self.config.publicationmode = int(self.ctlpublicationmode.GetValue())
        self.config.rawflag = self.ctlrawflag.GetSelection()

        self.config.cmap = self.ctl2dcm.GetStringSelection().encode('ascii')
        self.config.peakcmap = self.ctlpeakcm.GetStringSelection().encode(
            'ascii')
        self.config.poolflag = self.ctlpoolflag.GetSelection()

        self.config.exnorm = self.ctlnorm2.GetSelection()
        self.config.exchoice = self.ctlextract.GetSelection()
        try:
            self.config.exwindow = float(self.ctlextractwindow.GetValue())
        except ValueError:
            self.config.exwindow = 0
        try:
            if not self.config.minmz and not ud.isempty(
                    self.pres.eng.data.spectra[0].rawdata):
                self.config.minmz = np.amin(
                    self.pres.eng.data.spectra[0].rawdata[:, 0])
            if not self.config.maxmz and not ud.isempty(
                    self.pres.eng.data.spectra[0].rawdata):
                self.config.maxmz = np.amax(
                    self.pres.eng.data.spectra[0].rawdata[:, 0])
        except:
            self.config.minmz = 0
            self.config.maxmz = 1000000

        if self.config.msig > 0:
            self.parent.SetStatusText("Oligomer Blur Mass: " +
                                      str(self.config.molig) + " Std Dev: " +
                                      str(self.config.msig),
                                      number=4)
        else:
            self.parent.SetStatusText(" ", number=4)