Ejemplo n.º 1
0
def testMany(nReps=1000):
    psp = np.empty((1, nReps, 4))  ## last axis is [amp, xoff, rise, fall]
    psp[:,:,0] = 100e-12
    psp[...,1] = 1e-3
    psp[...,2] = 0.1e-3
    psp[...,3] = 0.6e-3
    
    ## generate table of traces
    data, xVals = mkDataSet(psp, downsample=40)
    
    ## fit all traces
    guess = np.array([50e-10, 0.1e-3, 0.5e-3, 3e-3])
    bounds = np.array([(0, 5e-9), (0, 2e-3), (50e-6, 5e-3), (200e-6, 20e-3)])

    #testFit("opt.leastsq", psp, data, xVals, fitPsp, guess=guess)
    #testFit("opt.leastsq_bounded", psp, data, xVals, fitPspBounded, guess=guess, bounds=bounds)

    global fits2, times2
    fits2, times2 = fitDataSet(xVals, data, fitPsp, guess=guess, bounds=bounds)
    print("Mean fit computation time: %0.2fms" % (times.mean() * 1000))
    
    p = pg.plot()
    p.setLabel('left', 'amplitude', units='A')
    p.setLabel('bottom', 'decay tau', units='s')
    p.plot(x=fits2[0, :, 3], y=fits2[0, :, 0], pen=None, symbol='o', symbolPen=None, symbolBrush=(255,255,255,100))
    p.plot(x=[psp[0, 0, 3]], y=[psp[0, 0, 0]], pen=None, symbol='+', symbolSize=15, symbolPen={'color': 'b', 'width': 3})
    
    p = pg.plot()
    p.setLabel('left', 'rise tau', units='s')
    p.setLabel('bottom', 'decay tau', units='s')
    p.plot(x=fits2[0, :, 3], y=fits2[0, :, 2], pen=None, symbol='o', symbolPen=None, symbolBrush=(255,255,255,100))
    p.plot(x=[psp[0, 0, 3]], y=[psp[0, 0, 2]], pen=None, symbol='+', symbolSize=15, symbolPen={'color': 'b', 'width': 3})
Ejemplo n.º 2
0
def testMany(nReps=1000):
    psp = np.empty((1, nReps, 4))  ## last axis is [amp, xoff, rise, fall]
    psp[:,:,0] = 100e-12
    psp[...,1] = 1e-3
    psp[...,2] = 0.1e-3
    psp[...,3] = 0.6e-3
    
    ## generate table of traces
    data, xVals = mkDataSet(psp, downsample=40)
    
    ## fit all traces
    guess = np.array([50e-10, 0.1e-3, 0.5e-3, 3e-3])
    bounds = np.array([(0, 5e-9), (0, 2e-3), (50e-6, 5e-3), (200e-6, 20e-3)])

    #testFit("opt.leastsq", psp, data, xVals, fitPsp, guess=guess)
    #testFit("opt.leastsq_bounded", psp, data, xVals, fitPspBounded, guess=guess, bounds=bounds)

    global fits2, times2
    fits2, times2 = fitDataSet(xVals, data, fitPsp, guess=guess, bounds=bounds)
    print "Mean fit computation time: %0.2fms" % (times.mean() * 1000)
    
    p = pg.plot()
    p.setLabel('left', 'amplitude', units='A')
    p.setLabel('bottom', 'decay tau', units='s')
    p.plot(x=fits2[0, :, 3], y=fits2[0, :, 0], pen=None, symbol='o', symbolPen=None, symbolBrush=(255,255,255,100))
    p.plot(x=[psp[0, 0, 3]], y=[psp[0, 0, 0]], pen=None, symbol='+', symbolSize=15, symbolPen={'color': 'b', 'width': 3})
    
    p = pg.plot()
    p.setLabel('left', 'rise tau', units='s')
    p.setLabel('bottom', 'decay tau', units='s')
    p.plot(x=fits2[0, :, 3], y=fits2[0, :, 2], pen=None, symbol='o', symbolPen=None, symbolBrush=(255,255,255,100))
    p.plot(x=[psp[0, 0, 3]], y=[psp[0, 0, 2]], pen=None, symbol='+', symbolSize=15, symbolPen={'color': 'b', 'width': 3})
Ejemplo n.º 3
0
def test_seek():
    global x, t
    ures = 6
    s.stop()
    s['microstep_resolution'] = ures
    s['encoder_prescaler'] = 8192
    s['encoder_position'] = 0
    s['standby_current'] = 0
    s['maximum_speed'] = 50
    s['power_down_delay'] = 1200
    #s['freewheeling'] = 1000
    #s['actual_position'] = 0

    s.move(600, relative=True)
    start = time.time()
    t = []
    x = []
    while True:
        now = time.time()
        if now - start > 3:
            print "QUIT"
            break
        t.append(now - start)
        x.append(s['encoder_position'])

    pg.plot(t, x)
