예제 #1
0
    def create_scale_marker_values_text(self):
        painter = QPainter(self)
        # painter.setRenderHint(QPainter.HighQualityAntialiasing)
        painter.setRenderHint(QPainter.Antialiasing)

        # Koordinatenursprung in die Mitte der Flaeche legen
        painter.translate(self.width() / 2, self.height() / 2)
        # painter.save()
        font = QFont(self.scale_fontname, self.scale_fontsize)
        fm = QFontMetrics(font)

        pen_shadow = QPen()

        pen_shadow.setBrush(self.ScaleValueColor)
        painter.setPen(pen_shadow)

        text_radius_factor = 0.8
        text_radius = self.widget_diameter/2 * text_radius_factor

        scale_per_div = int((self.value_max - self.value_min) / self.scala_main_count)

        angle_distance = (float(self.scale_angle_size) / float(self.scala_main_count))
        for i in range(self.scala_main_count + 1):
            # text = str(int((self.value_max - self.value_min) / self.scala_main_count * i))
            text = str(int(self.value_min + scale_per_div * i))
            w = fm.width(text) + 1
            h = fm.height()
            painter.setFont(QFont(self.scale_fontname, self.scale_fontsize))
            angle = angle_distance * i + float(self.scale_angle_start_value - self.angle_offset)
            x = text_radius * math.cos(math.radians(angle))
            y = text_radius * math.sin(math.radians(angle))
            # print(w, h, x, y, text)
            text = [x - int(w/2), y - int(h/2), int(w), int(h), Qt.AlignCenter, text]
            painter.drawText(text[0], text[1], text[2], text[3], text[4], text[5])
예제 #2
0
 def __gradient(self):
     left = QPointF(self.contentsRect().topLeft())
     right = QPointF(self.contentsRect().topRight())
     gradient = QLinearGradient(left, right)
     gradient.setColorAt(0.9, self.palette().color(QPalette.WindowText))
     gradient.setColorAt(1.0, self.palette().color(QPalette.Window))
     pen = QPen()
     pen.setBrush(QBrush(gradient))
     return pen
예제 #3
0
 def __gradient(self):
     left = QPointF(self.contentsRect().topLeft())
     right = QPointF(self.contentsRect().topRight())
     gradient = QLinearGradient(left, right)
     gradient.setColorAt(0.9, self.palette().color(QPalette.WindowText))
     gradient.setColorAt(1.0, self.palette().color(QPalette.Window))
     pen = QPen()
     pen.setBrush(QBrush(gradient))
     return pen
예제 #4
0
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
예제 #5
0
    def paint_elements(self, brushStyle = None):
        """ This member paints our path with the current
        color and line width.

        """

        if brushStyle:
            brush = QBrush(self.color, brushStyle)
        else:
            brush = QBrush(self.color)

        pen = QPen()
        pen.setWidth(self.width)
        pen.setBrush(brush)
        self.setPen(pen)
예제 #6
0
    def paint_elements(self, brushStyle=None):
        """ This member paints our path with the current
        color and line width.

        """

        if brushStyle:
            brush = QBrush(self.color, brushStyle)
        else:
            brush = QBrush(self.color)

        pen = QPen()
        pen.setWidth(self.width)
        pen.setBrush(brush)
        self.setPen(pen)
예제 #7
0
    def create_digital_indicator(self):
        """ Main value indicator inside the Gauge """
        painter = QPainter(self)
        # painter.setRenderHint(QPainter.HighQualityAntialiasing)
        painter.setRenderHint(QPainter.Antialiasing)

        # Koordinatenursprung in die Mitte der Flaeche legen
        # Place the coordinate origin in the center
        painter.translate(*self.center_p())
        # painter.save()
        # xShadow = 3.0
        # yShadow = 3.0
        font = QFont(self.value_fontname, self.value_fontsize)
        fm = QFontMetrics(font)

        pen_shadow = QPen()

        pen_shadow.setBrush(self.DisplayValueColor)
        painter.setPen(pen_shadow)

        text_radius = self.widget_diameter / 2 * self.text_radius_factor

        # angle_distance = (float(self.scale_angle_size) / float(self.scala_main_count))
        # for i in range(self.scala_main_count + 1):
        text = str(int(self.value))
        w = fm.width(text) + 1
        h = fm.height()
        painter.setFont(QFont(self.value_fontname, self.value_fontsize))

        # Mitte zwischen Skalenstart und Skalenende:
        # Skalenende = Skalenanfang - 360 + Skalenlaenge
        # Skalenmitte = (Skalenende - Skalenanfang) / 2 + Skalenanfang
        angle_end = float(self.scale_angle_start_value +
                          self.scale_angle_size - 360)
        angle = (angle_end - self.scale_angle_start_value
                 ) / 2 + self.scale_angle_start_value

        x = text_radius * math.cos(math.radians(angle))
        y = text_radius * math.sin(math.radians(angle))
        # print(w, h, x, y, text)
        text = [
            x - int(w / 2), y - int(h / 2),
            int(w),
            int(h), Qt.AlignCenter, text
        ]
        painter.drawText(text[0], text[1], text[2], text[3], text[4], text[5])
