コード例 #1
0
def draw_figure(canvas, figure, canvas_toolbar):
    if canvas.children:
        for child in canvas.winfo_children():
            child.destroy()
    if canvas_toolbar.children:
        for child in canvas_toolbar.winfo_children():
            child.destroy()
    figure_canvas_agg = FigureCanvasTkAgg(figure, canvas)
    figure_canvas_agg.draw()
    toolbar = Toolbar(figure_canvas_agg, canvas_toolbar)
    toolbar.config(background='#E3B04B',)
    for button in toolbar.winfo_children():
        button.config(background='#E3B04B')
    toolbar.update()
    figure_canvas_agg.get_tk_widget().pack(side="top", fill="both", expand=1)
コード例 #2
0
ファイル: CustomDialog.py プロジェクト: SwastikC/iSpec
class CustomDialog(Dialog):

    def __init__(self, parent, title, components):

        if not parent:
            parent = tkinter._default_root

        self.results = None
        self.components = components
        Dialog.__init__(self, parent, title)

    def destroy(self):
        self.components = None
        Dialog.destroy(self)

    def body(self, master):
        first_entry = None
        row = 0
        grid_frame = tkinter.Frame(master) # Form
        plot_frame = tkinter.Frame(master) # Plot
        stats_frame = tkinter.Frame(master) # Listbox
        for i, component in enumerate(self.components):
            row += i
            if component["type"].lower() == "label":
                component["object"] = tkinter.Label(grid_frame, text=component["text"])
                component["object"].grid(row=row, columnspan=2)
            if component["type"].lower() == "entry":
                tkinter.Label(grid_frame, text=component["text"]).grid(row=row, sticky=tkinter.W)
                component["object"] = tkinter.Entry(grid_frame, justify=tkinter.RIGHT)
                component["object"].delete(0, tkinter.END)
                component["object"].insert(0, str(component["default"]))
                component["object"].grid(row=row, column=1)
                if first_entry is None:
                    first_entry = component["object"]
            elif component["type"].lower() == "checkbutton":
                component["variable"] = tkinter.IntVar() # set to 1 if the button is selected, and 0 otherwise
                component["variable"].set(component["default"])
                component["object"] = tkinter.Checkbutton(grid_frame, text=component["text"], variable=component["variable"])
                component["object"].grid(row=row, columnspan=2, sticky=tkinter.E)
            #elif component["type"].lower() == "combobox":
            elif component["type"].lower() == "optionmenu":
                if len(component["options"]) <= 0:
                    raise Exception("Options needed!")
                tkinter.Label(grid_frame, text=component["text"]).grid(row=row, sticky=tkinter.W)
                component["variable"] = tkinter.StringVar()

                if "ttk" in list(sys.modules.keys()):
                    # It supports better long lists of options
                    max_width = 20
                    for value in component["options"]:
                        if len(value) > max_width:
                            max_width = len(value)+1
                    component["variable"].set(component["default"])
                    component["object"] = tkinter.ttk.Combobox(grid_frame, textvariable=component["variable"], state='readonly', width=max_width)
                    component["object"]['values'] = tuple(component["options"])
                    component["object"].grid(row=row, column=1, sticky=tkinter.W)
                else:
                    tkinter.Label(grid_frame, text=component["text"]).grid(row=row, sticky=tkinter.W)
                    component["variable"] = tkinter.StringVar()
                    component["variable"].set(component["default"])
                    component["object"] = tkinter.OptionMenu(*(grid_frame, component["variable"]) + tuple(component["options"]))
                    component["object"].grid(row=row, column=1, sticky=tkinter.W)
            elif component["type"].lower() == "radiobutton":
                tkinter.Label(grid_frame, text=component["text"]).grid(row=row, sticky=tkinter.W)
                component["variable"] = tkinter.StringVar()
                objects = []
                for j, text in enumerate(component["options"]):
                    objects.append(tkinter.Radiobutton(grid_frame, text=text, variable=component["variable"], value=text))
                    objects[-1].grid(row=row, column=1, sticky=tkinter.W)
                    row += 1
                component["variable"].set(component["default"])
            elif component["type"].lower() == "listbox" and component["options"] is not None and len(component["options"]) > 0:
                stats_scrollbar = tkinter.Scrollbar(stats_frame, orient=tkinter.VERTICAL)
                component["object"] = tkinter.Listbox(stats_frame, height=5, yscrollcommand=stats_scrollbar.set, font=('courier',10,'normal'), selectmode=tkinter.EXTENDED)
                stats_scrollbar.pack(side=tkinter.RIGHT, fill=tkinter.Y)
                component["object"].delete(0, tkinter.END) # Delete all
                for text in component["options"]:
                    component["object"].insert(tkinter.END, text)
                component["object"].pack(fill=tkinter.BOTH, expand=1)
            elif component["type"].lower() == "plot" and component["function"] is not None:
                # Create the mpl Figure and FigCanvas objects.
                # 5x4 inches, 100 dots-per-inch
                #
                self.dpi = 100
                self.fig = Figure((6.0, 3.0), dpi=self.dpi)
                self.canvas = FigCanvas(self.fig, master=plot_frame)
                self.canvas.draw()
                #self.canvas.get_tk_widget().grid(row = 0, column = 0)  # or .grid(row = 0)

                ### Since we have only one plot, we can use add_axes
                ### instead of add_subplot, but then the subplot
                ### configuration tool in the navigation toolbar wouldn't
                ### work.
                ###
                if component["axes"] == 1:
                    self.axes = self.fig.add_subplot(1, 1, 1)
                    #### Avoid using special notation that are not easy to understand in axis for big zoom
                    myyfmt = ScalarFormatter(useOffset=False)
                    self.axes.get_xaxis().set_major_formatter(myyfmt)
                    self.axes.get_yaxis().set_major_formatter(myyfmt)

                    self.toolbar = NavigationToolbar(self.canvas, plot_frame)
                    self.toolbar.update()

                    self.canvas._tkcanvas.pack(side=tkinter.TOP, fill=tkinter.BOTH, expand=1)
                elif component["axes"] > 1:
                    self.axes = []
                    for i in range(component["axes"]):
                        self.axes.append(self.fig.add_subplot(2, 1, i+1))
                        #### Avoid using special notation that are not easy to understand in axis for big zoom
                        myyfmt = ScalarFormatter(useOffset=False)
                        self.axes[i].get_xaxis().set_major_formatter(myyfmt)
                        self.axes[i].get_yaxis().set_major_formatter(myyfmt)

                    self.toolbar = NavigationToolbar(self.canvas, plot_frame)
                    self.toolbar.update()

                    self.canvas._tkcanvas.pack(side=tkinter.TOP, fill=tkinter.BOTH, expand=1)

                # Plotting function
                component["function"](*(self.axes, component))

        plot_frame.pack(side=tkinter.TOP, fill=tkinter.BOTH, expand=1)
        stats_frame.pack(side=tkinter.TOP, fill=tkinter.BOTH, expand=1)
        grid_frame.pack(side=tkinter.TOP, fill=tkinter.BOTH, expand=1)

        # Which should receive focus:
        return first_entry

    def validate(self):

        for component in self.components:
            if component["type"] == "Entry":
                try:
                    #value = float(component["object"].get())
                    if component["text-type"] == "str":
                        value = eval(component["text-type"] + "('%s')" % component["object"].get())
                    else:
                        value = eval(component["text-type"] + "(%s)" % component["object"].get())
                except Exception:
                    tkinter.messagebox.showwarning(
                        "Illegal value",
                        "Illegal value for " + component["text"] + "\nPlease try again",
                        parent = self
                    )
                    return 0
                if component["minvalue"] is not None and value < component["minvalue"]:
                    tkinter.messagebox.showwarning(
                        "Too small",
                        "'%s': "
                        "The allowed minimum value is %s. "
                        "Please try again." % (component["text"], component["minvalue"]),
                        parent = self
                    )
                    return 0
                if component["maxvalue"] is not None and value > component["maxvalue"]:
                    tkinter.messagebox.showwarning(
                        "Too big",
                        "'%s': "
                        "The allowed maximum value is %s. "
                        "Please try again." % (component["text"], component["maxvalue"]),
                        parent = self
                    )
                    return 0
        return 1

    def apply(self):
        self.results = {}
        for component in self.components:
            # Save results and modify defaults
            if component["type"] == "Entry":
                if component["text-type"] == "str":
                    value = eval(component["text-type"] + "('%s')" % component["object"].get())
                else:
                    value = eval(component["text-type"] + "(%s)" % component["object"].get())
                self.results[component["text"]] = value
                component["default"] = str(value)
            elif component["type"] in ["Checkbutton", "OptionMenu", "Radiobutton"]:
                self.results[component["text"]] = component["variable"].get()
                component["default"] = component["variable"].get()
