# -*- 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 = 5	# voltage span for ADC

def experiment(): # a diffusion editing sequence with stimulated echo and XY-16 detection

  # set up acqusition parameters:
    pars = {}
    pars['P90'] = 0.8e-6	# 90-degree pulse length (s)
    pars['SF'] = 161.85e6  	# spectrometer frequency (Hz)
    pars['O1'] = 0e3		# offset from SF (Hz)
    pars['NS'] = 16		# number of scans
    pars['DS'] = 0		# number of dummy scans
    pars['RD'] = 6		# delay between scans (s)
    pars['D1'] = 20e-6		# delay after first STE pulse (s)
    pars['D2'] = 30e-6		# delay after second STE pulse (s) 
    pars['D4'] = 2.5e-6		# pre-acquisition offset
    pars['NECH'] = 128          # number of 180-degree pulses
    pars['TAU'] = 50e-6         # half pulse period (s)
    pars['PHA'] = -95   	# receiver phase (degree) 
    pars['DATADIR'] = '/home/fprak/Desktop/test/'	# data directory
    pars['OUTFILE'] = None				# output file name

  # specify a variable parameter (optional):
    pars['VAR_PAR'] = 'D2'	# variable parameter name (a string)   
    start = 20e-6		# starting value
    stop = 3e-1			# end value
    steps = 24			# 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']%16 != 0:
        pars['NS'] = int(round(pars['NS'] / 16) + 1) * 16 
        print 'Number of scans changed to ',pars['NS'],' due to phase cycling'

    # 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 == 'D1':
            seconds = (sum(array)*2 + (pars['D2'] + pars['RD']) * steps) * (pars['NS'] + pars['DS'])
        elif var_key == 'D2':
            seconds = (sum(array) + (pars['D1']*2 + pars['RD']) * steps) * (pars['NS'] + pars['DS'])
        elif var_key == 'RD':
            seconds = (sum(array) + (pars['D1']*2 + pars['D2']) * steps) * (pars['NS'] + pars['DS'])
        else:
            seconds = (pars['D1']*2 + pars['D2'] + pars['RD']) * 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 ste16_experiment(pars, run)
            synchronize() 
    else:
       # estimate the experiment time:
        seconds = (pars['D1']*2 + pars['D2'] + pars['RD']) * (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 ste16_experiment(pars, run)  


# the pulse program: 

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

    dummy_scans = pars.get('DS')
    if dummy_scans:
        run -= dummy_scans

    pars['PROG'] = 'ste16_experiment'

    # phase lists [from J. Magn. Reson. 157, 31 (2002)]: 
    pars['PH1'] = [0, 180,   0, 180,   0, 180,   0, 180,  90, 270,  90, 270,  90, 270,  90, 270] # 1st 90-degree pulse
    pars['PH3'] = [0,   0, 180, 180,   0,   0, 180, 180,   0,   0, 180, 180,   0,   0, 180, 180] # 2nd 90-degree pulse
    pars['PH4'] = [0,   0,   0,   0, 180, 180, 180, 180,   0,   0,   0,   0, 180, 180, 180, 180] # 3nd 90-degree pulse
    pars['PH5'] = [0,   0,   0,   0,   0,   0,   0,   0, 270, 270, 270, 270, 270, 270, 270, 270] # 180-degree pulses
    pars['PH2'] = [0, 180, 180,   0, 180,   0,   0, 180, 270,  90,  90, 270,  90, 270, 270,  90] # receiver 
    
    # XY-16 phase cycle
    pars['PH5_XY16'] = [0,   90,   0,  90,  90,   0,  90,   0, 180, 270, 180, 270, 270, 180, 270, 180]    # XY-16: 180-degree pulses
    pars['PH2_XY16'] = [90, 270, 270,  90, 270, 270,  90,  90,  90, 270, 270,  90, 270, 270,  90,  90]    # XY_16: receiver 

    # read in variables:
    P90 = pars['P90']
    P180 = pars['P90']*2
    SF =  pars['SF']
    O1 =  pars['O1']    
    RD =  pars['RD']
    D1 =  pars['D1']
    D2 =  pars['D2']
    D4 =  pars['D4']
    TAU = pars['TAU']
    NECH = pars['NECH']
    PH1 = pars['PH1'][run%len(pars['PH1'])]
    PH3 = pars['PH3'][run%len(pars['PH3'])]
    PH4 = pars['PH4'][run%len(pars['PH4'])]
    PH5 = pars['PH5'][run%len(pars['PH5'])]
    PH2 = pars['PH2'][run%len(pars['PH2'])] 
    PH5_XY16 = [x+PH5 for x in pars['PH5_XY16']*(NECH/16)]
    PH2_XY16 = [x+PH2 for x in pars['PH2_XY16']*(NECH/16)]   
    PHA = pars['PHA'] 

    # set sampling parameters:
    SI = 128    	# number of echo samples
    SW = 20e6   	# sample rate
    AQ = (SI+6)/SW	# acquisition window
	
    if TAU < (P90+P180)/2+TXEnableDelay or TAU < (P180+TXEnableDelay+AQ)/2:
        raise Exception('pulse period is too short!')

    if 2*TAU < P180+TXEnableDelay+SI/SW:
        raise Exception('pulse period too short!')
    
   # run the pulse sequence: 
    e.wait(RD)						# delay between scans
    e.set_frequency(SF+O1, phase=PH1)
    e.ttl_pulse(TXEnableDelay, value=TXEnableValue)
    e.ttl_pulse(P90, value=TXEnableValue|TXPulseValue)	# 1st 90-degree pulse 

    e.wait(D1-P90/2-TXEnableDelay)			# short delay
    e.set_phase(PH3)

    e.ttl_pulse(TXEnableDelay, value=TXEnableValue)		
    e.ttl_pulse(P90, value=TXEnableValue|TXPulseValue)	# 2nd 90-degree pulse 

    e.wait(D2-P90/2-TXEnableDelay)			# long delay
    e.set_phase(PH4)

    e.ttl_pulse(TXEnableDelay, value=TXEnableValue)		
    e.ttl_pulse(P90, value=TXEnableValue|TXPulseValue)	# 3rd 90-degree pulse
    
    e.wait(D1+TAU-P90/2-TXEnableDelay)			# wait for first echo and tau
    
    for i in range(NECH):
        e.set_phase(PH5_XY16[i])                                     	# set phase for 180-degree pulse  
        e.ttl_pulse(TXEnableDelay, value=TXEnableValue)         	# enable RF amplifier
        e.ttl_pulse(P180, value=TXEnableValue|TXPulseValue)     	# apply 180-degree pulse
        e.set_phase(PHA)	                                       	# set phase for receiver     
        e.wait(TAU-(P180+TXEnableDelay+AQ)/2+D4)                   	# pre-acquisition delay
        e.record(SI, SW, timelength=AQ, sensitivity=ADCSensitivity)     # echo acquisition
        e.wait(TAU-(P180+TXEnableDelay+AQ)/2-D4)                   	# post-acquisition delay 

    # write experiment attributes:  
    for key in pars.keys():
        e.set_description(key, pars[key])		# acqusition parameters
    e.set_description('run', run)			# current scan
    e.set_description('rec_phase', [-1*x for x in PH2_XY16])        # current phase list for data routing

    return e