### Start API Documentation Server Source: https://github.com/dkriegner/xrayutilities/blob/main/README.md After installation, run 'pydoc -p PORT' to start a local web server for browsing the API documentation. Access it via any web browser. ```bash pydoc -p PORT ``` -------------------------------- ### Install xrayutilities from source Source: https://github.com/dkriegner/xrayutilities/blob/main/README.md Install xrayutilities from its source code using pip. ```bash pip install . ``` -------------------------------- ### Install xrayutilities from source with auto OpenMP Source: https://github.com/dkriegner/xrayutilities/blob/main/README.md Install xrayutilities from source, using OpenMP if available. ```bash pip install . --config-settings=setup-args="-Duse_openmp=auto" ``` -------------------------------- ### Identify Windows site-packages path Source: https://github.com/dkriegner/xrayutilities/blob/main/doc/source/index.rst Example of the directory structure for site-packages on Windows systems. ```bash /Lib/site-packages ``` -------------------------------- ### Install xrayutilities with a Specific Prefix Source: https://github.com/dkriegner/xrayutilities/blob/main/README.md Use this command to install the xrayutilities package to a specific directory. Replace '' with your desired installation path. ```bash pip install --prefix= . ``` -------------------------------- ### Install xrayutilities with pip Source: https://github.com/dkriegner/xrayutilities/blob/main/README.md Install the xrayutilities Python package using pip. ```bash pip install xrayutilities ``` -------------------------------- ### Install xrayutilities via pip Source: https://github.com/dkriegner/xrayutilities/blob/main/doc/source/index.rst Commands to install the package from the source directory using the meson-python build backend. ```bash >pip install . ``` ```bash >pip install --prefix=INSTALLPATH . ``` -------------------------------- ### Install xrayutilities from source without OpenMP Source: https://github.com/dkriegner/xrayutilities/blob/main/README.md Install xrayutilities from source, explicitly disabling OpenMP support. ```bash pip install . --config-settings=setup-args="-Duse_openmp=disabled" ``` -------------------------------- ### Simulate AlGaAs Superlattice Reflectivity and Diffraction Source: https://github.com/dkriegner/xrayutilities/blob/main/doc/source/index.rst This example demonstrates building an AlGaAs superlattice structure and simulating its X-ray reflectivity and dynamical diffraction curves. It requires defining layers, stack properties, and then initializing the respective simulation models. ```python import xrayutilities as xu from numpy import linspace from xrayutilities.simpack import Layer, PseudomorphicStack001, SpecularReflectivityModel, DynamicalModel from xrayutilities.materials import GaAs, AlGaAs from xrayutilities.units import inf # Build the pseudomorphic sample stack using the elastic parameters sub = Layer(GaAs, inf) lay1 = Layer(AlGaAs(0.25), 75, relaxation=0.0) lay2 = Layer(AlGaAs(0.75), 25, relaxation=0.0) pls = PseudomorphicStack001('pseudo', sub+10*(lay1+lay2)) # simulate reflectivity m = 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 = DynamicalModel(pls) Idyn = md.simulate(alphai, hkl=(0, 0, 4)) ``` -------------------------------- ### Determine xrayutilities Installation Location Source: https://github.com/dkriegner/xrayutilities/blob/main/README.md Run this Python command to find the installation path of the xrayutilities package. This is useful for verifying the installation or for manual updates. ```python python -c "import xrayutilities as xu; print xu.__file__" ``` -------------------------------- ### Configure PYTHONPATH on Unix/Linux Source: https://github.com/dkriegner/xrayutilities/blob/main/doc/source/index.rst Command to append the installation directory to the PYTHONPATH environment variable for non-standard locations. ```bash >export PYTHONPATH=$PYTHONPATH:/lib64/python2.7/site-packages ``` -------------------------------- ### Read Spec File and Plot Reciprocal Space Map Source: https://github.com/dkriegner/xrayutilities/blob/main/doc/source/index.rst This example demonstrates reading scan data from a SPEC file using xrayutilities and plotting the result as a reciprocal space map with matplotlib. It showcases basic usage for angle calculation and data visualization. ```python import xrayutilities as xu import matplotlib.pyplot as plt # Load data from a SPEC file scan = xu.read_spec("my_scan.dat") # Convert to reciprocal space coordinates # (Assuming a predefined experimental setup, e.g., four-circle) # For custom geometries, xu.q2ang_fit might be needed. # The exact conversion depends on the experimental setup used when recording the scan. # This is a placeholder and would need actual experimental setup details. # For demonstration, let's assume we have q_x, q_y, intensity data # In a real scenario, you'd use scan.get_q_map() or similar after proper setup. # Placeholder for actual data extraction and conversion # Example: q_map = scan.get_q_map(experiment_setup) # For this example, we'll simulate some data for plotting # Simulate reciprocal space data for plotting # In a real case, this would come from scan.get_q_map() or similar q_x = [1, 2, 3, 4, 5] q_y = [5, 4, 3, 2, 1] intensity = [10, 20, 30, 20, 10] # Plotting the reciprocal space map plt.figure() plt.scatter(q_x, q_y, c=intensity, cmap='viridis') plt.colorbar(label='Intensity') plt.xlabel('Qx (arbitrary units)') plt.ylabel('Qy (arbitrary units)') plt.title('Reciprocal Space Map') plt.grid(True) plt.show() ``` -------------------------------- ### Get arbitrary line cut from gridded data Source: https://context7.com/dkriegner/xrayutilities/llms.txt Extracts an arbitrary line cut from gridded reciprocal space maps. Requires start and end points, and integration width. ```python line_data = xu.analysis.get_arbitrary_line( [qy, qz], psd, (qy_start, qz_start), (qy_end, qz_end), npoints=500, intwidth=0.05 ) ``` -------------------------------- ### Initialize a Specular Reflectivity Model Source: https://github.com/dkriegner/xrayutilities/blob/main/doc/source/simulations.rst Sets up a reflectivity model with common parameters like beam flux, background, and resolution width. ```python m = xu.simpack.SpecularReflectivityModel(layerstack, I0=1e6, background=1, resolution_width=0.001) ``` -------------------------------- ### Run all unit tests Source: https://github.com/dkriegner/xrayutilities/blob/main/tests/README.txt Execute the full test suite from the package root directory. ```bash pytest ``` ```bash python -m unittest discover ``` -------------------------------- ### Create and Analyze Alloy Materials Source: https://context7.com/dkriegner/xrayutilities/llms.txt Demonstrates creating alloy materials (SiGe, AlGaAs, InGaAs) with composition-dependent lattice parameters using Vegard's law. It also shows how to calculate Q vectors for alloys and use the RelaxationTriangle for composition analysis. Requires importing xrayutilities. ```python import xrayutilities as xu # Create SiGe alloy with x_Ge = 0.3 SiGe = xu.materials.SiGe(0.3) print(f"SiGe(0.3) lattice constant: a = {SiGe.a:.5f} Angstrom") # Get Q vector for alloy q_004 = SiGe.Q(0, 0, 4) # AlGaAs alloy AlGaAs = xu.materials.AlGaAs(0.3) # 30% Al # InGaAs alloy InGaAs = xu.materials.InGaAs(0.2) # 20% In # Calculate composition from measured lattice parameter # Using relaxation triangle analysis Si = xu.materials.Si hxrd = xu.HXRD(Si.Q(1, 1, 0), Si.Q(0, 0, 1)) triangle = SiGe.RelaxationTriangle([0, 0, 4], Si, hxrd) ``` -------------------------------- ### Initialize Q-space conversion Source: https://context7.com/dkriegner/xrayutilities/llms.txt Set up Q-space conversion for a specific detector geometry and beam energy. Requires sample axes, detector axis, primary beam direction, and beam energy. ```python qconv = xu.QConversion( ['x+', 'y+', 'z-'], # sample axes 'x+', # detector axis [0, 1, 0], # primary beam direction en=8048 # energy in eV ) print(qconv) # Point detector conversion omega, chi, phi, twotheta = 20.0, 0.0, 0.0, 40.0 qx, qy, qz = qconv(omega, chi, phi, twotheta) print(f"Q = ({qx:.4f}, {qy:.4f}, {qz:.4f})") ``` -------------------------------- ### Initialize and convert with linear detector Source: https://context7.com/dkriegner/xrayutilities/llms.txt Configure and use a linear detector for Q-space conversion. Requires detector axis, channel count, number of channels, distance, and pixel width. ```python # Initialize linear detector qconv.init_linear('z+', cch=256, Nchannel=512, distance=500, pixelwidth=0.055) # Convert with linear detector qx, qy, qz = qconv.linear(omega, chi, phi, twotheta) ``` -------------------------------- ### Get 3D intensity distribution Source: https://context7.com/dkriegner/xrayutilities/llms.txt Access the 3D intensity data from a gridded dataset. This is a direct attribute access. ```python intensity_3d = gridder3d.data ``` -------------------------------- ### Add package to PYTHONPATH Source: https://github.com/dkriegner/xrayutilities/blob/main/README.md Add the directory where xrayutilities is installed to the PYTHONPATH environment variable to make it discoverable by the Python interpreter. ```bash export PYTHONPATH=$PYTHONPATH:/path/to/xrayutilities/package ``` -------------------------------- ### Set up kinematical diffraction model Source: https://context7.com/dkriegner/xrayutilities/llms.txt Sets up a kinematical diffraction model for simulating X-ray diffraction from a layer stack. Requires the layer stack and simulation parameters. ```python model = xu.simpack.KinematicalModel(pls, energy=8500, resolution_width=0.0004) ``` -------------------------------- ### Get omega scan from gridded data Source: https://context7.com/dkriegner/xrayutilities/llms.txt Extracts an omega scan (rocking curve) from gridded reciprocal space maps. Requires gridded data and integration parameters. ```python omega_cut, intensity, mask = xu.analysis.get_omega_scan( [qy, qz], psd, (0, 4.628), # center position 501, # number of points 0.1 # integration width ) ``` -------------------------------- ### Get radial scan from gridded data Source: https://context7.com/dkriegner/xrayutilities/llms.txt Extracts a radial scan (line cut) from gridded reciprocal space maps. Requires gridded data and integration parameters. ```python qz_center, intensity_cut, mask = xu.analysis.get_radial_scan( [qy, qz], psd, (0, 4.5), # center position (qy, qz) 1001, # number of points 0.155, # integration width intdir='2theta' # integration direction ) ``` -------------------------------- ### Create and Fit Specular Reflectivity Model Source: https://github.com/dkriegner/xrayutilities/blob/main/doc/source/simulations.rst Builds a specular reflectivity model, embeds it in a fit code, sets parameter limitations, and performs the fit. Exports the fit result to a file. ```python 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.)", ) ``` -------------------------------- ### 2D Gridder for Reciprocal Space Map Visualization Source: https://github.com/dkriegner/xrayutilities/blob/main/doc/source/examples.rst Utilize Gridder2D with matplotlib for visualizing reciprocal space maps. This example converts experimental angles to Q-space, grids the intensity data, and plots it as a contour map. ```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() ``` -------------------------------- ### Initialize and convert with area detector Source: https://context7.com/dkriegner/xrayutilities/llms.txt Set up and perform Q-space conversion using an area detector. Requires detector axes, channel counts, number of channels, distance, pixel widths, and optionally a region of interest (ROI). ```python # Initialize area detector qconv.init_area('z+', 'x+', cch1=256, cch2=256, Nch1=512, Nch2=512, distance=500, pwidth1=0.055, pwidth2=0.055) # Convert with area detector qx, qy, qz = qconv.area(omega, chi, phi, twotheta, roi=[100, 400, 100, 400]) ``` -------------------------------- ### Configure and Use HXRD Experiment Source: https://context7.com/dkriegner/xrayutilities/llms.txt Illustrates setting up a high-angle X-ray diffraction (HXRD) experiment with sample orientation and energy. It shows how to calculate diffraction angles for reflections and convert measured angles to Q-space and HKL coordinates. Requires importing xrayutilities and numpy. ```python import xrayutilities as xu import numpy as np Si = xu.materials.Si # Initialize HXRD experiment with crystal orientation # idir: inplane reference direction (along beam at zero angles) # ndir: surface normal direction hxrd = xu.HXRD(Si.Q(1, 1, -2), Si.Q(1, 1, 1), en=8048) # 8048 eV # Calculate diffraction angles for (111) reflection # Returns [omega, chi, phi, twotheta] angles = hxrd.Q2Ang(Si.Q(1, 1, 1)) print(f"Si(111): omega={angles[0]:.4f}, phi={angles[2]:.4f}, 2theta={angles[3]:.4f}") # Calculate angles for asymmetric reflection angles_224 = hxrd.Q2Ang(Si.Q(2, 2, 4)) print(f"Si(224): omega={angles_224[0]:.4f}, 2theta={angles_224[3]:.4f}") # Convert measured angles to Q-space (point detector) omega = np.linspace(30, 35, 100) twotheta = 2 * omega # symmetric scan qx, qy, qz = hxrd.Ang2Q(omega, twotheta) # Convert to HKL coordinates h, k, l = hxrd.Ang2HKL(omega, twotheta, mat=Si) ``` -------------------------------- ### Configure Grazing Incidence Small-Angle Scattering (GISAXS) Source: https://context7.com/dkriegner/xrayutilities/llms.txt Set up a GISAXS experiment. Converts angles (incidence, 2theta, beta) to Q-space coordinates. ```python # GISAXS experiment gisaxs = xu.GISAXS(Si.Q(1, 0, 0), Si.Q(0, 0, 1), en=10000) # Convert angles to Q-space alpha_i = 0.3 # incidence angle twotheta = np.linspace(-2, 2, 100) beta = np.linspace(0, 5, 100) qx, qy, qz = gisaxs.Ang2Q(alpha_i, twotheta, beta) ``` -------------------------------- ### Import Crystal Structure from CIF File Source: https://context7.com/dkriegner/xrayutilities/llms.txt Shows how to load crystal structure data from a CIF file, print lattice parameters, and calculate a powder diffraction pattern. The material can also be exported back to a CIF file. Requires importing xrayutilities and os. ```python import xrayutilities as xu import os # Create material from CIF file Calcite = xu.materials.Crystal.fromCIF("Calcite.cif") print(Calcite) # Access lattice parameters print(f"a = {Calcite.lattice.a:.4f} Angstrom") print(f"c = {Calcite.lattice.c:.4f} Angstrom") # Calculate powder diffraction pattern powder = xu.simpack.PowderDiffraction(Calcite) print(powder) # Export material back to CIF Calcite.toCIF("Calcite_export.cif") ``` -------------------------------- ### Iterate and Print Lattice Parameters Source: https://github.com/dkriegner/xrayutilities/blob/main/doc/source/simulations.rst Demonstrates how to iterate through a pseudomorphic stack and print the lattice parameters of each material. Useful for verifying strain conditions. ```python for l in pls: print(l.material.lattice) ``` -------------------------------- ### Configure Grazing Incidence Diffraction (GID) Source: https://context7.com/dkriegner/xrayutilities/llms.txt Set up a GID experiment using material properties and beam energy. Calculates angles for in-plane reflections. ```python import xrayutilities as xu import numpy as np Si = xu.materials.Si # Grazing Incidence Diffraction gid = xu.GID(Si.Q(1, 1, 0), Si.Q(0, 0, 1), en=10000) # Calculate angles for inplane reflection angles = gid.Q2Ang(Si.Q(2, 2, 0)) print(f"GID (220): alpha_i={angles[0]:.4f}, azimuth={angles[1]:.4f}, " f"2theta={angles[2]:.4f}, beta={angles[3]:.4f}") ``` -------------------------------- ### Simulate Dynamical Reflectivity Source: https://context7.com/dkriegner/xrayutilities/llms.txt Simulates dynamical reflectivity using the DynamicalReflectivityModel. Requires a stack, energy, and polarization. The simulate method takes alpha as input. ```python model_dyn = xu.simpack.DynamicalReflectivityModel( stack, energy=energy, polarization='S' ) R, T = model_dyn.simulate(alpha) # reflectivity and transmittance ``` -------------------------------- ### Create a Pseudomorphic Superlattice Stack Source: https://github.com/dkriegner/xrayutilities/blob/main/doc/source/simulations.rst Builds a pseudomorphic superlattice stack for (001) surfaces, automatically adapting lattice parameters. Supports partial/full relaxation. ```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)) ``` -------------------------------- ### Define and Use Crystal Materials Source: https://context7.com/dkriegner/xrayutilities/llms.txt Demonstrates defining predefined and custom crystal materials, calculating structure factors, and visualizing unit cells. Requires importing the xrayutilities library. ```python import xrayutilities as xu # Use predefined materials Si = xu.materials.Si Ge = xu.materials.Ge GaAs = xu.materials.GaAs # Define custom material using space group and Wyckoff positions In = xu.materials.elements.In P = xu.materials.elements.P InP = xu.materials.Crystal( "InP", xu.materials.SGLattice(216, 5.8687, atoms=[In, P], pos=["4a", "4c"]), xu.materials.CubicElasticTensor(10.11e10, 5.61e10, 4.56e10), thetaDebye=425 ) # Print material information print(InP) # Output: Crystal InP with lattice parameters a=5.8687 # Get reciprocal space vector for (004) reflection q_004 = Si.Q(0, 0, 4) print(f"Q(004) = {q_004}") # Calculate structure factor F = Si.StructureFactor(Si.Q(1, 1, 1), en=8048) # energy in eV print(f"|F(111)| = {abs(F):.3f}") # Visualize unit cell InP.show_unitcell() ``` -------------------------------- ### Create pseudomorphic layer stack Source: https://context7.com/dkriegner/xrayutilities/llms.txt Defines and creates a pseudomorphic layer stack for simulation. Requires substrate and layer materials and thickness. ```python sub = xu.simpack.Layer(xu.materials.Si, np.inf) layer = xu.simpack.Layer(xu.materials.SiGe(0.6), 145.87, relaxation=0.5) pls = xu.simpack.PseudomorphicStack001("SiGe/Si", sub, layer) ``` -------------------------------- ### Determine Linear Detector Parameters Source: https://github.com/dkriegner/xrayutilities/blob/main/doc/source/examples.rst Script to determine essential parameters for linear detector initialization, including pixel width, center channel, and optional detector tilt, by scanning through the primary beam. ```python import xrayutilities as xu import xrayutilities.examples as xue # load data # data = xu.load_data('path/to/your/data') # determine detector parameters # parameters = xue.xu_linear_detector_parameters(data) # initialize detector # detector = xu.LinearDetector(parameters) ``` -------------------------------- ### Configure xrayutilities Settings Source: https://github.com/dkriegner/xrayutilities/blob/main/doc/source/examples.rst Customize xrayutilities behavior by setting parameters like verbosity, default wavelength, and the number of threads in a user-specific configuration file. ```python # 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 ``` -------------------------------- ### Create a Silicon Layer Source: https://github.com/dkriegner/xrayutilities/blob/main/doc/source/simulations.rst Creates a single layer of silicon with a specified thickness. This is a basic building block for layer stacks. ```python import xrayutilities as xu lay = xu.simpack.Layer(xu.materials.Si, 200) ``` -------------------------------- ### Create a Superlattice Stack Source: https://github.com/dkriegner/xrayutilities/blob/main/doc/source/simulations.rst Constructs a superlattice stack by repeating a unit of multiple layers. Uses multiplication for repetition. ```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)) ``` -------------------------------- ### Calculate Angles with Grazing Incidence Diffraction (GID) Source: https://github.com/dkriegner/xrayutilities/blob/main/doc/source/examples.rst Initializes the GID class and calculates angles for a given Q vector. This is useful for grazing incidence diffraction experiments. ```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}") ``` -------------------------------- ### Run individual unit tests Source: https://github.com/dkriegner/xrayutilities/blob/main/tests/README.txt Execute a specific test file by providing the filename as an argument. ```bash python -m unitest ``` -------------------------------- ### Fitting InMnAs Epilayer Data Source: https://github.com/dkriegner/xrayutilities/blob/main/doc/source/simulations.rst Demonstrates setting up a pseudomorphic layer stack, configuring a dynamical model, and performing a fit using lmfit. ```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) # 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 ``` -------------------------------- ### Build a Layer Stack Source: https://github.com/dkriegner/xrayutilities/blob/main/doc/source/simulations.rst Combines multiple layers, including a substrate, into a LayerStack object. Supports stacking by summation and infinite substrate thickness. ```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) ``` -------------------------------- ### Define epitaxial layer stack for dynamical diffraction Source: https://context7.com/dkriegner/xrayutilities/llms.txt Defines an epitaxial layer stack for dynamical diffraction simulation. Requires substrate, buffer, and layer materials and thicknesses. ```python sub = xu.simpack.Layer(xu.materials.Si, np.inf) buffer = xu.simpack.Layer(xu.materials.SiGe(0.2), 500, relaxation=0.0) layer = xu.simpack.Layer(xu.materials.SiGe(0.4), 100, relaxation=0.0) stack = xu.simpack.PseudomorphicStack001("multilayer", sub, buffer, layer) ``` -------------------------------- ### Flexible Q-Space Conversion Source: https://context7.com/dkriegner/xrayutilities/llms.txt Introduces the QConversion class for flexible angular to Q-space conversion, supporting arbitrary goniometer configurations with multiple sample and detector circles. Requires importing xrayutilities and numpy. ```python import xrayutilities as xu import numpy as np # Define custom 4-circle goniometer ``` -------------------------------- ### Determine Area Detector Parameters (Variant 1) Source: https://github.com/dkriegner/xrayutilities/blob/main/doc/source/examples.rst Calculate initialization parameters for an area detector using scans through the primary beam. This includes center channels, pixel width, tilt, and rotation. The outer angle offset is determined but applied separately. ```python import xrayutilities as xu import xrayutilities.examples as xue # load data # data = xu.load_data('path/to/your/data') # determine detector parameters # parameters = xue.xu_ccd_parameter(data) # initialize detector # detector = xu.AreaDetector(parameters) ``` -------------------------------- ### Create Powder Diffraction Model Source: https://context7.com/dkriegner/xrayutilities/llms.txt Defines a crystal structure and creates a powder diffraction model. Requires material elements and lattice parameters. Fundamental parameters can be configured via a dictionary. ```python import xrayutilities as xu import numpy as np # Define material using space group La = xu.materials.elements.La B = xu.materials.elements.B LaB6 = xu.materials.Crystal( "LaB6", xu.materials.SGLattice( 221, 4.15692, atoms=[La, B], pos=["1a", ("6f", 0.19750)], b=[0.05, 0.15] # Debye-Waller factors ) ) # Create powder sample powder = xu.simpack.Powder( LaB6, 1, crystallite_size_gauss=1e6, crystallite_size_lor=0.5e-6, strain_gauss=0, strain_lor=0 ) # Fundamental parameters settings settings = { 'global': { 'diffractometer_radius': 0.337, 'equatorial_divergence_deg': 0.40, }, 'emission': {'emiss_intensities': (1.0, 0.45)}, # K-alpha1, K-alpha2 'displacement': { 'specimen_displacement': -3.8e-5, 'zero_error_deg': 0.0 } } # Create powder model pm = xu.simpack.PowderModel(LaB6_powder, I0=1e6, fpsettings=settings) # Simulate pattern twotheta = np.linspace(20, 140, 5000) intensity = pm.simulate(twotheta) # Fit to experimental data params = pm.create_fitparameters() params['primary_beam_intensity'].set(vary=True) params['displacement_specimen_displacement'].set(vary=True, min=-1e-4, max=1e-4) result = pm.fit(params, tt_exp, int_exp, std=sigma_exp) ``` -------------------------------- ### FuzzyGridder for smoother results Source: https://context7.com/dkriegner/xrayutilities/llms.txt Initialize and apply FuzzyGridder3D for smoothing gridded data. Requires grid dimensions and data to be provided. ```python fuzzy_gridder = xu.FuzzyGridder3D(100, 100, 100) fuzzy_gridder(qx, qy, qz, intensity) ``` -------------------------------- ### Clone xrayutilities Git Repository Source: https://github.com/dkriegner/xrayutilities/blob/main/README.md Use this command to clone the xrayutilities source code from its GitHub repository. This is the first step to obtaining the project's source files. ```bash git clone https://github.com/dkriegner/xrayutilities.git ``` -------------------------------- ### Plot Density Profile from Reflectivity Model Source: https://github.com/dkriegner/xrayutilities/blob/main/doc/source/simulations.rst Plots the density profile derived from a specular reflectivity model. Requires the model object to be built or fitted. ```python m.densityprofile(500, plot=True) # 500 number of points ``` -------------------------------- ### Add to sys.path and Import xrayutilities Source: https://github.com/dkriegner/xrayutilities/blob/main/README.md Before importing, ensure the xrayutilities package path is added to sys.path. This is typically done once at the beginning of a script. ```python sys.path.append("path to the xrayutilities package") import xrayutilities ``` -------------------------------- ### Basic 2D Gridder Initialization and Usage Source: https://github.com/dkriegner/xrayutilities/blob/main/doc/source/examples.rst Initialize a 2D Gridder for mapping data to a regular grid. Call the gridder instance with your data (x, y, data) and access the gridded data via the .data attribute. ```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. ``` -------------------------------- ### Full dynamical diffraction model simulation Source: https://context7.com/dkriegner/xrayutilities/llms.txt Simulates X-ray diffraction using the full dynamical (2-beam theory) model. Requires incidence angles and reflection indices. ```python model = xu.simpack.DynamicalModel(stack, energy=en, resolution_width=0.001) intensity = model.simulate(ai, hkl=(0, 0, 4)) ``` -------------------------------- ### Initialize 3D Gridder for area detector data Source: https://context7.com/dkriegner/xrayutilities/llms.txt Sets up a 3D Gridder to accumulate and organize data from area detector measurements in 3D reciprocal space. `KeepData(True)` allows accumulating data from multiple calls. ```python import xrayutilities as xu import numpy as np # 3D gridder for area detector data gridder3d = xu.Gridder3D(100, 100, 100) gridder3d.KeepData(True) # accumulate data from multiple calls # Process multiple frames for i, angles in enumerate(scan_positions): om, chi, phi, tt = angles qx, qy, qz = qconv.area(om, chi, phi, tt) gridder3d(qx, qy, qz, detector_data[i]) ``` -------------------------------- ### Simulate Powder Diffraction on Windows and macOS Source: https://github.com/dkriegner/xrayutilities/blob/main/doc/source/simulations.rst Encapsulates the simulation code within a main function to ensure compatibility with the multiprocessing module on Windows and macOS. ```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() ``` -------------------------------- ### Simplified dynamical diffraction model simulation Source: https://context7.com/dkriegner/xrayutilities/llms.txt Simulates X-ray diffraction using a simplified dynamical model, which is faster and provides a good approximation. Requires incidence angles and reflection indices. ```python simple_model = xu.simpack.SimpleDynamicalCoplanarModel(stack, energy=en) intensity_simple = simple_model.simulate(ai, hkl=(0, 0, 4), idxref=0) ``` -------------------------------- ### Plot simulation results Source: https://context7.com/dkriegner/xrayutilities/llms.txt Plots the simulated diffraction intensity against Qz. Requires matplotlib. ```python import matplotlib.pyplot as plt plt.semilogy(qz, intensity) plt.xlabel(r"$Q_z$ (\mathrm{\AA}^{-1})") plt.ylabel("Intensity (arb. u.)") ``` -------------------------------- ### Load Pre-defined Materials Source: https://github.com/dkriegner/xrayutilities/blob/main/doc/source/examples.rst Access built-in material definitions from the xu.materials module. ```python InP = xu.materials.InP InPWZ = xu.materials.InPWZ ``` -------------------------------- ### 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/local 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") ``` -------------------------------- ### Convert Powder Scans from Angle to Reciprocal Space Source: https://github.com/dkriegner/xrayutilities/blob/main/doc/source/examples.rst Creates a PowderExperiment object and converts angular data to reciprocal space (Q). This is useful for analyzing powder diffraction data. ```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) ``` -------------------------------- ### Transform SGLattice Settings Source: https://github.com/dkriegner/xrayutilities/blob/main/doc/source/examples.rst Convert between different origin choices or unit cell settings using transformation matrices and origin shifts. ```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 ``` -------------------------------- ### Define thin film structure for reflectivity Source: https://context7.com/dkriegner/xrayutilities/llms.txt Defines a thin film structure for X-ray reflectivity simulation. Requires substrate and film materials, thickness, and roughness. ```python STO = xu.materials.SrTiO3 CTO = xu.materials.CaTiO3 substrate = xu.simpack.Layer(STO, np.inf) film = xu.simpack.Layer(CTO, 200, roughness=5) # 20 nm with 5 A roughness stack = xu.simpack.LayerStack("CTO/STO", substrate + film) ``` -------------------------------- ### Grid irregular data onto a 2D grid Source: https://context7.com/dkriegner/xrayutilities/llms.txt Initializes a 2D Gridder object and uses it to map irregular Q-space data (qy, qz) and corresponding intensity onto a regular grid for visualization. Log scaling can be applied. ```python # Grid data onto regular 200x600 grid gridder = xu.Gridder2D(200, 600) gridder(qy, qz, psd) # Access gridded data intensity = gridder.data qy_axis = gridder.xaxis qz_axis = gridder.yaxis # Apply log scaling for visualization log_intensity = xu.maplog(intensity.T, 6, 0) # Plot with matplotlib import matplotlib.pyplot as plt plt.contourf(qy_axis, qz_axis, log_intensity, 100) plt.xlabel(r"$Q_{[110]}$ ($\\mathrm{\\AA}^{-1}$)") plt.ylabel(r"$Q_{[001]}$ ($\\mathrm{\\AA}^{-1}$)") plt.colorbar(label=r"$\\log($Int$)$") ``` -------------------------------- ### Calculate Bragg Reflection Angles with HXRD Source: https://github.com/dkriegner/xrayutilities/blob/main/doc/source/examples.rst Initializes the HXRD class with experimental directions and calculates Bragg reflection angles. The energy can be specified explicitly or defaults to CuKα1. ```python import xrayutilities as xu import numpy 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)") print(f"om, tt: {om:8.3f} {tt:8.3f}") om, chi, phi, tt = hxrd.Q2Ang(Si.Q(2, 2, 4)) print("Si (224)") print(f"om, tt: {om:8.3f} {tt:8.3f}") ``` ```python hxrd = xu.HXRD(Si.Q(1, 1, -2), Si.Q(1, 1, 1), en=10000) # energy in eV ``` -------------------------------- ### Plot dynamical diffraction results Source: https://context7.com/dkriegner/xrayutilities/llms.txt Plots the simulated diffraction intensity from both full and simplified dynamical models against the Qz axis. Requires matplotlib. ```python qz_axis = xu.simpack.get_qz(qx, ai, en) import matplotlib.pyplot as plt plt.semilogy(qz_axis, intensity, label='Full dynamical') plt.semilogy(qz_axis, intensity_simple, label='Simplified') plt.legend() ``` -------------------------------- ### Kinematical Multi-Beam Diffraction Simulation Source: https://github.com/dkriegner/xrayutilities/blob/main/doc/source/simulations.rst Employs a kinematical multi-beam diffraction model, restricted to (001) surfaces. Layer thicknesses must be multiples of the out-of-plane lattice spacing. This model is effective away from substrate peaks. ```python import xrayutilities as xu xu.config.VERBOSITY = 0 ``` ```python mk = xu.simpack.KinematicalMultiBeamModel(pls, energy=en, surface_hkl=(0, 0, 1), resolution_width=0.0001) Imult = mk.simulate(qz, hkl=(0, 0, 4)) ``` -------------------------------- ### Simulate kinematical diffraction Source: https://context7.com/dkriegner/xrayutilities/llms.txt Simulates X-ray diffraction intensity using the kinematical model. Requires Qz values and reflection indices. ```python qz = np.linspace(4.2, 5.0, 3000) intensity = model.simulate(qz, hkl=(0, 0, 4), refraction=True) ``` -------------------------------- ### Define Crystal Materials and Visualize Unit Cells Source: https://github.com/dkriegner/xrayutilities/blob/main/doc/source/examples.rst Defines crystal materials with specified space groups, lattice parameters, and atomic positions, then visualizes their unit cells. Supports different crystal structures like zincblende and wurtzite. ```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 # 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') ```