laue_dials.algorithms namespace

Submodules

laue_dials.algorithms.diffgeo module

This file contains useful functions for diffraction geometry calculations

laue_dials.algorithms.diffgeo.align_hkls(reference, target, spacegroup, anomalous=True)[source]

Use the point group operators in spacegroup to align target hkls to reference.

Parameters:
  • reference (np.array) – n x 3 array of miller indices.

  • target (np.array) – n x 3 array of miller indices.

  • spacegroup (gemmi.Spacegroup) – The space group of reference/target.

  • anomalous (bool, optional) – If true, test Friedel symmetries too.

Returns:

n x 3 array of miller indices equivalent to target.

Return type:

aligned (np.array)

laue_dials.algorithms.diffgeo.get_UB_matrices(A)[source]

Convert the reciprocal space indexing matrix, A into the product of an orthogonal matrix U and a lower triangular matrix B.

Parameters:

A (np.array) – A 3x3 indexing matrix such that the scattering vector S1-S0=Q=A@h.

Returns:

An orthogonal 3x3 matrix with the crystal U matrix. B (np.array): A 3x3 lower triangular matrix for the crystal B matrix.

Return type:

U (np.array)

laue_dials.algorithms.diffgeo.hkl2ray(hkl, wavelength=None)[source]

Convert a miller index to the shortest member of its central ray. Optionally, adjust its wavelength accordingly.

Parameters:
  • hkl (np.array) – n x 3 array of miller indices. The dtype must be interpretable as an integer.

  • wavelength (Optional[np.array]) – Length n array of wavelengths corresponding to each miller index.

Returns:

The miller index of the shortest vector on the same central ray as the original hkl. reduced_wavelength (Optional[np.array]): The wavelengths corresponding to reduced_hkl.

Return type:

reduced_hkl (np.array)

laue_dials.algorithms.diffgeo.is_ray_equivalent(hkl1, hkl2)[source]

Test for equivalency between two miller indices in a Laue experiment. Returns a boolean array for each of the n hkls in hkl{1,2}.

Parameters:
  • hkl1 (np.array) – n x 3 array of miller indices. The dtype must be interpretable as an integer.

  • hkl2 (np.array) – n x 3 array of miller indices. The dtype must be interpretable as an integer.

Returns:

Boolean array for hkl equivalency by index from original arrays.

Return type:

equal_hkl (np.array)

laue_dials.algorithms.diffgeo.mat_to_rot_xyz(R, deg=True)[source]

Decompose a rotation matrix into euler angles.

Parameters:
  • R (np.array) – 3 x 3 rotation matrix.

  • deg (Optional[bool]) – If True, angles are returned in degrees.

Returns:

Euler angle around x-axis to generate rotation matrix. rot_y (float): Euler angle around y-axis to generate rotation matrix. rot_z (float): Euler angle around z-axis to generate rotation matrix.

Return type:

rot_x (float)

laue_dials.algorithms.diffgeo.normalize(A)[source]

Normalize the last dimension of an array by dividing by its L2 norm.

Parameters:

A (np.array) – A non-normal matrix.

Returns:

A normalized matrix.

Return type:

A (np.array)

laue_dials.algorithms.diffgeo.orthogonalization(a, b, c, alpha, beta, gamma)[source]

Compute the orthogonalization matrix from cell params.

Parameters:
  • a (float) – Floats representing the magnitudes of the three unit cell axes.

  • b (float) – Floats representing the magnitudes of the three unit cell axes.

  • c (float) – Floats representing the magnitudes of the three unit cell axes.

  • alpha (float) – Floats representing the three unit cell angles.

  • beta (float) – Floats representing the three unit cell angles.

  • gamma (float) – Floats representing the three unit cell angles.

Returns:

3 x 3 orthogonalization matrix for unit cell.

Return type:

orthogonalization_matrix (np.array)

laue_dials.algorithms.diffgeo.rot_xyz_to_mat(rot_x, rot_y, rot_z, deg=True)[source]

Convert euler angles into a rotation matrix.

