An initial attempt to make a Python package for X-ray fluorescence (XRF) and differential phase contrast (DPC) analysis. It is thin but will grow.
- Data Correction: Deadtime correction and i0 normalization
- Energy Calibration: Flexible energy axis calibration
- Peak Detection: Automated scatter and XRF peak detection
- Physics-Based Identification: XRF line identification using excitation physics
- Spatial Mapping: Element distribution visualization
- DPC Analysis: Beam deflection calculations
git clone https://github.com/yourusername/xrf-analysis.git
cd xrf-analysis
pip install -e .- Python >= 3.8
- numpy >= 1.20.0
- scipy >= 1.7.0
- matplotlib >= 3.3.0
- h5py >= 3.0.0
- xraylib >= 4.0.0
import xrf_analysis as xrf
# Initialize XRF database
xrf.initialize_combined_xrf_database()
# Load and correct data
results = xrf.correct_xrf_data('your_file.h5')
results = xrf.apply_energy_calibration(results, eV_per_channel=10)
# Detect peaks
detection_results = xrf.detect_and_identify_xrf_peaks(results)
# Visualize
xrf.plot_peak_detection_results(detection_results)
xrf.plot_element_distribution(results, 'Fe', 'Ka')xrf_analysis/
├── core/
│ ├── physics.py # XRF physics calculations
│ ├── database.py # XRF line database
│ ├── corrections.py # Data corrections
│ └── peak_detection.py # Peak detection algorithms
├── visualization/
│ ├── spectra.py # Spectrum plotting
│ ├── spatial.py # Spatial distribution plots (single + batch)
│ └── trajectory.py # Stage trajectory diagnostics
└── dpc/
└── analysis.py # DPC calculations
# Load HDF5 file with deadtime and i0 correction
results = xrf.correct_xrf_data('data.h5')
# Apply energy calibration
results = xrf.apply_energy_calibration(
results,
eV_per_channel=10,
energy_offset=0
)# Plot integrated and maximum envelope spectra
xrf.plot_spectrum_with_energy(results)# Detect XRF peaks with scatter peak exclusion
detection_results = xrf.detect_and_identify_xrf_peaks(
results,
thresholds=[10, 50, 10], # [height, distance_eV, prominence]
tolerance_keV=0.060, # 60 eV matching tolerance
detect_scatter=True # Exclude elastic/Compton peaks
)
# Visualize detection results
xrf.plot_peak_detection_results(detection_results)Single element — one call, one figure:
intensities = xrf.plot_element_distribution(
results,
element_name='Fe',
line_family='Ka',
integration_width_keV=0.15,
sensor_sum=True,
scale='log',
)Use plot_element_distribution_tripcolor for the same result rendered as a
filled Delaunay triangulation (gap-free surface) rather than a scatter overlay.
Multiple elements — pass a {element: line_family} dict to get a
multi-panel subplot grid in one call:
intensities = xrf.plot_element_distributions(
results,
elements={
'Fe': 'Ka',
'Ca': 'Ka',
'Zn': 'Ka',
'U': 'Ma',
'elastic': '', # line_family ignored for scatter peaks
'compton': '',
},
scale='sqrt',
ncols=3,
percentile_lo=1.0,
percentile_hi=99.0,
cmap='hot',
)
# Returns dict[str, np.ndarray] of per-pixel intensities for downstream useSupported line families: Ka, Kb, La, Lb, Lg, Ma, Mb.
Three functions in xrf_analysis.visualization.trajectory help diagnose scan
quality before or after an analysis.
Acquisition path — draw the scan path coloured by acquisition order:
xrf.plot_scan_trajectory(results)
# For dense scans, subsample to speed up rendering:
xrf.plot_scan_trajectory(results, subsample=4)Encoder jitter — histogram step sizes and flag anomalous jumps:
jitter = xrf.analyze_encoder_jitter(results, n_sigma=3.0)
# Returns {'dx': ..., 'dy': ..., 'outlier_indices': ...}Missed positions — identify grid cells that were never visited:
missed = xrf.find_missed_positions(results, tol_factor=0.4)
# Returns {'expected': ..., 'visited': ..., 'missed': ..., 'n_missed': int}
print(f"{missed['n_missed']} positions unvisited")detection_results = xrf.detect_and_identify_xrf_peaks(
results,
thresholds=[20, 100, 15], # Higher thresholds for cleaner data
smooth_window=7, # More smoothing
bkg_method='polynomial', # Polynomial background
bkg_radius=100 # Larger background filter
)# For samples measured at 45° to the beam
xrf.plot_element_distribution(
results,
'Cu', 'Ka',
correct_45deg=True,
expand_x=True # Expand to sample surface coordinates
)from xrf_analysis.dpc import calculate_dpc_deflections, plot_dpc_results
# Calculate beam deflections
dpc_results = calculate_dpc_deflections(
thor_x, thor_y, thor_Tot, i0,
Lx=10, Ly=10 # Detector dimensions in mm
)
# Visualize DPC results
plot_dpc_results(abs_x, abs_y, dpc_results['beam_x'],
dpc_results['beam_y'], thor_Tot)Load and correct XRF data from HDF5 file.
Apply energy calibration to create energy axis.
Pre-calculate XRF line database (call once at startup).
Detect and identify XRF peaks with physics-based filtering.
Plot integrated and maximum-envelope spectra with energy axis.
Visualize peak detection results with element annotations.
Single-element scatter map. Key kwargs: scale ('linear'/'log'/'sqrt'),
integration_width_keV, sensor_sum, correct_45deg.
Same as above but rendered with Delaunay triangulation (gap-free surface).
Same kwargs as plot_element_distribution.
Batch multi-panel map. elements is a dict[str, str] mapping element
symbol to line family, e.g. {"Fe": "Ka", "U": "Ma", "compton": ""}.
Key kwargs: scale, ncols, percentile_lo, percentile_hi, cmap.
Returns dict[str, np.ndarray] of per-pixel intensities.
Draw the acquisition path as a viridis-coloured line. Use subsample=N
to plot every Nth point for dense scans.
Histogram Δx, Δy, and step distance; flag outlier steps.
Returns {'dx', 'dy', 'outlier_indices'}.
Identify expected grid cells with no measured point nearby.
Returns {'expected', 'visited', 'missed', 'n_missed'}.
MIT License - see LICENSE file for details.
Contributions welcome! Please open an issue or submit a pull request.
If you use this package in your research, please cite:
https://github.com/AustralianSynchrotron