def stimulation(self, circle_path, outputDir):

        #Paramters of Stimulation
        number_of_repetitions = 10
        interTrainDelay = 20000  # 10000 = 0.5s
        bin_length = 500  #Number of datapoints to crop after stimulus
        amp1 = 10
        amp2 = 10
        phase1 = 4
        phase2 = 4

        #Set gain back to normal operation conditions
        mea1kusr.init.board()
        mea1kusr.init.chip()

        save = stst.save('localhost')
        save.mkDir(outputDir)
        save.reset()

        print 'make chip'
        chip = libarray.Chip()
        print 'done'

        #mea1k.go(mea1k.cmdVRefMosR(1100)) #gives stable traces but many out of bounds after stim

        # Turn on power for the stimulation buffers
        mea1k.go(
            mea1k.cmdCore(
                onChipBias=1,
                stimPowerDown=0,
                outputEn=1,
                spi=0,  # 0 == DataxDO off
                tx=0,  # 0 == DAC0
                rstMode=0,  # 0 == auto
                offsetCyc=7,
                resetCyc=7,
                wlCyc=7))

        mea1k.go(
            mea1k.cmdReadout(
                s1Bypass=0,
                s1Gain=1,  # 1 == x16   0 == x7
                s1RstMode=0,  # 0 == disconnect
                s2Bypass=0,
                s2Gain=5,  # 5 == x16
                s3Bypass=0,
                s3Gain=0))  # 0 ==x2

        #Import the information about the stimulation electrodes
        el_list = h5py.File(circle_path + '/segmentation_logfile.h5', 'r')
        routed_el = [
            values['stim_el/gotten_el'][:]
            for key, values in el_list.iteritems()
        ]
        rec_el = [
            values['rec_el/gotten_el'][:]
            for key, values in el_list.iteritems()
        ]
        el_list.close()

        logfile = h5py.File(outputDir + '/stimlist_stim_config_.hdf5', 'w')
        lengths = [i.size for i in routed_el]

        #Start iterating over each electrode
        print '{0:02} iterations to be done.'.format(max(lengths))
        for i in range(max(lengths)):
            configFile = circle_path + '/config_structure/circles.hex.nrk'
            chip.loadHEX(configFile)
            print 'configFile loaded...'

            print 'Offset MEA around 512 bits...'
            Api = mea1kusr.api.Api()
            Api.binary_offset(512)
            #Offset the electrodes around 512 bits.
            print 'Offset done'

            stimlist = []
            for j in routed_el:
                if i < j.size:
                    stimlist.append(j[i])

            # Save the stimulation electrodes as attributes
            stim_group = logfile.create_group('stim_config_' + str(i) +
                                              '/stimlist')
            for k, p in enumerate(stimlist):
                stim_group.attrs.create('channel_' + str(k), p)

            rec_group = logfile.create_group('stim_config_' + str(i) +
                                             '/recording_electrodes')
            for k, p in enumerate(rec_el):
                rec_group.attrs.create('channel_' + str(k), p)

            stimChannels = []
            for k in stimlist:
                chip.electrodeToStim(k)
                stimChannels.append(chip.queryStimAtElectrode(k))

                chip.download()
            time.sleep(2)
            print 'El. \tbuffer'
            for p, k in enumerate(stimChannels):
                print stimlist[p], '\t', k

            while -1 in stimChannels:
                stimChannels.remove(-1)

            print 'Offset MEA around 512 bits...'
            Api = mea1kusr.api.Api()
            Api.binary_offset(512)
            #Offset the electrodes around 512 bits.
            print 'Offset done'

            save.openDir(outputDir)
            save.mapping(chip.get_mapping())

            c = mea1k.Config()
            c.add(self.switchOffAllChannels())
            c.add(self.switchOnChannels(stimChannels, 1))
            c.add(mea1k.cmdDelaySamples(100))

            for l in range(number_of_repetitions):
                c.add(
                    mea1k.cmdDelaySamples(interTrainDelay - (phase1 + phase2))
                )  #-8 to account for the stimulus length
                c.add(
                    self.voltageBiPhasicPulse(512, amp1, amp2, phase1, phase2))
            train_time = (number_of_repetitions * interTrainDelay) / 20000.

            save.start('raw_stim_config_' + str(i))
            c.send()
            time.sleep(train_time + 2)
            save.stop()
            time.sleep(3)

            raw_file = h5py.File(
                outputDir + '/raw_stim_config_' + str(i) + '.raw.h5', 'r')
            DAC = raw_file['sig'][1024, :]
            over_threshold_islets = np.where(DAC > 512 + (amp1 / 2))[
                0]  #Sometimes the stimulation buffer doesn't send a DAC value
            stim_edges = over_threshold_islets[np.hstack(
                (0,
                 np.asarray([
                     1 + el
                     for el in np.where(np.diff(over_threshold_islets) != 1)[0]
                 ])))]  #Extract the timing of the stimuli

            index = np.asarray(
                [np.arange(0, bin_length) + c for c in stim_edges])
            seconds = index / 20000.

            el_indices = []
            missing = {}
            for keys, values in logfile[
                    'stim_config_' + str(i) +
                    '/recording_electrodes'].attrs.iteritems():
                missing[keys] = []
                for it in values[:]:
                    try:
                        el_indices.append(
                            np.where(
                                raw_file['mapping']['electrode'] == it)[0][0])
                    except:
                        missing[keys].append(it)

            print 'miss.el. keys \t values'
            for keys, values in missing.iteritems():
                if values:
                    print '\t', keys, values
                    true_rec_el = list(
                        logfile['stim_config_' + str(i) +
                                '/recording_electrodes'].attrs[keys])
                    del logfile['stim_config_' + str(i) +
                                '/recording_electrodes'].attrs[keys]
                    for val in values:
                        true_rec_el.remove(val)
                    logfile['stim_config_' + str(i) +
                            '/recording_electrodes'].attrs.modify(
                                keys, true_rec_el)

            trace = np.empty(
                (1028, bin_length * stim_edges.size)
            )  #number_of_repetitions instead of stim_edges.size doesn't always work because sometimes the buffer missses some commands
            raw_file['sig'].read_direct(trace,
                                        source_sel=np.s_[:, index.flatten()])
            f = h5py.File(outputDir + '/stim_config_' + str(i) + '.h5', 'w')
            cropped_trace = trace[sorted(el_indices)]
            if not stim_edges.size == number_of_repetitions:
                print 'DAC channel transmitted {0:03} out of {1:01} stimuli.'.format(
                    stim_edges.size, number_of_repetitions)
                print 'Raw_trace is padded with zeros to get desired size.'
                corrected_traces = 512 * np.ones(
                    (len(el_indices), bin_length * number_of_repetitions))
                corrected_traces[:,
                                 bin_length * stim_edges.size] = cropped_trace
                f.create_dataset('sig', data=corrected_traces)
            else:
                f.create_dataset('sig', data=cropped_trace)
            f['mapping'] = raw_file['mapping'][sorted(el_indices)]
            f['proc0/spikeTimes'] = raw_file['proc0/spikeTimes'][:]
            f['time'] = seconds
            f['settings'] = raw_file['settings/gain'][:]
            f['version'] = raw_file['version'][:]

            raw_file.close()
            os.remove(outputDir + '/raw_stim_config_' + str(i) + '.raw.h5')
            f.close()
            print 'Iteration and postprocessing no. {0:03}/{1:01} done.'.format(
                i, max(lengths))

        logfile.close()
