示例#1
0
def test_ColorMap_getColors(color_list):
    cm = pg.ColorMap(pos, color_list, name='from QColors')

    colors = cm.getColors()
    assert (colors == int_tuples).all()

    colors = cm.getColors('byte')
    assert (colors == int_tuples).all()

    colors = cm.getColors('float')
    assert (colors == float_tuples).all()

    colors = cm.getColors('qcolor')
    for actual, good in zip(colors, qcols):
        assert actual.getRgbF() == good.getRgbF()
示例#2
0
    def RdBuCbar(self):
        """
        Use Matplotlib colortable `RdBu` for ImageView colorbar
        """
        self.parent.cbarName = 'RdBu'

        # Initialize a matplotlib colortable
        self.hist = self.getHistogramWidget()
        self.parent.setCbar()
        pos, color = np.arange(0, 1, 1 / 256), self.parent.colorTable

        # Hide the ticks on colorbar (only need for matplotlib cmap)
        self.hist.gradient.setColorMap(pg.ColorMap(pos, color))
        for tick in self.hist.gradient.ticks:
            tick.hide()
示例#3
0
 def init(self):
   if self.dataType == DataFormat.DATA_2D:
     if self.colorMapType == DataFormat.COLOR_MAP_BW: # Uses sqrt(x) for B/W levels
       pos = np.array([ 0. ,  0.1,  0.2,  0.3,  0.4,  0.5,  0.6,  0.7,  0.8,  0.9,  1. ])*(self.levels[1] - self.levels[0])*self.scalingFactor + self.levels[0]*self.scalingFactor
       color = np.array(
          [[   0.        ,    0.        ,    0.        ],
           [  80.63808033,   80.63808033,   80.63808033],
           [ 114.03946685,  114.03946685,  114.03946685],
           [ 139.66925216,  139.66925216,  139.66925216],
           [ 161.27616067,  161.27616067,  161.27616067],
           [ 180.3122292 ,  180.3122292 ,  180.3122292 ],
           [ 197.52215066,  197.52215066,  197.52215066],
           [ 213.34830677,  213.34830677,  213.34830677],
           [ 228.0789337 ,  228.0789337 ,  228.0789337 ],
           [ 241.914241  ,  241.914241  ,  241.914241  ],
           [ 255.        ,  255.        ,  255.        ]], dtype=np.uint16)
       self.cmap = pyqtgraph.ColorMap(pos, color)
       self.colorMap = self.cmap.getLookupTable(self.levels[0]*self.scalingFactor, self.levels[1]*self.scalingFactor, self.numPoints, alpha = True, mode='byte')
       
       # Used by HistogramLUTWidget only
       pos = np.array([0., 1.])
       self.cmap = pyqtgraph.ColorMap(pos, color)
     else:
       pos = np.array([0., 0.25, 0.50, 0.75, 1.])*(self.levels[1] - self.levels[0])*self.scalingFactor + self.levels[0]*self.scalingFactor
       color = np.array([[255,0,0,255], [255,255,0,255], [0,255,0,255], [0,255,255,255], [0,0,255,255]], dtype=np.uint16)
       self.cmap = pyqtgraph.ColorMap(pos, color)
       self.colorMap = self.cmap.getLookupTable(self.levels[0]*self.scalingFactor, self.levels[1]*self.scalingFactor, self.numPoints, alpha = True, mode='byte')
       
       # Used by HistogramLUTWidget only
       pos = np.array([0., 0.25, 0.50, 0.75, 1.])
       self.cmap = pyqtgraph.ColorMap(pos, color)
   else:
     if self.colorMapType == DataFormat.COLOR_MAP_BW: # Uses sqrt(x) for B/W levels
       pos = np.array([ 0. ,  0.1,  0.2,  0.3,  0.4,  0.5,  0.6,  0.7,  0.8,  0.9,  1. ])*(self.levels[1] - self.levels[0])*self.scalingFactor + self.levels[0]*self.scalingFactor
       color = np.array(
         [[ 0.        ,  0.        ,  0.        ],
         [ 0.31622777,  0.31622777,  0.31622777],
         [ 0.4472136 ,  0.4472136 ,  0.4472136 ],
         [ 0.54772256,  0.54772256,  0.54772256],
         [ 0.63245553,  0.63245553,  0.63245553],
         [ 0.70710678,  0.70710678,  0.70710678],
         [ 0.77459667,  0.77459667,  0.77459667],
         [ 0.83666003,  0.83666003,  0.83666003],
         [ 0.89442719,  0.89442719,  0.89442719],
         [ 0.9486833 ,  0.9486833 ,  0.9486833 ],
         [ 1.        ,  1.        ,  1.        ]], dtype=np.float32)
       self.cmap = pyqtgraph.ColorMap(pos, color)
       self.colorMap = self.cmap.getLookupTable(0, 1, self.numPoints, alpha = True, mode='float')
     else:
       #pos = np.array([0., 0.25, 0.50, 0.75, 1.])*(self.levels[1] - self.levels[0])*self.scalingFactor + self.levels[0]*self.scalingFactor
       #color = np.array([[1.,0.,0.,1.], [1.,1.,0.,0.8], [0.,1.,0.,0.5], [0.,1.,1.,0.2], [0.,0.,1.,0.01]], dtype=np.float32)
       pos = np.array([0., 0.33, 0.67, 1.])*(self.levels[1] - self.levels[0])*self.scalingFactor + self.levels[0]*self.scalingFactor
       color = np.array([[0.,0.,0.,1.], [0.,0.,1.,1.0], [1.,0.,0.,1.0], [1.,1.,0.,1.0]], dtype=np.float32)
       self.cmap = pyqtgraph.ColorMap(pos, color)
       self.colorMap = self.cmap.getLookupTable(0, 1, self.numPoints, alpha = True, mode='float')
