def getpgcmap(cmp='BuRd'): import pyqtgraph as pg import numpy as np if cmp =='bryw': STEPS = np.array([0.0, 0.2, 0.6, 1.0]) CLRS = ['k', 'r', 'y', 'w'] ## Create a ColorMap clrmp = pg.ColorMap(STEPS, np.array([pg.colorTuple(pg.Color(c)) for c in CLRS])) ## Get the LookupTable lut = clrmp.getLookupTable() elif cmp == 'TrmBlk': pos = np.array([0.0, 0.5, 1.0]) color = np.array([[0,0,0,255], [255,128,0,255], [255,255,0,255]], dtype=np.ubyte) map = pg.ColorMap(pos, color) lut = map.getLookupTable(0.0, 1.0, 256) elif cmp == 'RdBu': pos = np.array([0.0,0.5,1.0]) color = np.array([[255,0,0,0],[255,255,255,255],[0,0,255,0]],dtype=np.ubyte) map = pg.ColorMap(pos,color) lut = map.getLookupTable(0.0,1.0,256) elif cmp == 'BuRd': pos = np.array([0.0,0.5,1.0]) color = np.array([[0,0,255,0],[255,255,255,255],[255,0,0,0]],dtype=np.ubyte) map = pg.ColorMap(pos,color) lut = map.getLookupTable(0.0,1.0,256) return lut
def __init__(self, parent=None): pyqtgraph.setConfigOption('background', 'k') #before loading widget super(HyperSpecApp, self).__init__(parent) self.setupUi(self) self.updateBtn.clicked.connect(self.update) #self.view = pyqtgraph.ViewBox(self.gView0) #self.scene = pyqtgraph.ImageItem(self.view) STEPS = np.array([0.0, 0.2, 0.6, 1.0]) CLRS = ['k', 'r', 'y', 'w'] clrmp = pyqtgraph.ColorMap( STEPS, np.array([pyqtgraph.colorTuple(pyqtgraph.Color(c)) for c in CLRS])) data = np.random.normal(size=(100, 200, 200)) #imv = pyqtgraph.image(data) self.ImageView2.setImage(data) #self.ImageView2.ui.histogram.gradient.setColorMap(clrmp) #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 = pyqtgraph.ColorMap(pos, color) #lut = cmap.getLookupTable(0.0, 1.0, 256) #self.img.setLookupTable(lut) self.pltView1.plotItem.showGrid(True, True, 0.7) self.pltView2.plotItem.showGrid(True, True, 0.7)
def update(self): start = time.time() if not self.paused and not self.doingPlot and hasattr( self, 'data') and len(self.data) > 1: self.doingPlot = True data = list(self.data) if len(data) > self.decimateScale: del data[:len(data) - self.decimateScale] x, y = zip(*data) y2, x2 = np.histogram(y, bins=self.numberBins) if self.parent.subtractMeans: x2 = x2 - np.mean(x2) if self.parent.normalise: mean = np.mean(x2) x2 = x2 - mean x2 = x2 / np.std(x2) x2 = x2 + mean r, g, b, a = pg.colorTuple(pg.mkColor(self.recordspen)) self.pencolor = pg.mkColor(r, g, b, 255) self.brushcolor = pg.mkColor(r, g, b, 64) self.plot.setData({ 'x': x2, 'y': y2 }, pen=self.pencolor, stepMode=True, fillLevel=0, fillBrush=self.brushcolor) self.doingPlot = False
def setColor(self, color): if color != self._color: self._color = color self.colorChanged.emit() # handles different color formats try: r,g,b,a = pg.colorTuple(self._color) except: r,g,b,a = pg.colorTuple(pg.mkColor(self._color)) if self._color: self.setStyleSheet('background-color: rgba(%d,%d,%d,%d);' %(r,g,b,a)) self._color = pg.mkColor(self._color) else: self.setStyleSheet("")
def matrix(self, rows, cols, size=50, header_color='w', no_data_color='k'): w = pg.GraphicsLayoutWidget() v = w.addViewBox() v.setAspectLocked() v.invertY() 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)], ) default = no_data_color summary = self.connectivity_summary(cre_type=None) shape = (len(rows), len(cols)) text = np.empty(shape, dtype=object) fgcolor = np.empty(shape, dtype=object) bgcolor = np.empty(shape, dtype=object) for i, row in enumerate(rows): for j, col in enumerate(cols): if (row, col) in summary: conn = summary[(row, col)]['connected'] uconn = summary[(row, col)]['unconnected'] color = colormap.map(conn / (conn + uconn)) else: conn, uconn = 0, 0 color = default color = pg.colorTuple(pg.mkColor(color)) bgcolor[i, j] = color text[i, j] = "%d/%d" % (conn, conn + uconn) fgcolor[i, j] = 'w' if sum(color[:3]) < 200 else 'k' if conn == uconn == 0: fgcolor[i, j] = 0.3 w.matrix = MatrixItem(text=text, fgcolor=fgcolor, bgcolor=bgcolor, rows=rows.values(), cols=cols.values(), size=size, header_color=header_color) v.addItem(w.matrix) # colormap is logarithmic; remap to linear for legend colors = colormap.color x = np.linspace(0, 1, len(colors)) cmap2 = pg.ColorMap(x, colors) legend = pg.GradientLegend([25, 300], [-20, -30]) legend.setGradient(cmap2.getGradient()) legend.setLabels( {'%d' % int(a * 100): b for a, b in zip(colormap.pos, x)}) v.addItem(legend) w.show() self.matrix_widget = w return w
def export(self, fileName=None): if isinstance(self.item, pg.PlotItem): mpw = MatplotlibWindow() MatplotlibExporter.windows.append(mpw) fig = mpw.getFigure() ax = fig.add_subplot(111) ax.clear() #ax.grid(True) for item in self.item.curves: x, y = item.getData() opts = item.opts pen = pg.mkPen(opts['pen']) if pen.style() == QtCore.Qt.NoPen: linestyle = '' else: linestyle = '-' color = tuple([c/255. for c in pg.colorTuple(pen.color())]) symbol = opts['symbol'] if symbol == 't': symbol = '^' symbolPen = pg.mkPen(opts['symbolPen']) symbolBrush = pg.mkBrush(opts['symbolBrush']) markeredgecolor = tuple([c/255. for c in pg.colorTuple(symbolPen.color())]) markerfacecolor = tuple([c/255. for c in pg.colorTuple(symbolBrush.color())]) if opts['fillLevel'] is not None and opts['fillBrush'] is not None: fillBrush = pg.mkBrush(opts['fillBrush']) fillcolor = tuple([c/255. for c in pg.colorTuple(fillBrush.color())]) ax.fill_between(x=x, y1=y, y2=opts['fillLevel'], facecolor=fillcolor) ax.plot(x, y, marker=symbol, color=color, linewidth=pen.width(), linestyle=linestyle, markeredgecolor=markeredgecolor, markerfacecolor=markerfacecolor) xr, yr = self.item.viewRange() ax.set_xbound(*xr) ax.set_ybound(*yr) mpw.draw() else: raise Exception("Matplotlib export currently only works with plot items")
def __init__(self, elems, path, sdisp, color, spec_size, max_nspec, max_density, auto_adjust, *args, **kwargs): *_loc, elem = path self.id = elem.name self.display = sdisp self.smesh = elems.mesh._getStepsObjects()[0] if len(path) != 3: raise Exception( f'Invalid path for plotting elements in tetrahedrons: {path}') self.bound_min = elems.mesh.bbox.min * self.display.scale self.bound_max = elems.mesh.bbox.max * self.display.scale if color is None: self.col = pg.colorTuple( pg.intColor( _GenericScatterElem.COLOR_IND, hues=_GenericScatterElem.COLOR_NB, alpha=_GenericScatterElem.DEFAULT_ALPHA * 255, )) _GenericScatterElem.COLOR_IND += 1 elif hasattr(color, '__call__'): self.col = color(elem) else: self.col = color self.spec_size = spec_size self.max_nspec = max_nspec self.max_density = max_density self.auto_adjust = auto_adjust self.elems = np.array([tet.idx for tet in elems], dtype=INDEX_DTYPE) self.rspath = self._getResSelect(path) data = self._getData() pg.opengl.GLScatterPlotItem.__init__(self, pos=data, color=self.col, size=self.spec_size, pxMode=False) self.display.addItem(self)
def update_display(self): if self.data is None: self.image.setImage(np.zeros((1, 1))) return axes = self.selected_axes self.plot.setLabels(left=axes[1], bottom=axes[0]) data, colors = self.get_data() levels = self.levels or self.data_bounds if colors is None: self.image.setImage(data, levels=levels) else: comp = np.zeros(data.shape[:-1] + (3,), dtype=data.dtype) for i,color in enumerate(colors): color = np.array(pg.colorTuple(color)[:3], dtype=float).reshape(1, 1, 3) / 255. comp += data[..., i:i+1] * color self.image.setImage(comp, levels=levels) xvals = self.data_axes[axes[0]].values yvals = self.data_axes[axes[1]].values self.plot.getAxis('bottom').setTicks([[(i, "%0.2g"%xvals[i]) for i in range(len(xvals))]]) self.plot.getAxis('left').setTicks([[(i, "%0.2g"%yvals[i]) for i in range(len(yvals))]])
def __init__(self, parent=None): pyqtgraph.setConfigOption('background', 'k') #before loading widget super(HyperSpecApp, self).__init__(parent) self.setupUi(self) self.updateBtn.clicked.connect(self.update) #self.view = pyqtgraph.ViewBox(self.gView0) #self.scene = pyqtgraph.ImageItem(self.view) STEPS = np.array([0.0, 0.2, 0.6, 1.0]) CLRS = ['k','r','y','w'] clrmp = pyqtgraph.ColorMap(STEPS, np.array([pyqtgraph.colorTuple(pyqtgraph.Color(c)) for c in CLRS])) data = np.random.normal(size=(100, 200, 200)) #imv = pyqtgraph.image(data) self.ImageView2.setImage(data) #self.ImageView2.ui.histogram.gradient.setColorMap(clrmp) #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 = pyqtgraph.ColorMap(pos, color) #lut = cmap.getLookupTable(0.0, 1.0, 256) #self.img.setLookupTable(lut) self.pltView1.plotItem.showGrid(True, True, 0.7) self.pltView2.plotItem.showGrid(True, True, 0.7)
def intColor(self, index=0, range=9, palette=None): #--- Sanity-check arguments if isinstance(index, QColor): print "BUG WARNING: ColorPalette.intColor() called with a QColor as index (ignored)" print index return index if isinstance(index, (int, long)) != True: print "BUG WARNING: ColorPalette.intColor() called with index of wrong type (ignored)" print index index = 0 # print "MARC: ColorPalette.intColor(index=%d, range=%d)" % (index, range) #--- Map index into range if range > 0: index = index % range #--- dual-tone palette if palette == 'mono': r, g, b = [25, 25, 25] # dark gray return QColor(r, g, b, 255) if palette == 'dual': r, g, b = self.ColorPalette2[index % 2] return QColor(r, g, b, 255) if palette == 'accessible': index = index % len(self.ColorPalette2) r, g, b = self.ColorPalette2[index] return QColor(r, g, b, 255) #--- Few colors requested: Use the hardcoded palette if (palette != 'rainbow') and (range <= self.recommendedSize): r, g, b = self.ColorPalette2[index] return QColor(r, g, b, 255) #--- Many colors requested: Generate a rainbow palette # # The "pyqtgraph.intColor" function works in HSV space, and has two issues: # # 1) Some colors are difficult to see against the white background. # 2) Some colors are very similar to each other. # # Avoid issue #1: We calculate contrast and darken the worst offenders. # Avoid issue #2: FIXME color = pg.intColor(index, range) #--- Calculate relative luminance according to rec.709 (SRGB) # # Discussion: http://ux.stackexchange.com/questions/82056 r, g, b, a = pg.colorTuple(color) rg = (float(r) / 3294) if (r <= 10) else (((float(r) / 269) + 0.0513)**2.4) gg = (float(g) / 3294) if (g <= 10) else (((float(g) / 269) + 0.0513)**2.4) bg = (float(b) / 3294) if (b <= 10) else (((float(b) / 269) + 0.0513)**2.4) L_color = (0.2126 * rg) + (0.7152 * gg) + (0.0722 * bg) L_white = 1.0 contrast_actual = (L_white + 0.05) / (L_color + 0.05) #--- Darken the color if contrast is too low (against white background) # # The threshold value is arbitrary. Usability experts recommend a # contrast ratio of 7, but that would render the thin traces too dark. contrast_desired = 1.368 if contrast_actual < contrast_desired: #--- Adjust (linear) adjust = contrast_actual / contrast_desired rg = rg * (0.2126 * adjust) gg = gg * (0.7152 * adjust) bg = bg * (0.0722 * adjust) #--- Convert to 8-bit SRGB r = ((rg**(1 / 2.4)) - 0.0513) * 269 if rg > 0.0031 else rg * 3294 g = ((gg**(1 / 2.4)) - 0.0513) * 269 if gg > 0.0031 else gg * 3294 b = ((bg**(1 / 2.4)) - 0.0513) * 269 if bg > 0.0031 else bg * 3294 r = int(r + 0.5) g = int(g + 0.5) b = int(b + 0.5) r = r if r > 0 else 0 g = g if g > 0 else 0 b = b if b > 0 else 0 r = r if r < 255 else 255 g = g if g < 255 else 255 b = b if b < 255 else 255 #--- Convert to native color = QColor(r, g, b, a) return color
def matrix(self, rows, cols, size=50, header_color='k', no_data_color=0.9, mode='connectivity'): w = pg.GraphicsLayoutWidget() w.setRenderHints(w.renderHints() | pg.QtGui.QPainter.Antialiasing) v = w.addViewBox() v.setBackgroundColor('w') v.setAspectLocked() v.invertY() if mode == 'connectivity': 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)], ) else: colormap = pg.ColorMap( [0, 0.25, 0.5, 0.75, 1.0], [(0, 0, 100), (80, 0, 80), (140, 0, 0), (255, 100, 0), (255, 255, 100)], ) default = no_data_color summary = self.connectivity_summary(cre_type=None) shape = (len(rows), len(cols)) text = np.empty(shape, dtype=object) fgcolor = np.empty(shape, dtype=object) bgcolor = np.empty(shape, dtype=object) bordercolor = np.empty(shape, dtype=object) for i, row in enumerate(rows): for j, col in enumerate(cols): if (row, col) in summary: conn = summary[(row, col)]['connected'] uconn = summary[(row, col)]['unconnected'] else: conn, uconn = 0, 0 probed = conn + uconn if probed == 0: color = default else: if mode == 'connectivity': color = default if probed == 0 else colormap.map( conn / probed) color = pg.colorTuple(pg.mkColor(color)) bgcolor[i, j] = color elif mode == 'progress': prg = max(probed / 80., conn / 10.) color = pg.colorTuple(pg.mkColor(colormap.map(prg))) bordercolor[i, j] = 0.8 if probed == 0 else 'k' bgcolor[i, j] = color fgcolor[i, j] = 0.6 if probed == 0 else ( 'w' if sum(color[:3]) < 200 else 'k') text[i, j] = "%d/%d" % (conn, probed) if probed > 0 else '' w.matrix = MatrixItem(text=text, fgcolor=fgcolor, bgcolor=bgcolor, border_color=bordercolor, rows=rows.values(), cols=cols.values(), size=size, header_color=header_color) v.addItem(w.matrix) # colormap is logarithmic; remap to linear for legend colors = colormap.color x = np.linspace(0, 1, len(colors)) cmap2 = pg.ColorMap(x, colors) legend = pg.GradientLegend([25, 300], [-20, -30]) legend.setGradient(cmap2.getGradient()) legend.setLabels( {'%d' % int(a * 100): b for a, b in zip(colormap.pos, x)}) v.addItem(legend) w.show() self.matrix_widget = w return w
fit = gaussian(*params) print params height, center_x, center_y, width_x, width_y = params center_x += 256 center_y += 256 #tmp = np.fromfunction(lambda x,y: height*np.exp(-(((center_x-x)/width_x)**2+((center_y-y)/width_y)**2)/2), (1024,1024)) tmp = np.fromfunction(lambda x,y: np.sin(0.1*(x+y)), (512,512)) ################################### Visualization app = QtGui.QApplication([]) ## Create window with four ImageView widgets pg.setConfigOption('background', 'w') pg.setConfigOption('foreground', 'k') STEPS = np.array([0.0, 0.33, 0.66, 1.0]) CLRS = ['k', 'r', 'y', 'w'] clrmp = pg.ColorMap(STEPS, np.array([pg.colorTuple(pg.Color(c)) for c in CLRS])) win = QtGui.QMainWindow() win.show() win.resize(900,900) win.setWindowTitle('Seeing of '+data_filename) cw = QtGui.QWidget() win.setCentralWidget(cw) l = QtGui.QGridLayout() cw.setLayout(l) imv1, imv2, imv3, imv4 = pg.ImageView(), pg.ImageView(), pg.ImageView(), pg.ImageView() l.addWidget(imv1, 0, 0), l.addWidget(imv2, 0, 1), l.addWidget(imv3, 1, 0), l.addWidget(imv4, 1, 1) imv1.setImage(frame, levels=(300, 2000)), imv1.ui.normBtn.hide(), imv1.ui.histogram.gradient.setColorMap(clrmp) imv2.setImage(avg), imv2.ui.normBtn.hide(), imv2.ui.histogram.gradient.setColorMap(clrmp)
from misura.canon.indexer import SharedFile from misura.canon.reference import get_node_reference try: import pyqtgraph as pg import pyqtgraph.opengl as gl except: pg = False gl = False STEPS = np.array([0.0, 0.33, 0.66, 1.0]) CLRS = ['b', 'r', 'y', 'w'] if pg: clrmp = pg.ColorMap(STEPS, np.array([pg.colorTuple(pg.Color(c)) for c in CLRS])) #TODO: add decoding def read_file(profile, start=3500, end=-1, max_layers=1000, cut=0): xs = [] ys = [] zs = [] colors = [] c = 0. n = len(profile) if end < 0: end += n n = end - start + 1 step = max(n // max_layers, 1)
def contrasting_text_color(self, color): r, g, b, a = pg.colorTuple(pg.mkColor(color)) return pg.mkBrush( '000' if 1 - (r * 0.299 + g * 0.587 + b * 0.114) / 255 < 0.5 else 'fff')
def distance_plot(connected, distance, plots=None, color=(100, 100, 255), size=10, window=40e-6, spacing=None, name=None, fill_alpha=30): """Draw connectivity vs distance profiles with confidence intervals. Parameters ---------- connected : boolean array Whether a synaptic connection was found for each probe distance : array Distance between cells for each probe plots : list of PlotWidget | PlotItem (optional) Two plots used to display distance profile and scatter plot. color : tuple (R, G, B) color values for line and confidence interval. The confidence interval will be drawn with alpha=100 size: int size of scatter plot symbol window : float Width of distance window over which proportions are calculated for each point on the profile line. spacing : float Distance spacing between points on the profile line Note: using a spacing value that is smaller than the window size may cause an otherwise smooth decrease over distance to instead look more like a series of downward steps. """ color = pg.colorTuple(pg.mkColor(color))[:3] connected = np.array(connected).astype(float) distance = np.array(distance) pts = np.vstack([distance, connected]).T # scatter points a bit conn = pts[:,1] == 1 unconn = pts[:,1] == 0 if np.any(conn): cscat = pg.pseudoScatter(pts[:,0][conn], spacing=10e-6, bidir=False) mx = abs(cscat).max() if mx != 0: cscat = cscat * 0.2# / mx pts[:,1][conn] = -5e-5 - cscat if np.any(unconn): uscat = pg.pseudoScatter(pts[:,0][unconn], spacing=10e-6, bidir=False) mx = abs(uscat).max() if mx != 0: uscat = uscat * 0.2# / mx pts[:,1][unconn] = uscat # scatter plot connections probed if plots is None: grid = PlotGrid() grid.set_shape(2, 1) grid.grid.ci.layout.setRowStretchFactor(0, 5) grid.grid.ci.layout.setRowStretchFactor(1, 10) plots = (grid[1,0], grid[0,0]) plots[0].grid = grid plots[0].addLegend() grid.show() plots[0].setLabels(bottom=('distance', 'm'), left='connection probability') if plots[1] is not None: plots[1].setXLink(plots[0]) plots[1].hideAxis('bottom') plots[1].hideAxis('left') color2 = color + (100,) scatter = plots[1].plot(pts[:,0], pts[:,1], pen=None, symbol='o', labels={'bottom': ('distance', 'm')}, size=size, symbolBrush=color2, symbolPen=None, name=name) scatter.scatter.opts['compositionMode'] = pg.QtGui.QPainter.CompositionMode_Plus # use a sliding window to plot the proportion of connections found along with a 95% confidence interval # for connection probability if spacing is None: spacing = window / 4.0 xvals = np.arange(window / 2.0, 500e-6, spacing) upper = [] lower = [] prop = [] ci_xvals = [] for x in xvals: minx = x - window / 2.0 maxx = x + window / 2.0 # select points inside this window mask = (distance >= minx) & (distance <= maxx) pts_in_window = connected[mask] # compute stats for window n_probed = pts_in_window.shape[0] n_conn = pts_in_window.sum() if n_probed == 0: prop.append(np.nan) else: prop.append(n_conn / n_probed) ci = proportion_confint(n_conn, n_probed, method='beta') lower.append(ci[0]) upper.append(ci[1]) ci_xvals.append(x) # plot connection probability and confidence intervals color2 = [c / 3.0 for c in color] mid_curve = plots[0].plot(xvals, prop, pen={'color': color, 'width': 3}, antialias=True, name=name) upper_curve = plots[0].plot(ci_xvals, upper, pen=(0, 0, 0, 0), antialias=True) lower_curve = plots[0].plot(ci_xvals, lower, pen=(0, 0, 0, 0), antialias=True) upper_curve.setVisible(False) lower_curve.setVisible(False) color2 = color + (fill_alpha,) fill = pg.FillBetweenItem(upper_curve, lower_curve, brush=color2) fill.setZValue(-10) plots[0].addItem(fill, ignoreBounds=True) return plots, ci_xvals, prop, upper, lower
def __init__(self,map='map'): prefileMeas = sorted([x for x in [y for y in os.listdir("./")] if re.search("axion.m.[0-9]{5}$", x)]) fileMeas = [] for maes in prefileMeas: try: with h5py.File(maes, 'r') as f: if (map in f) : fileMeas.append(maes) except: print('Error opening file: %s'%maes) fileHdf5 = h5py.File(fileMeas[0], "r") self.Lx = fileHdf5["/"].attrs.get("Size") self.Ly = fileHdf5["/"].attrs.get("Size") self.Lz = fileHdf5["/"].attrs.get("Depth") self.z = fileHdf5["/"].attrs.get("z") self.R = self.z fileHdf5.close() self.allData = [] self.step = 1 self.tStep = 100 self.pause = False self.timer = pg.QtCore.QTimer() # Read all data self.i = 0 self.size = 0 # if os.path.exists("./Strings.PyDat"): # fp = gzip.open("./Strings.PyDat", "rb") # self.allData = pickle.load(fp) # fp.close() # self.size = len(self.allData) # else: for meas in fileMeas: # print(meas) fileHdf5 = h5py.File(meas, "r") Lx = fileHdf5["/"].attrs.get("Size") Ly = fileHdf5["/"].attrs.get("Size") Lz = fileHdf5["/"].attrs.get("Depth") zR = fileHdf5["/"].attrs.get("z") R = zR if 'R' in fileHdf5: R = fileHdf5["/"].attrs.get("R") fl = fileHdf5["/"].attrs.get("Field type").decode() if self.Lx != Lx or self.Ly != Ly or self.Lz != Lz: print("Error: Size mismatch (%d %d %d) vs (%d %d %d)\nAre you mixing files?\n" % (Lx, Ly, Lz, self.Lx, self.Ly, self.Lz)) exit() if fl == "Saxion": mTmp = fileHdf5[map]['m'].value.reshape(Ly,Lx,2) rData = np.sqrt(mTmp[:,:,0]**2 + mTmp[:,:,1]**2) rMax = np.amax(rData) rData = rData/R aData = (np.arctan2(mTmp[:,:,1], mTmp[:,:,0]) + 2*np.pi)/(4.*np.pi) elif fl == "Axion": aData = fileHdf5[map]['m'].value.reshape(Ly,Lx) # pm = np.amax(aData) # print ("BMax %f" % pm) aData = aData/R rData = np.ones(aData.shape) pData = np.ones(aData.shape)*(2*np.pi) aData = (aData + pData)/(4.*np.pi) # iData = np.trunc(aData/(2*np.pi)) # aData = aData - iData*(2*np.pi) # aData = aData - pData # pm = np.amax(aData) # print ("AMax %f" % pm) rMax = R else: print("Unrecognized field type %s" % fl) exit() self.allData.append([rData, aData, zR, rMax]) fileHdf5.close() self.size = self.size + 1 # fp = gzip.open("Strings.PyDat", "wb") # pickle.dump(self.allData, fp, protocol=2) # fp.close() self.app = QtGui.QApplication([]) self.pWin = pg.GraphicsLayoutWidget() self.pWin.setWindowTitle('Axion / Saxion evolution') self.pWin.resize(1600,1600) pg.setConfigOptions(antialias=True) self.aPlot = self.pWin.addPlot(row=0, col=0) self.sPlot = self.pWin.addPlot(row=0, col=1) self.aPlot.setXRange(0,Lx*1.2) self.aPlot.setYRange(0,Lx*1.2) self.sPlot.setXRange(0,Lx*1.2) self.sPlot.setYRange(0,Lx*1.2) self.zAtxt = pg.TextItem("z=0.000000") self.zStxt = pg.TextItem("z=0.000000") data = self.allData[0] aPos = np.array([0.00, 0.10, 0.25, 0.4, 0.5, 0.6, 0.75, 0.9, 1.0 ]) aCol = ['#006600', 'b', 'w', 'r', 'k', 'b', 'w', 'r', '#006600'] vb = self.aPlot.getViewBox() aSzeX = vb.size().width()*0.96 aSzeY = vb.size().height()*0.8 self.aMap = pg.ColorMap(aPos, np.array([pg.colorTuple(pg.Color(c)) for c in aCol])) self.aLut = self.aMap.getLookupTable() self.aLeg = pg.GradientLegend((aSzeX/20, aSzeY), (aSzeX, aSzeY/12.)) self.aLeg.setLabels({ "-pi": 0.0, "-pi/2": 0.25, "0.0": 0.50, "+pi/2": 0.75, "+pi": 1.00 }) self.aLeg.setParentItem(self.aPlot) self.aLeg.gradient.setColorAt(0.00, QtGui.QColor(255,255,255)) self.aLeg.gradient.setColorAt(0.25, QtGui.QColor(255, 0, 0)) self.aLeg.gradient.setColorAt(0.50, QtGui.QColor( 0, 0, 0)) self.aLeg.gradient.setColorAt(0.75, QtGui.QColor( 0, 0,255)) self.aLeg.gradient.setColorAt(1.00, QtGui.QColor(255,255,255)) self.aImg = pg.ImageItem(lut=self.aLut) self.aPlot.addItem(self.aImg) self.aPlot.addItem(self.zAtxt) # sPos = np.linspace(0.0, data[3], 5) sPos = np.array([0.00, 0.25, 0.50, 0.75, 1.00]) sLab = ["%.2f" % mod for mod in sPos] sCol = ['w', 'r', 'y', 'c', 'k'] vs = self.sPlot.getViewBox() sSzeX = vs.size().width()*0.96 sSzeY = vs.size().height()*0.8 self.sMap = pg.ColorMap(sPos, np.array([pg.colorTuple(pg.Color(c)) for c in sCol])) self.s**t = self.sMap.getLookupTable() self.sLeg = pg.GradientLegend((sSzeX/20, sSzeY), (aSzeX/0.96 + sSzeX, sSzeY/12.)) self.sLeg.setLabels({ sLab[0]: 0.0, sLab[1]: 0.25, sLab[2]: 0.50, sLab[3]: 0.75, sLab[4]: 1.00 }) self.sLeg.setParentItem(self.sPlot) self.sLeg.gradient.setColorAt(0.00, QtGui.QColor(255,255,255)) self.sLeg.gradient.setColorAt(0.25, QtGui.QColor(255, 0, 0)) self.sLeg.gradient.setColorAt(0.50, QtGui.QColor(255,255, 0)) self.sLeg.gradient.setColorAt(0.75, QtGui.QColor( 0,255,255)) self.sLeg.gradient.setColorAt(1.00, QtGui.QColor( 0, 0, 0)) self.sImg = pg.ImageItem(lut=self.s**t) self.sPlot.addItem(self.sImg) self.sPlot.addItem(self.zStxt) self.sImg.setImage(data[0], levels=(0.,1.)) self.aImg.setImage(data[1], levels=(0.,1.)) self.pWin.show() self.baseKeyPress = self.pWin.keyPressEvent
def __init__(self, model_runner): QtGui.QWidget.__init__(self) self.layout = QtGui.QGridLayout() self.layout.setContentsMargins(0, 0, 0, 0) self.setLayout(self.layout) self.splitter = QtGui.QSplitter(QtCore.Qt.Vertical) self.layout.addWidget(self.splitter) self.slicer = NDSlicer(model_runner.param_space.axes()) self.slicer.selection_changed.connect(self.selection_changed) self.splitter.addWidget(self.slicer) self.result_widget = ModelSingleResultWidget() self.splitter.addWidget(self.result_widget) # set up a few default 2D slicer views v1 = self.slicer.params.child('2D views').addNew() v1['axis 0'] = 'n_release_sites' v1['axis 1'] = 'base_release_probability' v2 = self.slicer.params.child('2D views').addNew() v2['axis 0'] = 'vesicle_recovery_tau' v2['axis 1'] = 'facilitation_recovery_tau' self.slicer.dockarea.moveDock(v2.viewer.dock, 'bottom', v1.viewer.dock) v3 = self.slicer.params.child('2D views').addNew() v3['axis 0'] = 'vesicle_recovery_tau' v3['axis 1'] = 'base_release_probability' v4 = self.slicer.params.child('2D views').addNew() v4['axis 0'] = 'facilitation_amount' v4['axis 1'] = 'facilitation_recovery_tau' self.slicer.dockarea.moveDock(v4.viewer.dock, 'bottom', v3.viewer.dock) # turn on max projection for all parameters by default for ch in self.slicer.params.child('max project'): if ch.name() == 'synapse': continue ch.setValue(True) self.model_runner = model_runner self.param_space = model_runner.param_space result_img = np.zeros(self.param_space.result.shape) for ind in np.ndindex(result_img.shape): result_img[ind] = self.param_space.result[ind]['likelihood'] self.slicer.set_data(result_img) self.results = result_img # select best result best = np.unravel_index(np.argmax(result_img), result_img.shape) self.select_result(best) max_like = self.results.max() # if results are combined across synapses, set up colors if 'synapse' in self.param_space.params: self.slicer.params['color axis', 'axis'] = 'synapse' syn_axis = list(self.param_space.params.keys()).index('synapse') max_img = np.array([ result_img.take(i, axis=syn_axis).max() for i in range(result_img.shape[syn_axis]) ]) max_like = max_img.min() max_img = max_img.min() / max_img syns = self.param_space.params['synapse'] for i in syns: c = pg.colorTuple(pg.intColor(i, len(syns) * 1.2)) c = pg.mkColor(c[0] * max_img[i], c[1] * max_img[i], c[2] * max_img[i]) self.slicer.params['color axis', 'colors', str(i)] = c # set histogram range self.slicer.histlut.setLevels(max_like * 0.85, max_like)
def distance_plot(connected, distance, plots=None, color=(100, 100, 255), size=10, window=40e-6, name=None, fill_alpha=30): """Draw connectivity vs distance profiles with confidence intervals. Parameters ---------- connected : boolean array Whether a synaptic connection was found for each probe distance : array Distance between cells for each probe plots : list of PlotWidget | PlotItem (optional) Two plots used to display distance profile and scatter plot. color : tuple (R, G, B) color values for line and confidence interval. The confidence interval will be drawn with reduced opacity (see *fill_alpha*) size: int size of scatter plot symbol window : float Width of distance window over which proportions are calculated for each point on the profile line. fill_alpha : int Opacity of confidence interval fill (0-255) Note: using a spacing value that is smaller than the window size may cause an otherwise smooth decrease over distance to instead look more like a series of downward steps. """ color = pg.colorTuple(pg.mkColor(color))[:3] connected = np.array(connected).astype(float) distance = np.array(distance) # scatter plot connections probed if plots is None: grid = PlotGrid() grid.set_shape(2, 1) grid.grid.ci.layout.setRowStretchFactor(0, 5) grid.grid.ci.layout.setRowStretchFactor(1, 10) plots = (grid[1, 0], grid[0, 0]) plots[0].grid = grid plots[0].addLegend() grid.show() plots[0].setLabels(bottom=('distance', 'm'), left='connection probability') if plots[1] is not None: # scatter points a bit pts = np.vstack([distance, connected]).T conn = pts[:, 1] == 1 unconn = pts[:, 1] == 0 if np.any(conn): cscat = pg.pseudoScatter(pts[:, 0][conn], spacing=10e-6, bidir=False) mx = abs(cscat).max() if mx != 0: cscat = cscat * 0.2 # / mx pts[:, 1][conn] = -5e-5 - cscat if np.any(unconn): uscat = pg.pseudoScatter(pts[:, 0][unconn], spacing=10e-6, bidir=False) mx = abs(uscat).max() if mx != 0: uscat = uscat * 0.2 # / mx pts[:, 1][unconn] = uscat plots[1].setXLink(plots[0]) plots[1].hideAxis('bottom') plots[1].hideAxis('left') color2 = color + (100, ) scatter = plots[1].plot(pts[:, 0], pts[:, 1], pen=None, symbol='o', labels={'bottom': ('distance', 'm')}, size=size, symbolBrush=color2, symbolPen=None, name=name) scatter.scatter.opts[ 'compositionMode'] = pg.QtGui.QPainter.CompositionMode_Plus # use a sliding window to plot the proportion of connections found along with a 95% confidence interval # for connection probability bin_edges = np.arange(0, 500e-6, window) xvals, prop, lower, upper = connectivity_profile(connected, distance, bin_edges) # plot connection probability and confidence intervals color2 = [c / 3.0 for c in color] xvals = (xvals[:-1] + xvals[1:]) * 0.5 mid_curve = plots[0].plot(xvals, prop, pen={ 'color': color, 'width': 3 }, antialias=True, name=name) upper_curve = plots[0].plot(xvals, upper, pen=(0, 0, 0, 0), antialias=True) lower_curve = plots[0].plot(xvals, lower, pen=(0, 0, 0, 0), antialias=True) upper_curve.setVisible(False) lower_curve.setVisible(False) color2 = color + (fill_alpha, ) fill = pg.FillBetweenItem(upper_curve, lower_curve, brush=color2) fill.setZValue(-10) plots[0].addItem(fill, ignoreBounds=True) return plots, xvals, prop, upper, lower
def distance_plot(connected, distance, plots=None, color=(100, 100, 255), window=40e-6, spacing=None, name=None, fill_alpha=30): """Draw connectivity vs distance profiles with confidence intervals. Parameters ---------- connected : boolean array Whether a synaptic connection was found for each probe distance : array Distance between cells for each probe plots : list of PlotWidget | PlotItem (optional) Two plots used to display distance profile and scatter plot. color : tuple (R, G, B) color values for line and confidence interval. The confidence interval will be drawn with alpha=100 window : float Width of distance window over which proportions are calculated for each point on the profile line. spacing : float Distance spacing between points on the profile line Note: using a spacing value that is smaller than the window size may cause an otherwise smooth decrease over distance to instead look more like a series of downward steps. """ color = pg.colorTuple(pg.mkColor(color))[:3] connected = np.array(connected).astype(float) distance = np.array(distance) pts = np.vstack([distance, connected]).T # scatter points a bit conn = pts[:, 1] == 1 unconn = pts[:, 1] == 0 if np.any(conn): cscat = pg.pseudoScatter(pts[:, 0][conn], spacing=10e-6, bidir=False) mx = abs(cscat).max() if mx != 0: cscat = cscat * 0.2 # / mx pts[:, 1][conn] = -2e-5 - cscat if np.any(unconn): uscat = pg.pseudoScatter(pts[:, 0][unconn], spacing=10e-6, bidir=False) mx = abs(uscat).max() if mx != 0: uscat = uscat * 0.2 # / mx pts[:, 1][unconn] = uscat # scatter plot connections probed if plots is None: grid = PlotGrid() grid.set_shape(2, 1) grid.grid.ci.layout.setRowStretchFactor(0, 5) grid.grid.ci.layout.setRowStretchFactor(1, 10) plots = (grid[1, 0], grid[0, 0]) plots[0].grid = grid plots[0].addLegend() grid.show() plots[0].setLabels(bottom=('distance', 'm'), left='connection probability') if plots[1] is not None: plots[1].setXLink(plots[0]) plots[1].hideAxis('bottom') plots[1].hideAxis('left') color2 = color + (100, ) scatter = plots[1].plot(pts[:, 0], pts[:, 1], pen=None, symbol='o', labels={'bottom': ('distance', 'm')}, symbolBrush=color2, symbolPen=None, name=name) scatter.scatter.opts[ 'compositionMode'] = pg.QtGui.QPainter.CompositionMode_Plus # use a sliding window to plot the proportion of connections found along with a 95% confidence interval # for connection probability if spacing is None: spacing = window / 4.0 xvals = np.arange(window / 2.0, 500e-6, spacing) upper = [] lower = [] prop = [] ci_xvals = [] for x in xvals: minx = x - window / 2.0 maxx = x + window / 2.0 # select points inside this window mask = (distance >= minx) & (distance <= maxx) pts_in_window = connected[mask] # compute stats for window n_probed = pts_in_window.shape[0] n_conn = pts_in_window.sum() if n_probed == 0: prop.append(np.nan) else: prop.append(n_conn / n_probed) ci = binomial_ci(n_conn, n_probed) lower.append(ci[0]) upper.append(ci[1]) ci_xvals.append(x) # plot connection probability and confidence intervals color2 = [c / 3.0 for c in color] mid_curve = plots[0].plot(xvals, prop, pen={ 'color': color, 'width': 3 }, antialias=True, name=name) upper_curve = plots[0].plot(ci_xvals, upper, pen=(0, 0, 0, 0), antialias=True) lower_curve = plots[0].plot(ci_xvals, lower, pen=(0, 0, 0, 0), antialias=True) upper_curve.setVisible(False) lower_curve.setVisible(False) color2 = color + (fill_alpha, ) fill = pg.FillBetweenItem(upper_curve, lower_curve, brush=color2) fill.setZValue(-10) plots[0].addItem(fill, ignoreBounds=True) return plots
def matrix(self, rows, cols, size=50, header_color='k', no_data_color=0.9, mode='connectivity', title='Connectivity Matrix'): w = pg.GraphicsLayoutWidget() w.setRenderHints(w.renderHints() | pg.QtGui.QPainter.Antialiasing) w.setWindowTitle(title) v = w.addViewBox() v.setBackgroundColor('w') v.setAspectLocked() v.invertY() if mode == 'connectivity': 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)], ) else: colormap = pg.ColorMap( [0, 0.25, 0.5, 0.75, 1.0], [(0,0,100), (80,0,80), (140,0,0), (255,100,0), (255,255,100)], ) default = no_data_color conn_matrix = self.connectivity_matrix(rows, cols) shape = (len(rows), len(cols)) text = np.empty(shape, dtype=object) fgcolor = np.empty(shape, dtype=object) bgcolor = np.empty(shape, dtype=object) bordercolor = np.empty(shape, dtype=object) for i,row in enumerate(rows): for j,col in enumerate(cols): conn, probed = conn_matrix[i, j] if probed == 0: color = default else: if mode == 'connectivity': color = default if probed == 0 else colormap.map(conn/probed) color = pg.colorTuple(pg.mkColor(color)) bgcolor[i, j] = color elif mode == 'progress': prg = max(probed/80., conn/10.) color = pg.colorTuple(pg.mkColor(colormap.map(prg))) bordercolor[i, j] = 0.8 if probed == 0 else 'k' bgcolor[i, j] = color fgcolor[i, j] = 0.6 if probed == 0 else ('w' if sum(color[:3]) < 200 else 'k') text[i, j] = "%d/%d" % (conn, probed) if probed > 0 else '' w.matrix = MatrixItem(text=text, fgcolor=fgcolor, bgcolor=bgcolor, border_color=bordercolor, rows=rows.values(), cols=cols.values(), size=size, header_color=header_color) v.addItem(w.matrix) # colormap is logarithmic; remap to linear for legend colors = colormap.color x = np.linspace(0, 1, len(colors)) cmap2 = pg.ColorMap(x, colors) legend = pg.GradientLegend([25, 300], [-20, -30]) legend.setGradient(cmap2.getGradient()) legend.setLabels({'%d'%int(a*100):b for a,b in zip(colormap.pos, x)}) v.addItem(legend) w.show() self.matrix_widget = w return w
def saveColorState(self): state = Parameter.saveState(self) state['value'] = pg.colorTuple(self.value()) return state
def contrasting_text_color(self, color): # (r, g, b) = (hex_str[:2], hex_str[2:4], hex_str[4:]) r, g, b, a = pg.colorTuple(pg.mkColor(color)) return pg.mkBrush( '000' if 1 - (r * 0.299 + g * 0.587 + b * 0.114) / 255 < 0.5 else 'fff')