Exemplo n.º 2
0
configDir = '/opt/MaxLab/configs/28x6x6/'
intermediate_data = '/home/user/Desktop/Data/' + Folder_name + '/'

#date_string = datetime.datetime.now().strftime('%y%m%d')
outputDir = intermediate_data + chip_name + '/PDMS_loc'

print outputDir

## Basic setup of chip & board

# default initialization
mea1kusr.init.board()
mea1kusr.init.chip()  # Corresponds to initialize on measerver

chip = libarray.Chip()  # Create Chip variable
lc = mea1k.Loop()  # Create loop variable (execute fast commands)

# reduce amplifier gain (ADC), amplifier have three stages: s1, s2, s3
#This amplifier is tuned to enhance neuronal signals (linear in uV-range). Amplifier is not
#optimal to enhance 1 kHz-stimulus in mV range (but still usable).
mea1k.go(
    mea1k.cmdReadout(
        s1Bypass=0,  # Bypass amplifier if needed
        s1Gain=0,  # 0 == x7 (=7-fache Verstaerkung)
        s1RstMode=0,  # 0 == disconnect amplifier
        s2Bypass=0,
        s2Gain=2,  # 2 == x2 (=14-fache Verstaerkung)
        s3Bypass=0,
        s3Gain=0  # 0 ==x2
    ))
    hdf = HDFStore(outputDir + '/stimlist_logfile.h5')
    f = File(path + '/segmentation_logfile.h5', "r")
    for i in range(len(f)):
        #Import the metadata of the configurations.
        routed_electrodes = np.asarray(f['structure_' +
                                         str(i + 1)]['gotten_el'][:])
        x = routed_electrodes % 220
        y = routed_electrodes / 220
        el_array = np.zeros((120, 220))
        el_array[y, x] = 1
        stim_list.append(manual_annot(el_array))
        hdf.put('Stim_el_struct' + str(i + 1), Series(stim_list[i]))
    hdf.close()