示例#4
0
def ImageColorMap(Cmap, grade):
    if Cmap == 'Wh_rainbow':
        file = Path + '/Wh_rainbow.dat'
        Colors0 = np.loadtxt(file)

    #Colors=[pg.QtGui.QColor(cl[0],cl[1],cl[2]) for cl in Colors0]
    Colors = [[int(cl[0] * 255),
               int(cl[1] * 255),
               int(cl[2] * 255), 255] for cl in Colors0]
    Val = np.linspace(0, 1, len(Colors))
    CM = pg.ColorMap(Val, Colors)

    return CM.getLookupTable(0.0, 1.0, grade)


#print(ImageColorMap('Wh_rainbow',grade))
    def gen_default_colour(self):
        """
        Generate the default colours of the plots
        """
        val = [0.0, 0.5, 1.0]
        colour = np.array(
            [[255, 0, 0, 255], [0, 255, 0, 255], [0, 0, 255, 255]],
            dtype=np.ubyte)
        self.plot_colourmap = pg.ColorMap(val, colour)
        c_list = self.plot_colourmap.getLookupTable(nPts=len(self.plotlines))

        self.def_colours = []
        for i in range(len(self.plotlines)):
            r, g, b = c_list[i]
            self.set_plot_colour(i, QColor(r, g, b))
            self.def_colours.append(QColor(r, g, b))
示例#6
0
    def __init__(self, cmap_name, cbin=256, parent=None):
        pg.GraphicsWidget.__init__(self)

        # Create colour map from matplotlib colourmap name
        self.cmap_name = cmap_name
        cmap = matplotlib.cm.get_cmap(self.cmap_name)
        if type(cmap) == matplotlib.colors.LinearSegmentedColormap:
            cbins = np.linspace(0.0, 1.0, cbin)
            colors = (cmap(cbins)[np.newaxis, :, :3][0]).tolist()
        else:
            colors = cmap.colors
        colors = [c + [1.] for c in colors]
        positions = np.linspace(0, 1, len(colors))
        self.map = pg.ColorMap(positions, colors)
        self.lut = self.map.getLookupTable()
        self.grad = self.map.getGradient()
示例#7
0
 def set_cp_data(self):
     self.data = self.dm.cp_data
     self.dmin = self.data.min()
     self.dmax = self.data.max()
     self.im.setImage(self.data)
     pos = np.linspace(self.dmin, self.dmax, len(self.colors))
     cmap = pg.ColorMap(pos, self.colors)
     lut = cmap.getLookupTable(self.dmin, self.dmax, self.data.size)
     self.im.setLookupTable(lut)
     self.plt.vb.setLimits(xMin=-1,
                           xMax=self.data.shape[0] + 1,
                           yMin=-1,
                           yMax=self.data.shape[1] + 1)
     self.row_marker.setBounds((0, self.data.shape[1]))
     self.col_marker.setBounds((0, self.data.shape[0]))
     self.auto_range()
示例#8
0
def make_colormap_from_gradient(clip, gradient):
    """
    -i- clip : list, clip value, [min, max], physical values
    -i- gradient : dictionary, color gradient, grade value range is 0-1.
    -o- colormap : class object
    Scale the gradient to the clip range and return colormap.
    """
    mode = gradient['mode']
    pos, color = [], []
    for tick in gradient['ticks']:
        # scale from color tick value to physical value in clip range
        stop = clip[0] + tick[0] * (clip[1] - clip[0])
        pos.append(stop)
        color.append(tick[1])
    colormap = pg.ColorMap(pos, color, mode)  # TODO check mode
    return colormap
示例#9
0
def createDatasetViewer(ds:Dataset):    
    # Interpret image data as row-major instead of col-major
    pg.setConfigOptions(imageAxisOrder='row-major')
    
    img = ds.renderGaussianSpots(10, 0.5)
        
    ## Create window with ImageView widget
    win = QtGui.QDialog()
    win.resize(800,800)
    layout = QVBoxLayout(win)
    imv = pg.ImageView()
    layout.addWidget(imv)
    #win.setCentralWidget(imv)
    win.show()
    name = ds['locs_path']
    win.setWindowTitle(f'Viewing {name}')
        
    ## Add time-varying signal
    """
    sig = np.zeros(data.shape[0])
    sig[30:] += np.exp(-np.linspace(1,10, 70))
    sig[40:] += np.exp(-np.linspace(1,10, 60))
    sig[70:] += np.exp(-np.linspace(1,10, 30))
    
    sig = sig[:,np.newaxis,np.newaxis] * 3
    data[:,50:60,30:40] += sig 
    """
    
    imv.setImage(img)
    
    
    ## Display the data and assign each frame a time value from 1.0 to 3.0
    #imv.setImage(data, xvals=np.linspace(1., 3., data.shape[0]))
    
    ## Set a custom color map
    colors = [
        (0, 0, 0),
        (45, 5, 61),
        (84, 42, 55),
        (150, 87, 60),
        (208, 171, 141),
        (255, 255, 255)
    ]
    cmap = pg.ColorMap(pos=np.linspace(0.0, 1.0, 6), color=colors)
    imv.setColorMap(cmap)
        
    return win
