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()
        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))

#default gain of 512 - if needed, change below
# 7x1x1(7)
# 7x8x2(112)
# 16x16x2(512)
# 16x16x4(1024)
# 16x32x4(2048)

mea1k.go(
    mea1k.cmdReadout(
        s1Bypass=0,