### Install with Prefix Source: https://github.com/dkriegner/xrayutilities/blob/main/README.md Install the package to a specific directory using the prefix flag. ```bash pip install --prefix= . ``` -------------------------------- ### Windows site-packages path example Source: https://github.com/dkriegner/xrayutilities/blob/main/doc/source/index.rst Example directory path for site-packages on Windows systems. ```bash /Lib/site-packages ``` -------------------------------- ### Install xrayutilities from source Source: https://github.com/dkriegner/xrayutilities/blob/main/README.md Commands for building and installing from the source directory with various OpenMP configuration options. ```bash pip install . ``` ```bash pip install . --config-settings=setup-args="-Duse_openmp=disabled" ``` ```bash pip install . --config-settings=setup-args="-Duse_openmp=auto" ``` -------------------------------- ### Install xrayutilities via Linux system package Source: https://github.com/dkriegner/xrayutilities/blob/main/README.md Installation command for Debian-based distributions. ```bash sudo apt install python3-xrayutilities ``` -------------------------------- ### Install xrayutilities via pip Source: https://github.com/dkriegner/xrayutilities/blob/main/README.md Standard installation command for the Python package manager. ```bash pip install xrayutilities ``` -------------------------------- ### Install xrayutilities via Conda Source: https://github.com/dkriegner/xrayutilities/blob/main/README.md Installation command using the conda-forge channel. ```bash conda install -c conda-forge xrayutilities ``` -------------------------------- ### Browse API Documentation Source: https://github.com/dkriegner/xrayutilities/blob/main/README.md Start a local pydoc server to view API documentation in a web browser. ```bash pydoc -p PORT ``` -------------------------------- ### Install xrayutilities via package managers Source: https://github.com/dkriegner/xrayutilities/blob/main/doc/README_sf.rst Standard installation commands for common Python package managers and system repositories. ```bash pip install xrayutilities ``` ```bash conda install -c conda-forge xrayutilities ``` ```bash sudo apt install python3-xrayutilities ``` ```bash pip install . ``` -------------------------------- ### Determine Installation Location Source: https://github.com/dkriegner/xrayutilities/blob/main/README.md Check the current installation path of the xrayutilities package. ```bash python -c "import xrayutilities as xu; print xu.__file__" ``` -------------------------------- ### Setup FitModel for InMnAs epilayer Source: https://github.com/dkriegner/xrayutilities/blob/main/doc/source/simulations.rst Initializes a LayerStack and FitModel for refining parameters of a pseudomorphic InMnAs epilayer on InAs(001). ```python from copy import deepcopy import xrayutilities as xu from matplotlib.pylab import * # global parameters wavelength = xu.wavelength('CuKa1') offset = -0.035 # angular offset of the zero position of the data # set up LayerStack for simulation: InAs(001)/(In,Mn)As(~25 nm) InAs = deepcopy(xu.materials.InAs) # do not modify internal database InAs.a = 6.057 lInAs = xu.simpack.Layer(InAs, inf) InMnAs = xu.materials.Crystal('InMnAs', xu.materials.SGLattice( 216, 6.050, atoms=('In', 'Mn', 'As'), pos=('4a', '4a', '4c'), occ=(0.99, 0.01, 1)), cij=InAs.cij) lInMnAs = xu.simpack.Layer(InMnAs, 254, relaxation=0) pstack = xu.simpack.PseudomorphicStack001('list', lInAs, lInMnAs) ``` -------------------------------- ### Configure Python Path for xrayutilities Source: https://github.com/dkriegner/xrayutilities/blob/main/README.md Add the installation directory to sys.path to ensure the package is discoverable by the Python interpreter. ```python import sys sys.path.append("path to the xrayutilities package") ``` ```python import sys sys.path.append("path to the xrayutilities package") import xrayutilities ``` -------------------------------- ### Dynamical Diffraction Model Fitting Source: https://github.com/dkriegner/xrayutilities/blob/main/doc/source/simulations.rst Setup and execution of a dynamical diffraction model to fit experimental X-ray diffraction data. ```python # set up simulation object thetaMono = arcsin(wavelength/(2 * xu.materials.Ge.planeDistance(2, 2, 0))) Cmono = cos(2 * thetaMono) dyn = xu.simpack.DynamicalModel(pstack, I0=1.5e9, background=0, resolution_width=2e-3, polarization='both', Cmono=Cmono) fitmdyn = xu.simpack.FitModel(dyn) fitmdyn.set_param_hint('InMnAs_c', vary=True, min=6.02, max= 6.06) fitmdyn.set_param_hint('InAs_a', vary=True) fitmdyn.set_param_hint('InMnAs_a', expr='InAs_a') fitmdyn.set_param_hint('resolution_width', vary=True) params = fitmdyn.make_params() # plot experimental data f = figure(figsize=(7,5)) d = xu.io.RASFile('inas_layer_radial_002_004.ras.bz2', path='examples/data') scan = d.scans[-1] tt = scan.data[scan.scan_axis] - offset semilogy(tt, scan.data['int'], 'o-', ms=3, label='data') # perform fit and plot the result fitmdyn.lmodel.set_hkl((0, 0, 4)) ai = (d.scans[-1].data[d.scan.scan_axis] - offset)/2 fitr = fitmdyn.fit(d.scans[-1].data['int'], params, ai) # print(fitr.fit_report()) # to get a summary of the fitted parameters ``` -------------------------------- ### Create a silicon layer Source: https://github.com/dkriegner/xrayutilities/blob/main/doc/source/simulations.rst Initializes a silicon layer with a thickness of 20 nm. ```python import xrayutilities as xu lay = xu.simpack.Layer(xu.materials.Si, 200) ``` -------------------------------- ### Initialize a Specular Reflectivity Model Source: https://github.com/dkriegner/xrayutilities/blob/main/doc/source/simulations.rst Configures a model with common parameters like intensity, background, and resolution width. ```python m = xu.simpack.SpecularReflectivityModel(layerstack, I0=1e6, background=1, resolution_width=0.001) ``` -------------------------------- ### Initialize material elements Source: https://github.com/dkriegner/xrayutilities/blob/main/doc/source/examples.rst Loads chemical elements with their respective X-ray optical properties from the materials subpackage. ```python import matplotlib.pyplot as plt import xrayutilities as xu # elements (which contain their x-ray optical properties) are loaded from # xrayutilities.materials.elements In = xu.materials.elements.In P = xu.materials.elements.P ``` -------------------------------- ### Hello World: Spec File Processing and Visualization Source: https://github.com/dkriegner/xrayutilities/blob/main/doc/source/index.rst Demonstrates calculating angles, reading a scan from a spec file, and plotting a reciprocal space map using matplotlib. ```python .. literalinclude:: example_xu_read_spec_easy.py :linenos: :language: python ``` -------------------------------- ### Initialize HXRD with explicit energy Source: https://github.com/dkriegner/xrayutilities/blob/main/doc/source/examples.rst Demonstrates initializing the HXRD class with a specific energy in eV. ```python hxrd = xu.HXRD(Si.Q(1, 1, -2), Si.Q(1, 1, 1), en=10000) # energy in eV ``` -------------------------------- ### Define user-specific configuration file Source: https://github.com/dkriegner/xrayutilities/blob/main/doc/source/examples.rst Configures xrayutilities parameters like verbosity, wavelength, and thread count. Place this in ~/.xrayutilities.conf or the working directory. ```ini # begin of xrayutilities configuration [xrayutilities] # verbosity level of information and debugging outputs # 0: no output # 1: very import notes for users # 2: less import notes for users (e.g. intermediate results) # 3: debuging output (e.g. print everything, which could be interesing) # levels can be changed in the config file as well verbosity = 1 # default wavelength in angstrom, wavelength = MoKa1 # Molybdenum K alpha1 radiation (17479.374eV) # default energy in eV # if energy is given wavelength settings will be ignored #energy = 10000 #eV # number of threads to use in parallel sections of the code nthreads = 1 # 0: the maximum number of available threads will be used (as returned by # omp_get_max_threads()) # n: n-threads will be used ``` -------------------------------- ### Verify Codebase and Run Tests Source: https://github.com/dkriegner/xrayutilities/blob/main/release.txt Perform static analysis and execute unit tests to ensure the integrity of the release. ```bash # change the version in meson.build # update copyright notice in README.md ruff check # run the unit tests python -m pytest ``` -------------------------------- ### Clone the source repository Source: https://github.com/dkriegner/xrayutilities/blob/main/doc/README_sf.rst Use git to download the latest source code from the official repository. ```bash git clone https://github.com/dkriegner/xrayutilities.git ``` -------------------------------- ### Simulate diffraction with DynamicalModel Source: https://github.com/dkriegner/xrayutilities/blob/main/doc/source/simulations.rst Configures a dynamical model for laboratory sources using a Ge(220) monochromator crystal. ```python import math qGe220 = linalg.norm(xu.materials.Ge.Q(2, 2, 0)) thMono = math.asin(qGe220 * xu.config.WAVELENGTH / (4*math.pi)) md = xu.simpack.DynamicalModel(pls, Cmono=math.cos(2 * thMono), polarization='both') Idyn = md.simulate(ai, hkl=(0, 0, 4)) ``` -------------------------------- ### Define Layer Stack and Simulate Specular Reflectivity Source: https://github.com/dkriegner/xrayutilities/blob/main/doc/source/simulations.rst Constructs a layer stack using materials and layers, then calculates the specular reflectivity. ```python import numpy # building a stack of layers sub = xu.simpack.Layer(xu.materials.GaAs, float('inf'), roughness=2.0) lay1 = xu.simpack.Layer(xu.materials.AlGaAs(0.25), 75, roughness=2.5) lay2 = xu.simpack.Layer(xu.materials.AlGaAs(0.75), 25, roughness=3.0) pls = xu.simpack.PseudomorphicStack001('pseudo', sub+5*(lay1+lay2)) # reflectivity calculation m = xu.simpack.SpecularReflectivityModel(pls, sample_width=5, beam_width=0.3) ai = numpy.linspace(0, 5, 10000) Ixrr = m.simulate(ai) ``` -------------------------------- ### Basic 2D Gridding Source: https://github.com/dkriegner/xrayutilities/blob/main/doc/source/examples.rst Initialize a 2D gridder and map data to a regular grid. ```python import xrayutilities as xu # import Python package g = xu.Gridder2D(100, 101) # initialize the Gridder object, which will # perform Gridding to a regular grid with 100x101 points #====== load some data here ===== g(x, y, data) # call the gridder with the data griddata = g.data # the data attribute contains the gridded data. ``` -------------------------------- ### Create a superlattice LayerStack Source: https://github.com/dkriegner/xrayutilities/blob/main/doc/source/simulations.rst Demonstrates creating complex superlattice stacks using multiplication of layer groups. ```python lay1 = xu.simpack.Layer(xu.materials.SiGe(0.3), 50) lay2 = xu.simpack.Layer(xu.materials.SiGe(0.6), 40) layerstack = xu.simpack.LayerStack('Si/SiGe SL', sub + 5*(lay1 + lay2)) ``` -------------------------------- ### Fit Area Detector Parameters Source: https://github.com/dkriegner/xrayutilities/blob/main/doc/source/examples.rst Demonstrates fitting detector parameters using primary beam scans. The resulting outer angle offset must be applied manually during q-conversion. ```python import xrayutilities as xu import numpy as np # define the detector # this is a dummy detector for demonstration det = xu.detectors.AreaDetector('z-', 'y+', cch1=140, cch2=1000, Nch1=516, Nch2=516, pwidth1=4.5e-5, pwidth2=4.5e-5, distance=1000., detrot=0, tiltazimuth=0, tilt=0) # define the fitting object # this requires a list of scans (here empty) fit = xu.fitting.FitAreaDetector(det, []) # fix some parameters fit.fix('pwidth1', 'pwidth2') # run the fit fit.fit() # print the results fit.print_results() ``` -------------------------------- ### Simulate Material Stack Diffraction Source: https://github.com/dkriegner/xrayutilities/blob/main/doc/source/index.rst Constructs a pseudomorphic sample stack and simulates reflectivity and dynamical diffraction curves. ```python import xrayutilities as xu # Build the pseudomorphic sample stack using the elastic parameters sub = xu.simpack.Layer(xu.materials.GaAs, inf) lay1 = xu.simpack.Layer(xu.materials.AlGaAs(0.25), 75, relaxation=0.0) lay2 = xu.simpack.Layer(xu.materials.AlGaAs(0.75), 25, relaxation=0.0) pls = xu.simpack.PseudomorphicStack001('pseudo', sub+10*(lay1+lay2)) # simulate reflectivity m = xu.simpack.SpecularReflectivityModel(pls, sample_width=5, beam_width=0.3) alphai = linspace(0, 10, 1000) Ixrr = m.simulate(alphai) # simulate dynamical diffraction curve alphai = linspace(29, 38, 1000) md = xu.simpack.DynamicalModel(pls) Idyn = md.simulate(alphai, hkl=(0, 0, 4)) ``` -------------------------------- ### Apply incidence angle constraints in Q2AngFit Source: https://github.com/dkriegner/xrayutilities/blob/main/doc/source/examples.rst Demonstrates using a pseudo-angle constraint to keep all angles free during fitting. Requires a defined constraint function. ```python aiconstraint = xu.q2ang_fit.incidenceAngleConst bounds = ((0, 90), (-180, 180), (-1, 90), (-1, 90)) ang, qerror, errcode = xu.Q2AngFit( q_laboratory, hxrd, bounds, constraints=[{'type':'eq', 'fun': lambda a: aiconstraint(a, 5, hxrd)}, ]) ``` -------------------------------- ### Tag and Push Release Source: https://github.com/dkriegner/xrayutilities/blob/main/release.txt Create a version tag in the Git repository and push it to the remote origin. ```bash git tag -a vX -m "version X" git push origin vX ``` -------------------------------- ### Simulate Diffuse Reflectivity Source: https://github.com/dkriegner/xrayutilities/blob/main/doc/source/simulations.rst Configures a layer stack and simulates diffuse reflectivity maps and curves. ```python from matplotlib.pylab import * import xrayutilities as xu sub = xu.simpack.Layer(xu.materials.Si, inf, roughness=1, lat_correl=100) lay1 = xu.simpack.Layer(xu.materials.Si, 200, roughness=1, lat_correl=200) lay2 = xu.simpack.Layer(xu.materials.Ge, 70, roughness=3, lat_correl=50) ls = xu.simpack.LayerStack('SL 5', sub+5*(lay2+lay1)) alphai = arange(0.17, 2, 0.001) # for the calculation on the specular rod qz = arange(0, 0.5, 0.0005) # for the map calculation qL = arange(-0.02, 0.02, 0.0003) m = xu.simpack.DiffuseReflectivityModel(ls, sample_width=10, beam_width=1, energy='CuKa1', vert_correl=1000, vert_nu=0, H=1, method=2, vert_int=0) d = m.simulate(alphai) imap = m.simulate_map(qL, qz) # or imap = m.simulate_map(qL, qz, scan='gisaxs', alphai=0.17) figure() subplot(121) semilogy(alphai, d, label='diffuse XRR') xlabel('incidence angle (deg)') ylabel('intensity (arb. u.)') ylim(1e-6, 1e-4) subplot(122) pcolor(qL, qz, imap.T, norm=mpl.colors.LogNorm()) xlabel(r'Q$_{\parallel}$ ($\\mathrm{\AA^{-1}}$)') ylabel(r'Q$_{\perp}$ ($\\mathrm{\AA^{-1}}$)') colorbar() tight_layout() ``` -------------------------------- ### Crystal Lattice Transformation Source: https://github.com/dkriegner/xrayutilities/blob/main/doc/source/examples.rst Demonstrates creating SGLattice objects and transforming them using identity matrices or specific conversion matrices. ```python import numpy import xrayutilities as xu C1 = xu.materials.SGLattice("227:1", 3.5668, atoms=["C"], pos=[(0,0,0)]) C2 = xu.materials.SGLattice("227:2", 3.5668, atoms=["C"], pos=[(1/8, 1/8, 1/8)]) C1 == C2 # False C3 = C2.transform(numpy.identity(3), (1/8, 1/8, 1/8)) C3 == C1 # True ``` ```python import xrayutilities as xu InP111_lattice = xu.materials.InP.lattice.transform(((-1/2, 0, 1), (1/2, -1/2, 1), (0, 1/2, 1)), (0, 0, 0)) ``` -------------------------------- ### Create a Pseudomorphic Superlattice Stack Source: https://github.com/dkriegner/xrayutilities/blob/main/doc/source/simulations.rst Defines a stack of layers with automatic lattice parameter adaptation for (001) surfaces. ```python sub = xu.simpack.Layer(xu.materials.Si, float('inf')) buf1 = xu.simpack.Layer(xu.materials.SiGe(0.5), 5000, relaxation=1.0) buf2 = xu.simpack.Layer(xu.materials.SiGe(0.8), 5000, relaxation=1.0) lay1 = xu.simpack.Layer(xu.materials.SiGe(0.6), 50, relaxation=0.0) lay2 = xu.simpack.Layer(xu.materials.SiGe(1.0), 50, relaxation=0.0) # create pseudomorphic superlattice stack pls = xu.simpack.PseudomorphicStack001('SL 5/5', sub+buf1+buf2+5*(lay1+lay2)) ``` -------------------------------- ### Load Predefined Materials Source: https://github.com/dkriegner/xrayutilities/blob/main/doc/source/examples.rst Accessing materials already included in the xrayutilities module. ```python InP = xu.materials.InP InPWZ = xu.materials.InPWZ ``` -------------------------------- ### Read XRDML files Source: https://github.com/dkriegner/xrayutilities/blob/main/doc/source/examples.rst Illustrates parsing Panalytical XRDML files, including support for compressed formats and low-level file access. ```python import xrayutilities as xu om, tt, psd = xu.io.getxrdml_map('rsm_%d.xrdml.bz2', [1, 2, 3, 4, 5], path='data') # or using the more flexible function tt, om, psd = xu.io.getxrdml_scan('rsm_%d.xrdml.bz2', 'Omega', scannrs=[1, 2, 3, 4, 5], path='data') # single files can also be opened directly using the low level approach xf = xu.io.XRDMLFile('data/rsm_1.xrdml.bz2') # then see xf.scan and its attributes ``` -------------------------------- ### Construct a LayerStack Source: https://github.com/dkriegner/xrayutilities/blob/main/doc/source/simulations.rst Combines multiple layers into a stack, demonstrating both constructor and summation methods. ```python sub = xu.simpack.Layer(xu.materials.Si, float('inf')) lay1 = xu.simpack.Layer(xu.materials.Ge, 200) lay2 = xu.simpack.Layer(xu.materials.SiO2, 30) ls = xu.simpack.LayerStack('Si/Ge', sub, lay1, lay2) # or equivalently ls = xu.simpack.LayerStack('Si/Ge', sub + lay1 + lay2) ``` -------------------------------- ### Configure PYTHONPATH for Unix/Linux Source: https://github.com/dkriegner/xrayutilities/blob/main/doc/source/index.rst Set the PYTHONPATH environment variable to include the xrayutilities site-packages directory. ```bash export PYTHONPATH=$PYTHONPATH:/lib64/python2.7/site-packages ``` -------------------------------- ### Determine linear detector parameters Source: https://github.com/dkriegner/xrayutilities/blob/main/doc/source/examples.rst Uses a script to calculate pixel width, center channel, and detector tilt for linear detectors. Requires a scan through the primary beam. ```python .. literalinclude:: example_xu_linear_detector_parameters.py :linenos: :language: python ``` -------------------------------- ### Read SPEC files using direct parsing or HDF5 conversion Source: https://github.com/dkriegner/xrayutilities/blob/main/doc/source/examples.rst Demonstrates two methods for handling SPEC files: direct parsing of scan data or dumping to HDF5 for efficient network access. ```python import xrayutilities as xu import os # open spec file or use open SPECfile instance try: s except NameError: s = xu.io.SPECFile("sample_name.spec", path="./specdir") # method (1) s.scan10.ReadData() scan10data = s.scan10.data # method (2) h5file = os.path.join("h5dir", "h5file.h5") s.Save2HDF5(h5file) # save content of SPEC file to HDF5 file # read data from HDF5 file [angle1, angle2], scan10data = xu.io.geth5_scan(h5file, [10], "motorname1", "motorname2") ``` ```python s.Update() # reparse for new scans in open SPECFile instance # reread data method (1) s.scan10.ReadData() scan10data = s.scan10.data # reread data method (2) s.Save2HDF5(h5) # save content of SPEC file to HDF5 file # read data from HDF5 file [angle1, angle2], scan10data = xu.io.geth5_scan(h5file, [10], "motorname1", "motorname2") ``` -------------------------------- ### Determine goniometer angles with geometry restrictions Source: https://github.com/dkriegner/xrayutilities/blob/main/doc/source/examples.rst Uses Q2AngFit to calculate goniometer angles given specific bounds. Ensure the qerror is verified after execution. ```python # tell bounds of angles / (min,max) pair or fixed value for all motors. # maximum of three free motors! here the first goniometer angle is fixed. # om, phi, tt, delta bounds = (5, (-180, 180), (-1, 90), (-1, 90)) ang, qerror, errcode = xu.Q2AngFit(q_laboratory, hxrd, bounds) print(f"err {errcode} ({qerror:.3g}) angles {np.round(ang, 5)}") # check that qerror is small!! print("sanity check with back-transformation (hkl): ", np.round(hxrd.Ang2HKL(*ang,mat=SmFeO3),5)) ``` -------------------------------- ### Read and convert EDF files to HDF5 Source: https://github.com/dkriegner/xrayutilities/blob/main/doc/source/examples.rst Shows how to parse CCD frames from EDF files and store them into an HDF5 container for better compression and handling of large datasets. ```python import xrayutilities as xu import numpy specfile = "specfile.spec" h5file = "h5file.h5" s = xu.io.SPECFile(specfile) s.Save2HDF5(h5file) # save to hdf5 file # read ccd frames from EDF files for i in range(1, 1001, 1): efile = "edfdir/sample_%04d.edf" % i e = xu.io.edf.EDFFile(efile) e.ReadData() e.Save2HDF5(h5file, group="/frelon_%04d" % i) ``` -------------------------------- ### Inspect Lattice Objects Source: https://github.com/dkriegner/xrayutilities/blob/main/doc/source/simulations.rst Iterates through a layer stack to print the lattice parameters of each layer. ```python for l in pls: print(l.material.lattice) ``` -------------------------------- ### Sequential 2D Gridding Source: https://github.com/dkriegner/xrayutilities/blob/main/doc/source/examples.rst Perform gridding in steps when data cannot be loaded all at once, requiring a predefined data range. ```python import xrayutilities as xu # import Python package g = xu.Gridder2D(100, 101) # initialize the Gridder object g.KeepData(True) g.dataRange(1, 2, 3, 4) # (xgrd_min, xgrd_max, ygrd_min, ygrd_max) #====== load some data here ===== g(x, y, data) # call the gridder with the data griddata = g.data # the data attribute contains the so far gridded data. #====== load some more data here ===== g(x, y, data) # call the gridder with the new data griddata = g.data # the data attribute contains the combined gridded data. ``` -------------------------------- ### Fit Experimental XRR Data Source: https://github.com/dkriegner/xrayutilities/blob/main/doc/source/simulations.rst Uses the lmfit package to fit experimental X-ray reflectivity data to a defined layer model. ```python import lmfit import numpy import xrayutilities as xu # load experimental data ai, edata, eps = numpy.loadtxt('data/xrr_data.txt'), unpack=True) ai /= 2.0 # define layers # SiO2 / Ru(5) / CoFe(3) / IrMn(3) / AlOx(10) lSiO2 = xu.simpack.Layer(xu.materials.SiO2, numpy.inf, roughness=2.5) lRu = xu.simpack.Layer(xu.materials.Ru, 47, roughness=2.8) rho_cf = 0.5*8900 + 0.5*7874 mat_cf = xu.materials.Amorphous('CoFe', rho_cf) lCoFe = xu.simpack.Layer(mat_cf, 27, roughness=4.6) lIrMn = xu.simpack.Layer(xu.materials.Ir20Mn80, 21, roughness=3.0) lAl2O3 = xu.simpack.Layer(xu.materials.Al2O3, 100, roughness=5.5) # create model m = xu.simpack.SpecularReflectivityModel(lSiO2, lRu, lCoFe, lIrMn, lAl2O3, energy='CuKa1', resolution_width=0.02, sample_width=6, beam_width=0.25, background=81, I0=6.35e9) # embed model in fit code fitm = xu.simpack.FitModel(m, plot=True, verbose=True) # set some parameter limitations fitm.set_param_hint('SiO2_density', vary=False) fitm.set_param_hint('Al2O3_density', min=0.8*xu.materials.Al2O3.density, max=1.2*xu.materials.Al2O3.density) p = fitm.make_params() fitm.set_fit_limits(xmin=0.05, xmax=8.0) # perform the fit res = fitm.fit(edata, p, ai, weights=1/eps) lmfit.report_fit(res, min_correl=0.5) # export the fit result for the full data range (Note that only data between # xmin and xmax were actually optimized) numpy.savetxt( "xrrfit.dat", numpy.vstack((ai, res.eval(res.params, x=ai))).T, header="incidence angle (deg), fitted intensity (arb. u.)", ) ``` -------------------------------- ### Define Crystal Materials Source: https://github.com/dkriegner/xrayutilities/blob/main/doc/source/examples.rst Demonstrates defining cubic and hexagonal crystal structures using elastic tensors and space group lattices. ```python # define elastic parameters of the material we use a helper function which # creates the 6x6 tensor needed from the only 3 free parameters of a cubic # material. elastictensor = xu.materials.CubicElasticTensor(10.11e+10, 5.61e+10, 4.56e+10) # definition of zincblende InP: InP = xu.materials.Crystal( "InP", xu.materials.SGLattice(216, 5.8687, atoms=[In, P], pos=['4a', '4c']), elastictensor) # a hexagonal equivalent which shows how parameters change for material # definition with a different space group. Since the elasticity tensor is # optional its not specified here. InPWZ = xu.materials.Crystal( "InP(WZ)", xu.materials.SGLattice(186, 4.1423, 6.8013, atoms=[In, P], pos=[('2b', 0), ('2b', 3/8.)])) f = plt.figure() InP.show_unitcell(fig=f, subplot=121) plt.title('InP zincblende') InPWZ.show_unitcell(fig=f, subplot=122) plt.title('InP wurtzite') ``` -------------------------------- ### Calculate Bragg Reflection Strength Source: https://github.com/dkriegner/xrayutilities/blob/main/doc/source/examples.rst Calculate the structure factor for specific Bragg reflections of a material. ```python import xrayutilities as xu # defining material and experimental setup InAs = xu.materials.InAs energy= 8048 # eV # calculate the structure factor for InAs (111) (222) (333) hkllist = [[1, 1, 1], [2, 2, 2], [3, 3, 3]] for hkl in hkllist: qvec = InAs.Q(hkl) F = InAs.StructureFactor(qvec, energy) print(f"|F| = {abs(F):8.3f}") ``` -------------------------------- ### Calculate Diffraction Angles for General Geometry Source: https://github.com/dkriegner/xrayutilities/blob/main/doc/source/examples.rst Calculates goniometer angles for a custom material by defining the experiment geometry and transforming the q-vector. ```python import xrayutilities as xu import numpy as np def Pnma(a, b, c): # create orthorhombic unit cell with space-group 62, # here for simplicity without base l = xu.materials.SGLattice(62, a, b, c) return l latticeConstants=[5.600, 7.706, 5.3995] SmFeO3 = xu.materials.Crystal("SmFeO3", Pnma(*latticeConstants)) # 2S+2D goniometer qconv=xu.QConversion(('x+', 'z+'), ('z+', 'x+'), (0, 1, 0)) # [1,1,0] surface normal hxrd = xu.Experiment(SmFeO3.Q(0, 0, 1), SmFeO3.Q(1, 1, 0), qconv=qconv) hkl=(2, 0, 0) q_material = SmFeO3.Q(hkl) q_laboratory = hxrd.Transform(q_material) # transform print(f"SmFeO3: hkl {hkl}, qvec {np.round(q_material, 5)}") print(f"Lattice plane distance: {SmFeO3.planeDistance(hkl):.4f}") ``` -------------------------------- ### Define a Graded Layer Stack Source: https://github.com/dkriegner/xrayutilities/blob/main/doc/source/simulations.rst Creates a buffer layer with a composition gradient using multiple sublayers to approximate a smooth transition. ```python buf = xu.simpack.GradedLayerStack(xu.materials.SiGe, 0.2, # xfrom Si0.8Ge0.2 0.7, # xto Si0.3Ge0.7 100, # number of sublayers 10000, # total thickness relaxation=1.0) ``` -------------------------------- ### Simulate Dynamical Diffraction Source: https://github.com/dkriegner/xrayutilities/blob/main/doc/source/simulations.rst Performs dynamical diffraction simulation using the two-beam theory. ```python resol = 0.001 # resolution in incidence angle md = xu.simpack.DynamicalModel(pls, energy=en, resolution_width=resol) Idyn = md.simulate(ai, hkl=(0, 0, 4)) ``` -------------------------------- ### Powder Diffraction Simulation Source: https://github.com/dkriegner/xrayutilities/blob/main/doc/source/simulations.rst Calculate powder diffraction patterns for mixed samples. Use the standard approach or a wrapped function for multiprocessing compatibility on Windows/macOS. ```python import numpy import xrayutilities as xu tt = numpy.arange(5, 120, 0.01) Fe_powder = xu.simpack.Powder(xu.materials.Fe, 1, crystallite_size_gauss=100e-9) Co_powder = xu.simpack.Powder(xu.materials.Co, 5, # 5 times more Co crystallite_size_gauss=200e-9) pm = xu.simpack.PowderModel(Fe_powder, Co_powder, I0=100) inte = pm.simulate(tt) pm.close() # after end-of-use ``` ```python import numpy import xrayutilities as xu from multiprocessing import freeze_support def main(): tt = numpy.arange(5, 120, 0.01) Fe_powder = xu.simpack.Powder(xu.materials.Fe, 1, crystallite_size_gauss=100e-9) Co_powder = xu.simpack.Powder(xu.materials.Co, 5, # 5 times more Co crystallite_size_gauss=200e-9) pm = xu.simpack.PowderModel(Fe_powder, Co_powder, I0=100) inte = pm.simulate(tt) pm.close() if __name__ == '__main__': freeze_support() # only required on MS Windows main() ``` -------------------------------- ### Define an amorphous material layer Source: https://github.com/dkriegner/xrayutilities/blob/main/doc/source/simulations.rst Creates a 5 nm thick metallic CoFe compound layer using mass density. ```python rho_cf = 0.5*8900 + 0.5*7874 # mass density in kg/m^3 mCoFe = xu.materials.Amorphous('CoFe', rho_cf) lCoFe = xu.simpack.Layer(mCoFe, 50) ``` -------------------------------- ### Update xrayutilities Source: https://github.com/dkriegner/xrayutilities/blob/main/README.md Commands to update the package using different package managers or source control. ```bash pip install -U xrayutilities ``` ```bash conda update xrayutilities ``` ```bash sudo apt update sudo apt install python3-xrayutilities ``` ```bash git pull ``` ```bash pip install . ``` -------------------------------- ### Simulate Kinematical Diffraction Source: https://github.com/dkriegner/xrayutilities/blob/main/doc/source/simulations.rst Performs basic kinematical diffraction simulation for a layer stack. ```python en = 9000 # eV mk = xu.simpack.KinematicalModel(pls, energy=en, resolution_width=0.0001) Ikin = mk.simulate(qz, hkl=(0, 0, 4)) ``` -------------------------------- ### Calculate Atomic Scattering Factor Components Source: https://github.com/dkriegner/xrayutilities/blob/main/doc/source/examples.rst Retrieve individual components of the atomic scattering factor for simulation inputs. ```python # f = f0(|Q|) + f1(en) + j * f2(en) import xrayutilities as xu Fe = xu.materials.elements.Fe # iron atom Q = [0, 0, 1.9] en = 10000 # energy in eV print(f"Iron (Fe): E: {en:9.1f} eV") print(f"f0: {Fe.f0(xu.math.VecNorm(Q)):8.4g}") print(f"f1: {Fe.f1(en):8.4g}") print(f"f2: {Fe.f2(en):8.4g}") ``` -------------------------------- ### Visualize Reciprocal Space Plane Source: https://github.com/dkriegner/xrayutilities/blob/main/doc/source/examples.rst Generates an interactive plot to explore available Bragg peaks in coplanar diffraction geometry for different materials. ```python import xrayutilities as xu mat = xu.materials.Crystal('GaTe', xu.materials.SGLattice(194, 4.06, 16.96, atoms=['Ga', 'Te'], pos=[('4f', 0.17), ('4f', 0.602)])) ttmax = 160 sub = xu.materials.Si hsub = xu.HXRD(sub.Q(1, 1, -2), sub.Q(1, 1, 1)) ax, h = xu.materials.show_reciprocal_space_plane(sub, hsub, ttmax=160) hxrd = xu.HXRD(mat.Q(1, 0, 0), mat.Q(0, 0, 1)) ax, h2 = xu.materials.show_reciprocal_space_plane(mat, hxrd, ax=ax) ``` -------------------------------- ### Plot Density Profile Source: https://github.com/dkriegner/xrayutilities/blob/main/doc/source/simulations.rst Generates a plot of the density profile for a given model. ```python m.densityprofile(500, plot=True) # 500 number of points ``` -------------------------------- ### Define Material via Atomic Positions Source: https://github.com/dkriegner/xrayutilities/blob/main/doc/source/examples.rst Alternative material definition using specific atomic coordinates instead of Wyckoff labels. ```python xu.config.VERBOSITY = 0 InP = xu.materials.Crystal( "InP", xu.materials.SGLattice(216, 5.8687, atoms=["In", "P"], pos=[(0,0,0), (1/4, 1/4, 1/4)])) ``` -------------------------------- ### Simulate Kinematical Multi-Beam Diffraction Source: https://github.com/dkriegner/xrayutilities/blob/main/doc/source/simulations.rst Performs multibeam kinematical diffraction simulation, restricted to (001) surfaces. ```python import xrayutilities as xu xu.config.VERBOSITY = 0 mk = xu.simpack.KinematicalMultiBeamModel(pls, energy=en, surface_hkl=(0, 0, 1), resolution_width=0.0001) Imult = mk.simulate(qz, hkl=(0, 0, 4)) ``` -------------------------------- ### Calculate angles for grazing incidence diffraction Source: https://github.com/dkriegner/xrayutilities/blob/main/doc/source/examples.rst Calculates angles for grazing incidence diffraction using the GID class. ```python >>> import xrayutilities as xu >>> gid = xu.GID(xu.materials.Si.Q(1, -1, 0), xu.materials.Si.Q(0, 0, 1)) >>> # calculate angles and print them to the screen >>> (alphai, azimuth, tt, beta) = gid.Q2Ang(xu.materials.Si.Q(2, -2, 0)) >>> print(f"azimuth, tt: {azimuth:8.3f} {tt:8.3f}") azimuth, tt: 113.651 47.302 ``` -------------------------------- ### Calculate Bragg reflection angles with HXRD Source: https://github.com/dkriegner/xrayutilities/blob/main/doc/source/examples.rst Calculates the position of Bragg reflections for a coplanar scattering geometry using the HXRD class. ```python >>> import xrayutilities as xu >>> Si = xu.materials.Si # load material from materials submodule >>> >>> # initialize experimental class with directions from experiment >>> hxrd = xu.HXRD(Si.Q(1, 1, -2), Si.Q(1, 1, 1)) >>> # calculate angles of Bragg reflections and print them to the screen >>> om, chi, phi, tt = hxrd.Q2Ang(Si.Q(1, 1, 1)) >>> print("Si (111)") Si (111) >>> print(f"om, tt: {om:8.3f} {tt:8.3f}") om, tt: 14.221 28.442 >>> om, chi, phi, tt = hxrd.Q2Ang(Si.Q(2, 2, 4)) >>> print("Si (224)") Si (224) >>> print(f"om, tt: {om:8.3f} {tt:8.3f}") om, tt: 63.485 88.028 ``` -------------------------------- ### Convert powder scans to reciprocal space Source: https://github.com/dkriegner/xrayutilities/blob/main/doc/source/examples.rst Converts powder diffraction scan data from angular to reciprocal space using the PowderExperiment class. ```python import xrayutilities as xu import numpy energy = 'CuKa12' # creating powder experiment xup = xu.PowderExperiment(en=energy) theta = numpy.arange(0, 70, 0.01) q = xup.Ang2Q(theta) ``` -------------------------------- ### Fit Area Detector with Reference Material Source: https://github.com/dkriegner/xrayutilities/blob/main/doc/source/examples.rst Extends detector fitting by incorporating scans of known reference materials to improve sensitivity to the outer angle offset. ```python import xrayutilities as xu import numpy as np # define the detector det = xu.detectors.AreaDetector('z-', 'y+', cch1=140, cch2=1000, Nch1=516, Nch2=516, pwidth1=4.5e-5, pwidth2=4.5e-5, distance=1000., detrot=0, tiltazimuth=0, tilt=0) # define the fitting object for symmetric coplanar diffraction # this requires a list of scans and the hkl of the reflection fit = xu.fitting.FitAreaDetectorHKL(det, [], [0, 0, 2], 1.54) # run the fit fit.fit() # print the results fit.print_results() ``` -------------------------------- ### Convert angular data to reciprocal space and plot Source: https://github.com/dkriegner/xrayutilities/blob/main/doc/source/examples.rst Converts angular coordinates to reciprocal space vectors and grids the intensity data for visualization. ```python Si = xu.materials.Si hxrd = xu.HXRD(Si.Q(1, 1, 0), Si.Q(0, 0, 1)) qx, qy, qz = hxrd.Ang2Q(om, tt) gridder = xu.Gridder2D(200, 600) gridder(qy, qz, psd) INT = xu.maplog(gridder.data.transpose(), 6, 0) # plot the intensity as contour plot plt.figure() cf = plt.contourf(gridder.xaxis, gridder.yaxis, INT, 100, extend='min') plt.xlabel(r'$Q_{[110]}$ ($\mathrm{\AA^{-1}}$)') plt.ylabel(r'$Q_{[001]}$ ($\mathrm{\AA^{-1}}$)') cb = plt.colorbar(cf) cb.set_label(r"$\log($Int$)$ (cps)") plt.tight_layout() ``` -------------------------------- ### Extract and plot line cuts from reciprocal space data Source: https://github.com/dkriegner/xrayutilities/blob/main/doc/source/examples.rst Performs radial scans with integration along different directions to mitigate beam footprint broadening. ```python # line cut with integration along 2theta to remove beam footprint broadening qzc, qzint, cmask = xu.analysis.get_radial_scan([qy, qz], psd, [0, 4.5], 1001, 0.155, intdir='2theta') # line cut with integration along omega qzc_om, qzint_om, cmask_om = xu.analysis.get_radial_scan([qy, qz], psd, [0, 4.5], 1001, 0.155, intdir='omega') plt.figure() plt.semilogy(qzc, qzint, label='Int-dir 2Theta') plt.semilogy(qzc_om, qzint_om, label='Int-dir Omega') plt.xlabel(r'scattering angle (deg)') plt.ylabel(r'intensity (arb. u.)') plt.legend() plt.tight_layout() ``` -------------------------------- ### Calculate Energy Dependence of Structure Factor Source: https://github.com/dkriegner/xrayutilities/blob/main/doc/source/examples.rst Determine how the structure factor changes across a range of energies. ```python import matplotlib.pyplot as plt energy= numpy.linspace(500, 20000, 5000) # 500 - 20000 eV F = InAs.StructureFactorForEnergy(InAs.Q(1, 1, 1), energy) plt.figure(); plt.clf() plt.plot(energy, F.real, '-k', label='Re(F)') plt.plot(energy, F.imag, '-r', label='Imag(F)') plt.xlabel("Energy (eV)"); plt.ylabel("F"); plt.legend() ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.