API Reference
Overview
XRayLabTool — Module
XRayLabTool - Material property calculations for X-ray interactions
This module provides functions to calculate X-ray optical properties of materials based on their chemical composition and density.
Main Functions (New API - Recommended):
calculate_xray_properties: Calculate properties for multiple chemical formulascalculate_single_material_properties: Calculate properties for a single chemical formula
Usage Examples:
# Single formula (new API)
result = calculate_single_material_properties("SiO2", [8.0, 10.0, 12.0], 2.2)
# Multiple formulas (new API) — returns Vector{XRayResult}
results = calculate_xray_properties(["SiO2", "Al2O3"], [8.0, 10.0, 12.0], [2.2, 3.95])
sio2 = results[1] # access by index (same order as input)
# Access properties
println("Molecular weight: ", result.molecular_weight)
println("Critical angle: ", result.critical_angle[1])The old function names Refrac and SubRefrac are still available for backward compatibility but are deprecated. Please use the new API names:
Refrac→calculate_xray_propertiesSubRefrac→calculate_single_material_properties
Input Parameters:
- Chemical formula(s): Case-sensitive strings (e.g., "CO" for Carbon Monoxide vs "Co" for Cobalt)
- Energy: Vector of X-ray energies in KeV (range: 0.03 - 30 KeV)
- Mass density: Density in g/cm³ (single value or vector matching formula count)
Output Properties: The functions return XRayResult struct(s) containing:
- Chemical formula (
formula) - Molecular weight in g/mol (
molecular_weight) - Number of electrons per molecule (
number_of_electrons) - Mass density in g/cm³ (
mass_density) - Electron density in 1/ų (
electron_density) - X-ray energy in KeV (
energy) - X-ray wavelength in Å (
wavelength) - Dispersion coefficient (
dispersion) - Absorption coefficient (
absorption) - Real part of atomic scattering factor (
f1) - Imaginary part of atomic scattering factor (
f2) - Critical angle in degrees (
critical_angle) - Attenuation length in cm (
attenuation_length) - Real part of scattering length density in Å⁻² (
real_sld) - Imaginary part of SLD in Å⁻² (
imag_sld)
Public API
Main functions
XRayLabTool.calculate_xray_properties — Function
calculate_xray_properties(formulaList, energy, massDensityList) -> Vector{XRayResult}Calculate X-ray optical properties for multiple chemical formulas (vector interface).
Arguments
formulaList::Vector{String}: List of chemical formulasenergy::Vector{Float64}: X-ray energies in KeV (0.03 - 30 KeV)massDensityList::Vector{Float64}: Mass densities in g/cm³
Returns
Vector{XRayResult}: Results in same order as input formulas
Examples
formulas = ["SiO2", "Al2O3", "Fe2O3"]
energies = [8.0, 10.0, 12.0, 15.0]
densities = [2.2, 3.95, 5.24]
results = calculate_xray_properties(formulas, energies, densities)
sio2_result = results[1]
println("SiO2 molecular weight: ", sio2_result.molecular_weight)XRayLabTool.calculate_single_material_properties — Function
calculate_single_material_properties(formulaStr, energy, massDensity) -> XRayResultCalculate X-ray optical properties for a single chemical formula.
Arguments
formulaStr::String: Chemical formula (e.g., "SiO2", "Al2O3")energy::Vector{Float64}: X-ray energies in KeVmassDensity::Float64: Mass density in g/cm³
Returns
XRayResult: Complete set of calculated optical properties
Examples
result = calculate_single_material_properties("SiO2", [8.0, 10.0, 12.0], 2.2)
println("Molecular weight: ", result.molecular_weight)
println("Critical angles: ", result.critical_angle)Result type
XRayLabTool.XRayResult — Type
XRayResultStruct to store complete X-ray optical property calculations for a material.
Contains all computed properties including scattering factors, optical constants, and derived quantities like critical angles and attenuation lengths.
Deprecated functions
These functions still work but will issue deprecation warnings. Use the new names instead.
| Deprecated | Replacement |
|---|---|
Refrac | calculate_xray_properties |
SubRefrac | calculate_single_material_properties |
XRayLabTool.Refrac — Function
Refrac(formulaList, energy, massDensityList) -> Vector{XRayResult}Use calculate_xray_properties instead.
XRayLabTool.SubRefrac — Function
SubRefrac(formulaStr, energy, massDensity) -> XRayResultUse calculate_single_material_properties instead.
Internal functions
These are not exported but are accessible via XRayLabTool.function_name.
Element data
XRayLabTool.atomic_number_and_mass — Function
atomic_number_and_mass(element_symbol::String) -> (Int, Float64)Retrieve atomic number and atomic mass for a given element symbol. Uses caching to avoid repeated lookups of the same element.
Arguments
- 'element_symbol::String': Chemical symbol (e.g., "Si", "O")
Returns
- 'Tuple{Int, Float64}': (atomicnumber, atomicmassinamu)
Throws
- 'ArgumentError': If element symbol is not found in periodic table
XRayLabTool.load_element_interpolators — Function
load_element_interpolators(element_symbol::String) -> (PCHIPInterp, PCHIPInterp)Load and cache PCHIP interpolators for an element's scattering factors.
Returns cached interpolator pair if available, otherwise loads the element's .nff data file, builds PCHIP interpolators for f1 and f2, and caches them.
Arguments
element_symbol::String: Chemical symbol (e.g., "Si", "O")
Returns
Tuple{PCHIPInterp, PCHIPInterp}: (f1interpolator, f2interpolator)
Throws
ArgumentError: If element data file cannot be found
Formula parsing
XRayLabTool.parse_formula — Function
parse_formula(formulaStr::String) -> (Vector{String}, Vector{Float64})Parse a chemical formula string into element symbols and their counts.
Arguments
- 'formulaStr::String': Chemical formula (e.g., "SiO2", "Al2O3", "Ca(OH)2", "Ca3(PO4)2")
Returns
- 'Tuple{Vector{String}, Vector{Float64}}': (elementsymbols, elementcounts)
Examples
'''julia symbols, counts = parse_formula("SiO2")
symbols = ["Si", "O"], counts = [1.0, 2.0]
symbols, counts = parse_formula("Al2O3")
symbols = ["Al", "O"], counts = [2.0, 3.0]
symbols, counts = parse_formula("Ca(OH)2")
symbols = ["Ca", "O", "H"], counts = [1.0, 2.0, 2.0]
symbols, counts = parse_formula("Ca3(PO4)2")
symbols = ["Ca", "P", "O"], counts = [3.0, 2.0, 8.0]
'''
Throws
- 'ArgumentError': If formula string is invalid or empty
Core calculation
XRayLabTool.accumulate_optical_coefficients! — Function
accumulate_optical_coefficients!(...)Vectorized calculation of X-ray scattering factors and optical properties.
This function performs the core calculation of delta (δ), beta (β), and total scattering factors for a material based on its elemental composition.
Arguments
- 'energies_eV::Vector{Float64}': X-ray energies in eV
- 'wavelengths_m::Vector{Float64}': Corresponding wavelengths in meters
- 'mass_density::Float64': Material density in g/cm³
- 'molecular_weight::Float64': Molecular weight in g/mol
- 'elementdata::Vector{ElementInterpolatorData}': Element data (count, f1interp, f2_interp)
- 'delta::Vector{Float64}': Output array for δ (real part of refractive index)
- 'beta::Vector{Float64}': Output array for β (imaginary part of refractive index)
- 'f1_total::Vector{Float64}': Output array for total f1 values
- 'f2_total::Vector{Float64}': Output array for total f2 values
Mathematical Background
The optical coefficients delta and beta are calculated using:
- δ = (λ²/2π) × rₑ × ρ × Nₐ × (Σᵢ nᵢ × f1ᵢ) / M
- β = (λ²/2π) × rₑ × ρ × Nₐ × (Σᵢ nᵢ × f2ᵢ) / M
Where:
- λ: X-ray wavelength in meters
- rₑ: Thomson scattering length
- ρ: Mass density
- Nₐ: Avogadro's number
- nᵢ: Number of atoms of element i
- f1ᵢ, f2ᵢ: Atomic scattering factors for element i
- M: Molecular weight
Utilities
XRayLabTool.clear_caches! — Function
clear_caches!()Clear all cached data to free memory.
This function clears both the atomic data cache and the f1f2 table cache. Useful for memory management in long-running applications or when processing many different materials.
Examples
'''julia
After processing many materials, clear caches to free memory
clear_caches!() '''
Debugging
XRayLabTool includes comprehensive debug logging across 6 categories. All log points use @debug level — zero cost when disabled (default).
Enable logging
# Via environment variable (before loading package)
ENV["JULIA_DEBUG"] = "XRayLabTool"
using XRayLabTool
result = calculate_single_material_properties("SiO2", [8.0, 10.0], 2.2)
# Prints: formula parsing, cache hits/misses, file I/O, computation steps, timingLog categories
Each log message is tagged with a _group for targeted filtering:
| Group | What it traces |
|---|---|
:parser | Formula parsing steps, parenthesized group expansion |
:cache | Cache hits, misses, writes, clears |
:io | .nff file path resolution, file loading with timing |
:validation | Energy range checks, formula validation |
:computation | Per-material calculation: MW, scattering factors, derived quantities, timing |
:batch | Batch orchestration: thread dispatch, parallel timing |
Filter by category
using Logging
# Custom logger that filters by group
struct GroupFilterLogger <: AbstractLogger
inner::AbstractLogger
groups::Set{Symbol}
end
Logging.min_enabled_level(l::GroupFilterLogger) = Logging.min_enabled_level(l.inner)
Logging.shouldlog(l::GroupFilterLogger, args...) = Logging.shouldlog(l.inner, args...)
Logging.catch_exceptions(l::GroupFilterLogger) = Logging.catch_exceptions(l.inner)
function Logging.handle_message(l::GroupFilterLogger, level, message, _module, group, id,
file, line; kwargs...)
group in l.groups || return
Logging.handle_message(
l.inner, level, message, _module, group, id, file, line; kwargs...)
end
# Show only cache and I/O messages
with_logger(GroupFilterLogger(ConsoleLogger(stderr, Logging.Debug), Set([:cache, :io]))) do
result = calculate_single_material_properties("SiO2", [8.0], 2.2)
endIndex
XRayLabToolXRayLabTool.XRayResultXRayLabTool.RefracXRayLabTool.SubRefracXRayLabTool.accumulate_optical_coefficients!XRayLabTool.atomic_number_and_massXRayLabTool.calculate_single_material_propertiesXRayLabTool.calculate_xray_propertiesXRayLabTool.clear_caches!XRayLabTool.load_element_interpolatorsXRayLabTool.parse_formula