示例#10
0
文件: go_widget.py 项目: mochar/bpsys
    def set_up(self):
        layout = QtGui.QHBoxLayout()
        self.setLayout(layout)

        # Graph
        self.graph_widget = self.create_graph_widget()
        self.color_map = pg.ColorMap([0, 0.5, 1], [(1., 1., 1.), (1., 1., 0.),
                                                   (1., 0.5, 0.)])

        # Enriched GO terms
        go_table = pg.TableWidget()
        go_table.setSelectionBehavior(QtGui.QAbstractItemView.SelectRows)
        go_table.clicked.connect(self.select_term)
        data = np.array([(term[0], float(term[1]), len(term[2]))
                         for term in self.analysis.go_terms.values()],
                        dtype=[('GO ID', object), ('P-waarde', float),
                               ('Eiwitten', int)])
        go_table.setData(data)

        # Proteins in selected GO term
        proteins_container = QtGui.QWidget()
        proteins_container.setLayout(QtGui.QVBoxLayout())
        self.proteins_table = pg.TableWidget()
        self.proteins_table.setSelectionBehavior(
            QtGui.QAbstractItemView.SelectRows)
        self.proteins_table.setSizePolicy(
            QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding,
                              QtGui.QSizePolicy.Expanding))
        self.graph_title = QtGui.QLabel('')
        self.graph_title.setAlignment(QtCore.Qt.AlignHCenter)
        self.graph_title.setOpenExternalLinks(True)
        font = QtGui.QFont()
        font.setBold(True)
        self.graph_title.setFont(font)
        self.graph_title.setWordWrap(True)
        self.show_graph_button = QtGui.QPushButton('Graph')
        self.show_graph_button.clicked.connect(self.show_graph)
        proteins_container.layout().addWidget(self.graph_title)
        proteins_container.layout().addWidget(self.proteins_table)
        proteins_container.layout().addWidget(self.show_graph_button)

        # Splitter with widgets
        splitter = QtGui.QSplitter(self)
        splitter.addWidget(go_table)
        splitter.addWidget(proteins_container)
        splitter.setSizes([1, 1, 1])
        layout.addWidget(splitter)
示例#11
0
 def colormap_legend(self):
     if self.legend is not None:
         self.view_box.removeItem(self.legend)
     if len(self.colorMap.children()) == 0:
         pg.QtGui.QMessageBox.information(
             self.main_window, '',
             "No Analysis ColorMap is selected, please add one and Update Results",
             pg.QtGui.QMessageBox.Ok)
         raise Exception("No color maps are selected.")
     cmap_item = [
         cmap for cmap in self.colorMap.children()
         if cmap['Enabled'] is True
     ][0]
     # log_scale = self.params.child('log_scale').value()
     colors = cmap_item.value().color
     x_min = cmap_item['Min']
     x_max = cmap_item['Max']
     x = np.linspace(x_min, x_max, len(colors))
     name = cmap_item.name()
     if name.endswith('Probability'):
         log_scale = True
     else:
         log_scale = False
     # units = self.colorMap.fields[name].get('units', None)
     min_scale, _ = pg.siScale(x_min)
     max_scale, _ = pg.siScale(x_max)
     scale = min_scale if (1 / min_scale) < (1 / max_scale) else max_scale
     # if units is not None:
     #     units = scale + units
     # else:
     #     units = ''
     self.legend = pg.GradientLegend([25, 300], [-20, -30])
     if log_scale is True:
         cmap2 = pg.ColorMap(x, colors)
         self.legend.setGradient(cmap2.getGradient())
         self.legend.setLabels({
             '%0.02f' % (a * scale): b
             for a, b in zip(cmap_item.value().pos, x)
         })
     else:
         self.legend.setGradient(cmap_item.value().getGradient())
         self.legend.setLabels({
             '%0.02f' % (a * scale): b
             for a, b in zip(x,
                             cmap_item.value().pos)
         })
     self.view_box.addItem(self.legend)
示例#12
0
    def gen_default_colour(self):
        """
        Reimplemented from LiveGraph.
        """
        val = [0.0, 0.5, 1.0]
        colour = np.array(
            [[255, 0, 0, 255], [0, 255, 0, 255], [0, 0, 255, 255]],
            dtype=np.ubyte)
        plot_colourmap = pg.ColorMap(val, colour)
        c_list = plot_colourmap.getLookupTable(nPts=len(self.peak_plots))

        self.def_colours = []
        for i in range(len(self.peak_plots)):
            r, g, b = c_list[i]
            #self.plotlines.set_plot_colour(i,QColor(r,g,b),True)
            self.plot_colours[i] = QColor(r, g, b)
            self.def_colours.append(QColor(r, g, b))
