initial check-in

This commit is contained in:
Markus Rosenstihl
2015-06-26 12:17:24 +00:00
commit d994875c0f
37 changed files with 7044 additions and 0 deletions

156
Scripts/CPMG/op_cpmg_exp.py Normal file
View File

@ -0,0 +1,156 @@
# -*- 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(): # Carr-Purcell-Meiboom-Gill (CPMG) experiment
# set up acquisition parameters:
pars = {}
pars['P90'] = 1.7e-6 # 90-degree pulse length (s)
pars['SF'] = 338.7e6 # spectrometer frequency (Hz)
pars['O1'] = -60e3 # offset from SF (Hz)
pars['NS'] = 8 # number of scans
pars['DS'] = 0 # number of dummy scans
pars['RD'] = 3 # delay between scans (s)
pars['NECH'] = 16 # number of 180-degree pulses
pars['TAU'] = 40e-6 # half pulse period (s)
pars['PHA'] = -127 # receiver phase (degree)
pars['DATADIR'] = '/home/fprak/Students/' # data directory
pars['OUTFILE'] = None # output file name
# specify a variable parameter (optional):
pars['VAR_PAR'] = None # variable parameter name (a string)
start = 40e-6 # starting value
stop = 100e-6 # end value
steps = 10 # number of values
log_scale = False # 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:
pars['NS'] = int(round(pars['NS'] / 4) + 1) * 4
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 experiment time:
if var_key == 'TAU':
seconds = (sum(array)* 2* pars['NECH'] + pars['RD'] * steps) * (pars['NS'] + pars['DS'])
elif var_key == 'NECH':
seconds = (pars['TAU']* 2* sum(array) + pars['RD'] * steps) * (pars['NS'] + pars['DS'])
elif var_key == 'RD':
seconds = (pars['TAU']* 2* pars['NECH'] + sum(array)) * (pars['NS'] + pars['DS'])
else:
seconds = (pars['TAU']* 2* pars['NECH'] + 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 cpmg_experiment(pars, run)
synchronize()
else:
# estimate the experiment time:
seconds = (pars['TAU']* 2* pars['NECH'] + 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 cpmg_experiment(pars, run)
# the pulse program:
def cpmg_experiment(pars, run):
e=Experiment()
dummy_scans = pars.get('DS')
if dummy_scans:
run -= dummy_scans
pars['PROG'] = 'cpmg_experiment'
# phase lists:
pars['PH1'] = [0, 180, 90, 270] # 90-degree pulse
pars['PH3'] = [90, 90, 180, 180] # 180-degree pulse
pars['PH2'] = [0, 180, 90, 270] # receiver
# read in variables:
P90 = pars['P90']
P180 = pars['P90']*2
SF = pars['SF']
O1 = pars['O1']
RD = pars['RD']
NECH = pars['NECH']
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']
# set sampling parameters:
SI = 128 # number of samples
SW = 20e6 # sampling 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) # set frequency and phase for 90-degree pulse
e.ttl_pulse(TXEnableDelay, value=TXEnableValue) # enable RF amplifier
e.ttl_pulse(P90, value=TXEnableValue|TXPulseValue) # apply 90-degree pulse
e.wait(TAU-P90/2-P180/2-TXEnableDelay) # wait for tau
e.set_phase(PH3) # change phase for 180-degree pulse
e.loop_start(NECH) # ----- loop for echoes: -----
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) # pre-acquisition delay
e.record(SI, SW, timelength=AQ, sensitivity=ADCSensitivity) # acquire echo samples
e.wait(TAU-(P180+TXEnableDelay+AQ)/2) # post-acquisition delay
e.set_phase(PH3) # set phase for theta-degree pulse
e.loop_end() # ----------------------------
# 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 data route
return e

176
Scripts/CPMG/op_cpmg_res.py Normal file
View File

@ -0,0 +1,176 @@
# -*- coding: iso-8859-1 -*-
from numpy import *
from scipy.signal import *
from scipy.optimize import *
from os import path, rename
def result():
measurement = MeasurementResult('Magnetization')
suffix = '' # output file name's suffix and...
counter = 1 # counter for arrayed experiments
# loop over the incoming results:
for timesignal in results:
if not isinstance(timesignal,ADC_Result):
continue
# read experiment parameters:
pars = timesignal.get_description_dictionary()
# rotate timesignal by current receiver's phase:
timesignal.phase(pars['rec_phase'])
# provide timesignal to the display tab:
data['Current scan'] = timesignal
# accumulate...
if not locals().get('accu'):
accu = Accumulation()
# skip dummy scans, if any:
if pars['run'] < 0: continue
# add up:
accu += timesignal
# provide accumulation to the display tab:
data['Accumulation'] = accu
# check how many scans are done:
if accu.n == pars['NS']: # accumulation is complete
# get number of echoes:
num_echoes = pars['NECH']
# downsize accu to one point per echo:
echodecay = accu + 0
echodecay.x = resize(echodecay.x, int(num_echoes))
echodecay.y[0] = resize(echodecay.y[0], int(num_echoes))
echodecay.y[1] = resize(echodecay.y[1], int(num_echoes))
# specify noise level:
if not locals().get('noise'):
echo = accu.get_accu_by_index(0)
noise = 0.1*max(abs(echo.y[0]))
samples = abs(echo.y[0]) > noise
# set echo times and intensities:
for i in range(num_echoes):
# get ith echo:
echo = accu.get_accu_by_index(i)
# set echo timing:
echodecay.x[i] = i*2*pars['TAU']
# set echo value:
echodecay.y[0][i] = sum(echo.y[0][samples]) # the sum of echo points that exeed noise
echodecay.y[1][i] = sum(echo.y[1][samples])
#echodecay.y[0][i] = sum(echo.y[0]) # the sum of all echo points
#echodecay.y[1][i] = sum(echo.y[1])
#echodecay.y[0][i] = echo.y[0][echo.x.size/2] # a middle echo point
#echodecay.y[1][i] = echo.y[1][echo.x.size/2]
# compute a signal's phase:
phi0 = arctan2(echodecay.y[1][0], echodecay.y[0][0]) * 180 / pi
if not locals().get('ref'): ref = phi0
print 'phi0 = ', phi0
# rotate signal to maximize Re (optional):
#echodecay.phase(-phi0)
# provide echo decay to the display tab:
data['Echo Decay'] = echodecay
# fit a mono-exponential function to the echo decay:
[amplitude, rate] = fitfunc(echodecay.x, echodecay.y[0])
print '%s%02g' % ('Amplitude = ', amplitude)
print '%s%02g' % ('T2 [s] = ', 1./rate)
# provide the fit to the display tab:
fit = MeasurementResult('Mono-Exponential Fit')
for i, key in enumerate(echodecay.x):
fit[key] = echodecay.y[0][i]
fit.y = func([amplitude, rate], echodecay.x)
data[fit.get_title()] = fit
# check whether it is an arrayed experiment:
var_key = pars.get('VAR_PAR')
if var_key:
# get variable parameter's value:
var_value = pars.get(var_key)
# provide data recorded with different var_value's to the display tab:
data['Accumulation'+"/"+var_key+"=%e"%(var_value)] = accu
data['Echo Decay'+"/"+var_key+"=%e"%(var_value)] = echodecay
data[fit.get_title()+"/"+var_key+"=%e"%(var_value)] = fit
# measure a signal parameter vs. var_value:
measurement[var_value] = amplitude
#measurement[var_value] = sum(echodecay.y[0][:])
#measurement[var_value] = 1./rate
# provide measurement to the display tab:
data[measurement.get_title()] = measurement
# save accu if required:
outfile = pars.get('OUTFILE')
if outfile:
datadir = pars.get('DATADIR')
# write data in Simpson format:
filename = datadir+outfile+suffix+'.dat'
if path.exists(filename):
rename(filename, datadir+'~'+outfile+suffix+'.dat')
accu.write_to_simpson(filename)
# write data in Tecmag format:
# filename = datadir+outfile+'.tnt'
# accu.write_to_tecmag(filename, nrecords=20)
# write parameters in a text file:
filename = datadir+outfile+suffix+'.par'
if path.exists(filename):
rename(filename, datadir+'~'+outfile+suffix+'.par')
fileobject = open(filename, 'w')
for key in sorted(pars.iterkeys()):
if key=='run': continue
if key=='rec_phase': continue
fileobject.write('%s%s%s'%(key,'=', pars[key]))
fileobject.write('\n')
fileobject.close()
# reset accumulation:
del accu
# the fitting procedure:
def fitfunc(xdata, ydata):
# initialize variable parameters:
try:
# solve Az = b:
A = array((ones(xdata.size/2), xdata[0:xdata.size/2]))
b = log(abs(ydata[0:xdata.size/2]))
z = linalg.lstsq(transpose(A), b)
amplitude = exp(z[0][0])
rate = -z[0][1]
except:
amplitude = abs(ydata[0])
rate = 1./(xdata[-1] - xdata[0])
p0 = [amplitude, rate]
# run least-squares optimization:
plsq = leastsq(residuals, p0, args=(xdata, ydata))
return plsq[0] # best-fit parameters
def residuals(p, xdata, ydata):
return ydata - func(p, xdata)
# here is the function to fit:
def func(p, xdata):
return p[0]*exp(-p[1]*xdata)
pass