[ ]:
Jupyter notebook for fitting omega scan profiles¶
import necessary modules¶
[1]:
import matplotlib.cm as cm
import matplotlib.pyplot as plt
import matplotlib.cbook as cbook
from matplotlib.path import Path
from matplotlib.patches import PathPatch
import nexusformat.nexus as nx
import pandas as pd
from PIL import ImageEnhance
import os, fnmatch
from scipy.integrate import quad
import numpy as np
from scipy import stats
from scipy.optimize import curve_fit
from pylab import *
import math
from scipy.fftpack import rfft, irfft, fftfreq
from lmfit.models import PseudoVoigtModel, LinearModel, GaussianModel
from lmfit import Model
set paths¶
below enter the paths to folders or the internal paths within the DAWN processed nxs file
[2]:
#path to where DAWN output has been saved
DAWN_OUT_FOLDER='/dls/science/users/rpy65944/Demo_omegascans/'
#path to where raw data has been saved
ORIGINAL_DATA_FOLDER='/dls/staging/dls/i07/data/2023/si33555-1/Sample6/'
#path from within the DAWN processed nxs file where the sum line profile is saved
lineprofilepath='/processed/auxiliary/2-Sum/sum/data'
crop_image_path='/processed/result/data'
#change working directory to where the SXRDcorrections.py file is saved and import correction functions
os.chdir('/dls/science/users/rpy65944/')
import SXRDcorrections as corrs
define fitting choices¶
[3]:
pattern = "*.nxs" # this is the file extension of the output from DAWN, will most likely be .nxs
sample='sample6' #name of sample used when creating subfolder to save data to
fit_type='pvoigt' #choose wither 'pvoigt' or 'gaussian', recomment to try pvoigt to start with
run fitting on all nxs output files in dawn out folder¶
[18]:
%cd {DAWN_OUT_FOLDER}
listOfFiles = os.listdir('.')
listOfFiles.sort()
def integrand(x1):
return result.eval_components(x=x1)['{}'.format(fit_type)]
mypath=f"{DAWN_OUT_FOLDER}/{sample}_IAPL/"
if not os.path.isdir(mypath):
os.makedirs(mypath)
os.chdir(mypath)
f = open(f'{sample}_omegas_datsIAPL.csv', "w")
f.write('entry\th\tk\tl\tI\tdI\n')
for entry in listOfFiles:
print(entry)
if fnmatch.fnmatch(entry, pattern):
scan_number=entry.split('_')[0].replace('i07-','')
print(scan_number)
dawn_data=nx.nxload(f'{DAWN_OUT_FOLDER}/{entry}')
linedata=dawn_data[f'{lineprofilepath}'].nxdata
original_data=nx.nxload(f"{ORIGINAL_DATA_FOLDER}/{entry.split('_')[0]}.nxs")
omega=original_data['entry/instrument']['diff2omega/value_set'].nxdata
gamma=original_data['entry/instrument']['diff2gamma/value'].nxdata
alpha=original_data['entry/instrument']['diff2alpha/value'].nxdata
delta=original_data['entry/instrument']['diff2delta/value'].nxdata
checkangles=[alpha,delta,gamma]
alpha,delta,gamma=[np.mean(ang) if np.atleast_1d(ang).size > 1 else ang for ang in checkangles]
#calculate corrections using equations from ANA software, in SXRDcorrections.py
corrI=corrs.intcorr(delta,gamma,alpha)
corrA=corrs.areacorr(delta,gamma,alpha)
corrP=corrs.polcorr(delta,gamma)
corrL=corrs.lorcorr(delta,gamma)
d5i=None #if d5i included in file put path here
#set x and y values for fitting*(corrA)
if d5i != None:
y = 1000*linedata*(corrI)*(corrP)*(corrL)*(corrA)/d5i
else:
y= 1000*linedata*(corrI)*(corrP)*(corrL)*(corrA)
x = omega
print(len(x), len(y))
#set line model and calculate fit to data
line_mod = LinearModel(prefix='line_')
if fit_type == 'gaussian':
fit_mod= GaussianModel()
elif fit_type =='pvoigt':
fit_mod=PseudoVoigtModel()
mod = line_mod + fit_mod
pars = line_mod.make_params(intercept=y.min(), slope=-700)
pars += fit_mod.guess(y, x=x)
result = mod.fit(y, pars, x=x)
xnew=arange(omega.min(),omega.max(),0.01)
comps = result.eval_components(x=xnew)
#dely = result.eval_uncertainty(sigma=1)
h=round(original_data['entry/instrument']['hkl/h'].nxdata.mean(),4)
k=round(original_data['entry/instrument']['hkl/k'].nxdata.mean(),4)
l=round(original_data['entry/instrument']['hkl/l'].nxdata.mean(),4)
I = round(quad(integrand, omega.min(), omega.max())[0],5)
dI=0.1*I
#write data to csv file
f.write(str(scan_number)+'\t'+str(h)+'\t'+str(k)+'\t'+str(l)+'\t'+str(I)+'\t'+str(dI)+'\n')
#create and save figure
fig, (ax1, ax2,ax3) = plt.subplots(3, 1, figsize=(15,10),sharex=False,gridspec_kw={'height_ratios': [3, 1,1]})
ax1.plot(x,y)
ax1.plot(xnew,(comps['{}'.format(fit_type)]))
ax1.plot(xnew,(comps['line_']))
ax1.plot(xnew,(comps['{}'.format(fit_type)]+comps['line_']))
ax1.set_title('{}'.format(entry))
if d5i!=None:
ax2.plot(x,d5i,color='black')
else:
ax2.text(0.5,0.5,'no d5i data')
ax3.imshow(dawn_data[f'{crop_image_path}'][np.argmax(linedata)].nxdata)
ax1.axvline(x[np.argmax(linedata)],ls='--')
savefig(f'anaIAPL_{scan_number}.png')
plt.close(fig)
print(I,dI,entry,f" \n corrections = cI {round(corrI,4)} ,cA {round(corrA,4)}, cP {round(corrP,4)}, cL {round(corrL,4)}, delta {delta}, gamma {gamma}, omega {omega.mean()}")
print(str(h)+' '+str(k)+' '+str(l)+' '+str(I)+' '+str(dI)+'\n')
f.close()
/dls/science/users/rpy65944/Demo_omegascans
i07-475543_processed_250304_085816.nxs
475543
81 81
1805149.00796 180514.90079600003 i07-475543_processed_250304_085816.nxs
corrections = cI 1.001 ,cA 0.173, cP 1.0307, cL 0.1725, delta 9.949582374, gamma 3.159939125, omega -153.76029166700002
-0.9998 0.4999 0.5 1805149.00796 180514.90079600003
i07-475544_processed_250304_130927.nxs
475544
81 81
1563794.94016 156379.494016 i07-475544_processed_250304_130927.nxs
corrections = cI 1.002 ,cA 0.1731, cP 1.0306, cL 0.1723, delta 9.946380268, gamma 4.220432675, omega -153.419680556
-0.9998 0.4999 0.666 1563794.94016 156379.494016
i07-475545_processed_250304_130928.nxs
475545
81 81
1762409.82892 176240.982892 i07-475545_processed_250304_130928.nxs
corrections = cI 1.001 ,cA 0.173, cP 1.0307, cL 0.1725, delta 9.950356853, gamma 3.1574823, omega -100.67338888900001
-0.9998 -0.4999 0.5 1762409.82892 176240.982892
i07-475546_processed_250304_130928.nxs
475546
29 29
334909.60101 33490.960101 i07-475546_processed_250304_130928.nxs
corrections = cI 1.0001 ,cA 0.1723, cP 1.0306, cL 0.1723, delta 9.922676778131304, gamma 1.3023208105363422, omega 79.00097386099654
1.0 0.5 0.2 334909.60101 33490.960101
sample6_IAPL
[ ]: