def voltageBiPhasicPulse(offset, ampBits_1, ampBits_2, samples_1=4, samples_2=4):
    	c = mea1k.Config()
    	c.add( mea1k.cmdDelaySamples(400) ) # waits 20ms
        c.add( mea1k.cmdStatusOut( 1 ) ) #..#
    	# Turn on stimulation buffer
    	c.add( mea1k.cmdDAC( 0, offset-ampBits_1, 512 ) )#pulse one towards up
    	c.add( mea1k.cmdDelaySamples( samples_1 ) ) #=4 ~ 200us ?? doesn't add up
    	c.add( mea1k.cmdDAC( 0, offset+ampBits_2, 512 ) )#pulse two towards down
    	c.add( mea1k.cmdDelaySamples( samples_2 ) )#=4 ~ 200us ?? doesn't add up
    	c.add( mea1k.cmdDAC( 0, offset, 512 ) )#pulse three towards ~0
    	return c
 def switchOffAllChannels(self):
     c = mea1k.Config()
     c.add(
         mea1k.cmdStimBuffer(  # shutdown all stimchannels
             dac=0,  # 0 == VRef, 1 == DAC0
             broadcast=1,
             channel=0,
             autozero=0,  # 0 == off
             azoff=1,  # 1 == disable AZmode
             Imode=0,  # 0 == voltage
             Irange=0,  # 0 == small
             power=1))
     return c
def switchOnChannel(buffer, dac):
    print electrode
    c = mea1k.Config()
    c.add( mea1k.cmdStimBuffer(
    	dac=dac,        # 0 == VRef, 1 == DAC0
    	broadcast=0,
        channel=buffer,
        autozero=0,   # 0 == off
    	azoff=1,      # 1 == disable AZmode
    	Imode=0,      # 0 == voltage
    	Irange=0,     # 0 == small
    	power=0))     # 0 == on
    return c
Exemplo n.º 4
0
def switchOnChannels(channels, dac):
    c = mea1k.Config()
    for channel in channels:
        c.add( mea1k.cmdStimBuffer(
        	dac=dac,        # 0 == VRef, 1 == DAC0
        	broadcast=0,
	        channel=channel,
	        autozero=0,   # 0 == off
        	azoff=1,      # 1 == disable AZmode
        	Imode=0,      # 0 == voltage
        	Irange=0,     # 0 == small
        	power=0))     # 0 == on
    return c
    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()
        chip.download()
    time.sleep(2)
    print stimChannels

    print 'Offset MEA around 512 bits...'
    import mea1kusr.api
    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(switchOffAllChannels())
    c.add(switchOnChannels(stimChannels, 1))
    c.add(mea1k.cmdDelaySamples(100))
    for u in range(number_of_repetitions):
        c.add(voltageBiPhasicPulse(512, amp1, amp2, phase1, phase2))
        c.add(mea1k.cmdDelaySamples(interTrainDelay))
    train_time = (number_of_repetitions * interTrainDelay) / 10000. + 1

    save.start('configstructure_{0:03}'.format(t + 1))
    c.send()

    time.sleep(train_time)
    save.stop()
    print t
    time.sleep(2)