示例#13
0
    def updateDiffImage(self, index):
        element = self.ViewControl.combo1.currentIndex()
        x_index = int(self.data.shape[3] * 0.3)
        y_index = int(self.data.shape[2]* 0.3)

        position = [0.0, 0.25, 0.4, 0.6, 0.75, 1.0]
        colors = [[64, 0, 0, 255], [255, 0, 0, 255], [255, 255, 255, 255], [255, 255, 255, 255], [0, 0, 255, 255], [0, 0, 64, 255]]
        bi_polar_color_map = pyqtgraph.ColorMap(position, colors)
        lookup_table = bi_polar_color_map.getLookupTable(0.0, 1.0, 256)
        if index < self.data.shape[1]-1:
            img = self.data[element, index] - self.data[element, index+1]
            img = img[y_index:-y_index, x_index:-x_index]
        else:
            img = self.data[element, index] - self.data[element, 0]
            img = img[x_index:-x_index, y_index:-y_index]
        self.diffView.projView.setImage(img, border='w')
        self.diffView.projView.setLookupTable(lookup_table)
示例#14
0
文件: Plot.py 项目: ligerliu/pyH5_GUI
 def get_colormap( self, mainWin ):
     #print( self.colormap_string )
     if self.mainWin.colormap_string == 'default':
         pos = np.array([0., 1., 0.5, 0.25, 0.75])
         color = np.array([[0, 0, 255, 255], [255, 0, 0, 255], [0, 255, 0, 255], (0, 255, 255, 255), (255, 255, 0, 255)],
              dtype=np.ubyte)
         cmap = pg.ColorMap(pos, color)
         self.mainWin.colormap = cmap
     elif self.mainWin.colormap_string in [ "jet", 'jet_extended', 'albula', 'albula_r',
                                   'goldish', "viridis", 'spectrum', 'vge', 'vge_hdr',]:
          self.mainWin.colormap =  color_map_dict[self.mainWin.colormap_string]
          cmap = self.generatePgColormap(  self.mainWin.colormap   )
          print('the color string is: %s.'%self.mainWin.colormap_string)
     else:
         pass
     self.mainWin.cmap = cmap
     return cmap
示例#15
0
    def __init__(self, master=None):
        QtWidgets.QMainWindow.__init__(self, master)
        self.ui = Ui_ZmwAnalysisWidget()
        self.ui.setupUi(self)
        self.filter_dialog = FilterPopup()
        self.analysis_dialog = AnalysisPopup()

        # self.plotlist = [[],[],[],[],[]]
        self.seqplotlist = [[]]
        self.firingplotlist = []

        self.ui.actionLoad.triggered.connect(self.getfile)
        self.ui.actionZ_Project.triggered.connect(self.z_project)
        self.ui.actionView_Stack.triggered.connect(self.view_stack)
        self.ui.actionClear_Settings.triggered.connect(self.clear_settings)
        self.ui.actionFilter.triggered.connect(self.show_filter_dialog)
        self.ui.actionCrop.triggered.connect(self.crop)
        self.ui.actionBase_Call.triggered.connect(self.show_analysis_dialog)
        self.ui.actionCheck_Controls.triggered.connect(self.check_controls)
        self.filter_dialog.acceptsignal.connect(self.filter_stack)
        self.analysis_dialog.acceptsignal.connect(self.analyze)

        self.image_plot = self.ui.imagePlot
        self.image_plot.roi.scaleSnap = self.image_plot.roi.translateSnap = True
        self.image_plot.roi.setSize([6, 17])
        colors = [(0, 0, 0), (45, 5, 61), (84, 42, 55), (150, 87, 60),
                  (208, 171, 141), (255, 255, 255)]
        cmap = pg.ColorMap(pos=np.linspace(0.0, 1.0, 6), color=colors)
        self.image_plot.setColorMap(cmap)
        self.direc = ''
        # self.roi_image_plot = self.roip2 = []
        self.filtertype = None
        self.xyz_filter = ()
        self.blueThresh = None
        self.redThresh = None
        self.bluePeakThresh = None
        self.redPeakThresh = None

        self.data_file_name = None
        self.background = None
        self.stack = None
        self.original_stack = None
        self.zpro = None

        self.image_plot.roi.scaleSnap = self.image_plot.roi.translateSnap = True
        self.image_plot.roi.removeHandle(1)  # Remove the rotation handle
示例#16
0
文件: graph.py 项目: imagect/imagect
    def __init__(self):
        pg.ImageView.__init__(self)
        self.resize(800, 800)
        ## Display the data and assign each frame a time value from 1.0 to 3.0
        data = createData()
        self.setImage(data, xvals=np.linspace(1., 3., data.shape[0]))

        ## Set a custom color map
        colors = [(0, 0, 0), (45, 5, 61), (84, 42, 55), (150, 87, 60),
                  (208, 171, 141), (255, 255, 255)]
        cmap = pg.ColorMap(pos=np.linspace(0.0, 1.0, 6), color=colors)
        self.setColorMap(cmap)

        def handle():
            self.show()

        self.cb = handle
