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

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

def experiment(): # 2D NOESY experiment, using States-TPPI technique for quadrature detection in F1 

                  # States-TPPI technique achieves two effects for an indirect dimension F1: 
                  # (1) signal frequency discrimination and (2) displacement of the unmodulated 
                  # artefact signal from an inconvenient location in the middle of spectrum to the edge.
                  # (1) is achieved by recording two data sets at each t1 point - with orthogonal phases 
                  # of the preparation pulse and same receiver phase - and storing them in separate memory 
                  # locations. These two fid measurements yield one complex data point in F1.
                  # (2) by inverting phase of the preparation pulse and the receiver each time when t1 is 
                  # incremented (that is for subsequent complex points). Therefore, the artefact signal 
                  # becomes modulated at the Nyquist frequency and appears in the spectrum at F1=ħSW/2 Hz 
                  # instead of 0 Hz, where SW is spectral width. [http://nmrwiki.org]
    
    # set up acqusition parameters:      
    pars = {}
    pars['P90'] = 1.65e-6           # 90-degree pulse length (s)
    pars['SF'] = 338.7e6            # spectrometer frequency (Hz)
    pars['O1'] = -57.0e3            # offset from SF (Hz)
    pars['SW'] = 150e3              # spectral width (Hz)
    pars['SI1'] = 32                # number of (complex) data points in F1 (2D)
    pars['SI2'] = 128               # number of (complex) data points in F2
    pars['D8'] = 100e-6             # mixing time, tm (s)
    pars['NS'] = 16                 # number of scans
    pars['DS'] = 0                  # number of dummy scans
    pars['RD'] = 2.5                # delay between scans (s)
    pars['DEAD1'] = 4e-6            # receiver dead time (s)  
    pars['PHA'] = 150               # receiver reference phase (degree)
    pars['DATADIR'] = '/home/fprak/'    # data directory
    pars['OUTFILE'] = 'test'                # output file name
    
    # specify a variable parameter (optional):
    pars['VAR_PAR'] = 'D8'	# variable parameter name (a string)   
    start = 10.e-6		# starting value
    stop = 1000e-6 		# end value
    steps = 3			# 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!!!")   
                         
    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']%8 != 0:
        pars['NS'] = (pars['NS'] / 8 + 1) * 8 
        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 == 'D8':
            seconds = (sum(array) + (.5*pars['SI1']/pars['SW'] + pars['RD']) * steps) * (pars['NS'] + pars['DS']) * 2*pars['SI1']
        elif var_key == 'RD':
            seconds = (sum(array) + (.5*pars['SI1']/pars['SW'] + pars['D8']) * steps) * (pars['NS'] + pars['DS']) * 2*pars['SI1']
        else:
            seconds = (.5*pars['SI1']/pars['SW'] + pars['D8'] + pars['RD']) * steps * (pars['NS']+ pars['DS']) * 2*pars['SI1']
        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 and sampling the indirect dimension F1:
            for run in xrange((pars['NS']+pars['DS'])*2*pars['SI1']):
                yield noesyst_experiment(pars, run)
            synchronize() 

    else:
       # estimate the experiment time:
        seconds = (.5*pars['SI1']/pars['SW'] + pars['D8'] + pars['RD']) * (pars['NS']+ pars['DS']) * 2*pars['SI1']
        print 'sec ', seconds
        m, s = divmod(seconds, 60)
        h, m = divmod(m, 60)
        print '%s%02d:%02d:%02d' % ('Experiment time estimated: ', h, m, s)

       # loop for accumulation and sampling the indirect dimension F1:
        for run in xrange((pars['NS']+pars['DS'])*2*pars['SI1']):
            yield noesyst_experiment(pars, run)


# the pulse program: 

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

    dummy_scans = pars.get('DS')
    if dummy_scans:
        run -= dummy_scans
    
    # phase lists (M.H.Levitt 'Spin Dynamics', 2nd edition, p.530): 
    pars['PH1'] = [  0, 180,   0, 180,   0, 180,   0, 180]	
    pars['PH3'] = [180, 180, 180, 180, 180, 180, 180, 180]
    pars['PH4'] = [  0,   0,  90,  90, 180, 180, 270, 270]	
    pars['PH2'] = [  0, 180,  90, 270, 180,   0, 270,  90]    # receiver

    # read in variables:
    P90 = pars['P90'] 
    SF = pars['SF']
    O1 = pars['O1']   
    RD = pars['RD']
    DEAD1 = pars['DEAD1']
    D8 = pars['D8']
    NS = pars['NS']
    PH1 = pars['PH1'][run%len(pars['PH1'])]
    PH3 = pars['PH3'][run%len(pars['PH3'])]
    PH4 = pars['PH4'][run%len(pars['PH4'])]
    PH2 = pars['PH2'][run%len(pars['PH2'])] 
    PHA = pars['PHA']
        
    # F1 sampling parameters:
    IN0 = 1./pars['SW']        # t1 increment
    
    # the States-TPPI bit:
    PH1-= (run/(1*NS))%4*90    # PH1 changes by 90-deg. after every 1*NS scans
    D0  = (run/(2*NS)) *IN0    # t1 increases by IN0 after every 2*NS scans   
    
    # F2 sampling parameters:
    SI2 = pars['SI2']
    SW2 = pars['SW']
    while SW2 <= 10e6 and SI2 < 256*1024:
        SI2 *= 2
        SW2 *= 2
        
    # 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)	# 90-degree pulse 

    e.wait(D0)                                          # incremented delay t1
    e.set_phase(PH3)

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

    e.wait(D8)                  	              	# mixing time
    e.set_phase(PH4)

    e.ttl_pulse(TXEnableDelay, value=TXEnableValue)		
    e.ttl_pulse(P90, value=TXEnableValue|TXPulseValue)	# 90-degree pulse
    e.set_phase(PHA)                                    # set phase for receiver 
    e.wait(DEAD1)                                       # wait for coil ringdown
    e.record(SI2, SW2, sensitivity=ADCSensitivity)     	# acquire signal

    # 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', -PH2)		# current receiver phase

    return e