Beispiel #1
0
    def init_lcg(self):
        self.cwd = os.getcwd()
        os.chdir('/tmp')
        self.filename = '/tmp/seal_test.h5'
        self.cfg_file = '/tmp/seal_test.xml'
        self.duration = self.opts['duration']
        duration = self.duration * 1e-3
        self.stim_file = '/tmp/seal_test.stim'
        self.amplitude = self.opts['amp']  #mV
        self.sampling_rate = env('SAMPLING_RATE')
        holding = self.opts['holding']
        channels = [{
            'type':
            'input',
            'channel':
            self.opts['ai'],
            'factor':
            float(os.environ['AI_CONVERSION_FACTOR_' + self.opts['mode']]),
            'units':
            os.environ['AI_UNITS_' + self.opts['mode']]
        }]

        channels.append({
            'type':
            'output',
            'channel':
            self.opts['ao'],
            'factor':
            float(os.environ['AO_CONVERSION_FACTOR_' + self.opts['mode']]),
            'units':
            os.environ['AO_UNITS_' + self.opts['mode']],
            'resetOutput':
            False,
            'stimfile':
            self.stim_file
        })

        #        print('Conversion factors are {0}{2} and {1}{3}.'.format(
        #                channels[0]['factor'],
        #                channels[1]['factor'],
        #                channels[0]['units'],
        #                channels[1]['units']))

        sys.argv = [
            'lcg-stimgen', '-o', self.stim_file, 'dc', '-d',
            str(duration / 4.0), '--',
            str(holding), 'dc', '-d',
            str(duration), '--',
            str(self.amplitude + holding), 'dc', '-d',
            str(duration / 2.0), '--',
            str(holding)
        ]
        lcg.stimgen.main()
        lcg.writeIOConfigurationFile(self.cfg_file,
                                     self.sampling_rate,
                                     duration * (7 / 4.0),
                                     channels,
                                     realtime=True,
                                     output_filename=self.filename)
        atexit.register(self.on_exit)
    def init_lcg(self):
        self.cwd = os.getcwd()
        os.chdir('/tmp')
        self.filename = '/tmp/seal_test.h5'
        self.cfg_file = '/tmp/seal_test.xml'
        self.duration = self.opts['duration']
        duration = self.duration*1e-3
        self.stim_file = '/tmp/seal_test.stim'
        self.amplitude = self.opts['amp'] #mV
        self.sampling_rate = env('SAMPLING_RATE')
        holding = self.opts['holding']
        channels = [{'type':'input',
                     'channel':self.opts['ai'],
                     'factor':float(os.environ['AI_CONVERSION_FACTOR_'+self.opts['mode']]),
                     'units':os.environ['AI_UNITS_'+self.opts['mode']]}]
        
        channels.append({'type':'output',
                         'channel':self.opts['ao'],
                         'factor':float(os.environ['AO_CONVERSION_FACTOR_'+self.opts['mode']]),
                         'units':os.environ['AO_UNITS_'+self.opts['mode']],
                         'resetOutput':False,
                         'stimfile':self.stim_file})

#        print('Conversion factors are {0}{2} and {1}{3}.'.format(
#                channels[0]['factor'],
#                channels[1]['factor'],
#                channels[0]['units'],
#                channels[1]['units']))
        
        sys.argv = ['lcg-stimgen','-o',self.stim_file,
                    'dc', '-d',str(duration/4.0),'--',str(holding),
                    'dc', '-d',str(duration),'--',str(self.amplitude+holding),
                    'dc', '-d',str(duration/2.0),'--',str(holding)]
        lcg.stimgen.main()
        lcg.writeIOConfigurationFile(self.cfg_file,self.sampling_rate,
                                     duration*(7/4.0),channels,
                                     realtime=True,
                                     output_filename=self.filename)
        atexit.register(self.on_exit)
Beispiel #3
0
        sys.exit(1)

    if ai < 0 or ao < 0:
        print('I/O channels must be non-negative.')
        sys.exit(1)

    if append:
        suffix = '-' + str(ai) + '-' + str(ao)
    else:
        suffix = ''
    stim = [[duration,11,0,amplitude,0,0,0,1,int(rnd.uniform(high=10000)),0,0,1],
            [1,1,0,0,0,0,0,0,0,0,0,1]]
    lcg.writeStimFile(stim_file,stim,True)
    channels = [{'type':'input', 'channel':ai, 'factor':input_factor, 'units':input_units},
                {'type':'output', 'channel':ao, 'factor':output_factor, 'units':output_units, 'stimfile':stim_file}]
    lcg.writeIOConfigurationFile(config_file,sampling_rate,duration+3.61,channels,realtime)
    oldfiles = glob.glob('*.h5')    
    sub.call(lcg.common.prog_name + ' -c ' + config_file, shell=True)
    try:
        os.system('beep')
    except:
        pass
    files = glob.glob('*.h5')
    for ff in files:
        if ff not in oldfiles:
            data_file = ff
    lcg.computeElectrodeKernel(os.path.abspath(data_file))
    try:
        os.remove('kernel' + suffix + '.dat')
    except:
        pass