Ejemplo n.º 4
0
def errorSurface(axes=[3, 0],
                 v1=None,
                 v2=None,
                 bounds=None,
                 noise=0.0,
                 n=5000):
    ## compute sum of squares error between two templates over a range of differences in v
    ## the two templates are generated from the parameters in v1 and v2
    ## the error surface is computed by varying v2[axis[n]] from bounds[axis[n]][0] to bounds[axis[n]][1] on
    ## each axis of the surface.

    ## displays and returns the error surface,
    ## also returns an array of all the v2 parameters used for each point in the surface.

    x = np.linspace(0, 0.5, 5000)
    v = [1.0, 0.05, 0.05, 0.1]  ## defaults used if v1 / v2 are not given
    if v1 is None:
        v1 = v[:]
    if v2 is None:
        v2 = v1[:]

    if bounds is None:
        bounds = [(0.0, 2.0), (0.0, 0.1), (0.01, 0.1), (0.01, 0.5)]

    template1 = pspFunc(v1, x) + np.random.normal(size=len(x), scale=noise)

    ## number of iterations per axis
    n = int(n**(1.0 / len(axes)))

    axv = []
    for ax in axes:
        axv.append(np.linspace(bounds[ax][0], bounds[ax][1], n))

    err = np.empty((n, ) * len(axes))
    vals = np.empty(err.shape, dtype=object)

    inds = np.indices(err.shape).reshape((len(axes), err.size))

    for i in xrange(inds.shape[1]):
        ind = tuple(inds[:, i])
        v2a = v2[:]
        for j in range(len(axes)):
            v2a[axes[j]] = axv[j][ind[j]]
        template2 = pspFunc(v2a, x)
        err[ind] = np.sum((template2 - template1)**2)
        vals[ind] = v2a

    if len(axes) == 2:
        p = pg.plot()
        img = pg.ImageItem(err)
        p.addItem(img)
        b1 = bounds[axes[0]]
        b2 = bounds[axes[1]]
        img.setRect(QtCore.QRectF(b1[0], b2[0], b1[1] - b1[0], b2[1] - b2[0]))
    elif len(axes) == 3:
        pg.image(err)

    return err, vals
Ejemplo n.º 5
0
def showTemplates(v):
    p = pg.plot()
    x = np.linspace(0, 10e-3, 1000)
    for i in range(v.shape[0]):
        vi = v[i]
        if len(vi) > 4:
            vi = processExtraVars(vi)
            print "Convert v:", v[i], " => ", vi
        p.plot(x=x, y=pspFunc(vi, x), pen=(i, v.shape[0]*1.5))
Ejemplo n.º 6
0
def test_encoder():
    plt = pg.plot()
    pos = []
    while True:
        pos.append(s['encoder_position'])
        while len(pos) > 300:
            pos.pop(0)
        plt.plot(pos, clear=True)
        pg.QtGui.QApplication.processEvents()
Ejemplo n.º 7
0
def showTemplates(v):
    p = pg.plot()
    x = np.linspace(0, 10e-3, 1000)
    for i in range(v.shape[0]):
        vi = v[i]
        if len(vi) > 4:
            vi = processExtraVars(vi)
            print "Convert v:", v[i], " => ", vi
        p.plot(x=x, y=pspFunc(vi, x), pen=(i, v.shape[0] * 1.5))
Ejemplo n.º 8
0
def errorSurface(axes=[3, 0], v1=None, v2=None, bounds=None, noise=0.0, n=5000):
    ## compute sum of squares error between two templates over a range of differences in v
    ## the two templates are generated from the parameters in v1 and v2
    ## the error surface is computed by varying v2[axis[n]] from bounds[axis[n]][0] to bounds[axis[n]][1] on 
    ## each axis of the surface.
    
    ## displays and returns the error surface, 
    ## also returns an array of all the v2 parameters used for each point in the surface.
    
    x = np.linspace(0, 0.5, 5000)
    v = [1.0, 0.05, 0.05, 0.1]  ## defaults used if v1 / v2 are not given
    if v1 is None:
        v1 = v[:]
    if v2 is None:
        v2 = v1[:]
    
    if bounds is None:
        bounds = [(0.0, 2.0), (0.0, 0.1), (0.01, 0.1), (0.01, 0.5)]
        
    template1 = pspFunc(v1, x) + np.random.normal(size=len(x), scale=noise)
    
    ## number of iterations per axis
    n = int(n**(1.0/len(axes)))
    
    axv = []
    for ax in axes:
        axv.append(np.linspace(bounds[ax][0], bounds[ax][1], n))
        
    err = np.empty((n,)*len(axes))
    vals = np.empty(err.shape, dtype=object)
    
    inds = np.indices(err.shape).reshape((len(axes), err.size))
    
    for i in xrange(inds.shape[1]):
        ind = tuple(inds[:,i])
        v2a = v2[:]
        for j in range(len(axes)):
            v2a[axes[j]] = axv[j][ind[j]]
        template2 = pspFunc(v2a, x)
        err[ind] = np.sum((template2-template1)**2)
        vals[ind] = v2a
            
    if len(axes) == 2:
        p = pg.plot()
        img = pg.ImageItem(err)
        p.addItem(img)
        b1 = bounds[axes[0]]
        b2 = bounds[axes[1]]
        img.setRect(QtCore.QRectF(b1[0], b2[0], b1[1]-b1[0], b2[1]-b2[0]))
    elif len(axes) == 3:
        pg.image(err)
        
    return err, vals
