Exemple #1
0
    def on_popup_five(self, event=None):
        """
        Spawns a dialog for the first selected item to select the color.
        Redraws the list control with the new colors and then triggers an EVT_DELETE_SELECTION_2.
        :param event: Unused Event
        :return: None
        """
        # Change Color
        item = self.list_ctrl.GetFirstSelected()
        col = self.list_ctrl.GetItemBackgroundColour(item)
        print("Color In:", col)
        col = wx.Colour(int(col[0]),
                        int(col[1]),
                        int(col[2]),
                        alpha=int(col.alpha))
        col2 = wx.ColourData()
        col2.SetColour(col)
        colout = col2
        dlg = wx.ColourDialog(None, data=col2)
        if dlg.ShowModal() == wx.ID_OK:
            coloutdlg = dlg.GetColourData()
            colout = deepcopy(coloutdlg.GetColour())
            print("Color Out", colout)
            dlg.Destroy()
        else:
            dlg.Destroy()
            return
        topcolor = ([colout[0] / 255., colout[1] / 255., colout[2] / 255.])
        self.list_ctrl.SetItemBackgroundColour(item, col=colout)

        luminance = ud.get_luminance(wx.Colour(colout), type=2)
        #print(wx.Colour(colout), luminance)
        if luminance < luminance_cutoff:
            self.list_ctrl.SetItemTextColour(item, col=white_text)
        else:
            self.list_ctrl.SetItemTextColour(item, col=black_text)

        peak = tofloat(self.list_ctrl.GetItem(item, col=1).GetText())
        i = ud.nearest(self.pks.masses, peak)
        self.pks.peaks[i].color = topcolor

        num = self.list_ctrl.GetSelectedItemCount()
        for i in range(1, num):
            item = self.list_ctrl.GetNextSelected(item)
            self.list_ctrl.SetItemBackgroundColour(item, col=colout)

            if luminance < luminance_cutoff:
                self.list_ctrl.SetItemTextColour(item, col=white_text)
            else:
                self.list_ctrl.SetItemTextColour(item, col=black_text)

            peak = tofloat(self.list_ctrl.GetItem(item, col=1).GetText())
            i = ud.nearest(self.pks.masses, peak)
            self.pks.peaks[i].color = topcolor

        newevent = wx.PyCommandEvent(self.EVT_DELETE_SELECTION_2._getEvtType(),
                                     self.GetId())
        self.GetEventHandler().ProcessEvent(newevent)
Exemple #2
0
 def on_selection(self, min, max):
     minscan = ud.nearest(self.eng.ticdat[:, 0], min)
     if self.eng.ticdat[minscan, 0] < min:
         minscan += 1
     maxscan = ud.nearest(self.eng.ticdat[:, 0], max)
     if self.eng.ticdat[maxscan, 0] > max:
         maxscan -= 1
     if maxscan <= minscan:
         maxscan = minscan + 1
     self.scans = [minscan, maxscan, min, max]
     self.get_scan_data()