コード例 #3
0
def itemClicked(event):
    specKey = str(left_tree.focus())
    global f, f2, canvas, specCanvas, onlySpectra, threeDthing, spectrumWindow, lineCollection, redlineCollection, ax, allSpecPreviousExistence, allSpectra, allLines
    print(specKey)

    chromKey = specKey.split("|")[0]

    if allSpecPreviousExistence is not chromKey:
        if len(lineCollection) > 0:
            for specNum in list(lineCollection):
                #for aLine in lineCollection[specNum]:
                #	aLine.remove()
                del lineCollection[specNum]

        del redlineCollection[:]

        f2.clf()

        # all spectra 3D plot------------------------------------------------
        if spectrumWindow.winfo_exists() == 0:
            spectrumWindow = Tk.Toplevel()  # Makes the window
            spectrumWindow.wm_title("All Spectra")
            spectrumWindow.geometry("700x650")

            topFrame = Tk.Frame(spectrumWindow, width=700, height=700)
            topFrame.pack(side="top", fill="both", expand=True)
            specCanvas = FigureCanvasTkAgg(f2, master=topFrame)

            specCanvas.get_tk_widget().pack(side="top",
                                            fill="both",
                                            expand=True)
            theTool2 = PlotNav(specCanvas, topFrame)
            theTool2.update()

        # on demand loading of all spectral data---------------------------------------
        if chromKey not in allSpectra:
            allSpectra[chromKey] = []

            clustData = next(
                iter(os.walk(os.path.join(allMSdataPath, chromKey))))

            #print os.path.join(allMSdataPath, chromKey)
            clusterPath = os.path.join(allMSdataPath, chromKey)

            majSpecBool = False

            internalSpecCount = 1
            for filename in clustData[2]:
                #print filename
                if ((".txt" in filename) & ("_" in filename)):
                    spectrumReader = open(os.path.join(clusterPath, filename),
                                          "r")
                    _textOut = ""

                    _spectrum = []
                    _count = 0
                    for line in spectrumReader:
                        #_textOut += line

                        if _count == 0:
                            _precursor = float(
                                re.search(r'\d+\.\d+', line).group())
                            _textOut += line
                        elif _count == 1:
                            _intensity = float(
                                re.search(r'\d+\.\d+', line).group())
                            _textOut += line
                        elif _count == 2:
                            _charge = int(re.search(r'\d', line).group())
                            _textOut += line
                        elif _count == 3:
                            _rt = float(re.search(r'\d+\.\d+', line).group())
                            _textOut += line
                        elif _count == 4:
                            _scanNo = float(re.search(r'\d+', line).group())
                            _textOut += line
                        elif _count == 6:
                            _id = re.search(filenamePatt, line).group(1)
                            _textOut += line
                        else:
                            spectrumData = re.match(spectrumPatt, line)
                            if spectrumData != None:
                                _spectrum.append([
                                    float(spectrumData.group(1)),
                                    float(spectrumData.group(2))
                                ])
                                #_textOut += theMZ + " " + str(round(theAb, 2))
                            else:
                                _textOut += line

                        _count += 1

                    spectrumReader.close()

                    storedMSdata[chromKey][1].append(
                        [_precursor, _charge, _rt, internalSpecCount])

                    chromLoc[chromKey][0].append(_rt)
                    chromLoc[chromKey][1].append(_precursor)
                    chromLoc[chromKey][2].append(_intensity)
                    chromLoc[chromKey][3].append("S%s" % (internalSpecCount))
                    chromLoc[chromKey][4].append(_id)

                    numRows = int(math.ceil(len(_spectrum) / 6.0))
                    _specOut = ["" for i in range(numRows)]

                    for i, peak in enumerate(_spectrum):
                        strMZ = str(peak[0])
                        strAb = str(round(peak[1], 2))

                        _specOut[i % numRows] += strMZ + " " + strAb + "\t\t\t"

                    _specOut.insert(
                        0, "\n" + "m/z\tAbundance\t\t" * 6 + "\n" +
                        "-------------------------------\t\t\t" * 6)

                    for aline in _specOut:
                        _textOut += aline + "\n"

                    onlySpectra[chromKey + "|" + str(internalSpecCount)] = [
                        _precursor, _charge, _rt, _spectrum, _textOut,
                        internalSpecCount
                    ]
                    allSpectra[chromKey].append([_spectrum, internalSpecCount])

                    internalSpecCount += 1

                if "majority" in filename:
                    majSpecBool = True

                    majSpectrumReader = open(
                        os.path.join(clusterPath, filename), "r")
                    _textOut = ""

                    _spectrum = []
                    _count = 0
                    for line in majSpectrumReader:
                        #_textOut += line

                        if _count == 0:
                            _monoIso = float(
                                re.search(r'\d+\.\d+', line).group())
                            _textOut += line
                        elif _count == 1:
                            if "UNKNOWN" not in line:
                                _charge = int(re.search(r'\d', line).group())
                            else:
                                _charge = 0

                            _textOut += line

                        elif _count == 2:
                            _constituentCount = int(
                                re.search(r'\d+', line).group())
                            _textOut += line
                        else:
                            majspectrumData = re.match(majSpectrumPatt, line)
                            if majspectrumData is not None:
                                _spectrum.append([
                                    float(majspectrumData.group(1)),
                                    float(majspectrumData.group(2)),
                                    majspectrumData.group(3)
                                ])

                                #_textOut += theMZ + " " + str(round(theAb, 2))
                            else:
                                _textOut += line

                        _count += 1

                    majSpectrumReader.close()

                    numRows = int(math.ceil(len(_spectrum) / 5.0))
                    _specOut = ["" for i in range(numRows)]

                    _maxMZmaj = max(_spectrum)[0]
                    _minMZmaj = min(_spectrum)[0]
                    for i, peak in enumerate(_spectrum):
                        strMZ = str(peak[0])
                        strAb = str(round(peak[1], 2))
                        if len(strAb) > 5:
                            strAb = str(round(peak[1], 1))
                        anno = peak[2]

                        _specOut[
                            i %
                            numRows] += strMZ + " " + strAb + "\t" + anno + "\t\t\t"

                    _specOut.insert(
                        0, "\n" + "m/z\tAb   Freq  Error\t\t\t" * 5 + "\n" +
                        "---------------------------------------\t\t\t\t" * 5)

                    for aline in _specOut:
                        _textOut += aline + "\n"

                    onlySpectra[chromKey + "|Majority"] = [
                        _monoIso, _charge, "N/A", _spectrum, _textOut,
                        "Majority", _maxMZmaj, _minMZmaj
                    ]

            # add to the tree!
            if majSpecBool:
                left_tree.insert(chromKey,
                                 "end",
                                 chromKey + "|Majority",
                                 text="MajoritySpectrum",
                                 values=("", "", _monoIso, "N/A"))

            for spectrumData in storedMSdata[chromKey][1]:
                spectrumCount = spectrumData[3]
                specTreeName = chromKey + "|" + str(spectrumCount)
                _prec = spectrumData[0]
                _rt = spectrumData[2]

                left_tree.insert(chromKey,
                                 "end",
                                 specTreeName,
                                 text="Spectrum" + str(spectrumCount),
                                 values=("", "", _prec, _rt))

            # ------------------ on demand chromatographic data loading
            chromReader = open(
                os.path.join(clusterPath, "chromatographicData.csv"), "r")

            firstLine = chromReader.readline().rstrip()
            chromReader.readline()

            _chromStats = []
            for line in chromReader:
                if "enter: " in line:
                    _initialInfo = line.rstrip()
                    _precursorChrom = float(
                        re.search(precursorPatt, _initialInfo).group(1))
                    _identifier = re.search(filenamePatt,
                                            _initialInfo).group(1)
                elif "Retention" in line:
                    _isoMZs = [
                        float(isoMZ) for isoMZ in re.findall(isoMZPatt, line)
                    ]

                else:
                    chromData = re.match(chromPatt, line)
                    if chromData != None:
                        theAbs = re.findall(AbPatt, line)
                        _chromStats.append(
                            [float(chromData.group(1))] +
                            [float(abVal[1:]) for abVal in theAbs])

                if line.rstrip() == "":
                    #storedMSdata[chromKey]["chromData"].append([_initialInfo, _precursorChrom, _chromStats])
                    _sortedChromStats = sorted(_chromStats)
                    onlyChrom[chromKey][0].add(_identifier)
                    onlyChrom[chromKey][1].append([
                        _initialInfo, _precursorChrom, _sortedChromStats,
                        _identifier, _isoMZs
                    ])
                    _chromStats = []
                    _initialInfo = ""
                    _precursorChrom = "WRONG"

            #if len(storedMSdata[chromKey]["chromData"]) > 1:
            #	print storedMSdata[chromKey]["chromData"]
            chromReader.close()

        #----------------------------------------------------------- 3D drawing of all spectra in the cluster

        allTheSpectra = allSpectra[chromKey]

        #if len(allTheSpectra) > 1:
        ax = f2.add_subplot(111, projection='3d')
        f2.subplots_adjust(left=0.02,
                           right=0.98,
                           top=0.98,
                           bottom=0.02,
                           wspace=0.02)

        ax.set_xlabel('m/z')
        ax.set_ylabel('Spectrum Index')
        ax.set_zlabel('Intensity')

        allMZ = []
        allIndex = []

        for threedspec in allTheSpectra:
            theSpectrum = threedspec[0]

            _theIndex = threedspec[1]
            lineCollection[_theIndex] = []

            allIndex.append(_theIndex)

            for peak in theSpectrum:
                _theMZ = peak[0]
                _theAbs = peak[1]

                if _theAbs > 50:

                    line = art3d.Line3D(*zip((_theMZ, _theIndex, 0),
                                             (_theMZ, _theIndex, _theAbs)),
                                        marker=' ',
                                        markevery=(1, 1))
                    ax.add_line(line)

                    lineCollection[_theIndex].append(line)

                    allMZ.append(_theMZ)

        ax.set_xlim(min(allMZ), max(allMZ))
        ax.set_ylim(0, len(allTheSpectra) + 1)
        ax.set_yticks(allIndex)
        ax.set_zlim(0, 1100)

        toolbar2 = f2.canvas.toolbar
        toolbar2.update()
        specCanvas.draw()

        allSpecPreviousExistence = chromKey

    # ------------------------------- 2D spectrum viewer
    if specKey in onlySpectra:

        #plt.clf()
        if len(threeDthing) > 0:
            a3dthing = threeDthing.pop()
            f.delaxes(a3dthing)
            #a3dthing.remove()
            del a3dthing

        #a = f.add_subplot(111)
        a = f.add_subplot(111)

        f.subplots_adjust(left=0.06, right=0.94, top=0.9, bottom=0.1)
        a.stem([0], [0], markerfmt=' ')
        a.spines['top'].set_visible(False)
        a.spines['right'].set_visible(False)
        #print specKey
        precursorMZ = onlySpectra[specKey][0]
        filteredSpectrum = onlySpectra[specKey][3]
        textOut = onlySpectra[specKey][4]
        specNum = onlySpectra[specKey][5]

        localMajorityBool = False
        if chromKey + "|Majority" in onlySpectra:
            localMajorityBool = True
            majMZmax = onlySpectra[chromKey + "|Majority"][6]
            majMZmin = onlySpectra[chromKey + "|Majority"][7]

        if len(redlineCollection) > 0:
            previousSpecNum = redlineCollection[0][1][1]
            for aLine in lineCollection[previousSpecNum]:
                ax.add_line(aLine)

            [rLine[0].remove() for rLine in redlineCollection]

            redlineCollection = []

        if specNum != "Majority":
            for aLine in lineCollection[specNum]:
                aLine.remove()

        sortedSpectrum = sorted(filteredSpectrum)
        xData = []
        yData = []

        for anAttr in sortedSpectrum:
            xData.append(anAttr[0])
            yData.append(anAttr[1] / 10)

        if localMajorityBool is False:
            theRange = (max(xData) + 10) - (min(xData) - 10)
            a.set_xlim(min(xData) - 10, max(xData) + 10)
        else:
            theRange = (majMZmax + 10) - (majMZmin - 10)
            a.set_xlim(majMZmin - 10, majMZmax + 10)
            print("worked!")

        a.arrow(float(precursorMZ),
                3,
                0.0,
                -1,
                fc="k",
                ec="k",
                head_width=theRange * 0.01,
                head_length=2)
        a.stem(xData, yData, 'silver', markerfmt=' ')

        a.set_ylim(0, 110)
        a.axvline(0, color='black', linewidth=2)

        a.grid(color='lightgray', alpha=0.7)

        a.set_xlabel("m/z", fontsize=12)
        a.set_ylabel("Relative Intensity", fontsize=12)

        whatToPlot = []
        theRecords = [
        ]  # you use this to check if there is any peak that is in the range of your current peak that would get in the way of the text (i.e. it's a higher intensity)
        for mz_intensity in sortedSpectrum:
            #this code will only allow text to be plotted either if the preceding plotted text is far enough away ( > theRange*0.05), or if it has a higher intensity than the preceding plotted text (which it subsequently removes)
            originalIntensity = mz_intensity[1]

            _xcoor = mz_intensity[0]
            _ycoor = originalIntensity / 10.0

            if ((originalIntensity > 50) & (specNum != "Majority")):
                line = art3d.Line3D(*zip((_xcoor, specNum, 0),
                                         (_xcoor, specNum, originalIntensity)),
                                    marker=' ',
                                    c='r',
                                    markevery=(1, 1))
                ax.add_line(line)
                redlineCollection.append(
                    [line, (_xcoor, specNum, originalIntensity)])

            if len(whatToPlot) > 0:
                last_xcoor = whatToPlot[-1][0]
                last_ycoor = whatToPlot[-1][1]

                #print "%s --> %s" % (_xcoor, _xcoor - last_xcoor)

                if (_xcoor - last_xcoor < theRange * 0.05) & (
                        _ycoor > last_ycoor
                ) & (
                        _ycoor > 1
                ):  # if it is NOT far enough away BUT it is taller than the last text then go ahead
                    whatToPlot.pop()
                    whatToPlot.append([_xcoor, _ycoor])
                    #print "popped! %s" % (last_xcoor)
                elif (_xcoor - last_xcoor > theRange * 0.05) & (
                        _ycoor > 1
                ):  # if it is far enough away from the last text then go ahead
                    goAhead = True
                    for checkPrevious in theRecords:
                        if (_xcoor - checkPrevious[0] < theRange * 0.05) & (
                                _ycoor < checkPrevious[1]
                        ):  # check to see if anything in range that is also greater than the current intensity
                            goAhead = False
                    if goAhead == True: whatToPlot.append([_xcoor, _ycoor])
            else:
                if (_ycoor > 1): whatToPlot.append([_xcoor, _ycoor])

            theRecords.append([_xcoor, _ycoor])

        #a.arrow(float(precursorMZ), 3, 0.0, -1, fc="k", ec="k", head_width=theRange*0.05, head_length=5)

        for dataToPlot in whatToPlot:
            a.annotate(str(dataToPlot[0]),
                       xy=(dataToPlot[0], dataToPlot[1]),
                       ha='center',
                       size='x-small')

        toolbar1 = f.canvas.toolbar
        toolbar1.update()
        canvas.draw()

        toolbar2 = f2.canvas.toolbar
        toolbar2.update()
        specCanvas.draw()

        threeDthing.append(a)

        specData.delete(1.0, Tk.END)
        specData.insert(0.0, textOut)

    # ------------------------------- MS1 chromatogram plot
    elif specKey in onlyChrom:

        if len(threeDthing) > 0:
            a3dthing = threeDthing.pop()
            f.delaxes(a3dthing)
            #a3dthing.remove()
            del a3dthing

        f.clf()

        ax2 = f.add_subplot(111, projection='3d')

        ax2.set_xlabel('retention time (seconds)')
        ax2.set_ylabel('m/z')
        ax2.set_zlabel('Raw Abundance')

        IDset = onlyChrom[specKey][0]
        fileNames = dict([(_id, (i * 0.01, i))
                          for i, _id in enumerate(sorted(IDset))])
        allLines = dict([(_id, []) for _id in IDset])

        #print fileNames
        theData = onlyChrom[specKey][1]
        specLocations = chromLoc[specKey]

        allMZs = []
        textOut = onlyChrom[specKey][2] + "\n\n"

        #print theData
        #allTrueTraceMZs = set([math.floor(aSet[1]*10) for aSet in theData])

        allTrueTraceMZs = dict([(_id, set()) for _id in IDset])
        for aSet in theData:
            _identifier = aSet[3]
            quickSearchVal = round(aSet[1] * 10)
            allTrueTraceMZs[_identifier].add(quickSearchVal)
        #print allTrueTraceMZs

        for aSet in theData:
            setLines = []
            _readOutData = aSet[0]
            textOut += _readOutData + "\n"
            _identifier = aSet[3]
            _isoMZs = aSet[4]

            theOffset = fileNames[_identifier][0]
            #theOffset = 0
            colorIndex = fileNames[_identifier][1]

            theLength = len(aSet[2])
            _prec = [aSet[1] for i in range(theLength)]
            _rt = [aSet[2][i][0] for i in range(theLength)]
            _real = [aSet[2][i][1] for i in range(theLength)]

            setLines = []
            #print(aSet[2])
            if len(aSet[2][0]) > 2:
                _fitted = [aSet[2][i][2] for i in range(theLength)]
                theLineFitted, = ax2.plot(_rt,
                                          _prec,
                                          _fitted,
                                          c='mediumblue',
                                          linestyle='--',
                                          label=_identifier)
                setLines.append(theLineFitted)

            # remember this HAS to come AFTER the fitted gaussian line because the legend color will be all messed up
            theLineReal, = ax2.plot(_rt,
                                    _prec,
                                    _real,
                                    c=colors[colorIndex % len(colors)],
                                    label=_identifier)
            setLines.append(theLineReal)

            allMZs.extend(_prec)

            for i, isoMZ in enumerate(_isoMZs):
                if round(isoMZ * 10) not in allTrueTraceMZs[_identifier]:
                    _isoTrace = [aSet[2][j][i + 3] for j in range(theLength)]
                    _isoPrec = [isoMZ for i in range(theLength)]
                    ghostLine, = ax2.plot(_rt,
                                          _isoPrec,
                                          _isoTrace,
                                          c=colors[colorIndex % len(colors)],
                                          label=_identifier,
                                          linestyle=':')
                    allMZs.extend(_isoPrec)

                    setLines.append(ghostLine)

            allLines[_identifier].extend(setLines)

        handles, labels = ax2.get_legend_handles_labels()
        by_label = OrderedDict(zip(labels, handles))
        #theLeg = ax2.legend(list(by_label.values()), list(by_label), loc=2, prop={'size': 7}, bbox_to_anchor=(1, 1))  # remember this moves the legend to not overlap the graph
        theLeg = ax2.legend(by_label.values(),
                            by_label.keys(),
                            loc=2,
                            prop={'size': 9})

        #modYcoors = []
        for x, y, z, theLabel, _id in zip(specLocations[0], specLocations[1],
                                          specLocations[2], specLocations[3],
                                          specLocations[4]):
            theOffset = fileNames[_id][0]
            colorIndex = fileNames[_id][1]
            theText = ax2.text(x, y, z, theLabel, size=9, color='k', label=_id)

            #modYcoors.append(y+theOffset)

            theScat = ax2.scatter(x,
                                  y,
                                  z,
                                  c=colors[colorIndex % len(colors)],
                                  marker='.',
                                  s=40,
                                  label=_id)
            allLines[_id].extend([theText, theScat])

        [legline.set_picker(5)
         for legline in theLeg.get_lines()]  # 5 pts tolerance

        minMZ = min(allMZs + specLocations[1]) - 0.05
        maxMZ = max(allMZs + specLocations[1]) + 0.05
        ax2.set_ylim(minMZ, maxMZ)

        threeDthing.append(ax2)

        specData.delete(1.0, Tk.END)
        specData.insert(0.0, textOut)
        #ax2.legend(loc=2, prop={'size': 9})

        #ax.set_axis_off
        #ax.scatter(pc1[ctrlN:], pc2[ctrlN:], pc3[ctrlN:], c='b', marker='^',s=60)

        canvas.mpl_connect('pick_event', onpick)
        canvas.mpl_connect('button_press_event',
                           lambda event: canvas._tkcanvas.focus_set())
        canvas.mpl_connect('key_press_event', on_key_press)
        canvas.draw()
コード例 #4
0
#rightFrame.grid(row=0, column=1, padx=10, pady=2)

specData = Tk.Text(rightFrame,
                   width=160,
                   height=20,
                   takefocus=0,
                   font=customFont)
#specData.grid(row=4, column=0, padx=10, pady=2)
specData.pack(side="bottom", in_=rightFrame, fill="both", expand=True)

canvas = FigureCanvasTkAgg(f, master=rightFrame)

canvas.get_tk_widget().pack(side="top", fill="both")
theTool = PlotNav(canvas, rightFrame)
theTool.update()

canvas.draw()

topFrame = Tk.Frame(spectrumWindow, width=700, height=700)
topFrame.pack(side="top", fill="both", expand=True)
specCanvas = FigureCanvasTkAgg(f2, master=topFrame)

specCanvas.get_tk_widget().pack(side="top", fill="both", expand=True)
theTool2 = PlotNav(specCanvas, topFrame)
theTool2.update()

specCanvas.draw()

#canvas.get_tk_widget().grid(column=0,row=1)
#canvas.get_tk_widget().pack_forget()