Beispiel #4
0
    if resetOutput is None:
        if suffix == 'CC':
            resetOutput = os.environ['LCG_RESET_OUTPUT'].lower() == 'yes'
        else:
            resetOutput = False

    if outputChannels is None or len(stimfiles) == len(outputChannels):
        total = repetitions
    else:
        total = repetitions * len(stimfiles)
    cnt = 1
    if len(reversalPotentials) == 0:
        writeConfigurationFile = lambda cfile,dur,chan:lcg.writeIOConfigurationFile(
            cfile,
            samplingRate,
            dur,
            chan,
            realtime,
            outputFilename,
            model)
    else:
        writeConfigurationFile = lambda cfile,dur,chan:lcg.writeConductanceStimulusConfigurationFile(
            cfile,
            samplingRate,
            dur,
            chan,
            reversalPotentials,
            model)
    all_channels = []
    all_durations = []
    if outputChannels is None or len(stimfiles) == len(outputChannels):
        tmpchannels = []
Beispiel #5
0
    stim.append([post, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1])
    totalDuration = lcg.writeStimFile(stimFile, stim, False)
    channels = [{
        'type': 'input',
        'channel': analogInput[0],
        'factor': inputGains[0],
        'units': inputUnits[0]
    }, {
        'type': 'input',
        'channel': analogInput[1],
        'factor': inputGains[1],
        'units': inputUnits[1]
    }, {
        'type': 'output',
        'channel': analogOutput,
        'factor': outputGain,
        'units': outputUnits,
        'stimfile': stimFile
    }]
    lcg.writeIOConfigurationFile(configFile, samplingRate, totalDuration,
                                 channels)

    for i in range(nTrials):
        sub.call(lcg.common.prog_name + ' -c ' + configFile, shell=True)
        if i < nTrials - 1:
            sub.call('sleep ' + str(interTrialInterval), shell=True)


if __name__ == '__main__':
    main()
