def setRectanglePen( self ): " Sets the diagram pen " pen = QPen( QColor( 0, 0, 0) ) pen.setWidth( 2 ) pen.setJoinStyle( Qt.RoundJoin ) self.setPen( pen ) return
def setRectanglePen(self): " Sets the diagram pen " pen = QPen(QColor(0, 0, 0)) pen.setWidth(2) pen.setJoinStyle(Qt.RoundJoin) self.setPen(pen) return
def __init__(self, source, dest): super().__init__() self.setAcceptedMouseButtons(Qt.LeftButton) self.setCacheMode(self.DeviceCoordinateCache) # Without this, burn thy CPU self.setZValue(1) pen = QPen(Edge.Color.DEFAULT[0], 1) pen.setJoinStyle(Qt.MiterJoin) self.setPen(pen) self.arrowHead = QtGui.QPolygonF() self._selected = False self._weights = [] self._labels = [] self.squares = GroupOfSquares(self) self.source = source self.dest = dest if source is dest: source.edges.append(self) else: source.edges.insert(0, self) dest.edges.insert(0, self) # Add text labels label = self.label = TextItem('', self) label.setFont(Edge.Font.DEFAULT) label.setZValue(3) self.adjust()
def __init__(self, source, dest): super().__init__() self.setAcceptedMouseButtons(Qt.LeftButton) self.setCacheMode( self.DeviceCoordinateCache) # Without this, burn thy CPU self.setZValue(1) pen = QPen(Edge.Color.DEFAULT[0], 1) pen.setJoinStyle(Qt.MiterJoin) self.setPen(pen) self.arrowHead = QtGui.QPolygonF() self._selected = False self._weights = [] self._labels = [] self.squares = GroupOfSquares(self) self.source = source self.dest = dest if source is dest: source.edges.append(self) else: source.edges.insert(0, self) dest.edges.insert(0, self) # Add text labels label = self.label = TextItem('', self) label.setFont(Edge.Font.DEFAULT) label.setZValue(3) self.adjust()
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 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 paint(self, QPainter, QStyleOptionGraphicsItem, QWidget_widget=None): # setPen pen = QPen() pen.setWidth(5) pen.setJoinStyle(Qt.MiterJoin) #让箭头变尖 QPainter.setPen(pen) # draw line QPainter.drawLine(self.line)
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 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 __init__(self): super(QFramesInTracksScene, self).__init__() self._coords = CoordTransform() self._track_items = {} self._frame_items = {} pen = QPen() pen.setWidthF(1.25) pen.setColor(Qt.black) # pen.setCapStyle(Qt.RoundCap) pen.setJoinStyle(Qt.RoundJoin) brush = QBrush() brush.setColor(Qt.blue) brush.setStyle(Qt.SolidPattern) self._frame_pen_brush = pen, brush pen = QPen(pen) pen.setWidthF(3.5) pen.setJoinStyle(Qt.RoundJoin) pen.setColor(Qt.blue) brush = QBrush(brush) brush.setColor(Qt.gray) self._track_pen_brush = pen, brush
def paint(self, painter, style, widget): painter.setRenderHint(QPainter.Antialiasing, True) rect = self.boundingRect() pen = QPen(self.borderColor) pen.setWidthF(10) pen.setJoinStyle(Qt.RoundJoin) path = QPainterPath() if(self.parentItem().property('direction') == 1): path.moveTo(5, rect.height() - 5) path.lineTo(rect.width() / 2, 5) path.lineTo(rect.width() - 5, rect.height() - 5) path.lineTo(5, rect.height() - 5) else: path.moveTo(5, 5) path.lineTo(rect.width() / 2, rect.height() - 5) path.lineTo(rect.width() - 5, 5) path.lineTo(5, 5) painter.fillPath(path, self.color) painter.strokePath(path, pen)
def paint(self, painter, style, widget): painter.setRenderHint(QPainter.Antialiasing, True) rect = self.boundingRect() pen = QPen(self.borderColor) pen.setWidthF(10) pen.setJoinStyle(Qt.RoundJoin) path = QPainterPath() if (self.parentItem().property('direction') == 1): path.moveTo(5, rect.height() - 5) path.lineTo(rect.width() / 2, 5) path.lineTo(rect.width() - 5, rect.height() - 5) path.lineTo(5, rect.height() - 5) else: path.moveTo(5, 5) path.lineTo(rect.width() / 2, rect.height() - 5) path.lineTo(rect.width() - 5, 5) path.lineTo(5, 5) painter.fillPath(path, self.color) painter.strokePath(path, pen)
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)
class PatternGridItem(QGraphicsSvgItem): Type = 70000 + 1 def __init__(self, unitDim, col, row, width, height, defaultSymbol, defaultColor = QColor(Qt.white), parent = None): super(PatternGridItem, self).__init__(parent) # NOTE: need this distinction for cache mode based on # the Qt version otherwise rendering is broken if NO_ITEM_CACHING: self.setCacheMode(QGraphicsItem.NoCache) else: self.setCacheMode(QGraphicsItem.DeviceCoordinateCache) self.origin = QPointF(0.0, 0.0) self.unitDim = unitDim self.row = row self.column = col self.width = width self.height = height self.size = QSizeF(self.unitDim.width() * width, self.unitDim.height() * height) self._penSize = 1.0 self._pen = QPen() self._pen.setWidthF(self._penSize) self._pen.setJoinStyle(Qt.MiterJoin) self._pen.setColor(Qt.black) self.isHidden = False self._selected = False self.color = defaultColor self._backBrush = QBrush(self.color) self._highlightBrush = QBrush(QColor(Qt.lightGray), Qt.SolidPattern) self.symbol = None self._set_symbol(defaultSymbol) def mousePressEvent(self, event): """ Handle user press events on the item. NOTE: We ignore all events with shift or control clicked. """ if (event.modifiers() & Qt.ControlModifier) or \ (event.modifiers() & Qt.ShiftModifier): event.ignore() return mode = self.scene().selectionMode if mode == HIDE_MODE: self.emit(SIGNAL("cell_hidden"), [self]) elif mode == UNHIDE_MODE: self.emit(SIGNAL("cell_visible"), [self]) elif not self.isHidden: if not self._selected: self.emit(SIGNAL("cell_selected"), self) else: self.emit(SIGNAL("cell_unselected"), self) def hide_cell(self): """ Hides the cell by setting the opacity to a low value. NOTE: This is different from Qt's hide function since it is not meant to disable the item completely. """ self.isHidden = True self.setOpacity(HIDE_OPACITY) def unhide_cell(self): """ Unhides the cell by setting the opacity back to 1.0. NOTE: This is the reverse of hide_cell(). """ self.isHidden = False self.setOpacity(1.0) def change_geometry(self, newDim): """ This slot changes the unit dimensions of the item. """ self.unitDim = newDim self.size = QSizeF(self.unitDim.width() * self.width, self.unitDim.height() * self.height) def change_color(self, newColor): """ This slot changes the color of the items. """ self.color = newColor self._backBrush = QBrush(self.color) @property def name(self): """ Return the name of the symbol we contain """ return self.symbol["name"] def _unselect(self): """ Unselects a given selected cell. """ self._selected = False self._backBrush = QBrush(self.color) self.update() def _select(self): """ Selects a given unselected cell. """ self._selected = True self._backBrush = self._highlightBrush self.update() def _set_symbol(self, newSymbol): """ Adds a new svg image of a knitting symbol to the scene. """ self.symbol = newSymbol svgPath = newSymbol["svgPath"] if not self.renderer().load(svgPath): errorMessage = ("PatternGridItem._set_symbol: failed to load " "symbol %s" % svgPath) logger.error(errorMessage) return # apply color if present if "backgroundColor" in newSymbol: self._backColor = QColor(newSymbol["backgroundColor"]) self._backBrush = QBrush(QColor(newSymbol["backgroundColor"])) self.update() def boundingRect(self): """ Return the bounding rectangle of the item. """ halfPen = self._penSize * 0.5 return QRectF(self.origin, self.size).adjusted(halfPen, halfPen, halfPen, halfPen) def paint(self, painter, option, widget): """ Paint ourselves. """ painter.setPen(self._pen) painter.setBrush(self._backBrush) halfPen = self._penSize * 0.5 scaledRect = \ QRectF(self.origin, self.size).adjusted(halfPen, halfPen, halfPen, halfPen) painter.drawRect(scaledRect) self.renderer().render(painter, scaledRect)
class PatternLegendItem(QGraphicsSvgItem): Type = 70000 + 2 def __init__(self, unitDim, width, height, defaultSymbol, defaultColor = QColor(Qt.white), zValue = 1, parent = None): super(PatternLegendItem, self).__init__(parent) # NOTE: need this distinction for cache mode based on # the Qt version otherwise rendering is broken if NO_ITEM_CACHING: self.setCacheMode(QGraphicsItem.NoCache) else: self.setCacheMode(QGraphicsItem.DeviceCoordinateCache) self.setZValue(zValue) self.setFlag(QGraphicsItem.ItemIsMovable, True) self.origin = QPointF(0.0, 0.0) self.unitDim = unitDim self.width = width self.height = height self.size = QSizeF(self.unitDim.width() * width, self.unitDim.height() * height) self.color = defaultColor self.symbol = None self._set_symbol(defaultSymbol) self._penSize = 1.0 self._pen = QPen() self._pen.setWidthF(self._penSize) self._pen.setJoinStyle(Qt.MiterJoin) self._pen.setColor(Qt.black) self.setAcceptsHoverEvents(True) self._outline = None def hoverEnterEvent(self, event): """ Stuff related to hover enter events. For now we just show a rectangular outline. """ if not self._outline: self._outline = QGraphicsRectItem(\ self.boundingRect().adjusted(-1,-1,1,1), self) highlightColor = QColor(Qt.blue) highlightColor.setAlpha(30) self._outline.setBrush(highlightColor) highlightPen = QPen(Qt.blue) highlightPen.setWidth(2) self._outline.setPen(highlightPen) else: self._outline.show() def hoverLeaveEvent(self, event): """ Stuff related to hover leave events. For now we just show a rectangular outline. """ self._outline.hide() def mousePressEvent(self, event): """ We reimplement this function to store the position of the item when a user issues a mouse press. """ self._position = self.pos() if (event.modifiers() & Qt.ControlModifier): QApplication.setOverrideCursor(QCursor(Qt.SizeAllCursor)) else: event.ignore() return QGraphicsSvgItem.mousePressEvent(self, event) def mouseReleaseEvent(self, event): """ We reimplement this function to check if its position has changed since the last mouse click. If yes we let the canvas know so it can store the action as a Redo/Undo event. """ QApplication.restoreOverrideCursor() # this is needed for redo/undo if self._position != self.pos(): self.scene().canvas_item_position_changed(self, self._position, self.pos()) return QGraphicsSvgItem.mouseReleaseEvent(self, event) def change_geometry(self, newDim): """ This slot changes the unit dimensions of the item. """ self.unitDim = newDim self.size = QSizeF(self.unitDim.width() * self.width, self.unitDim.height() * self.height) @property def name(self): """ Return the name of the knitting symbol we contain. """ return self.symbol["name"] def _set_symbol(self, newSymbol): """ Adds a new svg image of a knitting symbol to the scene. """ self.symbol = newSymbol svgPath = newSymbol["svgPath"] if not self.renderer().load(svgPath): errorMessage = ("PatternLegendItem._set_symbol: failed to load " "symbol %s" % svgPath) logger.error(errorMessage) return # apply color if present if "backgroundColor" in newSymbol: self.color = QColor(newSymbol["backgroundColor"]) def boundingRect(self): """ Return the bounding rectangle of the item. """ halfPen = self._penSize * 0.5 return QRectF(self.origin, self.size).adjusted(halfPen, halfPen, halfPen, halfPen) def paint(self, painter, option, widget): """ Paint ourselves. """ painter.setPen(self._pen) brush = QBrush(self.color) painter.setBrush(brush) halfPen = self._penSize * 0.5 painter.drawRect(\ QRectF(self.origin, self.size).adjusted(halfPen, halfPen, halfPen, halfPen)) self.renderer().render(painter, QRectF(self.origin, self.size))
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 PatternLegendItem(QGraphicsSvgItem): Type = 70000 + 2 def __init__(self, unitDim, width, height, defaultSymbol, itemID=0, defaultColor=QColor(Qt.white), zValue=1, parent=None): super(PatternLegendItem, self).__init__(parent) # NOTE: need this distinction for cache mode based on # the Qt version otherwise rendering is broken if NO_ITEM_CACHING: self.setCacheMode(QGraphicsItem.NoCache) else: self.setCacheMode(QGraphicsItem.DeviceCoordinateCache) self.itemID = itemID self.setZValue(zValue) self.setFlag(QGraphicsItem.ItemIsMovable, True) self.origin = QPointF(0.0, 0.0) self.unitDim = unitDim self.width = width self.height = height self.size = QSizeF(self.unitDim.width() * width, self.unitDim.height() * height) self.color = defaultColor self.symbol = None self._set_symbol(defaultSymbol) self._penSize = 1.0 self._pen = QPen() self._pen.setWidthF(self._penSize) self._pen.setJoinStyle(Qt.MiterJoin) self._pen.setColor(Qt.black) self.setAcceptsHoverEvents(True) self._outline = None def hoverEnterEvent(self, event): """ Stuff related to hover enter events. For now we just show a rectangular outline. """ if not self._outline: self._outline = QGraphicsRectItem(\ self.boundingRect().adjusted(-1,-1,1,1), self) highlightColor = QColor(Qt.blue) highlightColor.setAlpha(30) self._outline.setBrush(highlightColor) highlightPen = QPen(Qt.blue) highlightPen.setWidth(2) self._outline.setPen(highlightPen) else: self._outline.show() def hoverLeaveEvent(self, event): """ Stuff related to hover leave events. For now we just show a rectangular outline. """ self._outline.hide() def mousePressEvent(self, event): """ We reimplement this function to store the position of the item when a user issues a mouse press. """ self._position = self.pos() if (event.modifiers() & Qt.ControlModifier): QApplication.setOverrideCursor(QCursor(Qt.SizeAllCursor)) else: event.ignore() return QGraphicsSvgItem.mousePressEvent(self, event) def mouseReleaseEvent(self, event): """ We reimplement this function to check if its position has changed since the last mouse click. If yes we let the canvas know so it can store the action as a Redo/Undo event. """ QApplication.restoreOverrideCursor() # this is needed for redo/undo if self._position != self.pos(): self.scene().canvas_item_position_changed(self, self._position, self.pos()) return QGraphicsSvgItem.mouseReleaseEvent(self, event) def change_geometry(self, newDim): """ This slot changes the unit dimensions of the item. """ self.unitDim = newDim self.size = QSizeF(self.unitDim.width() * self.width, self.unitDim.height() * self.height) @property def name(self): """ Return the name of the knitting symbol we contain. """ return self.symbol["name"] def _set_symbol(self, newSymbol): """ Adds a new svg image of a knitting symbol to the scene. """ self.symbol = newSymbol svgPath = newSymbol["svgPath"] if not self.renderer().load(svgPath): errorMessage = ("PatternLegendItem._set_symbol: failed to load " "symbol %s" % svgPath) logger.error(errorMessage) return # apply color if present if "backgroundColor" in newSymbol: self.color = QColor(newSymbol["backgroundColor"]) def boundingRect(self): """ Return the bounding rectangle of the item. """ halfPen = self._penSize * 0.5 return QRectF(self.origin, self.size).adjusted(halfPen, halfPen, halfPen, halfPen) def paint(self, painter, option, widget): """ Paint ourselves. """ painter.setPen(self._pen) brush = QBrush(self.color) painter.setBrush(brush) halfPen = self._penSize * 0.5 painter.drawRect(\ QRectF(self.origin, self.size).adjusted(halfPen, halfPen, halfPen, halfPen)) self.renderer().render(painter, QRectF(self.origin, self.size))
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 PatternGridItem(QGraphicsSvgItem): Type = 70000 + 1 def __init__(self, unitDim, col, row, width, height, defaultSymbol, defaultColor=QColor(Qt.white), parent=None): super(PatternGridItem, self).__init__(parent) # NOTE: need this distinction for cache mode based on # the Qt version otherwise rendering is broken if NO_ITEM_CACHING: self.setCacheMode(QGraphicsItem.NoCache) else: self.setCacheMode(QGraphicsItem.DeviceCoordinateCache) self.origin = QPointF(0.0, 0.0) self.unitDim = unitDim self.row = row self.column = col self.width = width self.height = height self.size = QSizeF(self.unitDim.width() * width, self.unitDim.height() * height) self._penSize = 1.0 self._pen = QPen() self._pen.setWidthF(self._penSize) self._pen.setJoinStyle(Qt.MiterJoin) self._pen.setColor(Qt.black) self.isHidden = False self._selected = False self.color = defaultColor self._backBrush = QBrush(self.color) self._highlightBrush = QBrush(QColor(Qt.lightGray), Qt.SolidPattern) self.symbol = None self._set_symbol(defaultSymbol) def mousePressEvent(self, event): """ Handle user press events on the item. NOTE: We ignore all events with shift or control clicked. """ if (event.modifiers() & Qt.ControlModifier) or \ (event.modifiers() & Qt.ShiftModifier): event.ignore() return mode = self.scene().selectionMode if mode == HIDE_MODE: self.emit(SIGNAL("cell_hidden"), [self]) elif mode == UNHIDE_MODE: self.emit(SIGNAL("cell_visible"), [self]) elif not self.isHidden: if not self._selected: self.emit(SIGNAL("cell_selected"), self) else: self.emit(SIGNAL("cell_unselected"), self) def hide_cell(self): """ Hides the cell by setting the opacity to a low value. NOTE: This is different from Qt's hide function since it is not meant to disable the item completely. """ self.isHidden = True self.setOpacity(HIDE_OPACITY) def unhide_cell(self): """ Unhides the cell by setting the opacity back to 1.0. NOTE: This is the reverse of hide_cell(). """ self.isHidden = False self.setOpacity(1.0) def change_geometry(self, newDim): """ This slot changes the unit dimensions of the item. """ self.unitDim = newDim self.size = QSizeF(self.unitDim.width() * self.width, self.unitDim.height() * self.height) def change_color(self, newColor): """ This slot changes the color of the items. """ self.color = newColor self._backBrush = QBrush(self.color) @property def name(self): """ Return the name of the symbol we contain """ return self.symbol["name"] def _unselect(self): """ Unselects a given selected cell. """ self._selected = False self._backBrush = QBrush(self.color) self.update() def _select(self): """ Selects a given unselected cell. """ self._selected = True self._backBrush = self._highlightBrush self.update() def _set_symbol(self, newSymbol): """ Adds a new svg image of a knitting symbol to the scene. """ self.symbol = newSymbol svgPath = newSymbol["svgPath"] if not self.renderer().load(svgPath): errorMessage = ("PatternGridItem._set_symbol: failed to load " "symbol %s" % svgPath) logger.error(errorMessage) return # apply color if present if "backgroundColor" in newSymbol: self._backColor = QColor(newSymbol["backgroundColor"]) self._backBrush = QBrush(QColor(newSymbol["backgroundColor"])) self.update() def boundingRect(self): """ Return the bounding rectangle of the item. """ halfPen = self._penSize * 0.5 return QRectF(self.origin, self.size).adjusted(halfPen, halfPen, halfPen, halfPen) def paint(self, painter, option, widget): """ Paint ourselves. """ painter.setPen(self._pen) painter.setBrush(self._backBrush) halfPen = self._penSize * 0.5 scaledRect = \ QRectF(self.origin, self.size).adjusted(halfPen, halfPen, halfPen, halfPen) painter.drawRect(scaledRect) self.renderer().render(painter, scaledRect)
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()
def _paint(self, painter, option, widget): " Draws the corresponding scope element " s = self.canvas.settings if self.subKind == ScopeCellElement.TOP_LEFT: bgColor, _, borderColor = self.getCustomColors( painter.brush().color(), painter.brush().color()) brush = QBrush(bgColor) painter.setBrush(brush) if self.isSelected(): selectPen = QPen(s.selectColor) selectPen.setWidth(s.selectPenWidth) selectPen.setJoinStyle(Qt.RoundJoin) painter.setPen(selectPen) else: pen = QPen(borderColor) pen.setWidth(s.lineWidth) painter.setPen(pen) painter.drawRoundedRect(self.baseX + s.hCellPadding, self.baseY + s.vCellPadding, self.canvas.minWidth - 2 * s.hCellPadding, self.canvas.minHeight - 2 * s.vCellPadding, s.rectRadius, s.rectRadius) elif self.subKind == ScopeCellElement.DECLARATION: bgColor, fgColor, borderColor = self.getCustomColors( painter.brush().color(), s.boxFGColor) brush = QBrush(bgColor) painter.setBrush(brush) pen = QPen(fgColor) painter.setFont(s.monoFont) painter.setPen(pen) canvasLeft = self.baseX - s.rectRadius canvasTop = self.baseY - s.rectRadius textHeight = self._headerRect.height() yShift = 0 if hasattr(self.ref, "sideComment"): yShift = s.vTextPadding painter.drawText(canvasLeft + s.hHeaderPadding, canvasTop + s.vHeaderPadding + yShift, self._headerRect.width(), textHeight, Qt.AlignLeft, self._getText()) pen = QPen(borderColor) pen.setWidth(s.lineWidth) painter.setPen(pen) # If the scope is selected then the line may need to be shorter # to avoid covering the outline row = self.addr[1] - 1 column = self.addr[0] - 1 correction = 0.0 if self.canvas.cells[row][column].isSelected(): correction = s.selectPenWidth - 1 painter.drawLine( canvasLeft + correction, self.baseY + self.height, canvasLeft + self.canvas.minWidth - 2 * s.hCellPadding - correction, self.baseY + self.height) elif self.subKind == ScopeCellElement.SIDE_COMMENT: brush = QBrush(s.commentBGColor) painter.setBrush(brush) if self.isSelected(): selectPen = QPen(s.selectColor) selectPen.setWidth(s.selectPenWidth) selectPen.setJoinStyle(Qt.RoundJoin) painter.setPen(selectPen) else: pen = QPen(s.commentLineColor) pen.setWidth(s.commentLineWidth) pen.setJoinStyle(Qt.RoundJoin) painter.setPen(pen) canvasTop = self.baseY - s.rectRadius # s.vHeaderPadding below is used intentionally: to have the same # spacing on top, bottom and right for the comment box movedBaseX = self.canvas.baseX + self.canvas.minWidth - self.width - s.rectRadius - s.vHeaderPadding painter.drawPath(self.__sideCommentPath) pen = QPen(s.boxFGColor) painter.setFont(s.monoFont) painter.setPen(pen) painter.drawText(movedBaseX + s.hHeaderPadding + s.hTextPadding, canvasTop + s.vHeaderPadding + s.vTextPadding, self._sideCommentRect.width(), self._sideCommentRect.height(), Qt.AlignLeft, self._getSideComment()) elif self.subKind == ScopeCellElement.DOCSTRING: bgColor, fgColor, borderColor = self.getCustomColors( painter.brush().color(), s.boxFGColor) if self.ref.docstring.leadingCMLComments: colorSpec = CMLVersion.find( self.ref.docstring.leadingCMLComments, CMLcc) if colorSpec: if colorSpec.bg: bgColor = colorSpec.bg if colorSpec.fg: fgColor = colorSpec.fg brush = QBrush(bgColor) painter.setBrush(brush) canvasLeft = self.baseX - s.rectRadius if self.isSelected(): selectPen = QPen(s.selectColor) selectPen.setWidth(s.selectPenWidth) selectPen.setJoinStyle(Qt.RoundJoin) painter.setPen(selectPen) painter.drawRect(canvasLeft, self.baseY, self.canvas.minWidth - 2 * s.hCellPadding, self.height) else: # If the scope is selected then the line may need to be shorter # to avoid covering the outline row = self.addr[1] - 2 column = self.addr[0] - 1 correction = 0.0 if self.canvas.cells[row][column].isSelected(): correction = s.selectPenWidth - 1 # The background could also be custom pen = QPen(bgColor) pen.setWidth(s.lineWidth) pen.setJoinStyle(Qt.MiterJoin) painter.setPen(pen) dsCorr = float(s.lineWidth) if self.canvas.cells[row][column].isSelected(): dsCorr = float(s.selectPenWidth) / 2.0 + float( s.lineWidth) / 2.0 painter.drawRect( float(canvasLeft) + dsCorr, self.baseY + s.lineWidth, float(self.canvas.minWidth) - 2.0 * float(s.hCellPadding) - 2.0 * dsCorr, self.height - 2 * s.lineWidth) pen = QPen(borderColor) pen.setWidth(s.lineWidth) painter.setPen(pen) painter.drawLine( canvasLeft + correction, self.baseY + self.height, canvasLeft + self.canvas.minWidth - 2 * s.hCellPadding - correction, self.baseY + self.height) pen = QPen(fgColor) painter.setFont(s.monoFont) painter.setPen(pen) painter.drawText(canvasLeft + s.hHeaderPadding, self.baseY + s.vHeaderPadding, self.canvas.width - 2 * s.hHeaderPadding, self.height - 2 * s.vHeaderPadding, Qt.AlignLeft, self.getDocstringText()) return
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, 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, \ 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 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
def _paint( self, painter, option, widget ): " Draws the corresponding scope element " s = self.canvas.settings if self.subKind == ScopeCellElement.TOP_LEFT: bgColor, _, borderColor = self.getCustomColors( painter.brush().color(), painter.brush().color() ) brush = QBrush( bgColor ) painter.setBrush( brush ) if self.isSelected(): selectPen = QPen( s.selectColor ) selectPen.setWidth( s.selectPenWidth ) selectPen.setJoinStyle( Qt.RoundJoin ) painter.setPen( selectPen ) else: pen = QPen( borderColor ) pen.setWidth( s.lineWidth ) painter.setPen( pen ) painter.drawRoundedRect( self.baseX + s.hCellPadding, self.baseY + s.vCellPadding, self.canvas.minWidth - 2 * s.hCellPadding, self.canvas.minHeight - 2 * s.vCellPadding, s.rectRadius, s.rectRadius ) elif self.subKind == ScopeCellElement.DECLARATION: bgColor, fgColor, borderColor = self.getCustomColors( painter.brush().color(), s.boxFGColor ) brush = QBrush( bgColor ) painter.setBrush( brush ) pen = QPen( fgColor ) painter.setFont( s.monoFont ) painter.setPen( pen ) canvasLeft = self.baseX - s.rectRadius canvasTop = self.baseY - s.rectRadius textHeight = self._headerRect.height() yShift = 0 if hasattr( self.ref, "sideComment" ): yShift = s.vTextPadding painter.drawText( canvasLeft + s.hHeaderPadding, canvasTop + s.vHeaderPadding + yShift, self._headerRect.width(), textHeight, Qt.AlignLeft, self._getText() ) pen = QPen( borderColor ) pen.setWidth( s.lineWidth ) painter.setPen( pen ) # If the scope is selected then the line may need to be shorter # to avoid covering the outline row = self.addr[ 1 ] - 1 column = self.addr[ 0 ] - 1 correction = 0.0 if self.canvas.cells[ row ][ column ].isSelected(): correction = s.selectPenWidth - 1 painter.drawLine( canvasLeft + correction, self.baseY + self.height, canvasLeft + self.canvas.minWidth - 2 * s.hCellPadding - correction, self.baseY + self.height ) elif self.subKind == ScopeCellElement.SIDE_COMMENT: brush = QBrush( s.commentBGColor ) painter.setBrush( brush ) if self.isSelected(): selectPen = QPen( s.selectColor ) selectPen.setWidth( s.selectPenWidth ) selectPen.setJoinStyle( Qt.RoundJoin ) painter.setPen( selectPen ) else: pen = QPen( s.commentLineColor ) pen.setWidth( s.commentLineWidth ) pen.setJoinStyle( Qt.RoundJoin ) painter.setPen( pen ) canvasTop = self.baseY - s.rectRadius # s.vHeaderPadding below is used intentionally: to have the same # spacing on top, bottom and right for the comment box movedBaseX = self.canvas.baseX + self.canvas.minWidth - self.width - s.rectRadius - s.vHeaderPadding painter.drawPath( self.__sideCommentPath ) pen = QPen( s.boxFGColor ) painter.setFont( s.monoFont ) painter.setPen( pen ) painter.drawText( movedBaseX + s.hHeaderPadding + s.hTextPadding, canvasTop + s.vHeaderPadding + s.vTextPadding, self._sideCommentRect.width(), self._sideCommentRect.height(), Qt.AlignLeft, self._getSideComment() ) elif self.subKind == ScopeCellElement.DOCSTRING: bgColor, fgColor, borderColor = self.getCustomColors( painter.brush().color(), s.boxFGColor ) if self.ref.docstring.leadingCMLComments: colorSpec = CMLVersion.find( self.ref.docstring.leadingCMLComments, CMLcc ) if colorSpec: if colorSpec.bg: bgColor = colorSpec.bg if colorSpec.fg: fgColor = colorSpec.fg brush = QBrush( bgColor ) painter.setBrush( brush ) canvasLeft = self.baseX - s.rectRadius if self.isSelected(): selectPen = QPen( s.selectColor ) selectPen.setWidth( s.selectPenWidth ) selectPen.setJoinStyle( Qt.RoundJoin ) painter.setPen( selectPen ) painter.drawRect( canvasLeft, self.baseY, self.canvas.minWidth - 2 * s.hCellPadding, self.height ) else: # If the scope is selected then the line may need to be shorter # to avoid covering the outline row = self.addr[ 1 ] - 2 column = self.addr[ 0 ] - 1 correction = 0.0 if self.canvas.cells[ row ][ column ].isSelected(): correction = s.selectPenWidth - 1 # The background could also be custom pen = QPen( bgColor ) pen.setWidth( s.lineWidth ) pen.setJoinStyle( Qt.MiterJoin ) painter.setPen( pen ) dsCorr = float( s.lineWidth ) if self.canvas.cells[ row ][ column ].isSelected(): dsCorr = float( s.selectPenWidth ) / 2.0 + float( s.lineWidth ) / 2.0 painter.drawRect( float( canvasLeft ) + dsCorr, self.baseY + s.lineWidth, float( self.canvas.minWidth ) - 2.0 * float( s.hCellPadding ) - 2.0 * dsCorr, self.height - 2 * s.lineWidth ) pen = QPen( borderColor ) pen.setWidth( s.lineWidth ) painter.setPen( pen ) painter.drawLine( canvasLeft + correction, self.baseY + self.height, canvasLeft + self.canvas.minWidth - 2 * s.hCellPadding - correction, self.baseY + self.height ) pen = QPen( fgColor ) painter.setFont( s.monoFont ) painter.setPen( pen ) painter.drawText( canvasLeft + s.hHeaderPadding, self.baseY + s.vHeaderPadding, self.canvas.width - 2 * s.hHeaderPadding, self.height - 2 * s.vHeaderPadding, Qt.AlignLeft, self.getDocstringText() ) return