def updateCircle(self, s): size = s * self.zoom pixmap = QPixmap(self.width(), self.height()) pixmap.fill(Qt.transparent) #painter ellipse 1 painter = QPainter() painter.begin(pixmap) painter.setRenderHint(QPainter.Antialiasing) pen = QPen(Qt.red) pen.setWidth(3) painter.setPen(pen) brush = QBrush(Qt.green) painter.setBrush(brush) painter.drawEllipse(QRect(self.width()/2 - size/2, self.height()/2 - size/2, size, size)) painter.end() #painter ellipse 2 painter2 = QPainter() painter2.begin(pixmap) painter2.setRenderHint(QPainter.Antialiasing) pen2 = QPen(Qt.green) pen2.setStyle(Qt.DotLine) pen2.setWidth(3) painter2.setPen(pen2) painter2.drawEllipse(QRect(self.width()/2 - size/2, self.height()/2 - size/2, size, size)) painter2.end() self.ellipseLabel.setPixmap(QPixmap(pixmap)) self.lastSize = s
def paint(self, painter, option, widget): #Set Pen############################# if self.isSelected(): line_style = Qt.DashLine width = 2 steps = 25 else: line_style = Qt.SolidLine width = 2 steps = 125 pen = QPen() pen.setWidth(width) pen.setColor(self._color) pen.setStyle(line_style) painter.setPen(pen) self.setSteps(steps) ###################################### #painter.drawLine(self.p1(),self.p2()) control_points = self.controlPoints() oldPoint = control_points[0] for point in bezierCurveRange(self.steps(), control_points): painter.drawLine(self.mapToScene(oldPoint), self.mapToScene(point)) oldPoint = point
def paintEvent(self, QPaintEvent): super(LabelerWindow, self).paintEvent(QPaintEvent) p = QtGui.QPainter(self) image = ImageQt(Image.fromarray(self.buffer)) image = image.scaled(self.width(), self.height()) p.drawImage(0, 0, image) # Now for the HUD # -> Draw green cross-hairs old_pen = p.pen() new_pen = QPen() new_pen.setColor(Qt.green) new_pen.setStyle(Qt.DotLine) new_pen.setWidth(1) p.setPen(new_pen) p.drawLine(0, self.height()/2, self.width(), self.height()/2) p.drawLine(self.width()/2, 0, self.width()/2, self.height()) p.setPen(old_pen) # -> Show help for keystrokes help = "[X] Pos. [C] Neg. [UP] Zoom in [DN] Zoom Out [LT] Undo Last [RT] Ignore [LMB] Move " p.fillRect(0, 0, self.width(), p.fontMetrics().height()*1.5, Qt.gray) p.drawText(0, p.fontMetrics().height(), help)
def paintEvent(self, QPaintEvent): super(LabelerWindow, self).paintEvent(QPaintEvent) p = QtGui.QPainter(self) image = ImageQt(Image.fromarray(self.buffer)) image = image.scaled(self.width(), self.height()) p.drawImage(0, 0, image) # Now for the HUD # -> Draw green cross-hairs old_pen = p.pen() new_pen = QPen() new_pen.setColor(Qt.green) new_pen.setStyle(Qt.DotLine) new_pen.setWidth(1) p.setPen(new_pen) p.drawLine(0, self.height() / 2, self.width(), self.height() / 2) p.drawLine(self.width() / 2, 0, self.width() / 2, self.height()) p.setPen(old_pen) # -> Show help for keystrokes help = "[X] Pos. [C] Neg. [UP] Zoom in [DN] Zoom Out [LT] Undo Last [RT] Ignore [LMB] Move " p.fillRect(0, 0, self.width(), p.fontMetrics().height() * 1.5, Qt.gray) p.drawText(0, p.fontMetrics().height(), help)
def __updatePen(self): self.prepareGeometryChange() self.__boundingRect = None if self.__dynamic: if self.__dynamicEnabled: color = QColor(0, 150, 0, 150) else: color = QColor(150, 0, 0, 150) normal = QPen(QBrush(color), 2.0) hover = QPen(QBrush(color.darker(120)), 2.1) else: normal = QPen(QBrush(QColor("#9CACB4")), 2.0) hover = QPen(QBrush(QColor("#7D7D7D")), 2.1) if self.__state & LinkItem.Active: pen_style = Qt.SolidLine else: pen_style = Qt.DashLine normal.setStyle(pen_style) hover.setStyle(pen_style) if self.hover: pen = hover else: pen = normal self.curveItem.setPen(pen)
def updateCircle(self, s): size = s * self.zoom pixmap = QPixmap(self.width(), self.height()) pixmap.fill(Qt.transparent) #painter ellipse 1 painter = QPainter() painter.begin(pixmap) painter.setRenderHint(QPainter.Antialiasing) pen = QPen(Qt.red) pen.setWidth(3) painter.setPen(pen) brush = QBrush(Qt.green) painter.setBrush(brush) painter.drawEllipse( QRect(self.width() / 2 - size / 2, self.height() / 2 - size / 2, size, size)) painter.end() #painter ellipse 2 painter2 = QPainter() painter2.begin(pixmap) painter2.setRenderHint(QPainter.Antialiasing) pen2 = QPen(Qt.green) pen2.setStyle(Qt.DotLine) pen2.setWidth(3) painter2.setPen(pen2) painter2.drawEllipse( QRect(self.width() / 2 - size / 2, self.height() / 2 - size / 2, size, size)) painter2.end() self.ellipseLabel.setPixmap(QPixmap(pixmap)) self.lastSize = s
def __init__(self, id, text=None): QWidget.__init__(self) self.id = id self.setToolTip("<p>Adjust line style (leave " "unchecked to use default)</p>") hbox = HBoxLayout() self.penStyleComboBox = LineStyleComboBox() self.penStyleComboBox.setToolTip("Choose line style") self.penStyleComboBox.addItem("solid", QPen(Qt.black, 2, Qt.SolidLine)) self.penStyleComboBox.addItem("dashed", QPen(Qt.black, 2, Qt.DashLine)) self.penStyleComboBox.addItem("dotted", QPen(Qt.black, 2, Qt.DotLine)) self.penStyleComboBox.addItem("dotdash", QPen(Qt.black, 2, Qt.DashDotLine)) pen = QPen(Qt.black, 2, Qt.SolidLine) pen.setStyle(Qt.CustomDashLine) pen.setDashPattern([5, 2, 5, 2]) self.penStyleComboBox.addItem("twodash", pen) pen.setDashPattern([3, 2, 5, 2]) self.penStyleComboBox.addItem("twodash", pen) self.penStyleComboBox.addItem("blank", QPen(Qt.black, 2, Qt.NoPen)) delegate = LineStyleDelegate(self) self.penStyleComboBox.setItemDelegate(delegate) label = QLabel() if text is None: label.setText("Adjust line style") else: label.setText(text) hbox.addWidget(label) hbox.addWidget(self.penStyleComboBox) self.setLayout(hbox)
def shape(self): if self.__shape is None: path = self.path() pen = QPen(self.pen()) pen.setWidthF(max(pen.widthF(), 7.0)) pen.setStyle(Qt.SolidLine) self.__shape = stroke_path(path, pen) return self.__shape
def majorGridPen(): """ Reasonable default for major grid pen. @return QPen instance """ pen = QPen(QColor(170, 170, 170)) pen.setStyle(Qt.DashLine) return pen
def minorGridPen(): """ Reasonable default for minor grid pen. @return QPen instance """ pen = QPen(QColor(210, 210, 210)) pen.setStyle(Qt.DotLine) return pen
def paint(self, painter, option, widget): """ Draws a curve and then adds an arrow """ pen = QPen(QColor(0, 0, 0)) pen.setWidth(2) pen.setStyle(Qt.DotLine) self.setPen(pen) QGraphicsPathItem.paint(self, painter, option, widget) return
def __init__(self, font_loader, logger, opts, width=0, height=0, parent=None, x=0, y=0): QGraphicsRectItem.__init__(self, x, y, width, height, parent) self.font_loader, self.logger, self.opts = font_loader, logger, opts self.current_y, self.max_y, self.max_x = 0, height, width self.is_full = False pen = QPen() pen.setStyle(Qt.NoPen) self.setPen(pen) if not hasattr(self, "children"): self.children = self.childItems
def paint( self, painter, option, widget ): """ Draws a curve and then adds an arrow """ pen = QPen( QColor( 0, 0, 0) ) pen.setWidth( 2 ) pen.setStyle( Qt.DotLine ) self.setPen( pen ) QGraphicsPathItem.paint( self, painter, option, widget ) return
def make_pen(brush=Qt.black, width=1, style=Qt.SolidLine, cap_style=Qt.SquareCap, join_style=Qt.BevelJoin, cosmetic=False): pen = QPen(brush) pen.setWidth(width) pen.setStyle(style) pen.setCapStyle(cap_style) pen.setJoinStyle(join_style) pen.setCosmetic(cosmetic) return pen
def update_pen(pen, brush=None, width=None, style=None, cap_style=None, join_style=None, cosmetic=None): pen = QPen(pen) if brush is not None: pen.setBrush(QBrush(brush)) if width is not None: pen.setWidth(width) if style is not None: pen.setStyle(style) if cap_style is not None: pen.setCapStyle(cap_style) if join_style is not None: pen.setJoinStyle(join_style) return pen
def _drawMeasurements(self): if self.selNuc is None: return painter = QPainter() painter.begin(self.imagePixmap) painter.setRenderHint(QPainter.Antialiasing) rng_thick = 3 rng_thick *= self.pix_per_um if self.activeCh == "dna": # get nuclei boundary as a polygon nucb_qpoints_e = [ Qt.QPoint(x, y) for x, y in self.selNuc.buffer(rng_thick).exterior.coords ] nucb_qpoints_i = [ Qt.QPoint(x, y) for x, y in self.selNuc.exterior.coords ] painter.setPen(QPen(QBrush(QColor('white')), 3)) painter.drawPolygon(Qt.QPolygon(nucb_qpoints_i)) painter.drawPolygon(Qt.QPolygon(nucb_qpoints_e)) nucb_poly = Qt.QPolygon(nucb_qpoints_e).subtracted( Qt.QPolygon(nucb_qpoints_i)) brush = QBrush(QtCore.Qt.BDiagPattern) brush.setColor(QColor('white')) painter.setBrush(brush) painter.setPen(QPen(QBrush(QColor('transparent')), 0)) painter.drawPolygon(nucb_poly) elif self.activeCh == "act": nuc_pen = QPen(QBrush(QColor('red')), 2) nuc_pen.setStyle(QtCore.Qt.DotLine) painter.setPen(nuc_pen) for n in [e["boundary"] for e in self._boudaries]: # get nuclei boundary as a polygon nucb_qpoints = [Qt.QPoint(x, y) for x, y in n.exterior.coords] painter.drawPolygon(Qt.QPolygon(nucb_qpoints)) for me in self.measurements: painter.setPen( QPen( QBrush(QColor(me['c'])), 2 * self.pix_per_um if me == self.selectedLine else self.pix_per_um)) pts = [Qt.QPoint(x, y) for x, y in [me['ls0'], me['ls1']]] painter.drawLine(pts[0], pts[1]) painter.end()
def _set_pen ( self, pen ): from facets.ui.pen import Pen self._no_pen = (pen is None) if self._no_pen: pen = Qt.NoPen elif isinstance( pen, Pen ): qpen = QPen( pen.color ) qpen.setStyle( LineStyles[ pen.style ] ) qpen.setWidth( pen.width ) pen = qpen elif not isinstance( pen, QPen ): pen = color_for( pen ) self.graphics.setPen( pen )
def paint( self, painter, option, widget ): color = self.__settings.lineColor if self.penColor: color = self.penColor width = self.__settings.lineWidth if self.penWidth: width = self.penWidth pen = QPen( color ) pen.setWidth( width ) pen.setCapStyle( Qt.FlatCap ) pen.setJoinStyle( Qt.RoundJoin ) if self.penStyle: pen.setStyle( self.penStyle ) self.setPen( pen ) QGraphicsPathItem.paint( self, painter, option, widget ) return
def maj_affichage(self, event): nbAction = self.itk_active.intervention.nbAction self.semaine = self.largeur / self.nb_semaine semaine = self.semaine self.qp.begin(self) flag = 0 pen = QPen(Qt.black, 1, Qt.DotLine) self.qp.setPen(pen) while flag < self.nb_semaine + 1: posX = flag * semaine posY = 0 self.qp.drawLine(posX, posY, posX, posY + (nbAction + 1) * self.epAction) flag = flag + 1 pen.setStyle(Qt.SolidLine) self.qp.setPen(pen) flag = 0 while flag < nbAction: nomAction = self.itk_active.intervention.listeAction[ flag].action.nom pos_y = self.epAction / 2 + flag * self.epAction debut_action = semaine * ( self.itk_active.intervention.listeAction[flag].date + self.semaineAvant) long_action = semaine * self.itk_active.intervention.listeAction[ flag].duree self.qp.setBrush(QtGui.QColor(255, 80, 0, 160)) self.qp.drawRect(debut_action, pos_y, long_action, self.epAction) self.qp.setFont(QtGui.QFont('Decorative', 10)) self.qp.drawText(debut_action + 5, pos_y + 15, nomAction) flag = flag + 1 self.qp.end()
def __init__(self, font_loader, logger, opts, width=0, height=0, parent=None, x=0, y=0): QGraphicsRectItem.__init__(self, x, y, width, height, parent) self.font_loader, self.logger, self.opts = font_loader, logger, opts self.current_y, self.max_y, self.max_x = 0, height, width self.is_full = False pen = QPen() pen.setStyle(Qt.NoPen) self.setPen(pen) if not hasattr(self, 'children'): self.children = self.childItems
def __create_scene(self): # axis self.addItem(Axis(self.unit)) # pendulum pendulumPen = QPen(Qt.red, 3) pendulumBrush = QBrush(Qt.red) self.pole = self.addLine(QLineF(), pendulumPen) self.pend = self.addEllipse(QRectF(), pendulumPen, pendulumBrush) # reference position referencePen = QPen(Qt.black) referencePen.setStyle(Qt.DashLine) self.reference = self.addLine(QLineF(), referencePen) self.reference.setZValue(-1) # cart self.cart_width = 0.3 self.cart_height = 0.1 cartBrush = QBrush(Qt.blue) cartPen = QPen(Qt.blue, 5) self.cart = self.addRect(QRectF(), cartPen, cartBrush)
def paintEvent(self, event): painter = QPainter(self) painter.setRenderHint(painter.Antialiasing) tamanio = self.geometry().size() nuevoRect = QtCore.QRect(math.floor(self.anchoLinea / 2), math.floor(self.anchoLinea / 2), tamanio.width() - self.anchoLinea, tamanio.height() - self.anchoLinea) verde = QColor() verde.setNamedColor("#00FF00") amarillo = QColor() amarillo.setNamedColor("#FFFF00") rojo = QColor() rojo.setNamedColor("#FF0000") gradiente = QConicalGradient() gradiente.setCoordinateMode(QGradient.ObjectBoundingMode) gradiente.setAngle(60) gradiente.setColorAt(0, rojo) gradiente.setColorAt(0.25, amarillo) gradiente.setColorAt(0.50, verde) colorSeleccionado = QColor() colorSeleccionado.setNamedColor(self.colorDial) lapizTrazo = QPen() lapizTrazo.setStyle(QtCore.Qt.SolidLine) lapizTrazo.setWidth(self.anchoLinea) lapizTrazo.setBrush(colorSeleccionado) porcentaje = self.valor / float(self.maxValor - self.minValor) span = math.floor((self.finishAngle - self.startAngle) * porcentaje) painter.setPen(lapizTrazo) painter.drawArc(nuevoRect, self.startAngle * 16, span * 16) super(BKGauge, self).paintEvent(event)
def drawLines(self, qp): # mySize = self.size() pen = QPen(Qt.black, 2, Qt.SolidLine) myLocation = self.geometry() pen.setWidth(1) pen.setStyle(Qt.CustomDashLine) pen.setDashPattern([1, 2, 1, 2]) pen.setColor(QColor(55, 55, 55)) qp.setPen(pen) qp.drawLine(0, myLocation.height()*0.4+4, myLocation.width(), myLocation.height()*0.4+4) qp.drawLine(0, myLocation.height()*0.4+3, myLocation.width(), myLocation.height()*0.4+3) qp.drawLine(0, myLocation.height()*0.4+2, myLocation.width(), myLocation.height()*0.4+2) pen.setWidth(3) pen.setDashPattern([1, 1, 1, 1]) qp.setPen(pen) qp.drawLine(0, myLocation.height()*0.4-2, 5, myLocation.height()*0.4+3) qp.drawLine(0, myLocation.height()*0.4, 3, myLocation.height()*0.4+3) qp.drawLine(0, myLocation.height()*0.4+8, 5, myLocation.height()*0.4+3) qp.drawLine(0, myLocation.height()*0.4+6, 3, myLocation.height()*0.4+3) qp.drawLine(myLocation.width()-6, myLocation.height()*0.4+3, myLocation.width(), myLocation.height()*0.4-2) qp.drawLine(myLocation.width()-3, myLocation.height()*0.4+3, myLocation.width(), myLocation.height()*0.4) qp.drawLine(myLocation.width()-6, myLocation.height()*0.4+3, myLocation.width(), myLocation.height()*0.4+8) qp.drawLine(myLocation.width()-3, myLocation.height()*0.4+3, myLocation.width(), myLocation.height()*0.4+6)
def draw_colored_boxes(self, h): stick_colors = self.colors num_col_red = stick_colors.count("red") num_col_orange = stick_colors.count("orange") num_col_yellow = stick_colors.count("#EFDB00") num_col_gray = stick_colors.count("gray") colored_box_h = self.height + h - 5 if num_col_red: rect_red = QGraphicsRectItem(self.col_w * 0 - 1, self.coordY(self.ylim[1]) - 5, self.col_w * num_col_red, colored_box_h) qpen = QPen(QColor('red')) qpen.setWidth(1) qpen.setStyle( 5) # dash line : http://doc.qt.io/qt-4.8/qt.html#PenStyle-enum rect_red.setPen(qpen) rect_red.setBrush(QColor("#FFD1D1")) rect_red.setZValue(-1) rect_red.setParentItem(self.item) #rect_red.setOpacity(0.5) if num_col_orange: rect_orange = QGraphicsRectItem(self.col_w * num_col_red + 1, self.coordY(self.ylim[1]) - 5, self.col_w * num_col_orange - 2, colored_box_h) qpen = QPen(QColor('orange')) qpen.setWidth(1) qpen.setStyle( 5) # dash line : http://doc.qt.io/qt-4.8/qt.html#PenStyle-enum rect_orange.setPen(qpen) rect_orange.setBrush(QColor("#FFE3B0")) rect_orange.setZValue(-1) rect_orange.setParentItem(self.item) #rect_orange.setOpacity(0.5) if num_col_yellow: rect_yellow = QGraphicsRectItem( self.col_w * (num_col_orange + num_col_red) + 1, self.coordY(self.ylim[1]) - 5, self.col_w * num_col_yellow - 2, colored_box_h) qpen = QPen(QColor('#EFDB00')) qpen.setWidth(1) qpen.setStyle( 5) # dash line : http://doc.qt.io/qt-4.8/qt.html#PenStyle-enum rect_yellow.setPen(qpen) rect_yellow.setBrush(QColor("#FBFFA5")) rect_yellow.setZValue(-1) rect_yellow.setParentItem(self.item) #rect_yellow.setOpacity(0.5) if num_col_gray: rect_gray = QGraphicsRectItem( self.col_w * (num_col_orange + num_col_red + num_col_yellow) + 1, self.coordY(self.ylim[1]) - 5, self.col_w * num_col_gray, colored_box_h) qpen = QPen(QColor('gray')) qpen.setWidth(1) qpen.setStyle( 5) # dash line : http://doc.qt.io/qt-4.8/qt.html#PenStyle-enum rect_gray.setPen(qpen) rect_gray.setBrush(QColor("#E2E2E2")) rect_gray.setZValue(-1) rect_gray.setParentItem(self.item)
class View(QMainWindow, Ui_Dialog): """ Class View inherits the GUI generated by QtDesigner, and add customized actions """ def __init__(self, count, projectName, projectPath, nerfModel, fpgaOutput= [], userInput = [], parent = None): """ Constructor """ self.nerfModel = nerfModel # QMainWindow.__init__(self, parent, Qt.FramelessWindowHint) QMainWindow.__init__(self, parent) self.setStyleSheet("background-color: rgb(240, 235, 235); margin: 2px;") self.setWindowOpacity(0.85) # "QLineEdit { border-width: 20px;border-style: solid; border-color: darkblue; };") self.setupUi(self) self.projectName = projectName self.move(10+count*1050, 100) self.x = 200 self.pen = QPen() self.numPt = PIXEL_OFFSET self.isPause = False self.NUM_CHANNEL = len(fpgaOutput) self.setWindowTitle(projectPath) # Search all .bit files, make them selectable sys.path.append(projectPath) import os print projectPath for eachBitFile in glob(projectPath+"/*.bit"): # (filepath, filename) = os.path.split(eachBitFile) self.listWidget.addItem(eachBitFile) self.listWidget.setCurrentRow(0) self.listWidget.setStyleSheet("background-color: rgb(220, 235, 235); margin: 2px;") # Prepare # Prepare the widgets for each control channel to Fpga self.allUserInput = {} for (id, name, type, value) in userInput: if name != 'xxx': self.allUserInput[name] = CtrlChannel(hostDialog=self, id = id, name=name, type=type, value=value) # VERY important: dynamically connect SIGNAL to SLOT, with curried arguments for eachName, eachChan in self.allUserInput.iteritems(): fn = partial(onNewWireIn, self, eachName) # Customizing onNewWireIn() into channel-specific eachChan.doubleSpinBox.valueChanged.connect(fn) eachChan.doubleSpinBox.editingFinished.connect(fn) fn(eachChan.defaultValue) # Prepare the widgets for each Display channel self.allFpgaOutput = {} for i, (addr, name, visual_gain, type, color) in enumerate(fpgaOutput): if name != 'blank': self.allFpgaOutput[name] = ViewChannel(hostDialog=self, name=name, id=i, color = color, addr = addr, type = type) for eachName, eachChan in self.allFpgaOutput.iteritems(): fn = partial(onVisualSlider, self, eachName) # Customizing onNewWireIn() into channel-specific eachChan.slider.valueChanged.connect(fn) def individualWireIn(self, whichCh, value = -1): if value == -1: value = self.allUserInput[whichCh].doubleSpinBox.value() self.tellFpga(whichCh, value) #self.tellWhichFpga(0, whichCh, value) print "board", whichCh, " is now ", value def readParameters(self): for eachName, eachChan in self.allUserInput.iteritems(): val = eachChan.doubleSpinBox.value() print eachName, val self.individualWireIn(eachName, val) def plotData(self, data): from pylab import plot, show, subplot, title from scipy.io import savemat, loadmat import numpy as np dim = np.shape(data) if (data != []): forplot = np.array(data) i = 0 for eachName, eachChan in self.allFpgaOutput.iteritems(): subplot(dim[1], 1, i+1) plot(forplot[:, i]) title(eachName) i = i + 1 # show() timeTag = time.strftime("%Y%m%d_%H%M%S") savemat(self.projectName+"_"+timeTag+".mat", {eachName: forplot[:, i] for i, eachName in enumerate(self.allFpgaOutput)}) def savePipeOutData(self, pipeData): from pylab import plot, show, subplot, title from scipy.io import savemat, loadmat import numpy as np #forplot = np.array(pipeData) #print forplot timeTag = time.strftime("%Y%m%d_%H%M%S") savemat(self.projectName+"_pipeOut_"+timeTag+".mat", mdict={'pipeData': pipeData}) #savemat(self.projectName+"_pipeOut_"+timeTag+".mat", {forplot[]}mdict={'pipeData': pipeData}) def reportData(self): newData = [] newPipeData = [] for name, chan in self.allFpgaOutput.iteritems(): # Sweep thru channels coming out of Fpga #newData.append(max(-16777216, min(16777216, self.nerfModel.ReadFPGA(chan.addr, chan.type)))) # disable range limitation for spike raster newData.append(self.nerfModel.ReadFPGA(chan.addr, chan.type)) # newData.append(self.nerfModel.ReadFPGA(chan.addr, chan.type)) newPipeData.append(self.nerfModel.readFromPipe()) #BTPipeOut data return newData, newPipeData #pipedata has 128 elements def newDataIO(self, newData, newSpikeAll = []): for (name, ch), pt in zip(self.allFpgaOutput.iteritems(), newData): ch.data.appendleft(pt) ch.labelnum.setText("%4.6f" % pt) if ch.addr == 0x24 or ch.addr == 0x2C or ch.addr == 0x34 or ch.addr == 0x3A: # synaptic strength #self.udp_send(pt) # send udp val1 = self.allUserInput["flag_sync_inputs"].doubleSpinBox.value() #flag_sync_inputs val2 = self.allUserInput["block_neuron2"].doubleSpinBox.value() #block_neuron2 self.udp_send("%d,%d,%d,%d" % (pt, ch.addr, val1, val2)) #print pt self.spike_all = newSpikeAll def udp_send(self, val): UDP_IP = "192.168.0.122" #works in local wifi #UDP_IP = "192.168.0.1" UDP_PORT = 50000 MESSAGE = "Hello, from Eric!" # print val ## # print "UDP target IP:", UDP_IP # print "UDP target port:", UDP_PORT # print "message:", MESSAGE sock = socket.socket(socket.AF_INET, # Internet socket.SOCK_DGRAM) # UDP sock.sendto(val, (UDP_IP, UDP_PORT)) def onTimeOut(self): if (self.isPause): return size = self.size() self.update(QRect(self.x+ 1, 0,size.width() - self.x,size.height())) if (self.x < size.width() *0.7): # display line width adjustment self.x = self.x + 1 else: self.x = PIXEL_OFFSET def onChInGain(self): for ch in self.allFpgaOutput: ch.vscale = ch.slider.value()* 0.1 def paintEvent(self, e): """ Overload the standard paintEvent function """ #p = QPainter(self.graphicsView) ## our painter canvas = QPainter(self) ## our painter for name, ch in self.allFpgaOutput.iteritems(): if ch.type == "spike32": self.drawRaster(canvas, ch) else: self.drawPoints(canvas, ch) ## paint clipped graphics def drawRaster(self, gp, ch): size = self.size() # print size.height() winScale = size.height()*0.2 + size.height()*0.618/self.NUM_CHANNEL * 4; self.pen.setStyle(Qt.SolidLine) self.pen.setWidth(2) self.pen.setBrush(ch.color) self.pen.setCapStyle(Qt.RoundCap) self.pen.setJoinStyle(Qt.RoundJoin) gp.setPen(self.pen) yOffset = int(size.height()*0.20 + size.height()*0.818/self.NUM_CHANNEL * ch.id) #print yOffset, self.x bit_mask = 0x00000001 ## display the spike rasters #print ch.data[0] #spike_train = int(ch.data[0]) spike_train = ch.data[0] # print spike_train ,"spiketrain" for i in xrange(32): ## flexors if (bit_mask & spike_train) : ## Ia gp.drawLine(self.x-10, yOffset - 32 + i ,\ self.x+10, yOffset - 32 + i) bit_mask = bit_mask << 1 def drawRaster_old(self, gp): for spkid, i_mu in zip(self.spike_all, xrange(len(self.spike_all))): spikeSeq = unpack("%d" % len(spkid) + "b", spkid) size = self.size() winScale = size.height()*0.2 + size.height()*0.618/self.NUM_CHANNEL * 4; self.pen.setStyle(Qt.SolidLine) self.pen.setWidth(1) self.pen.setBrush(Qt.blue) self.pen.setCapStyle(Qt.RoundCap) self.pen.setJoinStyle(Qt.RoundJoin) gp.setPen(self.pen) ## display the spike rasters for i in xrange(0, len(spikeSeq), 2): neuronID = spikeSeq[i+1] rawspikes = spikeSeq[i] ## flexors if (rawspikes & 64) : ## Ia gp.drawLine(self.x-2,(winScale) - 22 + i ,\ self.x, (winScale) - 22 + i) if (rawspikes & 128) : ## MN # gp.drawPoint(self.x, (winScale) - 24 - (neuronID/4) ) gp.drawLine(self.x-2,(winScale) +22 - (neuronID/4)*0 + i_mu * 15 ,\ self.x, (winScale) + 26 - (neuronID/4) *0 + i_mu * 15) def drawPoints(self, qp, ch): """ Draw a line between previous and current data points. """ size = self.size() #for name, ch in allFpgaOutput.iteritems(): self.pen.setStyle(Qt.SolidLine) self.pen.setWidth(2) self.pen.setBrush(ch.color) self.pen.setCapStyle(Qt.RoundCap) self.pen.setJoinStyle(Qt.RoundJoin) qp.setPen(self.pen) yOffset = int(size.height()*0.20 + size.height()*0.818/self.NUM_CHANNEL * ch.id) y0 = yOffset - ch.data[1] * ch.vscale y1 = yOffset - ch.data[0] * ch.vscale # print "self.x=", self.x # print "y0=" , y0 # print "y1=" , y1 qp.drawLine(self.x - 1 , y0, self.x + 1 , y1) def tellFpga(self, chanName, newWireIn): ctrl = self.allUserInput[chanName] # Handle of the Tester channel ctrl.currValue = newWireIn if (ctrl.type == 'int32'): bitVal = convertType(floor(newWireIn), fromType = 'i', toType = 'I') elif (ctrl.type == 'float32'): bitVal = convertType(newWireIn, fromType = 'f', toType = 'I') # bitVal2 = convertType(0.0, fromType = 'f', toType = 'I') # print "bitval2, ", bitVal2 self.nerfModel.SendMultiPara(bitVal1 = bitVal, bitVal2=0, trigEvent = ctrl.id) def tellWhichFpga(self, xemNum, chanName, newWireIn): ctrl = self.allUserInput[chanName] # Handle of the Tester channel ctrl.currValue = newWireIn if (ctrl.type == 'int32'): bitVal = convertType(floor(newWireIn), fromType = 'i', toType = 'I') elif (ctrl.type == 'float32'): bitVal = convertType(newWireIn, fromType = 'f', toType = 'I') bitVal2 = convertType(0.0, fromType = 'f', toType = 'I') # velocity self.nerfModel[xemNum].SendMultiPara(bitVal1 = bitVal, bitVal2=bitVal2, trigEvent = ctrl.id) @pyqtSignature("QString") def on_comboBox_activated(self, p0): """ Slot documentation goes here. """ choice = p0 if choice == "waveform 1": # pipeInData = gen_ramp(T = [0.0, 0.1, 0.3, 1.0, 1.2, 2.0], L = [0.0, 0.0, 120000.0, 120000.0, 0.0, 0.0], FILT = False) # pipeInData = gen_ramp(T = [0.0, 0.1, 0.3, 1.0, 1.2, 2.0], L = [0.0, 0.0, 1.4, 1.4, 0.0, 0.0], FILT = False) pipeInData = gen_ramp(T = [0.0, 0.1, 0.2, 0.25, 0.3, 1.1, 1.2, 1.25, 1.3, 2.0], L = [0.8, 0.8, 1.4, 1.4, 0.8, 0.8, 1.4, 1.4, 0.8, 0.8], FILT = False) print "waveform 1 fed" # pipeInData = gen_sin(F = 1.0, AMP = 100.0, T = 2.0) elif choice == "waveform 2": print "waveform fed" # pipeInData = spike_train(firing_rate = 10) # pipeInData = gen_sin(F = 0.5, AMP = 5000.0, BIAS = 5001.0, T = 2.0) # pipeInData = gen_tri(T = 2.0) #pipeInData = gen_ramp(T = [0.0, 0.1, 0.9, 1.4, 1.9, 2.0], L = [0.5, 0.5, 1.5, 1.5, 0.5, 0.5], FILT = False) #pipeInData = gen_ramp(T = [0.0, 1.8, 2.0], L = [0.0, 30000.0, 0.0], FILT = False) #pipeInData = abs(gen_sin(F = 0.5, AMP = 17000.0, BIAS = 0.0, T = 2.0)) #big sine wave for training stdp #pipeInData[:] = [1 - x for x in pipeInData] #( 1 - pipeIndata) pipeInData = gen_rand(T=16.0, BIAS = 1500.0, AMP = 4400.0) # 16 seconds pipeInData2 = gen_rand(T=16.0, BIAS = 1500.0, AMP = 4400.0) # 16 seconds #pipeInData = gen_rand(BIAS = 3500.0, AMP = 400.0) # also works. input current bordered around threshold #pipeInData2 = gen_rand(BIAS = 3500.0, AMP = 400.0) elif choice == "waveform 3": # pipeInData = gen_tri() # pipeInData = spike_train(firing_rate = 1) print "waveform 3 fed" # pipeInData = gen_sin(F = 0.5, AMP = 0.15, BIAS = 1.15, T = 2.0) pipeInData = abs(gen_sin(F = 0.5, AMP = 17000.0, BIAS = 0.0, T = 2.0)) #big sine wave for training stdp #pipeInData = gen_ramp(T = [0.0, 0.1, 0.2, 0.8, 0.9, 2.0], L = [1.0, 1.0, 1.3, 1.3, 1.0, 1.0], FILT = False) # pipeInData = gen_ramp(T = [0.0, 0.4, 1.5, 1.55, 1.6, 2.0], L = [0, 0, 15000, 15000, 0, 0], FILT = False) # pipeInData = gen_ramp(T = [0.0, 0.2, 0.25, 1.75, 1.8, 2.0], L = [1.0, 1.0, 5000.0, 5000.0, 1.0, 1.0], FILT = False) # abrupt rise / fall # pipeInData = spike_train(firing_rate = 1000) self.nerfModel.SendPipe(pipeInData) self.nerfModel.SendPipe2(pipeInData2) @pyqtSignature("bool") def on_pushButton_toggled(self, checked): """ Pausing the plot, FPGA calculation still continues. """ self.isPause = checked @pyqtSignature("bool") def on_checkBox_clicked(self, checked): """ Auto-scale """ for name, ch in self.allFpgaOutput.iteritems(): ch.vscale = 50.0 / (max(ch.data)+1) @pyqtSignature("QListWidgetItem*") def on_listWidget_itemClicked(self, item): """ item burnt upon clicking the .bit file """ self.nerfModel.BurnBitFile(str(item.text())) # @pyqtSignature("QListWidgetItem*") # # def on_listWidget_itemActivated(self, item): # """ # Default selection of .bit file burnt without clicking burn button # """ # self.nerfModel.BurnBitFile(str(item.text())) # @pyqtSignature("bool") def on_checkBox_2_clicked(self, checked): """ Slot documentation goes here. """ newInput = checked print newInput self.nerfModel.SendButton(newInput, BUTTON_INPUT_FROM_TRIGGER) # # # @pyqtSignature("bool") # def on_pushButton_extraCN_clicked(self, checked): # """ # Slot documentation goes here. # """ # # dystonia # bitVal = convertType(0.0, fromType = 'f', toType = 'I') # if (checked): # self.nerfModel.SendMultiPara_TEMP(bitVal1 = bitVal, bitVal2=20000, bitVal3=10000, trigEvent = 9) # else: # self.nerfModel.SendMultiPara_TEMP(bitVal1 = bitVal, bitVal2=0, bitVal3=0, trigEvent = 9) # @pyqtSignature("bool") def on_checkBox_3_clicked(self, checked): """ cut_synapse1 """ newInput = checked print newInput self.nerfModel.SendButton(newInput, BUTTON_CUT_SYNAPSE1) @pyqtSignature("bool") def on_checkBox_4_clicked(self, checked): """ cut_synapse2 """ newInput = checked print newInput self.nerfModel.SendButton(newInput, BUTTON_CUT_SYNAPSE2)
class QtRenderer(Renderer): """An implementation of :class:`~renderer.Renderer` for PyQt4. This renderer will draw on any `QPaintDevice` """ def __init__(self, paint_device): """Creates a new renderer based on a QPaintDevice pd""" self._grid_pen = QPen(QColor(0x808080)) self._grid_pen.setStyle(Qt.DashLine) self._painter = None Renderer.__init__(self, paint_device) def set_canvas(self, canvas): """Tell the renderer to draw on canvas The type of canvas is implementation-dependent""" if self._painter is not None: self._painter.restore() self._painter.restore() self._painter.end() self._paintdevice = canvas self._painter = QPainter(canvas) self._painter.setRenderHint(QPainter.Antialiasing) # invert the y axis self._painter.scale(1,-1) self._painter.translate(0,-canvas.height()) Renderer.set_canvas(self,canvas) def _get_canvas_size(self,pd): """Get the canvas size tuple (width,height)""" return (pd.width(), pd.height()) def push_state(self): """Store the current state on the stack. Current state includes default pose, pen and brush""" ### FIXME store things self._painter.save() def pop_state(self): """Restore the last saved state from the stack The state includes default pose, pen and brush""" ### FIXME store things self._painter.restore() def _calculate_bounds(self): transform = self._painter.worldTransform().inverted()[0] xs,ys = zip( transform.map(0.0,0.0), transform.map(0.0,float(self.size[1])), transform.map(float(self.size[0]),float(self.size[1])), transform.map(float(self.size[0]),0.0) ) self._bounds = (min(xs), min(ys), max(xs), max(ys)) def _draw_grid(self): self.reset_pose() self._painter.setPen(self._grid_pen) xmin, ymin, xmax, ymax = self._bounds # Determine min/max x & y line indices: x_ticks = (int(xmin//self._grid_spacing), int(xmax//self._grid_spacing + 1)) y_ticks = (int(ymin//self._grid_spacing), int(ymax//self._grid_spacing + 1)) self._painter.drawLines( [QLineF(xmin, i * self._grid_spacing, xmax, i * self._grid_spacing) for i in range(*y_ticks)]) self._painter.drawLines( [QLineF(i * self._grid_spacing, ymin, i * self._grid_spacing, ymax) for i in range(*x_ticks)]) def scale(self, factor): """Scale drawing operations by factor To be implemented in subclasses.""" self._painter.scale(factor,factor) def rotate(self, angle): """Rotate canvas by angle (in radians) To be implemented in subclasses.""" self._painter.rotate(degrees(angle)) def translate(self, dx, dy): """Translate canvas by dx, dy To be implemented in subclasses.""" self._painter.translate(dx,dy) def clear_screen(self): """Erases the current screen with a white brush""" self._painter.save() self._painter.resetTransform() self.set_pen(0xFFFFFF) self.set_brush(0xFFFFFF) self.draw_rectangle(0,0,self.size[0],self.size[1]) self._painter.restore() Renderer.clear_screen(self) @staticmethod def __qcolor(color): """Returns qcolor for a given ARGB color""" c = QColor(color) if color > 0xFFFFFF: c.setAlpha((color >> 24) & 0xFF) return c def set_pen(self,color=0, thickness=0): """Sets the line color and thickness. Color is interpreted as 0xAARRGGBB.""" if color is None: self._painter.setPen(Qt.NoPen) else: self._painter.setPen(QPen(self.__qcolor(color),thickness)) def set_brush(self,color): """Sets the fill color. Color is interpreted as 0xAARRGGBB.""" if color is None: self._painter.setBrush(Qt.NoBrush) else: self._painter.setBrush(self.__qcolor(color)) def draw_polygon(self,points): """Draws a polygon. Expects a list of points as a list of tuples or as a numpy array.""" self._painter.drawPolygon(QPolygonF([QPointF(*point[:2]) for point in points])) def draw_ellipse(self, cx, cy, ra, rb = None): """Draws an ellipse.""" if rb is None: rb = ra self._painter.drawEllipse(QRectF(cx-ra,cy-ra,2*ra,2*rb)) def draw_rectangle(self, x, y, w, h): """Draws a rectangle.""" self._painter.drawRect(QRectF(x,y,w,h)) def draw_text(self, text, x, y, bgcolor = 0): """Draws a text string at the defined position.""" pass def draw_line(self, x1, y1, x2, y2): """Draws a line using the current pen from (x1,y1) to (x2,y2)""" self._painter.drawLine(QLineF(x1,y1,x2,y2))
class QtRenderer(Renderer): """An implementation of :class:`~renderer.Renderer` for PyQt4. This renderer will draw on any `QPaintDevice` """ def __init__(self, paint_device): """Creates a new renderer based on a QPaintDevice pd""" self._grid_pen = QPen(QColor(0x808080)) self._grid_pen.setStyle(Qt.DashLine) self._painter = None Renderer.__init__(self, paint_device) def set_canvas(self, canvas): """Tell the renderer to draw on canvas The type of canvas is implementation-dependent""" if self._painter is not None: self._painter.restore() self._painter.restore() self._painter.end() self._paintdevice = canvas self._painter = QPainter(canvas) self._painter.setRenderHint(QPainter.Antialiasing) # invert the y axis self._painter.scale(1, -1) self._painter.translate(0, -canvas.height()) Renderer.set_canvas(self, canvas) def _get_canvas_size(self, pd): """Get the canvas size tuple (width,height)""" return (pd.width(), pd.height()) def push_state(self): """Store the current state on the stack. Current state includes default pose, pen and brush""" ### FIXME store things self._painter.save() def pop_state(self): """Restore the last saved state from the stack The state includes default pose, pen and brush""" ### FIXME store things self._painter.restore() def _calculate_bounds(self): transform = self._painter.worldTransform().inverted()[0] xs, ys = zip(transform.map(0.0, 0.0), transform.map(0.0, float(self.size[1])), transform.map(float(self.size[0]), float(self.size[1])), transform.map(float(self.size[0]), 0.0)) self._bounds = (min(xs), min(ys), max(xs), max(ys)) def _draw_grid(self): self.reset_pose() self._painter.setPen(self._grid_pen) xmin, ymin, xmax, ymax = self._bounds # Determine min/max x & y line indices: x_ticks = (int(xmin // self._grid_spacing), int(xmax // self._grid_spacing + 1)) y_ticks = (int(ymin // self._grid_spacing), int(ymax // self._grid_spacing + 1)) self._painter.drawLines([ QLineF(xmin, i * self._grid_spacing, xmax, i * self._grid_spacing) for i in range(*y_ticks) ]) self._painter.drawLines([ QLineF(i * self._grid_spacing, ymin, i * self._grid_spacing, ymax) for i in range(*x_ticks) ]) def scale(self, factor): """Scale drawing operations by factor To be implemented in subclasses.""" self._painter.scale(factor, factor) def rotate(self, angle): """Rotate canvas by angle (in radians) To be implemented in subclasses.""" self._painter.rotate(degrees(angle)) def translate(self, dx, dy): """Translate canvas by dx, dy To be implemented in subclasses.""" self._painter.translate(dx, dy) def clear_screen(self): """Erases the current screen with a white brush""" self._painter.save() self._painter.resetTransform() self.set_pen(0xFFFFFF) self.set_brush(0xFFFFFF) self.draw_rectangle(0, 0, self.size[0], self.size[1]) self._painter.restore() Renderer.clear_screen(self) @staticmethod def __qcolor(color): """Returns qcolor for a given ARGB color""" c = QColor(color) if color > 0xFFFFFF: c.setAlpha((color >> 24) & 0xFF) return c def set_pen(self, color): """Sets the line color. Color is interpreted as 0xAARRGGBB.""" if color is None: self._painter.setPen(Qt.NoPen) else: self._painter.setPen(self.__qcolor(color)) def set_brush(self, color): """Sets the fill color. Color is interpreted as 0xAARRGGBB.""" if color is None: self._painter.setBrush(Qt.NoBrush) else: self._painter.setBrush(self.__qcolor(color)) def draw_polygon(self, points): """Draws a polygon. Expects a list of points as a list of tuples or as a numpy array.""" self._painter.drawPolygon( QPolygonF([QPointF(*point[:2]) for point in points])) def draw_ellipse(self, cx, cy, ra, rb=None): """Draws an ellipse.""" if rb is None: rb = ra self._painter.drawEllipse(QRectF(cx - ra, cy - ra, 2 * ra, 2 * rb)) def draw_rectangle(self, x, y, w, h): """Draws a rectangle.""" self._painter.drawRect(QRectF(x, y, w, h)) def draw_text(self, text, x, y, bgcolor=0): """Draws a text string at the defined position.""" pass def draw_line(self, x1, y1, x2, y2): """Draws a line using the current pen from (x1,y1) to (x2,y2)""" self._painter.drawLine(QLineF(x1, y1, x2, y2))
def getPenFromCmnd(self, peninfo): ''' Returns a QPen based on the information in the dictionary peninfo. A ValueError is raised if the value for the "style", "capstyle", or "joinstyle" key, if given, is not recognized. Recognized keys in the outline dictionary are: "color": color name or 24-bit RGB integer value (eg, 0xFF0088) "alpha": alpha value from 0 (transparent) to 255 (opaque) "width": pen width in points (1/72 inches); possibly further scaled by the width scaling factor "style": pen style name ("solid", "dash", "dot", "dashdot", "dashdotdot") "capstyle": pen cap style name ("square", "flat", "round") "joinstyle": pen join style name ("bevel", "miter", "round") ''' try: mycolor = self.getColorFromCmnd(peninfo) mypen = QPen(mycolor) except KeyError: mypen = QPen() try: penwidth = float(peninfo["width"]) penwidth *= self.__viewer.widthScalingFactor() mypen.setWidthF(penwidth) except KeyError: pass try: mystyle = peninfo["style"] if mystyle == "solid": mystyle = Qt.SolidLine elif mystyle == "dash": mystyle = Qt.DashLine elif mystyle == "dot": mystyle = Qt.DotLine elif mystyle == "dashdot": mystyle = Qt.DashDotLine elif mystyle == "dashdotdot": mystyle = Qt.DashDotDotLine else: raise ValueError( self.__viewer.tr( \ "Unknown pen style %1").arg(str(mystyle)) ) mypen.setStyle(mystyle) except KeyError: pass try: mystyle = peninfo["capstyle"] if mystyle == "square": mystyle = Qt.SquareCap elif mystyle == "flat": mystyle = Qt.FlatCap elif mystyle == "round": mystyle = Qt.RoundCap else: raise ValueError( self.__viewer.tr( \ "Unknown pen cap style %1").arg(str(mystyle)) ) mypen.setCapStyle(mystyle) except KeyError: pass try: mystyle = peninfo["joinstyle"] if mystyle == "bevel": mystyle = Qt.BevelJoin elif mystyle == "miter": mystyle = Qt.MiterJoin elif mystyle == "round": mystyle = Qt.RoundJoin else: raise ValueError( self.__viewer.tr( \ "Unknown pen join style %1").arg(str(mystyle)) ) mypen.setJoinStyle(mystyle) except KeyError: pass return mypen
class View(QMainWindow, Ui_Dialog): """ Class View inherits the GUI generated by QtDesigner, and add customized actions """ def __init__(self, parent=None, VIEWER_REFRESH_RATE=5, ch_all=[]): """ Constructor """ # QMainWindow.__init__(self, parent, Qt.FramelessWindowHint) QMainWindow.__init__(self, parent) self.setupUi(self) self.x = 200 self.pen = QPen() self.numPt = PIXEL_OFFSET self.isPause = False self.NUM_CHANNEL = len(CHIN_PARAM) # Create a gain_slider for each channel self.ch_all = [] for (addr, name, visual_gain, type, color), i in zip(CHIN_PARAM, xrange(NUM_CHANNEL)): exec interp( 'self.ch_#{name} = ViewChannel(hostDialog=self, name=name, id=i, color = color)' ) exec interp( 'self.connect(self.ch_#{name}.slider, SIGNAL("valueChanged(int)"), self.onChInGain)' ) exec interp('self.ch_all.append(self.ch_#{name})') #print self.ch_all self.timer = QTimer(self) self.connect(self.timer, SIGNAL("timeout()"), self.onTimeOut) self.timer.start(VIEWER_REFRESH_RATE) def newDataIO(self, newData, newSpikeAll=[]): for ch, pt in zip(self.ch_all, newData): ch.data.appendleft(pt) ch.label.setText("%4.2f" % pt) self.spike_all = newSpikeAll def onTimeOut(self): if (self.isPause): return size = self.size() self.update(QRect(self.x + 1, 0, size.width() - self.x, size.height())) if (self.x < size.width()): self.x = self.x + 1 else: self.x = PIXEL_OFFSET def onChInGain(self): for ch in self.ch_all: ch.vscale = ch.slider.value() * 0.1 def paintEvent(self, e): """ Overload the standard paintEvent function """ #p = QPainter(self.graphicsView) ## our painter canvas = QPainter(self) ## our painter self.drawPoints(canvas, self.ch_all) ## paint clipped graphics self.drawRaster(canvas) def drawRaster(self, gp): for spkid, i_mu in zip(self.spike_all, xrange(len(self.spike_all))): spikeSeq = unpack("%d" % len(spkid) + "b", spkid) size = self.size() winScale = size.height() * 0.2 + size.height( ) * 0.618 / self.NUM_CHANNEL * 4 self.pen.setStyle(Qt.SolidLine) self.pen.setWidth(1) self.pen.setBrush(Qt.blue) self.pen.setCapStyle(Qt.RoundCap) self.pen.setJoinStyle(Qt.RoundJoin) gp.setPen(self.pen) ## display the spike rasters for i in xrange(0, len(spikeSeq), 2): neuronID = spikeSeq[i + 1] rawspikes = spikeSeq[i] ## flexors if (rawspikes & 64): ## Ia gp.drawLine(self.x-2,(winScale) - 22 ,\ self.x, (winScale) - 22) if (rawspikes & 128): ## MN # gp.drawPoint(self.x, (winScale) - 24 - (neuronID/4) ) gp.drawLine(self.x-2,(winScale) +22 - (neuronID/4)*0 + i_mu * 15 ,\ self.x, (winScale) + 26 - (neuronID/4) *0 + i_mu * 15) def drawPoints(self, qp, ch_all): """ Draw a line between previous and current data points. """ size = self.size() for ch in ch_all: self.pen.setStyle(Qt.SolidLine) self.pen.setWidth(2) self.pen.setBrush(ch.color) self.pen.setCapStyle(Qt.RoundCap) self.pen.setJoinStyle(Qt.RoundJoin) qp.setPen(self.pen) yOffset = int(size.height() * 0.2 + size.height() * 0.618 / self.NUM_CHANNEL * ch.id) y0 = yOffset - ch.data[1] * ch.vscale y1 = yOffset - ch.data[0] * ch.vscale qp.drawLine(self.x - 1, y0, self.x + 1, y1) @pyqtSignature("bool") def on_pushButton_toggled(self, checked): """ Pausing the plot, FPGA calculation still continues. """ self.isPause = checked @pyqtSignature("bool") def on_checkBox_clicked(self, checked): """ Slot documentation goes here. """ # TODO: not implemented yet for ch in self.ch_all: ch.vscale = 50.0 / (max(ch.data) + 1)
class lineItem(QGraphicsLineItem): def __init__(self, x1, y1, x2, y2, parent=None, scene=None): QGraphicsItem.__init__(self, x1, y1, x2, y2, parent=parent, scene=scene) self.selec = False self.ctrlPressed = False self.selectWidth = 2.5 self.id = None self.parentSelected = False self.parentList = [] self.allItems = [] self.backupPen = self.pen() self.select_pen = QPen(QtCore.Qt.gray) self.select_pen.setStyle(QtCore.Qt.DotLine) self.select_pen.setWidthF(self.selectWidth) def setParents(self, parentList, allItems, id): self.parentList = [item for item in parentList if not item == self] self.parentSelected = False self.id = id self.allItems = allItems def getLayer(self): return self.layer def setLayer(self, name): self.layer = name def setOneRow(self, row1): self.tableItem1 = row1 self.haveTwoItems = False def setTwoRow(self, row1, row2): self.tableItem1 = row1 self.tableItem2 = row2 self.haveTwoItems = True def testprint(self): print "I'm printable!" def dragEnterEvent(self, event): print event def setPressed(self, key): if(key == QtCore.Qt.Key_Control): self.ctrlPressed = True def setUnPressed(self, key): if(key == QtCore.Qt.Key_Control): self.ctrlPressed = False def myIsSelected(self): return self.selec def isPressed(self): return self.ctrlPressed def setBackupPen(self, pen): self.backupPen = pen def getBackupPen(self): return self.backupPen def decreaseWidth(self): pen = self.pen() if(self.myIsSelected()): pen.setWidthF(pen.widthF() * 1 / 1.05) self.selectWidth = pen.widthF() self.backupPen.setWidthF(self.backupPen.widthF() * 1 / 1.05) else: pen.setWidthF(pen.widthF() * 1 / 1.05) self.selectWidth = self.selectWidth * 1 / 1.05 self.backupPen = pen self.setPen(pen) def increaseWidth(self): pen = self.pen() if(self.myIsSelected()): pen.setWidthF(pen.widthF() * 1.05) self.selectWidth = pen.widthF() self.backupPen.setWidthF(self.backupPen.widthF() * 1.05) else: pen.setWidthF(pen.widthF() * 1.05) self.selectWidth = self.selectWidth * 1.05 self.backupPen = pen self.setPen(pen) def setWidth(self, width): self.backupPen.setWidthF(width) self.setPen(self.backupPen) def selectParents(self, selection): for each in self.parentList: #each.setParentSelected(selection) each.setSelected(selection) def setParentSelected(self, value): self.parentSelected = value def mySetSelected(self, selection, first): if (selection): self.setPen(self.pen) self.setSelected(selection) if (first): self.selectParents(True) else: self.setPen(self.backupPen) self.setSelected(selection) if (first): self.selectParents(False) self.selec = selection def deselectRow(self): if(self.haveTwoItems): self.tableItem2.setSelected(False) self.tableItem1.setSelected(False) def selectRow(self): if(self.haveTwoItems): self.tableItem2.setSelected(self.selec) self.tableItem1.setSelected(self.selec) def getId(self): return self.id def hoverEnterEvent(self, event): print event def itemChange(self, event, value): if event == QGraphicsItem.ItemSelectedHasChanged: if self.isSelected(): self.setPen(self.select_pen) self.selec = True else: self.setPen(self.backupPen) self.selec = False return value
def maj_affichage(self, event): nbPlante = self.itk_active.plantation.nbPlante self.semaine = self.largeur / self.nb_semaine semaine = self.semaine self.qp.begin(self) flag = 0 pen = QPen(Qt.black, 1, Qt.DotLine) self.qp.setPen(pen) while flag < self.nb_semaine + 1: posX = flag * semaine posY = 0 self.qp.drawLine(posX, posY, posX, posY + (nbPlante + 1) * self.epPlante) flag = flag + 1 pen.setStyle(Qt.SolidLine) self.qp.setPen(pen) flag = 0 self.qp.setFont(QtGui.QFont('Decorative', 10)) while flag < self.nb_semaine + 1: posX = flag * semaine + 2 posY = 0 if flag < 53 + self.semaineAvant: num_semaine = flag - self.semaineAvant if flag > 52 + self.semaineAvant: num_semaine = flag - 52 - self.semaineAvant self.qp.drawText(posX, posY + 15, str(num_semaine)) flag = flag + 5 flag = 0 while flag < nbPlante: nomPlante = self.itk_active.plantation.listePlante[flag].plante.nom pos_y = self.epPlante + flag * self.epPlante debut_semis = semaine * ( self.itk_active.plantation.listePlante[flag].date_semis + self.semaineAvant) long_semis = semaine * self.itk_active.plantation.listePlante[ flag].plante.duree_pepiniere debut_croissance = debut_semis + long_semis long_croissance = (semaine * self.itk_active.plantation.listePlante[flag]. plante.duree_croissance) - long_semis debut_recolte = debut_croissance + long_croissance long_recolte = semaine * self.itk_active.plantation.listePlante[ flag].plante.duree_recolte self.qp.setBrush(QtGui.QColor(255, 80, 0, 160)) self.qp.drawRect(debut_semis, pos_y, long_semis, self.epPlante) self.qp.setBrush(QtGui.QColor(0, 255, 0)) self.qp.drawRect(debut_croissance, pos_y, long_croissance, self.epPlante) self.qp.setBrush(QtGui.QColor(255, 0, 0)) self.qp.drawRect(debut_recolte, pos_y, long_recolte, self.epPlante) self.qp.setFont(QtGui.QFont('Decorative', 10)) self.qp.drawText(debut_croissance + 5, pos_y + 15, nomPlante) flag = flag + 1 self.qp.end()
class View(QMainWindow, Ui_Dialog): """ Class View inherits the GUI generated by QtDesigner, and add customized actions """ def __init__(self, count, projectName, projectPath, nerfModel, fpgaOutput= [], userInput = [], parent = None): """ Constructor """ self.nerfModel = nerfModel # QMainWindow.__init__(self, parent, Qt.FramelessWindowHint) QMainWindow.__init__(self, parent) # self.setStyleSheet("background-color: rgb(240, 235, 235); margin: 2px;") self.setStyleSheet("background-color: white; margin: 2px;") self.setWindowOpacity(0.9) # "QLineEdit { border-width: 20px;border-style: solid; border-color: darkblue; };") self.setupUi(self) self.projectName = projectName self.move(10+count*500, 100) self.x = 200 self.pen = QPen() self.numPt = PIXEL_OFFSET self.isPause = False self.NUM_CHANNEL = len(fpgaOutput) self.setWindowTitle(projectPath) # Search all .bit files, make them selectable sys.path.append(projectPath) import os print projectPath for eachBitFile in sorted(glob(projectPath+"/*.bit"), key=os.path.getmtime, reverse=True): # (filepath, filename) = os.path.split(eachBitFile) self.listWidget.addItem(eachBitFile) self.listWidget.setCurrentRow(0) self.listWidget.setStyleSheet("background-color: rgb(220, 235, 235); margin: 2px;") # Prepare # Prepare the widgets for each control channel to Fpga self.allUserInput = {} for (id, name, type, value) in userInput: if name != 'xxx': self.allUserInput[name] = CtrlChannel(hostDialog=self, id = id, name=name, type=type, value=value) # VERY important: dynamically connect SIGNAL to SLOT, with curried arguments for eachName, eachChan in self.allUserInput.iteritems(): fn = partial(onNewWireIn, self, eachName) # Customizing onNewWireIn() into channel-specific eachChan.doubleSpinBox.valueChanged.connect(fn) eachChan.doubleSpinBox.editingFinished.connect(fn) fn(eachChan.defaultValue) # Prepare the widgets for each Display channel self.allFpgaOutput = {} for i, (addr, name, visual_gain, type, color) in enumerate(fpgaOutput): if name != 'xxx': self.allFpgaOutput[name] = ViewChannel(hostDialog=self, name=name, id=i, color = color, addr = addr, type = type) for eachName, eachChan in self.allFpgaOutput.iteritems(): fn = partial(onVisualSlider, self, eachName) # Customizing onNewWireIn() into channel-specific eachChan.slider.valueChanged.connect(fn) def individualWireIn(self, whichCh, value = -1): if value == -1: value = self.allUserInput[whichCh].doubleSpinBox.value() self.tellFpga(whichCh, value) #self.tellWhichFpga(0, whichCh, value) print "board", whichCh, " is now ", value def readParameters(self): for eachName, eachChan in self.allUserInput.iteritems(): if eachName != 'half_cnt': # don't mess with simulation speed val = eachChan.doubleSpinBox.value() self.individualWireIn(eachName, val) print eachName, val def plotData(self, data): from pylab import plot, show, subplot, title from scipy.io import savemat, loadmat import numpy as np dim = np.shape(data) if (data != []): forplot = np.array(data) i = 0 for eachName, eachChan in self.allFpgaOutput.iteritems(): subplot(dim[1], 1, i+1) plot(forplot[:, i]) title(eachName) i = i + 1 # show() timeTag = time.strftime("%Y%m%d_%H%M%S") savemat(self.projectName+"_"+timeTag+".mat", {eachName: forplot[:, i] for i, eachName in enumerate(self.allFpgaOutput)}) def reportData(self): newData = [] for name, chan in self.allFpgaOutput.iteritems(): # Sweep thru channels coming out of Fpga #newData.append(max(-16777216, min(16777216, self.nerfModel.ReadFPGA(chan.addr, chan.type)))) # disable range limitation for spike raster newData.append(self.nerfModel.ReadFPGA(chan.addr, chan.type)) # newData.append(self.nerfModel.ReadFPGA(chan.addr, chan.type)) return newData def newDataIO(self, newData, newSpikeAll = []): for (name, ch), pt in zip(self.allFpgaOutput.iteritems(), newData): ch.data.appendleft(pt) ch.label.setText("%4.6f" % pt) self.spike_all = newSpikeAll def onTimeOut(self): if (self.isPause): return size = self.size() self.update(QRect(self.x+ 1, 0,size.width() - self.x,size.height())) if (self.x < size.width() *0.7): # display line width adjustment self.x = self.x + 1 else: self.x = PIXEL_OFFSET def onChInGain(self): for ch in self.allFpgaOutput: ch.vscale = ch.slider.value()* 0.1 def paintEvent(self, e): """ Overload the standard paintEvent function """ #p = QPainter(self.graphicsView) ## our painter canvas = QPainter(self) ## our painter for name, ch in self.allFpgaOutput.iteritems(): if ch.type == "spike32": self.drawRaster(canvas, ch) else: self.drawPoints(canvas, ch) ## paint clipped graphics def drawRaster(self, gp, ch): size = self.size() winScale = size.height()*0.2 + size.height()*0.618/self.NUM_CHANNEL * 4; self.pen.setStyle(Qt.SolidLine) self.pen.setWidth(1) self.pen.setBrush(ch.color) self.pen.setCapStyle(Qt.RoundCap) self.pen.setJoinStyle(Qt.RoundJoin) gp.setPen(self.pen) yOffset = int(size.height()*0.20 + size.height()*0.818/self.NUM_CHANNEL * ch.id) bit_mask = 0x0000001 ## display the spike rasters # print ch.data[0] spike_train = int(ch.data[0]) #print spike_train for i in xrange(32): ## flexors if (bit_mask & spike_train) : ## Ia gp.drawLine(self.x-10, yOffset - 32 + i ,\ self.x+10, yOffset - 32 + i) bit_mask = bit_mask << 1 def drawRaster_old(self, gp): for spkid, i_mu in zip(self.spike_all, xrange(len(self.spike_all))): spikeSeq = unpack("%d" % len(spkid) + "b", spkid) size = self.size() winScale = size.height()*0.2 + size.height()*0.618/self.NUM_CHANNEL * 4; self.pen.setStyle(Qt.SolidLine) self.pen.setWidth(1) self.pen.setBrush(Qt.blue) self.pen.setCapStyle(Qt.RoundCap) self.pen.setJoinStyle(Qt.RoundJoin) gp.setPen(self.pen) ## display the spike rasters for i in xrange(0, len(spikeSeq), 2): neuronID = spikeSeq[i+1] rawspikes = spikeSeq[i] ## flexors if (rawspikes & 64) : ## Ia gp.drawLine(self.x-2,(winScale) - 22 + i ,\ self.x, (winScale) - 22 + i) if (rawspikes & 128) : ## MN # gp.drawPoint(self.x, (winScale) - 24 - (neuronID/4) ) gp.drawLine(self.x-2,(winScale) +22 - (neuronID/4)*0 + i_mu * 15 ,\ self.x, (winScale) + 26 - (neuronID/4) *0 + i_mu * 15) def drawPoints(self, qp, ch): """ Draw a line between previous and current data points. """ size = self.size() #for name, ch in allFpgaOutput.iteritems(): self.pen.setStyle(Qt.SolidLine) self.pen.setWidth(2) self.pen.setBrush(ch.color) self.pen.setCapStyle(Qt.RoundCap) self.pen.setJoinStyle(Qt.RoundJoin) qp.setPen(self.pen) yOffset = int(size.height()*0.20 + size.height()*0.818/self.NUM_CHANNEL * ch.id) y0 = yOffset - ch.data[1] * ch.vscale y1 = yOffset - ch.data[0] * ch.vscale # print "self.x=", self.x # print "y0=" , y0 # print "y1=" , y1 qp.drawLine(self.x - 1 , y0, self.x + 1 , y1) def tellFpga(self, chanName, newWireIn): ctrl = self.allUserInput[chanName] # Handle of the Tester channel ctrl.currValue = newWireIn if (ctrl.type == 'int32'): bitVal = convertType(floor(newWireIn), fromType = 'i', toType = 'I') elif (ctrl.type == 'float32'): bitVal = convertType(newWireIn, fromType = 'f', toType = 'I') # bitVal2 = convertType(0.0, fromType = 'f', toType = 'I') # print "bitval2, ", bitVal2 self.nerfModel.SendMultiPara(bitVal1 = bitVal, bitVal2=0, trigEvent = ctrl.id) def tellWhichFpga(self, xemNum, chanName, newWireIn): ctrl = self.allUserInput[chanName] # Handle of the Tester channel ctrl.currValue = newWireIn if (ctrl.type == 'int32'): bitVal = convertType(floor(newWireIn), fromType = 'i', toType = 'I') elif (ctrl.type == 'float32'): bitVal = convertType(newWireIn, fromType = 'f', toType = 'I') bitVal2 = convertType(0.0, fromType = 'f', toType = 'I') # velocity self.nerfModel[xemNum].SendMultiPara(bitVal1 = bitVal, bitVal2=bitVal2, trigEvent = ctrl.id) @pyqtSignature("QString") def on_comboBox_activated(self, p0): """ Slot documentation goes here. """ choice = p0 if choice == "waveform 1": # pipeInData = gen_ramp(T = [0.0, 0.1, 0.11, 0.65, 0.66, 16.0], L = [0.0, 0.0, 1.4, 1.4, 0.0, 0.0], FILT = False) # pipeInData = gen_ramp(T = [0.0, 0.1, 0.3, 1.0, 1.2, 2.0], L = [0.0, 0.0, 120000.0, 120000.0, 0.0, 0.0], FILT = False) # pipeInData = gen_ramp(T = [0.0, 0.1, 0.3, 1.0, 1.2, 2.0], L = [0.0, 0.0, 1.4, 1.4, 0.0, 0.0], FILT = False) # pipeInData = gen_ramp(T = [0.0, 0.1, 0.2, 0.3, 1.1, 1.2,1.3, 2.0], L = [0.8, 0.8, 1.4, 0.8, 0.8, 1.4, 0.8, 0.8], FILT = False) # 100ms rise # pipeInData = gen_ramp(T = [0.0, 0.1, 0.11, 0.12, 1.1, 1.11,1.12, 2.0], L = [0.8, 0.8, 1.4, 0.8, 0.8, 1.4, 0.8, 0.8], FILT = False) # 10ms rise # pipeInData = gen_ramp(T = [0.0, 0.1, 0.2, 0.3, 1.1, 1.2, 1.25, 1.3, 2.0], L = [0.8, 0.8, 1.4, 0.8, 0.8, 1.4, 1.4, 0.8, 0.8], FILT = False) pipeInData, self.gamma_dyn, self.gamma_sta = self.gen_from_file() self.individualWireIn('gamma_sta', float(self.gamma_sta)) self.individualWireIn('gamma_dyn', float(self.gamma_dyn)) """ up_pulse, dummy = gen_jerk(xi=1.0, xf = 1.5, T = 0.05) down_pulse, dummy = gen_jerk(xi=1.5, xf=1.0, T=0.05) flat_tail = np.array([1.0]*np.floor((1.0-0.1)*1024 + 1)) pipeInData = np.hstack((up_pulse, down_pulse, flat_tail, up_pulse, down_pulse, flat_tail)) print len(pipeInData) """ # pipeInData = np.append(p1, flat_tail) print pipeInData print "waveform 1 fed" # pipeInData = gen_sin(F = 1.0, AMP = 100.0, T = 2.0) elif choice == "waveform 2": print "waveform fed" # pipeInData = spike_train(firing_rate = 10) # pipeInData = gen_sin(F = 0.5, AMP = 5000.0, BIAS = 5001.0, T = 2.0) # pipeInData = gen_tri(T = 2.0) # pipeInData = gen_sin(F = 1.0, AMP = 0.15, BIAS = 1.15, T = 2.0) pipeInData = gen_ramp(T = [0.0, 0.1, 0.3, 0.8, 0.9, 2.0], L = [1.0, 1.0, 1.30, 1.30, 1.0, 1.0], FILT = False) # pipeInData = gen_ramp(T = [0.0, 0.1, 0.11, 0.51, 0.52, 1.0, 1.1, 1.11, 1.51, 1.52, 2.0], L = [0.7, 0.7, 1.5, 1.5, 0.7, 0.7, 0.7, 1.5, 1.5, 0.7, 0.7], FILT = False) # one second repeat # pipeInData = gen_ramp(T = [0.0, 0.1, 0.11, 0.51, 0.52, 1.0, 2.0], L = [0.7, 0.7, 1.5, 1.5, 0.7, 0.7, 0.7], FILT = False) # two second repeat # pipeInData = gen_ramp(T = [0.0, 0.1, 0.101, 0.121, 0.122, 1.0, 1.1, 1.101, 1.121, 1.122, 2.0], L = [0.8, 0.8, 1.5, 1.5, 0.8, 0.8, 0.8, 1.5, 1.5, 0.8, 0.8], FILT = False) # 20ms pulse for LLSR elif choice == "waveform 3": # pipeInData = gen_tri() # pipeInData = spike_train(firing_rate = 1) print "waveform 3 fed" #pipeInData = gen_sin(F = 0.5, AMP = 0.4, BIAS = 1.0, T = 2.0) self.j1List=[] self.j2List=[] self.j3List=[] self.j4List=[] self.j5List=[] self.j6List=[] # for line in open('/home/eric/Dropbox/MATLAB/WonJoon_code/matlab_wjsohn/posAllData.txt', "r").readlines(): # j1 , j2, j3, j4, j5, j6= line.split('\t') # j1 = float(j1) # j2 = float(j2) # print type(j1) # print j1 # self.j1List.append(j1) # # self.j2List.append(j2) # # self.j3List.append(j3) # # self.j4List.append(j4) # # self.j5List.append(j5) # # self.j6List.append(j6) # # for line in open('/home/eric/nerf_verilog_eric/source/py/1125_resampled/expt_rampnhold.gd_160.gs_160.rep_5.dev_fpga_resampled.txt', "r").readlines(): j1, j2 = line.split('\n') # j1 = line.splitlines() j1 = float(j1) print type(j1) print j1 self.j1List.append(j1) # # print self.j1List pipeInData_bf = gen_wave(L=self.j1List, FILT = False) pipeInData = [x for x in pipeInData_bf] #pipeInData = gen_ramp(T = [0.0, 0.1, 0.2, 0.8, 0.9, 2.0], L = [1.0, 1.0, 1.3, 1.3, 1.0, 1.0], FILT = False) # pipeInData = gen_ramp(T = [0.0, 0.4, 1.5, 1.55, 1.6, 2.0], L = [0, 0, 15000, 15000, 0, 0], FILT = False) # pipeInData = gen_ramp(T = [0.0, 0.2, 0.25, 1.75, 1.8, 2.0], L = [1.0, 1.0, 5000.0, 5000.0, 1.0, 1.0], FILT = False) # abrupt rise / fall # pipeInData = spike_train(firing_rate = 1000) self.nerfModel.SendPipe(pipeInData) @pyqtSignature("bool") def on_pushButton_toggled(self, checked): """ Pausing the plot, FPGA calculation still continues. """ self.isPause = checked @pyqtSignature("bool") def on_checkBox_clicked(self, checked): """ Auto-scale """ for name, ch in self.allFpgaOutput.iteritems(): ch.vscale = 50.0 / (max(ch.data)+1) @pyqtSignature("QListWidgetItem*") def on_listWidget_itemClicked(self, item): """ item burnt upon clicking the .bit file """ self.nerfModel.BurnBitFile(str(item.text())) # @pyqtSignature("QListWidgetItem*") # # def on_listWidget_itemActivated(self, item): # """ # Default selection of .bit file burnt without clicking burn button # """ # self.nerfModel.BurnBitFile(str(item.text())) # @pyqtSignature("bool") def on_checkBox_2_clicked(self, checked): """ Slot documentation goes here. """ newInput = checked print newInput self.nerfModel.SendButton(newInput, BUTTON_INPUT_FROM_TRIGGER) # # # @pyqtSignature("bool") # def on_pushButton_extraCN_clicked(self, checked): # """ # Slot documentation goes here. # """ # # dystonia # bitVal = convertType(0.0, fromType = 'f', toType = 'I') # if (checked): # self.nerfModel.SendMultiPara_TEMP(bitVal1 = bitVal, bitVal2=20000, bitVal3=10000, trigEvent = 9) # else: # self.nerfModel.SendMultiPara_TEMP(bitVal1 = bitVal, bitVal2=0, bitVal3=0, trigEvent = 9) # # @pyqtSignature("bool") # def on_checkBox_3_clicked(self, checked): # """ # healthy person setting. # """ # # TODO: not implemented yet # # if checked: # self.tellFpga('syn_Ia_gain', 10.0); # self.tellFpga('syn_CN_gain', 20.0); # self.tellFpga('syn_II_gain', 10.0); # else: # self.tellFpga('syn_Ia_gain', 30.0); # self.tellFpga('syn_CN_gain', 60.0); # self.tellFpga('syn_II_gain', 30.0); @pyqtSignature("bool") def on_checkBox_3_clicked(self, checked): """ Slot documentation goes here. """ if checked: # whichCh = 'syn_Ia_gain' # value = 10.0 # self.tellFpga(whichCh, value); # print "board", whichCh, " is now ", value # # whichCh = 'syn_CN_gain' # value = 50.0 # self.tellFpga(whichCh, value); # print "board", whichCh, " is now ", value # # whichCh = 'syn_II_gain' # value = 10.0 # self.tellFpga(whichCh, value); # print "board", whichCh, " is now ", value tempList = ['syn_Ia_gain','syn_CN_gain','syn_II_gain'] tempVal = [60.0,0.0,60.0] for eachPort, eachVal in zip(tempList, tempVal): self.tellFpga(eachPort, eachVal) print "board", eachPort, " is now ", eachVal else: # self.tellFpga('syn_Ia_gain', 60.0); # self.tellFpga('syn_CN_gain', 200.0); # self.tellFpga('syn_II_gain', 60.0); # tempList = ['syn_Ia_gain','syn_CN_gain','syn_II_gain'] tempVal = [60.0,200.0,60.0] for eachPort, eachVal in zip(tempList, tempVal): self.tellFpga(eachPort, eachVal) print "board", eachPort, " is now ", eachVal def gen_from_file(self): input_path = "/home/eric/nerf_verilog_eric/source/py/1125_resampled/" conditions = np.loadtxt('conditions.txt') gamma_dyn = int(conditions[0]) gamma_sta = int(conditions[1]) rep = int(conditions[2]) found = False for i in range(gamma_dyn, 220, 40): for j in range(gamma_sta, 220, 40): for k in range(rep,20): file_name = "expt_rampnhold.gd_" + str(i) + ".gs_" + str(j) + ".rep_" + str(k) + ".dev_fpga_resampled.txt" if path.exists(input_path + file_name): print file_name x = np.loadtxt(input_path + file_name) found = True file = open('conditions.txt', 'w') if k < 19: file.write(str(i) + '\n' + str(j) + '\n' + str(k + 1) + '\n') elif j < 200: file.write(str(i) + '\n' + str(j + 20) + '\n' + str(0) + '\n') else: file.write(str(i + 20) + '\n' + str(0) + '\n' + str(0) + '\n') file.close() if found: break rep = 0 if found: break rep = 0 gamma_sta = 0 if found: break return x, i, j
class QTerminalWidget(QWidget): # color scheme: normal_foreground, normal_background, inverse_foreground, inverse_background, cursor_color color_scheme_names = { "white" : 0, "amber" : 1, "green": 2 } color_schemes= [ [ QColor("#000"),QColor("#fff"), QColor(0xff,0xff, 0xff,0xc0) ], [ QColor("#000"), QColor("#ffbe00"), QColor(0xff, 0xbe, 0x00,0xc0) ], [ QColor("#000"), QColor("#18f018"), QColor(0x00,0xff,0x00,0xc0) ], ] # # Keymap keycodes # keymap = { Qt.Key_Backspace: chr(127), Qt.Key_Escape: chr(27), Qt.Key_AsciiTilde: "~~", Qt.Key_Up: "~A", Qt.Key_Down: "~B", Qt.Key_Left: "~D", Qt.Key_Right: "~C", Qt.Key_PageUp: "~1", Qt.Key_PageDown: "~2", Qt.Key_Home: "~H", Qt.Key_End: "~F", Qt.Key_Insert: "~3", Qt.Key_Delete: "~4", Qt.Key_F1: "~a", Qt.Key_F2: "~b", Qt.Key_F3: "~c", Qt.Key_F4: "~d", Qt.Key_F5: "~e", Qt.Key_F6: "~f", Qt.Key_F7: "~g", Qt.Key_F8: "~h", Qt.Key_F9: "~i", Qt.Key_F10: "~j", Qt.Key_F11: "~k", Qt.Key_F12: "~l", } def __init__(self,parent, font_name, font_size, font_height, w,h, colorscheme): super().__init__(parent) self.setFocusPolicy(Qt.WheelFocus) self.setAutoFillBackground(False) self.setAttribute(Qt.WA_OpaquePaintEvent, True) self.setCursor(Qt.IBeamCursor) font = QFont(font_name) font.setPixelSize(font_size) self.setFont(font) self._screen = [] self._text = [] self._transform= QTransform() self._cursor_col = 0 self._cursor_row = 0 self._dirty = False self._kbdfunc= None self._w=w self._h=h self._alt_sequence= False self._alt_seq_length=0 self._alt_seq_value=0 self._cursortype= CURSOR_OFF self._color_scheme=self.color_schemes[self.color_scheme_names[colorscheme]] self._cursor_color=self._color_scheme[2] self._cursor_char= 0x20 self._cursor_attr=-1 self._cursor_update=True self._blink= True self._blink_counter=0 self._cursor_rect = QRect(0, 0, self._char_width, self._char_height) self._cursor_polygon=QPolygon([QPoint(0,0+(self._char_height/2)), QPoint(0+(self._char_width*0.8),0+self._char_height), QPoint(0+(self._char_width*0.8),0+(self._char_height*0.67)), QPoint(0+self._char_width,0+(self._char_height*0.67)), QPoint(0+self._char_width,0+(self._char_height*0.33)), QPoint(0+(self._char_width*0.8),0+(self._char_height*0.33)), QPoint(0+(self._char_width*0.8),0), QPoint(0,0+(self._char_height/2))]) # # overwrite standard methods # def sizeHint(self): return QSize(self._w,self._h) def minimumSizeHint(self): return QSize(self._w,self._h) def resizeEvent(self, event): self.resize(self._w, self._h) def setkbdfunc(self,func): self._kbdfunc= func def setFont(self, font): super().setFont(font) self._update_metrics() # # overwrite standard events # # # Paint event, this event repaints the screen if the screen memory was changed or # paints the cursor # This event is fired if # - the terminal window becomes visible again # - after processing a new key in the termianl output queue # def paintEvent(self, event): painter = QPainter(self) if self._dirty: self._dirty = False self._paint_screen(painter) else: self._blink_counter+=1 if self._blink_counter > CURSOR_BLINK: self._blink_counter=0 self._paint_cursor(painter) event.accept() # # keyboard pressed event, process keys and put them into the keyboard input buffer # def keyPressEvent(self, event): text = event.text() key = event.key() modifiers = event.modifiers() alt = modifiers == Qt.AltModifier if (event.isAutoRepeat() and text) or self._kbdfunc == None: event.accept() return if alt: if not self._alt_sequence: self._alt_sequence= True self._alt_seq_length=0 self._alt_seq_value=0 if self._alt_seq_length==0: if key== Qt.Key_5: self._kbdfunc(ord("["),False) self._alt_sequence=False elif key== Qt.Key_6: self._kbdfunc(ord("]"),False) self._alt_sequence=False elif key== Qt.Key_7: self._kbdfunc(124,False) self._alt_sequence=False elif key== Qt.Key_8: self._kbdfunc(ord("{"),False) self._alt_sequence=False elif key== Qt.Key_9: self._kbdfunc(ord("}"),False) self._alt_sequence=False elif key== Qt.Key_L: self._kbdfunc(ord("@"),False) self._alt_sequence=False elif key== Qt.Key_I: self._kbdfunc(72,True) self._alt_sequence=False elif key== Qt.Key_1 or key == Qt.Key_0 : self._alt_seq_value+= key - Qt.Key_0 self._alt_seq_length+=1 else: self._alt_sequence=False else: if key >= Qt.Key_0 and key <= Qt.Key_9: self._alt_seq_value*=10 self._alt_seq_value+= key - Qt.Key_0 self._alt_seq_length+=1 if self._alt_seq_length == 3: if self._alt_seq_value <= 127: self._kbdfunc(self._alt_seq_value,False) self._alt_sequence= False else: self._alt_sequence= False elif text: t=ord(text) if t== 13: # lf -> Endline self._kbdfunc(82, True) elif t== 8: # BACK ESC Q self._kbdfunc(81, True) elif t== 127: # -CHAR ESC G self._kbdfunc(71, True) else: if t < 128: # > 127 generates BASIC KEYWORDS! self._kbdfunc(t, False) else: s = self.keymap.get(key) if s: if s == "~A": # cursor up ESC A self._kbdfunc(65,True) elif s == "~B": # cursor down ESC D self._kbdfunc(68, True) elif s == "~C": # cursor right ESC C self._kbdfunc(67,True) elif s == "~D": # cursor left ESC B self._kbdfunc(66, True) elif s == "~3": # I/R ESC H self._kbdfunc(72, True) elif s == "~4": # -CHAR ESC G self._kbdfunc(71,True) elif s == "~1": # Page Up ESC J self._kbdfunc(74,True) elif s == "~2": # Page Down ESC K self._kbdfunc(75, True) elif s == "~H": # Begin of line ESC E self._kbdfunc(69,True) elif s == "~F": # End of line ESC F self._kbdfunc(70, True) elif s == "~a": # F1 -> Attn ESC L self._kbdfunc(76, True) elif s == "~b": # F2 -> Run ESC M self._kbdfunc(77, True) elif s == "~c": # F3 -> Cmds ESC N self._kbdfunc(78, True) elif s == "~d": # F4 -> SST ESC P self._kbdfunc(80, True) elif s == "~e": # F5 -> -Line ESC I self._kbdfunc(73, True) elif s == "~f": # F6 -> LC ESC O self._kbdfunc(79, True) # elif s == "~g": # F7 -> Ctrl ESC S # self._kbdfunc(83, True) else: pass if (event.isAutoRepeat() and not text) : time.sleep(0.05) event.accept() # # internal methods # def _update_metrics(self): fm = self.fontMetrics() self._char_height = fm.height() self._char_width = fm.width("W") # # update cursor position # def _update_cursor_rect(self): if self._cursortype== CURSOR_OFF or (self._cursor_col== -1 and self._cursor_row==-1): return cx, cy = self._pos2pixel(self._cursor_col, self._cursor_row) self._transform.reset() self._transform.translate(cx,cy) self._cursor_update=True self._blink=True # # determine pixel position from rowl, column # def _pos2pixel(self, col, row): x = (col * self._char_width) y = row * self._char_height return x, y # # paint cursor # def _paint_cursor(self, painter): if self._cursortype== CURSOR_OFF or (self._cursor_col== -1 and self._cursor_row==-1): return # # cursor position was updated initialize some variables # if self._cursor_update: self._cursor_update= False self._blink_brush=QBrush(self._cursor_color) self._blink_pen=QPen(self._cursor_color) self._blink_pen.setStyle(0) if self._cursor_attr: self._noblink_background_color = self._color_scheme[1] self._noblink_foreground_color = self._color_scheme[0] else: self._noblink_background_color = self._color_scheme[0] self._noblink_foreground_color = self._color_scheme[1] self._noblink_brush = QBrush(self._noblink_background_color) # # blink on: draw cursor # if self._blink: painter.setPen(self._blink_pen) painter.setBrush(self._blink_brush) painter.setTransform(self._transform) if self._cursortype== CURSOR_OVERWRITE: painter.drawRect(self._cursor_rect) else: painter.drawPolygon(self._cursor_polygon) self._blink= not self._blink # # blink off: draw character # else: painter.setBrush(self._noblink_brush) painter.setTransform(self._transform) painter.setPen(QPen(self._noblink_background_color)) painter.drawRect(self._cursor_rect) painter.fillRect(self._cursor_rect, self._noblink_brush) painter.setPen(QPen(self._noblink_foreground_color)) painter.drawText(self._cursor_rect,Qt.AlignTop | Qt.AlignLeft,chr(self._cursor_char)) self._blink= not self._blink # # paint screen from screen memory # def _paint_screen(self, painter): # Speed hacks: local name lookups are faster vars().update(QColor=QColor, QBrush=QBrush, QPen=QPen, QRect=QRect) char_width = self._char_width char_height = self._char_height painter_drawText = painter.drawText painter_fillRect = painter.fillRect painter_setPen = painter.setPen align = Qt.AlignTop | Qt.AlignLeft color_scheme= self._color_scheme # set defaults background_color = color_scheme[1] foreground_color = color_scheme[0] brush = QBrush(background_color) painter_fillRect(self.rect(), brush) pen = QPen(foreground_color) painter_setPen(pen) y = 0 text = [] text_append = text.append for row, line in enumerate(self._screen): col = 0 text_line = "" for item in line: if isinstance(item, str): x = col * char_width length = len(item) rect = QRect( x, y, x + char_width * length, y + char_height) painter_fillRect(rect, brush) painter_drawText(rect, align, item) col += length text_line += item else: invers_flag = item if invers_flag: background_color = color_scheme[1] foreground_color = color_scheme[0] else: background_color = color_scheme[0] foreground_color = color_scheme[1] pen = QPen(foreground_color) brush = QBrush(background_color) painter_setPen(pen) painter.setBrush(brush) y += char_height text_append(text_line) self._text = text # # external interface # # set cursor type (insert, replace, off) # def setCursorType(self,t): self._cursortype=t #: # get terminal memory and cursor information # def update_term(self,dump): (self._cursor_col, self._cursor_row, self._cursor_char, self._cursor_attr), self._screen = dump() self._update_cursor_rect() self._dirty = True def setDirty(self): self._dirty= True
class View(QMainWindow, Ui_Dialog): """ Class View inherits the GUI generated by QtDesigner, and add customized actions """ def __init__(self, parent = None, \ NUM_CHANNEL = 1, DISPLAY_SCALING = [1.0], \ VIEWER_REFRESH_RATE = 5, CHANNEL_COLOR = [Qt.blue]): """ Constructor """ # QMainWindow.__init__(self, parent, Qt.FramelessWindowHint) QMainWindow.__init__(self, parent) self.setupUi(self) self.x = 200 ZERO_DATA = [0.0 for ix in xrange(NUM_CHANNEL)] self.data = self.data_1 = ZERO_DATA self.pen = QPen() self.numPt = INIT_X self.isPause = False self.NUM_CHANNEL = NUM_CHANNEL self.DISPLAY_SCALING = DISPLAY_SCALING self.PEN_COLOR = CHANNEL_COLOR self.timer = QTimer(self) #self.connect(timer, SIGNAL("timeout()"), self, SLOT("update()")) #self.connect(timer, SIGNAL("timeout()"), self, SLOT("timerEvent()")) self.connect(self.timer, SIGNAL("timeout()"), self.onTimeOut) self.connect(self.doubleSpinBox, SIGNAL("editingFinished()"), self.onCh0Gain) self.connect(self.doubleSpinBox_2, SIGNAL("editingFinished()"), self.onCh1Gain) self.connect(self.doubleSpinBox_3, SIGNAL("editingFinished()"), self.onCh2Gain) self.connect(self.doubleSpinBox_4, SIGNAL("editingFinished()"), self.onCh3Gain) self.connect(self.doubleSpinBox_5, SIGNAL("editingFinished()"), self.onCh4Gain) self.connect(self.doubleSpinBox_6, SIGNAL("editingFinished()"), self.onCh5Gain) self.connect(self.doubleSpinBox, SIGNAL("valueChanged(double)"), self.onCh0Gain) self.connect(self.doubleSpinBox_2, SIGNAL("valueChanged(double)"), self.onCh1Gain) self.connect(self.doubleSpinBox_3, SIGNAL("valueChanged(double)"), self.onCh2Gain) self.connect(self.doubleSpinBox_4, SIGNAL("valueChanged(double)"), self.onCh3Gain) self.connect(self.doubleSpinBox_5, SIGNAL("valueChanged(double)"), self.onCh4Gain) self.connect(self.doubleSpinBox_6, SIGNAL("valueChanged(double)"), self.onCh5Gain) self.doubleSpinBox.setValue(DISPLAY_SCALING[0]) self.doubleSpinBox_2.setValue(DISPLAY_SCALING[1]) self.doubleSpinBox_3.setValue(DISPLAY_SCALING[2]) self.doubleSpinBox_4.setValue(DISPLAY_SCALING[3]) self.doubleSpinBox_5.setValue(DISPLAY_SCALING[4]) self.doubleSpinBox_6.setValue(DISPLAY_SCALING[5]) self.timer.start(VIEWER_REFRESH_RATE) def newData(self, newData, newSpike=''): self.data_1 = self.data self.data = newData self.spike = newSpike def onTimeOut(self): if (self.isPause): return size = self.size() self.update(QRect(self.x, 0, size.width() - self.x + 3, size.height())) if (self.x < size.width()): self.x = self.x + 1 else: self.x = INIT_X def onCh0Gain(self): self.DISPLAY_SCALING[0] = self.doubleSpinBox.value() def onCh1Gain(self): self.DISPLAY_SCALING[1] = self.doubleSpinBox_2.value() def onCh2Gain(self): self.DISPLAY_SCALING[2] = self.doubleSpinBox_3.value() def onCh3Gain(self): self.DISPLAY_SCALING[3] = self.doubleSpinBox_4.value() def onCh4Gain(self): self.DISPLAY_SCALING[4] = self.doubleSpinBox_5.value() def onCh5Gain(self): self.DISPLAY_SCALING[5] = self.doubleSpinBox_6.value() def paintEvent(self, e): """ Overload the standard paintEvent function """ #p = QPainter(self.graphicsView) ## our painter p = QPainter(self) ## our painter #r1 = QRegion ( QRect(100,100,200,80), QRegion.Ellipse() ) r1 = QRegion(QRect(self.x - 2, 10, 5, 100)) r2 = QRegion(QRect(100, 120, 10, 30)) ## r2 = rectangular region r3 = QRegion(r1.intersect(r2)) ## r3 = intersection #p.setClipRegion( r1 ) ## set clip region self.drawPoints(p) ## paint clipped graphics self.drawRaster(p) def drawRaster(self, gp): spikeSeq = unpack("%d" % len(self.spike) + "b", self.spike) size = self.size() winScale = size.height() * 0.2 + size.height( ) * 0.618 / self.NUM_CHANNEL * 4 self.pen.setStyle(Qt.SolidLine) self.pen.setWidth(4) self.pen.setBrush(Qt.blue) self.pen.setCapStyle(Qt.RoundCap) self.pen.setJoinStyle(Qt.RoundJoin) gp.setPen(self.pen) ## display the spike rasters for i in xrange(0, len(spikeSeq), 2): neuronID = spikeSeq[i + 1] rawspikes = spikeSeq[i] ## flexors if (rawspikes & 64): ## Ia gp.drawLine(self.x-2,(winScale) - 22 ,\ self.x, (winScale) - 22) if (rawspikes & 128): ## MN # gp.drawPoint(self.x, (winScale) - 24 - (neuronID/4) ) gp.drawLine(self.x-3,(winScale) - 25 - (neuronID/4) ,\ self.x+3, (winScale) - 22 - (neuronID/4) ) def drawPoints(self, qp): """ Draw a line between previous and current data points. """ size = self.size() self.yOffset = [ size.height() * 0.2 + size.height() * 0.618 / self.NUM_CHANNEL * y for y in xrange(self.NUM_CHANNEL) ] for ix in xrange(self.NUM_CHANNEL): self.pen.setStyle(Qt.SolidLine) self.pen.setWidth(2) self.pen.setBrush(self.PEN_COLOR[ix]) self.pen.setCapStyle(Qt.RoundCap) self.pen.setJoinStyle(Qt.RoundJoin) qp.setPen(self.pen) qp.drawLine(self.x - 2, self.yOffset[ix] - \ self.data_1[ix] * self.DISPLAY_SCALING[ix],\ self.x , self.yOffset[ix] - \ self.data[ix] * self.DISPLAY_SCALING[ix]) # print "Yes!" # for i in range(self.numPt): # y = random.randint(1, size.height()-1) # #qp.drawPoint(x, y) # qp.drawLine(self.x, y, self.x + 3, y) @pyqtSignature("bool") def on_pushButton_toggled(self, checked): """ Pausing the plot, FPGA calculation still continues. """ self.isPause = checked @pyqtSignature("") def on_doubleSpinBox_editingFinished(self): """ Slot documentation goes here. """ print self.doubleSpinBox.value()
class View(QMainWindow, Ui_Dialog): """ Class View inherits the GUI generated by QtDesigner, and add customized actions """ def __init__(self, parent = None, \ NUM_CHANNEL = 1, DISPLAY_SCALING = [1.0], \ VIEWER_REFRESH_RATE = 5, CHANNEL_COLOR = [Qt.blue]): """ Constructor """ # QMainWindow.__init__(self, parent, Qt.FramelessWindowHint) QMainWindow.__init__(self, parent) self.setupUi(self) self.x = 200 ZERO_DATA = [0.0 for ix in xrange(NUM_CHANNEL)] self.data = self.data_1 = ZERO_DATA self.pen = QPen() self.numPt = INIT_X self.isPause = False self.NUM_CHANNEL = NUM_CHANNEL self.DISPLAY_SCALING = DISPLAY_SCALING self.PEN_COLOR = CHANNEL_COLOR self.timer = QTimer(self) #self.connect(timer, SIGNAL("timeout()"), self, SLOT("update()")) #self.connect(timer, SIGNAL("timeout()"), self, SLOT("timerEvent()")) self.connect(self.timer, SIGNAL("timeout()"), self.onTimeOut) self.connect(self.doubleSpinBox, SIGNAL("editingFinished()"), self.onCh0Gain) self.connect(self.doubleSpinBox_2, SIGNAL("editingFinished()"), self.onCh1Gain) self.connect(self.doubleSpinBox_3, SIGNAL("editingFinished()"), self.onCh2Gain) self.connect(self.doubleSpinBox_4, SIGNAL("editingFinished()"), self.onCh3Gain) self.connect(self.doubleSpinBox_5, SIGNAL("editingFinished()"), self.onCh4Gain) self.connect(self.doubleSpinBox_6, SIGNAL("editingFinished()"), self.onCh5Gain) self.connect(self.doubleSpinBox, SIGNAL("valueChanged(double)"), self.onCh0Gain) self.connect(self.doubleSpinBox_2, SIGNAL("valueChanged(double)"), self.onCh1Gain) self.connect(self.doubleSpinBox_3, SIGNAL("valueChanged(double)"), self.onCh2Gain) self.connect(self.doubleSpinBox_4, SIGNAL("valueChanged(double)"), self.onCh3Gain) self.connect(self.doubleSpinBox_5, SIGNAL("valueChanged(double)"), self.onCh4Gain) self.connect(self.doubleSpinBox_6, SIGNAL("valueChanged(double)"), self.onCh5Gain) self.doubleSpinBox.setValue(DISPLAY_SCALING[0]) self.doubleSpinBox_2.setValue(DISPLAY_SCALING[1]) self.doubleSpinBox_3.setValue(DISPLAY_SCALING[2]) self.doubleSpinBox_4.setValue(DISPLAY_SCALING[3]) self.doubleSpinBox_5.setValue(DISPLAY_SCALING[4]) self.doubleSpinBox_6.setValue(DISPLAY_SCALING[5]) self.timer.start(VIEWER_REFRESH_RATE) def newData(self, newData): self.data_1 = self.data self.data = newData def onTimeOut(self): if (self.isPause): return size = self.size() self.update(QRect(self.x, 0,size.width() - self.x + 1,size.height())) if (self.x < size.width()): self.x = self.x + 1 else: self.x = INIT_X def onCh0Gain(self): self.DISPLAY_SCALING[0] = self.doubleSpinBox.value() def onCh1Gain(self): self.DISPLAY_SCALING[1] = self.doubleSpinBox_2.value() def onCh2Gain(self): self.DISPLAY_SCALING[2] = self.doubleSpinBox_3.value() def onCh3Gain(self): self.DISPLAY_SCALING[3] = self.doubleSpinBox_4.value() def onCh4Gain(self): self.DISPLAY_SCALING[4] = self.doubleSpinBox_5.value() def onCh5Gain(self): self.DISPLAY_SCALING[5] = self.doubleSpinBox_6.value() def paintEvent(self, e): """ Overload the standard paintEvent function """ #p = QPainter(self.graphicsView) ## our painter p = QPainter(self) ## our painter #r1 = QRegion ( QRect(100,100,200,80), QRegion.Ellipse() ) r1 = QRegion ( QRect(self.x,10,5,100)) r2 = QRegion ( QRect(100,120,10,30) ) ## r2 = rectangular region r3 = QRegion (r1.intersect( r2 )) ## r3 = intersection #p.setClipRegion( r1 ) ## set clip region self.drawPoints(p) ## paint clipped graphics # qp = QPainter() # qp.begin(self) # self.drawPoints(qp) # qp.end() def drawPoints(self, qp): """ Draw a line between previous and current data points. """ # pen = self.pen size = self.size() self.yOffset = [size.height()*0.2 + size.height()*0.618/self.NUM_CHANNEL * y for y in xrange(self.NUM_CHANNEL) ] for ix in xrange(self.NUM_CHANNEL): self.pen.setStyle(Qt.SolidLine) self.pen.setWidth(2) self.pen.setBrush(self.PEN_COLOR[ix]) self.pen.setCapStyle(Qt.RoundCap) self.pen.setJoinStyle(Qt.RoundJoin) qp.setPen(self.pen) qp.drawLine(self.x - 2, self.yOffset[ix] - \ self.data_1[ix] * self.DISPLAY_SCALING[ix],\ self.x , self.yOffset[ix] - \ self.data[ix] * self.DISPLAY_SCALING[ix]) # print "Yes!" # for i in range(self.numPt): # y = random.randint(1, size.height()-1) # #qp.drawPoint(x, y) # qp.drawLine(self.x, y, self.x + 3, y) @pyqtSignature("bool") def on_pushButton_toggled(self, checked): """ Pausing the plot, FPGA calculation still continues. """ self.isPause = checked @pyqtSignature("") def on_doubleSpinBox_editingFinished(self): """ Slot documentation goes here. """ print self.doubleSpinBox.value()
class lineItem(QGraphicsLineItem): def __init__(self, x1, y1, x2, y2, parent=None, scene=None): QGraphicsItem.__init__(self, x1, y1, x2, y2, parent=parent, scene=scene) self.selec = False self.ctrlPressed = False self.selectWidth = 2.5 self.id = None self.parentSelected = False self.parentList = [] self.allItems = [] self.backupPen = self.pen() self.select_pen = QPen(QtCore.Qt.gray) self.select_pen.setStyle(QtCore.Qt.DotLine) self.select_pen.setWidthF(self.selectWidth) def setParents(self, parentList, allItems, id): self.parentList = [item for item in parentList if not item == self] self.parentSelected = False self.id = id self.allItems = allItems def getLayer(self): return self.layer def setLayer(self, name): self.layer = name def setOneRow(self, row1): self.tableItem1 = row1 self.haveTwoItems = False def setTwoRow(self, row1, row2): self.tableItem1 = row1 self.tableItem2 = row2 self.haveTwoItems = True def testprint(self): print "I'm printable!" def dragEnterEvent(self, event): print event def setPressed(self, key): if (key == QtCore.Qt.Key_Control): self.ctrlPressed = True def setUnPressed(self, key): if (key == QtCore.Qt.Key_Control): self.ctrlPressed = False def myIsSelected(self): return self.selec def isPressed(self): return self.ctrlPressed def setBackupPen(self, pen): self.backupPen = pen def getBackupPen(self): return self.backupPen def decreaseWidth(self): pen = self.pen() if (self.myIsSelected()): pen.setWidthF(pen.widthF() * 1 / 1.05) self.selectWidth = pen.widthF() self.backupPen.setWidthF(self.backupPen.widthF() * 1 / 1.05) else: pen.setWidthF(pen.widthF() * 1 / 1.05) self.selectWidth = self.selectWidth * 1 / 1.05 self.backupPen = pen self.setPen(pen) def increaseWidth(self): pen = self.pen() if (self.myIsSelected()): pen.setWidthF(pen.widthF() * 1.05) self.selectWidth = pen.widthF() self.backupPen.setWidthF(self.backupPen.widthF() * 1.05) else: pen.setWidthF(pen.widthF() * 1.05) self.selectWidth = self.selectWidth * 1.05 self.backupPen = pen self.setPen(pen) def setWidth(self, width): self.backupPen.setWidthF(width) self.setPen(self.backupPen) def selectParents(self, selection): for each in self.parentList: #each.setParentSelected(selection) each.setSelected(selection) def setParentSelected(self, value): self.parentSelected = value def mySetSelected(self, selection, first): if (selection): self.setPen(self.pen) self.setSelected(selection) if (first): self.selectParents(True) else: self.setPen(self.backupPen) self.setSelected(selection) if (first): self.selectParents(False) self.selec = selection def deselectRow(self): if (self.haveTwoItems): self.tableItem2.setSelected(False) self.tableItem1.setSelected(False) def selectRow(self): if (self.haveTwoItems): self.tableItem2.setSelected(self.selec) self.tableItem1.setSelected(self.selec) def getId(self): return self.id def hoverEnterEvent(self, event): print event def itemChange(self, event, value): if event == QGraphicsItem.ItemSelectedHasChanged: if self.isSelected(): self.setPen(self.select_pen) self.selec = True else: self.setPen(self.backupPen) self.selec = False return value
class View(QMainWindow, Ui_Dialog): """ Class View inherits the GUI generated by QtDesigner, and add customized actions """ def __init__(self, parent = None, VIEWER_REFRESH_RATE = 5, ch_all = []): """ Constructor """ # QMainWindow.__init__(self, parent, Qt.FramelessWindowHint) QMainWindow.__init__(self, parent) self.setupUi(self) self.x = 200 self.pen = QPen() self.numPt = PIXEL_OFFSET self.isPause = False self.NUM_CHANNEL = len(CHIN_PARAM) # Create a gain_slider for each channel self.ch_all = [] for (addr, name, visual_gain, type, color), i in zip(CHIN_PARAM, xrange(NUM_CHANNEL)): exec interp('self.ch_#{name} = ViewChannel(hostDialog=self, name=name, id=i, color = color)') exec interp('self.connect(self.ch_#{name}.slider, SIGNAL("valueChanged(int)"), self.onChInGain)') exec interp('self.ch_all.append(self.ch_#{name})') #print self.ch_all self.timer = QTimer(self) self.connect(self.timer, SIGNAL("timeout()"), self.onTimeOut) self.timer.start(VIEWER_REFRESH_RATE) def newDataIO(self, newData, newSpikeAll = []): for ch, pt in zip(self.ch_all, newData): ch.data.appendleft(pt) ch.label.setText("%4.2f" % pt) self.spike_all = newSpikeAll def onTimeOut(self): if (self.isPause): return size = self.size() self.update(QRect(self.x+ 1, 0,size.width() - self.x,size.height())) if (self.x < size.width()): self.x = self.x + 1 else: self.x = PIXEL_OFFSET def onChInGain(self): for ch in self.ch_all: ch.vscale = ch.slider.value()* 0.1 def paintEvent(self, e): """ Overload the standard paintEvent function """ #p = QPainter(self.graphicsView) ## our painter canvas = QPainter(self) ## our painter self.drawPoints(canvas, self.ch_all) ## paint clipped graphics # self.drawRaster(canvas) # def drawRaster(self, gp): # for spkid, i_mu in zip(self.spike_all, xrange(len(self.spike_all))): # spikeSeq = unpack("%d" % len(spkid) + "b", spkid) # # size = self.size() # winScale = size.height()*0.2 + size.height()*0.618/self.NUM_CHANNEL * 4; # self.pen.setStyle(Qt.SolidLine) # self.pen.setWidth(1) # self.pen.setBrush(Qt.blue) # self.pen.setCapStyle(Qt.RoundCap) # self.pen.setJoinStyle(Qt.RoundJoin) # gp.setPen(self.pen) # ## display the spike rasters # for i in xrange(0, len(spikeSeq), 2): # neuronID = spikeSeq[i+1] # rawspikes = spikeSeq[i] # ## flexors # if (rawspikes & 64) : ## Ia # gp.drawLine(self.x-2,(winScale) - 22 ,\ # self.x, (winScale) - 22) # if (rawspikes & 128) : ## MN # # gp.drawPoint(self.x, (winScale) - 24 - (neuronID/4) ) # gp.drawLine(self.x-2,(winScale) +22 - (neuronID/4)*0 + i_mu * 15 ,\ # self.x, (winScale) + 26 - (neuronID/4) *0 + i_mu * 15) def drawPoints(self, qp, ch_all): """ Draw a line between previous and current data points. """ size = self.size() for ch in ch_all: self.pen.setStyle(Qt.SolidLine) self.pen.setWidth(2) self.pen.setBrush(ch.color) self.pen.setCapStyle(Qt.RoundCap) self.pen.setJoinStyle(Qt.RoundJoin) qp.setPen(self.pen) yOffset = int(size.height()*0.2 + size.height()*0.618/self.NUM_CHANNEL * ch.id) y0 = yOffset - ch.data[1] * ch.vscale y1 = yOffset - ch.data[0] * ch.vscale qp.drawLine(self.x - 1 , y0, self.x + 1 , y1) @pyqtSignature("bool") def on_pushButton_toggled(self, checked): """ Pausing the plot, FPGA calculation still continues. """ self.isPause = checked @pyqtSignature("bool") def on_checkBox_clicked(self, checked): """ Slot documentation goes here. """ # TODO: not implemented yet for ch in self.ch_all: ch.vscale = 50.0 / (max(ch.data)+1)