示例#17
0
	def __init__(self, handle):
		self.S = 8192
		# self.x = np.loadtxt('config/x.txt')
		
		self.TERM = binascii.unhexlify('FFFFFFFF')
		self.SP_RON = binascii.unhexlify('F5000000')
		self.RWT = binascii.unhexlify('F9000000')
		self.ECHO = binascii.unhexlify('FF00AF00')
		
		self.weights = np.zeros(self.S, dtype=int)
		self.post = 10 # number of postsynaptic neurons
		self.post_list = [450, 460, 470, 480, 490, 500, 510, 520, 530, 540]
		self.im_width = 20
		self.n_tot = self.im_width**2
		
		# Plotting color scheme definition
		self.pos = np.array([0.0, 0.5, 1.0])
		self.color = np.array([[29,82,135,255], [53,193,133,255], [208,246,106,255]])
		self.color_map = pg.ColorMap(self.pos, self.color, mode=None)

		self.app = pg.mkQApp()
		# self.proc = mp.QtProcess()
		# self.rpg = self.proc._import('pyqtgraph')

		self.win = QtGui.QMainWindow()
		self.win.resize(1600,400)
		self.cw = QtGui.QWidget() # central widget
		self.win.setCentralWidget(self.cw)
		self.l = QtGui.QGridLayout() # layout
		self.cw.setLayout(self.l)

		self.subplots = []
		for i in range(self.post):
			# self.subplots.append(pg.image(np.zeros((self.im_width, self.im_width))))
			self.subplots.append(pg.ImageView())
			# self.subplots[i].view.setAspectLocked(False)
			self.subplots[i].setColorMap(self.color_map)
			self.subplots[i].resize(340,170)
			self.subplots[i].ui.roiBtn.hide()
			self.subplots[i].ui.menuBtn.hide()

			self.l.addWidget(self.subplots[i], int(i/5), i-int(i/5)*5)

		self.win.show()

		self.handle = handle
示例#18
0
    def __init__(self, parent=None):

        super(TofGPlots2, self).__init__()

        self.pos, self.colors = zip(*cmapToColormap(matplotlib.cm.jet))
        # Set the colormap
        self.clrmp = pg.ColorMap(self.pos, self.colors)

        self.TofGPlotsUi = Tof2GatedPlots.Ui_Tof2GatedPlots()
        self.TofGPlotsUi.setupUi(self)

        self.XYItem = pg.PlotItem(title='XY',
                                  labels={
                                      'bottom': ('X', 'mm'),
                                      'left': ('Y', 'mm')
                                  })
        self.XYItem.setAspectLocked(False)
        self.XYPlot = pg.ImageView(name='XY', view=self.XYItem)
        self.XYPlot.setColorMap(self.clrmp)
        self.XYPlot.view.invertY(False)
        self.TofGPlotsUi.XY.insertWidget(0, self.XYPlot)

        self.eARItem = pg.PlotItem(title='eAR',
                                   labels={
                                       'bottom': ('Angle', 'rad'),
                                       'left': ('Radius', 'pixel')
                                   })
        self.eARItem.setAspectLocked(False)
        self.eARPlot = pg.ImageView(name='eAR', view=self.eARItem)
        self.eARPlot.setColorMap(self.clrmp)
        self.eARPlot.view.invertY(False)
        self.TofGPlotsUi.PiPiCo.insertWidget(0, self.eARPlot)
        self.eARItem.setAspectLocked(False)

        self.eXYItem = pg.PlotItem(title='eXY',
                                   labels={
                                       'bottom': ('X', 'mm'),
                                       'left': ('Y', 'mm')
                                   })
        self.eXYItem.setAspectLocked(False)
        self.eXYPlot = pg.ImageView(name='eXY', view=self.eXYItem)
        self.eXYPlot.setColorMap(self.clrmp)
        self.eXYPlot.view.invertY(False)
        self.TofGPlotsUi.eXY.insertWidget(0, self.eXYPlot)

        self.show()
示例#19
0
    def __init__(self, rec, *args, **kwargs):
        """
        Reimplemented from LiveGraph.

        Parameters
        ----------
        rec: Recorder
            The reference of the Recorder
        The rest are passed into LiveGraph
        """
        self.peak_plots = []
        self.peak_trace = []
        self.trace_counter = []
        self.trace_countlimit = 30
        self.level_colourmap = None

        super().__init__(*args, **kwargs)
        self.plotItem.setTitle(title="Channel Levels", color='FFFFFF')
        self.plotItem.setLabel('bottom', 'Amplitude')
        self.plotItem.hideAxis('left')

        self.chanlvl_pts = self.plotItem.plot()
        self.chanlvl_bars = pg.ErrorBarItem(x=np.arange(rec.channels),
                                            y=np.arange(rec.channels) * 0.1,
                                            beam=CHANLVL_FACTOR / 2,
                                            pen=pg.mkPen(width=3))

        self.plotItem.addItem(self.chanlvl_bars)

        baseline = pg.InfiniteLine(pos=0.0, movable=False)
        self.plotItem.addItem(baseline)

        self.threshold_line = pg.InfiniteLine(pos=0.0,
                                              movable=True,
                                              bounds=[0, 1])
        self.threshold_line.sigPositionChanged.connect(self.change_threshold)
        self.plotItem.addItem(self.threshold_line)

        self.reset_channel_peaks(rec)

        val = [0.0, 0.5, 0.8]
        colour = np.array(
            [[0, 255, 0, 255], [0, 255, 0, 255], [255, 0, 0, 255]],
            dtype=np.ubyte)
        self.level_colourmap = pg.ColorMap(val, colour)