Ejemplo n.º 9
0
def test_load():
    plt = pg.plot()
    load = []
    s['mixed_decay_threshold'] = 2047
    s.rotate(200)

    def update():
        load.append(s['actual_load_value'])
        while len(load) > 300:
            load.pop(0)
        plt.plot(load, clear=True)

    global t
    t = pg.QtCore.QTimer()
    t.timeout.connect(update)
    t.start(0)
Ejemplo n.º 10
0
    def measureTipPosition(self, padding=50e-6, threshold=0.7, frame=None, pos=None, tipLength=None, show=False):
        """Find the pipette tip location by template matching within a region surrounding the
        expected tip position.

        Return `((x, y, z), corr)`, where *corr* is the normalized cross-correlation value of
        the best template match.

        If the strength of the match is less than *threshold*, then raise RuntimeError.
        """
        # Grab one frame (if it is not already supplied) and crop it to the region around the pipette tip.
        if frame is None:
            frame = self.takeFrame()

        # load up template images
        reference = self._getReference()

        if tipLength is None:
            # select a tip length similar to template images
            tipLength = reference['tipLength']

        minImgPos, maxImgPos, tipRelPos = self.getTipImageArea(frame, padding, pos=pos, tipLength=tipLength)
        img = frame.data()
        if img.ndim == 3:
            img = img[0]
        img = img[minImgPos[0]:maxImgPos[0], minImgPos[1]:maxImgPos[1]]
        img = self.filterImage(img)

        # resample acquired image to match template pixel size
        pxr = frame.info()['pixelSize'][0] / reference['pixelSize'][0]
        if pxr != 1.0:
            img = scipy.ndimage.zoom(img, pxr)

        # run template match against all template frames, find the frame with the strongest match
        match = [self.matchTemplate(img, t) for t in reference['frames']]

        if show:
            pg.plot([m[0][0] for m in match], title='x match vs z')
            pg.plot([m[0][1] for m in match], title='y match vs z')
            pg.plot([m[1] for m in match], title='match correlation vs z')

        maxInd = np.argmax([m[1] for m in match])
        if match[maxInd][1] < threshold:
            raise RuntimeError("Unable to locate pipette tip (correlation %0.2f < %0.2f)" % (match[maxInd][1], threshold))

        # measure z error
        zErr = (maxInd - reference['centerInd']) * reference['zStep']

        # measure xy position
        offset = match[maxInd][0]
        tipImgPos = (minImgPos[0] + (offset[0] + reference['centerPos'][0]) / pxr, 
                     minImgPos[1] + (offset[1] + reference['centerPos'][1]) / pxr)
        tipPos = frame.mapFromFrameToGlobal(pg.Vector(tipImgPos))
        return (tipPos.x(), tipPos.y(), tipPos.z() + zErr), match[maxInd][1]
Ejemplo n.º 11
0
def testFit(title, psp, data, xVals, fitFn, *args, **kargs):
    global fits, times
    print "Running fit test", title
    fits, times = fitDataSet(xVals, data, fitFn, *args, **kargs)
    print "Mean fit computation time: %0.2fms" % (times.mean() * 1000)
    
    ## compute fractional error
    psp2 = psp.copy()
    psp2[1] = psp2[2]  ## compare xoff against rise when determining fractional error
    err = (fits-psp2) / psp2
    errAvg = err.mean(axis=1)
    
    ## plot log(error) in each fit parameter vs amplitude
    ## (errors get larger as amplitude approaches the noise floor)
    p1 = pg.plot(title=title)
    p1.plot(x=psp[:,0,0], y=np.log(abs(errAvg[:,0])), pen='g')
    p1.plot(x=psp[:,0,0], y=np.log(abs(errAvg[:,1])), pen='y')
    p1.plot(x=psp[:,0,0], y=np.log(abs(errAvg[:,2])), pen='r')
    p1.plot(x=psp[:,0,0], y=np.log(abs(errAvg[:,3])), pen='b')
