API Reference
Data Handling
Cross-Section
- class nbragg.cross_section.CrossSection(materials=None, name=None, total_weight=1.0, **kwargs)[source]
Bases:
objectRepresents a combination of cross-sections for crystal materials.
- format_orientations(dir1=None, dir2=None, phi=0.0, theta=0.0)[source]
Converts dir1 and dir2 vectors to NCrystal orientation format with optional rotation.
- Return type:
Dict[str,List[float]]
- classmethod from_mtex(csv_file, material, powder_phase=True, short_name=None)[source]
Create a CrossSection from MTEX CSV orientation data.
- Parameters:
csv_file (str) – Path to the CSV file containing MTEX orientation data with columns: - alpha_mtex, beta_mtex, gamma_mtex: Euler angles - volume_mtex: Volume fraction for each orientation - fwhm: Full width at half maximum (mosaicity) - xh, xk, xl: First crystal direction components - yh, yk, yl: Second crystal direction components
material (str or dict) – Material specification. Can be: - A string filename (e.g., “Fe_sg225_Iron-gamma.ncmat”) - will be loaded from nbragg.materials - A material dictionary from nbragg.materials with keys like ‘mat’, ‘temp’, etc.
powder_phase (bool, optional) – Whether to add a non-oriented powder phase with complementary weight (default: True)
short_name (str, optional) – Short name prefix for the phase (e.g., ‘γ’ for gamma). If not provided, will be extracted from the material name.
- Returns:
CrossSection object with oriented materials from CSV data and optional powder phase
- Return type:
Examples
>>> # Using material dictionary >>> xs = nbragg.CrossSection.from_mtex( ... "orientations.csv", ... material=nbragg.materials["Fe_sg225_Iron-gamma.ncmat"], ... short_name="gamma" ... )
>>> # Using material filename (string) >>> xs = nbragg.CrossSection.from_mtex( ... "orientations.csv", ... material="Fe_sg225_Iron-gamma.ncmat" ... )
>>> # Without specifying short_name (auto-extracted) >>> xs = nbragg.CrossSection.from_mtex( ... "orientations.csv", ... material=nbragg.materials["Fe_sg225_Iron-gamma.ncmat"] ... )
- get_atomic_density()[source]
Get the atomic density (number density) from the material.
- Returns:
Atomic number density in atoms/barn/cm
- get_phase_xs(wl, phase, **kwargs)[source]
Get cross section for a specific phase.
- Parameters:
wl (
ndarray) – Wavelength arrayphase (
str) – Phase name**kwargs – Parameters for updating the phase configuration
- Returns:
Cross section array for the specified phase
- plot(**kwargs)[source]
Plot the weighted neutron cross-section data for each phase and the total.
This method will: 1. Update lattice and extinction parameters for each material (if applicable). 2. Load and populate the cross-section data table. 3. Plot each phase’s weighted cross-section in the same order as the table columns. 4. Plot the total cross-section as a thicker dark line. 5. Generate a legend with phase names and their weight percentages.
- Parameters:
title (str, optional) – Title of the plot. Defaults to the cross-section object’s name.
ylabel (str, optional) – Y-axis label. Defaults to
"σ [barn]".xlabel (str, optional) – X-axis label. Defaults to
"Wavelength [Å]".lw (float, optional) – Base line width for phase curves. Defaults to
1.0.**kwargs – Additional keyword arguments passed to
pandas.DataFrame.plotfor the phase curves.
- Returns:
The matplotlib Axes object containing the plot.
- Return type:
matplotlib.axes.Axes
Notes
The order of phases in the plot and legend is preserved according to the
order of the columns in
self.table(excluding the “total” column). - The “total” curve is always plotted last, with a distinct style and label.Examples
>>> xs = 0.0275 * nbragg.CrossSection(celloluse=nbragg.materials["Cellulose_C6O5H10.ncmat"]) ... + (1 - 0.00275) * nbragg.CrossSection(α=nbragg.materials["Fe_sg229_Iron-alpha_CrysExtn1.ncmat"]) >>> ax = xs.plot(title="Cross-section comparison", lw=1.5) >>> ax.figure.show()
- update(**kwargs)[source]
Update the CrossSection object after modifying self.materials. Optionally accepts kwargs to update material parameters before reprocessing.
- Parameters:
**kwargs (dict) – Material parameters to update. Can specify material-specific parameters (e.g., beryllium={‘ext_tilt’: ‘rect’}) or global parameters that apply to all materials (e.g., ext_l=10).
Examples
>>> xs.update(ext_tilt='rect') # Apply to all materials >>> xs.update(beryllium={'ext_tilt': 'rect'}) # Apply to specific material
Transmission Model
Utilities
- class nbragg.utils.Hyperlink(url)[source]
Bases:
objectA simple hyperlink representation that displays as ‘hyperlink’ in repr but can be clicked in Jupyter/IPython environments.
- class nbragg.utils.LazyMaterialsDict[source]
Bases:
dictDictionary that initializes materials on first access and returns MaterialSpec objects.
- class nbragg.utils.MaterialSpec[source]
Bases:
dictA dictionary subclass for material specifications that supports weight multiplication and provides enhanced representation with hyperlinks.
- Usage:
material = nbragg.materials[“Al2O3_sg167_Corundum”] weighted_material = material * 0.5 # Creates new MaterialSpec with weight=0.5 xs = CrossSection(phase1=material * 0.3, phase2=other_material * 0.7)
Response Functions
- class nbragg.response.Background(kind='expo_norm', vary=False)[source]
Bases:
object- constant_background(wl, bg0=0.0, **kwargs)[source]
Generates a constant background.
Parameters: wl (np.ndarray): Wavelength values. b0 (float): Constant background value.
- plot(wl, params=None, **kwargs)[source]
Plots the background function.
Parameters: wl (np.ndarray): Wavelength values. params (dict): Parameters for the background function.
- polynomial3_background(wl, bg0=0.0, bg1=1.0, bg2=0.0, **kwargs)[source]
Computwls a third-degree polynomial background.
Parameters: wl (np.ndarray): Energy values. bg0 (float): Constant term. bg1 (float): Linear term. bg2 (float): Quadratic term.
- polynomial5_background(wl, bg0=0.0, bg1=1.0, bg2=0.0, bg3=0.0, bg4=0.0, **kwargs)[source]
Computes a fifth-degree polynomial background.
Parameters: wl (np.ndarray): Wavelegth values. bg0 (float): Constant term. bg1 (float): Linear term. bg2 (float): Quadratic term. bg3 (float): Cubic term. bg4 (float): Quartic term.
- class nbragg.response.Response(kind='jorgensen', vary=False, wlstep=0.1, tstep=1e-05)[source]
Bases:
object- cut_array_symmetric(arr, threshold)[source]
Symmetrically cuts the array based on a threshold.
Parameters: arr (np.ndarray): Input array to be cut. threshold (float): The threshold value for cutting the array.
Returns: np.ndarray: Symmetrically cut array with an odd number of elements.
- full_jorgensen_response(wl=4.0, α0=0.0, α1=0.5, β0=0.5, β1=0.0, σ0=0.0, σ1=0.001, σ2=0.0, **kwargs)[source]
Jorgensen TOF peak profile with d-spacing-dependent parameters.
- Implements eq. 3.40 of Jorgensen et al. (1978):
h(Δ, σ, α, β) = αβ / (2(α+β)) · (exp(u) erfc(y) + exp(v) erfc(z))
- with
α = α0 + α1 / d [1/µs] β = β0 + β1 / d^4 [1/µs] σ² = σ0² + (σ1·d)² + (σ2·d²)² [µs²]
Parameter units are GSAS-style: α, β in 1/µs and σ in µs. The profile is evaluated on self.tgrid (seconds) — the function converts units internally so the user-facing values stay in the 0.001–1000 range.
Uses the identity exp(u)·erfc(y) = exp(−x²/(2σ²))·erfcx(y) on the y≥0 side to avoid exp(α²σ²/2) overflow when σ is large; the y<0 side is already bounded so it uses the direct form.
Returns a 1-D normalized profile defined on self.tgrid.
- jorgensen_response(α0, β0, σ1=None, **kwargs)[source]
Calculates the Jorgensen peak profile function with Greek Unicode parameters.
Parameters:
- α0float or list/tuple
Alpha parameter [α0₁, α0₂] or single value α0₁ (α0₂ defaults to 0)
- β0float or list/tuple
Beta parameter [β0₁, β0₂] or single value β0₁ (β0₂ defaults to 0)
- σ1list/tuple, optional
Sigma parameters [σ₁, σ₂, σ₃], defaults to [0, 0, 0]
Returns:
: numpy.ndarray
Normalized profile values with NaN values replaced by 0
- plot(params=None, **kwargs)[source]
Plots the response function.
Parameters: params (dict): Parameters for the response function. **kwargs: Additional arguments for plot customization.
- register_response(response_func, lmfit_params=None, **kwargs)[source]
Registers a new response using any scipy.stats function.
Parameters: response_func (function): A function from scipy.stats, e.g., exponnorm.pdf. lmfit_params (lmfit.Parameters): Optional lmfit.Parameters to define limits and vary. kwargs: Default parameter values for the response function.
- square_jorgensen_response(α0=3.67, β0=3, σ1=None, width=None, **kwargs)[source]
Calculates the Jorgensen peak profile function with an additional square width parameter.
Parameters:
- α0float or list/tuple
Alpha parameter [α0, α0] or single value α0 (α0 defaults to 0)
- β0float or list/tuple
Beta parameter [β0, β0] or single value β0 (β0 defaults to 0)
- σ1list/tuple, optional
Sigma parameters [σ₁, σ₂, σ₃], defaults to [0, 0, 0]
- widthfloat, optional
Square width to broaden the response [usec]
Returns:
: numpy.ndarray
Normalized profile values with NaN values replaced by 0
- square_response(width=10, center=True, **kwargs)[source]
Returns a square response in time with a given width [µs].
- staged_preset()[source]
Recommended staged-fit ordering for this response kind.
Returns a dict suitable for assigning to TransmissionModel.stages, merging with other stages as needed. For full_jorgensen the order follows Jorgensen-profile fitting best practice: refine σ1 first (dominant resolution term), then β0 (decay), then α1 (rise).