示例#20
0
    def setSpectra(self, msexperiment):
        msexperiment.updateRanges()

        # resolution: mz_res Da in m/z, rt_res seconds in RT dimension
        mz_res = 1.0
        rt_res = 1.0

        # size of image
        cols = 1.0 / mz_res * msexperiment.getMaxMZ()
        rows = 1.0 / rt_res * msexperiment.getMaxRT()

        # create regular spaced data to turn spectra into an image
        max_intensity = msexperiment.getMaxInt()
        bilip = pyopenms.BilinearInterpolation()
        tmp = bilip.getData()
        tmp.resize(int(rows), int(cols), float())
        bilip.setData(tmp)

        bilip.setMapping_0(0.0, 0.0, rows - 1, msexperiment.getMaxRT())
        bilip.setMapping_1(0.0, 0.0, cols - 1, msexperiment.getMaxMZ())

        img = pg.ImageItem(autoDownsample=True)
        self.addItem(img)

        for spec in msexperiment:
            if spec.getMSLevel() == 1:
                mzs, ints = spec.get_peaks()
                rt = spec.getRT()
                for i in range(0, len(mzs)):
                    bilip.addValue(rt, mzs[i], ints[i])  # slow

        data = np.ndarray(shape=(int(cols), int(rows)), dtype=np.float64)
        grid_data = bilip.getData()
        for i in range(int(rows)):
            for j in range(int(cols)):
                data[j][i] = grid_data.getValue(i, j)  # slow

        ## Set a custom color map
        pos = np.array([0., 0.01, 0.05, 0.1, 1.])
        color = np.array([(255, 255, 255, 0), (255, 255, 0, 255),
                          (255, 0, 0, 255), (0, 0, 255, 255), (0, 0, 0, 255)],
                         dtype=np.ubyte)
        cmap = pg.ColorMap(pos, color)
        img.setLookupTable(cmap.getLookupTable(0.0, 1.0, 256))
        img.setImage(data)
示例#21
0
    def set_colormap(self, cmap):
        """
        Setup colormap.

        Can be name of one built-in colormaps (``"gray"``, ``"gray_sat"``, ``"gray_doublesat"``, ``"hot"``, ``"hot_sat"``),
        one of PyQtGraph built-in cmaps (e.g., ``"flame"`` or ``"bipolar"``),
        a list specifying PyQtGraph colormap or a :class:`pyqtgraph.ColorMap` instance.
        """
        if cmap in pyqtgraph.graphicsItems.GradientEditorItem.Gradients:
            self.image_window.setPredefinedGradient(cmap)
        else:
            cmap = builtin_cmaps.get(cmap, cmap)
            if isinstance(cmap, tuple):
                if any([isinstance(v, float) for c in cmap[1] for v in c]):
                    cols = [tuple([int(v * 255) for v in c]) for c in cmap[1]]
                    cmap = cmap[0], cols
                cmap = pyqtgraph.ColorMap(*cmap)
            self.image_window.setColorMap(cmap)
    def set_result(self, model, result, pre_state, post_state):
        self.model = model
        self.result = result
        self.pre_state = pre_state
        self.post_state = post_state

        # color events by likelihood
        cmap = pg.ColorMap([0, 1.0], [(0, 0, 0), (255, 0, 0)])
        threshold = 10
        err_colors = cmap.map((threshold - result['likelihood']) / threshold)
        brushes = [pg.mkBrush(c) for c in err_colors]

        # log spike intervals to make visualization a little easier
        compressed_spike_times = np.empty(len(result['spike_time']))
        compressed_spike_times[0] = 0.0
        np.cumsum(np.diff(result['spike_time'])**0.25, out=compressed_spike_times[1:])

        self.plt1.clear()
        self.plt1.plot(compressed_spike_times, result['likelihood'], pen=None, symbol='o', symbolBrush=brushes)
        
        self.plt2.clear()
        self.plt2.plot(compressed_spike_times, result['expected_amplitude'], pen=None, symbol='x', symbolPen=0.5, symbolBrush=brushes)
        amp_sp = self.plt2.plot(compressed_spike_times, result['amplitude'], pen=None, symbol='o', symbolBrush=brushes)
        amp_sp.scatter.sigClicked.connect(self.amp_sp_clicked)
        
        self.plt3.clear()
        self.plt3.plot(compressed_spike_times, pre_state['available_vesicle'], pen=None, symbol='t', symbolBrush=brushes)
        self.plt3.plot(compressed_spike_times, post_state['available_vesicle'], pen=None, symbol='o', symbolBrush=brushes)

        self.plt4.clear()
        
        # plot full distribution of event amplitudes
        bins = np.linspace(self.amp_sample_values[0], self.amp_sample_values[-1], 40)
        amp_hist = np.histogram(self.result['amplitude'], bins=bins)
        self.plt4.plot(amp_hist[1], amp_hist[0] * len(amp_hist[0]) / amp_hist[0].sum(), stepMode=True, fillLevel=0, brush=0.3)

        # plot average model event distribution
        amps = self.amp_sample_values
        total_dist = np.zeros(len(amps))
        for i in range(self.result.shape[0]):
            state = self.pre_state[i]
            total_dist += self.model.likelihood(amps, state)
        total_dist *= len(total_dist) / total_dist.sum()
        self.plt4.plot(amps, total_dist, fillLevel=0, brush=(255, 0, 0, 50))
