Example #1
0
    def newFrame(self, frame):
        """
        Called when task is finished (truly completes, no errors/abort)
        frame contains all of the data returned from all devices
        """
        self.lastFrame = frame
        self.update()  # updates image

        # Store image if requested
        storeFlag = frame['cmd']['protocol']['storeData'] # get flag 
        if storeFlag and len(self.lastResult) > 0:
            result = self.lastResult[0]  # for now we only handle single-component programs

            dirhandle = frame['cmd']['protocol']['storageDir'] # grab storage directory
            
                       
            # to line below, add x, y for the camera (look at camera video output)

            info = [dict(name='Time', units='s', values=result['scanParams'].frameTimes()), 
                    dict(name='X'), dict(name='Y'), {
                        'transform': result['transform'],
                        'imageProcessing': result['params'],
                    }]
            ma = metaarray.MetaArray(result['image'], info=info)
            fh = dirhandle.writeFile(ma, 'Imaging.ma')
            fh.setInfo(transform=result['transform'])
Example #2
0
 def processData(self, In):
     data = In.view(np.ndarray)
     units = None
     if (hasattr(In, 'implements') and In.implements('MetaArray')):
         units = In.axisUnits(1)
     y,x = np.histogram(data, bins=self.ctrls['numBins'].value())
     x = (x[1:] + x[:-1]) * 0.5
     return metaarray.MetaArray(y, info=[{'name': 'bins', 'values': x, 'units': units}])
Example #3
0
    def getResult(self):
        ## getResult from DAQGeneric, then add in command waveform
        result = DAQGenericTask.getResult(self)
        if result is None:
            return None

        arr = result.view(np.ndarray)

        daqInfo = result._info[-1]['DAQ']
        ## find DAQ info for any output channel
        for ch in ['shutter', 'qSwitch', 'pCell']:
            if ch in daqInfo:
                ds = daqInfo[ch].get('downsampling', 1)
                break

        if 'powerWaveform' in self.cmd:
            ## downsample power waveform to match other channels
            power = self.cmd['powerWaveform']
            if ds > 1:
                power = NiDAQ.meanResample(power, ds)
            arr = np.append(arr, power[np.newaxis, :], axis=0)

            #result = np.append(result, self.cmd['powerWaveform'][np.newaxis, :], axis=0)
            result._info[0]['cols'].append({'name': 'power', 'units': 'W'})
        elif 'switchWaveform' in self.cmd:
            switch = self.cmd['switchWaveform']
            if ds > 1:
                switch = NiDAQ.meanResample(switch, ds)
            arr = np.append(arr, switch[np.newaxis, :], axis=0)
            #result = np.append(result, self.cmd['switchWaveform'][np.newaxis, :], axis=0)
            result._info[0]['cols'].append({'name': 'switch'})
        #elif 'power' in self.cmd:
        #arr = np.append(arr, self.cmd['power']['command'][np.newaxis, :], axis=0)
        #result._info[0]['cols'].append({'name': str(self.cmd['power']['type'])})

        info = {
            'currentPower': self.currentPower,
            'expectedPower': self.expectedPower,
            'requestedWavelength': self.cmd.get('wavelength', None),
            'shutterMode': self.cmd['shutterMode'],
            'powerCheckRequested': self.cmd.get('checkPower', False),
            'pulsesCmd': self.cmd.get('pulses', None)
        }

        result._info[-1]['Laser'] = info

        result = metaarray.MetaArray(arr, info=result._info)
        self.dev.lastResult = result

        return result
Example #4
0
import user

Qt.QApplication.setGraphicsSystem('raster')
app = Qt.QApplication([])

win = Qt.QMainWindow()
cw = Qt.QWidget()
win.setCentralWidget(cw)
ui = builderTemplate.Ui_Form()
ui.setupUi(cw)
win.show()
win.resize(800, 600)

ui.labelTree.header().setResizeMode(Qt.QHeaderView.ResizeToContents)

data = metaarray.MetaArray(file=dataFile, mmap=True)
## data must have axes (anterior, dorsal, right)
if not os.path.exists(labelFile):
    label = metaarray.MetaArray(np.zeros(data.shape[:-1], dtype=np.uint16),
                                info=data.infoCopy()[:3] + [{
                                    'labels': {}
                                }])
    label.write(labelFile, mappable=True)