Ejemplo n.º 12
0
def testFit(title, psp, data, xVals, fitFn, *args, **kargs):
    global fits, times
    print("Running fit test", title)
    fits, times = fitDataSet(xVals, data, fitFn, *args, **kargs)
    print("Mean fit computation time: %0.2fms" % (times.mean() * 1000))
    
    ## compute fractional error
    psp2 = psp.copy()
    psp2[1] = psp2[2]  ## compare xoff against rise when determining fractional error
    err = (fits-psp2) / psp2
    errAvg = err.mean(axis=1)
    
    ## plot log(error) in each fit parameter vs amplitude
    ## (errors get larger as amplitude approaches the noise floor)
    p1 = pg.plot(title=title)
    p1.plot(x=psp[:,0,0], y=np.log(abs(errAvg[:,0])), pen='g')
    p1.plot(x=psp[:,0,0], y=np.log(abs(errAvg[:,1])), pen='y')
    p1.plot(x=psp[:,0,0], y=np.log(abs(errAvg[:,2])), pen='r')
    p1.plot(x=psp[:,0,0], y=np.log(abs(errAvg[:,3])), pen='b')
Ejemplo n.º 13
0
def step_curve(decay_threshold=-1):
    """Measure encoder following single steps at all microstep resolutions.
    """
    s['mixed_decay_threshold'] = decay_threshold
    s['stall_detection_threshold'] = 0
    plt = pg.plot()
    for res in range(7):
        x = []
        s['microstep_resolution'] = res
        #s['encoder_prescaler'] = int(2**res * 100)
        s['encoder_prescaler'] = 6400
        for i in range(150):
            s.move(1, relative=True)
            while s['target_pos_reached'] == 0:
                pass
            x.append(s['encoder_position'])
            x.append(s['encoder_position'])
            x.append(s['encoder_position'])
            print i, x[-1]
        plt.plot(x, symbol='o')
        pg.QtGui.QApplication.processEvents()
Ejemplo n.º 14
0
    def analyze(self):
        # frames = []
        # for frame in self.frames:
        #     frames.append(frame.getImage()[np.newaxis, ...])
        # self.frameArray = np.concatenate(frames, axis=0)
        # self.imageView = pg.image(self.frameArray)

        # linear regression to determine scale between stage steps and camera microns
        x = ((self.positions - self.positions[0])**2).sum(axis=1)**0.5
        y = (self.offsets**2).sum(axis=1)**0.5
        slope, yint, r, p, stdev = scipy.stats.linregress(x, y)

        # subtract linear approximation to get residual error
        y1 = x * slope + yint
        self.xvals = x
        self.error = y - y1
        self.errorPlot = pg.plot(x,
                                 self.error,
                                 title='X axis error (slope = %0.2f um/step)' %
                                 (slope * 1e6),
                                 labels={
                                     'left': ('Error', 'm'),
                                     'bottom': ('position', 'steps')
                                 })

        # fit residual to combination of sine waves
        def fn(p, x):
            return (p[2] * np.sin((x + p[0]) * 1 * p[1]) + p[3] * np.sin(
                (x + p[0]) * 2 * p[1]) + p[4] * np.sin(
                    (x + p[0]) * 3 * p[1]) + p[5] * np.sin(
                        (x + p[0]) * 4 * p[1]))

        def erf(p, x, y):
            return fn(p, x) - y

        f0 = 6 * np.pi / x.max()  # guess there are 3 cycles in the data
        amp = self.error.max()
        self.fit = scipy.optimize.leastsq(erf, [0, f0, amp, amp, amp, amp],
                                          (x, self.error))[0]
        self.errorPlot.plot(x, fn(self.fit, x), pen='g')
