def __init__(self, host, rec=None): self.host = host ## host is the parent Photostim object self.stubs = [] ## list of ScanStub objects for scans in the map that have not been loaded yet self.scans = [] ## list of loaded Scan objects self.scanItems = {} ## maps {scan: tree item} #self.points = [] ## Holds all data: [ (position, [(scan, dh), ...], spotData), ... ] self.pointsByFile = {} ## just a lookup dictionary self.spots = [] ## holds all data {pos, size, [(scan, dh), ...]}; used to construct scatterplotitem self.sPlotItem = pg.ScatterPlotItem(pxMode=False, pen=(50,50,50)) self.header = self.mapFields.keys()[2:] self.item = QtGui.QTreeWidgetItem([""] * len(self.header)) self.item.setFlags(QtCore.Qt.ItemIsSelectable| QtCore.Qt.ItemIsEditable| QtCore.Qt.ItemIsEnabled) self.item.map = self self.item.setExpanded(True) self.rowID = None ## If a DB record was supplied, that means this map already exists in the DB so ## we can reload the list of scans already included in the map if rec is not None: self.rowID = rec['rowid'] scans = rec['scans'] #del rec['scans'] #del rec['cell'] for i in range(len(self.header)): self.item.setText(i, str(rec[self.header[i]])) for fh,rowid in scans: item = QtGui.QTreeWidgetItem([fh.shortName()]) #print "Create scan stub:", fh self.stubs.append(ScanStub(fh, item, rowid)) ## rowid can be either a (table, rowid) pair or an integer implying ('ProtocolSequence', rowid) item.handle = fh self.item.addChild(item)
def __init__(self, name, ptSize, **args): pg.CrosshairROI.__init__(self, pos=(0,0), size=args.get('size', [ptSize*4]*2), angle=args.get('angle', 0), **args) self.name = name self.params = pTypes.SimpleParameter(name=self.name, type='bool', value=True, removable=True, renamable=True, children=[ dict(name='layout', type='list', value=args.get('layout', 'Hexagonal'), values=['Square', 'Hexagonal']), dict(name='spacing', type='float', value=args.get('spacing', ptSize), suffix='m', siPrefix=True, bounds=[1e-9, None], step=10e-6), dict(name='Active Regions', type='group', addText="Add region...", addList=['Rectangle', 'Polygon']) ]) self.params.item = self self.params.param('Active Regions').addNew = self.addActiveRegion self.rgns = [] self.pointSize = ptSize self._points = np.empty((0,2), dtype=float) self._scene = None self._scatter = pg.ScatterPlotItem(pxMode=False, brush=None, antialias=True) self._scatter.setParentItem(self) self._needScatterUpdate = False self.params.param('layout').sigStateChanged.connect(self.invalidatePoints) self.params.param('spacing').sigStateChanged.connect(self.invalidatePoints) self.params.param('Active Regions').sigChildRemoved.connect(self.rgnRemoved) self.sigRegionChanged.connect(self.invalidatePoints) self.params.sigValueChanged.connect(self.toggled) self.params.sigRemoved.connect(self.removed)
def __init__(self, name, ui): self.scatter = pg.ScatterPlotItem(pxMode=False) self.name = name self.ui = weakref.ref(ui) self.frames = [] self.spots = {'pos': [], 'size': [], 'color': []} self.updateParams() self.z = Task.z Task.z += 1
def addScan(self, scanDict): plot = pg.ScatterPlotItem(pen=QtGui.QPen(QtCore.Qt.NoPen), brush=pg.mkBrush((255, 255, 255, 100))) self.plot.addItem(plot) plot.sigClicked.connect(self.plotClicked) if not isinstance(scanDict, dict): scanDict = {'key': scanDict} #print "Adding:", scan.name for scan in scanDict.values(): item = QtGui.QTreeWidgetItem([scan.name()]) item.setCheckState(0, QtCore.Qt.Checked) item.scan = scan self.scanList.addTopLevelItem(item) self.scans[scan] = [plot, item, False] self.updateScan(scan) scan.sigEventsChanged.connect(self.invalidateScan)
def showMap(dh=None): """ Display a graphic of an input map for the currently selected cell """ global v, g, atlas if dh is None: dh = man.currentFile db = man.getModule('Data Manager').currentDatabase() v.clear() cd = dh sd = cd.parent() atlas.loadState(sd) g = atlas.schematicGraphicsItems(contours=False, sliceScale=10, cellDir=cd) v.addItem(g) cellGroup = pg.ItemGroup() g.cellGroup = cellGroup cellScale = 10. cellGroup.scale(cellScale, cellScale) cellGroup.setParentItem(g) g.atlasScale.hide() g.arrowGroup.hide() ## reposition/rescale atlas group b1 = g.atlasGroup.mapRectToParent(g.atlasGroup.childrenBoundingRect()) b2 = g.sliceClip.mapRectToParent(g.sliceClip.boundingRect()) g.atlasGroup.setPos(b2.right()-b1.left()+0.001, b2.top()-b1.top()) b1 = g.atlasGroup.mapRectToParent(g.atlasGroup.childrenBoundingRect()) bounds = b1 | b2 if cd.exists('morphology.png'): ## small image to go over slice schematic imgf = cd['morphology.png'] imgd = pg.colorToAlpha(imgf.read(), np.array([255,255,255])) mimg1 = pg.ImageItem(imgd) tr = pg.SRTTransform(imgf.info()['userTransform']) mimg1.setTransform(tr) mimg1.setParentItem(g.sliceGroup) mimg1.setZValue(100) g.cellImg1 = mimg1 ## larger image to be displayed above mimg2 = pg.ImageItem(imgd) mimg2.setParentItem(cellGroup) mimg2.setTransform(tr * g.sliceGroup.transform()) mimg2.scale(1.0 / g.sliceScaleFactor, 1.0 / g.sliceScaleFactor) #angle = pg.SRTTransform(g.sliceGroup.transform()).getRotation() #mimg2.rotate(angle) g.cellImg2 = mimg2 cellGroup.scale(5,5) ## reposition next to slice schematic imgBounds = g.mapRectFromItem(mimg2, mimg2.boundingRect()) pos = pg.Point(bounds.right()-imgBounds.left(), bounds.bottom()-imgBounds.bottom()) cellGroup.setPos(pos) ## add scale bar sbLength = 50e-6 g.cellScale = Qt.QGraphicsLineItem(0.0, 0.0, sbLength, 0.0) g.cellScale.setPen(pg.mkPen(color=0.0, width=5)) g.cellScale.setZValue(10) g.cellScale.text = pg.TextItem(u"%d µm" % int(sbLength*1e6), anchor=(0.5, 1), color=(0,0,0)) g.cellScale.text.setParentItem(g.cellScale) g.cellScale.text.setPos(sbLength*0.5, -50e-6/cellScale) #g.cellScale = pg.ScaleBar(sbLength) g.cellScale.setParentItem(cellGroup) corner = mimg2.mapToParent(mimg2.boundingRect()).boundingRect().bottomRight() g.cellScale.setPos(corner + pg.Point(-sbLength/2., -sbLength/3.)) pos = pg.SRTTransform(cd.info()['userTransform']).map(pg.Point(0,0)) size = pg.Point(30e-6, 30e-6) g.cellMarker = Qt.QGraphicsEllipseItem(Qt.QRectF(pos-size, pos+size)) g.cellMarker.setBrush(pg.mkBrush(100,100,255,150)) g.cellMarker.setPen(pg.mkPen('k', width=0.5)) g.cellMarker.setParentItem(g.sliceGroup) g.cellMarker.setZValue(90) sites = db.select('map_site_view', ['ProtocolDir', 'HasInput'], where={'CellDir': cd}) if len(sites) > 0: tr = sites[0]['ProtocolDir'].parent().info().get('userTransform', None) if tr is None: tr = pg.SRTTransform() else: tr = pg.SRTTransform(tr) pos = [] size = sites[0]['ProtocolDir'].info()['Scanner']['spotSize'] brushes = [] for site in sites: pd = site['ProtocolDir'] x,y = pd.info()['Scanner']['position'] p2 = tr.map(pg.Point(x,y)) pos.append((p2.x(), p2.y())) if site['HasInput']: brushes.append(pg.mkBrush('w')) else: brushes.append(pg.mkBrush(None)) inputMap = pg.ScatterPlotItem(pos=np.array(pos), size=size, brush=brushes, pen=(0,0,0,50), pxMode=False, antialias=True) g.sliceGroup.addItem(inputMap) g.inputMap = inputMap inputMap.setZValue(50) cell = dh sl = cell.parent() day = sl.parent() name = day.shortName() + "_" + sl.shortName() + "_" + cell.shortName() rec = db.select('DirTable_Cell', '*', where={'Dir': cd})[0] name += "\nType: " + str(rec['CellType']) + " Temp: " + str(rec['Temperature']) + " Internal: " + str(rec['Internal']) + " Age:" + str(rec['Age']) + " Raccess: " + str(rec['AccessResistance']) name += "\nDirect Area: %s>0pA %s>20pA %s>100pA" % (str(rec['DirectAreaGt0']), str(rec['DirectAreaGt20']), str(rec['DirectAreaGt100'])) name += " Direct n spikes: " + str(rec['DirectNSpikes']) name += "\nSpont Ex Decay: %s Spont In Decay: %s" % (str(rec['SpontExDecay1']), str(rec['SpontInDecay'])) name += "\nExcitatory input" if (rec['EvokedExDecay'] is not None or rec['EvokedExAmp'] is not None) else "" print(rec) #name += '\nDirect Slow Decay: %s %s' % (str(rec['DirectAreaGT0']), str(rec['DirectAreaGT0'])) g.cellName = pg.TextItem(name, color=(0,0,0)) g.cellName.setParentItem(g) g.cellName.setPos(0, bounds.bottom())
bTimes = [x[1] for x in l2] print key, " \tcompute time:\t%0.1f \ttotal cost:\t%0.1f \tmax interval:\t%0.1f\t" % ( time.time()-start, sum(bTimes), max(bTimes) ) #print " total cost:\t%0.1f" % sum(bTimes) #print " max interval:\t%0.1f" % max(bTimes) check(locs, l2) vb = pg.ViewBox() view.addItem(vb) data = [{'pos': l2[i][0], 'brush': (i * 255/ len(l2),)*3} for i in range(len(l2))] sp = pg.ScatterPlotItem(data, pen=0.3, pxMode=False, size=1e-4) vb.addItem(sp) ## number spots #for i in range(len(data)): #t = QtGui.QGraphicsTextItem() #t.setHtml('<span style="color: #f00">%d</span>'%i) #t.setFlag(t.ItemIgnoresTransformations, True) #t.setPos(*l2[i][0]) #vb.addItem(t) vb.setRange(sp.boundingRect()) ### show video of sequence #img = np.zeros((n**2, n, n, 3), dtype=float) #l3 = [x[0] for x in l2]
def __init__(self, **opts): self.defaultSize = 1e-4 # set a default spot size as 100 um. if 'handle' not in opts: raise Exception( "ScanCanvasItem must be initialized with 'handle' or 'handles' specified in opts" ) ## Top-level dirHandle tells us the default name of the item ## and may have a userTransform dirHandle = opts['handle'] if 'name' not in opts: opts['name'] = dirHandle.shortName() ## Get the specific list of subdirs to use from which to pull spot information if 'subDirs' in opts: dirs = opts['subDirs'] else: model = acq4.Manager.getManager().dataModel typ = model.dirType(dirHandle) if typ == 'ProtocolSequence': dirs = [dirHandle[d] for d in dirHandle.subDirs()] elif typ == 'Protocol': dirs = [dirHandle] else: raise Exception("Invalid dir type '%s'" % typ) ## Generate spot data and a scatterplotitem pts = [] for d in dirs: if 'Scanner' in d.info() and 'position' in d.info( )['Scanner']: #Note: this is expected to fail (gracefully) when a protocol sequence is incomplete pos = d.info()['Scanner']['position'] if 'spotSize' in d.info()['Scanner']: size = d.info()['Scanner']['spotSize'] else: size = self.defaultSize pts.append({'pos': pos, 'size': size, 'data': d}) self.scatterPlotData = pts if len(pts) == 0: raise Exception( "No data found in scan %s." % dirHandle.name(relativeTo=dirHandle.parent().parent())) gitem = pg.ScatterPlotItem(pts, pxMode=False, pen=(50, 50, 50, 200)) #citem = ScanCanvasItem(self, item, handle=dirHandle, **opts) #self._addCanvasItem(citem) #return [citem] CanvasItem.__init__(self, gitem, **opts) #self.scatterPlot = gitem self.originalSpotSize = size self._ctrlWidget = Qt.QWidget() self.ui = ScanCanvasItemTemplate.Ui_Form() self.ui.setupUi(self._ctrlWidget) self.layout.addWidget(self._ctrlWidget, self.layout.rowCount(), 0, 1, 2) self.ui.outlineColorBtn.setColor((50, 50, 50, 200)) #self.transformGui.mirrorImageBtn.clicked.connect(self.mirrorY) self.ui.sizeSpin.setOpts(dec=True, step=1, minStep=1e-6, siPrefix=True, suffix='m', bounds=[1e-6, None]) self.ui.sizeSpin.setValue(self.originalSpotSize) self.ui.sizeSpin.valueChanged.connect(self.sizeSpinEdited) self.ui.sizeFromCalibrationRadio.clicked.connect(self.updateSpotSize) self.ui.outlineColorBtn.sigColorChanging.connect(self.updateOutline) self.addScanImageBtn = self.ui.loadSpotImagesBtn #self.createGradientBtn = self.ui.createGradientBtn #self.removeGradientBtn = self.ui.removeGradientBtn self.addScanImageBtn.connect(self.addScanImageBtn, Qt.SIGNAL('clicked()'), self.loadScanImage)