# -*- coding: iso-8859-1 -*-

TXEnableDelay = 2e-6
TXEnableValue = 0b0001	# TTL line blanking RF amplifier (bit 0)
TXPulseValue  = 0b0010	# TTL line triggering RF pulses  (bit 1)
ADCSensitivity = 2	# voltage span for ADC

def experiment(): # saturation-recovery experiment

  # set up acquisition parameters:
    pars = {}
    pars['P90'] = 1.7e-6	# 90-degree pulse length (s)
    pars['SF'] = 338.7e6	# spectrometer frequency (Hz)
    pars['SW'] = 200e3		# sampling rate (Hz)
    pars['SI'] = 1*256		# number of acquisition points
    pars['NS'] = 8		# number of scans
    pars['DS'] = 0		# number of dummy scans
    pars['TAU'] = 1		# delay for recovery (s)
    pars['DEAD1'] = 5e-6	# receiver dead time (s)
    pars['PHA'] = 0		# receiver phase (degree)
      # -*- these aren't variable: -*-
    pars['NECH'] = 7		# number of saturation pulses
    pars['D1'] = 100e-3		# starting interval in saturation sequence (s) 
    pars['D2'] = 1e-4		# end interval in saturation sequence (s) 
    pars['DATADIR'] = '/home/fprak/Students/'	# data directory
    pars['OUTFILE'] = None			# output file name

    # specify a variable parameter (optional):
    pars['VAR_PAR'] = 'TAU'	# variable parameter name (a string)   
    start = 1e-3		# starting value
    stop = 5e-0			# end value
    steps = 10			# number of values
    log_scale = True		# log scale flag 
    stag_range = False		# staggered range flag

    # check parameters for safety:
    if pars['PHA'] < 0:
        pars['PHA'] = 360 + pars['PHA']

    if pars['P90'] > 20e-6:
        raise Exception("Pulse too long!!!")

    # check whether a variable parameter is named: 
    var_key = pars.get('VAR_PAR')
    if var_key == 'P90' and (start > 20e-6 or stop > 20e-6):
        raise Exception("Pulse too long!!!")

    if pars['NS']%4 != 0:
        print 'Number of scans should be changed to ',pars['NS'],' due to phase cycling'

    if pars['D1'] < pars['D2']:
        raise Exception("D1 must be greater than D2")

    sat_length = sum(log_range(pars['D1'],pars['D2'],pars['NECH']))
    if sat_length > 1.:
        raise Exception("Saturation sequence too long!!!")   

    # start the experiment:
    if var_key: 
        # this is an arrayed experiment:
        if log_scale:
            array = log_range(start,stop,steps)
        else:
            array = lin_range(start,stop,steps)

        if stag_range:
            array = staggered_range(array, size = 2)

        # estimate the experiment time:
        if var_key == 'TAU':
            seconds = (sat_length * steps + sum(array)) * (pars['NS'] + pars['DS'])
        else:
            seconds = (sat_length + pars['TAU']) * steps * (pars['NS']+ pars['DS'])
        m, s = divmod(seconds, 60)
        h, m = divmod(m, 60)
        print '%s%02d:%02d:%02d' % ('Experiment time estimated: ', h, m, s)

        # loop for a variable parameter:
        for index, pars[var_key] in enumerate(array):
            print 'Arrayed experiment for '+var_key+': run = '+str(index+1)+\
                             ' out of '+str(array.size)+': value = '+str(pars[var_key])
            # loop for accumulation:
            for run in xrange(pars['NS']+pars['DS']):
                yield satrec_experiment(pars, run)
            synchronize()

    else:
       # estimate the experiment time:
        seconds = (sat_length + pars['TAU']) * (pars['NS'] + pars['DS'])
        m, s = divmod(seconds, 60)
        h, m = divmod(m, 60)
        print '%s%02d:%02d:%02d' % ('Experiment time estimated: ', h, m, s)

        # loop for accumulation:
        for run in xrange(pars['NS']+pars['DS']):
            yield satrec_experiment(pars, run) 


# the pulse program:

def satrec_experiment(pars, run):
    e=Experiment()

    dummy_scans = pars.get('DS')
    if dummy_scans:
        run -= dummy_scans
        
    pars['PROG'] = 'satrec_experiment'

    # phase lists:
    pars['PH1'] = [0]	 		# saturation pulses
    pars['PH3'] = [0,180,90,270]	# measuring pulse 
    pars['PH2'] = [0,180,90,270]	# receiver

    # read in variables:
    P90 = pars['P90']
    SF =  pars['SF']
    DEAD1 = pars['DEAD1']
    NECH = pars['NECH']
    D1 =  pars['D1']
    D2 =  pars['D2']
    TAU = pars['TAU']
    PH1 = pars['PH1'][run%len(pars['PH1'])]
    PH3 = pars['PH3'][run%len(pars['PH3'])]
    PH2 = pars['PH2'][run%len(pars['PH2'])]
    PHA = pars['PHA']
    SI = pars["SI"]
    SW = pars["SW"]
    # set variable delay list for saturation pulses:
    vdlist = log_range(D2, D1, NECH-1)

    # run the pulse sequence:

    # saturation:
    e.set_frequency(SF, phase=PH1)				# set frequency and phase for saturation pulses
    e.ttl_pulse(TXEnableDelay, value=TXEnableValue)		# enable RF amplifier
    e.ttl_pulse(P90, value=TXEnableValue|TXPulseValue)		# apply 90-degree pulse
    for delay in vdlist[::-1]:
        e.wait(delay-P90-TXEnableDelay)				# wait for next pulse
        e.ttl_pulse(TXEnableDelay, value=TXEnableValue)		# enable RF amplifier
        e.ttl_pulse(P90, value=TXEnableValue|TXPulseValue)	# apply 90-degree pulse

    e.set_phase(PH3)						# set phase for measuring pulse
    # recovery:
    e.wait(TAU-5e-7)							# recovery time

    # detection:
    e.ttl_pulse(TXEnableDelay, value=TXEnableValue)		# enable RF amplifier
    e.ttl_pulse(P90, value=TXEnableValue|TXPulseValue)  	# apply 90-degree pulse  
    e.set_phase(PHA)						# set phase for receiver
    e.wait(DEAD1-5e-7)                                               # wait for coil ringdown
    e.record(SI, SW, sensitivity=ADCSensitivity)		# acquire signal

    # write experiment parameters:  
    for key in pars.keys():
        e.set_description(key, pars[key])			# acquisition parameters
    e.set_description('run', run)				# current scan
    e.set_description('rec_phase', -PH2)			# current receiver phase

    return e