Ejemplo n.º 15
0
Archivo: Imager.py Proyecto: hiuwo/acq4
    def takeImage(self):
        """
        Take an image using the scanning system and PMT, and return with the data.
        """
        # first make sure laser information is updated on the module interface
        if self.laserDev is not None:
            self.param['Wavelength'] = (self.laserDev.getWavelength()*1e9)
            self.param['Power'] = (self.laserDev.outputPower())
        else:
            self.param['Wavelength'] = 0.0
            self.param['Power'] = 0.0
        #
        # get image parameters from the ROI:
        #
        state = self.currentRoi.getState()
        w, h = state['size']
        p0 = pg.Point(0,0)
        p1 = pg.Point(w,0)
        p2 = pg.Point(0, h)
        points = [p0, p1, p2]
        points = [pg.Point(self.currentRoi.mapToView(p)) for p in points] # convert to view points (as needed for scanner)

        Xpos = self.xPos
        Ypos = self.yPos
        xCenter = Xpos
        yCenter = Ypos
        nPointsX = int(self.width/self.pixelSize)
        nPointsY = int(self.height/self.pixelSize)
        xScan = NP.linspace(0., self.width, nPointsX)
        xScan += xCenter
        sampleRate = self.param['Sample Rate']
        downsample = self.param['Downsample']
        overScan = self.param['Overscan']/100.     ## fraction of voltage scan range
        overScanWidth = self.width*overScan
        overScanPixels = int(nPointsX / 2. * overScan)
        pixelsPerRow = nPointsX + 2 * overScanPixels  ## make sure width is increased by an even number.
        samplesPerRow = pixelsPerRow * downsample
        samples = samplesPerRow * nPointsY
        if not self.param['Bidirectional']:
            saw1 = NP.linspace(0., self.width+overScanWidth, num=samplesPerRow)
            saw1 += xCenter-overScanWidth/2.0
            xSaw = NP.tile(saw1, (1, nPointsY))[0,:]
        else:
            saw1 = NP.linspace(0., self.width+overScanWidth, num=samplesPerRow)
            saw1 += xCenter-overScanWidth/2.0
            rows = [saw1, saw1[::-1]] * int(nPointsY/2)
            if len(rows) < nPointsY:
                rows.append(saw1)
            xSaw = NP.concatenate(rows, axis=0)

        yvals = NP.linspace(0., self.height, num=nPointsY)
        yvals += yCenter
        yScan = NP.empty(samples)
        for y in range(nPointsY):
            yScan[y*samplesPerRow:(y+1)*samplesPerRow] = yvals[y]
        
        # now translate this scan into scanner voltage coordinates...
        x, y = self.scannerDev.mapToScanner(xSaw, yScan, self.laserDev.name())

        # take some data
        imgData = NP.zeros((pixelsPerRow, nPointsY))
        for N in xrange(self.param['Average']):

            cmd= {'protocol': {'duration': samples/sampleRate},
                  'DAQ' : {'rate': sampleRate, 'numPts': samples, 'downsample':downsample}, 
                  'Scanner-Raw': {
                      'XAxis' : {'command': x},
                      'YAxis' : {'command': y}
                      },
                  'PockelCell': {'Switch' : {'preset': self.param['Pockels']}},
                  'PMT' : {
                      'Input': {'record': True},
                    #  'PlateVoltage': {'record' : False, 'recordInit': True}
                      }
                }
            task = self.Manager.createTask(cmd)
            if self.param['Blank Screen'] and not self.ui.video_button.isChecked(): # prevent video push from using blanking
                with ScreenBlanker():
                    task.execute(block = False)
                    while not task.isDone():
                        QtGui.QApplication.processEvents()
                        time.sleep(0.01)
            else:
                task.execute(block = False)
                while not task.isDone():
                    QtGui.QApplication.processEvents()
                    time.sleep(0.01)
    
            data = task.getResult()
            imgData1 = data['PMT']['Input'].view(NP.ndarray)
            imgData1.shape = (nPointsY, pixelsPerRow)
            imgData += imgData1.transpose()
        
        if self.param['Average'] > 1:
            imgData = imgData/self.param['Average']
            
        if self.param['Bidirectional']:
            for y in range(1, nPointsY, 2):
                imgData[:,y] = imgData[::-1,y]
            if self.param['Decomb', 'Auto']:
                imgData, shift = self.decomb(imgData, minShift=0*sampleRate, maxShift=200e-6*sampleRate)  ## correct for mirror lag up to 200us
                self.param['Decomb', 'Shift'] = shift / sampleRate
            else:
                imgData, shift = self.decomb(imgData, auto=False, shift=self.param['Decomb', 'Shift']*sampleRate)
                
        if overScanPixels > 0:
            imgData = imgData[overScanPixels:-overScanPixels]  ## remove overscan

        if self.img is not None:
            self.cameraModule.window().removeItem(self.img)
            self.img = None
        
        # code to display the image on the camera image
        self.img = pg.ImageItem(imgData) # make data into a pyqtgraph image
        self.cameraModule.window().addItem(self.img)
        self.currentRoi.setZValue(10)
        self.hideOverlayImage()
        
        w = imgData.shape[0]
        h = imgData.shape[1]
        localPts = map(pg.Vector, [[0,0], [w,0], [0, h], [0,0,1]]) # w and h of data of image in pixels.
        globalPts = map(pg.Vector, [[Xpos, Ypos], [Xpos+self.width, Ypos], [Xpos, Ypos+self.height], [0, 0, 1]]) # actual values in global coordinates
        ##imgData.shape[0]*imgData.shape[1] # prog['points'] # sort of. - 
        m = pg.solve3DTransform(localPts, globalPts)
        m[:,2] = m[:,3]
        m[2] = m[3]
        m[2,2] = 1

        tr = QtGui.QTransform(*m[:3,:3].transpose().reshape(9))

        if self.ui.hide_check.isChecked() is False:
            if self.img is not None:
                self.cameraModule.window().removeItem(self.img)
            self.img = None
        
        # code to display the image on the camera image
            self.img = pg.ImageItem(imgData) # make data into a pyqtgraph image
            self.cameraModule.window().addItem(self.img)
            self.hideOverlayImage()
            self.img.setTransform(tr)
        