예제 #8
0
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
예제 #9
0
    def create_values_text(self):
        painter = QPainter(self)
        # painter.setRenderHint(QPainter.HighQualityAntialiasing)
        painter.setRenderHint(QPainter.Antialiasing)

        # Koordinatenursprung in die Mitte der Flaeche legen
        painter.translate(self.width() / 2, self.height() / 2)
        # painter.save()
        # xShadow = 3.0
        # yShadow = 3.0
        font = QFont(self.value_fontname, self.value_fontsize)
        fm = QFontMetrics(font)

        pen_shadow = QPen()

        pen_shadow.setBrush(self.DisplayValueColor)
        painter.setPen(pen_shadow)

        text_radius = self.widget_diameter / 2 * self.text_radius_factor

        # angle_distance = (float(self.scale_angle_size) / float(self.scala_main_count))
        # for i in range(self.scala_main_count + 1):
        frac, whole = math.modf(self.value)

        text = ("%0.1f" % (abs(frac)*10)) + 'E' + str(int(whole)) + ' ' + self.units
        w = fm.width(text) + 1
        h = fm.height()
        painter.setFont(QFont(self.value_fontname, self.value_fontsize))

        # Mitte zwischen Skalenstart und Skalenende:
        # Skalenende = Skalenanfang - 360 + Skalenlaenge
        # Skalenmitte = (Skalenende - Skalenanfang) / 2 + Skalenanfang
        angle_end = float(self.scale_angle_start_value + self.scale_angle_size - 360)
        angle = (angle_end - self.scale_angle_start_value) / 2 + self.scale_angle_start_value

        x = text_radius * math.cos(math.radians(angle))
        y = text_radius * math.sin(math.radians(angle))
        # print(w, h, x, y, text)
        text = [x - int(w/2), y - int(h/2), int(w), int(h), Qt.AlignCenter, text]
        painter.drawText(text[0], text[1], text[2], text[3], text[4], text[5])
예제 #10
0
    def paintEvent(self, event):
        painter = QPainter(self)
        painter.setRenderHint(painter.Antialiasing)

        tamanio = self.geometry().size()

        nuevoRect = QtCore.QRect(math.floor(self.anchoLinea / 2), math.floor(self.anchoLinea / 2), tamanio.width() - self.anchoLinea, tamanio.height() - self.anchoLinea)
        verde = QColor()
        verde.setNamedColor("#00FF00")

        amarillo = QColor()
        amarillo.setNamedColor("#FFFF00")

        rojo = QColor()
        rojo.setNamedColor("#FF0000")

        gradiente = QConicalGradient()
        gradiente.setCoordinateMode(QGradient.ObjectBoundingMode)
        gradiente.setAngle(60)
        gradiente.setColorAt(0, rojo)
        gradiente.setColorAt(0.25, amarillo)
        gradiente.setColorAt(0.50, verde)

        colorSeleccionado = QColor()
        colorSeleccionado.setNamedColor(self.colorDial)

        lapizTrazo = QPen()
        lapizTrazo.setStyle(QtCore.Qt.SolidLine)
        lapizTrazo.setWidth(self.anchoLinea)
        lapizTrazo.setBrush(colorSeleccionado)

        porcentaje = self.valor / float(self.maxValor - self.minValor)
        span = math.floor((self.finishAngle - self.startAngle) * porcentaje)

        painter.setPen(lapizTrazo)
        painter.drawArc(nuevoRect, self.startAngle * 16, span * 16)

        super(BKGauge, self).paintEvent(event)
예제 #11
0
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()
예제 #12
0
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)
예제 #13
0
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)
예제 #14
0
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)
예제 #15
0
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
예제 #16
0
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()