示例#23
0
    def run(self):
        self.win.setWindowTitle('Microphone data')
        # Sound wave plot
        plot = self.win.addPlot()
        plot.setLabel('bottom', 'Time', 's')
        plot.setLabel('left', 'Amplitude', '')
        plot.showGrid(x=True, y=True)
        self.curve = plot.plot(x=self.xdata, y=self.ydata, pen=(255, 0, 0))

        # Next row
        self.win.nextRow()

        # Spectrogram plot
        self.specImg = pg.ImageItem()
        specPlot = self.win.addPlot()
        specPlot.addItem(self.specImg)
        self.imgArray = np.zeros((1000, self.sampToSpec / 2 + 1))

        # Bipolar colormap
        pos = np.array([0., 1., 0.5, 0.25, 0.75])
        color = np.array(
            [[0, 255, 255, 255], [255, 255, 0, 255], [0, 0, 0, 255],
             (0, 0, 255, 255), (255, 0, 0, 255)],
            dtype=np.ubyte)
        cmap = pg.ColorMap(pos, color)
        lut = cmap.getLookupTable(0.0, 1.0, 256)

        # Set colormap
        self.specImg.setLookupTable(lut)
        self.specImg.setLevels([-50, 40])

        # Setup the correct scaling for y-axis
        freq = np.arange((self.sampToSpec / 2) + 1) / (float(self.sampToSpec) /
                                                       self.SAMPLING_FREQ)
        yscale = 1.0 / (self.imgArray.shape[1] / freq[-1])
        self.specImg.scale((1. / self.SAMPLING_FREQ) * self.sampToSpec, yscale)

        specPlot.setLabel('left', 'Frequency', units='Hz')
        self.wind = np.hanning(self.sampToSpec)
        self.timer.timeout.connect(self.update)

        # Timer init
        self.timer.start(1. / self.graphUpdateFreq * 1000)
        self.app.exec_()
示例#24
0
    def setARAcolors(self):
        #Make up a disjointed colormap
        pos = np.array([0.0, 0.001, 0.25, 0.35, 0.45, 0.65, 0.9])
        color = np.array([[0, 0, 0, 255], [255, 0, 0, 255], [0, 2, 230, 255],
                          [7, 255, 112, 255], [255, 240, 7, 255],
                          [7, 153, 255, 255], [255, 7, 235, 255]],
                         dtype=np.ubyte)
        map = pg.ColorMap(pos, color)
        lut = map.getLookupTable(0.0, 1.0, 256)

        #Assign the colormap to the imagestack object
        self.ARAlayerName = self.lasagna.imageStackLayers_Model.index(
            0, 0).data().toString()  #TODO: a bit horrible
        firstLayer = self.lasagna.returnIngredientByName(self.ARAlayerName)
        firstLayer.lut = lut
        #Specify what colors the histogram should be so it doesn't end up megenta and
        #vomit-yellow, or who knows what, due to the weird color map we use here.
        firstLayer.histPenCustomColor = [180, 180, 180, 255]
        firstLayer.histBrushCustomColor = [150, 150, 150, 150]
示例#25
0
def display_connectivity(pre_class, post_class, result, show_confidence=True):
    # Print results
    print("{pre_class:>20s} -> {post_class:20s} {connections_found:>5s} / {connections_probed}".format(
        pre_class=pre_class.name, 
        post_class=post_class.name, 
        connections_found=str(len(result['connected_pairs'])),
        connections_probed=len(result['probed_pairs']),
    ))

    # Pretty matrix results
    colormap = pg.ColorMap(
        [0, 0.01, 0.03, 0.1, 0.3, 1.0],
        [(0,0,100), (80,0,80), (140,0,0), (255,100,0), (255,255,100), (255,255,255)],
    )

    connectivity, lower_ci, upper_ci = result['connection_probability']

    if show_confidence:
        output = {'bordercolor': 0.6}
        default_bgcolor = np.array([128., 128., 128.])
    else:
        output = {'bordercolor': 0.8}
        default_bgcolor = np.array([220., 220., 220.])
    
    if np.isnan(connectivity):
        output['bgcolor'] = tuple(default_bgcolor)
        output['fgcolor'] = 0.6
        output['text'] = ''
    else:
        # get color based on connectivity
        color = colormap.map(connectivity)
        
        # desaturate low confidence cells
        if show_confidence:
            confidence = (1.0 - (upper_ci - lower_ci)) ** 2
            color = color * confidence + default_bgcolor * (1.0 - confidence)
        
        # invert text color for dark background
        output['fgcolor'] = 'w' if sum(color[:3]) < 384 else 'k'
        output['text'] = "%d/%d" % (result['n_connected'], result['n_probed'])
        output['bgcolor'] = tuple(color)

    return output
示例#26
0
    def __init__(self):
        super(PyQtImageWidget, self).__init__()

        self.img = pg.ImageItem()
        self.addItem(self.img)

        #self.img_array = np.zeros((1000, CHUNKSZ/2+1))

        # bipolar colormap
        pos = np.array([0., 1., 0.5, 0.25, 0.75])
        color = np.array(
            [[0, 255, 255, 255], [255, 255, 0, 255], [0, 0, 0, 255],
             (0, 0, 255, 255), (255, 0, 0, 255)],
            dtype=np.ubyte)
        cmap = pg.ColorMap(pos, color)
        lut = cmap.getLookupTable(0.0, 1.0, 256)

        self.img.setLookupTable(lut)
        self.img.setLevels([-50, 40])
