def paint_pieces(self, painter): # for tile in [t for t in Board.TILES if t.piece is not None]: for tile in [t for t in self.tiles if t.piece is not None]: if tile.piece.player == 'B': painter.setBrush(QBrush(Qt.black)) painter.setPen(QPen(Qt.black, 0.1 * self.r_hex)) painter.drawPath(self.piece_circle_path(tile)) painter.setBrush(QBrush(Qt.white)) pen = QPen(Qt.white, 0.12 * sqrt(3) * self.r_hex) pen.setCapStyle(Qt.RoundCap) painter.setPen(pen) painter.drawPath(self.piece_sign_path(tile)) elif tile.piece.player == 'W': painter.setBrush(QBrush(Qt.white)) painter.setPen(QPen(Qt.black, 0.1 * self.r_hex)) painter.drawPath(self.piece_circle_path(tile)) painter.setBrush(QBrush(Qt.black)) pen = QPen(Qt.black, 0.12 * sqrt(3) * self.r_hex) pen.setCapStyle(Qt.RoundCap) painter.setPen(pen) painter.drawPath(self.piece_sign_path(tile))
def __drawLine(self, painter, graph, width, height): path = QPainterPath() try: day = graph[0][0].day value = graph[0][0].data(self.__index) (x, y) = self.__getCoordinates(width, height, day, value) path.moveTo(x, y) except IndexError: pass for pos in range(1, len(graph[0])): point = graph[0][pos] day = point.day value = point.data(self.__index) (x, y) = self.__getCoordinates(width, height, day, value) path.lineTo(x, y) pen = QPen() pen.setColor(QColor(graph[2])) pen.setWidth(3) pen.setCapStyle(Qt.RoundCap); pen.setJoinStyle(Qt.RoundJoin); painter.setPen(pen) painter.setBrush(Qt.NoBrush) painter.drawPath(path)
def mouseMoveEvent(self, event): if event.buttons() & Qt.LeftButton: downPos = event.buttonDownPos(Qt.LeftButton) if not self.__tmpLine and self.__dragStartItem and \ (downPos - event.pos()).manhattanLength() > \ QApplication.instance().startDragDistance(): # Start a line drag line = QGraphicsLineItem(self) start = self.__dragStartItem.boundingRect().center() start = self.mapFromItem(self.__dragStartItem, start) line.setLine(start.x(), start.y(), event.pos().x(), event.pos().y()) pen = QPen(Qt.black, 4) pen.setCapStyle(Qt.RoundCap) line.setPen(pen) line.show() self.__tmpLine = line if self.__tmpLine: # Update the temp line line = self.__tmpLine.line() line.setP2(event.pos()) self.__tmpLine.setLine(line) QGraphicsWidget.mouseMoveEvent(self, event)
def __init__(self, parent, pos, angle, pit=False): QGraphicsItemGroup.__init__(self, parent) AbstractSector.__init__(self, pos, angle) self.setZValue(3) self.black = QGraphicsPathItem(self) self.white = QGraphicsPathItem(self) start = 3 * (_trackWidth / 2) end = -start - abs(_pitDistance if pit else 0) rowdelta = _trackWidth / 4 for item, y in [(self.black, -rowdelta), (self.white, rowdelta)]: item.setCacheMode(QGraphicsPathItem.DeviceCoordinateCache) self.addToGroup(item) path = QPainterPath() path.moveTo(start, y) path.lineTo(end, y) path.moveTo(end, -y) path.lineTo(start, -y) item.setPath(path) pen = QPen(Qt.black, _trackWidth / 2) pen.setCapStyle(Qt.FlatCap) pen.setDashPattern([1, 1]) self.black.setPen(QPen(pen)) pen.setColor(Qt.white) self.white.setPen(pen)
def paintEvent(self, event): painter = QPainter(self) minSize = min(self.rect().width(), self.rect().height()) myRect = QRect(self.rect().x(), self.rect().y(), minSize, minSize) painter.drawPixmap(myRect, self.backgroundPic, self.backgroundPic.rect()) pen = QPen() pen.setCapStyle(Qt.RoundCap) pen.setWidthF(4.0) pen.setColor(Qt.red) pen.setJoinStyle(Qt.RoundJoin) painter.setPen(pen) spacing = 40 contentRect = myRect.adjusted(spacing, spacing, -spacing, -spacing) valueInPercent = (self.m_value - self.m_minimum) / (self.m_maximum - self.m_minimum) math_pi = 3.14159265358979323846 degree = (self.m_startAngle + 90) - valueInPercent * 2.0 * self.m_startAngle degree = degree * math_pi / 180.0 radius = (contentRect.width() - spacing * 0.5) * 0.5 vec = QPoint(radius * math.cos(degree), radius * -math.sin(degree)) painter.drawLine(contentRect.center(), contentRect.center() + vec)
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 __init__(self, id_pair, painter_path, initial_pen=None): super(SingleEdgeItem, self).__init__() self.parent = None # Should be initialized with set_parent() self.id_pair = id_pair if not initial_pen: initial_pen = QPen() initial_pen.setCosmetic(True) initial_pen.setCapStyle(Qt.RoundCap) initial_pen.setColor(Qt.white) initial_pen.setWidth(3) self.setPen(initial_pen) self.setPath(painter_path)
def __init__(self, id_pair, painter_path, initial_pen=None): super( SingleEdgeItem, self ).__init__() self.parent = None # Should be initialized with set_parent() self.id_pair = id_pair if not initial_pen: initial_pen = QPen() initial_pen.setCosmetic(True) initial_pen.setCapStyle(Qt.RoundCap) initial_pen.setColor(Qt.white) initial_pen.setWidth(3) self.setPen(initial_pen) self.setPath(painter_path)
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 addLink(self, output, input): """ Add a link between `output` (:class:`OutputSignal`) and `input` (:class:`InputSignal`). """ if not compatible_channels(output, input): return if output not in self.source.output_channels(): raise ValueError("%r is not an output channel of %r" % \ (output, self.source)) if input not in self.sink.input_channels(): raise ValueError("%r is not an input channel of %r" % \ (input, self.sink)) if input.single: # Remove existing link if it exists. for s1, s2, _ in self.__links: if s2 == input: self.removeLink(s1, s2) line = QGraphicsLineItem(self) source_anchor = self.sourceNodeWidget.anchor(output) sink_anchor = self.sinkNodeWidget.anchor(input) source_pos = source_anchor.boundingRect().center() source_pos = self.mapFromItem(source_anchor, source_pos) sink_pos = sink_anchor.boundingRect().center() sink_pos = self.mapFromItem(sink_anchor, sink_pos) line.setLine(source_pos.x(), source_pos.y(), sink_pos.x(), sink_pos.y()) pen = QPen(Qt.black, 4) pen.setCapStyle(Qt.RoundCap) line.setPen(pen) self.__links.append(_Link(output, input, line))
def paintEvent(self, event): spacing = 15 contentRect = self.rect().adjusted(spacing, spacing, -spacing, -spacing) painter = QPainter(self) painter.setRenderHint(QPainter.Antialiasing) pen = QPen() pen.setCapStyle(Qt.RoundCap) pen.setWidthF(1.0 + self.width() / 15.0) pen.setColor(Qt.white) pen.setJoinStyle(Qt.RoundJoin) painter.setPen(pen) painter.drawArc(contentRect, (-45) * 16, (2 * 135) * 16) valueInPercent = (self.m_value - self.m_minimum) / (self.m_maximum - self.m_minimum) math_pi = 3.14159265358979323846 degree = (135 + 90) - valueInPercent * 2.0 * 135.0 degree = degree * math_pi / 180.0 radius = (contentRect.width() - spacing * 0.5) * 0.5 vec = QPoint(radius * math.cos(degree), radius * -math.sin(degree)) painter.drawLine(contentRect.center(), contentRect.center() + vec)
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
def paintEvent(self, event): # Initialize QPainter properties painter = QPainter() painter.begin(self) painter.setRenderHint(QPainter.Antialiasing) if self.height() <= self.width() / self.ref_aspect_ratio: v_scale = self.height() h_scale = v_scale * self.ref_aspect_ratio else: h_scale = self.width() v_scale = h_scale / self.ref_aspect_ratio # Scale all objects proportionate to window size painter.scale(h_scale / self.width_ref, v_scale / self.height_ref) painter.setClipPath(self.dial) # Don't allow objects or text to extend outside of main dial shape painter.save() # First draw main gauge background pen = QPen(painter.pen()) pen.setWidth(1) pen.setColor(Qt.black) painter.setPen(pen) painter.setBrush(QColor(100, 100, 100, 255)) # self.dial_bg) painter.drawPath(self.dial) # Add Minor and Major Alarm limit bars pen.setWidth(16) pen.setCapStyle(Qt.FlatCap) pen.setJoinStyle(Qt.BevelJoin) pen.setColor(Qt.yellow) painter.setPen(pen) painter.setBrush(Qt.NoBrush) painter.drawPath(self.low_arc) painter.drawPath(self.high_arc) pen.setColor(Qt.red) painter.setPen(pen) painter.drawPath(self.lolo_arc) painter.drawPath(self.hihi_arc) painter.restore() # Display PV current value painter.save() font = QFont() font.setPixelSize(45) painter.setFont(font) sevr = self.channel.sevr.lower() if sevr == 'major': color = Qt.red elif sevr == 'minor': color = Qt.yellow elif sevr == 'invalid': color = Qt.magenta else: color = Qt.green pen.setColor(color) painter.setPen(pen) font_metric = QFontMetrics(font) painter.translate(self.dial_width / 2, self.dial_height / 2) label = self.format_label(self.channel_value) painter.drawText(QPointF(0.0 - font_metric.width(label) / 2.0, font_metric.height() / 2.0), label) # Display PV name painter.setFont(self.pv_label_font) pen.setColor(Qt.black) # Qt.darkCyan) pen.setWidth(1) painter.setPen(pen) # brush = QBrush(Qt.darkCyan) # painter.setBrush(brush) font_metric = QFontMetrics(self.pv_label_font) pv_label = self.channel.egu # self.channel.name + ' (' + self.channel.egu + ')' painter.drawText(QPointF(0.0 - font_metric.width(pv_label) / 2.0, (self.dial_height / 2.0) + (font_metric.height() * 1.5)), pv_label) # painter.drawPath(self.pv_label_path) painter.restore() # Next add division markers painter.save() painter.translate(self.dial_width / 2, self.dial_height * 0.98) pen.setColor(Qt.black) # Qt.cyan) pen.setWidth(2) painter.setPen(pen) for i in range(0, 31): if (i % 5) != 0: painter.drawLine(-self.dial_width / 2.1, 0.0, -self.dial_width / 2.2, 0.0) else: painter.drawLine(-self.dial_width / 2.1, 0.0, -self.dial_width / 2.3, 0.0) painter.rotate(6.0) painter.restore() # Layout division text labels painter.save() painter.translate(self.dial_width / 2, self.dial_height * 0.98) pen.setColor(Qt.black) # Qt.cyan) painter.setPen(pen) font = QFont() font.setPixelSize(18) painter.setFont(font) font_metric = QFontMetrics(font) labels = linspace(self.lim_low, self.lim_hi, 7) painter.rotate(-90) for i in range(0, 7): label = self.format_label(labels[i]) painter.drawText(QPointF(0.0 - font_metric.width(label) / 2.0, -self.dial_height * 0.75), label) painter.rotate(30) painter.restore() # Draw needle at appropriate angle for data painter.save() painter.translate(self.dial_width / 2, self.dial_height * 0.98) painter.rotate(-180 * (1.0 - self.percentage)) pen.setColor(QColor(self.needle_color).darker(200)) pen.setWidth(1) painter.setPen(pen) painter.setBrush(self.needle_color) painter.drawPolygon(self.needle) painter.restore() # if self.percentage <= 0.5: # shadow = max(490 * self.percentage, 127) # needle_left_color = QColor(0, shadow, shadow) # Qt.darkCyan # QColor(80,80,80,255) # needle_right_color = Qt.cyan # QColor(230,230,230,255) # else: # shadow = max(125 / self.percentage, 127) # needle_left_color = Qt.cyan # QColor(230,230,230,255) # needle_right_color = QColor(0, shadow, shadow) # Qt.darkCyan # QColor(80,80,80,255) # # # Draw Highlight side of needle # pen.setWidth(1) # pen.setColor(Qt.gray) # needle_left_color) # painter.setPen(pen) # painter.setBrush(Qt.gray) # needle_left_color) # painter.drawPolygon(self.needle_left) # # # Draw shadow side of needle # pen.setColor(Qt.gray) # needle_right_color) # painter.setPen(pen) # painter.setBrush(Qt.gray) # needle_right_color) # painter.drawPolygon(self.needle_right) # painter.restore() # Draw needle axel pin painter.save() pen.setWidth(1) pen.setColor(Qt.black) painter.setPen(pen) painter.setBrush(QColor(50, 50, 50, 255)) # self.pin_bg) painter.translate(self.dial_width / 2, self.dial_height * 0.98) painter.drawEllipse(self.pin_rect) painter.restore() # Draw glass reflection and shadow effects # painter.save() # painter.translate(self.dial_width / 2.0, self.dial_height / 2.0) # painter.setPen(Qt.NoPen) # painter.setBrush(QColor(0, 0, 0, 20)) # painter.drawEllipse(self.shadow_rect) # painter.setBrush(self.gloss_gradient) # painter.drawEllipse(self.gloss_rect) # painter.restore() painter.end()
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, 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 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()
def attachCurves(self, names, settings, usedMnts): """ To attach the curves for the layers to the profile :param names: layers names """ if (self.__profiles is None) or (self.__profiles == 0): return self.__getLinearPoints() if usedMnts is not None and (usedMnts[0] or usedMnts[1] or usedMnts[2]): self.__getMnt(settings) c = 0 if self.__mntPoints is not None: for p in range(len(self.__mntPoints[0])): if usedMnts[p]: legend = QLabel("<font color='" + self.__colors[c] + "'>" + self.__mntPoints[0][p] + "</font>") self.__legendLayout.addWidget(legend) if self.__lib == 'Qwt5': xx = [list(g) for k, g in itertools.groupby(self.__mntPoints[1], lambda x: x is None) if not k] yy = [list(g) for k, g in itertools.groupby(self.__mntPoints[2][p], lambda x: x is None) if not k] for j in range(len(xx)): curve = QwtPlotCurve(self.__mntPoints[0][p]) curve.setData(xx[j], yy[j]) curve.setPen(QPen(QColor(self.__colors[c]), 3)) curve.attach(self.__plotWdg) elif self.__lib == 'Matplotlib': qcol = QColor(self.__colors[c]) self.__plotWdg.figure.get_axes()[0].plot(self.__mntPoints[1], self.__mntPoints[2][p], gid=self.__mntPoints[0][p], linewidth=3) tmp = self.__plotWdg.figure.get_axes()[0].get_lines() for t in range(len(tmp)): if self.__mntPoints[0][p] == tmp[t].get_gid(): tmp[c].set_color((old_div(qcol.red(), 255.0), old_div(qcol.green(), 255.0), old_div(qcol.blue(), 255.0), old_div(qcol.alpha(), 255.0))) self.__plotWdg.draw() break c += 1 if 'z' in self.__profiles[0]: for i in range(len(self.__profiles[0]['z'])): if i < self.__numLines: v = 0 else: v = i - self.__numLines + 1 name = names[v] xx = [] yy = [] for prof in self.__profiles: xx.append(prof['l']) yy.append(prof['z'][i]) for j in range(len(yy)): if yy[j] is None: xx[j] = None if i == 0 or i > (self.__numLines-1): legend = QLabel("<font color='" + self.__colors[c] + "'>" + name + "</font>") self.__legendLayout.addWidget(legend) if self.__lib == 'Qwt5': # Split xx and yy into single lines at None values xx = [list(g) for k, g in itertools.groupby(xx, lambda x: x is None) if not k] yy = [list(g) for k, g in itertools.groupby(yy, lambda x: x is None) if not k] # Create & attach one QwtPlotCurve per one single line for j in range(len(xx)): curve = QwtPlotCurve(name) curve.setData(xx[j], yy[j]) curve.setPen(QPen(QColor(self.__colors[c]), 3)) if i > (self.__numLines-1): curve.setStyle(QwtPlotCurve.Dots) pen = QPen(QColor(self.__colors[c]), 8) pen.setCapStyle(Qt.RoundCap) curve.setPen(pen) curve.attach(self.__plotWdg) elif self.__lib == 'Matplotlib': qcol = QColor(self.__colors[c]) if i < self.__numLines: self.__plotWdg.figure.get_axes()[0].plot(xx, yy, gid=name, linewidth=3) else: self.__plotWdg.figure.get_axes()[0].plot(xx, yy, gid=name, linewidth=5, marker='o', linestyle='None') tmp = self.__plotWdg.figure.get_axes()[0].get_lines() for t in range(len(tmp)): if name == tmp[t].get_gid(): tmp[c].set_color((old_div(qcol.red(), 255.0), old_div(qcol.green(), 255.0), old_div(qcol.blue(), 255.0), old_div(qcol.alpha(), 255.0))) self.__plotWdg.draw() break c += 1 # scaling this try: self.__reScalePlot(None, True) except: self.__iface.messageBar().pushMessage( QCoreApplication.translate("VDLTools", "Rescale problem... (trace printed)"), level=QgsMessageBar.CRITICAL, duration=0) print( QCoreApplication.translate("VDLTools", "rescale problem : "), sys.exc_info()[0], traceback.format_exc()) if self.__lib == 'Qwt5': self.__plotWdg.replot() elif self.__lib == 'Matplotlib': self.__plotWdg.figure.get_axes()[0].redraw_in_frame() self.__plotWdg.draw() self.__activateMouseTracking(True) self.__marker.show()
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
if __name__ == "__main__": import time import numpy as np from PyQt4.QtGui import QApplication, QGraphicsView, QGraphicsScene, QTransform app = QApplication([]) import h5py with h5py.File('/magnetic/data/multicut-testdata/2d/256/Superpixels.h5', 'r') as superpixels_f: labels_img = superpixels_f['data'][:] labels_img = labels_img[...,0] # drop channel default_pen = QPen() default_pen.setCosmetic(True) default_pen.setCapStyle(Qt.RoundCap) default_pen.setColor(Qt.blue) default_pen.setWidth(3) # Changes to this pen table will be detected automatically in the QGraphicsItem pen_table = SignalingDefaultDict(parent=None, default_factory=lambda:default_pen) start = time.time() path_items = generate_path_items_for_labels(pen_table, labels_img, None) print "generate took {}".format(time.time() - start) # 52 ms edges_item = SegmentationEdgesItem(path_items, pen_table) def assign_random_color( id_pair): print "handling click: {}".format(id_pair) pen = pen_table[id_pair]
if __name__ == "__main__": import time import numpy as np from PyQt4.QtGui import QApplication, QGraphicsView, QGraphicsScene, QTransform app = QApplication([]) import h5py with h5py.File('/magnetic/data/multicut-testdata/2d/256/Superpixels.h5', 'r') as superpixels_f: labels_img = superpixels_f['data'][:] labels_img = labels_img[..., 0] # drop channel default_pen = QPen() default_pen.setCosmetic(True) default_pen.setCapStyle(Qt.RoundCap) default_pen.setColor(Qt.blue) default_pen.setWidth(3) # Changes to this pen table will be detected automatically in the QGraphicsItem pen_table = SignalingDefaultDict(parent=None, default_factory=lambda: default_pen) start = time.time() path_items = generate_path_items_for_labels(pen_table, labels_img, None) print "generate took {}".format(time.time() - start) # 52 ms edges_item = SegmentationEdgesItem(path_items, pen_table) def assign_random_color(id_pair, buttons): print "handling click: {}".format(id_pair)
def replot_experiments(self): """Replot the whole quality plot. """ self.scene.clear() labels = [] max_dist = numpy.nanmax(list(filter(None, self.distances))) rug_widgets = [] group_pen = QPen(Qt.black) group_pen.setWidth(2) group_pen.setCapStyle(Qt.RoundCap) background_pen = QPen(QColor(0, 0, 250, 150)) background_pen.setWidth(1) background_pen.setCapStyle(Qt.RoundCap) main_widget = QGraphicsWidget() layout = QGraphicsGridLayout() attributes = self.data.domain.attributes if self.data is not None: for (group, indices), dist_vec in zip(self.groups, self.distances): indices_set = set(indices) rug_items = [] if dist_vec is not None: for i, attr in enumerate(attributes): # Is this a within group distance or background in_group = i in indices_set if in_group: rug_item = ClickableRugItem(dist_vec[i] / max_dist, 1.0, self.on_rug_item_clicked) rug_item.setPen(group_pen) tooltip = experiment_description(attr) rug_item.setToolTip(tooltip) rug_item.group_index = indices.index(i) rug_item.setZValue(rug_item.zValue() + 1) else: rug_item = ClickableRugItem(dist_vec[i] / max_dist, 0.85, self.on_rug_item_clicked) rug_item.setPen(background_pen) tooltip = experiment_description(attr) rug_item.setToolTip(tooltip) rug_item.group = group rug_item.index = i rug_item.in_group = in_group rug_items.append(rug_item) rug_widget = RugGraphicsWidget(parent=main_widget) rug_widget.set_rug(rug_items) rug_widgets.append(rug_widget) label = group_label(self.selected_split_by_labels(), group) label_item = QGraphicsSimpleTextItem(label, main_widget) label_item = GraphicsSimpleTextLayoutItem(label_item, parent=layout) label_item.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) labels.append(label_item) for i, (label, rug_w) in enumerate(zip(labels, rug_widgets)): layout.addItem(label, i, 0, Qt.AlignVCenter) layout.addItem(rug_w, i, 1) layout.setRowMaximumHeight(i, 30) main_widget.setLayout(layout) self.scene.addItem(main_widget) self.main_widget = main_widget self.rug_widgets = rug_widgets self.labels = labels self.on_view_resize(self.scene_view.size())
def replot_experiments(self): """Replot the whole quality plot. """ self.scene.clear() labels = [] max_dist = numpy.nanmax(list(filter(None, self.distances))) rug_widgets = [] group_pen = QPen(Qt.black) group_pen.setWidth(2) group_pen.setCapStyle(Qt.RoundCap) background_pen = QPen(QColor(0, 0, 250, 150)) background_pen.setWidth(1) background_pen.setCapStyle(Qt.RoundCap) main_widget = QGraphicsWidget() layout = QGraphicsGridLayout() attributes = self.data.domain.attributes if self.data is not None: for (group, indices), dist_vec in zip(self.groups, self.distances): indices_set = set(indices) rug_items = [] if dist_vec is not None: for i, attr in enumerate(attributes): # Is this a within group distance or background in_group = i in indices_set if in_group: rug_item = ClickableRugItem( dist_vec[i] / max_dist, 1.0, self.on_rug_item_clicked) rug_item.setPen(group_pen) tooltip = experiment_description(attr) rug_item.setToolTip(tooltip) rug_item.group_index = indices.index(i) rug_item.setZValue(rug_item.zValue() + 1) else: rug_item = ClickableRugItem( dist_vec[i] / max_dist, 0.85, self.on_rug_item_clicked) rug_item.setPen(background_pen) tooltip = experiment_description(attr) rug_item.setToolTip(tooltip) rug_item.group = group rug_item.index = i rug_item.in_group = in_group rug_items.append(rug_item) rug_widget = RugGraphicsWidget(parent=main_widget) rug_widget.set_rug(rug_items) rug_widgets.append(rug_widget) label = group_label(self.selected_split_by_labels(), group) label_item = QGraphicsSimpleTextItem(label, main_widget) label_item = GraphicsSimpleTextLayoutItem(label_item, parent=layout) label_item.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) labels.append(label_item) for i, (label, rug_w) in enumerate(zip(labels, rug_widgets)): layout.addItem(label, i, 0, Qt.AlignVCenter) layout.addItem(rug_w, i, 1) layout.setRowMaximumHeight(i, 30) main_widget.setLayout(layout) self.scene.addItem(main_widget) self.main_widget = main_widget self.rug_widgets = rug_widgets self.labels = labels self.on_view_resize(self.scene_view.size())
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 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)
def attachCurves(self, names, settings, usedMnts): """ To attach the curves for the layers to the profile :param names: layers names """ if (self.__profiles is None) or (self.__profiles == 0): return self.__getLinearPoints() if usedMnts is not None and (usedMnts[0] or usedMnts[1] or usedMnts[2]): self.__getMnt(settings) c = 0 if self.__mntPoints is not None: for p in range(len(self.__mntPoints[0])): if usedMnts[p]: legend = QLabel("<font color='" + self.__colors[c] + "'>" + self.__mntPoints[0][p] + "</font>") self.__legendLayout.addWidget(legend) if self.__lib == 'Qwt5': xx = [list(g) for k, g in itertools.groupby(self.__mntPoints[1], lambda x: x is None) if not k] yy = [list(g) for k, g in itertools.groupby(self.__mntPoints[2][p], lambda x: x is None) if not k] for j in range(len(xx)): curve = QwtPlotCurve(self.__mntPoints[0][p]) curve.setData(xx[j], yy[j]) curve.setPen(QPen(QColor(self.__colors[c]), 3)) curve.attach(self.__plotWdg) elif self.__lib == 'Matplotlib': qcol = QColor(self.__colors[c]) self.__plotWdg.figure.get_axes()[0].plot(self.__mntPoints[1], self.__mntPoints[2][p], gid=self.__mntPoints[0][p], linewidth=3) tmp = self.__plotWdg.figure.get_axes()[0].get_lines() for t in range(len(tmp)): if self.__mntPoints[0][p] == tmp[t].get_gid(): tmp[c].set_color((old_div(qcol.red(), 255.0), old_div(qcol.green(), 255.0), old_div(qcol.blue(), 255.0), old_div(qcol.alpha(), 255.0))) self.__plotWdg.draw() break c += 1 if 'z' in self.__profiles[0]: for i in range(len(self.__profiles[0]['z'])): if i < self.__numLines: v = 0 else: v = i - self.__numLines + 1 name = names[v] xx = [] yy = [] for prof in self.__profiles: xx.append(prof['l']) yy.append(prof['z'][i]) for j in range(len(yy)): if yy[j] is None: xx[j] = None if i == 0 or i > (self.__numLines-1): legend = QLabel("<font color='" + self.__colors[c] + "'>" + name + "</font>") self.__legendLayout.addWidget(legend) if self.__lib == 'Qwt5': # Split xx and yy into single lines at None values xx = [list(g) for k, g in itertools.groupby(xx, lambda x: x is None) if not k] yy = [list(g) for k, g in itertools.groupby(yy, lambda x: x is None) if not k] # Create & attach one QwtPlotCurve per one single line for j in range(len(xx)): curve = QwtPlotCurve(name) curve.setData(xx[j], yy[j]) curve.setPen(QPen(QColor(self.__colors[c]), 3)) if i > (self.__numLines-1): curve.setStyle(QwtPlotCurve.Dots) pen = QPen(QColor(self.__colors[c]), 8) pen.setCapStyle(Qt.RoundCap) curve.setPen(pen) curve.attach(self.__plotWdg) elif self.__lib == 'Matplotlib': qcol = QColor(self.__colors[c]) if i < self.__numLines: self.__plotWdg.figure.get_axes()[0].plot(xx, yy, gid=name, linewidth=3) else: self.__plotWdg.figure.get_axes()[0].plot(xx, yy, gid=name, linewidth=5, marker='o', linestyle='None') tmp = self.__plotWdg.figure.get_axes()[0].get_lines() for t in range(len(tmp)): if name == tmp[t].get_gid(): tmp[c].set_color((old_div(qcol.red(), 255.0), old_div(qcol.green(), 255.0), old_div(qcol.blue(), 255.0), old_div(qcol.alpha(), 255.0))) self.__plotWdg.draw() break c += 1 # scaling this try: self.__reScalePlot(None, True) except: self.__iface.messageBar().pushMessage( QCoreApplication.translate("VDLTools", "Rescale problem... (trace printed)"), level=QgsMessageBar.CRITICAL, duration=0) print(sys.exc_info()[0], traceback.format_exc()) if self.__lib == 'Qwt5': self.__plotWdg.replot() elif self.__lib == 'Matplotlib': self.__plotWdg.figure.get_axes()[0].redraw_in_frame() self.__plotWdg.draw() self.__activateMouseTracking(True) self.__marker.show()