label = metaarray.MetaArray(file=labelFile, mmap=True, writable=True)

labelCache = None
labelInfo = {}
#ui.view.enableMouse()
#ui.view.setAspectLocked(True)

vb = pg.ViewBox()
Example #5
0
 def process(self, data, display=True):
     
     rp = self.ctrls['risePower'].value()
     stimTime = self.ctrls['stimulusTime'].value()
     times = data.xvals('Time')
     dt = times[1] - times[0]
     data1 = data.view(np.ndarray)
     if stimTime > times[-1]:
         raise Exception("stimulusTime is larger than length of input data.")
     stimInd = np.argwhere(times>=stimTime)[0][0]
     
     # 1. make sure offset is removed
     offset = np.median(data1[:stimInd])
     data2 = data1 - offset
     
     # 2. check for zero-crossing events within 4ms after stimulus
     cross = functions.zeroCrossingEvents(data2[stimInd:])
     maxInd = 4e-3 / dt
     minLength = self.ctrls['minDirectDuration'].value() / dt
     gotEvent = None
     for start, length, sum, peak in cross:
         if start > maxInd:
             break
         if length < minLength:
             continue
         if gotEvent is None or length > gotEvent[1]:
             gotEvent = (start+stimInd, length)
     #if len(cross) == 0: ## must be a single large event
         #gotEvent = (0, len(data2)-stimInd)
     
     fitParams = dict(
         directFitAmp1=0., directFitAmp2=0., directFitTime=0., 
         directFitRise=0., directFitDecay1=0., directFitDecay2=0.,
         directFitPeakTime=0., directFitPeak=0., directFitSubtracted=False,
         directFitValid=False,
         )
     
     # 3. if there is no large event near stimulus, return original data
     if gotEvent is None:
         if display:
             self.plotItem.clear()
         return {'output': data, 'fitParams': fitParams, 'plot': self.plotItem}
     
     #print "============"
     #print stimInd
     #print gotEvent
     #print cross[:20]
     
     # 4. guess amplitude, tau from detected event
     evStart = gotEvent[0]
     evEnd = evStart + gotEvent[1]
     evRgn = data2[evStart:evEnd]
     #pg.plot(evRgn)
     mx = evRgn.max()
     mn = evRgn.min()
     ampGuess = mx if abs(mx) > abs(mn) else mn
     tauGuess = gotEvent[1] * dt
     if ampGuess < 0:
         ampBound = [None, 0]
     else:
         ampBound = [0, None]
     
     # 5. fit
     guess = [ampGuess*2, ampGuess*2, stimTime, 1e-3, tauGuess*0.5, tauGuess*2]
     bounds = [
         ampBound, ampBound,
         [stimTime, stimTime+4e-3],
         [1e-4, 100e-3],
         [1e-3, 1],
         [5e-3, 10],
     ]
     #print guess
     #print bounds
     endInd = evStart + gotEvent[1] * 10
     fitYData = data2[stimInd:endInd]
     fitXData = times[stimInd:endInd]
     fit = functions.fitDoublePsp(x=fitXData, y=fitYData, guess=guess, bounds=bounds, risePower=rp)
     
     # 6. subtract fit from original data (offset included), return
     y = functions.doublePspFunc(fit, times, rp)
     
     if display:
         self.plotItem.setData(x=fitXData, y=y[stimInd:endInd], pen=self.ctrls['plotColor'].color())        
         
     ## prepare list of fit params for output
     (xMax, yMax) = functions.doublePspMax(fit)
     xMax -= fit[2]  ## really interested in time-to-peak, not the exact peak time.
     
     fitParams = dict(
         directFitAmp1=fit[0], directFitAmp2=fit[1], directFitTime=fit[2], 
         directFitRise=fit[3], directFitDecay1=fit[4], directFitDecay2=fit[5],
         directFitPeakTime=xMax, directFitPeak=yMax, directFitSubtracted=None, directFitValid=True,
         )
         
     if self.ctrls['subtractDirect'].isChecked():
         out = metaarray.MetaArray(data-y, info=data.infoCopy())
         fitParams['directFitSubtracted'] = True
     else:
         out = data
         fitParams['directFitSubtracted'] = False
         
         
     return {'fitParams': fitParams, 'output': out, 'plot': self.plotItem}