Parameters:
  • rot_x (float) – Euler angle around x-axis to generate rotation matrix.

  • rot_y (float) – Euler angle around y-axis to generate rotation matrix.

  • rot_z (float) – Euler angle around z-axis to generate rotation matrix.

  • deg (Optional[bool]) – If True, input angles are assumed to be in degrees.

Returns:

3 x 3 rotation matrix.

Return type:

R (np.array)

laue_dials.algorithms.integration module

This file contains useful classes and functions for profiling and integration

class laue_dials.algorithms.integration.Integrator(pixels, centroids, panel_ids=None, panel_masks=None, neighbor_coords=None, radius=None, k=5, isigi_cutoff=3.0, epsilon=1e-06)[source]

Bases: IntegratorBase

assign_knn()[source]
estimate_background()[source]
estimate_profiles()[source]
integrate()[source]
property pixel_weights
property score

Loss function value

set_strong()[source]

set self.strong

class laue_dials.algorithms.integration.IntegratorBase(pixels, centroids, panel_ids=None, panel_masks=None, neighbor_coords=None, radius=None, k=5, isigi_cutoff=3.0, epsilon=1e-06)[source]

Bases: object

fg_to_image(window_values, fill_value=0.0)[source]

convert an array of the same shape as self.pixels[*self.window_idx] -> array(refls x pixels) to something the same shape as refls.pixels

fit(maxiter=2, tol=0.001)[source]

Iteratively refine the background, profiles, and intensities.

The objective is evaluated after an iteration’s updates have been applied, so the value compared always describes the current state. Fitting stops once an iteration fails to improve the objective by at least tol in relative terms, which covers both a plateau and an outright increase.

Parameters:
  • maxiter (int) – Maximum number of iterations to run.

  • tol (float) – Minimum relative improvement in the objective needed to keep iterating. Defaults to 1e-3, i.e. 0.1 percent.

get_log_p_mdist()[source]
property log_profile_values
plot_image(pixels=None, autoscale=True, **kwargs)[source]

autoscale uses skimage.exposure.adjust_log

plot_image_with_profiles()[source]
plot_profiles(ax=None, n_std=2.0, weak_color='w', strong_color='y', facecolor='none', **kwargs)[source]
predict()[source]
property profile_dist
property profile_values
single_profile_image(fg_values, fill_value=0.0)[source]
property windows
property xy
laue_dials.algorithms.integration.cov(m, aweights=None, return_mean=False, ddof=0)[source]

A batched version of np.cov to estimate the sample covariance matrix where m has leading batch dims.

laue_dials.algorithms.integration.detector_global_pixels(detector, panel_ids, spots)[source]

Map panel-local centroids onto a single detector-wide pixel grid.

xyzcal.px is panel-local: every panel starts again at (0, 0), so on a multi-panel detector the panels are superimposed and the coordinates are useless as scaling metadata – on the LADI drum they pile 48 wedges on top of one another. This lays the panels out on a common grid instead.

The panels are assumed to share a slow direction, which is what makes a two-dimensional layout meaningful at all. Writing s for the mean slow axis, each lab-frame point is split into its component along s (the slow coordinate) and its azimuth about s (the fast coordinate, converted to a distance with the mean panel radius). For a curved detector that is the unrolled arc length; for a flat one it is a smooth monotonic function of the fast coordinate. The branch cut is placed in the largest angular gap between panels, so a detector wrapping past 180 degrees – the LADI drum covers about 304 – does not wrap around on itself. The origin is the corner of the panel at the low end of both coordinates, so the result is non-negative and depends only on the detector model.

Parameters:
  • detector – dxtbx detector model, or any sequence of panels supporting get_slow_axis, get_origin, get_pixel_size, get_image_size and get_pixel_lab_coord.

  • panel_ids (np.ndarray) – (n,) panel index per centroid.

  • spots (np.ndarray) – (n, 2) panel-local centroids in pixels.

Returns:

(n, 2) centroids on the detector-wide grid, in pixels. A single-panel detector is returned unchanged. None if the panels have no common slow direction, or if they close a full circle and so leave no gap to cut at.

Return type:

np.ndarray or None

laue_dials.algorithms.integration.estimate_integration_radius(centroids)[source]

Estimate the default integration radius from the spacing of spot centroids.

The radius is half the 20th percentile of nearest-neighbor centroid distances, rounded to the nearest integer. The same radius is used both for the integration window and for dilating the detector mask when discarding predictions that fall in masked regions, so the two stay consistent.

The centroids must be in a frame shared by every panel. Panel-local pixel coordinates superimpose the panels, which drives the nearest-neighbor distances – and the radius with them – towards zero.

Parameters:

centroids (np.ndarray) – (n, 2) array of centroid pixel coordinates.

Returns:

Estimated radius in pixels.

Return type:

int

laue_dials.algorithms.integration.mvn_log_pdf(x, loc, scale, return_zscore=False)[source]

a batched version of scipy.stats.multivariate_normal.log_pdf

laue_dials.algorithms.integration.panel_validity(stack_shape, shapes, panel_masks=None)[source]

Build the per-pixel validity array for a padded panel stack.

A pixel is valid if it lies inside its panel’s true extent and is not masked off by the detector mask.

Parameters:
  • stack_shape (tuple) – Shape of the padded stack, (n_panels, rows, cols).

  • shapes (list) – True (rows, cols) shape of each panel.

  • panel_masks (sequence, optional) – One boolean mask per panel, True for good pixels. Entries may be None. If omitted, every real pixel is valid.

Returns:

Boolean array with the shape of the padded stack.

Return type:

np.ndarray

laue_dials.algorithms.integration.stack_panels(pixels)[source]

Normalize panel pixel data into a single (n_panels, rows, cols) array.

A 2D array is treated as a single panel, so the single-panel call Integrator(pixels, centroids) is unchanged. A sequence of 2D arrays – one per panel, as returned by imageset.get_raw_data() – is padded to the largest panel shape; the padding is marked invalid by panel_validity() and never enters the fit.

Parameters:

pixels (np.ndarray or sequence of np.ndarray) – Panel pixel data.

Returns:

(stack, shapes), the padded (n_panels, rows, cols) array and the list of true (rows, cols) shapes.

Return type:

tuple

laue_dials.algorithms.integration.unmasked_prediction_selection(np_mask, x, y, radius, img_row_size)[source]

Determine which predicted centroids fall outside the detector mask, dilated by the given radius.

If np_mask has no bad (False) pixels at all – e.g. no external mask file was supplied – a genuine 1px border is marked as invalid around the detector edge, and the dilation radius is reduced by 1 to compensate for that added border. This is needed because skimage.morphology.isotropic_dilation relies on scipy.ndimage.distance_transform_edt, which has no real background reference point when there are no bad pixels at all, and would otherwise spuriously mask a small region near pixel (0, 0).

Parameters:
  • np_mask (np.ndarray) – Boolean detector mask with shape (n_rows, n_cols); True for valid pixels.

  • x (np.ndarray) – Integer pixel x-coordinates of predicted centroids.

  • y (np.ndarray) – Integer pixel y-coordinates of predicted centroids.

  • radius (int) – Radius in pixels to dilate the detector mask by.

  • img_row_size (int) – Number of pixels per detector row, used to flatten (x, y) coordinates into the flattened mask.

Returns:

Boolean array, True for centroids to keep.

Return type:

np.ndarray

laue_dials.algorithms.laue module

Classes and functions for Laue-specific processes.

class laue_dials.algorithms.laue.LaueAssigner(s0, s1, cell, R, lam_min, lam_max, lam_peak, dmin, spacegroup='1')[source]

Bases: LaueBase

An object to assign miller indices to a laue still

property H

The Miller indices for inlying reflections.

Type:

np.ndarray

assign()[source]

Assign miller indices to the inlier reflections.