# flip the PMT image LR, since that is how it is... there is a mirror in the path
# (should this be a settable parameter? )

        imgData = NP.fliplr(imgData)
        
        if self.param['Show PMT V']:
            x=NP.linspace(0, samples/sampleRate, imgData.size)
            pg.plot(y=imgData.reshape(imgData.shape[0]*imgData.shape[1]), x=x)
        if self.param['Show Mirror V']:
            pg.plot(y=xScan, x=NP.linspace(0, samples/self.param['Sample Rate'], xScan.size))
        
        # generate all meta-data for this frame
        info = self.saveParams()
        info['transform'] = pg.SRTTransform3D(tr)
        #print 'info: ', info                            
        return (imgData, info)
Ejemplo n.º 16
0
def showFit(index):
    global xVals, data, psp, fits
    p = pg.plot(xVals, data[index])
    p.plot(xVals, pspFunc(psp[index], xVals), pen='b')
    p.plot(xVals, pspFunc(fits[index], xVals), pen='r')
Ejemplo n.º 17
0
Archivo: Imager.py Proyecto: ablot/acq4
    def takeImage(self, doShutter = True, reCompute = True):
        """
        Take an image using the scanning system and PMT, and return with the data.
        doShutter True means that we normally trigger the shutter from here
        but there may be times when that is not appropriate
        """
        # first make sure laser information is updated on the module interface
        if self.laserDev is not None:
            self.param['Wavelength'] = (self.laserDev.getWavelength()*1e9)
            self.param['Power'] = (self.laserDev.outputPower())
        else:
            self.param['Wavelength'] = 0.0
            self.param['Power'] = 0.0
        
        sampleRate = self.param['Sample Rate']
        if doShutter and self.laserDev is not None and self.laserDev.hasShutter:
            self.laserDev.openShutter()
        p0 = pg.Point(self.xPos,self.yPos)
        p1 = pg.Point(self.xPos+self.width,self.yPos)
        p2 = pg.Point(self.xPos, self.height+self.yPos)
        points = [p0, p1, p2]
