fontsize=14, verticalalignment='top', horizontalalignment='left', bbox=patch_properties) # make a splan selector and have it turned off initially until user # presses 'q' or 'a' on the key board via toggle_selector span = SpanSelector(ax1, onselect, 'horizontal', useblit=True, rectprops=dict(alpha=0.5, facecolor='red')) span.visible = False # connect span with the toggle selector in order to toggle span selector on and off span.connect_event('key_press_event', toggle_selector) # make sure that the layout of the subplots do not overlap plt.tight_layout() plt.show() except IOError as error: print 'cannot read file' + error.filename print error.message except IndexError as error: print 'Cannot read file! Bad file!' print error.message except ValueError as error: print error.message
class HELPQDialg(QWidget): def __init__(self, parent=None): super(HELPQDialg, self).__init__(parent) self.results = {} self.help_result = [] self.pc = 0 self.ms = [] self.rt = [] self.createVariabletable() self.create_canvas1('scan', 'ETA or LPG') self.create_canvas2('scan', 'Resolved Chromatographic Profiles') self.canvas1.setMinimumWidth(800) self.canvas1.setMaximumWidth(800) self.canvas2.setMinimumWidth(800) self.canvas2.setMaximumWidth(800) self.mthcombox = QComboBox() self.mthcombox.addItem("ETA") self.mthcombox.addItem("LPG") self.DoETA = QPushButton("Do") LAYER = QLabel("LAYER:") self.LComboBox = QSpinBox() wLabel = QLabel("W:") self.DComboBox = QSpinBox() self.DComboBox.setRange(3, 9) self.DComboBox.setSingleStep(2) self.DComboBox.setValue(7) CLabel1 = QLabel("~") CLabel2 = QLabel("~") CLabel3 = QLabel("~") Selabel = QLabel("SE:") self.SComboBox1 = QLineEdit() self.SComboBox2 = QLineEdit() self.sbtn = QPushButton("...") Ovlabel = QLabel("OV:") self.obtn1 = QPushButton("...") self.OComboBox1 = QLineEdit() self.OComboBox2 = QLineEdit() self.OComboBox3 = QLineEdit() self.OComboBox4 = QLineEdit() self.obtn2 = QPushButton("...") self.DoFR = QPushButton("FR") self.addbtn = QPushButton("Add raw data") self.undobtn = QPushButton("Undo") hbox0 = QHBoxLayout() hbox0.addWidget(LAYER) hbox0.addWidget(self.LComboBox) hbox1 = QHBoxLayout() hbox1.addWidget(wLabel) hbox1.addWidget(self.DComboBox) hbox2 = QHBoxLayout() hbox2.addWidget(self.mthcombox) hbox2.addWidget(self.DoETA) hbox3 = QHBoxLayout() hbox3.addWidget(Selabel) hbox3.addWidget(self.SComboBox1) hbox3.addWidget(CLabel1) hbox3.addWidget(self.SComboBox2) hbox3.addWidget(self.sbtn) hbox4 = QHBoxLayout() hbox4.addWidget(Ovlabel) hbox4.addWidget(self.OComboBox1) hbox4.addWidget(CLabel2) hbox4.addWidget(self.OComboBox2) hbox4.addWidget(self.obtn1) hbox5 = QHBoxLayout() hbox5.addWidget(Ovlabel) hbox5.addWidget(self.OComboBox3) hbox5.addWidget(CLabel3) hbox5.addWidget(self.OComboBox4) hbox5.addWidget(self.obtn2) hbox6 = QHBoxLayout() hbox6.addStretch() hbox6.addWidget(self.DoFR) hbox7 = QHBoxLayout() hbox7.addStretch() hbox7.addWidget(self.undobtn) GLay = QGridLayout() GLay.addWidget(self.addbtn, 0, 0) GLay.addLayout(hbox0, 1, 0) GLay.addLayout(hbox1, 2, 0) GLay.addLayout(hbox2, 3, 0) GLay.addLayout(hbox3, 4, 0) GLay.addLayout(hbox4, 5, 0) GLay.addLayout(hbox5, 6, 0) GLay.addLayout(hbox6, 7, 0) GLay.addLayout(hbox7, 8, 0) VLay = QVBoxLayout() VLay.addWidget(self.canvas1) VLay.addWidget(self.canvas2) VLay1 = QVBoxLayout() VLay1.addLayout(GLay) VLay1.addStretch() mainLayout = QHBoxLayout() mainLayout.addLayout(VLay) mainLayout.addLayout(VLay1) self.setLayout(mainLayout) self.resize(800, 600) self.move(320, 75) self.setWindowTitle("HELP") self.span1.set_active(True) self.span2.set_active(False) self.span3.set_active(False) self.DoETA.clicked.connect(self.eta) self.DoFR.clicked.connect(self.fr) self.undobtn.clicked.connect(self.undo) self.sbtn.clicked.connect(self.span_mode1) self.obtn1.clicked.connect(self.span_mode2) self.obtn2.clicked.connect(self.span_mode3) def createVariabletable(self): self.VariableTable = QtGui.QTableWidget(0, 1) self.VariableTable.setSelectionMode( QtGui.QAbstractItemView.SingleSelection) self.VariableTable.horizontalHeader().hide() self.VariableTable.verticalHeader().hide() self.VariableTable.setShowGrid(False) self.VariableTable.setFixedWidth(200) def redraw1(self): self.canvas1.draw() self.update() def redraw2(self): self.canvas2.draw() self.update() def create_canvas1(self, xname, title): self.fig1 = plt.figure() self.axes1 = plt.subplot(111) self.axes1.set_xlabel(xname) self.axes1.set_title(title, fontsize=9) self.canvas1 = FigureCanvas(self.fig1) self.axes1.tick_params(axis='both', labelsize=8) ymino, ymaxo = self.axes1.get_ylim() xmino, xmaxo = self.axes1.get_xlim() self.oxy = [(xmino, xmaxo), (ymino, ymaxo)] self.span1 = SpanSelector(self.axes1, self.span_select_callback1, 'horizontal', minspan=0.002, useblit=True, rectprops=dict(alpha=0.5, facecolor='red'), onmove_callback=None, button=[1]) self.span2 = SpanSelector(self.axes1, self.span_select_callback2, 'horizontal', minspan=0.002, useblit=True, rectprops=dict(alpha=0.5, facecolor='green'), onmove_callback=None, button=[1]) self.span3 = SpanSelector(self.axes1, self.span_select_callback3, 'horizontal', minspan=0.002, useblit=True, rectprops=dict(alpha=0.5, facecolor='green'), onmove_callback=None, button=[1]) plt.subplots_adjust(bottom=0.2, top=0.90, left=0.08, right=0.9) self.redraw1() self.span1.set_active(True) def create_canvas2(self, xname, title): self.fig2 = plt.figure() self.axes2 = plt.subplot(111) self.axes2.set_xlabel(xname) self.axes2.set_title(title, fontsize=9) self.canvas2 = FigureCanvas(self.fig2) self.axes2.tick_params(axis='both', labelsize=8) plt.subplots_adjust(bottom=0.2, top=0.90, left=0.08, right=0.9) self.redraw2() def span_mode1(self, event): self.span1.set_active(True) self.span2.set_active(False) self.span3.set_active(False) self.span1.connect_event('motion_notify_event', self.span1.onmove) self.span1.connect_event('button_press_event', self.span1.press) self.span1.connect_event('button_release_event', self.span1.release) self.leftdblclick = False self.rightdblclick = False self.redraw1() print "span1" def span_mode2(self, event): self.span1.set_active(False) self.span3.set_active(False) self.span2.set_active(True) self.span2.connect_event('motion_notify_event', self.span2.onmove) self.span2.connect_event('button_press_event', self.span2.press) self.span2.connect_event('button_release_event', self.span2.release) self.leftdblclick = False self.rightdblclick = False self.redraw1() print "span2" def span_mode3(self, event): self.span1.set_active(False) self.span2.set_active(False) self.span3.set_active(True) self.span3.connect_event('motion_notify_event', self.span3.onmove) self.span3.connect_event('button_press_event', self.span3.press) self.span3.connect_event('button_release_event', self.span3.release) self.leftdblclick = False self.rightdblclick = False self.redraw1() print "span3" def span_select_callback1(self, xmin, xmax): ax = np.arange(0, self.x['d'].shape[0]) imin, imax = np.searchsorted(ax, (xmin, xmax)) imax = min(len(ax) - 1, imax) seg = ax[[imin, imax]] # self.axes1.scatter(xmin, self.y[imin], s=30, marker='^', # color='red', label='x1 samples') # self.axes1.scatter(xmax, self.y[imax], s=30, marker='v', # color='red', label='x1 samples') self.axes1.fill_between(range(imin, imax), self.oxy[1][0], self.oxy[1][1], facecolor='yellow', alpha=0.5) self.redraw1() self.SComboBox1.setText(str(imin)) self.SComboBox2.setText(str(imax)) def span_select_callback2(self, xmin, xmax): ax = np.arange(0, self.x['d'].shape[0]) imin, imax = np.searchsorted(ax, (xmin, xmax)) imax = min(len(ax) - 1, imax) seg = ax[[imin, imax]] # self.axes1.scatter(xmin, self.y[imin], s=30, marker='^', # color='red', label='x1 samples') # self.axes1.scatter(xmax, self.y[imax], s=30, marker='v', # color='red', label='x1 samples') self.axes1.fill_between(range(imin, imax), self.oxy[1][0], self.oxy[1][1], facecolor='Green', alpha=0.5) self.redraw1() self.OComboBox1.setText(str(imin)) self.OComboBox2.setText(str(imax)) def span_select_callback3(self, xmin, xmax): ax = np.arange(0, self.x['d'].shape[0]) imin, imax = np.searchsorted(ax, (xmin, xmax)) imax = min(len(ax) - 1, imax) seg = ax[[imin, imax]] self.axes1.fill_between(range(imin, imax), self.oxy[1][0], self.oxy[1][1], facecolor='Green', alpha=0.5) self.redraw1() self.OComboBox3.setText(str(imin)) self.OComboBox4.setText(str(imax)) def add_data(self, x, pc): self.x = x self.pc = pc self.new_x = x['d'] self.axes1.plot(x['d']) self.axes1.set_title("raw data", fontsize=9) self.axes1.set_xlabel("Scans") self.axes1.tick_params(axis='both', labelsize=8) self.LComboBox.setRange(1, self.pc) ymino, ymaxo = self.axes1.get_ylim() xmino, xmaxo = self.axes1.get_xlim() self.oxy = [(xmino, xmaxo), (ymino, ymaxo)] self.redraw1() def eta(self): self.layel = self.LComboBox.value() if self.layel < self.pc: if self.mthcombox.currentText() == "ETA": w = self.DComboBox.value() self.l, self.em = FSWFA(self.new_x, w, self.pc) self.axes1.clear() self.axes1.plot(self.l, self.em, '-o') self.axes1.set_title("ETA", fontsize=9) self.axes1.set_xlabel("Scans") self.axes1.tick_params(axis='both', labelsize=8) self.redraw1() else: u, T = svdX(self.new_x) self.axes1.clear() self.axes1.plot(u[:, 0], u[:, 1], '-o') C = np.arange(0, u.shape[0]) for a, b, c in zip(u[:, 0], u[:, 1], C): self.axes1.text(a, b + 0.001, '%.0f' % c, ha='center', va='bottom', fontsize=7) self.axes1.set_xlabel("p1") self.axes1.set_ylabel("p2") self.axes1.set_title("LPG", fontsize=9) self.redraw1() ymino, ymaxo = self.axes1.get_ylim() xmino, xmaxo = self.axes1.get_xlim() self.oxy = [(xmino, xmaxo), (ymino, ymaxo)] else: msgBox = QMessageBox() msgBox.setText("All component finished") msgBox.exec_() def fr(self): s1 = self.SComboBox1.text() s2 = self.SComboBox2.text() z1 = self.OComboBox1.text() z2 = self.OComboBox2.text() z3 = self.OComboBox3.text() z4 = self.OComboBox4.text() s = list() z = list() if (s1 and s2): s.append(range(int(s1), int(s2))) if (z1 and z2): z.append(range(int(z1), int(z2))) if (z3 and z4): z.append(range(int(z3), int(z4))) if len(s[0]) == 0 or len(z[0]) == 0: msgBox = QMessageBox() msgBox.setText( "Please input selective region or zero-concentration region") msgBox.exec_() if len(s) and len(z): DATAF = open('HELP_m.pkl', 'w') X = {'x': self.new_x, 'so': s[0], 'z': z[0]} pickle.dump(X, DATAF) DATAF.close() c, new_x = FR(self.new_x, s[0], z[0], self.pc - self.LComboBox.value() + 1) # plt.plot(c) # plt.show() # plt.plot(new_x) # plt.show() helpre = {'new_x': self.new_x, 'l': self.l, 'em': self.em, 'c': c} if len(self.help_result) == self.layel: self.help_result.pop(self.layel) self.help_result.append(helpre) self.new_x = new_x self.LComboBox.setValue(self.LComboBox.value() + 1) self.SComboBox1.setText(str()) self.SComboBox2.setText(str()) self.OComboBox1.setText(str()) self.OComboBox2.setText(str()) self.OComboBox3.setText(str()) self.OComboBox4.setText(str()) self.axes2.plot(c / np.linalg.norm(c)) self.redraw2() self.axes1.clear() self.axes1.set_xlabel("scan") self.axes1.plot(self.new_x) self.axes1.set_title("after stripping", fontsize=9) self.axes1.set_xlabel("Scans") self.redraw1() ymino, ymaxo = self.axes1.get_ylim() xmino, xmaxo = self.axes1.get_xlim() self.oxy = [(xmino, xmaxo), (ymino, ymaxo)] if self.layel == self.pc - 1: #cc = np.sum(self.new_x, 1) indd = np.argmax(np.sum(self.new_x, 0)) cc = self.new_x[:, indd] ind = np.argmax(cc) for i, indd in enumerate(np.arange(ind, 0, -1)): if cc[indd - 1] >= cc[indd] and cc[indd - 1] <= 0.5 * np.max(cc): cc[0:indd] = 0 break if cc[indd - 1] < 0: cc[0:indd] = 0 break for i, indd in enumerate(np.arange(ind, len(cc) - 1, 1)): if cc[indd + 1] >= cc[indd] and cc[indd + 1] <= 0.5 * np.max(cc): cc[indd + 1:len(cc)] = 0 break if cc[indd + 1] < 0: cc[indd + 1:len(cc)] = 0 break helpre = { 'new_x': [], 'l': [], 'em': [], 'c': cc / np.linalg.norm(cc) } self.help_result.append(helpre) self.axes2.plot(cc / np.linalg.norm(cc)) self.redraw2() return self.layel = self.layel + 1 w = self.DComboBox.value() self.l, self.em = FSWFA(self.new_x, w, self.pc - self.LComboBox.value() + 1) def undo(self): self.axes1.clear() self.axes1.set_xlabel("scan") self.axes2.clear() self.axes2.set_xlabel("scan") self.LComboBox.setValue(1) self.help_result = [] self.rt = [] self.ms = [] self.new_x = self.x['d'] self.axes1.plot(self.new_x) self.axes1.set_title("raw data", fontsize=9) self.axes1.set_xlabel("Scans") self.axes1.tick_params(axis='both', labelsize=8) self.redraw2() self.redraw1() def getmsrt(self): if len(self.help_result) == self.pc: C = np.zeros((self.x['d'].shape[0], self.pc)) for i, v in enumerate(self.help_result): C[:, i] = self.help_result[i]['c'] S = np.zeros((self.pc, self.x['d'].shape[1])) for j in range(0, S.shape[1]): a = fnnls(np.dot(C.T, C), np.dot(C.T, self.x['d'][:, j]), tole='None') S[:, j] = a['xx'] rts = self.x['rt'][np.sort(np.argmax(C, axis=0))] index = np.argsort(np.argmax(C, axis=0)) for ind, val in enumerate(index): self.rt.append(rts[ind]) ss = S[val, :] self.ms.append(ss / norm(ss)) else: msgBox = QMessageBox() msgBox.setText("Please resolve all components") msgBox.exec_() def get_resu(self): self.getmsrt() if len(self.rt): RESU = { "methods": "H", "ms": self.ms, 'rt': self.rt, 'mz': self.x['mz'], 'pc': self.pc, 'R2': 'none' } else: RESU = {} return RESU
class LSFQDialg(QWidget): def __init__(self): QWidget.__init__(self) self.handles = [] self.create_canvas() self.segments = [] vbox = QVBoxLayout() vbox.addWidget(self.canvas) self.setLayout(vbox) self.resize(800, 600) self.move(320, 75) self.setWindowTitle("Least Square Fitting (2D)") def create_canvas(self): self.fig = plt.figure() self.canvas = FigureCanvas(self.fig) self.axes = plt.subplot(111) self.axes.set_xlabel("Scans") self.axes.set_ylabel("Instensity") self.axes.set_title("Least Square Fitting(2D)", fontsize=9) self.axes.tick_params(axis='both', labelsize=8) plt.subplots_adjust(bottom=0.22, top=0.90, left=0.08, right=0.9) self.span = SpanSelector(self.axes, self.span_select_callback, 'horizontal', minspan=0.002, useblit=True, rectprops=dict(alpha=0.5, facecolor='red'), onmove_callback=None, button=[1]) axspan = plt.axes([0.09, 0.04, 0.08, 0.075]) axundo = plt.axes([0.2, 0.04, 0.08, 0.075]) axstar = plt.axes([0.31, 0.04, 0.08, 0.075]) self.btnspan = Button(axspan, 'span') self.btnundo = Button(axundo, 'undo') self.btnstar = Button(axstar, 'start') self.btnspan.on_clicked(self.span_mode) self.btnundo.on_clicked(self.undo_mode) self.btnstar.on_clicked(self.star_mode) self.span.set_active(True) self.redraw() ymino, ymaxo = self.axes.get_ylim() xmino, xmaxo = self.axes.get_xlim() self.oxy = [(xmino, xmaxo), (ymino, ymaxo)] def redraw(self): self.canvas.draw() self.update() def span_mode(self, event): self.span.connect_event('motion_notify_event', self.span.onmove) self.span.connect_event('button_press_event', self.span.press) self.span.connect_event('button_release_event', self.span.release) self.span.connect_event('draw_event', self.span.update_background) self.leftdblclick = False self.rightdblclick = False self.redraw() print "span" def undo_mode(self, event): self.span.disconnect_events() if len(self.segments) >= 1: del self.axes.collections[:] self.segments = self.segments[:-1] self.select_inter(self.segments) self.redraw() print "undo" def star_mode(self, event): if len(self.segments) == 0: msgBox = QMessageBox() msgBox.setText("No selected noise region") msgBox.exec_() else: fit, bas = self.backremv(self.segments) self.show_bas(bas) self.show_fit(fit) self.emit(SIGNAL('after_baseline'), fit) def show_bas(self, bas): self.axes.plot(np.sum(bas, axis=1), lw=2, c='k', alpha=.7, picker=5) def show_fit(self, fit): self.axes.plot(np.sum(fit, axis=1), lw=2, c='r', alpha=.7, picker=5) def show_org(self, x): self.axes.plot(np.sum(x, axis=0), lw=2, c='b', alpha=.7, picker=5) def span_select_callback(self, xmin, xmax): cc = np.arange(0, self.x.shape[0]) indmin, indmax = np.searchsorted(cc, (xmin, xmax)) indmax = min(len(self.x) - 1, indmax) self.segments.append((indmin, indmax)) self.axes.vlines(xmin, self.oxy[1][0], self.oxy[1][1], color='r', linestyles='--') self.axes.vlines(xmax, self.oxy[1][0], self.oxy[1][1], color='r', linestyles='--') self.redraw() def updata_data(self, x): self.xx = x self.axes.clear() self.axes.set_xlabel("Scans") self.axes.set_ylabel("Instensity") self.axes.set_title("Least Square Fitting(2D)", fontsize=9) self.x = x['d'] self.y = np.sum(self.x, axis=1) self.axes.plot(self.y, lw=1, c='b', alpha=.7, picker=5) diff_y = max(self.y) - min(self.y) self.axes.set_xlim(0, len(self.y)) self.axes.set_ylim(0, max(self.y) * 1.1) ymino, ymaxo = self.axes.get_ylim() xmino, xmaxo = self.axes.get_xlim() self.oxy = [(xmino, xmaxo), (ymino, ymaxo)] self.plotorg = True self.redraw() def select_inter(self, segments): for i in range(0, len(segments)): indmin, indmax = segments[i] self.axes.vlines(self.x[indmin], self.oxy[1][0], self.oxy[1][1], color='r', linestyles='--') self.axes.vlines(self.x[indmax], self.oxy[1][0], self.oxy[1][1], color='r', linestyles='--') def backremv(self, seg): mn = np.shape(self.x) bak2 = np.zeros(mn) for i in range(0, mn[1]): tiab = [] reg = [] for j in range(0, len(seg)): tt = range(seg[j][0], seg[j][1]) tiab.extend(self.x[tt, i]) reg.extend(np.arange(seg[j][0], seg[j][1])) rm = reg - np.mean(reg) tm = tiab - np.mean(tiab) b = np.dot(np.dot(float(1) / np.dot(rm.T, rm), rm.T), tm) s = np.mean(tiab) - np.dot(np.mean(reg), b) b_est = s + b * np.arange(mn[0]) bak2[:, i] = self.x[:, i] - b_est bak = self.x - bak2 self.yy = bak2 return bak2, bak def accept(self): self.xx['d'] = self.yy self.close()
class DisplayWindow(object): global CdMeOTPRef, MeOTPRef color_list = deque(['b','g','r','c','m','y','k']) current_checker = None def __init__(self, master,ax = None): self.rootref = master self.master = Toplevel() self.checker_frame=Tkinter.Frame(master = self.master)#,yscrollcommand=self.scroll.set) #self.scroll.config(command=self.checker_frame.yview) self.frame = Frame(master = self.master) self.Plot = Figure(figsize=(6,3)) self.channel_list = [] self.array_list = [] self.Plot.a = self.Plot.add_subplot(111) self.Plot.a.set_xlabel('Raman Shift (cm$^{-1}$)') self.Plot.a.set_ylabel('Intensity (a.u.)') self.Plot.a.legend([]) self.Plot.a.get_legend().set_visible(False) self.checker_list = self.Plot.a.lines self.legend_var = IntVar() self.legend_var.set(1) self.legendbox = Checkbutton(self.frame, variable=self.legend_var, command=self.update_legend,text='Legend') # self.legend_label=Label(self.master, bd=1, anchor=W) # self.legend_label.config(text = "Legend") self.statusbar = Label(self.master, bd=1, relief=SUNKEN, anchor=W) self.statusbar.config(text = "Ready") self.canvas = FigureCanvasTkAgg(self.Plot,master = self.frame) self.canvas.show() self.master.protocol("WM_DELETE_WINDOW", self.quitproc) self.master.title(string = "RamanViewer") #self.scroll = Tkinter.Scrollbar(self.frame) #self.scroll.pack(side = Tkinter.RIGHT, fill = Tkinter.BOTH) self.checker_frame=Tkinter.Frame(master = self.master)#,yscrollcommand=self.scroll.set) #self.scroll.config(command=self.checker_frame.yview) self.menubar = Menu(self.master) self.filemenu = Menu(self.menubar, tearoff=0) self.filemenu.add_command(label="New window", command = lambda: DisplayWindow(self.rootref)) self.filemenu.add_command(label="Open", command = self.DisplaySpectrum) self.filemenu.add_command(label="Save",command = self.SaveSpectrum) self.filemenu.add_command(label="SaveFig",command = self.SaveFigure) self.filemenu.add_command(label="ViewNotebook",command = self.ViewNotebook) self.filemenu.add_command(label="Exit", command = self.quitproc) self.menubar.add_cascade(label="File", menu=self.filemenu) # create more pulldown menus self.editmenu = Menu(self.menubar, tearoff=0) self.editmenu.add_command(label="Smooth", command = self.SmoothSpectrum) self.filemenu.add_command(label="Fitting window", command = lambda:FittingWindow(Toplevel(),ramanspectrum=self.current_checker.spectrum))#, kwargs = {'ramanspectrum':self.current_checker.channel.spec_array}) self.editmenu.add_command(label="Calc Noise", command = self.start_calc_noise) self.editmenu.add_command(label="Calc Area", command = self.start_calc_area) self.editmenu.add_command(label="Basline", command = self.start_autobaseline) self.editmenu.add_command(label="disconnect", command = self.disconnect) self.editmenu.add_command(label='Quick Scan',command = self.open_next_spectrum_in_folder) self.editmenu.add_command(label='Normalize All',command = self.normalizeall) self.editmenu.add_command(label='Zero All',command = self.zeroall) self.editmenu.add_command(label = 'FFT process', command=self.FFT) self.editmenu.add_command(label = 'Remove noise', command = self.removenoise) self.editmenu.add_command(label="Copy") self.editmenu.add_command(label="Paste") self.menubar.add_cascade(label="Edit", menu=self.editmenu) self.correctionmenu = Menu(self.menubar,tearoff=0) self.correctionmenu.add_command(label='SPID633', command = self.SPIDcorrect633) self.correctionmenu.add_command(label='SPID785', command = self.SPIDcorrect785) self.menubar.add_cascade(label = 'Corrections', menu = self.correctionmenu) self.notesmenu =Menu(self.menubar, tearoff=0) self.notesmenu.add_command(label = "Notes", command = self.ViewNotebook) self.notesmenu.add_command(label = "Spectrum Info", command = self.showinfo) self.menubar.add_cascade(label = 'Info', menu = self.notesmenu) self.refsmenu =Menu(self.menubar, tearoff=0) self.refsmenu.add_command(label = "chloroform", command = None) self.refsmenu.add_command(label = "CdMeOTP", command = lambda:self.AddChannel(CdMeOTPRef)) self.refsmenu.add_command(label = "MeOTP", command = lambda:self.AddChannel(MeOTPRef)) self.refsmenu.add_command(label = "ClTP", command = lambda:self.AddChannel(ClTPRef)) self.refsmenu.add_command(label = "BrTP", command = lambda:self.AddChannel(BrTPRef)) self.refsmenu.add_command(label = "FTP", command = lambda:self.AddChannel(FTPRef)) self.refsmenu.add_command(label = "MethylTP", command = lambda:self.AddChannel(MethylTPRef)) self.refsmenu.add_command(label = "CdODPA", command = lambda:self.AddChannel(CdODPARef)) self.refsmenu.add_command(label = "toluene", command = lambda:self.AddChannel(tolueneRef)) self.refsmenu.add_command(label = "CdMethylTP", command = lambda:self.AddChannel(CdMethylTPRef)) self.menubar.add_cascade(label = 'References', menu = self.refsmenu) self.master.config(menu= self.menubar) self.left_click_menu = Menu(self.frame, tearoff=0) self.left_click_menu.add_command(label="open", command = self.DisplaySpectrum) # self.left_click_menu.add_command(label="blue", command=lambda:self.change_color('b')) # self.left_click_menu.add_command(label="black", command=lambda:self.change_color('k')) # self.left_click_menu.add_command(label="yellow", command=lambda:self.change_color('y')) # self.canvas._tkcanvas.bind("<Button-3>", self.popup) self.frame.pack(side = TOP, expand=1, fill=BOTH)#(row = 0, column = 0, padx = 25, pady = 25) self.legendbox.pack(side=BOTTOM) self.statusbar.pack(side = BOTTOM,expand=1,fill=X) self.checker_frame.pack(side=BOTTOM,expand = 1,fill=X)#(row=1,column=0) self.canvas._tkcanvas.pack( expand = 1, fill = BOTH) self.toolbar = NavigationToolbar2TkAgg(self.canvas, self.frame) self.toolbar.update() self.toolbar.pack(side= BOTTOM,expand =True) self.canvas.draw() list_of_display_windows.append(self) if ax is not None: for line in ax.lines: self.Plot.a.add_line(checker(self,line,color = line.get_color())) self.Plot.a.relim() self.Plot.a.autoscale_view(tight = False) self.Plot.canvas.draw() self.current_checker = self.Plot.a.lines[-1] plt.close(ax.get_figure()) return None def popup(self,event): print event.x_root, event.y_root self.left_click_menu.post(event.x_root, event.y_root) def update_legend(self): if self.legend_var.get() == 0: self.Plot.a.get_legend().set_visible(False) else: l = list() for entry in self.checker_list: if True:#entry.get_visible(): l.append(entry.commentbox.get()) self.Plot.a.legend(l) self.Plot.canvas.draw() return 0 def showinfo(self): tkMessageBox.showinfo('Spectrum info',self.current_checker.spectrum.info) return 0 def getcolor(self): self.color_list.rotate(1) return self.color_list[0] def DisplaySpectrum(self): import re options = {} #options['defaultextension'] = '.SPE' options['filetypes'] = [('all files','.*'),('SPE','.spe'),('txt', '.txt'),('csv','.csv')] options['multiple'] = True options['title'] = 'Open Spectrum...' options['parent'] = self.master str_name_list = tkFileDialog.askopenfilenames(**options) if type(str_name_list) == tuple: for name in str_name_list: if 'notes' in name: SFG_Notebook.SFG_NotebookWindow(target_file = name) elif name =='': continue else: newspectrum = RamanSpectrum(name) self.Plot.a.add_line(checker(self,newspectrum,color = self.getcolor())) self.Plot.a.relim() self.Plot.a.autoscale_view(tight = False) self.Plot.canvas.draw() self.current_checker = self.Plot.a.lines[-1] elif str_name_list == '': return 0 elif type(str_name_list) == list: for name in re.split(' ',str_name_list): newspectrum = RamanSpectrum(name) self.Plot.a.add_line(checker(self,newspectrum,color = self.getcolor())) self.Plot.a.relim() self.Plot.a.autoscale_view(tight = False) self.Plot.canvas.draw() self.current_checker = self.Plot.a.lines[-1] return 0 def SaveSpectrum(self): file_opt = options = {} options['defaultextension'] = '.txt' options['filetypes'] = [('all files', '.*')] options['title'] = 'Open Spectrum...' options['initialfile'] = os.path.basename(self.current_checker.name) options['parent'] = self.master if self.current_checker == None: return 0 str_filename = tkFileDialog.asksaveasfilename(**options) if str_filename == '': return 0 else: data = transpose([self.current_checker.get_xdata(),self.current_checker.get_ydata()]) savetxt(str_filename,data,delimiter = ',',comments = '#'+str(self.current_checker.spectrum.info))#SaveSpectrum(self.current_checker.channel.spec_array,str_filename) os.chdir(os.path.dirname(str_filename)) return 0 def ViewNotebook(self): print os.path.dirname(self.current_checker.name) try: SFG_Notebook.SFG_NotebookWindow(target_dir = os.path.dirname(self.current_checker.name)) except IOError: tkSimpleDialog.Message('no file found') return 0 def zeroall(self): for c in self.Plot.a.lines: c.set_ydata(c.get_ydata()-min(c.get_ydata())) self.Plot.a.relim() self.Plot.a.autoscale_view(tight = False) self.Plot.canvas.draw() return 0 def SmoothSpectrum(self): if self.current_checker == None: return 0 newspectrum = smooth(self.current_checker.spectrum) self.Plot.a.add_line(checker(self,newspectrum,color = self.getcolor(),operations = 'sp = smooth(sp)\n')) self.Plot.a.relim() self.Plot.a.autoscale_view(tight = False) self.Plot.canvas.draw() self.current_checker = self.Plot.a.lines[-1] return 0 def SPIDcorrect785(self): if self.current_checker == None: return 0 else: newspectrum = SPIDcorrect785(self.current_checker.spectrum) self.Plot.a.add_line(checker(self,newspectrum,color = self.getcolor(),operations = 'sp = SPIDcorrect785(sp)\n')) self.Plot.a.relim() self.Plot.a.autoscale_view(tight = False) self.Plot.canvas.draw() self.current_checker = self.Plot.a.lines[-1] return 0 def SPIDcorrect633(self): if self.current_checker == None: return 0 else: newspectrum = SPIDcorrect633(self.current_checker.spectrum) self.Plot.a.add_line(checker(self,newspectrum,color = self.getcolor(),operations = 'sp = SPIDcorrect633(sp)\n')) self.Plot.a.relim() self.Plot.a.autoscale_view(tight = False) self.Plot.canvas.draw() self.current_checker = self.Plot.a.lines[-1] return 0 def open_next_spectrum_in_folder(self): self.Plot.canvas.mpl_connect('key_press_event',self.open_next_spectrum) for c in self.checker_list[1:]: self.RemoveSpectrum(self.checker) self.checker_list[0].set_current(0) return 0 def open_next_spectrum(self,event): directory_index = os.listdir(os.path.dirname(os.path.abspath(self.current_checker.channel.spec_array.name))) for x in directory_index: if 'txt' not in x: directory_index.remove(x) directory_index.sort() i=directory_index.index(os.path.basename(self.current_checker.channel.spec_array.name)) if i>len(directory_index)-2: i=-1 if 'txt' not in directory_index[1+1]: i+=1 if event.key == 'right': i+=1 elif event.key == 'left': i-=1 try: newspectrum = RamanSpectrum(directory_index[i]) except: print 'error' print 'i=',i return -1 self.RemoveSpectrum(self.current_checker) self.AddChannel(self.newspectrum) self.checker_list[0].set_current(0) return 0 def normalizeall(self): for check in self.checker_list: data = check.get_ydata() data[:]-=min(data) data/=max(data) check.set_ydata(data) self.Plot.a.relim() self.Plot.a.set_ylim(-0.5,1.5) self.Plot.a.autoscale_view(tight = False) self.Plot.canvas.draw() return 0 def start_calc_noise(self): self.span = SpanSelector(self.Plot.a, self.calc_noise, 'horizontal') self.span.connect_event('pick_event',self.calc_noise) gcf().canvas.mpl_connect('button_press_event',self.disconnect) return 0 def start_calc_area(self): self.span = SpanSelector(self.Plot.a, self.calc_area, 'horizontal') self.span.connect_event('pick_event',self.calc_area) gcf().canvas.mpl_connect('button_press_event',self.disconnect) return 0 def start_autobaseline(self): # self.toolbar.release(None) self.span = SpanSelector(self.Plot.a, self.autobaseline, 'horizontal') self.span.connect_event('pick_event',self.autobaseline) gcf().canvas.mpl_connect('button_press_event',self.disconnect) return 0 def autobaseline(self,start,end): order = int(tkSimpleDialog.askinteger('Fit order', 'Choose the polynomial order.')) if order == None: return 0 if self.current_checker == None: return 0 newspectrum = autobaseline(self.current_checker.spectrum,(start,end),order = order) self.Plot.a.add_line(checker(self,newspectrum,color = self.getcolor(),operations = 'sp = autobaseline(sp), ('+str(start)+','+str(end)+'), order ='+str(order)+')\n')) self.Plot.a.relim() self.Plot.a.autoscale_view(tight = False) self.Plot.canvas.draw() self.current_checker = self.Plot.a.lines[-1] self.span.disconnect_events() return 0 def calc_noise(self,start,end): try: print "STD =", calc_noise(pandas.Series(self.current_checker.channel.get_ydata(),self.current_checker.channel.get_xdata()),(start,end)) except: print 'error' return 0 def calc_area(self, start,end): try: print "Area =", calc_area(pandas.Series(self.current_checker.channel.get_ydata(),self.current_checker.channel.get_xdata()),(start,end)) except: print 'error' return 0 def disconnect(self): #print event.button#gcf().canvas.mpl_disconnect(self.cid) self.span.disconnect_events() return 0 def removenoise(self): newspectrum = removecorrelatednoise(self.current_checker.spectrum) self.Plot.a.add_line(checker(self,newspectrum,operations = 'sp = removecorrelatednoise(sp)',color=self.getcolor())) self.Plot.a.relim() self.Plot.a.autoscale_view(tight = False) self.Plot.canvas.draw() self.current_checker = self.Plot.a.lines[-1] return None def AddChannel(self,spectrum): self.Plot.a.add_line(checker(self,spectrum)) self.Plot.a.lines[-1].set_color(self.getcolor()) self.Plot.a.relim() self.Plot.a.autoscale_view(tight = False) self.Plot.canvas.draw() self.current_checker = self.Plot.a.lines[-1] return 0 def RemoveSpectrum(self,checker): self.Plot.a.lines.remove(checker) self.Plot.a.relim() self.Plot.a.autoscale_view(tight = False) self.canvas.draw() checker.frame.pack_forget() return 0 def SaveFigure(self): os.chdir('/home/chris/Desktop') self.Plot.savefig('figure.png') f = open('/home/chris/Desktop/figure.py','wb') for line in self.Plot.a.lines: f.write(line.operations) f.close() return 0 def FFT(self): return 0 def quitproc(self): self.master.destroy() list_of_display_windows.remove(self) if len(list_of_display_windows)==0: self.rootref.destroy() return 0
class TICPlot(QWidget): def __init__(self): QWidget.__init__(self) self.handles = [] self.ncr = dict() self.fileno = 0 self.segments = [] self.create_canvas() def create_canvas(self): self.fig = plt.figure() self.canvas = FigureCanvas(self.fig) self.axes = plt.subplot(111) self.axes.set_xlabel("Retention Time") self.axes.set_ylabel("Instensity") self.axes.tick_params(axis='both', labelsize=8) plt.subplots_adjust(bottom=0.25, top=0.90, left=0.08, right=0.9) self.zoom = RectangleSelector(self.axes, self.rectangle_select_callback, drawtype='box', useblit=True, button=[1], minspanx=5, minspany=5, spancoords='pixels') self.span = SpanSelector(self.axes, self.span_select_callback, 'horizontal', minspan=0.002, useblit=True, rectprops=dict(alpha=0.5, facecolor='red'), onmove_callback=None, button=[1]) axbasic = plt.axes([0.59, 0.04, 0.08, 0.075]) axPan = plt.axes([0.7, 0.04, 0.08, 0.075]) axPick = plt.axes([0.81, 0.04, 0.08, 0.075]) self.btnBasic = Button(axbasic, 'Zoom') self.btnPan = Button(axPan, 'Span') self.btnPick = Button(axPick, 'Undo') axtic = plt.axes([0.92, 0.825, 0.06, 0.075]) axext = plt.axes([0.92, 0.725, 0.06, 0.075]) axres = plt.axes([0.92, 0.625, 0.06, 0.075]) self.TICbutton = Button(axtic, 'TIC') self.EXTbutton = Button(axext, 'EXT') self.RESbutton = Button(axres, 'RES') vbox = QVBoxLayout() vbox.addWidget(self.canvas) self.setLayout(vbox) self.btnBasic.on_clicked(self.zoom_mode) self.btnPan.on_clicked(self.span_mode) self.btnPick.on_clicked(self.undo_mode) self.TICbutton.on_clicked(self.slot_tic) self.EXTbutton.on_clicked(self.slot_ext) self.RESbutton.on_clicked(self.slot_res) self.zoom_mode(True) self.redraw() ymino, ymaxo = self.axes.get_ylim() xmino, xmaxo = self.axes.get_xlim() self.oxy = [(xmino, xmaxo), (ymino, ymaxo)] def slot_tic(self, event): self.add_tic(self.ncr, self.fileno) def slot_ext(self, event): self.emit(SIGNAL("ext_plot")) def slot_res(self, event): self.emit(SIGNAL("res_plot"), ) def add_tic(self, ncr, fn): if not len(self.segments): self.fn = fn self.ncr = ncr tic = self.ncr.tic() self.x = tic['rt'] self.y = tic['val'] self.axes.clear() self.axes.set_xlabel("Retention Time") self.axes.set_ylabel("Instensity") self.axes.set_title(str(fn), fontsize=9) self.axes.plot(self.x, self.y, lw=1, c='b', alpha=.7, picker=5) self.axes.set_xlim(min(self.x), max(self.x)) self.axes.set_ylim(min(self.y), max(self.y) * 1.1) ymino, ymaxo = self.axes.get_ylim() xmino, xmaxo = self.axes.get_xlim() self.oxy = [(xmino, xmaxo), (ymino, ymaxo)] self.redraw() # def add_ext(self): def clear_data(self): self.axes.clear() self.axes.set_xlabel("Retention Time") self.axes.set_ylabel("Instensity") self.redraw() def redraw(self): self.canvas.draw() self.update() def zoom_mode(self, event): self.zoom.set_active(True) self.span.set_active(False) self.cidPress = self.canvas.mpl_connect('button_press_event', self.mouse_press_callback) self.cidRelease = self.canvas.mpl_connect('button_release_event', self.mouse_release_callback) self.span.disconnect_events() self.leftdblclick = False self.rightdblclick = False self.redraw() print "zoom" def span_mode(self, event): self.zoom.set_active(False) self.span.set_active(True) self.span.connect_event('motion_notify_event', self.span.onmove) self.span.connect_event('button_press_event', self.span.press) self.span.connect_event('button_release_event', self.span.release) self.span.connect_event('draw_event', self.span.update_background) # self.span.connect_event('button_press_event', self.mouse_press_callback) self.rightdblclick = False self.leftdblclick = False self.rightdblclick = False self.redraw() print "span" def undo_mode(self, event): self.zoom.set_active(True) self.span.disconnect_events() self.cidPress = self.canvas.mpl_connect('button_press_event', self.mouse_press_callback) if len(self.segments) >= 1: self.emit(SIGNAL("delete_SELECT"), self.segments[-1]) del self.axes.collections[:] self.segments = self.segments[:-1] self.select_inter(self.segments) if self.ind_right_press != 0: self.axes.vlines(self.xdata, self.oxy[1][0], self.oxy[1][1], color='g', linestyles='-') self.redraw() print "undo" def mouse_press_callback(self, event): if (event.button == 1 and event.dblclick == True): self.leftdblclick = True if event.button == 3: self.xdata = event.xdata self.ind_right_press = np.searchsorted(self.x, event.xdata) del self.axes.collections[:] self.axes.vlines(event.xdata, self.oxy[1][0], self.oxy[1][1], color='g', linestyles='-') self.select_inter(self.segments) self.redraw() self.emit(SIGNAL("MASS_SELECT"), self.ncr, self.ind_right_press) def select_inter(self, segments): for i in range(0, len(segments)): indmin, indmax = segments[i] self.axes.vlines(self.x[indmin], self.oxy[1][0], self.oxy[1][1], color='r', linestyles='--') self.axes.vlines(self.x[indmax], self.oxy[1][0], self.oxy[1][1], color='r', linestyles='--') def mouse_release_callback(self, event): if (self.leftdblclick): self.leftdblclick = False self.axes.set_xlim(self.oxy[0]) self.axes.set_ylim(self.oxy[1]) self.redraw() if (self.rightdblclick): self.rightdblclick = False del self.axes.collections[:] self.redraw() def rectangle_select_callback(self, eclick, erelease): x1, y1 = eclick.xdata, eclick.ydata x2, y2 = erelease.xdata, erelease.ydata if eclick.button == 1 and erelease.button == 1: self.axes.set_xlim(min(x1, x2), max(x1, x2)) self.axes.set_ylim(min(y1, y2), max(y1, y2)) self.redraw() def span_select_callback(self, xmin, xmax): indmin, indmax = np.searchsorted(self.x, (xmin, xmax)) indmax = min(len(self.x) - 1, indmax) self.segments.append((indmin, indmax)) self.axes.vlines(xmin, self.oxy[1][0], self.oxy[1][1], color='r', linestyles='--') self.axes.vlines(xmax, self.oxy[1][0], self.oxy[1][1], color='r', linestyles='--') self.redraw() self.emit(SIGNAL("range_SELECT"), self.ncr, (indmin, indmax)) def loading(self): self.axes.clear() self.axes.set_xlabel("Retention Time") self.axes.set_ylabel("Instensity") self.redraw() self.zoom_mode(True) ymino, ymaxo = self.axes.get_ylim() xmino, xmaxo = self.axes.get_xlim() self.oxy = [(xmino, xmaxo), (ymino, ymaxo)]
patch_properties = {'boxstyle': 'round', 'facecolor': 'wheat', 'alpha': 0.5 } ax2_text = ax2.text(0.05, 0.95, text2, transform = ax2.transAxes, fontsize = 14, verticalalignment = 'top', horizontalalignment = 'left', bbox = patch_properties) # make a splan selector and have it turned off initially until user # presses 'q' or 'a' on the key board via toggle_selector span = SpanSelector(ax1, onselect, 'horizontal', useblit=True, rectprops=dict(alpha=0.5, facecolor='red')) span.visible = False # connect span with the toggle selector in order to toggle span selector on and off span.connect_event('key_press_event', toggle_selector) # make sure that the layout of the subplots do not overlap plt.tight_layout() plt.show() except IOError as error: print 'cannot read file' + error.filename print error.message except IndexError as error: print 'Cannot read file! Bad file!' print error.message except ValueError as error: print error.message