print 'make chip'
chip = libarray.Chip()
print 'done'

# Turn on power for the stimulation buffers
mea1k.go(
    mea1k.cmdCore(
        onChipBias=1,
        stimPowerDown=0,
        outputEn=1,
        spi=0,  # 0 == DataxDO off
        tx=0,  # 0 == DAC0
        rstMode=0,  # 0 == auto
        offsetCyc=7,
        resetCyc=7,
        wlCyc=7))
Exemplo n.º 4
0
    def testElectrodes(self):
    	import math
    	import mea1k
    	import libarray
    	import mea1kusr.init
    	import mea1kusr.save
        import mea1kusr.api

    	## Program an FPGA loop on VRefVari
    	def sineVari(t_period, n_samples, amp=5, periods=1):
            lc.stopLoop()
            lc.clear()
            lc.reset()
            lc.setStart() #Start the period'
            for i in range(0,n_samples):
                v = int(-amp*math.sin( periods*2*math.pi /n_samples * i)) #Amplitude of the sin-wave in bits
                s = int(20e3 * t_period/n_samples) #Time between the samples in bits. 1 bit = 50us = sampling freq.
            	#print i,v,s
            	lc.toLoop( mea1k.cmdVRefVari( 2048+v ) ) #Program v around 2048 bits. DAC has 12 bits
            			 #(=max. 4098 bits)
            	lc.toLoop( mea1k.cmdDelaySamples( s ))
            lc.setStop()
            lc.download() #Download the loop to the FPGA


    	configDir = "/opt/MaxLab/configs/28x6x6/"
        outputDir = self.path

    	## Basic setup of chip & board

    	# default initialization
    	mea1kusr.init.board()
    	mea1kusr.init.chip() # Corresponds to initialize on measerver

    	chip = libarray.Chip() # Create Chip variable
    	lc   = mea1k.Loop() # Create loop variable (execute fast commands)

    	# reduce amplifier gain (ADC), amplifier have three stages: s1, s2, s3
    	#This amplifier is tuned to enhance neuronal signals (linear in uV-range). Amplifier is not
    	#optimal to enhance 1 kHz-stimulus in mV range (but still usable).
    	mea1k.go( mea1k.cmdReadout(
        		s1Bypass=0,			# Bypass amplifier if needed
        		s1Gain=0,                   # 0 == x7 (=7-fache Verstaerkung)
        		s1RstMode=0,                # 0 == disconnect amplifier
        		s2Bypass=0,
        		s2Gain=2,                   # 2 == x2 (=14-fache Verstaerkung)
        		s3Bypass=0,
        		s3Gain=0                    # 0 ==x2
    	))

    	'''PCB has 8 analog switches in total, 4xSW1 and 4xSW2. SW2 can be completely open (=0).
        For SW1 we want to connect pin NO1 to pin NO4 -> connect int. ref el to VRefVari
        (which are the DAC's). SW1_1/2/3/4 is 	 represented by four binary digits. Eg. 0001 (=1)
        closes first switch, eg. connects NO1 and COM1. 1000 	(=8) closes the fourth switch,
        eg. connects NO4 and COM4. In hexadecimal this is 9 (binary = 1001).'''
    	# 1. remove VrefIn from refEl
    	mea1k.go( mea1k.cmdSw2( 0 ) )
    	# 2. connect all refels to vrefvari
    	mea1k.go( mea1k.cmdSw1(  0x9 ) )

    	# 1 kHz w/ 20 samples (Gives exactly the sampling frequency of 20000/s) and 10 bit amplitude
    	sineVari( 0.001 , 20 , 10)

    	print 'Offset MEA around 512 bits...'
    	lc.startLoop() #Starts to apply the function to MEA
    	Api = mea1kusr.api.Api()
    	Api.binary_offset( 512 ); #Offset the electrodes around 512 bits.
    	lc.stopLoop()
    	print 'Offset done'

    	## Save && run scan
    	save = mea1kusr.save.save('localhost')
    	save.mkDir( outputDir )
    	save.reset( )

    	for cfg in range( 25 ):
    		print cfg
    		cfgFile = configDir +'{0:03}.hex.nrk'.format(cfg)
    		chip.loadHEX( cfgFile ) #Load the config file
    		chip.download() #Download the config to the chip
    		save.mapping(chip.get_mapping( ))
    		lc.startLoop()
    		time.sleep(0.3)
    		save.start('{0:03}'.format(cfg))
    		time.sleep(0.2)
    		save.stop()
    		time.sleep(0.3)
    		lc.stopLoop()