Beispiel #6
0
        sys.exit(1)

    # default value of resetOutput, for voltage and current clamp stimulations
    if resetOutput is None:
        if suffix == 'CC':
            resetOutput = os.environ['LCG_RESET_OUTPUT'].lower() == 'yes'
        else:
            resetOutput = False

    if outputChannels is None or len(stimfiles) == len(outputChannels):
        total = repetitions
    else:
        total = repetitions * len(stimfiles)
    cnt = 1
    if len(reversalPotentials) == 0:
        writeConfigurationFile = lambda cfile, dur, chan: lcg.writeIOConfigurationFile(
            cfile, samplingRate, dur, chan, realtime, outputFilename, model)
    else:
        writeConfigurationFile = lambda cfile, dur, chan: lcg.writeConductanceStimulusConfigurationFile(
            cfile, samplingRate, dur, chan, reversalPotentials, model)
    all_channels = []
    all_durations = []
    if outputChannels is None or len(stimfiles) == len(outputChannels):
        tmpchannels = []
        # input channels
        if not inputChannels is None:
            tmpchannels = [{
                'type': 'input',
                'subdevice': inputSubdevice,
                'channel': inputChannels[j],
                'factor': inputGains[j],
                'units': inputUnits[j]
def main():
    opts = parse_options()
    os.chdir('/tmp')
    
    filename = 'conv_factors.stim'
    config_file = 'conv_factors.xml'
    h5_file = 'conv_factors.h5'
    expected_voltage_deflection = 10 #mV
    CCin_value = expected_voltage_deflection/opts['model_cell']
    VCin_value = expected_voltage_deflection
    CCout_value = 6
    VCout_value = 6
    duration = 0.5

    ## TODO: make that it saves always to this file always when using streams!!
    board_range = 10
    samplingRate=20000
    sub.call('lcg-zero')
    ############################# Current Clamp ##################################

    print_str = '''\nThis is a simple program to compute the conversion factors 
for your data acquisition card. This has to be done only once for each user 
(assuming you don't reset the file as when using a live cd...).

\033[32mPlease follow the instructions carefully.\033[0m
1) Prepare your amplifier to read the Current Clamp (CC) conversion factors:
\t - Connect the MODEL CELL ({0}MOhm, this is called bath mode sometimes) and respective ground.
\t\t\t You can use the -m <Resistance in MOhm> switch to specify the correct
\t\t\t resistance of your model cell. 
\t - (Zero the) offset of the amplifier.
\t - Put the amplifier in current clamp (CC) mode.
\t - Inject {1}nA with the amplifier (use the holding current).
\t - Activate the External COMMAND so that you can drive the model cell.
\t\t\t (This is not necessary in some amplifiers, like the 
\t\t\tAXON MULTICLAMP, as it is set by default).

\033[31;1m\t\t [Press ENTER when ready, this will take {2} second(s)] \033[0m
'''.format(opts['model_cell'],CCin_value,duration*2.0)
    from sys import  stdout
    stdout.write(print_str),stdout.flush()
    tmp = raw_input()

    channels = [{'type':'input',
                 'channel':opts['CCchannels'][0],
                 'factor':1.0,
                 'units':'mV'}]
    channels.append({'type':'output',
                     'channel':opts['CCchannels'][1],
                     'factor':1.0,
                     'units':'pA',
                     'stimfile':filename})
    V_post = board_range
    while (np.mean(V_post)>board_range-1):
        CCout_value = CCout_value/2.0
        sys.argv = ['lcg-stimgen','-o',filename,
                    'dc', '-d',str(duration/2.0),'--','0',
                    'dc', '-d',str(duration),'--',str(CCout_value),
                    'dc', '-d',str(duration/2.0),'--','0']
        lcg.stimgen.main()
        lcg.writeIOConfigurationFile(config_file,samplingRate,
                                     duration*2.0,channels,
                                     True,output_filename=h5_file)
    
        sub.call('lcg-experiment -c {0} -V 4'.format(config_file),shell=True)   
        rV,time,info = read_analog_input(h5_file)
        idx_pre = np.where(time < duration/4.0)[0]
        idx_post = np.where((time > duration) & (time<(info['tend']-duration/1.5)))[0]
        V_pre = rV[idx_pre]
        V_post = rV[idx_post]
        
    CCin = np.round(np.mean(V_pre)/expected_voltage_deflection,4)
    deltaV = (np.mean(V_post)-np.mean(V_pre))/CCin
    CCout = np.round(CCout_value/(1000.0*(deltaV/opts['model_cell'])),6)
    CCin = 1./CCin
    print("CCin = %lf; CCout = %lf \n"%(CCin,CCout))
    ############################# Voltage Clamp ###############################
    sub.call('lcg-zero')

    print_str = '''\n
2) Prepare your amplifier for reading the Voltage Clamp conversion factors:
\t - Put the amplifier in voltage clamp (VC) mode.
\t - Inject {1}mV with the amplifier (use the holding voltage).
\t - Assure that the External COMMAND is active.

\033[31;1m\t\t [Press ENTER when ready, this will take {2} second(s)] \033[0m
'''.format(opts['model_cell'],expected_voltage_deflection ,duration*2.0)


    stdout.write(print_str);stdout.flush();tmp = raw_input()

    channels = [{'type':'input',
                 'channel':opts['VCchannels'][0],
                 'factor':1.0,
                'units':'pA'}]
    channels.append({'type':'output', 
                     'channel':opts['VCchannels'][1],
                     'factor':1.0,
                     'units':'mV',
                     'stimfile':filename})
    I_post = board_range
    while (np.mean(I_post)>board_range-1):
        VCout_value = VCout_value/2.0
        sys.argv = ['lcg-stimgen','-o',filename,
                    'dc', '-d',str(duration/2.0),'--','0',
                    'dc', '-d',str(duration),'--',str(VCout_value),
                    'dc', '-d',str(duration/2.0),'--','0']
        lcg.stimgen.main()
        lcg.writeIOConfigurationFile(config_file,samplingRate,
                                     duration*2.0,channels,
                                     True,output_filename=h5_file)

        sub.call('lcg-experiment -c {0} -V 4'.format(config_file),shell=True)

        rI,time,info = read_analog_input(h5_file)
        I_pre = rI[(time < duration/4.0)]
        I_post = rI[(time > duration) & (time<(info['tend']-duration/1.5))]
    
    VCin =1000.0*np.round((VCin_value/opts['model_cell'])/np.mean(I_pre),4)
    deltaI = VCin*(np.mean(I_post)-np.mean(I_pre))
    expected_current_deflection = 1000.
    VCout =np.round(((expected_current_deflection/opts['model_cell'])*VCout_value)/deltaI,6)
    factors = ['AI_CONVERSION_FACTOR_CC={0}'.format(CCin),
               'AO_CONVERSION_FACTOR_CC={0}'.format(CCout),
               'AI_CONVERSION_FACTOR_VC={0}'.format(VCin),
               'AO_CONVERSION_FACTOR_VC={0}'.format(VCout)]
    print_str = '''
Make sure the following values are correct:
{0}
\n'''.format('\n'.join(factors))
    stdout.write(print_str);stdout.flush()

    stdout.write('Looking for lcg-env in .bashrc and .bash_profile\n');stdout.flush()
    lcg_env = None
    sys.exit()
    with open('{0}/.bashrc'.format(os.environ['HOME'])) as fd:
        for line in fd.readlines():
            if 'lcg-env' in line and 'source' in line:
                lcg_env = os.path.expanduser(os.path.expandvars(
                        line.split('source ')[-1].rstrip()))
    amp_name=[]
    amp_line=[]
    if not lcg_env is None:
        with open(lcg_env) as fd:
            contents = fd.readlines()
            for ii,line in enumerate(contents):
                if 'AMPLIFIER=' in line:
                    amp_name.append(line.split('AMPLIFIER="')[-1].rstrip().strip('"'))
                    amp_line.append(ii)
        stdout.write('Found lcg-env file with amplifiers: {0}\n'.format(' ,'.join(amp_name)))
        amplifier = str(raw_input('\033[36;1m Replace Amplifier or add a new one?\n\033[0m (Write amplifier name as above or write a new one.)'))
        with open(lcg_env,'r+') as fd:
            contents = fd.readlines()
            for ii,line in enumerate(contents):
                if 'AMPLIFIER=' in line:
                    if not amplifier in line.split('AMPLIFIER="')[-1].rstrip().strip('"'):
                        if not line[0] == '#':
                            contents[ii] = '#'+line
                if amplifier in amp_name:
                    if '"{0}"'.format(amplifier) in line:
                        for jj in range(4):
                            contents[ii+jj+1] = factors[jj]+'\n'
                elif amplifier.strip() not in ['']:
                    if '"HEKA-EPC10")' in line:
                        contents.insert(ii+1,'\t"{0}")\n'.format(amplifier))
                        for jj,a in enumerate(factors):
                            contents.insert(ii+jj+1,'\t\t'+a+'\n')
                        contents.insert(ii+jj+2,'\t\t;;\n')
                        break
                else:
                    print("Empty names not valid... Nothing was saved.")
                    break
            if not amplifier in amp_name:
                contents.insert(amp_line[0],'AMPLIFIER="{0}"\n'.format(amplifier))
            for ii,amp in enumerate(amp_name):
                if amplifier in amp:
                    contents[amp_line[ii]] = 'AMPLIFIER="{0}"\n'.format(amplifier)
            fd.seek(0)
            fd.truncate()
            [fd.write(c) for c in contents]
            stdout.flush(); stdout.write("Written to {0}.\n".format(lcg_env))
            [os.unlink(f) for f in [filename,config_file,h5_file]]
Beispiel #8
0
        sys.exit(1)

    if withRecovery and pause <= 0:
        print('The interval between pulse train and recovery pulse must positive.')
        sys.exit(1)

    if computeKernel:
        sub.call('lcg kernel -F ' + str(samplingRate) + ' -I ' + str(analogInput[0]) + ' -O ' + str(analogOutput) + \
                     ' --input-factor ' + str(inputGains[0]) + ' --output-factor ' + str(outputGain) + \
                     ' --input-units ' + inputUnits[0] + ' --output-units ' + outputUnits + ' --non-rt', shell=True)

    stim = [[pre,1,0,0,0,0,0,0,0,0,0,1],
            [nPulses/stimulusFrequency,8,stimulusAmplitude,-stimulusFrequency,stimulusDuration,0,0,0,0,0,0,1]]
    if withRecovery:
        stim.append([pause-1./stimulusFrequency,1,0,0,0,0,0,0,0,0,0,1])
        stim.append([stimulusDuration*1e-3,1,stimulusAmplitude,0,0,0,0,0,0,0,0,1])
    stim.append([post,1,0,0,0,0,0,0,0,0,0,1])
    totalDuration = lcg.writeStimFile(stimFile, stim, False)
    channels = [{'type':'input', 'channel':analogInput[0], 'factor':inputGains[0], 'units':inputUnits[0]},
                {'type':'input', 'channel':analogInput[1], 'factor':inputGains[1], 'units':inputUnits[1]},
                {'type':'output', 'channel':analogOutput, 'factor':outputGain, 'units':outputUnits, 'stimfile':stimFile}]
    lcg.writeIOConfigurationFile(configFile,samplingRate,totalDuration,channels)

    for i in range(nTrials):
        sub.call(lcg.common.prog_name + ' -c ' + configFile, shell=True)
        if i < nTrials-1:
            sub.call('sleep ' + str(interTrialInterval), shell=True)

if __name__ == '__main__':
    main()
Beispiel #9
0
    if len(inputGains) == 0:
        inputGains = [float(os.environ['AI_CONVERSION_FACTOR_' + suffix]) for i in range(len(inputChannels))]

    if len(inputUnits) == 0:
        inputUnits = [os.environ['AI_UNITS_' + suffix] for i in range(len(inputChannels))]

    if (len(inputChannels) != len(inputGains)) or (len(inputChannels) != len(inputUnits)):
        print('The number of input channels, input gains and input units must be the same.')
        sys.exit(1)

    if duration is None:
        print('You must specify the duration of the recording (-d switch).')
        sys.exit(1)

    lcg.writeIOConfigurationFile(configFile,samplingRate,duration,
                                 [{'type':'input', 'channel':inputChannels[i], 'factor':inputGains[i], 'units':inputUnits[i]}
                                  for i in range(len(inputChannels))],realtime=realtime)
    sys.stdout.write('\n')
    sys.stdout.flush()
    for i in range(repetitions):
        runCommand(lcg.common.prog_name + ' -c ' + 
                   configFile + ' -V ' + str(verbose),'timer',duration,
                   '\rElapsed time (trial ' + str(i+1) + ' of ' + str(repetitions) + ' ): {0:.2f}s ')
        if i < repetitions-1:
            sub.call('sleep ' + str(interval), shell=True)
        
    sys.stdout.write('\rRan ' + str(i+1) + ' repetitions (%d time(s) %.2f s).' % (i+1,duration))
    sys.stdout.flush()
    sys.stdout.write('\n')

if __name__ == '__main__':
Beispiel #10
0
def main():
    mode = None

    if len(sys.argv) < 2 or sys.argv[1] in ('-h','--help','help'):
        usage()
        sys.exit(0)

    mode = sys.argv[1]
    if mode != 'current' and mode != 'conductance':
        print('Unknown working mode: [%s].' % sys.argv[1])
        sys.exit(1)

    opts = parseGlobalArgs()

    if mode == 'current':
        opts = dict(parseCurrentModeArgs(), **opts)
        if opts['separate'] and (type(opts['ao']) == int or type(opts['ai']) == int or \
                                     len(opts['ao']) == 1 or len(opts['ai']) == 1):
            print('When using the --separate options, two channels must be specified (use the -I and -O options).')
            sys.exit(1)
    else:
        opts = dict(parseConductanceModeArgs(), **opts)

    if (mode == 'current' and opts['with_bg']) or mode == 'conductance':
        ratio = lcg.computeRatesRatio(Vm=opts['balanced_voltage'], Rin=opts['input_resistance'])
        Gm_exc,Gm_inh,Gs_exc,Gs_inh = lcg.computeSynapticBackgroundCoefficients(ratio, R_exc=opts['R_exc'], Rin=opts['input_resistance'])
        opts['Gm_exc'] = Gm_exc
        opts['Gm_inh'] = Gm_inh
    else:
        # no background conductances, it will be a current-clamp experiment
        gexc = None
        ginh = None

    if mode == 'current':
        if opts['with_bg']:
            # background conductances only
            gexc = [[2.61,1,0,0,0,0,0,0,0,0,0,1],
                    [opts['duration'],2,Gm_exc,Gs_exc,5,0,0,1,random_seed,0,0,1],
                    [1,1,0,0,0,0,0,0,0,0,0,1]]
            ginh = [[2.61,1,0,0,0,0,0,0,0,0,0,1],
                    [opts['duration'],2,Gm_inh,Gs_inh,10,0,0,1,random_seed,0,0,1],
                    [1,1,0,0,0,0,0,0,0,0,0,1]]
            
        if opts['mean'] == 0 and opts['std'] == 0 and opts['tau'] == 0:
            # sinusoidal modulating current only
            if opts['separate']:
                current = [[opts['duration'],1,0,0,0,0,0,1,random_seed,0,0,1], # OU current
                           [1,1,0,0,0,0,0,0,0,0,0,1]]
                modulation = [[opts['duration'],3,opts['I_modul'],frequency_value,0,0,0,0,0,0,0,1],
                              [1,1,0,0,0,0,0,0,0,0,0,1]]
            else:
                current = [[opts['duration'],3,opts['I_modul'],frequency_value,0,0,0,0,0,0,0,1],
                           [1,1,0,0,0,0,0,0,0,0,0,1]]
        elif opts['tau'] == 0:
            # sinusoid on top of a DC current
            if opts['separate']:
                current = [[opts['duration'],1,opts['mean'],0,0,0,0,0,random_seed,0,0,1], # OU current
                           [1,1,0,0,0,0,0,0,0,0,0,1]]
                modulation = [[opts['duration'],3,opts['I_modul'],frequency_value,0,0,0,0,0,0,0,1],
                              [1,1,0,0,0,0,0,0,0,0,0,1]]
            else:
                current = [[opts['duration'],-2,opts['mean'],0,0,0,0,0,0,1,0,1],
                           [0,-2,opts['I_modul'],frequency_value,0,0,0,0,0,3,1,1],
                           [1,1,0,0,0,0,0,0,0,0,0,1]]
        else:
            # sinusoid on top of a noisy (OU) current
            if opts['separate']:
                current = [[opts['duration'],2,opts['mean'],opts['std'],opts['tau'],0,0,1,random_seed,0,0,1], # OU current
                           [1,1,0,0,0,0,0,0,0,0,0,1]]
                modulation = [[opts['duration'],3,opts['I_modul'],frequency_value,0,0,0,0,0,0,0,1],
                              [1,1,0,0,0,0,0,0,0,0,0,1]]
            else:
                current = [[opts['duration'],-2,opts['mean'],opts['std'],opts['tau'],0,0,1,random_seed,2,0,1], # OU current
                           [0,-2,opts['I_modul'],frequency_value,0,0,0,0,0,3,1,1],
                           [1,1,0,0,0,0,0,0,0,0,0,1]]
    else:
        # current just for the preamble
        current = [[opts['duration']+1,1,0,0,0,0,0,0,0,0,0,1]]
        # conductances
        opts['R_inh'] = opts['R_exc']/ratio
        if opts['exc']:
            gexc = createSinusoidallyModOU(frequency_value, 'exc', random_seed, opts)
        else:
            gexc = [{'matrix': [[2.61,1,0,0,0,0,0,0,0,0,0,1],
                                [opts['duration'],2,Gm_exc,Gs_exc,5,0,0,1,random_seed,0,0,1],
                                [1,1,0,0,0,0,0,0,0,0,0,1]], 'filename': 'gexc.stim'}]
        if opts['inh']:
            ginh = createSinusoidallyModOU(frequency_value, 'inh', random_seed, opts)
        else:
            ginh = [{'matrix': [[2.61,1,0,0,0,0,0,0,0,0,0,1],
                                [opts['duration'],2,Gm_inh,Gs_inh,10,0,0,1,random_seed,0,0,1],
                                [1,1,0,0,0,0,0,0,0,0,0,1]], 'filename': 'ginh.stim'}]

    if gexc and ginh:
        writeConfigurationFile(opts)
        
    cnt = 0
    tot = opts['reps']*len(opts['frequencies'])
    for i in range(opts['reps']):
        np.random.shuffle(opts['frequencies'])
        for f in opts['frequencies']:
            if opts['compute_kernel'] and cnt%opts['kernel_frequency'] == 0:
                if 'separate' in opts and  opts['separate']:
                    # compute a kernel for each channel
                    sub.call('lcg kernel -I ' + str(opts['ai'][0]) + ' -O ' + str(opts['ao'][0]) +
                             ' -F '+ str(opts['sampling_rate']) + ' --non-rt --append', shell=True)
                    sub.call('lcg kernel -I ' + str(opts['ai'][1]) + ' -O ' + str(opts['ao'][1]) +
                             ' -F '+ str(opts['sampling_rate']) + ' --non-rt --append', shell=True)
                    pass
                else:
                    sub.call('lcg kernel -I ' + str(opts['ai']) + ' -O ' + str(opts['ao']) +
                             ' -F '+ str(opts['sampling_rate']), shell=True)
            cnt = cnt+1
            print('[%02d/%02d] F = %g Hz.' % (cnt,tot,f))
            
            I = copy.deepcopy(current)
            replaceValue(I, random_seed)
            replaceValue(I, frequency_value, f)
            lcg.writeStimFile(current_file, I, preamble=True)
            if 'separate' in opts and opts['separate']:
                I = copy.deepcopy(modulation)
                replaceValue(I, frequency_value, f)
                lcg.writeStimFile(modulation_file, I, preamble=[0,0])
            if gexc and ginh:
                for stimulus in gexc:
                    G = copy.deepcopy(stimulus['matrix'])
                    replaceValue(G, random_seed)
                    replaceValue(G, frequency_value, f)
                    lcg.writeStimFile(stimulus['filename'], G)
                for stimulus in ginh:
                    G = copy.deepcopy(stimulus['matrix'])
                    replaceValue(G, random_seed)
                    replaceValue(G, frequency_value, f)
                    lcg.writeStimFile(stimulus['filename'], G)
                sub.call(lcg.common.prog_name + ' -V 3 -c ' + config_file, shell=True)
            else:
                if 'separate' in opts and opts['separate']:
                    channels = [{'type':'input', 'channel':opts['ai'][0]},{'type':'input', 'channel':opts['ai'][1]},
                                {'type':'output', 'channel':opts['ao'][0], 'stimfile':current_file},
                                {'type':'output', 'channel':opts['ao'][1], 'stimfile':modulation_file}]
                    lcg.writeIOConfigurationFile(config_file,opts['sampling_rate'],opts['duration']+3.61,channels)
                    sub.call(lcg.common.prog_name + ' -c ' + config_file, shell=True)
                else:
                    sub.call('lcg stimulus -s ' + current_file + ' -F '+ str(opts['sampling_rate']), shell=True)

            if cnt != tot:
                sub.call(['sleep', str(opts['interval'])])
def main():
    opts = parse_options()
    os.chdir('/tmp')

    filename = 'conv_factors.stim'
    config_file = 'conv_factors.xml'
    h5_file = 'conv_factors.h5'
    expected_voltage_deflection = 10  #mV
    CCin_value = expected_voltage_deflection / opts['model_cell']
    VCin_value = expected_voltage_deflection
    CCout_value = 6
    VCout_value = 6
    duration = 0.5

    ## TODO: make that it saves always to this file always when using streams!!
    board_range = 10
    samplingRate = 20000
    sub.call('lcg-zero')
    ############################# Current Clamp ##################################

    print_str = '''\nThis is a simple program to compute the conversion factors 
for your data acquisition card. This has to be done only once for each user 
(assuming you don't reset the file as when using a live cd...).

\033[32mPlease follow the instructions carefully.\033[0m
1) Prepare your amplifier to read the Current Clamp (CC) conversion factors:
\t - Connect the MODEL CELL ({0}MOhm, this is called bath mode sometimes) and respective ground.
\t\t\t You can use the -m <Resistance in MOhm> switch to specify the correct
\t\t\t resistance of your model cell. 
\t - (Zero the) offset of the amplifier.
\t - Put the amplifier in current clamp (CC) mode.
\t - Inject {1}nA with the amplifier (use the holding current).
\t - Activate the External COMMAND so that you can drive the model cell.
\t\t\t (This is not necessary in some amplifiers, like the 
\t\t\tAXON MULTICLAMP, as it is set by default).

\033[31;1m\t\t [Press ENTER when ready, this will take {2} second(s)] \033[0m
'''.format(opts['model_cell'], CCin_value, duration * 2.0)
    from sys import stdout
    stdout.write(print_str), stdout.flush()
    tmp = raw_input()

    channels = [{
        'type': 'input',
        'channel': opts['CCchannels'][0],
        'factor': 1.0,
        'units': 'mV'
    }]
    channels.append({
        'type': 'output',
        'channel': opts['CCchannels'][1],
        'factor': 1.0,
        'units': 'pA',
        'stimfile': filename
    })
    V_post = board_range
    while (np.mean(V_post) > board_range - 1):
        CCout_value = CCout_value / 2.0
        sys.argv = [
            'lcg-stimgen', '-o', filename, 'dc', '-d',
            str(duration / 2.0), '--', '0', 'dc', '-d',
            str(duration), '--',
            str(CCout_value), 'dc', '-d',
            str(duration / 2.0), '--', '0'
        ]
        lcg.stimgen.main()
        lcg.writeIOConfigurationFile(config_file,
                                     samplingRate,
                                     duration * 2.0,
                                     channels,
                                     True,
                                     output_filename=h5_file)

        sub.call('lcg-experiment -c {0} -V 4'.format(config_file), shell=True)
        rV, time, info = read_analog_input(h5_file)
        idx_pre = np.where(time < duration / 4.0)[0]
        idx_post = np.where((time > duration)
                            & (time < (info['tend'] - duration / 1.5)))[0]
        V_pre = rV[idx_pre]
        V_post = rV[idx_post]

    CCin = np.round(np.mean(V_pre) / expected_voltage_deflection, 4)
    deltaV = (np.mean(V_post) - np.mean(V_pre)) / CCin
    CCout = np.round(CCout_value / (1000.0 * (deltaV / opts['model_cell'])), 6)
    CCin = 1. / CCin
    print("CCin = %lf; CCout = %lf \n" % (CCin, CCout))
    ############################# Voltage Clamp ###############################
    sub.call('lcg-zero')

    print_str = '''\n
2) Prepare your amplifier for reading the Voltage Clamp conversion factors:
\t - Put the amplifier in voltage clamp (VC) mode.
\t - Inject {1}mV with the amplifier (use the holding voltage).
\t - Assure that the External COMMAND is active.

\033[31;1m\t\t [Press ENTER when ready, this will take {2} second(s)] \033[0m
'''.format(opts['model_cell'], expected_voltage_deflection, duration * 2.0)

    stdout.write(print_str)
    stdout.flush()
    tmp = raw_input()

    channels = [{
        'type': 'input',
        'channel': opts['VCchannels'][0],
        'factor': 1.0,
        'units': 'pA'
    }]
    channels.append({
        'type': 'output',
        'channel': opts['VCchannels'][1],
        'factor': 1.0,
        'units': 'mV',
        'stimfile': filename
    })
    I_post = board_range
    while (np.mean(I_post) > board_range - 1):
        VCout_value = VCout_value / 2.0
        sys.argv = [
            'lcg-stimgen', '-o', filename, 'dc', '-d',
            str(duration / 2.0), '--', '0', 'dc', '-d',
            str(duration), '--',
            str(VCout_value), 'dc', '-d',
            str(duration / 2.0), '--', '0'
        ]
        lcg.stimgen.main()
        lcg.writeIOConfigurationFile(config_file,
                                     samplingRate,
                                     duration * 2.0,
                                     channels,
                                     True,
                                     output_filename=h5_file)

        sub.call('lcg-experiment -c {0} -V 4'.format(config_file), shell=True)

        rI, time, info = read_analog_input(h5_file)
        I_pre = rI[(time < duration / 4.0)]
        I_post = rI[(time > duration)
                    & (time < (info['tend'] - duration / 1.5))]

    VCin = 1000.0 * np.round(
        (VCin_value / opts['model_cell']) / np.mean(I_pre), 4)
    deltaI = VCin * (np.mean(I_post) - np.mean(I_pre))
    expected_current_deflection = 1000.
    VCout = np.round(
        ((expected_current_deflection / opts['model_cell']) * VCout_value) /
        deltaI, 6)
    factors = [
        'AI_CONVERSION_FACTOR_CC={0}'.format(CCin),
        'AO_CONVERSION_FACTOR_CC={0}'.format(CCout),
        'AI_CONVERSION_FACTOR_VC={0}'.format(VCin),
        'AO_CONVERSION_FACTOR_VC={0}'.format(VCout)
    ]
    print_str = '''
Make sure the following values are correct:
{0}
\n'''.format('\n'.join(factors))
    stdout.write(print_str)
    stdout.flush()

    stdout.write('Looking for lcg-env in .bashrc and .bash_profile\n')
    stdout.flush()
    lcg_env = None
    sys.exit()
    with open('{0}/.bashrc'.format(os.environ['HOME'])) as fd:
        for line in fd.readlines():
            if 'lcg-env' in line and 'source' in line:
                lcg_env = os.path.expanduser(
                    os.path.expandvars(line.split('source ')[-1].rstrip()))
    amp_name = []
    amp_line = []
    if not lcg_env is None:
        with open(lcg_env) as fd:
            contents = fd.readlines()
            for ii, line in enumerate(contents):
                if 'AMPLIFIER=' in line:
                    amp_name.append(
                        line.split('AMPLIFIER="')[-1].rstrip().strip('"'))
                    amp_line.append(ii)
        stdout.write('Found lcg-env file with amplifiers: {0}\n'.format(
            ' ,'.join(amp_name)))
        amplifier = str(
            raw_input(
                '\033[36;1m Replace Amplifier or add a new one?\n\033[0m (Write amplifier name as above or write a new one.)'
            ))
        with open(lcg_env, 'r+') as fd:
            contents = fd.readlines()
            for ii, line in enumerate(contents):
                if 'AMPLIFIER=' in line:
                    if not amplifier in line.split(
                            'AMPLIFIER="')[-1].rstrip().strip('"'):
                        if not line[0] == '#':
                            contents[ii] = '#' + line
                if amplifier in amp_name:
                    if '"{0}"'.format(amplifier) in line:
                        for jj in range(4):
                            contents[ii + jj + 1] = factors[jj] + '\n'
                elif amplifier.strip() not in ['']:
                    if '"HEKA-EPC10")' in line:
                        contents.insert(ii + 1, '\t"{0}")\n'.format(amplifier))
                        for jj, a in enumerate(factors):
                            contents.insert(ii + jj + 1, '\t\t' + a + '\n')
                        contents.insert(ii + jj + 2, '\t\t;;\n')
                        break
                else:
                    print("Empty names not valid... Nothing was saved.")
                    break
            if not amplifier in amp_name:
                contents.insert(amp_line[0],
                                'AMPLIFIER="{0}"\n'.format(amplifier))
            for ii, amp in enumerate(amp_name):
                if amplifier in amp:
                    contents[amp_line[ii]] = 'AMPLIFIER="{0}"\n'.format(
                        amplifier)
            fd.seek(0)
            fd.truncate()
            [fd.write(c) for c in contents]
            stdout.flush()
            stdout.write("Written to {0}.\n".format(lcg_env))
            [os.unlink(f) for f in [filename, config_file, h5_file]]