#        points = [pg.Point(p) for p in points]
#        [pg.Point(self.currentRoi.mapToView(p)) for p in points]        
        # compute the scan voltages and return some computed values
        if reCompute: # only update if asked - otherwise use old ones.
            (self.xScanner, self.yScanner) = SUF.designRectScan(scannerDev = self.scannerDev,
                                    laserDev = self.laserDev.name(), 
                                    rectRoi = points,
                                    pixelSize = self.pixelSize,
                                    sampleRate = self.param['Sample Rate'],
                                    downSample = self.param['Downsample'],
                                    overScan = self.param['Overscan'],
                                    bidirectional = self.param['Bidirectional'])
        # Now, take some data
       # print SUF.getScanXYSize()
        imgData = NP.zeros(SUF.getScanXYSize()) # allocate an array
        samples = SUF.getSamples()
        for N in xrange(self.param['Average']):
            # set up a task for the task manager.
            cmd= {'protocol': {'duration': samples/self.param['Sample Rate']},
                  'DAQ' : {'rate': self.param['Sample Rate'], 'numPts': samples,
                           'downsample': self.param['Downsample']}, 
                  'Scanner-Raw': {
                      'XAxis' : {'command': self.xScanner},
                      'YAxis' : {'command': self.yScanner}
                      },
                  self.attenuatorDev.name(): {self.attenuatorChannel: {'preset': self.param['Pockels']}},
                  self.detectorDev.name(): {
                      self.detectorChannel: {'record': True},
                    #  'PlateVoltage': {'record' : False, 'recordInit': True}
                      }
                }
            task = self.Manager.createTask(cmd)
            if self.param['Blank Screen'] and not self.ui.video_button.isChecked(): # prevent video push from using blanking
                with ScreenBlanker():
                    task.execute(block = False)
                    while not task.isDone():
                        QtGui.QApplication.processEvents()
                        time.sleep(0.01)
            else:
                task.execute(block = False)
                while not task.isDone():
                    QtGui.QApplication.processEvents()
                    time.sleep(0.01)     
            data = task.getResult() # obvious, but here is where we get the data
            imgData1 = data[self.detectorDev.name()][self.detectorChannel].view(NP.ndarray) # which is a PMT voltage array
            xys = SUF.getScanXYSize()
            imgData1.shape = (xys[1], xys[0]) # (nPointsY, pixelsPerRow) # make 2d image
            imgData += imgData1.transpose() # sum if we are averaging.

        if doShutter and self.laserDev is not None and self.laserDev.hasShutter:
            self.laserDev.closeShutter() # immediately after acquisition...        
        if self.param['Average'] > 1:
            imgData = imgData/self.param['Average']            
        
        if self.param['Bidirectional']:
            imgData, shift = SUF.adjustBidirectional(imgData, 
                                                            self.param['Decomb', 'Auto'],
                                                            self.param['Decomb', 'Shift'])
            if self.param['Decomb', 'Auto']:
                self.param['Decomb', 'Shift'] = shift
            #for y in range(1, SUF.getnPointsY(), 2): # reverse direction for alternate rows
                #imgData[:,y] = imgData[::-1,y]
            #if self.param['Decomb', 'Auto']:
                #imgData, shift = SUF.decomb(imgData, minShift=0*sampleRate, maxShift=200e-6*sampleRate)  ## correct for mirror lag up to 200us
                #self.param['Decomb', 'Shift'] = shift / sampleRate
            #else:
                #imgData, shift = SUF.decomb(imgData, auto=False, shift=self.param['Decomb', 'Shift']*sampleRate)
                
        imgData = SUF.removeOverscan(imgData)
        #overScanPixels = SUF.getOverScanPixels()
        #if overScanPixels > 0: # remove the overscan for one image.
            #imgData = imgData[overScanPixels:-overScanPixels]  ## remove overscan

        w = imgData.shape[0]
        h = imgData.shape[1]
        localPts = map(pg.Vector, [[0,0], [w,0], [0, h], [0,0,1]]) # w and h of data of image in pixels.
        #globalPts = map(pg.Vector, [[self.xPos, self.yPos], 
                                    #[self.xPos+self.width, self.yPos], 
                                    #[self.xPos, self.yPos+self.height], [0, 0, 1]]) # actual values in global coordinates
        globalPts = map(pg.Vector, [points[0], 
                                    points[1], 
                                    points[2], [0, 0, 1]]) # actual values in global coordinates
        ##imgData.shape[0]*imgData.shape[1] # prog['points'] # sort of. - 
        m = pg.solve3DTransform(localPts, globalPts)
        m[:,2] = m[:,3]
        m[2] = m[3]
        m[2,2] = 1
        tr = QtGui.QTransform(*m[:3,:3].transpose().reshape(9))

        if self.img is not None and self.ui.hide_check.isChecked() is False:
            self.cameraModule.window().removeItem(self.img)
    
        # display the image on top of the camera image
        self.img = pg.ImageItem(imgData) # make data into a pyqtgraph image
        self.img.setTransform(tr)
        self.cameraModule.window().addItem(self.img)
        self.hideOverlayImage() # hide if the box is checked    
        # flip the PMT image LR, since that is how it is... there is a mirror in the path
        # (should this be a settable parameter? )
        imgData = NP.fliplr(imgData)        
        if self.param['Show PMT V']:
            xv=NP.linspace(0, samples/sampleRate, imgData.size)
            pg.plot(y=imgData.reshape(imgData.shape[0]*imgData.shape[1]), x=xv)
        if self.param['Show Mirror V']:
            pg.plot(y=y, x=NP.linspace(0, samples/self.param['Sample Rate'], len(x)))
        
        # generate all meta-data for this frame
        info = self.saveParams()
        info['transform'] = pg.SRTTransform3D(tr)
        #print 'info: ', info                            
        return (imgData, info)