示例#27
0
    def __init__(self):
        super(CamView, self).__init__()

        layout = qw.QGridLayout()  # create a grid for subWidgets
        layout.setSpacing(10)
        self.setLayout(layout)

        self.camWindow = pg.ImageView()
        layout.addWidget(self.camWindow, 0, 2, 3, 4)
        self.camWindow.setImage(self.gauss_img)
        colors = [(0, 0, 0), (255, 255, 255)]
        cmap = pg.ColorMap(pos=np.linspace(0.0, 1.0, 2), color=colors)
        self.camWindow.setColorMap(cmap)

        self.start_btn = qw.QPushButton('Start Video')
        layout.addWidget(self.start_btn, 0, 0)
        self.start_btn.setCheckable(True)
        self.start_btn.clicked.connect(self.start_acquisition)

        self.gauss_btn = qw.QPushButton('Show Gaussian')
        layout.addWidget(self.gauss_btn, 2, 0)
        # self.gauss_btn.setCheckable(True)
        self.gauss_btn.clicked.connect(self.show_gaussian)

        # self.avg_input = qw.QTextEdit()
        # layout.addWidget(self.avg_input, 1, 0,1,1)
        self.devices = {}
        self.get_devicelist()

        self.fps_display = qw.QLabel('0')
        layout.addWidget(self.fps_display, 1, 1)

        self.fps = 0

        self.timer = qc.QTimer()
        self.timer.setInterval(1)
        self.timer.timeout.connect(self.on_timer)
        self.timer.start()

        self.cam = cv2.VideoCapture(self.CAMERA)

        self.show()
示例#28
0
    def plotblack(self):
        self.img = pg.ImageItem()
        self.addItem(self.img)

        self.img_array = np.zeros((1000, CHUNKSZ//2+1))
        #print ('self.img_array' ,self.img_array)
        #print len(self.img_array)

        # bipolar colormap
        pos = np.array([0., 1., 0.5, 0.25, 0.75])
        color = np.array([[0,255,255,255], [255,255,0,255], [0,0,0,255], (0, 0, 255, 255), (255, 0, 0, 255)], dtype=np.ubyte)
        cmap = pg.ColorMap(pos, color)
        lut = cmap.getLookupTable(0.0, 1.0, 256)

        # set colormap
        self.img.setLookupTable(lut)
        self.img.setLevels([-50,40])

        # setup the correct scaling for y-axis
        freq = np.arange((CHUNKSZ/2)+1)/(float(CHUNKSZ)/FS)
        yscale = 1.0/(self.img_array.shape[1]/freq[-1])
        self.img.scale((1./FS)*CHUNKSZ, yscale)

        self.setLabel('left', 'Frequency', units='Hz')
        #print ('frequency', freq)
        #print len(freq)
        #print ('yscale', yscale)
        #print len(yscale)
        #print ('self.img.scale',self.img.scale)
        #print len(self.img.scale)

        # prepare window for later use
        self.win = np.hanning(CHUNKSZ)
        #print (self.win.shape)
        #print ('self.win', self.win)
        #print len(self.win )
        self.show()
        timer = QtCore.QTimer()
        timer.timeout.connect(self.update)
        timer.start(100)
        # keep reference to timer        
        self.timer = timer
示例#29
0
    def __init__(self, series, Fs, s_chunklen, parent=None):
        # s_chunklen in seconds
        self.name = series.name
        self.parent = parent
        self.origidx = series.index.values

        self.fs = Fs
        self.data = series.values
        self.chunksize = int(s_chunklen * Fs)
        self.win = np.hanning(self.chunksize)

        axisItem = SpectroTimeAxisItem(
            initvalue=self.origidx[0],
            samplerate=self.fs,
            chunksize=self.chunksize,
            orientation='bottom',
        )
        axisItems = {'bottom': axisItem}
        super().__init__(parent=self.parent, axisItems=axisItems)

        self.img = pg.ImageItem()
        self.addItem(self.img)
        self.setLabel('left', 'Frequency', units='Hz')

        # bipolar colormap
        pos = np.array([0.0, 0.25, 0.5, 0.75, 1.0])
        color = np.array(
            [
                [0, 0, 0, 255],
                [0, 0, 255, 255],
                [0, 255, 255, 255],
                [255, 255, 0, 255],
                [255, 0, 0, 255],
            ],
            dtype=np.ubyte,
        )
        cmap = pg.ColorMap(pos, color)
        lut = cmap.getLookupTable(0.0, 1.0, 256)
        self.img.setLookupTable(lut)

        self.calculate_psd()
        self.render()
    def update_display(self):
        ModelResultView.update_display(self)
        result = self._parent.result
        spikes = result['result']['spike_time']
        amps = result['result']['amplitude']

        cmap = pg.ColorMap(
            np.linspace(0, 1, 4),
            np.array([[255, 255, 255], [255, 255, 0], [255, 0, 0], [0, 0, 0]],
                     dtype='ubyte'))
        cvals = [((np.log(dt) / np.log(10)) + 2) / 4.
                 for dt in np.diff(spikes)]
        brushes = [pg.mkBrush(cmap.map(c)) for c in cvals]

        self.plot.clear()
        self.plot.plot(amps[:-1],
                       amps[1:],
                       pen=None,
                       symbol='o',
                       symbolBrush=brushes)