garnet.utilities package#
Submodules#
garnet.utilities.autoreduce module#
- class AutoReduce(filename)[source]#
Bases:
objectMethods
Locate the most recently modified autoreduce yaml config, if any.
Bin the detector-space (gamma, nu) view into a 2D histogram (mean intensity per bin, mirroring NeuXtalViz's ub_tools.py calculate_instrument_view), and render it as an interactive Plotly heatmap for the monitor page.
Compute default UB-driven HKL-projection slices, MDNorm-normalize against the configured vanadium solid-angle/flux, accumulate on-disk with any prior run of the same title, and plot/upload.
compress
elastic
publish_plots
- find_autoreduce_config()[source]#
Locate the most recently modified autoreduce yaml config, if any.
Requires UBFile, VanadiumFile, and FluxFile keys; missing file or keys means the slice preview workflow is skipped entirely.
garnet.utilities.calculate module#
- class CalculateUB(a, b, c, alpha, beta, gamma)[source]#
Bases:
objectOptimizer of crystal orientation from peaks and known lattice parameters.
- Attributes:
- a, b, cfloat
Lattice constants in ansgroms.
- alpha, beta, gammafloat
Lattice angles in degrees.
Methods
UB_matrix(U, B)Calculate \(UB\)-matrix.
cost(param, B, kf_ki_dir, wavelength)Cost function for indexing given a proposed orientation.
indexer(UB, kf_ki_dir, wavelength[, tol, alpha])Laue indexer for a given \(UB\) matrix.
Calculate the reciprocal metric tensor \(G^*\).
Calculate the metric tensor \(G\).
minimize(kf_ki_dir, wavelength[, n_proc])Fit the orientation and other parameters.
objective(x)Objective function.
orientation_U(u0, u1, u2)The sample orientation matrix \(U\).
The reciprocal lattice \(B\)-matrix.
refine(kf_ki_dir, wavelength[, cell, error])Refine the orientation and lattice parameters under constraints.
residual(x, kf_ki_dir, hkl, wavelength, fun)Optimization residual function.
cartesian_matrix_metric_tensor
cubic
get_lattice_constants
get_orientation_parameters
hexagonal
index
monoclinic
orthorhombic
rhombohedral
set_lattice_constants
set_orientation_parameters
softplus
tetragonal
triclinic
- UB_matrix(U, B)[source]#
Calculate \(UB\)-matrix.
- Parameters:
- U2d-array
3x3 orientation matrix.
- B2d-array
3x3 reciprocal lattice vectors Cartesian matrix.
- Returns:
- UB2d-array
3x3 oriented reciprocal lattice.
- cost(param, B, kf_ki_dir, wavelength)[source]#
Cost function for indexing given a proposed orientation.
- Parameters:
- paramtuple, float
Orientation parameters.
- Barray, float
Reciprocal lattice B-matrix.
- kf_ki_dirarray, float
- wavelengthlist, float
Wavelength band (min, max).
- Returns:
- errorfloat
Total indexing cost.
- indexer(UB, kf_ki_dir, wavelength, tol=0.1, alpha=0.1)[source]#
Laue indexer for a given \(UB\) matrix.
- Parameters:
- UB2d-array
3x3 sample oriented lattice matrix.
- kf_ki_dirlist
Difference between scattering and incident beam directions.
- wavelengthlist
Wavelength of each reflection.
- tolfloat, optional
Indexing tolerance. Default is 0.15.
- Returns:
- errfloat
Indexing cost.
- numint
Number of peaks index.
- hkllist
Miller indices. Un-indexed are labeled [0,0,0].
- lamdalist
Resolved wavelength. Unindexed are labeled inf.
- metric_G_star_tensor()[source]#
Calculate the reciprocal metric tensor \(G^*\).
- Returns:
- Gstar2d-array
3x3 matrix of reciprocal lattice info for Cartesian transforms.
- metric_G_tensor()[source]#
Calculate the metric tensor \(G\).
- Returns:
- G2d-array
3x3 matrix of lattice parameter info for Cartesian transforms.
- minimize(kf_ki_dir, wavelength, n_proc=-1)[source]#
Fit the orientation and other parameters.
- Parameters:
- n_procint, optional
Number of processes to use. The default is -1.
- Returns:
- numint
Number of peaks index.
- hkllist
Miller indices. Un-indexed are labeled [0,0,0].
- lamdalist
Resolved wavelength. Un-indexed are labeled inf.
- objective(x)[source]#
Objective function.
- Parameters:
- xarray
Refineable parameters.
- Returns:
- neg_indint
Negative number of peaks indexed.
- orientation_U(u0, u1, u2)[source]#
The sample orientation matrix \(U\).
- Parameters:
- u0, u1, u2float
Rotation paramters.
- Returns:
- U2d-array
3x3 sample orientation matrix.
- reciprocal_lattice_B()[source]#
The reciprocal lattice \(B\)-matrix.
- Returns:
- B2d-array
3x3 matrix of reciprocal lattice in Cartesian coordinates.
- refine(kf_ki_dir, wavelength, cell='Triclinic', error=0.15)[source]#
Refine the orientation and lattice parameters under constraints.
garnet.utilities.calibration module#
- class Calibration(config)[source]#
Bases:
objectMethods
calculate_goniometer_angles
calculate_goniometer_matrix
calculate_orientation_matrix
calculate_orientation_vector
calculate_tilt_matrices
calculate_tilt_matrix
calibrate_goniometer
calibrate_instrument
cell_symmetry_matrices
fix_offsets
generate_diagnostic
gravity_angle
initialize_peaks
load_instrument
load_peaks
optimize_goniometer
refine_goniometer
refine_offsets
reindex_peaks
residual
run
garnet.utilities.combine module#
garnet.utilities.confirm module#
- confirm_autoreduce(filename)[source]#
Confirm autoreduction status based on reduction logs.
- Parameters:
- filenamestr
Full data path containing facility, instrument, and IPTS fields.
Notes
Confirmation logic:
Unknown→ No.logfiles detectedYes→ Logs exist and no failures detectedPartially→ Some runs failedNo→ All runs failed
garnet.utilities.crystal module#
garnet.utilities.ipts module#
garnet.utilities.macromolecular module#
garnet.utilities.peaks module#
garnet.utilities.peakview module#
garnet.utilities.refinement module#
- class NuclearStructureRefinement(cell, space_group, sites, filename, parameters=None, twin_laws=None, u_vector=None, v_vector=None)[source]#
Bases:
objectMethods
add_twin_parameters(params)Twin domain volume fractions (
twin_frac_0..twin_frac_{n-1}, domain 0 the identity), reparametrized as n-1 free, independently bounded [0, 1] "stick-breaking" parameterstwin_s_i:frac_0 = s_0,frac_1 = (1-s_0)*s_1, ..., and the last fraction is the leftover productprod(1-s_i).beam_weights(sample_points, G, ds, bx, by, sigma)Calculate Gaussian beam weights for sample points.
calculate_structure_amplitudes(params[, hkl])Compute complex structure amplitudes Fs (per unique hkl) for given params.
calculate_structure_factors(params)F2_calc per observation, incoherently summed over twin domains weighted by their refined volume fraction: each domain sees the same structural model but a transformed hkl (
T @ hkl), since domains are distinct crystallites (no amplitude interference between them).extinction_correction(param, F2)Calculate structure factor-dependent extinction correction.
objective_correction(params)Objective for absorption/extinction refinement.
objective_structure(params)Objective for structure + scale refinement.
plot_hkl_families([filename])Create multi-page PDF with one page per hkl family.
Plot the refined ellipsoidal sample shape with beam directions.
plot_wobble_correction(off[, filename])Plot wobble correction scale factors vs rotation angle.
refine([report, cutoff, n_iter, abs_corr, ...])Iterative refinement protocol: 7 stages per iteration.
Apply absorption corrections to all peaks and save to new file.
twin_fractions(params)Volume fraction of each twin domain (
self.twin_laws, domain 0 always the identity), read off thetwin_frac_iparametersadd_twin_parametersderives from the freetwin_s_istick-breaking parameters.wobble_correction(off)Scale model for off-centering/wobble correction.
absorption_correction
add_absorption_extinction_parameters
add_beam_parameters
add_detector_run_scale_parameters
calculate_scale_factor
calculate_statistics
chemical_formula_z_parameter
cost
detector_bank_scale_factors
extinction_xp
extinction_xs
extinction_xx
extract_info
extract_parameters
generate_parameters
generate_symmetry_transforms
initialize_correction
initialize_crystal_structure
initialize_material
initialize_unit_cell_atoms
load_hkls
normalization_correction
plot_absorption_correction
plot_result
report
run_angle_scale_factors
save_detector_scales
spherical_absorption
spherical_absorption_correction
spherical_extinction
update_sample
- add_twin_parameters(params)[source]#
Twin domain volume fractions (
twin_frac_0..twin_frac_{n-1}, domain 0 the identity), reparametrized as n-1 free, independently bounded [0, 1] “stick-breaking” parameterstwin_s_i:frac_0 = s_0,frac_1 = (1-s_0)*s_1, …, and the last fraction is the leftover productprod(1-s_i). This keeps every fraction in [0, 1] and summing to 1 for any values the optimizer picks, unlike a naiveexpr='1-f_1-...-f_{n-1}'for the last fraction, which lmfit would not keep bounded.n=1 (the default, no twin laws beyond the implicit identity) adds a single fixed
twin_frac_0 = 1and no free parameters.
- beam_weights(sample_points, G, ds, bx, by, sigma)[source]#
Calculate Gaussian beam weights for sample points.
- Parameters:
- sample_pointsndarray, shape (N, 3)
Monte Carlo sample points in sample frame
- Gndarray, shape (P, 3, 3)
Goniometer matrices for each peak
- dsndarray, shape (P, 3)
Sample center offset in sample frame for each peak
- bx, byfloat
Beam center position in lab frame
- sigmafloat
Gaussian beam width
- Returns:
- bwndarray, shape (N, P)
Beam weights for each sample point and peak
- calculate_structure_amplitudes(params, hkl=None)[source]#
Compute complex structure amplitudes Fs (per unique hkl) for given params. hkl defaults to self.equiv (the observed unique HKLs) but may be a transformed array, e.g. a twin domain’s T @ hkl.
This is identical to the inner part of calculate_structure_factors but returns the complex amplitudes (not squared magnitudes).
- calculate_structure_factors(params)[source]#
F2_calc per observation, incoherently summed over twin domains weighted by their refined volume fraction: each domain sees the same structural model but a transformed hkl (
T @ hkl), since domains are distinct crystallites (no amplitude interference between them).
- extinction_correction(param, F2)[source]#
Calculate structure factor-dependent extinction correction.
Model
Nature
Parameter
Type I, GaussianSecondary
Mosaic [unitless]
Type I, LorentzianSecondary
Mosaic [unitless]
Type IIPrimary
Block size² [um²]
SHELXPhenomenological
Crystal size [cm]
[1] P. J. Becker and P. Coppens, Acta Cryst A 30, 2 (1974). [2] P. J. Becker and P. Coppens, Acta Cryst A 30, 2 (1974). [3] A. C. Larson, Crystallographic Computing (1970).
- Parameters:
- paramfloat
Exinction parameter.
- F2array
Structure factors (fm^2).
- Returns:
- yarray
Extinction (unitless).
- objective_correction(params)[source]#
Objective for absorption/extinction refinement.
Structure and scale are held fixed; F2s are precomputed for the current structural model.
- objective_structure(params)[source]#
Objective for structure + scale refinement.
This stage varies positional, occupancy and displacement parameters together with the overall scale, while using the current absorption/extinction parameters as fixed values.
- plot_wobble_correction(off, filename=None)[source]#
Plot wobble correction scale factors vs rotation angle.
Shows observed data points and model curves for different wavelengths.
- refine(report=True, cutoff=10, n_iter=3, abs_corr=False, off_corr=False, det_corr=False, run_corr=False, norm_corr=False, ext_model='shelx')[source]#
Iterative refinement protocol: 7 stages per iteration.
- Per iteration:
Structure + scale (fixed corrections).
Absorption only.
Extinction only.
Wobble only.
Detector scales (optional).
Run/orientation scales (optional).
Normalization scales (optional).
- twin_fractions(params)[source]#
Volume fraction of each twin domain (
self.twin_laws, domain 0 always the identity), read off thetwin_frac_iparametersadd_twin_parametersderives from the freetwin_s_istick-breaking parameters. Sums to 1 by construction.
- wobble_correction(off)[source]#
Scale model for off-centering/wobble correction.
Based on WobbleCorrection model: accounts for beam displacement and sample misalignment effects on intensity measurements.
- Parameters:
- offarray-like
[b, c, rx, rz] where: - b: spread (wavelength-dependent scaling) - c: center displacement - rx: in-plane displacement - rz: beam displacement
- Returns:
- array
Scale factors for each reflection
garnet.utilities.reflections module#
- class AbsorptionCorrection(peaks, chemical_formula, z_parameter, u_vector=[0, 0, 1], v_vector=[1, 0, 0], params=None, filename=None)[source]#
Bases:
objectMethods
Correct every peak's intensity for absorption.
calculate_correction
save_ellipsoid_stl
set_material
set_orientation
set_shape
verify_chemical_formula
write_absortion_parameters
- class Peaks(peaks, filename, scale=None, point_group=None, HKLTransform=None, intensity='3D')[source]#
Bases:
objectMethods
load_consistent_UB(ub_file[, tol, min_frac])Load the UB matrix in
ub_fileonto the peaks only if it indexes at leastmin_fracof them to their current HKL withintol; otherwise keep the UB the peaks carry, e.g. when the file was saved before (or after) anHKLTransform.remove_forbidden_reflections(cell, ...[, ...])Flag anomalously strong forbidden/weak reflections using the (cell, space_group, sites) structural model -- the same triple
NuclearStructureRefinement/StructureAnalysisalready carry as the reduction plan's Material block (space group + atom sites), which is the source of truth here.remove_forbidden_reflections_from_cif(...[, ...])Convenience fallback for
remove_forbidden_reflectionswhen a CIF file is available instead of an explicit (cell, space_group, sites) triple.remove_low_volume_fraction([cutoff])Flag peaks whose fitted-ellipsoid volume fraction on the detector (peaks_vol_frac) falls below
cutoff.Remove reflections contaminated by powder lines, e.g. from the sample environment, over all runs.
remove_volume_outliers([lo, hi])Flag peaks whose 3D Gaussian profile-fit intensity (I_3d) disagrees with the peak's assigned intensity (peak.getIntensity()).
transform_hkl([peaks, tol])Apply
self.HKLTransformto correct an indexing/setting error discovered after integration, without re-integrating.use_radial_intensities(peaks)Report the radial fit along Q, logged with each peak, as its intensity in place of the 3D integration.
write_cif_report([peaks, mu, transmission, ...])Write a minimal CIF-format summary for post-reduction checking: unit-cell constants with esd's, the measured wavelength/theta/ d-spacing range, crystal size, a transmission range, and the merging statistics (Rint) from the last
calculate_statisticscall.write_radial_comparison(filename)Tabulate, for every peak with a radial fit along Q, its 3D integration (the profile fit or the count), the radial fit and their ratio, both normalized by flux and solid angle and not yet scaled or corrected.
calculate_statistics
get_cell
load_peaks
load_spectrum
median_absolute_devation
merge_intensities
peak_info
plot_signal_noise
plot_volume_fraction
refine_UB
refine_ellipsoids
remove_non_indexed
remove_non_integrated
remove_off_centered
renumber_peaks
rescale_intensities
reset_satellite
resort_hkl
save_peaks
update_monitor
- load_consistent_UB(ub_file, tol=0.15, min_frac=0.9)[source]#
Load the UB matrix in
ub_fileonto the peaks only if it indexes at leastmin_fracof them to their current HKL withintol; otherwise keep the UB the peaks carry, e.g. when the file was saved before (or after) anHKLTransform.
- remove_forbidden_reflections(cell, space_group, sites, sigma=4.5, weak_frac=0.05, peaks=None, twin_laws=None)[source]#
Flag anomalously strong forbidden/weak reflections using the (cell, space_group, sites) structural model – the same triple
NuclearStructureRefinement/StructureAnalysisalready carry as the reduction plan’s Material block (space group + atom sites), which is the source of truth here. Seeremove_forbidden_reflections_from_ciffor the fallback when a user supplies a CIF file instead.sitesentries are(atom, x, y, z, occ)– the plan’s Material.Sites format has no Uiso – or(atom, x, y, z, occ, Uiso); a missing Uiso defaults to 0, matchingNuclearStructureRefinement’s own convention.
- remove_forbidden_reflections_from_cif(cif_filename, sigma=4.5, weak_frac=0.05, peaks=None)[source]#
Convenience fallback for
remove_forbidden_reflectionswhen a CIF file is available instead of an explicit (cell, space_group, sites) triple.
- remove_low_volume_fraction(cutoff=0.5)[source]#
Flag peaks whose fitted-ellipsoid volume fraction on the detector (peaks_vol_frac) falls below
cutoff. A low vol_frac means intensity/sigma were extrapolated from a small observed fraction of the peak (edge/gap clipping), which is amplified by 1/vol_frac and therefore unreliable.
- remove_powder_shells()[source]#
Remove reflections contaminated by powder lines, e.g. from the sample environment, over all runs.
Powder raises the local background of every reflection whose region a ring crosses, at the ring’s apparent d-spacing, whether or not the intensity follows; rings off the sample position fall at d-spacings that differ from the tabulated ones and from detector to detector, so none are assumed. Each reflection’s log background per unit normalization is compared with a smooth trend in wavelength and scattering angle, along which it varies most; shells are d-spacing windows with significantly more reflections far above it than the typical window (binomial test), a systematic rise rather than a few bad peaks.
Within a shell, a reflection more than _SHELL_PEAK_Z robust spreads above the trend, with the ring in its own region, is compared with the median intensity of its symmetry equivalents without the ring, measured elsewhere on the detector or in other runs; it is kept if it agrees within _SHELL_Z standard errors, and otherwise, or with no such equivalents, flagged for removal.
- remove_volume_outliers(lo=0.1, hi=10.0)[source]#
Flag peaks whose 3D Gaussian profile-fit intensity (I_3d) disagrees with the peak’s assigned intensity (peak.getIntensity()). Peaks whose I_3d / getIntensity() ratio falls outside [lo, hi] are considered outliers and flagged for removal.
- save_peaks(name=None, fit_dict=None, mu=0.0, transmission=None, instrument=None, correction_type=None, control_software=None, crystal_size=None)[source]#
- transform_hkl(peaks=None, tol=0.15)[source]#
Apply
self.HKLTransformto correct an indexing/setting error discovered after integration, without re-integrating. A no-op when the transform is the identity (the default).
- use_radial_intensities(peaks)[source]#
Report the radial fit along Q, logged with each peak, as its intensity in place of the 3D integration. Both are normalized by flux and solid angle and not yet scaled or corrected. A peak without a successful radial fit is flagged for removal.
- Parameters:
- peaksstr
Name of peaks table, keyed as info_dict is.
- write_cif_report(peaks=None, mu=0.0, transmission=None, correction_type=None, instrument=None, facility=None, control_software=None, crystal_size=None, filename=None)[source]#
Write a minimal CIF-format summary for post-reduction checking: unit-cell constants with esd’s, the measured wavelength/theta/ d-spacing range, crystal size, a transmission range, and the merging statistics (Rint) from the last
calculate_statisticscall.transmission, when given, is the actual per-peak absorption factor already computed for the correction that was applied (e.g.AbsorptionCorrection.T) and is reported as-is. Leave at None to instead approximate it frommu(the linear absorption coefficient in cm^-1, evaluated at a single reference wavelength) and each peak’s absorption-weighted path length (Tbar);mu=0(default) reports T = 1, i.e. no absorption correction applied.crystal_sizeis the (thickness, width, height) full-axis lengths of the sample ellipsoid in mm, e.g.self.paramsfromAbsorptionCorrectionorself.parametersfromNuclearStructureRefinement; leave at None to report those fields as unknown.
- write_radial_comparison(filename)[source]#
Tabulate, for every peak with a radial fit along Q, its 3D integration (the profile fit or the count), the radial fit and their ratio, both normalized by flux and solid angle and not yet scaled or corrected.
- Parameters:
- filenamestr
Name of the table; nothing is written without radial fits.
- error_volume(a, b, c, alpha, beta, gamma, e_a, e_b, e_c, e_alpha, e_beta, e_gamma)[source]#
Propagate cell-edge and cell-angle esd’s to a cell-volume esd by central finite differences, since OrientedLattice has no direct volume-esd accessor.
garnet.utilities.sliceview module#
garnet.utilities.structure module#
garnet.utilities.vanadium module#
- class Vanadium(config)[source]#
Bases:
objectMethods
Accurate per-pixel geometric solid angle (pixel_area * cos(gamma) / L2^2).
Per-bank background count rate from the standalone background run, normalized by solid angle only (stays per-steradian).
Per-bank signal count rate R_b(lambda) ~= Phi(lambda) * epsilon_b(lambda), in counts / (charge * Angstrom * barn): background-subtracted, absorption-corrected, normalized by solid angle and vanadium cross section (unlike generate_background_count_rate, which stays per-steradian).
apply_absorption_correction
apply_calibration
apply_masks
finalize_and_save
generate_plots
load_instrument
load_runs
process_data
run
set_sample_geometry
subtract_background
- calculate_pixel_solid_angle()[source]#
Accurate per-pixel geometric solid angle (pixel_area * cos(gamma) / L2^2). Computed directly on “vanadium” (not self.instrument, which can resolve to a different, undated IDF) so the grouping can’t disagree with the grouping already applied to the data.
- generate_background_count_rate()[source]#
Per-bank background count rate from the standalone background run, normalized by solid angle only (stays per-steradian). calculate_pixel_solid_angle must have already run (generate_count_rate does this).
- generate_count_rate()[source]#
Per-bank signal count rate R_b(lambda) ~= Phi(lambda) * epsilon_b(lambda), in counts / (charge * Angstrom * barn): background-subtracted, absorption-corrected, normalized by solid angle and vanadium cross section (unlike generate_background_count_rate, which stays per-steradian).
set_sample_geometry must have been called first (self.N_illum, self.sigma_s).