Exemple #3
0
 def createcompareplot(self):
     xvals = self.plot2.zoom.comparexvals
     yvals = self.plot2.zoom.compareyvals
     data2d = win_fft_grid(self.rawdata, self.binsize, self.wbin, self.window_fwhm, self.diffrange)
     for x in range(0, len(xvals) // 2):
         if xvals[x * 2] > xvals[x * 2 + 1]: xvals[x * 2], xvals[x * 2 + 1] = xvals[x * 2 + 1], xvals[x * 2]
         if yvals[x * 2] > yvals[x * 2 + 1]: yvals[x * 2], yvals[x * 2 + 1] = yvals[x * 2 + 1], yvals[x * 2]
         # assure that x and y values are not equal
         if xvals[x * 2] == xvals[x * 2 + 1] or yvals[x * 2] == yvals[x * 2 + 1]:
             self.comparetext.SetLabel("Line or point drawn, please try again.")
             return 0
     # Round to nearest value, find index for that value
     nearestxvalind = []
     for val in xvals:
         roundedval = self.wbin * round(val / self.wbin)
         nearestxvalind.append(nearest(data2d[:, 0], roundedval))
     nearestyvalind = []
     indexdiff = ((self.diffrange[1] - self.diffrange[0]) / self.binsize) - 1
     for val in yvals:
         roundedval = self.binsize * round(val / self.binsize)
         nearestyvalind.append(nearest(data2d[0:int(indexdiff), 1], roundedval))
     # Sum up the rows in each box
     boxsums = []
     rowdiffs = []
     maxsum = 0
     for x in range(0, len(xvals) // 2):
         rowsums = []
         tmpdiff = []
         for row in range(nearestyvalind[x * 2], nearestyvalind[x * 2 + 1]):
             sum = 0
             for col in range(nearestxvalind[x * 2], nearestxvalind[x * 2 + 1], int(indexdiff)):
                 sum += data2d[int(col + row), 2]
             rowsums.append(sum)
             tmpdiff.append(self.diffrange[0] + self.binsize + (self.binsize * row))
             if sum > maxsum:
                 maxsum = sum
         boxsums.append(rowsums)
         rowdiffs.append(tmpdiff)
     colormap = cm.get_cmap('rainbow', len(xvals) / 2)
     cols = colormap(np.arange(len(xvals) / 2))
     tmp = [y / maxsum for y in boxsums[0]]
     self.on_get_peaks(data=np.transpose([rowdiffs[0],tmp]))
     self.plot4.plotrefreshtop(rowdiffs[0], tmp, color=cols[0],
                               xlabel="Mass Difference", ylabel="Intensity", linestyle="solid")
     for x in range(1, len(xvals) // 2):
         tmp = [y / maxsum for y in boxsums[x]]
         self.on_get_peaks(data=np.transpose([rowdiffs[x], tmp]))
         self.plot4.plotadd(rowdiffs[x], tmp, cols[x], None)
     self.plot4.repaint()
     return 1
Exemple #4
0
 def peaks_error_FWHM(self, pks, data):
     """
     Calculates the error of each peak in pks using FWHM.
     Looks for the left and right point of the peak that is 1/2 the peaks max intensity, rightmass - leftmass = error
     :param pks:
     :param data: self.data.massdat
     :return:
     """
     pmax = np.amax([p.height for p in pks.peaks])
     datamax = np.amax(np.asarray(data)[:, 1])
     div = datamax / pmax
     for pk in pks.peaks:
         int = pk.height
         index = ud.nearest(data[:, 0], pk.mass)
         leftwidth = 0
         rightwidth = 0
         counter = 1
         leftfound = False
         rightfound = False
         while rightfound is False and leftfound is False:
             if leftfound is False:
                 if data[index - counter, 1] <= (int * div) / 2:
                     leftfound = True
                 else:
                     leftwidth += 1
             if rightfound is False:
                 if data[index + counter, 1] <= (int * div) / 2:
                     rightfound = True
                 else:
                     rightwidth += 1
             counter += 1
         pk.errorFWHM = data[index + rightwidth, 0] - data[index - leftwidth, 0]
Exemple #5
0
def linearize_2d(xvals, yvals, igrid, binsize):
    """
    Linearize the x-axis of a 2D grid
    :param xvals: 2D numpy array (x values)
    :param yvals: 2D numpy array (y values)
    :param igrid: 2D numpy array (intensity values)
    :param binsize: difference between consecutive linear x points
    :return: x, y, and z grid linearized along the x-axis
    """
    firstpoint = math.ceil(xvals[0] / binsize) * binsize
    lastpoint = math.floor(xvals[len(xvals) - 1] / binsize) * binsize
    intx = np.arange(firstpoint, lastpoint, binsize)
    iout = np.zeros((len(intx), len(yvals)))
    shape = igrid.shape
    for i in xrange(0, shape[0]):
        if intx[0] < xvals[i] < intx[len(intx) - 1]:
            index = ud.nearest(intx, xvals[i])
            # iout[index]+=C[i]
            if intx[index] == xvals[i]:
                iout[index] += igrid[i]
            if intx[index] < xvals[i] and index < shape[0] - 1:
                index2 = index + 1
                interpos = ud.linear_interpolation(intx[index], intx[index2],
                                                   xvals[i])
                iout[index] += (1 - interpos) * igrid[i]
                iout[index2] += interpos * igrid[i]
            if intx[index] > xvals[i] and index > 0:
                index2 = index - 1
                interpos = ud.linear_interpolation(intx[index], intx[index2],
                                                   xvals[i])
                iout[index] += (1 - interpos) * igrid[i]
                iout[index2] += interpos * igrid[i]

    xout, yout = np.meshgrid(intx, yvals, indexing='ij')
    return xout, yout, iout
Exemple #6
0
 def add_peaks_mass(self, e=None):
     for p in self.pks.peaks:
         if p.ignore == 0:
             pos = ud.nearest(self.datalist[self.pos][:, 0], p.mass)
             data = self.datalist[self.pos][pos]
             if data[1] > self.config.peakplotthresh * np.amax(
                     self.datalist[self.pos][:, 1]):
                 self.plot.plotadddot(data[0], data[1], p.color, p.marker)
     self.plot.repaint()
Exemple #7
0
 def peaks_error_replicates(self, pks, spectra, config):
     peakvals = []
     for x in range(0, len(pks.peaks)):
         peakvals.append([])
     for i, pk in enumerate(pks.peaks):
         ints = []
         for spec in spectra:
             index = ud.nearest(spec.massdat[:, 0], pk.mass)
             startindmass = ud.nearest(spec.massdat[:, 0], spec.massdat[index, 0] - config.peakwindow)
             endindmass = ud.nearest(spec.massdat[:, 0], spec.massdat[index, 0] + config.peakwindow)
             maxind = index
             for x in range(startindmass, endindmass + 1):
                 if spec.massdat[x, 1] > spec.massdat[maxind, 1]:
                     maxind = x
             peakvals[i].append(spec.massdat[maxind, 0])
             ints.append(spec.massdat[maxind, 1])
         print peakvals[i], ints
         pk.errorreplicate = ud.weighted_std(peakvals[i], ints)
Exemple #8
0
 def on_popup_nine(self, e=None):
     item = self.list_ctrl.GetFirstSelected()
     peak = float(self.list_ctrl.GetItem(item, col=1).GetText())
     i = ud.nearest(self.pks.masses, peak)
     dlg = SelectMarker(self)
     dlg.initialize_interface(self.pks, i)
     self.list_ctrl.SetItem(i, 0, self.pks.peaks[i].textmarker)
     newevent = wx.PyCommandEvent(self.EVT_DELETE_SELECTION_2._getEvtType(),
                                  self.GetId())
     self.GetEventHandler().ProcessEvent(newevent)
Exemple #9
0
 def on_get_peaks(self, e=None, data=None):
     if data is None:
         data=self.diffdat
     print("Data range", np.amin(data[:,0]), "to", np.amax(data[:,0]))
     peaks = peakdetect(data, window=1000.)[:, 0]
     for p in peaks:
         index = nearest(data[:, 0], p)
         idiff = int(3 / self.binsize)
         print("Peak value:", p)
         fit, fitdat = fitting.isolated_peak_fit(data[index - idiff:index + idiff, 0],
                                                 data[index - idiff:index + idiff, 1], psfun=0)
         print("Peak Fit:", fit[1, 0], "+/-", fit[1, 1])
Exemple #10
0
    def on_fit(self, e):
        peaks = ud.peakdetect(self.data1d, window=3)
        print("Peaks:", peaks[:, 0])
        peaks = np.concatenate((peaks, [[0, np.amin(self.data1d[:, 1])]]))
        fitdat, fits = MassFitter(self.data1d, peaks, 3, "microguess").perform_fit()
        print("Fits:", fits[:, 0])

        self.plot3.plotadd(self.data1d[:, 0], fitdat, "green", nopaint=False)

        for f in fits[:, 0]:
            if np.amin(self.data1d[:, 0]) <= f <= np.amax(self.data1d[:, 0]):
                y = np.amax(self.data1d[ud.nearest(self.data1d[:, 0], f), 1])
                self.plot3.addtext(str(np.round(f, 3)), f + 0.075, y * 0.95, vlines=False)
                self.plot3.addtext("", f, y, vlines=True)
Exemple #11
0
    def get_data_from_times(self, min, max):
        minscan = ud.nearest(self.ticdat[:, 0], min)
        if self.ticdat[minscan, 0] < min:
            minscan += 1
        maxscan = ud.nearest(self.ticdat[:, 0], max)
        if self.ticdat[maxscan, 0] > max:
            maxscan -= 1
        if maxscan <= minscan:
            maxscan = minscan + 1
        self.scans = [minscan, maxscan, min, max]

        attrs = {
            "timestart": min,
            "timeend": max,
            "timemid": (min + max) / 2.,
            "scanstart": minscan,
            "scanend": maxscan,
            "scanmid": (minscan + maxscan) / 2.
        }
        self.attrs = attrs

        self.get_data_from_scans([minscan, maxscan])
        return self.mzdata
Exemple #12
0
    def get_chrom_peaks(self, window=None):
        # Cleanup TIC Data
        ticdat = deepcopy(self.ticdat)
        ticdat = ud.gsmooth(ticdat, 2)
        ticdat[:, 1] -= np.amin(ticdat[:, 1])
        # ticdat = ud.gaussian_backgroud_subtract(ticdat, 100)
        maxval = np.amax(ticdat[:, 1])
        ticdat[:, 1] /= maxval
        maxt = np.amax(ticdat[:, 0])
        mint = np.amin(ticdat[:, 0])

        # Set Window
        if window is None:
            window = self.config.chrom_peak_width

        # Set Threshold
        noise = ud.noise_level2(ticdat, percent=0.50)
        print("Noise Level:", noise, "Window:", window)

        # Detect Peaks
        peaks = ud.peakdetect_nonlinear(ticdat, window=window, threshold=noise)

        # Filter Peaks
        goodpeaks = []
        tranges = []
        diffs = np.diff(ticdat[:, 0])
        for p in peaks:
            fwhm, range = ud.calc_FWHM(p[0], ticdat)
            index = ud.nearest(ticdat[:, 0], p[0])
            if index >= len(diffs):
                index = len(diffs) - 1
            localdiff = diffs[index]
            if p[0] - fwhm / 2. < mint or p[
                    0] + fwhm / 2. > maxt or fwhm > 4 * window or fwhm < localdiff * 2 or range[
                        0] == p[0] or range[1] == p[0]:
                print("Bad Peak", p, fwhm, range)
                pass
            else:
                print(p[0], fwhm)
                goodpeaks.append(p)
                tranges.append(range)
        self.chrompeaks = goodpeaks
        self.chrompeaks_tranges = tranges
        return goodpeaks, tranges
Exemple #13
0
    def get_maxima(self):
        """
        Detect peaks in self.offset_totals (the total extracted intensitites) and set default parameters.
        Plot the results.
        :return: None
        """
        defaultcolors = [[255, 0, 0, 255], [0, 0, 255, 255], [0, 255, 0, 255],
                         [255, 0, 255, 255]]
        defaultmarkers = ['o', 'v', '^', '>', 's', 'd', '*']

        peaks = ud.peakdetect(self.offset_totals, window=2, threshold=0.1)
        print(peaks)
        self.zoffs = []
        for p in peaks:
            i = ud.nearest(self.offset_totals[:, 0], p[0])
            zoff = Zoffset()
            zoff.make(p[0], p[1], i,
                      defaultcolors[len(self.zoffs) % len(defaultcolors)],
                      defaultmarkers[len(self.zoffs)])
            self.zoffs.append(zoff)
        self.plot_zoffs()
Exemple #14
0
    def on_com(self, e=None):
        print("Starting COM calculations")
        dims = self.data2d.shape

        x = np.unique(self.data2d[:, 0])
        y = np.unique(self.data2d[:, 1])
        xl = len(x)
        yl = len(y)
        z = self.data2d[:, 2].reshape((xl, yl))
        zlin = np.array([np.max(d) for d in z])

        self.on_label_peaks(e=0)

        coms = []
        for d in z.transpose():
            data = np.transpose([x, d])
            b1 = d > np.amax(d) * 0.1
            com, std = ud.center_of_mass(data[b1])
            coms.append(com)

        for p in self.peaks:
            index = ud.nearest(y, p[0])
            c = coms[index]
            carray = [c]
            try:
                carray.append(coms[index - 1])
            except:
                pass
            try:
                carray.append(coms[index + 1])
            except:
                pass

            com = np.average(carray)
            print(p[0], com)

        self.plot1.plotrefreshtop(y,
                                  coms,
                                  xlabel="Mass Defect",
                                  ylabel="Center of Mass (Da)")
Exemple #15
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)