This method updates the following attributes: - self.H: Miller indices associated with the assigned reflections. - self.wav: Wavelengths associated with the assigned reflections. - self.qpred: Predicted scattering vectors associated with the assigned reflections. - self.harmonics: Boolean array indicating whether the assigned reflections are harmonics.

The assignment is performed by solving the linear sum assignment problem using scipy.optimize.linear_sum_assignment. The cost matrix is computed based on the angular distance between observed and predicted scattering vectors.

The feasible set of reflections is determined from the reciprocal lattice points within the specified geometry. Reflections with duplicated scattering vectors are removed, and then the assignment is performed.

This method is essential for updating the information of assigned reflections, allowing subsequent steps in Laue indexing procedures to utilize the assigned miller indices and associated parameters.

property harmonics

Boolean array indicating whether inlying reflections correspond to harmonic reflections.

Type:

np.ndarray

property qobs

The observed q vectors for inlying reflections.

Type:

np.ndarray

property qpred

The predicted q vectors for inlying reflections.

Type:

np.ndarray

reject_outliers(nstd=10.0)[source]

Update the list of inliers based on robust statistical measures.

Parameters:

nstd (float) – Number of standard deviations from the median to consider as inliers.

This method uses Minimum Covariance Determinant (MCD) to robustly estimate the covariance matrix of the concatenated observed and predicted q vectors. It then considers inliers as the points within a specified number of standard deviations from the median Mahalanobis distance.

The list of inliers is updated accordingly.

reset_inliers()[source]

Reset all reflections as inliers.

property s1

The normalized direction of the scattered beam wavevector for inlying reflections.

Type:

np.ndarray

set_H(H)[source]

Set the Miller indices for inlying reflections.

Parameters:

H (np.ndarray) – Miller indices.

set_harmonics(harmonics)[source]

Set whether inlying reflections correspond to harmonics.

Parameters:

harmonics (np.ndarray) – Boolean array indicating harmonics.

set_inliers(inliers)[source]

Set the inliers for the current set of reflections.

Parameters:

inliers (np.ndarray) – Boolean array indicating inliers.

set_qpred(qpred)[source]

Set the predicted q vectors for inlying reflections.

Parameters:

qpred (np.ndarray) – Predicted q vectors.

set_wav(wav)[source]

Set the wavelengths for inlying reflections.

Parameters:

wav (np.ndarray) – Wavelengths.

update_rotation()[source]

Update the rotation matrix (self.R) based on the inlying reflections.

property wav

The wavelengths associated with inlying reflections.

Type:

np.ndarray

class laue_dials.algorithms.laue.LaueBase(s0, cell, R, lam_min, lam_max, dmin, spacegroup='1')[source]

Bases: object

A base class to be extended for Laue procedures

property RB

Calculates the product RB.

Returns:

The product of the rotation matrix (R) and the fractionalization matrix (B).

Return type:

np.ndarray

class laue_dials.algorithms.laue.LauePredictor(s0, cell, R, lam_min, lam_max, dmin, spacegroup='1')[source]

Bases: LaueBase

An object to predict spots given a Laue experiment.

predict_s1(delete_harmonics=False)[source]

Predicts scattering vectors and associated parameters for feasible Laue spots.

Parameters:

delete_harmonics (Optional[bool]) – If True, removes harmonic reflections from the prediction.

Returns:

Predicted feasible scattering vectors. lams (np.ndarray): Wavelengths associated with the predicted scattering vectors. qall (np.ndarray): Q vectors associated with the predicted scattering vectors. Hall (np.ndarray): Miller indices associated with the predicted scattering vectors.

Return type:

s1_pred (np.ndarray)

This method predicts scattering vectors for feasible spots given the current Laue experiment’s geometry. The feasible set of reflections is determined within the specified geometry, and the scattering vectors are predicted.

If delete_harmonics is True, harmonic reflections are removed from the prediction. Harmonics are identified based on duplicated scattering vectors in the reciprocal lattice.

The returned arrays provide essential information about the predicted scattering vectors and associated parameters, allowing further analysis and utilization in Laue indexing procedures.