Ejemplo n.º 18
0
Archivo: Imager.py Proyecto: hiuwo/acq4
    def cameraSnap(self):
        width = self.param['Image Width']
        height = self.param['Image Height']
        
        xscan = self.regionCtrl.width()
        yscan = self.regionCtrl.height()
        xcenter = self.regionCtrl.center().x()
        ycenter = self.regionCtrl.center().y()
            
        sampleRate = self.param['Sample Rate']
        downsample = self.param['Downsample']
        overscan = self.param['Overscan']/100.     ## fraction of voltage scan range
        xscan *= overscan + 1.0 
        overscanPixels = int(width / 2. * overscan)
        pixelsPerRow = width + 2 * overscanPixels  ## make sure width is increased by an even number.
        samplesPerRow = pixelsPerRow * downsample
        samples = samplesPerRow * height
        if not self.param['Bidirectional']:
            saw1 = NP.linspace(xcenter-xscan, xcenter+xscan, samplesPerRow)
            xScan = NP.tile(saw1, (1, height))[0,:]
        else:
            saw1 = NP.linspace(xcenter-xscan, xcenter+xscan, samplesPerRow)
            rows = [saw1, saw1[::-1]] * int(height/2)
            if len(rows) < height:
                rows.append(saw1)
            xScan = NP.concatenate(rows, axis=0)
            
        yvals = NP.linspace(ycenter-yscan, ycenter+yscan, height)
        yScan = NP.empty(samples)
        for y in range(height):
            yScan[y*samplesPerRow:(y+1)*samplesPerRow] = yvals[y]
        
            
        cmd= {'protocol': {'duration': samples/sampleRate},
              'DAQ' : {'rate': sampleRate, 'numPts': samples, 'downsample':downsample}, 
              #'Scanner-Raw': {
                  #'XAxis' : {'command': xScan},
                  #'YAxis' : {'command': yScan}
                  #},
              'Scanner': {
                  'xPosition' : xScan,
                  'yPosition' : yScan
                  },
              self.attenuatorDev.name(): {self.attenuatorChannel : {'preset': self.param['Pockels']}},
              self.detectorDev.name() : {
                  self.detectorChannel: {'record': True},
                  }
            }
        # take some data
        task = self.Manager.createTask(cmd)
        if self.param['Blank Screen']:
            with ScreenBlanker():
                task.execute(block = False)
                while not task.isDone():
                    QtGui.QApplication.processEvents()
                    time.sleep(0.1)
        else:
            task.execute(block = False)
            while not task.isDone():
                QtGui.QApplication.processEvents()
                time.sleep(0.1)

        data = task.getResult()
        imgData = data[self.detectorDev.name()]['Input'].view(NP.ndarray)
        imgData.shape = (height, pixelsPerRow)
        imgData = imgData.transpose()
        
        if self.param['Bidirectional']:
            for y in range(1, height, 2):
                imgData[:,y] = imgData[::-1,y]
            if self.param['Decomb', 'Auto']:
                imgData, shift = self.decomb(imgData, minShift=0*sampleRate, maxShift=200e-6*sampleRate)  ## correct for mirror lag up to 200us
                self.param['Decomb', 'Shift'] = shift / sampleRate
            else:
                #print self.param['Decomb', 'Shift'], sampleRate
                imgData, shift = self.decomb(imgData, auto=False, shift=self.param['Decomb', 'Shift']*sampleRate)
            
        
        if overscanPixels > 0:
            imgData = imgData[overscanPixels:-overscanPixels]  ## remove overscan

        if self.param['Show PMT V']:
            pg.plot(y=imgData, x=NP.linspace(0, samples/sampleRate, imgData.size))
        if self.param['Show Mirror V']:
            pg.plot(y=xScan, x=NP.linspace(0, samples/self.param['Sample Rate'], xScan.size))

        self.view.setImage(imgData)

        return imgData
        
Ejemplo n.º 19
0
    p.system.defaultState['p2'][0] = np.array([0, -100e-6])
    p.system.defaultState['p2'][2] = 'fixed'
    p.system.defaultState['numFrames'][0] = 1
    p.updateSystem()
    w = ParameterTree()
    w.setParameters(p)
    w.show()
    return p, w


if __name__ == '__main__':
    import user
    test_RectScan()
    p, w = test_RectScanParameter()
    w.resize(300, 700)
    plt = pg.plot()

    def update():
        global p, plt
        arr = np.zeros((100000, 2))
        plt.clear()
        try:
            p.system.writeArray(arr)
            plt.plot(arr[:, 0], arr[:, 1])
            r = p.system.numCols - 1
            e = p.system.numCols * p.system.numRows - 1
            x = [arr[0, 0], arr[r, 0], arr[e, 0]]
            y = [arr[0, 1], arr[r, 1], arr[e, 1]]
            b = list(map(pg.mkBrush, ['g', 'b', 'r']))
            plt.plot(x, y, pen=None, symbol='o', symbolBrush=b)
            plt.plotItem.setAspectLocked()
Ejemplo n.º 20
0
def showFit(index):
    global xVals, data, psp, fits
    p = pg.plot(xVals, data[index])
    p.plot(xVals, pspFunc(psp[index], xVals), pen='b')
    p.plot(xVals, pspFunc(fits[index], xVals), pen='r')