def configure_plot(self): self.marker = add_marker(self.plot) self.line = MeasurementLine() self.line.setVisible(0) self.label = make_label(self.marker, self.line) setupCommonStyle(self.line, self.marker) manager = PlotManager(self.widget) manager.add_plot(self.plot) tool = manager.add_tool(MzSelectionTool) tool.activate() manager.set_default_tool(tool) self.plot.add_item(self.marker) self.plot.add_item(self.label) self.plot.add_item(self.line) self.plot.startMeasuring.connect(self.line.start_measuring) self.plot.moveMeasuring.connect(self.line.move_measuring) self.plot.stopMeasuring.connect(self.line.stop_measuring) self.plot.moveMarker.connect(self.marker.move_local_point_to) self.line.updated.connect(self.plot.replot)
def configure_plot(self): set_x_axis_scale_draw(self.widget) manager = PlotManager(self.widget) manager.add_plot(self.plot) tool = manager.add_tool(RtSelectionTool) tool.activate() manager.set_default_tool(tool) self.marker = add_marker(self.plot) setupStyleRtMarker(self.marker) self.marker.rts = (0, ) self.plot.moveMarker.connect(self.marker.move_local_point_to) self.plot.moveMarker.connect(self.move_rt_cursor)
class TestDialog(QDialog): def __init__(self): QDialog.__init__(self) vlayout = QVBoxLayout() self.setLayout(vlayout) self.widget = CurveWidget() self.curve_item = make.curve([], [], color='r') self.widget.plot.add_item(self.curve_item) self.pm = PlotManager(self.widget) self.pm.add_plot(self.widget.plot) t = self.pm.add_tool(MyTool) t.curve_item = self.curve_item self.pm.set_default_tool(t) t.activate() self.layout().addWidget(self.widget) self.update_curve() def update_curve(self): x = np.arange(0,10,.1) y = np.sin(np.sin(x)) self.curve_item.set_data(x, y) self.curve_item.plot().replot()
class MzPlottingWidget(CurveWidget): def __init__(self, parent=None): super(MzPlottingWidget, self).__init__(parent, xlabel="mz", ylabel="I") patch_inner_plot_object(self, MzPlot) self.plot.centralMz = None def label(self, x): # label with full precision: return QwtText(str(x)) a = QwtScaleDraw() a.label = new.instancemethod(label, self.plot, QwtScaleDraw) self.plot.setAxisScaleDraw(self.plot.xBottom, a) self.pm = PlotManager(self) self.pm.add_plot(self.plot) self.curve = make_unselectable_curve([], [], color="b", curvestyle="Sticks") self.plot.add_item(self.curve) t = self.pm.add_tool(MzSelectionTool) self.pm.set_default_tool(t) t.activate() marker = Marker(label_cb=self.plot.label_info, constraint_cb=self.plot.on_plot) marker.attach(self.plot) line = make_measurement_line() line.setVisible(0) setupCommonStyle(line, marker) line.shapeparam.line.color = "#555555" line.shapeparam.update_shape(line) label = make.info_label("TR", [MzCursorInfo(marker, line)], title=None) label.labelparam.label = "" label.labelparam.font.size = 12 label.labelparam.update_label(label) self.marker = marker self.label = label self.line = line def plot_spectra(self, all_peaks, labels): self.plot.del_all_items() self.plot.add_item(self.marker) self.plot.add_item(make.legend("TL")) self.plot.add_item(self.label) for i, (peaks, label) in enumerate(zip(all_peaks, labels)): config = dict(color=getColor(i)) curve = make_unselectable_curve([], [], title=label, curvestyle="Sticks", **config) curve.set_data(peaks[:, 0], peaks[:, 1]) self.plot.add_item(curve) self.plot.resample_config = [] self.plot.add_item(self.line) if len(all_peaks): self.plot.all_peaks = np.vstack(all_peaks) else: self.plot.all_peaks = np.zeros((0, 2)) def _setup_configs_and_titles(self, configs, titles, n): configs = configs if configs is not None else [None] * n titles = titles if titles is not None else [""] * n def default(i): return dict(color=getColor(i)) configs = [ ci if ci is not None else default(i) for (i, ci) in enumerate(configs) ] return configs, titles def set_overall_range(self, mzmin, mzmax): self.plot.overall_x_min = mzmin self.plot.overall_x_max = mzmax def plot_peakmaps(self, peakmap_ranges, configs=None, titles=None): has_titles = titles is not None configs, titles = self._setup_configs_and_titles( configs, titles, len(peakmap_ranges)) self.plot.del_all_items() self.plot.add_item(self.marker) if has_titles: self.plot.add_item(make.legend("TL")) self.plot.add_item(self.label) self.plot.plot_peakmap_ranges(peakmap_ranges, configs, titles) self.plot.add_item(self.line) def set_cursor_pos(self, mz): self.plot.set_mz(mz) def resetAxes(self): self.plot.reset_x_limits() def reset_mz_limits(self, xmin=None, xmax=None, fac=1.1): self.plot.reset_x_limits(xmin, xmax, fac) def reset(self): self.plot.del_all_items() self.replot() def replot(self): self.plot.replot() def set_visible(self, visible): self.plot.setVisible(visible) def updateAxes(self): self.plot.updateAxes() def shrink_and_replot(self, mzmin, mzmax): self.reset_mz_limits(mzmin, mzmax) self.plot.reset_y_limits() self.plot.replot()
class MzPlottingWidget(CurveWidget): def __init__(self, parent=None): super(MzPlottingWidget, self).__init__(parent, xlabel="mz", ylabel="I") patch_inner_plot_object(self, MzPlot) self.plot.centralMz = None def label(self, x): # label with full precision: return QwtText(str(x)) a = QwtScaleDraw() a.label = new.instancemethod(label, self.plot, QwtScaleDraw) self.plot.setAxisScaleDraw(self.plot.xBottom, a) self.pm = PlotManager(self) self.pm.add_plot(self.plot) self.curve = make_unselectable_curve([], [], color="b", curvestyle="Sticks") self.plot.add_item(self.curve) t = self.pm.add_tool(MzSelectionTool) self.pm.set_default_tool(t) t.activate() marker = Marker(label_cb=self.plot.label_info, constraint_cb=self.plot.on_plot) marker.attach(self.plot) line = make_measurement_line() line.setVisible(0) setupCommonStyle(line, marker) line.shapeparam.line.color = "#555555" line.shapeparam.update_shape(line) label = make.info_label("TR", [MzCursorInfo(marker, line)], title=None) label.labelparam.label = "" label.labelparam.font.size = 12 label.labelparam.update_label(label) self.marker = marker self.label = label self.line = line def plot_spectra(self, all_peaks, labels): self.plot.del_all_items() self.plot.add_item(self.marker) self.plot.add_item(make.legend("TL")) self.plot.add_item(self.label) for i, (peaks, label) in enumerate(zip(all_peaks, labels)): config = dict(color=getColor(i)) curve = make_unselectable_curve([], [], title=label, curvestyle="Sticks", **config) curve.set_data(peaks[:, 0], peaks[:, 1]) self.plot.add_item(curve) self.plot.resample_config = [] self.plot.add_item(self.line) if len(all_peaks): self.plot.all_peaks = np.vstack(all_peaks) else: self.plot.all_peaks = np.zeros((0, 2)) def _setup_configs_and_titles(self, configs, titles, n): configs = configs if configs is not None else [None] * n titles = titles if titles is not None else [""] * n def default(i): return dict(color=getColor(i)) configs = [ci if ci is not None else default(i) for (i, ci) in enumerate(configs)] return configs, titles def set_overall_range(self, mzmin, mzmax): self.plot.overall_x_min = mzmin self.plot.overall_x_max = mzmax def plot_peakmaps(self, peakmap_ranges, configs=None, titles=None): has_titles = titles is not None configs, titles = self._setup_configs_and_titles(configs, titles, len(peakmap_ranges)) self.plot.del_all_items() self.plot.add_item(self.marker) if has_titles: self.plot.add_item(make.legend("TL")) self.plot.add_item(self.label) self.plot.plot_peakmap_ranges(peakmap_ranges, configs, titles) self.plot.add_item(self.line) def set_cursor_pos(self, mz): self.plot.set_mz(mz) def resetAxes(self): self.plot.reset_x_limits() def reset_mz_limits(self, xmin=None, xmax=None, fac=1.1): self.plot.reset_x_limits(xmin, xmax, fac) def reset(self): self.plot.del_all_items() self.replot() def replot(self): self.plot.replot() def set_visible(self, visible): self.plot.setVisible(visible) def updateAxes(self): self.plot.updateAxes() def shrink_and_replot(self, mzmin, mzmax): self.reset_mz_limits(mzmin, mzmax) self.plot.reset_y_limits() self.plot.replot()
class RtPlotter(PlotterBase): def __init__(self, parent=None, rangeSelectionCallback=None): PlotterBase.__init__(self, "RT", "I") self.rangeSelectionCallback = rangeSelectionCallback widget = self.widget widget.plot.__class__ = RtPlot self.pm = PlotManager(widget) self.pm.add_plot(widget.plot) t = self.pm.add_tool(RtSelectionTool) t.activate() self.pm.set_default_tool(t) marker = Marker(label_cb=self.widget.plot.label_info, constraint_cb=self.widget.plot.on_plot) marker.rts = [0] setupStyleRtMarker(marker) marker.attach(self.widget.plot) self.marker = marker self.cursor_info = RtCursorInfo(marker) label = make.info_label("T", [self.cursor_info], title=None) label.labelparam.label = "" label.labelparam.font.size = 12 label.labelparam.border.color = "#ffffff" label.labelparam.update_label(label) self.label = label self.minRTRangeSelected = None self.maxRTRangeSelected = None def _set_rt_x_axis_labels(self): # todo: refactor as helper a = QwtScaleDraw() # render tic labels in modfied format: label = lambda self, v: QwtText(formatSeconds(v)) a.label = new.instancemethod(label, self.widget.plot, QwtScaleDraw) self.widget.plot.setAxisScaleDraw(self.widget.plot.xBottom, a) def _set_ts_x_axis_labels(self, data): # todo: refactor as helper all_ts = [tsi for ts in data for tsi in ts.x] pos = find_datetime_split_pos(all_ts) a = QwtScaleDraw() # render tic labels in modfied format: label = lambda self, v, pos=pos: QwtText(format_datetime_value(pos, v)) # QwtText(str(v)) a.label = new.instancemethod(label, self.widget.plot, QwtScaleDraw) self.widget.plot.setAxisScaleDraw(self.widget.plot.xBottom, a) def reset(self): """empties plot""" self.plot([]) self.marker.rts = [0] self.replot() def plot(self, data, is_time_series=False, titles=None, configs=None, withmarker=False): """ do not forget to call replot() after calling this function ! """ allrts = [] self.widget.plot.del_all_items() if is_time_series: self._set_ts_x_axis_labels(data) self.widget.plot.set_axis_title("bottom", "time") else: self._set_rt_x_axis_labels() self.widget.plot.set_axis_title("bottom", "RT") labels = set() legend_items = [] if is_time_series: seen = set() for i, ts in enumerate(data): # we do not plot duplicates, which might happen if multiple lines in the # table explorer are sellected ! if id(ts) in seen: continue seen.add(id(ts)) config = None if configs is not None: config = configs[i] if config is None: config = dict(color=getColor(i)) title = ts.label labels.add(title) for j, (x, y) in enumerate(ts.for_plotting()): x = [xi.toordinal() if isinstance(xi, datetime) else xi for xi in x] allrts.extend(x) curve = make.curve(x, y, title="<pre>%s</pre>" % title, **config) curve.__class__ = ModifiedCurveItem self.widget.plot.add_item(curve) self.cursor_info.is_time_series = True if j == 0: legend_items.append(curve) else: seen = set() for i, (rts, chromatogram) in enumerate(data): # we do not plot duplicates, which might happen if multiple lines in the # table explorer are sellected ! if (id(rts), id(chromatogram)) in seen: continue seen.add((id(rts), id(chromatogram))) config = None if configs is not None: config = configs[i] if config is None: config = dict(color=getColor(i)) if titles: title = "<pre>%s</pre>" % titles[i] else: title = "" labels.add(title) curve = make.curve(rts, chromatogram, title=title, **config) curve.__class__ = ModifiedCurveItem allrts.extend(rts) self.widget.plot.add_item(curve) self.cursor_info.is_time_series = False if withmarker: self.widget.plot.add_item(self.label) allrts = sorted(set(allrts)) self.marker.rts = allrts self.marker.attach(self.widget.plot) self.widget.plot.add_item(self.marker) labels -= set((None,)) labels -= set(("",)) if labels: legend = make.legend("TL", restrict_items=legend_items) legend.labelparam.font.size = 12 legend.labelparam.update_label(legend) self.widget.plot.add_item(legend) if not is_time_series: self._add_range_selector(allrts) def setEnabled(self, enabled): self.widget.plot.setVisible(enabled) def _add_range_selector(self, rtvalues): self.rtvalues = rtvalues self.minRTRangeSelected = 0 self.maxRTRangeSelected = 0 range_ = SnappingRangeSelection(self.minRTRangeSelected, self.maxRTRangeSelected, self.rtvalues) setupStyleRangeMarker(range_) self.range_ = range_ # you have to register item to plot before you can register the # rtSelectionHandler: self.widget.plot.add_item(range_) range_.SIG_RANGE_CHANGED.connect(self._range_selection_handler) #self.widget.disconnect(range_.plot(), SIG_RANGE_CHANGED, #self._range_selection_handler) #self.widget.connect(range_.plot(), SIG_RANGE_CHANGED, #self._range_selection_handler) cc = make.info_label("TR", [RtRangeSelectionInfo(range_)], title=None) cc.labelparam.label = "" cc.labelparam.font.size = 12 cc.labelparam.update_label(cc) self.widget.plot.add_item(cc) def getRangeSelectionLimits(self): return sorted((self.range_._min, self.range_._max)) def setRangeSelectionLimits(self, xleft, xright): saved = self.rangeSelectionCallback self.rangeSelectionCallback = None self.minRTRangeSelected = xleft self.maxRTRangeSelected = xright # left and right bar of range marker self.range_.move_point_to(0, (xleft, 0)) self.range_.move_point_to(1, (xright, 0)) self.rangeSelectionCallback = saved @protect_signal_handler def _range_selection_handler(self, obj, left, right): min_, max_ = sorted((left, right)) self.minRTRangeSelected = min_ self.maxRTRangeSelected = max_ if self.rangeSelectionCallback is not None: self.rangeSelectionCallback() reset_rt_limits = PlotterBase.reset_x_limits reset_intensity_limits = PlotterBase.reset_y_limits
class GuiQwtPlot( QtGui.QMainWindow ): def __init__( self ): QtGui.QMainWindow.__init__( self ) self.__create_layout() self.__setup_layout() def __create_layout( self ): self.setWindowTitle( "Live *.Chi plotter, v. 2.1.0 (April 2013)" ) self.plot = CurvePlot( self ) self.plot.set_antialiasing( True ) self.plot2 = CurvePlot( self ) self.plot2.set_antialiasing( True ) self.button = QtGui.QPushButton( "Search for files" ) self.button2 = QtGui.QPushButton( "Plot selected files" ) self.button3 = QtGui.QPushButton( "Select all" ) self.button4 = QtGui.QPushButton( "Select none" ) self.button5 = QtGui.QPushButton( "Integrate" ) self.button6 = QtGui.QPushButton( "Integral over ROI (defined by the two vertical cursors)" ) left_hbox0 = QtGui.QVBoxLayout() right_hbox0 = QtGui.QVBoxLayout() # Main graph left_vbox = QtGui.QVBoxLayout() left_vbox.addWidget( self.plot, 3) # Smaller graph left_vbox.addWidget( self.plot2, 1 ) self.tick_axis_reset = QtGui.QCheckBox("Reset axis when replotting data") self.tick_axis_reset.setCheckState(Qt.Checked) left_hbox0.addWidget( self.tick_axis_reset ) # Static text field right_hbox0.addWidget( QtGui.QLabel('Directory'), 0, QtCore.Qt.AlignRight ) hbox0 = QtGui.QHBoxLayout() hbox0.addLayout( left_hbox0 ) hbox0.addLayout( right_hbox0 ) left_vbox.addLayout( hbox0 ) # Add buttons to the left side left_vbox.addWidget( self.button ) left_vbox.addWidget( self.button2 ) left_vbox.addWidget( self.button6 ) # Data series list view log_label = QtGui.QLabel("Data series:") self.series_list_model = QtGui.QStandardItemModel() self.series_list_view = QtGui.QListView() self.series_list_view.setModel(self.series_list_model) right_vbox = QtGui.QVBoxLayout() right_vbox.addWidget( log_label ) right_vbox.addWidget( self.series_list_view ) # Create editable text box for inputting directory self.text1 = QtGui.QTextEdit() self.text1.setFixedHeight(22) # Put current directory to the text box self.text1.setText(os.getcwd()) right_vbox.addWidget( self.text1 ) # Add buttons right_vbox.addWidget( self.button3 ) right_vbox.addWidget( self.button4 ) right_vbox.addWidget( self.button5 ) # Combine left and right box hbox = QtGui.QHBoxLayout() hbox.addLayout( left_vbox, 2 ) # Second parameter is the stretch factor hbox.addLayout( right_vbox, 1 ) # of the widget, letting the figure to stretch more w = QtGui.QWidget() w.setLayout( hbox ) self.setCentralWidget( w ) def __setup_layout( self ): self.connect( self.button, QtCore.SIGNAL( 'clicked()' ), self.button_Click ) self.connect( self.button2, QtCore.SIGNAL( 'clicked()' ), self.button_Click2 ) self.connect( self.button3, QtCore.SIGNAL( 'clicked()' ), self.button_Click3 ) self.connect( self.button4, QtCore.SIGNAL( 'clicked()' ), self.button_Click4 ) self.connect( self.button5, QtCore.SIGNAL( 'clicked()' ), self.button_Click5 ) self.connect( self.button6, QtCore.SIGNAL( 'clicked()' ), self.button_Click6 ) # Vertical cursor self.cursorposition = 0.8 self.cursorposition2 = 1.2 self.vcursor1 = make.vcursor(self.cursorposition, label='x = %.2f') self.plot.add_item( self.vcursor1 ) self.vcursor2 = make.vcursor(self.cursorposition2, label='x = %.2f') self.plot.add_item( self.vcursor2 ) # Define the y label, x might change depending on user definition CurvePlot.set_axis_title(self.plot,CurvePlot.Y_LEFT,"Intensity (counts)") # Crate the PlotManager self.manager = PlotManager( self ) self.manager.add_plot( self.plot ) self.manager.add_plot( self.plot2 ) # Create Toolbar toolbar = self.addToolBar( 'tools' ) self.manager.add_toolbar( toolbar, id( toolbar ) ) # Register the ToolBar's type self.manager.register_all_curve_tools( ) # self.manager.register_other_tools() # Register a custom tool self.manager.add_tool( SelectPointTool, title = 'Position', on_active_item = True, mode = 'create' ) def fill_series_list(self, names): self.series_list_model.clear() counterlist = 0 for name in reversed(names): item = QtGui.QStandardItem(name) # if counterlist == 0: # Check only the first one # item.setCheckState(Qt.Checked) # else: item.setCheckState(Qt.Unchecked) item.setCheckable(True) self.series_list_model.appendRow(item) counterlist = counterlist + 1 # Load data to the list def button_Click( self ): # Find the newest files in the directory and subdirectories # and populate the list of files self.y = {} self.x = {} self.timestamp = {} self.names = [] self.fullfilename = {} # Clear the list in case used another directory before self.series_list_model.clear() # Go to the directory specified in the field or if none, give error message curdir = str(self.text1.toPlainText()) if os.path.isdir(curdir): os.chdir(curdir) else: print curdir+" is not a valid directory!" # Find the files in the directory counterfiles = 0 for dirpath, dirnames, filenames in os.walk(os.getcwd()): filenames.sort(key=lambda x: os.path.getmtime(dirpath+'/'+x)) for file1 in filenames: prefix,postfix = os.path.splitext(file1) # Only *.chi files ending with a number are accepted if len(re.findall("[\d]"+".chi",file1))>0: fullfilename1 = dirpath+'/'+file1 time1 = os.path.getmtime(fullfilename1) tmp,subpath = os.path.split(dirpath) tmp,subpath2 = os.path.split(tmp) seriesname1 = os.path.basename(str(subpath2+'_'+subpath+'_'+file1)) self.names.append(seriesname1) # Load data tmp = np.genfromtxt(str(fullfilename1),dtype=None,skip_header=4) self.y[seriesname1] = map(float, np.transpose(tmp[:,1])) self.x[seriesname1] = map(float, np.transpose(tmp[:,0])) self.datalen = len(self.x[seriesname1]) self.timestamp[seriesname1] = time1 self.fullfilename[seriesname1] = fullfilename1 counterfiles = counterfiles + 1 # Populate the checkbox list self.fill_series_list(self.names) #Refresh the figure def button_Click2( self ): # has_series = False # Seed for random generator of colors, so that they are always in the same order random.seed(654321) colorlistred = [220, 255, 155, 24, 0, 0, 48, 205, 255, 255, 0, 142] colorlistgreen = [20, 105, 48, 116, 229, 238, 128, 205, 193, 97, 0, 142] colorlistblue = [60, 180, 255, 205, 238, 118, 20, 0, 37, 3, 0, 142] # Clear the plot first self.plot.del_all_items() # Add back the vertical cursor to the plot in the same position as before self.plot.add_item( self.vcursor1 ) self.plot.add_item( self.vcursor2 ) # For axes take max of 2theta and max of intensity maxtth = 0 maxintensity = 0 mintth = 100 minintensity = 100 # Use first predefined colours, then random colorcounter = 0 # Two simple markers to test if mixed x ranges exist foundq = 0 foundtth = 0 for row in range(self.series_list_model.rowCount()): model_index = self.series_list_model.index(row, 0) checked = self.series_list_model.data(model_index, Qt.CheckStateRole) == QVariant(Qt.Checked) name = str(self.series_list_model.data(model_index).toString()) if checked: # has_series = True self.curveAlabel = name if len(colorlistred) > colorcounter: self.curveA = make.curve( [ ], [ ], self.curveAlabel, QtGui.QColor( colorlistred[colorcounter], colorlistgreen[colorcounter], colorlistblue[colorcounter] ), linewidth=3.0) colorcounter = colorcounter + 1 else: self.curveA = make.curve( [ ], [ ], self.curveAlabel, QtGui.QColor( random.randint(0,255), random.randint(0,255), random.randint(0,255) ), linewidth=3.0) self.plot.add_item( self.curveA ) self.curveA.set_data( self.x[name], self.y[name]) if max(self.x[name])>maxtth: maxtth = max(self.x[name]) if max(self.y[name])>maxintensity: maxintensity = max(self.y[name]) if min(self.x[name])<mintth: mintth = min(self.x[name]) if min(self.y[name])<minintensity and min(self.y[name]) > 0: minintensity = min(self.y[name]) # Check if TTH or Q range, redefine x label if Q f = open(str(self.fullfilename[name])) text1 = f.read() f.close() if 'Azimuth (Degrees)' in text1: foundtth = 1 CurvePlot.set_axis_title(self.plot,CurvePlot.X_BOTTOM,"Azimuth angle (degrees)") elif 'Q' in text1: foundq = 1 CurvePlot.set_axis_title(self.plot,CurvePlot.X_BOTTOM,"q (1/nm)") elif '2-Theta Angle (Degrees)' in text1: foundtth = 1 CurvePlot.set_axis_title(self.plot,CurvePlot.X_BOTTOM,"2-theta (degrees)") if foundq == 1 and foundtth == 1: CurvePlot.set_axis_title(self.plot,CurvePlot.X_BOTTOM,"Mixed! q (1/nm) and 2-theta (degrees)") self.legend = make.legend( 'TR' ) # Top Right self.plot.add_item( self.legend ) # Reset axis if checkbox is checked, otherwise ignore if self.tick_axis_reset.isChecked()==True: CurvePlot.set_axis_limits(self.plot,CurvePlot.X_BOTTOM,mintth*0.9,maxtth*1.1) CurvePlot.set_axis_limits(self.plot,CurvePlot.Y_LEFT,minintensity*0.9,maxintensity*1.1) # Plot everything self.plot.replot( ) # Refresh also the integral plot self.button_Click6( ) # Select all def button_Click3( self ): for k in range(0,len(self.names)): self.series_list_model.item(k).setCheckState( Qt.Checked ) # Select none def button_Click4( self ): for k in range(0,len(self.names)): self.series_list_model.item(k).setCheckState( Qt.Unchecked ) # Download and integrate button def button_Click5( self ): curdir = str(self.text1.toPlainText()) execfile(curdir+"/setup/pipeline.py") # Update file list after integrating self.button_Click( ) # Sum over ROI and update the lower graph def button_Click6( self ): # Clear the plot first self.plot2.del_all_items() # Seed for random generator of colors, so that they are always in the same order random.seed(654321) colorlistred = [220, 255, 155, 24, 0, 0, 48, 205, 255, 255, 0, 142] colorlistgreen = [20, 105, 48, 116, 229, 238, 128, 205, 193, 97, 0, 142] colorlistblue = [60, 180, 255, 205, 238, 118, 20, 0, 37, 3, 0, 142] markerlist = ['Rect','Diamond', 'UTriangle', 'DTriangle', 'RTriangle','Cross', 'Ellipse', 'Star1', 'XCross', 'LTriangle', 'Star2'] # Get cursor positions to define ROI x1 = guiqwt.shapes.Marker.xValue(self.vcursor1) x2 = guiqwt.shapes.Marker.xValue(self.vcursor2) if x2 < x1: x3 = copy.deepcopy(x1) x1 = copy.deepcopy(x2) x2 = x3 indices = [] self.sumy = {} self.sumx = {} # Use first predefined colours, then random colorcounter = 0 maxsumx = 0 minsumx = 10000 maxsumy = 0 minsumy = 10000000 self.sumxall = {} self.sumyall = {} seriesnames = [] for row in range(self.series_list_model.rowCount()): model_index = self.series_list_model.index(row, 0) checked = self.series_list_model.data(model_index, Qt.CheckStateRole) == QVariant(Qt.Checked) name = str(self.series_list_model.data(model_index).toString()) if checked: # Find x values over which to sum indices = [] for index,value in enumerate(self.x[name]): if value > x1 and value < x2: indices.append(index) xx = np.array(self.x[name]) yy = np.array(self.y[name]) sumy1 = np.trapz(yy[indices],xx[indices]) self.sumy[name] = [float(sumy1)] number1 = re.findall("(?<=_|-)[\d]*(?=.chi)",name) sumx1 = int(number1[0]) self.sumx[name] = [float(sumx1)] if max(self.sumx[name])>maxsumx: maxsumx = max(self.sumx[name]) if max(self.sumy[name])>maxsumy: maxsumy = max(self.sumy[name]) if min(self.sumx[name])<minsumx: minsumx = min(self.sumx[name]) if min(self.sumy[name])<minsumy and min(self.sumy[name]) > 0: minsumy = min(self.sumy[name]) # Check which series names we have name1 = re.findall("[\W\S\d]*(?=-[\d]{5}.chi)",name) # Try different versions of writing the names if first one does not succeed if name1 == []: name1 = re.findall("[\W\S\d]*(?=_[\d]{4}.chi)",name) if name1 == []: name1 = re.findall("[\W\S\d]*(?=_[\d]{5}.chi)",name) seriesname1 = str(name1[0]) if seriesname1 not in seriesnames: seriesnames.append(seriesname1) self.sumxall[seriesname1] = [] self.sumyall[seriesname1] = [] self.sumxall[seriesname1].append(sumx1) self.sumyall[seriesname1].append(sumy1) # Make lines and legends to separate different sample series colorcounter = 0 random.seed(654321) markercounter = 0 for seriesname1 in seriesnames: if len(colorlistred) > colorcounter: self.curveB = make.curve( [ ], [ ], seriesname1, QtGui.QColor( colorlistred[colorcounter], colorlistgreen[colorcounter], colorlistblue[colorcounter] ), linewidth=3.0, marker=markerlist[markercounter], markerfacecolor = QtGui.QColor( colorlistred[colorcounter], colorlistgreen[colorcounter], colorlistblue[colorcounter] ), markeredgecolor= QtGui.QColor( colorlistred[colorcounter], colorlistgreen[colorcounter], colorlistblue[colorcounter] )) colorcounter = colorcounter + 1 markercounter = markercounter + 1 else: newcolor = QtGui.QColor( random.randint(0,255), random.randint(0,255), random.randint(0,255)) self.curveB = make.curve( [ ], [ ], seriesname1, newcolor, linewidth=3.0, marker=markerlist[markercounter], markerfacecolor = newcolor, markeredgecolor = newcolor ) markercounter = markercounter + 1 if markercounter > len(markerlist): markercounter = 0 self.plot2.add_item( self.curveB ) self.curveB.set_data( self.sumxall[seriesname1],self.sumyall[seriesname1] ) CurvePlot.set_axis_title(self.plot2,CurvePlot.X_BOTTOM,"File number") CurvePlot.set_axis_title(self.plot2,CurvePlot.Y_LEFT,"ROI sum") self.legend2 = make.legend( 'TR' ) # Top Right self.plot2.add_item( self.legend2 ) # Reset axis if ticked if self.tick_axis_reset.isChecked()==True: CurvePlot.set_axis_limits(self.plot2,CurvePlot.X_BOTTOM,minsumx*0.9,maxsumx*1.1) CurvePlot.set_axis_limits(self.plot2,CurvePlot.Y_LEFT,minsumy*0.9,maxsumy*1.1) # Plot everything self.plot2.replot( )
class EicPlottingWidget(CurveWidget): SELECTED_RANGE_CHANGED = pyqtSignal(float, float) def __init__(self, parent=None, with_range=True): super(EicPlottingWidget, self).__init__(parent, ylabel="I") patch_inner_plot_object(self, EicPlot) self._with_range = with_range self._setup_plot() def enable_range(self, flag): self._with_range = flag self._setup_range_selector() def _setup_plot(self): self.pm = PlotManager(self) self.pm.add_plot(self.plot) t = self.pm.add_tool(RtSelectionTool) t.activate() self.pm.set_default_tool(t) self._setup_cursor() self._setup_range_selector() self._setup_label() self._setup_axes() def _setup_cursor(self): marker = Marker(label_cb=self.plot.label_info, constraint_cb=self.plot.on_plot) marker.rts = [0] setup_marker_param(marker, {"symbol.size": 0, "symbol.alpha": 0.0, "sel_symbol.size": 0, "sel_symbol.alpha": 0.0, "line.color": "#909090", "line.width": 1.0, "line.style": "SolidLine", "sel_line.color": "#909090", "sel_line.width": 1.0, "sel_line.style": "SolidLine", "markerstyle": "VLine"}) marker.attach(self.plot) self.marker = marker self._setup_cursor_info(marker) def _setup_cursor_info(self, marker): self.cursor_info = RtCursorInfo(marker) def _setup_range_selector(self): if not self._with_range: self.range_ = None return self.range_ = SnappingRangeSelection(0, 0) # you have to register item to plot before you can register the # rtSelectionHandler: self.plot.add_item(self.range_) self.range_.SELECTED_RANGE_CHANGED.connect(self._range_selection_handler) cc = make.info_label("TR", [RangeSelectionInfo(self.range_)], title=None) setup_label_param(cc, {"label": "", "font.size": 12}) self.plot.add_item(cc) def _setup_label(self): label = make.info_label("T", [self.cursor_info], title=None) setup_label_param(label, {"label": "", "font.size": 12, "border.color": "#ffffff"}) self.label = label def _setup_axes(self): # render tic labels in modfied format: set_rt_formatting_on_x_axis(self.plot) self.plot.set_axis_title("bottom", "RT") def plot_(self, eics): self.add_eics(eics) def set_cursor_pos(self, rt): self.plot.set_rt(rt) def set_overall_range(self, rtmin, rtmax): self.plot.overall_x_min = rtmin self.plot.overall_x_max = rtmax def add_eics(self, data, labels=None, configs=None): """ do not forget to call replot() after calling this function ! """ allrts = list() if configs is None: configs = [{"color": getColor(i)} for i in range(len(data))] if labels is None: labels = [""] * len(data) unique_labels = set() # items_with_label = [] seen = set() for i, (rts, chromatogram) in enumerate(data): # we do not plot duplicates, which might happen if multiple lines in the # table explorer are sellected ! if (id(rts), id(chromatogram)) in seen: continue seen.add((id(rts), id(chromatogram))) config = configs[i] label = "<pre>%s</pre>" % labels[i] unique_labels.add(label) curve = make_unselectable_curve(rts, chromatogram, title=label, **config) allrts.extend(rts) self.plot.add_item(curve) self.plot.add_item(self.label) self.plot.set_x_values(sorted(set(allrts))) # no idea why guiqwt needs double registration here: self.marker.attach(self.plot) self.plot.add_item(self.marker) # self._add_legend(unique_labels, items_with_label) if self.range_ is not None: self.plot.add_item(self.range_) def _add_legend(self, unique_labels, items_with_label): # überbleibsel von zeitreihen plott unique_labels -= set((None,)) unique_labels -= set(("",)) if unique_labels: legend = make.legend("TL", restrict_items=items_with_label) setup_label_param(legend, {"font.size": 12}) self.plot.add_item(legend) def add_eic_filled(self, rts, iis, baseline, color): shape = create_closed_shape(rts, iis, baseline, color) if shape is not None: self.plot.add_item(shape) def set_visible(self, visible): self.plot.setVisible(visible) def get_range_selection_limits(self): if self.range_ is None: return None, None return sorted((self.range_._min, self.range_._max)) def set_range_selection_limits(self, xleft, xright): if self.range_ is None: return self.range_.move_point_to(0, (xleft, 0)) self.range_.move_point_to(1, (xright, 0)) def reset_intensity_limits(self, imin=None, imax=None, fac=1.1, rtmin=None, rtmax=None): self.plot.reset_y_limits(imin, imax, fac, rtmin, rtmax) @protect_signal_handler def _range_selection_handler(self, left, right): min_, max_ = sorted((left, right)) self.SELECTED_RANGE_CHANGED.emit(min_, max_) def set_rt_axis_limits(self, xmin, xmax): self.plot.update_plot_xlimits(xmin, xmax) def get_limits(self): return self.plot.get_plot_limits() def updateAxes(self): self.plot.updateAxes() def set_intensity_axis_limits(self, ymin, ymax): self.plot.update_plot_ylimits(ymin, ymax) def reset_rt_limits(self, rt_min=None, rt_max=None, fac=1.1): self.plot.reset_x_limits(rt_min, rt_max, fac) def reset_intensitiy_limits(self, i_min=None, i_max=None, fac=1.1, rt_min=None, rt_max=None): self.plot.reset_y_limits(i_min, i_max, fac, rt_min, rt_max) def set_limit(self, ix, value): self.plot.set_limit(ix, value) def getLimits(self): return self.plot.get_plot_limits() def replot(self): self.plot.replot() def del_all_items(self): self.plot.del_all_items() def reset(self): """empties plot""" self.del_all_items() self.replot() def shrink_and_replot(self, rtmin, rtmax): self.reset_rt_limits(rtmin, rtmax) self.plot.reset_y_limits() self.plot.replot()
class RtPlotter(PlotterBase): def __init__(self, rangeSelectionCallback = None): super(RtPlotter, self).__init__("RT", "I") self.rangeSelectionCallback = rangeSelectionCallback widget = self.widget widget.plot.__class__ = RtPlot # todo: refactor as helper a = QwtScaleDraw() # render tic labels in modfied format: label = lambda self, v: QwtText(formatSeconds(v)) a.label = new.instancemethod(label, widget.plot, QwtScaleDraw) widget.plot.setAxisScaleDraw(widget.plot.xBottom, a) #a.label = new.instancemethod(label, widget.plot, QwtScaleDraw) self.pm = PlotManager(widget) self.pm.add_plot(widget.plot) t = self.pm.add_tool(RtSelectionTool) self.addTool(RtSelectionTool) self.pm.set_default_tool(t) marker = Marker(label_cb=self.widget.plot.label_info,\ constraint_cb=self.widget.plot.on_plot) marker.rts = [0] setupStyleRtMarker(marker) marker.attach(self.widget.plot) self.marker = marker label = make.info_label("T", [RtCursorInfo(marker)], title=None) label.labelparam.label = "" self.label=label self.minRTRangeSelected = None self.maxRTRangeSelected = None def addTool(self, tool): t = self.pm.add_tool(tool) t.activate() def reset(self): self.plot([]) self.marker.rts = [0] self.replot() def plot(self, chromatograms, titles=None, configs=None,\ withmarker=False): """ do not forget to call replot() after calling this function ! """ allrts = set() self.widget.plot.del_all_items() #self.widget.plot.set_antialiasing(True) for i in range(len(chromatograms)): rts, chromatogram = chromatograms[i] config = None if configs is not None: config = configs[i] if config is None: config = dict(color = getColor(i)) if titles: title = titles[i] else: title = "" curve = make.curve(rts, chromatogram, title=title, **config) curve.__class__ = ModifiedCurveItem allrts.update(rts) self.widget.plot.add_item(curve) if withmarker: self.widget.plot.add_item(self.label) allrts = sorted(allrts) self.marker.rts = allrts self.marker.attach(self.widget.plot) self.widget.plot.add_item(self.marker) if titles is not None: self.widget.plot.add_item(make.legend("TL")) self.addRangeSelector(allrts) def setEnabled(self, enabled): self.widget.plot.setVisible(enabled) def addRangeSelector(self, rtvalues): self.rtvalues = rtvalues self.minRTRangeSelected = 0 self.maxRTRangeSelected = 0 range_ = SnappingRangeSelection(self.minRTRangeSelected,\ self.maxRTRangeSelected, self.rtvalues) setupStyleRangeMarker(range_) self.range_ = range_ # you have to register item to plot before you can register the # rtSelectionHandler: self.widget.plot.add_item(range_) self.widget.disconnect(range_.plot(), SIG_RANGE_CHANGED,\ self.rangeSelectionHandler) self.widget.connect(range_.plot(), SIG_RANGE_CHANGED,\ self.rangeSelectionHandler) cc = make.info_label("TR", [RtRangeSelectionInfo(range_)], title=None) cc.labelparam.label = "" self.widget.plot.add_item(cc) def getRangeSelectionLimits(self): return sorted( (self.range_._min, self.range_._max) ) def setRangeSelectionLimits(self, xleft, xright): saved = self.rangeSelectionCallback self.rangeSelectionCallback = None self.minRTRangeSelected = xleft self.maxRTRangeSelected = xright # left and right bar of range marker self.range_.move_point_to(0, (xleft,0), emitsignal=False) self.range_.move_point_to(1, (xright,0)) # calls self.rangeSelectionHandler ! self.rangeSelectionCallback = saved @protect_signal_handler def rangeSelectionHandler(self, obj, left, right): min_, max_ = sorted((left, right)) self.minRTRangeSelected = min_ self.maxRTRangeSelected = max_ if self.rangeSelectionCallback is not None: self.rangeSelectionCallback()
class MzPlotter(PlotterBase): def __init__(self, c_callback=None): super(MzPlotter, self).__init__("m/z", "I") self.c_callback = c_callback widget = self.widget # inject mofified behaviour of wigets plot attribute: widget.plot.__class__ = MzPlot widget.plot.register_c_callback(self.handle_c_pressed) self.setHalfWindowWidth(0.05) self.centralMz = None # todo: refactor as helper a = QwtScaleDraw() label = lambda self, x : QwtText("%s" % x) a.label = new.instancemethod(label, widget.plot, QwtScaleDraw) widget.plot.setAxisScaleDraw(widget.plot.xBottom, a) self.pm = PlotManager(widget) self.pm.add_plot(widget.plot) self.curve = make.curve([], [], color='b', curvestyle="Sticks") # inject modified behaviour: self.curve.__class__ = ModifiedCurveItem self.widget.plot.add_item(self.curve) t = self.pm.add_tool(MzSelectionTool) self.pm.set_default_tool(t) t.activate() marker = Marker(label_cb=widget.plot.label_info,\ constraint_cb=widget.plot.on_plot) marker.attach(self.widget.plot) line = make.segment(0, 0, 0, 0) line.__class__ = ModifiedSegment line.setVisible(0) setupCommonStyle(line, marker) label = make.info_label("TR", [MzCursorInfo(marker, line)], title=None) label.labelparam.label = "" self.marker = marker self.label = label self.line = line def setHalfWindowWidth(self, w2): self.widget.plot.set_half_window_width(w2) def setCentralMz(self, mz): self.widget.plot.set_central_mz(mz) def handle_c_pressed(self, p): if self.c_callback: self.c_callback(p) def plot(self, spectra, configs=None, titles=None): """ do not forget to call replot() after calling this function ! """ self.widget.plot.del_all_items() self.widget.plot.add_item(self.marker) if titles is not None: self.widget.plot.add_item(make.legend("TL")) self.widget.plot.add_item(self.label) allpeaks = [] for i in range(len(spectra)): peaks = spectra[i] allpeaks.append(peaks) config = configs[i] if configs is not None else None if config is None: config = dict(color = getColor(i)) if titles is not None: title = titles[i] else: title = u"" curve = make.curve([], [], title=title,\ curvestyle="Sticks", **config) curve.set_data(peaks[:, 0], peaks[:, 1]) curve.__class__ = ModifiedCurveItem self.widget.plot.add_item(curve) self.widget.plot.add_item(self.line) if len(allpeaks): self.widget.plot.all_peaks = np.vstack(allpeaks) else: self.widget.plot.all_peaks = np.zeros((0,2)) def resetAxes(self): self.widget.plot.reset_x_limits() def reset(self): self.plot(np.ndarray((0,2))) self.replot()
class EicPlottingWidget(CurveWidget): SELECTED_RANGE_CHANGED = pyqtSignal(float, float) def __init__(self, parent=None, with_range=True): super(EicPlottingWidget, self).__init__(parent, ylabel="I") patch_inner_plot_object(self, EicPlot) self._with_range = with_range self._setup_plot() def enable_range(self, flag): self._with_range = flag self._setup_range_selector() def _setup_plot(self): self.pm = PlotManager(self) self.pm.add_plot(self.plot) t = self.pm.add_tool(RtSelectionTool) t.activate() self.pm.set_default_tool(t) self._setup_cursor() self._setup_range_selector() self._setup_label() self._setup_axes() def _setup_cursor(self): marker = Marker(label_cb=self.plot.label_info, constraint_cb=self.plot.on_plot) marker.rts = [0] setup_marker_param( marker, { "symbol.size": 0, "symbol.alpha": 0.0, "sel_symbol.size": 0, "sel_symbol.alpha": 0.0, "line.color": "#909090", "line.width": 1.0, "line.style": "SolidLine", "sel_line.color": "#909090", "sel_line.width": 1.0, "sel_line.style": "SolidLine", "markerstyle": "VLine" }) marker.attach(self.plot) self.marker = marker self._setup_cursor_info(marker) def _setup_cursor_info(self, marker): self.cursor_info = RtCursorInfo(marker) def _setup_range_selector(self): if not self._with_range: self.range_ = None return self.range_ = SnappingRangeSelection(0, 0) # you have to register item to plot before you can register the # rtSelectionHandler: self.plot.add_item(self.range_) self.range_.SELECTED_RANGE_CHANGED.connect( self._range_selection_handler) cc = make.info_label("TR", [RangeSelectionInfo(self.range_)], title=None) setup_label_param(cc, {"label": "", "font.size": 12}) self.plot.add_item(cc) def _setup_label(self): label = make.info_label("T", [self.cursor_info], title=None) setup_label_param(label, { "label": "", "font.size": 12, "border.color": "#ffffff" }) self.label = label def _setup_axes(self): # render tic labels in modfied format: set_rt_formatting_on_x_axis(self.plot) self.plot.set_axis_title("bottom", "RT") def plot_(self, eics): self.add_eics(eics) def set_cursor_pos(self, rt): self.plot.set_rt(rt) def set_overall_range(self, rtmin, rtmax): self.plot.overall_x_min = rtmin self.plot.overall_x_max = rtmax def add_eics(self, data, labels=None, configs=None): """ do not forget to call replot() after calling this function ! """ allrts = list() if configs is None: configs = [{"color": getColor(i)} for i in range(len(data))] if labels is None: labels = [""] * len(data) unique_labels = set() # items_with_label = [] seen = set() for i, (rts, chromatogram) in enumerate(data): # we do not plot duplicates, which might happen if multiple lines in the # table explorer are sellected ! if (id(rts), id(chromatogram)) in seen: continue seen.add((id(rts), id(chromatogram))) config = configs[i] label = "<pre>%s</pre>" % labels[i] unique_labels.add(label) curve = make_unselectable_curve(rts, chromatogram, title=label, **config) allrts.extend(rts) self.plot.add_item(curve) self.plot.add_item(self.label) self.plot.set_x_values(sorted(set(allrts))) # no idea why guiqwt needs double registration here: self.marker.attach(self.plot) self.plot.add_item(self.marker) # self._add_legend(unique_labels, items_with_label) if self.range_ is not None: self.plot.add_item(self.range_) def _add_legend(self, unique_labels, items_with_label): # überbleibsel von zeitreihen plott unique_labels -= set((None, )) unique_labels -= set(("", )) if unique_labels: legend = make.legend("TL", restrict_items=items_with_label) setup_label_param(legend, {"font.size": 12}) self.plot.add_item(legend) def add_eic_filled(self, rts, iis, baseline, color): shape = create_closed_shape(rts, iis, baseline, color) if shape is not None: self.plot.add_item(shape) def set_visible(self, visible): self.plot.setVisible(visible) def get_range_selection_limits(self): if self.range_ is None: return None, None return sorted((self.range_._min, self.range_._max)) def set_range_selection_limits(self, xleft, xright): if self.range_ is None: return self.range_.move_point_to(0, (xleft, 0)) self.range_.move_point_to(1, (xright, 0)) def reset_intensity_limits(self, imin=None, imax=None, fac=1.1, rtmin=None, rtmax=None): self.plot.reset_y_limits(imin, imax, fac, rtmin, rtmax) @protect_signal_handler def _range_selection_handler(self, left, right): min_, max_ = sorted((left, right)) self.SELECTED_RANGE_CHANGED.emit(min_, max_) def set_rt_axis_limits(self, xmin, xmax): self.plot.update_plot_xlimits(xmin, xmax) def get_limits(self): return self.plot.get_plot_limits() def updateAxes(self): self.plot.updateAxes() def set_intensity_axis_limits(self, ymin, ymax): self.plot.update_plot_ylimits(ymin, ymax) def reset_rt_limits(self, rt_min=None, rt_max=None, fac=1.1): self.plot.reset_x_limits(rt_min, rt_max, fac) def reset_intensitiy_limits(self, i_min=None, i_max=None, fac=1.1, rt_min=None, rt_max=None): self.plot.reset_y_limits(i_min, i_max, fac, rt_min, rt_max) def set_limit(self, ix, value): self.plot.set_limit(ix, value) def getLimits(self): return self.plot.get_plot_limits() def replot(self): self.plot.replot() def del_all_items(self): self.plot.del_all_items() def reset(self): """empties plot""" self.del_all_items() self.replot() def shrink_and_replot(self, rtmin, rtmax): self.reset_rt_limits(rtmin, rtmax) self.plot.reset_y_limits() self.plot.replot()
class RtPlotter(PlotterBase): def __init__(self, rangeSelectionCallback=None): super(RtPlotter, self).__init__("RT", "I") self.rangeSelectionCallback = rangeSelectionCallback widget = self.widget widget.plot.__class__ = RtPlot # todo: refactor as helper a = QwtScaleDraw() # render tic labels in modfied format: label = lambda self, v: QwtText(formatSeconds(v)) a.label = new.instancemethod(label, widget.plot, QwtScaleDraw) widget.plot.setAxisScaleDraw(widget.plot.xBottom, a) self.pm = PlotManager(widget) self.pm.add_plot(widget.plot) t = self.pm.add_tool(RtSelectionTool) self.addTool(RtSelectionTool) self.pm.set_default_tool(t) marker = Marker(label_cb=self.widget.plot.label_info, constraint_cb=self.widget.plot.on_plot) marker.rts = [0] setupStyleRtMarker(marker) marker.attach(self.widget.plot) self.marker = marker label = make.info_label("T", [RtCursorInfo(marker)], title=None) label.labelparam.label = "" self.label = label self.minRTRangeSelected = None self.maxRTRangeSelected = None def addTool(self, tool): t = self.pm.add_tool(tool) t.activate() def reset(self): self.plot([]) self.marker.rts = [0] self.replot() def plot(self, chromatograms, titles=None, configs=None, withmarker=False): """ do not forget to call replot() after calling this function ! """ allrts = set() self.widget.plot.del_all_items() # self.widget.plot.set_antialiasing(True) for i in range(len(chromatograms)): rts, chromatogram = chromatograms[i] config = None if configs is not None: config = configs[i] if config is None: config = dict(color=getColor(i)) if titles: title = titles[i] else: title = "" curve = make.curve(rts, chromatogram, title=title, **config) curve.__class__ = ModifiedCurveItem allrts.update(rts) self.widget.plot.add_item(curve) if withmarker: self.widget.plot.add_item(self.label) allrts = sorted(allrts) self.marker.rts = allrts self.marker.attach(self.widget.plot) self.widget.plot.add_item(self.marker) if titles is not None: self.widget.plot.add_item(make.legend("TL")) self.addRangeSelector(allrts) def setEnabled(self, enabled): self.widget.plot.setVisible(enabled) def addRangeSelector(self, rtvalues): self.rtvalues = rtvalues self.minRTRangeSelected = 0 self.maxRTRangeSelected = 0 range_ = SnappingRangeSelection(self.minRTRangeSelected, self.maxRTRangeSelected, self.rtvalues) setupStyleRangeMarker(range_) self.range_ = range_ # you have to register item to plot before you can register the # rtSelectionHandler: self.widget.plot.add_item(range_) self.widget.disconnect(range_.plot(), SIG_RANGE_CHANGED, self.rangeSelectionHandler) self.widget.connect(range_.plot(), SIG_RANGE_CHANGED, self.rangeSelectionHandler) cc = make.info_label("TR", [RtRangeSelectionInfo(range_)], title=None) cc.labelparam.label = "" self.widget.plot.add_item(cc) def getRangeSelectionLimits(self): return sorted((self.range_._min, self.range_._max)) def setRangeSelectionLimits(self, xleft, xright): saved = self.rangeSelectionCallback self.rangeSelectionCallback = None self.minRTRangeSelected = xleft self.maxRTRangeSelected = xright # left and right bar of range marker self.range_.move_point_to(0, (xleft, 0), emitsignal=False) self.range_.move_point_to(1, (xright, 0)) # calls self.rangeSelectionHandler ! self.rangeSelectionCallback = saved @protect_signal_handler def rangeSelectionHandler(self, obj, left, right): min_, max_ = sorted((left, right)) self.minRTRangeSelected = min_ self.maxRTRangeSelected = max_ if self.rangeSelectionCallback is not None: self.rangeSelectionCallback()
class MzPlotter(PlotterBase): def __init__(self, c_callback=None, image_plot=None): super(MzPlotter, self).__init__("m/z", "I") self.c_callback = c_callback widget = self.widget # inject mofified behaviour of wigets plot attribute: widget.plot.__class__ = MzPlot widget.plot.register_c_callback(self.handle_c_pressed) widget.plot.image_plot = image_plot self.setHalfWindowWidth(0.05) self.centralMz = None # todo: refactor as helper a = QwtScaleDraw() label = lambda self, x: QwtText("%s" % x) a.label = new.instancemethod(label, widget.plot, QwtScaleDraw) widget.plot.setAxisScaleDraw(widget.plot.xBottom, a) self.pm = PlotManager(widget) self.pm.add_plot(widget.plot) self.curve = make.curve([], [], color='b', curvestyle="Sticks") # inject modified behaviour: self.curve.__class__ = ModifiedCurveItem self.widget.plot.add_item(self.curve) t = self.pm.add_tool(MzSelectionTool) self.pm.set_default_tool(t) t.activate() marker = Marker(label_cb=widget.plot.label_info, constraint_cb=widget.plot.on_plot) marker.attach(self.widget.plot) line = make.segment(0, 0, 0, 0) line.__class__ = ModifiedSegment line.setVisible(0) setupCommonStyle(line, marker) label = make.info_label("TR", [MzCursorInfo(marker, line)], title=None) label.labelparam.label = "" self.marker = marker self.label = label self.line = line def setHalfWindowWidth(self, w2): self.widget.plot.set_half_window_width(w2) def setCentralMz(self, mz): self.widget.plot.set_central_mz(mz) def handle_c_pressed(self, p): if self.c_callback: self.c_callback(p) def plot(self, data, configs=None, titles=None): """ do not forget to call replot() after calling this function ! """ self.widget.plot.del_all_items() self.widget.plot.add_item(self.marker) if titles is not None: self.widget.plot.add_item(make.legend("TL")) self.widget.plot.add_item(self.label) all_peaks = [] self.widget.plot.data = [] self.widget.plot.curves = [] for i, (pm, rtmin, rtmax, mzmin, mzmax, npeaks) in enumerate(data): if rtmin is None and rtmax is None: rtmin, rtmax = pm.rtRange() elif rtmin is None: rtmin, __ = pm.rtRange() elif rtmax is None: __, rtmax = pm.rtRange() if mzmin is None and mzmax is None: mzmin, mzmax = pm.mzRange() elif mzmin is None: mzmin, __ = pm.mzRange() elif mzmax is None: __, mzmax = pm.mzRange() if npeaks is None: npeaks = 3000 peaks = sample_peaks(pm, rtmin, rtmax, mzmin, mzmax, npeaks) all_peaks.append(peaks) config = configs[i] if configs is not None else None if config is None: config = dict(color=getColor(i)) if titles is not None: title = titles[i] else: title = u"" curve = make.curve([], [], title=title, curvestyle="Sticks", **config) curve.set_data(peaks[:, 0], peaks[:, 1]) curve.__class__ = ModifiedCurveItem self.widget.plot.add_item(curve) self.widget.plot.curves.append(curve) self.widget.plot.data.append((pm, rtmin, rtmax, mzmin, mzmax, npeaks)) self.widget.plot.add_item(self.line) if len(all_peaks): self.widget.plot.all_peaks = np.vstack(all_peaks) else: self.widget.plot.all_peaks = np.zeros((0, 2)) def resetAxes(self): self.widget.plot.reset_x_limits() def reset(self): self.plot(np.ndarray((0, 2))) self.replot()