laue_dials.algorithms.laue.gen_beam_models(expts, refls)[source]

A function for generating beam models according to wavelengths in a reflection table.

Parameters:
  • expts (ExperimentList) – ExperimentList to insert beams into.

  • refls (dials.array_family.flex.reflection_table) – A reflection_table containing wavelengths for beam models.

Returns:

ExperimentList with additional beam models and adjusted identifiers. refls (dials.array_family.flex.reflection_table): A reflection table with updated identifiers.

Return type:

new_expts (dxtbx.model.ExperimentList)

laue_dials.algorithms.laue.remove_beam_models(expts, new_id)[source]

A function for removing beam models no longer needed after refinement.

Parameters:
  • expts (dxtbx.model.ExperimentList) – ExperimentList to remove beams from.

  • new_id (int) – ID to assign to the final experiment.

Returns:

An ExperimentList with an experiment per image, all sharing a beam.

Return type:

new_expts (dxtbx.model.ExperimentList)

laue_dials.algorithms.laue.store_wavelengths(expts, refls)[source]

A function for storing wavelength data in beam objects in the reflection table.

Parameters:
  • expts (dxtbx.model.ExperimentList) – ExperimentList to retrieve wavelengths from.

  • refls (dials.array_family.flex.reflection_table) – A reflection_table to store wavelengths in.

Returns:

A reflection_table with updated wavelengths.

Return type:

new_refls (dials.array_family.flex.reflection_table)

laue_dials.algorithms.monochromatic module

This file contains functions for monochromatic processing

laue_dials.algorithms.monochromatic.find_spots(params, expts)[source]

Find strong reflections on images given a set of experiments.

Parameters:
  • params (libtbx.phil.scope_extract) – A phil scope extract containing the parameters for the DIALS spotfinding code.

  • expts (dxtbx.model.ExperimentList) – A list of experiment objects.

Returns:

A reflection table containing the found strong reflections.

Return type:

refls (dials.array_family.flex.reflection_table)

laue_dials.algorithms.monochromatic.initial_index(params, expts, refls)[source]

Indexes a dataset at a single wavelength using FFT3D.

Parameters:
  • params (libtbx.phil.scope_extract) – A phil scope extract containing the parameters for the DIALS indexing code.

  • expts (dxtbx.model.ExperimentList) – A list of imported experiment objects.

  • refls (dials.array_family.flex.reflection_table) – A reflection table containing strong reflections.

Returns:

An ExperimentList containing the indexing solution geometry. refls_indexed (dials.array_family.flex.reflection_table): A reflection table containing reflections with indexed data.

Return type:

expts_indexed (dxtbx.model.ExperimentList)

laue_dials.algorithms.monochromatic.scan_varying_refine(params, expts, refls)[source]

Performs scan-varying geometric refinement over a sequence of images.

Parameters:
  • params (phil) – A phil scope containing the needed input for dials.refine.

  • expts (dxtbx.model.ExperimentList) – A list of experiment objects.

  • refls (dials.array_family.flex.reflection_table) – A reflection table containing strong reflections.

Returns:

An ExperimentList containing the refined geometric solution. refls_refined (dials.array_family.flex.reflection_table): A reflection table containing reflections with refined data.

Return type:

expts_refined (dxtbx.model.ExperimentList)

laue_dials.algorithms.outliers module

Outlier rejection functions.

laue_dials.algorithms.outliers.gen_kde(elist, refls)[source]

Train a Gaussian Kernel Density Estimator (KDE) on 1/d^2 and wavelengths of submitted strong spots.

Parameters:
  • elist (dxtbx.model.ExperimentList) – The list of experiment objects.

  • refls (dials.array_family.flex.reflection_table) – The reflection table containing strong spots.

Returns:

The normalized resolutions (1/d^2) of the strong spots. lams (np.ndarray): The wavelengths of the strong spots. kde (scipy.stats.gaussian_kde): The trained Gaussian KDE model.

Return type:

normalized_resolution (np.ndarray)

Note

Harmonic reflections are removed from consideration before training the KDE.